PageSourceSearch

https://app.slinkylayer.ai/assets/index-DBFDVNU-.js

js slinkylayer.ai collected 2026-10-05 12:38:26 UTC 1,161,390 bytes, 66 lines download raw bytes

1var tT=Object.defineProperty;var dg=e=>{throw TypeError(e)};var rT=(e,t,r)=>t in e?tT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var q=(e,t,r)=>rT(e,typeof t!="symbol"?t+"":t,r),fg=(e,t,r)=>t.has(e)||dg("Cannot "+r);var qa=(e,t,r)=>(fg(e,t,"read from private field"),r?r.call(e):t.get(e)),Ha=(e,t,r)=>t.has(e)?dg("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ga=(e,t,r,n)=>(fg(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);import{r as N,j as u,a as _e,W as Yc,v as nT,c as Ni,d as Fh,t as $v,e as Pr,f as sT,m as hg,h as iT,k as aT,l as zv,o as Kv,p as qv,g as Qc,J as Hv,C as Gv,q as oT,s as lT}from"./vendor-web3-x3amP11p.js";import{r as Wv,c as cT,G as uT,_ as dT,a as fT}from"./vendor-charts-CaphL54U.js";import{c as hT,a as Vo,u as on,B as pT,P as Lr,V as Yv,b as Uh,d as Vh,e as ti,f as Rt,R as mT,g as gT,h as yT,i as vT,C as Qv,j as xT,k as bT,T as wT,S as Co,D as Xc,l as Jc,m as Xv,n as Zc,o as eu,p as Jv,q as Zv,r as CT,s as ex,t as tx,v as ST,w as rx,I as nx,x as sx,y as ix,z as ax,L as ox,A as lx,E as ET,F as TT,G as cx,H as ux,J as dx,K as _T,M as IT,N as AT,O as fx,Q as kT,U as hx,W as px,X as NT,Y as mx,Z as RT,_ as gx,$ as yx,a0 as PT,a1 as jT,a2 as vx,a3 as BT,a4 as DT,a5 as LT,a6 as MT,a7 as OT}from"./vendor-ui-DuHlwx8J.js";import{X as tu,C as ru,a as jr,b as xx,W as Ts,L as ls,P as bx,c as zn,U as So,d as FT,M as UT,e as $h,S as Ef,f as Tf,G as VT,g as ri,h as zh,i as $T,B as nu,j as wx,k as zT,l as ys,m as ya,R as KT,n as qT,N as HT,o as GT,p as Cx,q as WT,r as YT,s as QT,t as XT,A as Sx,u as JT,v as Ex,w as Tx,x as ZT,y as e_,T as t_,z as r_,D as n_,E as s_,F as yd,H as _x,I as i_,Z as Ix,J as a_,K as o_,O as Ax,Q as mc,V as Kh,Y as l_,_ as c_,$ as u_,a0 as kx,a1 as d_,a2 as f_,a3 as h_,a4 as gc,a5 as p_,a6 as m_,a7 as Nx,a8 as g_,a9 as pg,aa as y_,ab as v_}from"./vendor-icons-B95TO5rD.js";import{c as x_,u as b_,a as qh,s as Xt,r as ni,b as Ri,d as Rx,o as Gn,e as fa,n as Hh,l as su,f as Px,g as jx,h as Bx,Q as w_}from"./vendor-utils-K4oM8dQG.js";import{u as Dx,L as oo,a as Sa,b as C_,B as S_,R as E_,c as Bs,N as T_}from"./vendor-react-DJSp9NgH.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();var _f={},mg=Wv;_f.createRoot=mg.createRoot,_f.hydrateRoot=mg.hydrateRoot;const __=1,I_=1e6;let vd=0;function A_(){return vd=(vd+1)%Number.MAX_SAFE_INTEGER,vd.toString()}const xd=new Map,gg=e=>{if(xd.has(e))return;const t=setTimeout(()=>{xd.delete(e),lo({type:"REMOVE_TOAST",toastId:e})},I_);xd.set(e,t)},k_=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,__)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(r=>r.id===t.toast.id?{...r,...t.toast}:r)};case"DISMISS_TOAST":{const{toastId:r}=t;return r?gg(r):e.toasts.forEach(n=>{gg(n.id)}),{...e,toasts:e.toasts.map(n=>
1n.id===r||r===void 0?{...n,open:!1}:n)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(r=>r.id!==t.toastId)}}},Zl=[];let ec={toasts:[]};function lo(e){ec=k_(ec,e),Zl.forEach(t=>{t(ec)})}function N_({...e}){const t=A_(),r=s=>lo({type:"UPDATE_TOAST",toast:{...s,id:t}}),n=()=>lo({type:"DISMISS_TOAST",toastId:t});return lo({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:s=>{s||n()}}}),{id:t,dismiss:n,update:r}}function jn(){const[e,t]=N.useState(ec);return N.useEffect(()=>(Zl.push(t),()=>{const r=Zl.indexOf(t);r>-1&&Zl.splice(r,1)}),[e]),{...e,toast:N_,dismiss:r=>lo({type:"DISMISS_TOAST",toastId:r})}}var Gh="ToastProvider",[Wh,R_,P_]=hT("Toast"),[Lx,qH]=Vo("Toast",[P_]),[j_,iu]=Lx(Gh),Mx=e=>{const{__scopeToast:t,label:r="Notification",duration:n=5e3,swipeDirection:s="right",swipeThreshold:i=50,announcerContainer:a,children:o}=e,[l,c]=N.useState(null),[d,f]=N.useState(0),h=N.useRef(!1),m=N.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${Gh}\`. Expected non-empty \`string\`.`),u.jsx(Wh.Provider,{scope:t,children:u.jsx(j_,{scope:t,label:r,duration:n,swipeDirection:s,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:c,onToastAdd:N.useCallback(()=>f(g=>g+1),[]),onToastRemove:N.useCallback(()=>f(g=>g-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:m,announcerContainer:a,children:o})})};Mx.displayName=Gh;var Ox="ToastViewport",B_=["F8"],If="toast.viewportPause",Af="toast.viewportResume",Fx=N.forwardRef((e,t)=>{const{__scopeToast:r,hotkey:n=B_,label:s="Notifications ({hotkey})",...i}=e,a=iu(Ox,r),o=R_(r),l=N.useRef(null),c=N.useRef(null),d=N.useRef(null),f=N.useRef(null),h=on(t,f,a.onViewportChange),m=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=a.toastCount>0;N.useEffect(()=>{const w=b=>{n.length!==0&&n.every(T=>b[T]||b.code===T)&&f.current?.focus()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[n]),N.useEffect(()=>{const w=l.current,b=f.current;if(g&&w&&b){const C=()=>{if(!a.isClosePausedRef.current){const _=new CustomEvent(If);b.dispatchEvent(_),a.isClosePausedRef.current=!0}},T=()=>{if(a.isClosePausedRef.current){const _=new CustomEvent(Af);b.dispatchEvent(_),a.isClosePausedRef.current=!1}},I=_=>{!w.contains(_.relatedTarget)&&T()},k=()=>{w.contains(document.activeElement)||T()};return w.addEventListener("focusin",C),w.addEventListener("focusout",I),w.addEventListener("pointermove",C),w.addEventListener("pointerleave",k),window.addEventListener("blur",C),window.addEventListener("focus",T),()=>{w.removeEventListener("focusin",C),w.removeEventListener("focusout",I),w.removeEventListener("pointermove",C),w.removeEventListener("pointerleave",k),window.removeEventListener("blur",C),window.removeEventListener("focus",T)}}},[g,a.isClosePausedRef]);const v=N.useCallback(({tabbingDirection:w})=>{const C=o().map(T=>{const I=T.ref.current,k=[I,...G_(I)];return w==="forwards"?k:k.reverse()});return(w==="forwards"?C.reverse():C).flat()},[o]);return N.useEffect(()=>{const w=f.current;if(w){const b=C=>{const T=C.altKey||C.ctrlKey||C.metaKey;if(C.key==="Tab"&&!T){const k=document.activeElement,_=C.shiftKey;if(C.target===w&&_){c.current?.focus();return}const G=v({tabbingDirection:_?"backwards":"forwards"}),L=G.findIndex(H=>H===k);bd(G.slice(L+1))?C.preventDefault():_?c.current?.focus():d.current?.focus()}};return w.addEventListener("keydown",b),()=>w.removeEventListener("keydown",b)}},[o,v]),u.jsxs(pT,{ref:l,role:"region","aria-label":s.replace("{hotkey}",m),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&u.jsx(kf,{ref:c,onFocusFromOutsideViewport:()=>{const w=v({tabbingDirection:"forwards"});bd(w)}}),u.jsx(Wh.Slot,{scope:r,children:u.jsx(Lr.ol,{tabIndex:-1,...i,ref:h})}),g&&u.jsx(kf,{ref:d,onFocusFromOutsideViewport:()=>{const w=v({tabbingDirection:"backwards"});bd(w)}})]})});Fx.displayName=Ox;var Ux="ToastFocusProxy",kf=N.forwardRef((e,t)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...s}=e,i=iu(Ux,r);return u.jsx(Yv,{tabIndex:0,...s,ref:t,style:{position:"fixed"},onFocus:a=>{const o=a.relatedTarget;!i.viewport?.contains(o)&&n()}})});kf.displayName=Ux;
1var $o="Toast",D_="toast.swipeStart",L_="toast.swipeMove",M_="toast.swipeCancel",O_="toast.swipeEnd",Vx=N.forwardRef((e,t)=>{const{forceMount:r,open:n,defaultOpen:s,onOpenChange:i,...a}=e,[o,l]=Uh({prop:n,defaultProp:s??!0,onChange:i,caller:$o});return u.jsx(Vh,{present:r||o,children:u.jsx(V_,{open:o,...a,ref:t,onClose:()=>l(!1),onPause:ti(e.onPause),onResume:ti(e.onResume),onSwipeStart:Rt(e.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Rt(e.onSwipeMove,c=>{const{x:d,y:f}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","move"),c.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${d}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${f}px`)}),onSwipeCancel:Rt(e.onSwipeCancel,c=>{c.currentTarget.setAttribute("data-swipe","cancel"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Rt(e.onSwipeEnd,c=>{const{x:d,y:f}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","end"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${d}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${f}px`),l(!1)})})})});Vx.displayName=$o;var[F_,U_]=Lx($o,{onClose(){}}),V_=N.forwardRef((e,t)=>{const{__scopeToast:r,type:n="foreground",duration:s,open:i,onClose:a,onEscapeKeyDown:o,onPause:l,onResume:c,onSwipeStart:d,onSwipeMove:f,onSwipeCancel:h,onSwipeEnd:m,...g}=e,v=iu($o,r),[w,b]=N.useState(null),C=on(t,b),T=N.useRef(null),I=N.useRef(null),k=s||v.duration,_=N.useRef(0),M=N.useRef(k),V=N.useRef(0),{onToastAdd:G,onToastRemove:L}=v,H=ti(()=>{w?.contains(document.activeElement)&&v.viewport?.focus(),a()}),F=N.useCallback(J=>{!J||J===1/0||(window.clearTimeout(V.current),_.current=new Date().getTime(),V.current=window.setTimeout(H,J))},[H]);N.useEffect(()=>{const J=v.viewport;if(J){const oe=()=>{F(M.current),c?.()},xe=()=>{const ge=new Date().getTime()-_.current;M.current=M.current-ge,window.clearTimeout(V.current),l?.()};return J.addEventListener(If,xe),J.addEventListener(Af,oe),()=>{J.removeEventListener(If,xe),J.removeEventListener(Af,oe)}}},[v.viewport,k,l,c,F]),N.useEffect(()=>{i&&!v.isClosePausedRef.current&&F(k)},[i,k,v.isClosePausedRef,F]),N.useEffect(()=>()=>{window.clearTimeout(V.current)},[]),N.useEffect(()=>(G(),()=>L()),[G,L]);const Q=N.useMemo(()=>w?Wx(w):null,[w]);return v.viewport?u.jsxs(u.Fragment,{children:[Q&&u.jsx($_,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite",children:Q}),u.jsx(F_,{scope:r,onClose:H,children:Wv.createPortal(u.jsx(Wh.ItemSlot,{scope:r,children:u.jsx(mT,{asChild:!0,onEscapeKeyDown:Rt(o,()=>{v.isFocusedToastEscapeKeyDownRef.current||H(),v.isFocusedToastEscapeKeyDownRef.current=!1}),children:u.jsx(Lr.li,{tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":v.swipeDirection,...g,ref:C,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:Rt(e.onKeyDown,J=>{J.key==="Escape"&&(o?.(J.nativeEvent),J.nativeEvent.defaultPrevented||(v.isFocusedToastEscapeKeyDownRef.current=!0,H()))}),onPointerDown:Rt(e.onPointerDown,J=>{J.button===0&&(T.current={x:J.clientX,y:J.clientY})}),onPointerMove:Rt(e.onPointerMove,J=>{if(!T.current)return;const oe=J.clientX-T.current.x,xe=J.clientY-T.current.y,ge=!!I.current,$=["left","right"].includes(v.swipeDirection),le=["left","up"].includes(v.swipeDirection)?Math.min:Math.max,B=$?le(0,oe):0,Te=$?0:le(0,xe),ye=J.pointerType==="touch"?10:2,U={x:B,y:Te},Qe={originalEvent:J,delta:U};ge?(I.current=U,Rl(L_,f,Qe,{discrete:!1})):yg(U,v.swipeDirection,ye)?(I.current=U,Rl(D_,d,Qe,{discrete:!1}),J.target.setPointerCapture(J.pointerId)):(Math.abs(oe)>ye||Math.abs(xe)>ye)&&(T.current=null)}),onPointerUp:Rt(e.onPointerUp,J=>{const oe=I.current,xe=J.target;if(xe.hasPointerCapture(J.pointerId)&&xe.releasePointerCapture(J.pointerId),I.current=null,T.current=null,oe){const ge=J.currentTarget,$={originalEvent:J,delta:oe};yg(oe,v.swipeDirection,v.swipeThreshold)?Rl(O_,m,$,{discrete:!0}):Rl(M_,h,$,{discrete:!0}),ge.addEventListener("click",le=>le.preventDefault(),{once:!0})}})})})}),v.viewport)})]}):null}),$_=e=>{const{__scopeToast:t,children:r,...n}=e,s=iu($o,t),[i,a]=N.useState(!1),[o,l]=N.useState(!1);return q_(()=>a(!0)),N.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),o?null:u.jsx(gT,{asChild:!0,container:s.announcerContainer||void 0,children:u.jsx(Yv,{...n,children:i&&u.jsxs(u.Fragment,{children:[s.label," ",r]})})})},z_="ToastTitle",$x=N.forwardRef((e,t)=>
1{const{__scopeToast:r,...n}=e;return u.jsx(Lr.div,{...n,ref:t})});$x.displayName=z_;var K_="ToastDescription",zx=N.forwardRef((e,t)=>{const{__scopeToast:r,...n}=e;return u.jsx(Lr.div,{...n,ref:t})});zx.displayName=K_;var Kx="ToastAction",qx=N.forwardRef((e,t)=>{const{altText:r,...n}=e;return r.trim()?u.jsx(Gx,{altText:r,asChild:!0,children:u.jsx(Yh,{...n,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${Kx}\`. Expected non-empty \`string\`.`),null)});qx.displayName=Kx;var Hx="ToastClose",Yh=N.forwardRef((e,t)=>{const{__scopeToast:r,...n}=e,s=U_(Hx,r);return u.jsx(Gx,{asChild:!0,children:u.jsx(Lr.button,{type:"button",...n,ref:t,onClick:Rt(e.onClick,s.onClose)})})});Yh.displayName=Hx;var Gx=N.forwardRef((e,t)=>{const{__scopeToast:r,altText:n,...s}=e;return u.jsx(Lr.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...s,ref:t})});function Wx(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),H_(n)){const s=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!s)if(i){const a=n.dataset.radixToastAnnounceAlt;a&&t.push(a)}else t.push(...Wx(n))}}),t}function Rl(e,t,r,{discrete:n}){const s=r.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:r});t&&s.addEventListener(e,t,{once:!0}),n?vT(s,i):s.dispatchEvent(i)}var yg=(e,t,r=0)=>{const n=Math.abs(e.x),s=Math.abs(e.y),i=n>s;return t==="left"||t==="right"?i&&n>r:!i&&s>r};function q_(e=()=>{}){const t=ti(e);yT(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[t])}function H_(e){return e.nodeType===e.ELEMENT_NODE}function G_(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const s=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||s?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function bd(e){const t=document.activeElement;return e.some(r=>r===t?!0:(r.focus(),document.activeElement!==t))}var W_=Mx,Yx=Fx,Qx=Vx,Xx=$x,Jx=zx,Zx=qx,eb=Yh;function tb(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(r=tb(e[t]))&&(n&&(n+=" "),n+=r);else for(t in e)e[t]&&(n&&(n+=" "),n+=t);return n}function Y_(){for(var e,t,r=0,n="";r<arguments.length;)(e=arguments[r++])&&(t=tb(e))&&(n&&(n+=" "),n+=t);return n}const vg=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,xg=Y_,Ea=(e,t)=>r=>{var n;if(t?.variants==null)return xg(e,r?.class,r?.className);const{variants:s,defaultVariants:i}=t,a=Object.keys(s).map(c=>{const d=r?.[c],f=i?.[c];if(d===null)return null;const h=vg(d)||vg(f);return s[c][h]}),o=r&&Object.entries(r).reduce((c,d)=>{let[f,h]=d;return h===void 0||(c[f]=h),c},{}),l=t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((c,d)=>{let{class:f,className:h,...m}=d;return Object.entries(m).every(g=>{let[v,w]=g;return Array.isArray(w)?w.includes({...i,...o}[v]):{...i,...o}[v]===w})?[...c,f,h]:c},[]);return xg(e,a,l,r?.class,r?.className)},Qh="-",Q_=e=>{const t=J_(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=e;return{getClassGroupId:a=>{const o=a.split(Qh);return o[0]===""&&o.length!==1&&o.shift(),rb(o,t)||X_(a)},getConflictingClassGroupIds:(a,o)=>{const l=r[a]||[];return o&&n[a]?[...l,...n[a]]:l}}},rb=(e,t)=>{if(e.length===0)return t.classGroupId;const r=e[0],n=t.nextPart.get(r),s=n?rb(e.slice(1),n):void 0;if(s)return s;if(t.validators.length===0)return;const i=e.join(Qh);return t.validators.find(({validator:a})=>a(i))?.classGroupId},bg=/^\[(.+)\]$/,X_=e=>{if(bg.test(e)){const t=bg.exec(e)[1],r=t?.substring(0,t.indexOf(":"));if(r)return"arbitrary.."+r}},J_=e=>{const{theme:t,prefix:r}=e,n={nextPart:new Map,validators:[]};return eI(Object.entries(e.classGroups),r).forEach(([i,a])=>{Nf(a,n,i,t)}),n},Nf=(e,t,r,n)=>{e.forEach(s=>{if(typeof s=="string"){const i=s===""?t:wg(t,s);i.classGroupId=r;return}if(typeof s=="function"){if(Z_(s)){Nf(s(n),t,r,n);return}t.validators.push({validator:s,classGroupId:r});return}
vendor: 4,835 bytes, line 1
1Object.entries(s).forEach(([i,a])=>{Nf(a,wg(t,i),r,n)})})},wg=(e,t)=>{let r=e;return t.split(Qh).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},Z_=e=>e.isThemeGetter,eI=(e,t)=>t?e.map(([r,n])=>{const s=n.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([a,o])=>[t+a,o])):i);return[r,s]}):e,tI=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=new Map,n=new Map;const s=(i,a)=>{r.set(i,a),t++,t>e&&(t=0,n=r,r=new Map)};return{get(i){let a=r.get(i);if(a!==void 0)return a;if((a=n.get(i))!==void 0)return s(i,a),a},set(i,a){r.has(i)?r.set(i,a):s(i,a)}}},nb="!",rI=e=>{const{separator:t,experimentalParseClassName:r}=e,n=t.length===1,s=t[0],i=t.length,a=o=>{const l=[];let c=0,d=0,f;for(let w=0;w<o.length;w++){let b=o[w];if(c===0){if(b===s&&(n||o.slice(w,w+i)===t)){l.push(o.slice(d,w)),d=w+i;continue}if(b==="/"){f=w;continue}}b==="["?c++:b==="]"&&c--}const h=l.length===0?o:o.substring(d),m=h.startsWith(nb),g=m?h.substring(1):h,v=f&&f>d?f-d:void 0;return{modifiers:l,hasImportantModifier:m,baseClassName:g,maybePostfixModifierPosition:v}};return r?o=>r({className:o,parseClassName:a}):a},nI=e=>{if(e.length<=1)return e;const t=[];let r=[];return e.forEach(n=>{n[0]==="["?(t.push(...r.sort(),n),r=[]):r.push(n)}),t.push(...r.sort()),t},sI=e=>({cache:tI(e.cacheSize),parseClassName:rI(e),...Q_(e)}),iI=/\s+/,aI=(e,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:s}=t,i=[],a=e.trim().split(iI);let o="";for(let l=a.length-1;l>=0;l-=1){const c=a[l],{modifiers:d,hasImportantModifier:f,baseClassName:h,maybePostfixModifierPosition:m}=r(c);let g=!!m,v=n(g?h.substring(0,m):h);if(!v){if(!g){o=c+(o.length>0?" "+o:o);continue}if(v=n(h),!v){o=c+(o.length>0?" "+o:o);continue}g=!1}const w=nI(d).join(":"),b=f?w+nb:w,C=b+v;if(i.includes(C))continue;i.push(C);const T=s(v,g);for(let I=0;I<T.length;++I){const k=T[I];i.push(b+k)}o=c+(o.length>0?" "+o:o)}return o};function oI(){let e=0,t,r,n="";for(;e<arguments.length;)(t=arguments[e++])&&(r=sb(t))&&(n&&(n+=" "),n+=r);return n}const sb=e=>{if(typeof e=="string")return e;let t,r="";for(let n=0;n<e.length;n++)e[n]&&(t=sb(e[n]))&&(r&&(r+=" "),r+=t);return r};function lI(e,...t){let r,n,s,i=a;function a(l){const c=t.reduce((d,f)=>f(d),e());return r=sI(c),n=r.cache.get,s=r.cache.set,i=o,o(l)}function o(l){const c=n(l);if(c)return c;const d=aI(l,r);return s(l,d),d}return function(){return i(oI.apply(null,arguments))}}const ir=e=>{const t=r=>r[e]||[];return t.isThemeGetter=!0,t},ib=/^\[(?:([a-z-]+):)?(.+)\]$/i,cI=/^\d+\/\d+$/,uI=new Set(["px","full","screen"]),dI=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,fI=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,hI=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,pI=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,mI=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,vs=e=>ha(e)||uI.has(e)||cI.test(e),Ds=e=>Ta(e,"length",SI),ha=e=>!!e&&!Number.isNaN(Number(e)),wd=e=>Ta(e,"number",ha),Wa=e=>!!e&&Number.isInteger(Number(e)),gI=e=>e.endsWith("%")&&ha(e.slice(0,-1)),_t=e=>ib.test(e),Ls=e=>dI.test(e),yI=new Set(["length","size","percentage"]),vI=e=>Ta(e,yI,ab),xI=e=>Ta(e,"position",ab),bI=new Set(["image","url"]),wI=e=>Ta(e,bI,TI),CI=e=>Ta(e,"",EI),Ya=()=>!0,Ta=(e,t,r)=>{const n=ib.exec(e);return n?n[1]?typeof t=="string"?n[1]===t:t.has(n[1]):r(n[2]):!1},SI=e=>fI.test(e)&&!hI.test(e),ab=()=>!1,EI=e=>pI.test(e),TI=e=>mI.test(e),_I=()=>{const e=ir("colors"),t=ir("spacing"),r=ir("blur"),n=ir("brightness"),s=ir("borderColor"),i=ir("borderRadius"),a=ir("borderSpacing"),o=ir("borderWidth"),l=ir("contrast"),c=ir("grayscale"),d=ir("hueRotate"),f=ir("invert"),h=ir("gap"),m=ir("gradientColorStops"),g=ir("gradientColorStopPositions"),v=ir("inset"),w=ir("margin"),b=ir("opacity"),C=ir("padding"),T=ir("saturate"),I=ir("scale"),k=ir("sepia"),_=ir("skew"),M=ir("space"),V=ir("translate"),G=()=>["auto","contain","none"],L=()=>["auto","hidden","clip","visible","scroll"],H=()=>["auto",_t,t],F=()=>[_t,t],Q=()=>["",vs,Ds],J=()=>["auto",ha,_t],oe=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],xe=()=>["solid","dashed","dotted","double","none"],ge=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],$=()=>["start","end","center","between","around","evenly","stretch"],le=()=>["","0",_t],B=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Te=()=>[ha,_t];return{cacheSize:500,separator:":",theme:{colors:[Ya],spacing:[vs,Ds],blur:["none","",Ls,_t],brightness:Te(),borderColor:[e],borderRadius:["n
1one","","full",Ls,_t],borderSpacing:F(),borderWidth:Q(),contrast:Te(),grayscale:le(),hueRotate:Te(),invert:le(),gap:F(),gradientColorStops:[e],gradientColorStopPositions:[gI,Ds],inset:H(),margin:H(),opacity:Te(),padding:F(),saturate:Te(),scale:Te(),sepia:le(),skew:Te(),space:F(),translate:F()},classGroups:{aspect:[{aspect:["auto","square","video",_t]}],container:["container"],columns:[{columns:[Ls]}],"break-after":[{"break-after":B()}],"break-before":[{"break-before":B()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...oe(),_t]}],overflow:[{overflow:L()}],"overflow-x":[{"overflow-x":L()}],"overflow-y":[{"overflow-y":L()}],overscroll:[{overscroll:G()}],"overscroll-x":[{"overscroll-x":G()}],"overscroll-y":[{"overscroll-y":G()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[v]}],"inset-x":[{"inset-x":[v]}],"inset-y":[{"inset-y":[v]}],start:[{start:[v]}],end:[{end:[v]}],top:[{top:[v]}],right:[{right:[v]}],bottom:[{bottom:[v]}],left:[{left:[v]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Wa,_t]}],basis:[{basis:H()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",_t]}
vendor: 9,639 bytes, line 1
1],grow:[{grow:le()}],shrink:[{shrink:le()}],order:[{order:["first","last","none",Wa,_t]}],"grid-cols":[{"grid-cols":[Ya]}],"col-start-end":[{col:["auto",{span:["full",Wa,_t]},_t]}],"col-start":[{"col-start":J()}],"col-end":[{"col-end":J()}],"grid-rows":[{"grid-rows":[Ya]}],"row-start-end":[{row:["auto",{span:[Wa,_t]},_t]}],"row-start":[{"row-start":J()}],"row-end":[{"row-end":J()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",_t]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",_t]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...$()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...$(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...$(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[C]}],px:[{px:[C]}],py:[{py:[C]}],ps:[{ps:[C]}],pe:[{pe:[C]}],pt:[{pt:[C]}],pr:[{pr:[C]}],pb:[{pb:[C]}],pl:[{pl:[C]}],m:[{m:[w]}],mx:[{mx:[w]}],my:[{my:[w]}],ms:[{ms:[w]}],me:[{me:[w]}],mt:[{mt:[w]}],mr:[{mr:[w]}],mb:[{mb:[w]}],ml:[{ml:[w]}],"space-x":[{"space-x":[M]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[M]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",_t,t]}],"min-w":[{"min-w":[_t,t,"min","max","fit"]}],"max-w":[{"max-w":[_t,t,"none","full","min","max","fit","prose",{screen:[Ls]},Ls]}],h:[{h:[_t,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[_t,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[_t,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[_t,t,"auto","min","max","fit"]}],"font-size":[{text:["base",Ls,Ds]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",wd]}],"font-family":[{font:[Ya]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",_t]}],"line-clamp":[{"line-clamp":["none",ha,wd]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",vs,_t]}],"list-image":[{"list-image":["none",_t]}],"list-style-type":[{list:["none","disc","decimal",_t]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...xe(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",vs,Ds]}],"underline-offset":[{"underline-offset":["auto",vs,_t]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:F()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",_t]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",_t]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...oe(),xI]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",vI]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},wI]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[m]}],"gradient-via":[{via:[m]}],"gradient-to":[{to:[m]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...xe(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:xe()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...xe()]}],"outline-offset":[{"outline-offset":[vs,_t]}],"outline-w":[{outline:[vs,Ds]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:Q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[vs,Ds]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Ls,CI]}],"shadow-color":[{shadow:[Ya]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...ge(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":ge()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",Ls,_t]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[f]}],saturate:[{saturate:[T]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[f]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[T]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",_t]}],duration:[{duration:Te()}],ease:[{ease:["linear","in","out","in-out",_t]}],delay:[{delay:Te()}],animate:[{animate:["none","spin","ping","pulse","bounce",_t]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[I]}],"scale-x":[{"scale-x":[I]}],"scale-y":[{"scale-y":[I]}],rotate:[{rotate:[Wa,_t]}],"translate-x":[{"translate-x":[V]}],"translate-y":[{"translate-y":[V]}],"skew-x":[{"skew-x":[_]}],"skew-y":[{"skew-y":[_]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",_t]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",_t]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":F()}],"scroll-mx":[{"scroll-mx":F()}],"scroll-my":[{"scroll-my":F()}],"scroll-ms":[{"scroll-ms":F()}],"scroll-me":[{"scroll-me":F()}],"scroll-mt":[{"scroll-mt":F()}],"scroll-mr":[{"scroll-mr":F()}],"scroll-mb":[{"scroll-mb":F()}],"scroll-ml":[{"scroll-ml":F()}],"scroll-p":[{"scroll-p":F()}],"scroll-px":[{"scroll-px":F()}],"scroll-py":[{"scroll-py":F()}],"scroll-ps":[{"scroll-ps":F()}],"scroll-pe":[{"scroll-pe":F()}],"scroll-pt":[{"scroll-pt":F()}],"scroll-pr":[{"scroll-pr":F()}],"scroll-pb":[{"scroll-pb":F()}],"scroll-pl":[{"scroll-pl":F()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}
1],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",_t]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[vs,Ds,wd]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},II=lI(_I);function ze(...e){return II(cT(e))}const AI=W_,ob=N.forwardRef(({className:e,...t},r)=>u.jsx(Yx,{ref:r,className:ze("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),...t}));ob.displayName=Yx.displayName;const kI=Ea("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-background text-destructive-foreground"}},defaultVariants:{variant:"default"}}),lb=N.forwardRef(({className:e,variant:t,...r},n)=>u.jsx(Qx,{ref:n,className:ze(kI({variant:t}),e),...r}));
1lb.displayName=Qx.displayName;const cb=N.forwardRef(({className:e,...t},r)=>u.jsx(Zx,{ref:r,className:ze("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),...t}));cb.displayName=Zx.displayName;const ub=N.forwardRef(({className:e,...t},r)=>u.jsx(eb,{ref:r,className:ze("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",...t,children:u.jsx(tu,{className:"h-4 w-4"})}));ub.displayName=eb.displayName;const db=N.forwardRef(({className:e,...t},r)=>u.jsx(Xx,{ref:r,className:ze("text-sm font-semibold",e),...t}));db.displayName=Xx.displayName;const fb=N.forwardRef(({className:e,...t},r)=>u.jsx(Jx,{ref:r,className:ze("text-sm opacity-90",e),...t}));fb.displayName=Jx.displayName;function NI(){const{toasts:e}=jn();return u.jsxs(AI,{children:[e.map(function({id:t,title:r,description:n,action:s,...i}){return u.jsxs(lb,{...i,children:[u.jsxs("div",{className:"grid gap-1",children:[r&&u.jsx(db,{children:r}),n&&u.jsx(fb,{children:n})]}),s,u.jsx(ub,{})]},t)}),u.jsx(ob,{})]})}var RI=(e,t,r,n,s,i,a,o)=>{let l=document.documentElement,c=["light","dark"];function d(m){(Array.isArray(e)?e:[e]).forEach(g=>{let v=g==="class",w=v&&i?s.map(b=>i[b]||b):s;v?(l.classList.remove(...w),l.classList.add(i&&i[m]?i[m]:m)):l.setAttribute(g,m)}),f(m)}function f(m){o&&c.includes(m)&&(l.style.colorScheme=m)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(n)d(n);else try{let m=localStorage.getItem(t)||r,g=a&&m==="system"?h():m;d(g)}catch{}},Cg=["light","dark"],hb="(prefers-color-scheme: dark)",PI=typeof window>"u",Xh=N.createContext(void 0),jI={setTheme:e=>{},themes:[]},pb=()=>{var e;return(e=N.useContext(Xh))!=null?e:jI},BI=e=>N.useContext(Xh)?N.createElement(N.Fragment,null,e.children):N.createElement(LI,{...e}),DI=["light","dark"],LI=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:r=!0,enableColorScheme:n=!0,storageKey:s="theme",themes:i=DI,defaultTheme:a=r?"system":"light",attribute:o="data-theme",value:l,children:c,nonce:d,scriptProps:f})=>{let[h,m]=N.useState(()=>OI(s,a)),[g,v]=N.useState(()=>h==="system"?Cd():h),w=l?Object.values(l):i,b=N.useCallback(k=>{let _=k;if(!_)return;k==="system"&&r&&(_=Cd());let M=l?l[_]:_,V=t?FI(d):null,G=document.documentElement,L=H=>{H==="class"?(G.classList.remove(...w),M&&G.classList.add(M)):H.startsWith("data-")&&(M?G.setAttribute(H,M):G.removeAttribute(H))};if(Array.isArray(o)?o.forEach(L):L(o),n){let H=Cg.includes(a)?a:null,F=Cg.includes(_)?_:H;G.style.colorScheme=F}V?.()},[d]),C=N.useCallback(k=>{let _=typeof k=="function"?k(h):k;m(_);try{localStorage.setItem(s,_)}catch{}},[h]),T=N.useCallback(k=>{let _=Cd(k);v(_),h==="system"&&r&&!e&&b("system")},[h,e]);N.useEffect(()=>{let k=window.matchMedia(hb);return k.addListener(T),T(k),()=>k.removeListener(T)},[T]),N.useEffect(()=>{let k=_=>{_.key===s&&(_.newValue?m(_.newValue):C(a))};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[C]),N.useEffect(()=>{b(e??h)},[e,h]);let I=N.useMemo(()=>({theme:h,setTheme:C,forcedTheme:e,resolvedTheme:h==="system"?g:h,themes:r?[...i,"system"]:i,systemTheme:r?g:void 0}),[h,C,e,g,r,i]);return N.createElement(Xh.Provider,{value:I},N.createElement(MI,{forcedTheme:e,storageKey:s,attribute:o,enableSystem:r,enableColorScheme:n,defaultTheme:a,value:l,themes:i,nonce:d,scriptProps:f}),c)},MI=N.memo(({forcedTheme:e,storageKey:t,attribute:r,enableSystem:n,enableColorScheme:s,defaultTheme:i,value:a,themes:o,nonce:l,scriptProps:c})=>{let d=JSON.stringify([r,t,i,e,o,a,n,s]).slice(1,-1);return N.createElement("script",{...c,suppressHydrationWarning:!0,nonce:typeof window>"u"?l:"",dangerouslySetInnerHTML:{__html:`(${RI.toString()})(${d})`}})}),OI=(e,t)=>{if(PI)return;let r;try{r=localStorage.getItem(e)||void 0}catch{}return r||t},FI=e=>{let t=document.createElement("style");return e&&t.setAttribute("nonce",e),t.appendChild(document.createTextNode("*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(t),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(t)},1)}},Cd=e=>
1(e||(e=window.matchMedia(hb)),e.matches?"dark":"light"),UI=e=>{switch(e){case"success":return zI;case"info":return qI;case"warning":return KI;case"error":return HI;default:return null}},VI=Array(12).fill(0),$I=({visible:e})=>_e.createElement("div",{className:"sonner-loading-wrapper","data-visible":e},_e.createElement("div",{className:"sonner-spinner"},VI.map((t,r)=>_e.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),zI=_e.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},_e.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),KI=_e.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},_e.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),qI=_e.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},_e.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),HI=_e.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},_e.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),GI=()=>{let[e,t]=_e.useState(document.hidden);return _e.useEffect(()=>{let r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e},Rf=1,WI=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;let{message:r,...n}=e,s=typeof e?.id=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:Rf++,i=this.toasts.find(o=>o.id===s),a=e.dismissible===void 0?!0:e.dismissible;return i?this.toasts=this.toasts.map(o=>o.id===s?(this.publish({...o,...e,id:s,title:r}),{...o,...e,id:s,dismissible:a,title:r}):o):this.addToast({title:r,...n,dismissible:a,id:s}),s},this.dismiss=e=>(e||this.toasts.forEach(t=>{this.subscribers.forEach(r=>r({id:t.id,dismiss:!0}))}),this.subscribers.forEach(t=>t({id:e,dismiss:!0})),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>
1this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let r;t.loading!==void 0&&(r=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));let n=e instanceof Promise?e:e(),s=r!==void 0;return n.then(async i=>{if(QI(i)&&!i.ok){s=!1;let a=typeof t.error=="function"?await t.error(`HTTP error! status: ${i.status}`):t.error,o=typeof t.description=="function"?await t.description(`HTTP error! status: ${i.status}`):t.description;this.create({id:r,type:"error",message:a,description:o})}else if(t.success!==void 0){s=!1;let a=typeof t.success=="function"?await t.success(i):t.success,o=typeof t.description=="function"?await t.description(i):t.description;this.create({id:r,type:"success",message:a,description:o})}}).catch(async i=>{if(t.error!==void 0){s=!1;let a=typeof t.error=="function"?await t.error(i):t.error,o=typeof t.description=="function"?await t.description(i):t.description;this.create({id:r,type:"error",message:a,description:o})}}).finally(()=>{var i;s&&(this.dismiss(r),r=void 0),(i=t.finally)==null||i.call(t)}),r},this.custom=(e,t)=>{let r=t?.id||Rf++;return this.create({jsx:e(r),id:r,...t}),r},this.subscribers=[],this.toasts=[]}},pn=new WI,YI=(e,t)=>{let r=t?.id||Rf++;return pn.addToast({title:e,...t,id:r}),r},QI=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",XI=YI,JI=()=>pn.toasts;Object.assign(XI,{success:pn.success,info:pn.info,warning:pn.warning,error:pn.error,custom:pn.custom,message:pn.message,promise:pn.promise,dismiss:pn.dismiss,loading:pn.loading},{getHistory:JI});function ZI(e,{insertAt:t}={}){if(typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t==="top"&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}ZI(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999}:where([data-sonner-toaster][data-x-position="right"]){right:max(var(--offset),env(safe-area-inset-right))}:where([data-sonner-toaster][data-x-position="left"]){left:max(var(--offset),env(safe-area-inset-left))}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:max(var(--offset),env(safe-area-inset-top))}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:max(var(--offset),env(safe-area-inset-bottom))}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;
1left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;background:var(--gray1);color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:0;right:0;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}
1:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount, 0px));transition:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation:swipe-out .2s ease-out forwards}@keyframes swipe-out{0%{transform:translateY(calc(var(--lift) * var(--offset) + var(--swipe-amount)));opacity:1}to{transform:translateY(calc(var(--lift) * var(--offset) + var(--swipe-amount) + var(--lift) * -100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;--mobile-offset: 16px;right:var(--mobile-offset);left:var(--mobile-offset);width:100%}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset)}[data-sonner-toaster][data-y-position=bottom]{bottom:20px}[data-sonner-toaster][data-y-position=top]{top:20px}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset);right:var(--mobile-offset);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
2`);function Pl(e){return e.label!==void 0}var eA=3,tA="32px",rA=4e3,nA=356,sA=14,iA=20,aA=200;function oA(...e){return e.filter(Boolean).join(" ")}var lA=e=>{var t,r,n,s,i,a,o,l,c,d;let{invert:f,toast:h,unstyled:m,interacting:g,setHeights:v,visibleToasts:w,heights:b,index:C,toasts:T,expanded:I,removeToast:k,defaultRichColors:_,closeButton:M,style:V,cancelButtonStyle:G,actionButtonStyle:L,className:H="",descriptionClassName:F="",duration:Q,position:J,gap:oe,loadingIcon:xe,expandByDefault:ge,classNames:$,icons:le,closeButtonAriaLabel:B="Close toast",pauseWhenPageIsHidden:Te,cn:ye}=e,[U,Qe]=_e.useState(!1),[pt,We]=_e.useState(!1),[dt,ft]=_e.useState(!1),[At,Le]=_e.useState(!1),[Ut,tt]=_e.useState(0),[ct,ht]=_e.useState(0),
2kt=_e.useRef(null),Xr=_e.useRef(null),ps=C===0,K=C+1<=w,fe=h.type,W=h.dismissible!==!1,Ce=h.className||"",Ee=h.descriptionClassName||"",be=_e.useMemo(()=>b.findIndex(nt=>nt.toastId===h.id)||0,[b,h.id]),Ve=_e.useMemo(()=>{var nt;return(nt=h.closeButton)!=null?nt:M},[h.closeButton,M]),rt=_e.useMemo(()=>h.duration||Q||rA,[h.duration,Q]),ue=_e.useRef(0),Se=_e.useRef(0),Ge=_e.useRef(0),st=_e.useRef(null),[Et,cr]=J.split("-"),Xe=_e.useMemo(()=>b.reduce((nt,Wt,ke)=>ke>=be?nt:nt+Wt.height,0),[b,be]),bt=GI(),sr=h.invert||f,mr=fe==="loading";Se.current=_e.useMemo(()=>be*oe+Xe,[be,Xe]),_e.useEffect(()=>{Qe(!0)},[]),_e.useLayoutEffect(()=>{if(!U)return;let nt=Xr.current,Wt=nt.style.height;nt.style.height="auto";let ke=nt.getBoundingClientRect().height;nt.style.height=Wt,ht(ke),v(Zr=>Zr.find(cn=>cn.toastId===h.id)?Zr.map(cn=>cn.toastId===h.id?{...cn,height:ke}:cn):[{toastId:h.id,height:ke,position:h.position},...Zr])},[U,h.title,h.description,v,h.id]);let $e=_e.useCallback(()=>{We(!0),tt(Se.current),v(nt=>nt.filter(Wt=>Wt.toastId!==h.id)),setTimeout(()=>{k(h)},aA)},[h,k,v,Se]);_e.useEffect(()=>{if(h.promise&&fe==="loading"||h.duration===1/0||h.type==="loading")return;let nt,Wt=rt;return I||g||Te&&bt?(()=>{if(Ge.current<ue.current){let ke=new Date().getTime()-ue.current;Wt=Wt-ke}Ge.current=new Date().getTime()})():Wt!==1/0&&(ue.current=new Date().getTime(),nt=setTimeout(()=>{var ke;(ke=h.onAutoClose)==null||ke.call(h,h),$e()},Wt)),()=>clearTimeout(nt)},[I,g,ge,h,rt,$e,h.promise,fe,Te,bt]),_e.useEffect(()=>{let nt=Xr.current;if(nt){let Wt=nt.getBoundingClientRect().height;return ht(Wt),v(ke=>[{toastId:h.id,height:Wt,position:h.position},...ke]),()=>v(ke=>ke.filter(Zr=>Zr.toastId!==h.id))}},[v,h.id]),_e.useEffect(()=>{h.delete&&$e()},[$e,h.delete]);function Jr(){return le!=null&&le.loading?_e.createElement("div",{className:"sonner-loader","data-visible":fe==="loading"},le.loading):xe?_e.createElement("div",{className:"sonner-loader","data-visible":fe==="loading"},xe):_e.createElement($I,{visible:fe==="loading"})}return _e.createElement("li",{"aria-live":h.important?"assertive":"polite","aria-atomic":"true",role:"status",tabIndex:0,ref:Xr,className:ye(H,Ce,$?.toast,(t=h?.classNames)==null?void 0:t.toast,$?.default,$?.[fe],(r=h?.classNames)==null?void 0:r[fe]),"data-sonner-toast":"","data-rich-colors":(n=h.richColors)!=null?n:_,"data-styled":!(h.jsx||h.unstyled||m),"data-mounted":U,"data-promise":!!h.promise,"data-removed":pt,"data-visible":K,"data-y-position":Et,"data-x-position":cr,"data-index":C,"data-front":ps,"data-swiping":dt,"data-dismissible":W,"data-type":fe,"data-invert":sr,"data-swipe-out":At,"data-expanded":!!(I||ge&&U),style:{"--index":C,"--toasts-before":C,"--z-index":T.length-C,"--offset":`${pt?Ut:Se.current}px`,"--initial-height":ge?"auto":`${ct}px`,...V,...h.style},onPointerDown:nt=>{mr||!W||(kt.current=new Date,tt(Se.current),nt.target.setPointerCapture(nt.pointerId),nt.target.tagName!=="BUTTON"&&(ft(!0),st.current={x:nt.clientX,y:nt.clientY}))},onPointerUp:()=>{var nt,Wt,ke,Zr;if(At||!W)return;st.current=null;let cn=Number(((nt=Xr.current)==null?void 0:nt.style.getPropertyValue("--swipe-amount").replace("px",""))||0),Is=new Date().getTime()-((Wt=kt.current)==null?void 0:Wt.getTime()),al=Math.abs(cn)/Is;if(Math.abs(cn)>=iA||al>.11){tt(Se.current),(ke=h.onDismiss)==null||ke.call(h,h),$e(),Le(!0);return}(Zr=Xr.current)==null||Zr.style.setProperty("--swipe-amount","0px"),ft(!1)},onPointerMove:nt=>{var Wt;if(!st.current||!W)return;let ke=nt.clientY-st.current.y,Zr=nt.clientX-st.current.x,cn=(Et==="top"?Math.min:Math.max)(0,ke),Is=nt.pointerType==="touch"?10:2;Math.abs(cn)>Is?(Wt=Xr.current)==null||Wt.style.setProperty("--swipe-amount",`${ke}px`):Math.abs(Zr)>Is&&(st.current=null)}},Ve&&!h.jsx?_e.createElement("button",{"aria-label":B,"data-disabled":mr,"data-close-button":!0,onClick:mr||!W?()=>{}:()=>{var nt;$e(),(nt=h.onDismiss)==null||nt.call(h,h)},className:ye($?.closeButton,(s=h?.classNames)==null?void 0:s.closeButton)},_e.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},_e.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),_e.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))):null,h.jsx||_e.isValidElement(h.title)?h.jsx||h.title:_e.createElement(_e.Fragment,null,fe||h.icon||h.promise?_e.createElement("div",{"data-icon":"",className:ye($?.icon,(i=h?.classNames)==null?void 0:i.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||Jr():null,h.type!=="loading"?h.icon||le?.[fe]||UI(fe):null):null,_e.createElement("div",{"data-content":"",className:ye($?.content,(a=h?.classNames)==null?void 0:a.content)},_e.createElement("div",{"data-title":"",className:ye($?.title,(o=h?.classNames)==null?void 0:o.title)},h.title),h.description?_e.createElement("div",{"data-description":"",className:ye(F,Ee,$?.description,(l=h?.classNames)==null?void 0:l.description)},h.description):null),_e.isValidElement(h.cancel)?h.cancel:h.cancel&&Pl(h.cancel)?_e.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||G,onClick:nt=>{var Wt,ke;Pl(h.cancel)&&W&&((ke=(Wt=h.cancel).onClick)==null||ke.call(Wt,nt),$e())},className:ye($?.cancelButton,(c=h?.classNames)==null?void 0:c.cancelButton)},h.cancel.label):null,_e.isValidElement(h.action)?h.action:h.action&&Pl(h.action)?_e.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||L,onClick:nt=>{var Wt,ke;Pl(h.action)&&(nt.defaultPrevented||((ke=(Wt=h.action).onClick)==null||ke.call(Wt,nt),$e()))},className:ye($?.actionButton,(d=h?.classNames)==null?void 0:d.actionButton)},h.action.label):null))};function Sg(){if(typeof window>"u"||typeof document>"u")return"ltr";let e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}var cA=e=>{let{invert:t,position:r="bottom-right",hotkey:n=["altKey","KeyT"],expand:s,closeButton:i,className:a,offset:o,theme:l="light",richColors:c,duration:d,style:f,visibleToasts:h=eA,toastOptions:m,dir:g=Sg(),gap:v=sA,loadingIcon:w,icons:b,containerAriaLabel:C="Notifications",pauseWhenPageIsHidden:T,cn:I=oA}=e,[k,_]=_e.useState([]),M=_e.useMemo(()=>Array.from(new Set([r].concat(k.filter(Te=>Te.position).map(Te=>Te.position)))),[k,r]),[V,G]=_e.useState([]),[L,H]=_e.useState(!1),[F,Q]=_e.useState(!1),[J,oe]=_e.useState(l!=="system"?l:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dar
2k":"light"),xe=_e.useRef(null),ge=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),$=_e.useRef(null),le=_e.useRef(!1),B=_e.useCallback(Te=>{var ye;(ye=k.find(U=>U.id===Te.id))!=null&&ye.delete||pn.dismiss(Te.id),_(U=>U.filter(({id:Qe})=>Qe!==Te.id))},[k]);return _e.useEffect(()=>pn.subscribe(Te=>{if(Te.dismiss){_(ye=>ye.map(U=>U.id===Te.id?{...U,delete:!0}:U));return}setTimeout(()=>{uT.flushSync(()=>{_(ye=>{let U=ye.findIndex(Qe=>Qe.id===Te.id);return U!==-1?[...ye.slice(0,U),{...ye[U],...Te},...ye.slice(U+1)]:[Te,...ye]})})})}),[]),_e.useEffect(()=>{if(l!=="system"){oe(l);return}l==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?oe("dark"):oe("light")),typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",({matches:Te})=>{oe(Te?"dark":"light")})},[l]),_e.useEffect(()=>{k.length<=1&&H(!1)},[k]),_e.useEffect(()=>{let Te=ye=>{var U,Qe;n.every(pt=>ye[pt]||ye.code===pt)&&(H(!0),(U=xe.current)==null||U.focus()),ye.code==="Escape"&&(document.activeElement===xe.current||(Qe=xe.current)!=null&&Qe.contains(document.activeElement))&&H(!1)};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[n]),_e.useEffect(()=>{if(xe.current)return()=>{$.current&&($.current.focus({preventScroll:!0}),$.current=null,le.current=!1)}},[xe.current]),k.length?_e.createElement("section",{"aria-label":`${C} ${ge}`,tabIndex:-1},M.map((Te,ye)=>{var U;let[Qe,pt]=Te.split("-");return _e.createElement("ol",{key:Te,dir:g==="auto"?Sg():g,tabIndex:-1,ref:xe,className:a,"data-sonner-toaster":!0,"data-theme":J,"data-y-position":Qe,"data-x-position":pt,style:{"--front-toast-height":`${((U=V[0])==null?void 0:U.height)||0}px`,"--offset":typeof o=="number"?`${o}px`:o||tA,"--width":`${nA}px`,"--gap":`${v}px`,...f},onBlur:We=>{le.current&&!We.currentTarget.contains(We.relatedTarget)&&(le.current=!1,$.current&&($.current.focus({preventScroll:!0}),$.current=null))},onFocus:We=>{We.target instanceof HTMLElement&&We.target.dataset.dismissible==="false"||le.current||(le.current=!0,$.current=We.relatedTarget)},onMouseEnter:()=>H(!0),onMouseMove:()=>H(!0),onMouseLeave:()=>{F||H(!1)},onPointerDown:We=>{We.target instanceof HTMLElement&&We.target.dataset.dismissible==="false"||Q(!0)},onPointerUp:()=>Q(!1)},k.filter(We=>!We.position&&ye===0||We.position===Te).map((We,dt)=>{var ft,At;return _e.createElement(lA,{key:We.id,icons:b,index:dt,toast:We,defaultRichColors:c,duration:(ft=m?.duration)!=null?ft:d,className:m?.className,descriptionClassName:m?.descriptionClassName,invert:t,visibleToasts:h,closeButton:(At=m?.closeButton)!=null?At:i,interacting:F,position:Te,style:m?.style,unstyled:m?.unstyled,classNames:m?.classNames,cancelButtonStyle:m?.cancelButtonStyle,actionButtonStyle:m?.actionButtonStyle,removeToast:B,toasts:k.filter(Le=>Le.position==We.position),heights:V.filter(Le=>Le.position==We.position),setHeights:G,expandByDefault:s,gap:v,loadingIcon:w,expanded:L,pauseWhenPageIsHidden:T,cn:I})}))})):null};const uA=({...e})=>{const{theme:t="system"}=pb();return u.jsx(cA,{theme:t,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...e})},dA=xT,fA=bT,hA=wT,mb=N.forwardRef(({className:e,sideOffset:t=4,...r},n)=>u.jsx(Qv,{ref:n,sideOffset:t,className:ze("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r}));mb.displayName=Qv.displayName;const pA=Ea("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",sleek:"text-gray-300 hover:bg-[#98fe00]/20 hover:text-[#98fe00] transition-all duration-200",default1:"bg-[#98fe00]/10 text-[#98fe00] hover:bg-[#98fe00]/20 transition-all duration-300",default2:"bg-black text-[white] hover:bg-[#98fe00]/10 hover:text-[white] transition-all duration-300"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10",xs:"h-7 rounded-md px-3 text-xs"}},defaultVariants:{variant:"default",size:"default"}}),yt=N.forwardRef(({className:e,variant:t,size:r,asChild:n=!1,...s},i)=>{const a=n?Co:"button";return u.jsx(a,{className:ze(pA({variant:t,size:r,className:e})),ref:i,...s})});yt.displayName="Button";const mA=Zv,gA=CT,yA=Jv,gb=N.forwardRef(({className:e,...t},r)=>u.jsx(Xc,{className:ze("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:r}));gb.displayName=Xc.displayName;const vA=Ea("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4  border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),yb=N.forwardRef(({side:e="right",className:t,children:r,...n},s)=>u.jsxs(yA,{children:[u.jsx(gb,{}),u.jsxs(Jc,{ref:s,className:ze(vA({side:e}),t),...n,children:[r,u.jsxs(Xv,{className:"absolute right-4 top-4 roun
2ded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(tu,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));yb.displayName=Jc.displayName;const xA=N.forwardRef(({className:e,...t},r)=>u.jsx(Zc,{ref:r,className:ze("text-lg font-semibold text-foreground",e),...t}));xA.displayName=Zc.displayName;const bA=N.forwardRef(({className:e,...t},r)=>u.jsx(eu,{ref:r,className:ze("text-sm text-muted-foreground",e),...t}));bA.displayName=eu.displayName;const Pf=ET,jf=TT,wA=N.forwardRef(({className:e,inset:t,children:r,...n},s)=>u.jsxs(ex,{ref:s,className:ze("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...n,children:[r,u.jsx(ru,{className:"ml-auto h-4 w-4"})]}));wA.displayName=ex.displayName;const CA=N.forwardRef(({className:e,...t},r)=>u.jsx(tx,{ref:r,className:ze("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));CA.displayName=tx.displayName;const yc=N.forwardRef(({className:e,sideOffset:t=4,...r},n)=>u.jsx(ST,{children:u.jsx(rx,{ref:n,sideOffset:t,className:ze("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));yc.displayName=rx.displayName;const zs=N.forwardRef(({className:e,inset:t,...r},n)=>u.jsx(nx,{ref:n,className:ze("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));zs.displayName=nx.displayName;const SA=N.forwardRef(({className:e,children:t,checked:r,...n},s)=>u.jsxs(sx,{ref:s,className:ze("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:r,...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(ix,{children:u.jsx(jr,{className:"h-4 w-4"})})}),t]}));SA.displayName=sx.displayName;const EA=N.forwardRef(({className:e,children:t,...r},n)=>u.jsxs(ax,{ref:n,className:ze("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(ix,{children:u.jsx(xx,{className:"h-2 w-2 fill-current"})})}),t]}));EA.displayName=ax.displayName;const TA=N.forwardRef(({className:e,inset:t,...r},n)=>u.jsx(ox,{ref:n,className:ze("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));TA.displayName=ox.displayName;const vb=N.forwardRef(({className:e,...t},r)=>u.jsx(lx,{ref:r,className:ze("-mx-1 my-1 h-px bg-muted",e),...t}));
2vb.displayName=lx.displayName;function _A(e){const[t,r]=N.useState(!1);return N.useEffect(()=>{const n=window.matchMedia(e);n.matches!==t&&r(n.matches);const s=()=>r(n.matches);return window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[t,e]),t}const xb={address:"0xBB3D6C47379Abb4713Acffffa27483B726ee67dB",symbol:"SLINKY",decimals:18,chainId:8453,image:"/uploads/slinkylayer-token-icon.svg"},IA={chainId:"0x2105",chainName:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://mainnet.base.org"],blockExplorerUrls:["https://basescan.org"]};function Bf(e){return e?.code===4001||/reject|denied/i.test(e?.message||"")}async function AA(e,t){const r=`0x${t.toString(16)}`;try{if((await e.request({method:"eth_chainId"}))?.toLowerCase()===r.toLowerCase())return}catch{}try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]})}catch(n){if(Bf(n))throw n;t===8453&&await e.request({method:"wallet_addEthereumChain",params:[IA]})}}async function kA(e=xb){const t=window.ethereum;if(!t?.request||!e.address)return"unsupported";try{await AA(t,e.chainId)}catch(r){if(Bf(r))return"rejected"}try{const r=e.image?new URL(e.image,window.location.origin).href:void 0;return await t.request({method:"wallet_watchAsset",params:{type:"ERC20",options:{address:e.address,symbol:e.symbol,decimals:e.decimals,...r?{image:r}:{}}}})===!1?"rejected":"added"}catch(r){return Bf(r)?"rejected":r?.code===4200||/unsupported|not supported/i.test(r?.message||"")?"unsupported":"error"}}const Df=({variant:e="panel",token:t,className:r})=>{const{toast:n}=jn(),[s,i]=N.useState("idle"),a={...xb,...Object.fromEntries(Object.entries(t||{}).filter(([,h])=>h!=null&&h!==""))},o=`Add ${a.symbol} to wallet`,l=async h=>{if(h.preventDefault(),h.stopPropagation(),s==="pending")return;i("pending");const m=await kA(a);if(m==="added"){i("done"),n({description:`${a.symbol} added to your wallet`,duration:2500}),setTimeout(()=>i("idle"),2e3);return}if(i("idle"),m!=="rejected"){if(m==="unsupported"){n({description:`Your wallet doesn't support adding tokens automatically. Token address: ${a.address}`,duration:6e3});return}n({description:"Could not add the token. Please try again from your wallet.",variant:"destructive",duration:4e3})}},c=s==="pending"?ls:s==="done"?jr:bx,d="inline-flex items-center justify-center gap-1.5 font-medium transition-all duration-150 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:opacity-60",f={panel:ze("h-8 rounded-lg border border-border/70 bg-white px-3 text-[11px] uppercase tracking-wider text-foreground","hover:border-[#98fe00] hover:bg-[#98fe00]/10"),compact:ze("h-[34px] rounded-lg border border-border/60 bg-background/80 px-2.5 text-xs text-foreground","hover:border-[#98fe00] hover:bg-[#98fe00]/10"),menu:ze("w-full min-h-[44px] rounded-[8px] px-3 py-3 text-sm text-foreground justify-start gap-2.5","hover:bg-[#98fe00]/12 hover:text-foreground active:bg-[#98fe00]/25","focus:ring-0 focus:ring-offset-0")};return u.jsxs("button",{type:"button",onClick:l,disabled:s==="pending",title:e==="menu"?void 0:o,"aria-label":o,className:ze(d,f[e],r),children:[u.jsx(c,{className:ze("h-4 w-4 flex-shrink-0",s==="pending"&&"animate-spin",e==="menu"&&"text-[#4ba300]",s==="done"&&"text-[#4ba300]")}),e==="compact"?u.jsx("span",{className:"hidden lg:inline whitespace-nowrap",children:s==="done"?"Added":`Add ${a.symbol}`}):u.jsx("span",{className:"whitespace-nowrap font-medium",children:s==="done"?"Added to wallet ✓":o}),e==="menu"&&s!=="done"&&u.jsx(Ts,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground/70"})]})};function Sd({className:e}){return u.jsx("svg",{viewBox:"0 0 111 111",fill:"currentColor",className:e,"aria-hidden":!0,children:u.jsx("path",{d:"M54.9 110.1C85.2 110.1 109.8 85.5 109.8 55.2C109.8 24.9 85.2 0.3 54.9 0.3C26.1 0.3 2.5 22.5 0.2 50.7H72.8V59.7H0.2C2.5 87.9 26.1 110.1 54.9 110.1Z"})})}const NA=[{icon:$h,label:"Chat",path:"/chat"},{icon:Ef,label:"Tools",path:"/tools"},{icon:So,label:"Account",path:"/account"}],RA=({walletAddress:e,currentNetwork:t,onDisconnect:r})=>{const n=Dx(),[s,i]=N.useState(!1),[a,o]=N.useState(!1);pb();const{toast:l}=jn(),c=_A("(max-width: 768px)"),d=async()=>
2{if(e)try{await navigator.clipboard.writeText(e),o(!0),l({description:"Wallet address copied to clipboard!",duration:2e3}),setTimeout(()=>o(!1),2e3)}catch{l({description:"Failed to copy address",variant:"destructive",duration:2e3})}},f=({mobile:h=!1,onItemClick:m})=>u.jsx(u.Fragment,{children:NA.map(g=>{const v=g.icon,w=n.pathname===g.path;return u.jsxs(oo,{to:g.path,onClick:m,className:ze("relative px-1 py-2 text-[1rem] transition-all duration-200 group nav-link","hover:text-black focus:outline-none",h?"w-full flex items-center gap-3 px-6 py-2":"whitespace-nowrap"),children:[h&&u.jsx(v,{className:"h-4 w-4 flex-shrink-0"}),u.jsx("span",{className:"type","data-text":g.label,style:{"--n":g.label.length,"--w":`${g.label.length}ch`,"--dur":".9s"},children:u.jsx("span",{children:g.label})}),!h&&u.jsx("span",{className:ze("absolute bottom-0 left-0 h-[1px] bg-current transition-[width] duration-300 origin-left",w?"w-full":"w-0 group-hover:w-[100%]")})]},g.path)})});return u.jsxs("div",{className:"flex items-center justify-between w-full",children:[!c&&u.jsx("div",{className:"flex-1 flex justify-center",children:u.jsx("nav",{className:"flex items-center gap-8",children:u.jsx(f,{})})}),u.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e&&!c&&u.jsxs(fA,{children:[u.jsx(hA,{asChild:!0,children:u.jsxs("button",{onClick:d,className:ze("flex items-center gap-2 px-3 py-1.5 rounded-lg transition-all duration-150","bg-background/80 hover:bg-accent/10 border border-border/60","focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"),children:[u.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-[#1A50F9]",children:u.jsx(Sd,{className:"h-5 w-5"})}),u.jsx("span",{className:"text-sm font-medium text-foreground",children:`${e.slice(0,6)}...${e.slice(-4)}`}),a?u.jsx(jr,{className:"h-3 w-3 text-green-500"}):u.jsx(zn,{className:"h-3 w-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]})}),u.jsx(mb,{side:"bottom",className:"text-xs",children:"Wallet Address • Click to Copy"})]}),e&&!c&&u.jsx(Df,{variant:"compact"}),e&&u.jsxs(Pf,{children:[u.jsx(jf,{asChild:!0,children:u.jsx(yt,{variant:"ghost",className:"h-8 w-8 rounded-full hover:bg-accent transition-all duration-200 p-0",title:"User",children:u.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-[#98fe00] to-[#98fe00] flex items-center justify-center",children:u.jsx(So,{className:"h-4 w-4 text-black"})})})}),u.jsxs(yc,{align:"end",className:"w-[210px] mt-2 bg-background/95 backdrop-blur-sm border border-border rounded-lg shadow-lg",children:[c&&e&&u.jsx(u.Fragment,{children:u.jsxs("div",{className:"px-3 py-2 border-b border-border flex",children:[u.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-[#1A50F9]",children:u.jsx(Sd,{className:"h-5 w-5","aria-hidden":!0})}),u.jsxs("button",{onClick:d,className:"flex ml-[10px] items-center gap-2 rounded-md px-2 py-1 text-sm font-medium text-foreground hover:bg-accent/10 transition-colors",children:[`${e.slice(0,8)}...${e.slice(-6)}`,a?u.jsx(jr,{className:"h-3 w-3 text-green-500"}):u.jsx(zn,{className:"h-3 w-3"})]})]})}),c&&e&&u.jsx(zs,{asChild:!0,onSelect:h=>h.preventDefault(),className:"p-0 focus:bg-transparent data-[highlighted]:bg-transparent data-[highlighted]:text-foreground",children:u.jsx(Df,{variant:"menu"})}),u.jsx(zs,{asChild:!0,children:u.jsxs(oo,{to:"/account",className:"flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent rounded-md transition-colors duration-150",children:[u.jsx(So,{className:"h-4 w-4"}),"Account"]})}),u.jsxs(zs,{onClick:r,className:"flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent rounded-md transition-colors duration-150 cursor-pointer",children:[u.jsx(FT,{className:"h-4 w-4"}),"Disconnect"]})]})]}),c&&u.jsxs(mA,{open:s,onOpenChange:i,children:[u.jsx(gA,{asChild:!0,children:u.jsx(yt,{variant:"ghost",size:"icon",className:"md:hidden h-8 w-8 hover:bg-accent rounded-full","aria-label":"Open navigation menu",children:u.jsx(UT,{className:"h-4 w-4"})})}),u.jsx(yb,{side:"right",className:"w-72 p-0 bg-background/95 backdrop-blur-sm border-l border-border",children:u.jsxs("div",{className:"flex flex-col h-full",children:[u.jsx("div",{className:"flex items-center justify-between p-6 border-b border-border",children:u.jsx(oo,{to:"/",onClick:()=>
2i(!1),children:u.jsx("img",{src:"/uploads/slinky-logo.png",alt:"SlinkyLayer Logo",className:"w-[120px] object-contain"})})}),u.jsx("div",{className:"flex-1 py-6",children:u.jsxs("div",{className:"space-y-1",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-4 px-6",children:"Menu"}),u.jsx(f,{mobile:!0,onItemClick:()=>i(!1)})]})}),e&&u.jsx("div",{className:"p-6 border-t border-border",children:u.jsx("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-accent/10",children:u.jsxs("div",{className:"flex overflow-hidden",children:[u.jsx("div",{className:"flex items-center gap-2 mb-1",children:u.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-[#1A50F9]",children:u.jsx(Sd,{className:"h-5 w-5","aria-hidden":!0})})}),u.jsxs("button",{onClick:d,className:"text-sm ml-[10px] font-medium truncate text-left rounded-md px-2 py-1 hover:bg-accent/10 transition-colors flex items-center gap-1",children:[`${e.slice(0,8)}...${e.slice(-6)}`,a?u.jsx(jr,{className:"h-3 w-3 text-green-500"}):u.jsx(zn,{className:"h-3 w-3 opacity-50"})]})]})})})]})})]})]})]})},PA=()=>u.jsx("footer",{className:"hidden md:block border-t border-border bg-background/95 backdrop-blur-sm",children:u.jsxs("div",{className:"container mx-auto px-6 py-8",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-8",children:[u.jsxs("div",{className:"col-span-1 md:col-span-1",children:[u.jsx("div",{className:"flex items-center mb-[-20px]",children:u.jsx("img",{src:"/uploads/slinky-logo.png",alt:"SlinkyLayer Logo",className:"w-[185px] object-contain"})}),u.jsx("p",{className:"text-sm text-muted-foreground max-w-xs",children:"The Private Access Layer for AI"})]}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-foreground mb-4",children:"Others Links"}),u.jsxs("ul",{className:"space-y-2",children:[u.jsx("li",{children:u.jsx("a",{href:"https://docs.slinky.network",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Documentation"})}),u.jsx("li",{children:u.jsx("a",{href:"https://x.com/slinkylayer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Twitter"})}),u.jsx("li",{children:u.jsx("a",{href:"http://t.me/slinkylayer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Telegram"})}),u.jsx("li",{children:u.jsx("a",{href:"https://discord.com/invite/JnMyrBHpst",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Discord"})})]})]}),u.jsxs("div",{children:[u.jsx("h3",{className:"font-semibold text-foreground mb-4",children:"Legal"}),u.jsxs("ul",{className:"space-y-2",children:[u.jsx("li",{children:u.jsx("a",{href:"https://docs.slinky.network/legal/privacy-policy",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Privacy Policy"})}),u.jsx("li",{children:u.jsx("a",{href:"https://docs.slinky.network/legal/terms-of-service",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Terms of Service"})})]})]})]}),u.jsx("div",{className:"mt-8 pt-8 border-t border-border",children:u.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center",children:[u.jsx("p",{className:"text-sm text-muted-foreground",children:"© 2026 SlinkyLayer. All rights reserved."}),u.jsxs("div",{className:"flex items-center space-x-4 mt-4 md:mt-0",children:[u.jsx("a",{href:"https://x.com/slinkylayer",className:"text-muted-foreground hover:text-foreground transition-colors",children:u.jsx("svg",{className:"h-5 w-5",fill:"currentColor",viewBox:"0 0 24 24","aria-hidden":"true",children:u.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})})}),u.jsx("a",{href:"http://t.me/slinkylayer",className:"text-muted-foreground hover:text-foreground transition-colors",children:u.jsx("svg",{className:"h-5 w-5",fill:"currentColor",viewBox:"0 0 24 24","aria-hidden":"true",children:u.jsx("path",{d:"M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.9
262 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"})})}),u.jsx("a",{href:"https://discord.com/invite/JnMyrBHpst",className:"text-muted-foreground hover:text-foreground transition-colors",children:u.jsx("svg",{className:"h-5 w-5",fill:"currentColor",viewBox:"0 0 24 24","aria-hidden":"true",children:u.jsx("path",{d:"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419-.019 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1568 2.4189Z"})})})]})]})})]})}),jA=()=>{const e=Sa(),t=Dx();jn();const r=n=>t.pathname===n;return u.jsxs("nav",{className:"flex justify-around py-4 bg-black/80  border border-border/50 backdrop-blur-lg",children:[u.jsxs("button",{onClick:()=>e("/tools"),className:`flex flex-col items-center space-y-1 transition-all duration-200 text-xs font-semibold select-none ${r("/tools")?"text-[#98fe00] scale-105":"text-muted-foreground hover:text-[#98fe00]"}`,"aria-label":"Tools",title:"Tools",children:[u.jsx(Tf,{className:"h-5 w-5"}),u.jsx("span",{children:"Tools"})]}),u.jsxs("button",{onClick:()=>e("/profile"),className:`flex flex-col items-center space-y-1 transition-all duration-200 text-xs font-semibold select-none ${r("/profile")?"text-[#98fe00] scale-105":"text-muted-foreground hover:text-[#98fe00]"}`,"aria-label":"Account",title:"Account",children:[u.jsx(So,{className:"h-5 w-5"}),u.jsx("span",{children:"Account"})]})]})},BA="https://rczgfugipbjrrxsmsaqa.supabase.co",DA="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJjemdmdWdpcGJqcnJ4c21zYXFhIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQyODYwNTcsImV4cCI6MjA1OTg2MjA1N30.pELZO0foUj96Cto3cD3JontGcDZAxKibIpvqM7LyE6A",En=x_(BA,DA),LA=()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},MA={chainId:"0x2105",chainName:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://mainnet.base.org"],blockExplorerUrls:["https://basescan.org"]};function OA(e){if(typeof e=="string"){const t=e.trim().toLowerCase();return t.startsWith("0x")?t:"0x"+parseInt(t,10).toString(16)}return typeof e=="number"?"0x"+e.toString(16):""}async function FA(e,t){const r=await e.request({method:"eth_chainId"});if(OA(r)!==t.chainId)try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:t.chainId}]})}catch(s){const i=(s?.message||"").toLowerCase();if(s?.code===4902||s?.code===-32603&&i.includes("unrecognized"))await e.request({method:"wallet_addEthereumChain",params:[t]}),await e.request({method:"wallet_switchEthereumChain",params:[{chainId:t.chainId}]});else throw s?.code===4001?new Error(`User rejected network switch to ${t.chainName}.`):s}}const UA=async()=>{const{ethereum:e}=window;if(!e)throw new Error("MetaMask is not installed");await FA(e,MA);const t=new Yc(e);return await t.send("eth_requestAccounts",[]),{address:(await t.getSigner().getAddress()).toLowerCase(),type:"evm"}},VA=async(e,t)=>{if(!window.ethereum)throw new Error("MetaMask is not installed");return await(await new Yc(window.ethereum).getSigner()).signMessage(e)},$A=(e,t,r)=>{try{const n=nT(e,t);return!!r&&n.toLowerCase()===r.toLowerCase()}catch{return!1}},zA=async(e,t)=>{if(window.solana&&window.solana.isPhantom)try{const r=new TextEncoder().encode(e),n=await window.solana.signMessage(r,"utf8");return Array.from(n.signature).map(s=>s.toString(16).padStart(2,"0")).join("")}catch{throw new Error("Failed to sign message with Phantom wallet")}return`solana_signature_${e}_${t}`},KA=(e,t,r)=>t===`solana_signature_${e}_${r}`||t.length===128,qA=async e=>{const t=LA();let r;if(e.type==="evm"){if(r=await VA(t,e.address),!$A(t,r,e.address))throw new Error("Invalid EVM signature")}else if(r=await zA(t,e.address),!KA(t,r,e.address))throw new Error("Invalid Solana signature");const{data:n,error:s}=await En.functions.invoke("generate-web3-jwt",{body:{wallet_address:e.address,wallet_type:e.type}});if(s)throw s;if(!n||!n.token||!n.user)throw new Error("Invalid response from authentication service");if(co(),localStorage.setItem("wallet_address",e.address),localStorage.setItem("wallet_type",e.type),localStorage.setItem("web3_jwt",n.token),localStorage.setItem("wallet_connected_at",Date.now().toString()),window.dispatchEvent(new Event("walletConnected")),localStorage.getItem("web3_jwt")!==n.token)throw new Error("Failed to store authentication token");return{token:n.token,user:n.user}},Eo=()=>{const e=localStorage.getItem("wallet_address"),t=localStorage.getItem("wallet_type"),r=localStorage.getItem("web3_jwt"),n=localStorage.getItem("wallet_connected_at");if(!e||!t||!r||!n)return null;const s=Date.now()-parseInt(n),i=24*60*60*1e3;return s>=i?(co(),null):{address:e,type:t}},co=()=>{localStorage.removeItem("wallet_address"),localStorage.removeItem("wallet_type"),localStorage.removeItem("web3_jwt"),localStorage.removeItem("wallet_connected_at"),localStorage.removeItem("current_user"),window.dispatchEvent(new Event("walletDisconnected"))},HA=async()=>{const e=Eo();if(!e)return null;try{if(e.type==="evm"&&window.ethereum){const r=await new Yc(window.ethereum).send("eth_accounts",[]);if(r.length>0&&r[0]&&r[0].toLowerCase()===e.address)return e}else if(e.type==="solana"&&(window.solana&&window.solana.isPhantom&&window.solana.isConnected||e.address.startsWith("sol_mock_")))return e}catch{}return null},zo=Zv,GA=Jv,bb=N.forwardRef(({className:e,...t},r)=>u.jsx(Xc,{ref:r,className:ze("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));bb.displayName=Xc.displayName;const _a=N.forwardRef(({className:e,children:t,hideCloseButton:r=!1,...n},s)=>u.jsxs(GA,{children:[u.jsx(bb,{}),u.jsxs(Jc,{ref:s,className:ze("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rou
2nded-lg",e),...n,children:[t,!r&&u.jsxs(Xv,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(tu,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));_a.displayName=Jc.displayName;const Ko=({className:e,...t})=>u.jsx("div",{className:ze("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Ko.displayName="DialogHeader";const qo=N.forwardRef(({className:e,...t},r)=>u.jsx(Zc,{ref:r,className:ze("text-lg font-semibold leading-none tracking-tight",e),...t}));qo.displayName=Zc.displayName;const au=N.forwardRef(({className:e,...t},r)=>u.jsx(eu,{ref:r,className:ze("text-sm text-muted-foreground",e),...t}));au.displayName=eu.displayName;const Jh=({isOpen:e,onClose:t,onWalletConnected:r})=>{const[n,s]=N.useState(!1),[i,a]=N.useState(null),{toast:o}=jn(),l=async()=>{s(!0),a("evm");try{const c=await UA(),d=await qA(c);await new Promise(f=>setTimeout(f,100)),r(c),t(),o({title:"EVM Wallet Connected",description:`Successfully connected to ${c.address.slice(0,8)}...${c.address.slice(-6)}`})}catch(c){o({title:"Connection Failed",description:c.message||"Failed to connect EVM wallet",variant:"destructive"})}finally{s(!1),a(null)}};return u.jsx(zo,{open:e,onOpenChange:()=>{},children:u.jsxs(_a,{className:"sm:max-w-md",children:[u.jsxs(Ko,{children:[u.jsx("div",{className:"flex",children:u.jsx(qo,{className:"",children:"Connect Wallet"})}),u.jsx(au,{children:"Connect your preferred wallet to continue"})]}),u.jsx("div",{className:"space-y-4 py-4",children:u.jsxs(yt,{onClick:l,disabled:n,className:"w-full h-16 bg-[#98fe00]/10 text-[#98fe00] border border-[#98fe00]/30 hover:bg-[#98fe00]/20 transition-all duration-300 disabled:opacity-50",children:[u.jsx(Ts,{className:"h-6 w-6 mr-3 text-black"}),u.jsxs("div",{className:"text-left",children:[u.jsx("div",{className:"font-semibold text-black",children:n&&i==="evm"?"Connecting...":"EVM Wallet"}),u.jsx("div",{className:"text-sm opacity-70 text-black",children:"MetaMask, WalletConnect"})]})]})})]})})},pi=({children:e,walletAddress:t,onConnect:r})=>{const[n,s]=N.useState(!1);N.useEffect(()=>{if(t)s(!1);else{const a=Eo();!!(localStorage.getItem("web3_jwt")&&a)||s(!0)}},[t]);const i=a=>{s(!1),r(a)};return u.jsxs(u.Fragment,{children:[e,u.jsx(Jh,{isOpen:n,onClose:()=>s(!1),onWalletConnected:i})]})};function WA(e){return VT({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M389.2 48h70.6L305.6 224.2 487 464H345L233.7 318.6 106.5 464H35.8L200.7 275.5 26.8 48H172.4L272.9 180.9 389.2 48zM364.4 421.8h39.1L151.1 88h-42L364.4 421.8z"},child:[]}]})(e)}var Ho=e=>e.type==="checkbox",Ti=e=>e instanceof Date,Gr=e=>e==null;const wb=e=>typeof e=="object";var br=e=>!Gr(e)&&!Array.isArray(e)&&wb(e)&&!Ti(e),YA=e=>br(e)&&e.target?Ho(e.target)?e.target.checked:e.target.value:e,QA=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,XA=(e,t)=>e.has(QA(t)),JA=e=>{const t=e.constructor&&e.constructor.prototype;return br(t)&&t.hasOwnProperty("isPrototypeOf")},Zh=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function vn(e){let t;const r=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Zh&&(e instanceof Blob||e instanceof FileList))&&(r||br(e)))if(t=r?[]:{},!r&&!JA(e))t=e;else for(const n in e)e.hasOwnProperty(n)&&(t[n]=vn(e[n]));else return e;return t}var ou=e=>Array.isArray(e)?e.filter(Boolean):[],xr=e=>e===void 0,et=(e,t,r)=>{if(!t||!br(e))return r;const n=ou(t.split(/[,[\].]+?/)).reduce((s,i)=>Gr(s)?s:s[i],e);return xr(n)||n===e?xr(e[t])?r:e[t]:n},Xn=e=>typeof e=="boolean",ep=e=>/^\w*$/.test(e),Cb=e=>ou(e.replace(/["|']|\]/g,"").split(/\.|\[/)),ar=(e,t,r)=>{let n=-1;const s=ep(t)?[t]:Cb(t),i=s.length,a=i-1;for(;++n<i;){const o=s[n];let l=r;if(n!==a){const c=e[o];l=br(c)||Array.isArray(c)?c:isNaN(+s[n+1])?{}:[]}if(o==="__proto__")return;e[o]=l,e=e[o]}return e};const Eg={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},Un={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},xs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};_e.createContext(null);var ZA=(e,t,r,n=!0)=>{const s={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(s,i,{get:()=>{const a=i;return t._proxyFormState[a]!==Un.all&&(t._proxyFormState[a]=!n||Un.all),e[a]}});return s},tn=e=>br(e)&&!Object.keys(e).length,ek=(e,t,r,n)=>{r(e);const{name:s,...i}=e;return tn(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(a=>t[a]===Un.all)},tc=e=>Array.isArray(e)?e:[e];function tk(e){const t=_e.useRef(e);t.current=e,_e.useEffect(()=>{const r=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{r&&r.unsubscribe()}},[e.disabled])}var is=e=>typeof e=="string",rk=(e,t,r,n,s)=>is(e)?(n&&t.watch.add(e),et(r,e,s)):Array.isArray(e)?e.map(i=>(n&&t.watch.add(i),et(r,i))):(n&&(t.watchAll=!0),r),nk=(e,t,r,n,s)=>t?{...r[e],types:{...r[e]&&r[e].types?r[e].types:{},[n]:s||!0}}:{},Tg=e=>({isOnSubmit:!e||e===Un.onSubmit,isOnBlur:e===Un.onBlur,isOnChange:e===Un.onChange,isOnAll:e===Un.all,isOnTouch:e===Un.onTouched}),_g=(e,t,r)=>!r&&(t.watchAll||t.watch.has(e)||[...t.watch].some(n=>e.startsWith(n)&&/^\.\w+/.test(e.slice(n.length))));const uo=(e,t,r,n)=>{for(const s of r||Object.keys(e)){const i=et(e,s);if(i){const{_f:a,...o}=i;
vendor: 17,328 bytes, line 2
2if(a){if(a.refs&&a.refs[0]&&t(a.refs[0],s)&&!n)return!0;if(a.ref&&t(a.ref,a.name)&&!n)return!0;if(uo(o,t))break}else if(br(o)&&uo(o,t))break}}};var sk=(e,t,r)=>{const n=tc(et(e,r));return ar(n,"root",t[r]),ar(e,r,n),e},tp=e=>e.type==="file",Cs=e=>typeof e=="function",vc=e=>{if(!Zh)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},rc=e=>is(e),rp=e=>e.type==="radio",xc=e=>e instanceof RegExp;const Ig={value:!1,isValid:!1},Ag={value:!0,isValid:!0};var Sb=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!xr(e[0].attributes.value)?xr(e[0].value)||e[0].value===""?Ag:{value:e[0].value,isValid:!0}:Ag:Ig}return Ig};const kg={isValid:!1,value:null};var Eb=e=>Array.isArray(e)?e.reduce((t,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:t,kg):kg;function Ng(e,t,r="validate"){if(rc(e)||Array.isArray(e)&&e.every(rc)||Xn(e)&&!e)return{type:r,message:rc(e)?e:"",ref:t}}var Ji=e=>br(e)&&!xc(e)?e:{value:e,message:""},Rg=async(e,t,r,n,s)=>{const{ref:i,refs:a,required:o,maxLength:l,minLength:c,min:d,max:f,pattern:h,validate:m,name:g,valueAsNumber:v,mount:w,disabled:b}=e._f,C=et(t,g);if(!w||b)return{};const T=a?a[0]:i,I=F=>{n&&T.reportValidity&&(T.setCustomValidity(Xn(F)?"":F||""),T.reportValidity())},k={},_=rp(i),M=Ho(i),V=_||M,G=(v||tp(i))&&xr(i.value)&&xr(C)||vc(i)&&i.value===""||C===""||Array.isArray(C)&&!C.length,L=nk.bind(null,g,r,k),H=(F,Q,J,oe=xs.maxLength,xe=xs.minLength)=>{const ge=F?Q:J;k[g]={type:F?oe:xe,message:ge,ref:i,...L(F?oe:xe,ge)}};if(s?!Array.isArray(C)||!C.length:o&&(!V&&(G||Gr(C))||Xn(C)&&!C||M&&!Sb(a).isValid||_&&!Eb(a).isValid)){const{value:F,message:Q}=rc(o)?{value:!!o,message:o}:Ji(o);if(F&&(k[g]={type:xs.required,message:Q,ref:T,...L(xs.required,Q)},!r))return I(Q),k}if(!G&&(!Gr(d)||!Gr(f))){let F,Q;const J=Ji(f),oe=Ji(d);if(!Gr(C)&&!isNaN(C)){const xe=i.valueAsNumber||C&&+C;Gr(J.value)||(F=xe>J.value),Gr(oe.value)||(Q=xe<oe.value)}else{const xe=i.valueAsDate||new Date(C),ge=B=>new Date(new Date().toDateString()+" "+B),$=i.type=="time",le=i.type=="week";is(J.value)&&C&&(F=$?ge(C)>ge(J.value):le?C>J.value:xe>new Date(J.value)),is(oe.value)&&C&&(Q=$?ge(C)<ge(oe.value):le?C<oe.value:xe<new Date(oe.value))}if((F||Q)&&(H(!!F,J.message,oe.message,xs.max,xs.min),!r))return I(k[g].message),k}if((l||c)&&!G&&(is(C)||s&&Array.isArray(C))){const F=Ji(l),Q=Ji(c),J=!Gr(F.value)&&C.length>+F.value,oe=!Gr(Q.value)&&C.length<+Q.value;if((J||oe)&&(H(J,F.message,Q.message),!r))return I(k[g].message),k}if(h&&!G&&is(C)){const{value:F,message:Q}=Ji(h);if(xc(F)&&!C.match(F)&&(k[g]={type:xs.pattern,message:Q,ref:i,...L(xs.pattern,Q)},!r))return I(Q),k}if(m){if(Cs(m)){const F=await m(C,t),Q=Ng(F,T);if(Q&&(k[g]={...Q,...L(xs.validate,Q.message)},!r))return I(Q.message),k}else if(br(m)){let F={};for(const Q in m){if(!tn(F)&&!r)break;const J=Ng(await m[Q](C,t),T,Q);J&&(F={...J,...L(Q,J.message)},I(J.message),r&&(k[g]=F))}if(!tn(F)&&(k[g]={ref:T,...F},!r))return k}}return I(!0),k};function ik(e,t){const r=t.slice(0,-1).length;let n=0;for(;n<r;)e=xr(e)?n++:e[t[n++]];return e}function ak(e){for(const t in e)if(e.hasOwnProperty(t)&&!xr(e[t]))return!1;return!0}function Sr(e,t){const r=Array.isArray(t)?t:ep(t)?[t]:Cb(t),n=r.length===1?e:ik(e,r),s=r.length-1,i=r[s];return n&&delete n[i],s!==0&&(br(n)&&tn(n)||Array.isArray(n)&&ak(n))&&Sr(e,r.slice(0,-1)),e}var Ed=()=>{let e=[];return{get observers(){return e},next:s=>{for(const i of e)i.next&&i.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(i=>i!==s)}}),unsubscribe:()=>{e=[]}}},Lf=e=>Gr(e)||!wb(e);function $s(e,t){if(Lf(e)||Lf(t))return e===t;if(Ti(e)&&Ti(t))return e.getTime()===t.getTime();const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(const s of r){const i=e[s];if(!n.includes(s))return!1;if(s!=="ref"){const a=t[s];if(Ti(i)&&Ti(a)||br(i)&&br(a)||Array.isArray(i)&&Array.isArray(a)?!$s(i,a):i!==a)return!1}}return!0}var Tb=e=>e.type==="select-multiple",ok=e=>rp(e)||Ho(e),Td=e=>vc(e)&&e.isConnected,_b=e=>{for(const t in e)if(Cs(e[t]))return!0;return!1};function bc(e,t={}){const r=Array.isArray(e);if(br(e)||r)for(const n in e)Array.isArray(e[n])||br(e[n])&&!_b(e[n])?(t[n]=Array.isArray(e[n])?[]:{},bc(e[n],t[n])):Gr(e[n])||(t[n]=!0);return t}function Ib(e,t,r){const n=Array.isArray(e);if(br(e)||n)for(const s in e)Array.isArray(e[s])||br(e[s])&&!_b(e[s])?xr(t)||Lf(r[s])?r[s]=Array.isArray(e[s])?bc(e[s],[]):{...bc(e[s])}:Ib(e[s],Gr(t)?{}:t[s],r[s]):r[s]=!$s(e[s],t[s]);return r}var Qa=(e,t)=>Ib(e,t,bc(t)),Ab=(e,{valueAsNumber:t,valueAsDate:r,setValueAs:n})=>xr(e)?e:t?e===""?NaN:e&&+e:r&&is(e)?new Date(e):n?n(e):e;function _d(e){const t=e.ref;if(!(e.refs?e.refs.every(r=>r.disabled):t.disabled))return tp(t)?t.files:rp(t)?Eb(e.refs).value:Tb(t)?[...t.selectedOptions].map(({value:r})=>r):Ho(t)?Sb(e.refs).value:Ab(xr(t.value)?e.ref.value:t.value,e)}var lk=(e,t,r,n)=>{const s={};for(const i of e){const a=et(t,i);a&&ar(s,i,a._f)}return{criteriaMode:r,names:[...e],fields:s,shouldUseNativeValidation:n}},Xa=e=>xr(e)?e:xc(e)?e.source:br(e)?xc(e.value)?e.value.source:e.value:e;const Pg="AsyncFunction";var ck=e=>(!e||!e.validate)&&!!(Cs(e.validate)&&e.validate.constructor.name===Pg||br(e.validate)&&Object.values(e.validate).find(t=>t.constructor.name===Pg)),uk=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function jg(e,t,r){const n=et(e,r);if(n||ep(r))return{error:n,name:r};const s=r.split(".");for(;s.length;){const i=s.join("."),a=et(t,i),o=et(e,i);if(a&&!Array.isArray(a)&&r!==i)return{name:r};if(o&&o.type)return{name:i,error:o};s.pop()}return{name:r}}var dk=(e,t,r,n,s)=>s.isOnAll?!1:!r&&s.isOnTouch?!(t||e):(r?n.isOnBlur:s.isOnBlur)?!e:(r?n.isOnChange:s.isOnChange)?e:!0,fk=(e,t)=>!ou(et(e,t)).length&&Sr(e,t);const hk={mode:Un.onSubmit,reValidateMode:Un.onChange,shouldFocusError:!0};function pk(e={}){let t={...hk,...e},r={submitCount:0,isDirty:!1,isLoading:Cs(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},n={},s=br(t.defaultValues)||br(t.values)?vn(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:vn(s),a={action:!1,mount:!1,watch:!1},o={mount:new Set,unMount:new Set,array:new Set,watch:new Set},l,c=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},f={values:Ed(),array:Ed(),state:Ed()},h=Tg(t.mode),m=Tg(t.reValidateMode),g=t.criteriaMode===Un.all,v=K=>fe=>{clearTimeout(c),c=setTimeout(K,fe)},w=async K=>{if(!e.disabled&&(d.isValid||K)){const fe=t.resolver?tn((await V()).errors):await L(n,!0);fe!==r.isValid&&f.state.next({isValid:fe})}},b=(K,fe)=>{!e.disabled&&(d.isValidating||d.validatingFields)&&((K||Array.from(o.mount)).forEach(W=>{W&&(fe?ar(r.validatingFields,W,fe):Sr(r.validatingFields,W))}),f.state.next({validatingFields:r.validatingFields,isValidating:!tn(r.validatingFields)}))},C=(K,fe=[],W,Ce,Ee=!0,be=!0)=>{if(Ce&&W&&!e.disabled){if(a.action=!0,be&&Array.isArray(et(n,K))){const Ve=W(et(n,K),Ce.argA,Ce.argB);Ee&&ar(n,K,Ve)}if(be&&Array.isArray(et(r.errors,K))){const Ve=W(et(r.errors,K),Ce.argA,Ce.argB);Ee&&ar(r.errors,K,Ve),fk(r.errors,K)}if(d.touchedFields&&be&&Array.isArray(et(r.touchedFields,K))){const Ve=W(et(r.touchedFields,K),Ce.argA,Ce.argB);Ee&&ar(r.touchedFields,K,Ve)}d.dirtyFields&&(r.dirtyFields=Qa(s,i)),f.state.next({name:K,isDirty:F(K,fe),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else ar(i,K,fe)},T=(K,fe)=>{ar(r.errors,K,fe),f.state.next({errors:r.errors})},I=K=>{r.errors=K,f.state.next({errors:r.errors,isValid:!1})},k=(K,fe,W,Ce)=>{const Ee=et(n,K);if(Ee){const be=et(i,K,xr(W)?et(s,K):W);xr(be)||Ce&&Ce.defaultChecked||fe?ar(i,K,fe?be:_d(Ee._f)):oe(K,be),a.mount&&w()}},_=(K,fe,W,Ce,Ee)=>{let be=!1,Ve=!1;const rt={name:K};if(!e.disabled){const ue=!!(et(n,K)&&et(n,K)._f&&et(n,K)._f.disabled);if(!W||Ce){d.isDirty&&(Ve=r.isDirty,r.isDirty=rt.isDirty=F(),be=Ve!==rt.isDirty);const Se=ue||$s(et(s,K),fe);Ve=!!(!ue&&et(r.dirtyFields,K)),Se||ue?Sr(r.dirtyFields,K):ar(r.dirtyFields,K,!0),rt.dirtyFields=r.dirtyFields,be=be||d.dirtyFields&&Ve!==!Se}if(W){const Se=et(r.touchedFields,K);Se||(ar(r.touchedFields,K,W),rt.touchedFields=r.touchedFields,be=be||d.touchedFields&&Se!==W)}be&&Ee&&f.state.next(rt)}return be?rt:{}},M=(K,fe,W,Ce)=>{const Ee=et(r.errors,K),be=d.isValid&&Xn(fe)&&r.isValid!==fe;if(e.delayError&&W?(l=v(()=>T(K,W)),l(e.delayError)):(clearTimeout(c),l=null,W?ar(r.errors,K,W):Sr(r.errors,K)),(W?!$s(Ee,W):Ee)||!tn(Ce)||be){const Ve={...Ce,...be&&Xn(fe)?{isValid:fe}:{},errors:r.errors,name:K};r={...r,...Ve},f.state.next(Ve)}},V=async K=>{b(K,!0);const fe=await t.resolver(i,t.context,lk(K||o.mount,n,t.criteriaMode,t.shouldUseNativeValidation));return b(K),fe},G=async K=>{const{errors:fe}=await V(K);if(K)for(const W of K){const Ce=et(fe,W);Ce?ar(r.errors,W,Ce):Sr(r.errors,W)}else r.errors=fe;return fe},L=async(K,fe,W={valid:!0})=>{for(const Ce in K){const Ee=K[Ce];if(Ee){const{_f:be,...Ve}=Ee;if(be){const rt=o.array.has(be.name),ue=Ee._f&&ck(Ee._f);ue&&d.validatingFields&&b([Ce],!0);const Se=await Rg(Ee,i,g,t.shouldUseNativeValidation&&!fe,rt);if(ue&&d.validatingFields&&b([Ce]),Se[be.name]&&(W.valid=!1,fe))break;!fe&&(et(Se,be.name)?rt?sk(r.errors,Se,be.name):ar(r.errors,be.name,Se[be.name]):Sr(r.errors,be.name))}!tn(Ve)&&await L(Ve,fe,W)}}return W.valid},H=()=>{for(const K of o.unMount){const fe=et(n,K);fe&&(fe._f.refs?fe._f.refs.every(W=>!Td(W)):!Td(fe._f.ref))&&We(K)}o.unMount=new Set},F=(K,fe)=>!e.disabled&&(K&&fe&&ar(i,K,fe),!$s(Te(),s)),Q=(K,fe,W)=>rk(K,o,{...a.mount?i:xr(fe)?s:is(K)?{[K]:fe}:fe},W,fe),J=K=>ou(et(a.mount?i:s,K,e.shouldUnregister?et(s,K,[]):[])),oe=(K,fe,W={})=>{const Ce=et(n,K);let Ee=fe;if(Ce){const be=Ce._f;be&&(!be.disabled&&ar(i,K,Ab(fe,be)),Ee=vc(be.ref)&&Gr(fe)?"":fe,Tb(be.ref)?[...be.ref.options].forEach(Ve=>Ve.selected=Ee.includes(Ve.value)):be.refs?Ho(be.ref)?be.refs.length>1?be.refs.forEach(Ve=>(!Ve.defaultChecked||!Ve.disabled)&&(Ve.checked=Array.isArray(Ee)?!!Ee.find(rt=>rt===Ve.value):Ee===Ve.value)):be.refs[0]&&(be.refs[0].checked=!!Ee):be.refs.forEach(Ve=>Ve.checked=Ve.value===Ee):tp(be.ref)?be.ref.value="":(be.ref.value=Ee,be.ref.type||f.values.next({name:K,values:{...i}})))}(W.shouldDirty||W.shouldTouch)&&_(K,Ee,W.shouldTouch,W.shouldDirty,!0),W.shouldValidate&&B(K)},xe=(K,fe,W)=>{for(const Ce in fe){const Ee=fe[Ce],be=`${K}.${Ce}`,Ve=et(n,be);(o.array.has(K)||br(Ee)||Ve&&!Ve._f)&&!Ti(Ee)?xe(be,Ee,W):oe(be,Ee,W)}},ge=(K,fe,W={})=>{const Ce=et(n,K),Ee=o.array.has(K),be=vn(fe);ar(i,K,be),Ee?(f.array.next({name:K,values:{...i}}),(d.isDirty||d.dirtyFields)&&W.shouldDirty&&f.state.next({name:K,dirtyFields:Qa(s,i),isDirty:F(K,be)})):Ce&&!Ce._f&&!Gr(be)?xe(K,be,W):oe(K,be,W),_g(K,o)&&f.state.next({...r}),f.values.next({name:a.mount?K:void 0,values:{...i}})},$=async K=>{a.mount=!0;const fe=K.target;let W=fe.name,Ce=!0;const Ee=et(n,W),be=()=>fe.type?_d(Ee._f):YA(K),Ve=rt=>{Ce=Number.isNaN(rt)||Ti(rt)&&isNaN(rt.getTime())||$s(rt,et(i,W,rt))};if(Ee){let rt,ue;const Se=be(),Ge=K.type===Eg.BLUR||K.type===Eg.FOCUS_OUT,st=!uk(Ee._f)&&!t.resolver&&!et(r.errors,W)&&!Ee._f.deps||dk(Ge,et(r.touchedFields,W),r.isSubmitted,m,h),Et=_g(W,o,Ge);ar(i,W,Se),Ge?(Ee._f.onBlur&&Ee._f.onBlur(K),l&&l(0)):Ee._f.onChange&&Ee._f.onChange(K);const cr=_(W,Se,Ge,!1),Xe=!tn(cr)||Et;if(!Ge&&f.values.next({name:W,type:K.type,values:{...i}}),st)return d.isValid&&(e.mode==="onBlur"?Ge&&w():w()),Xe&&f.state.next({name:W,...Et?{}:cr});if(!Ge&&Et&&f.state.next({...r}),t.resolver){const{errors:bt}=await V([W]);if(Ve(Se),Ce){const sr=jg(r.errors,n,W),mr=jg(bt,n,sr.name||W);rt=mr.error,W=mr.name,ue=tn(bt)}}else b([W],!0),rt=(await Rg(Ee,i,g,t.shouldUseNativeValidation))[W],b([W]),Ve(Se),Ce&&(rt?ue=!1:d.isValid&&(ue=await L(n,!0)));Ce&&(Ee._f.deps&&B(Ee._f.deps),M(W,ue,rt,cr))}},le=(K,fe)=>{if(et(r.errors,fe)&&K.focus)return K.focus(),1},B=async(K,fe={})=>{let W,Ce;const Ee=tc(K);if(t.resolver){const be=await G(xr(K)?K:Ee);W=tn(be),Ce=K?!Ee.some(Ve=>et(be,Ve)):W}else K?(Ce=(await Promise.all(Ee.map(async be=>{const Ve=et(n,be);return await L(Ve&&Ve._f?{[be]:Ve}:Ve)}))).every(Boolean),!(!Ce&&!r.isValid)&&w()):Ce=W=await L(n);return f.state.next({...!is(K)||d.isValid&&W!==r.isValid?{}:{name:K},...t.resolver||!K?{isValid:W}:{},errors:r.errors}),fe.shouldFocus&&!Ce&&uo(n,le,K?Ee:o.mount),Ce},Te=K=>{const fe={...a.mount?i:s};return xr(K)?fe:is(K)?et(fe,K):K.map(W=>et(fe,W))},ye=(K,fe)=>({invalid:!!et((fe||r).errors,K),isDirty:!!et((fe||r).dirtyFields,K),error:et((fe||r).errors,K),isValidating:!!et(r.validatingFields,K),isTouched:!!et((fe||r).touchedFields,K)}),U=K=>{K&&tc(K).forEach(fe=>Sr(r.errors,fe)),f.state.next({errors:K?r.errors:{}})},Qe=(K,fe,W)=>{const Ce=(et(n,K,{_f:{}})._f||{}).ref,Ee=et(r.errors,K)||{},{ref:be,message:Ve,type:rt,...ue}=Ee;ar(r.errors,K,{...ue,...fe,ref:Ce}),f.state.next({name:K,errors:r.errors,isValid:!1}),W&&W.shouldFocus&&Ce&&Ce.focus&&Ce.focus()},pt=(K,fe)=>Cs(K)?f.values.subscribe({next:W=>K(Q(void 0,fe),W)}):Q(K,fe,!0),We=(K,fe={})=>{for(const W of K?tc(K):o.mount)o.mount.delete(W),o.array.delete(W),fe.keepValue||(Sr(n,W),Sr(i,W)),!fe.keepError&&Sr(r.errors,W),!fe.keepDirty&&Sr(r.dirtyFields,W),!fe.keepTouched&&Sr(r.touchedFields,W),!fe.keepIsValidating&&Sr(r.validatingFields,W),!t.shouldUnregister&&!fe.keepDefaultValue&&Sr(s,W);f.values.next({values:{...i}}),f.state.next({...r,...fe.keepDirty?{isDirty:F()}:{}}),!fe.keepIsValid&&w()},dt=({disabled:K,name:fe,field:W,fields:Ce,value:Ee})=>{if(Xn(K)&&a.mount||K){const be=K?void 0:xr(Ee)?_d(W?W._f:et(Ce,fe)._f):Ee;ar(i,fe,be),_(fe,be,!1,!1,!0)}},ft=(K,fe={})=>{let W=et(n,K);const Ce=Xn(fe.disabled)||Xn(e.disabled);return ar(n,K,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:K}},name:K,mount:!0,...fe}}),o.mount.add(K),W?dt({field:W,disabled:Xn(fe.disabled)?fe.disabled:e.disabled,name:K,value:fe.value}):k(K,!0,fe.value),{...Ce?{disabled:fe.disabled||e.disabled}:{},...t.progressive?{required:!!fe.required,min:Xa(fe.min),max:Xa(fe.max),minLength:Xa(fe.minLength),maxLength:Xa(fe.maxLength),pattern:Xa(fe.pattern)}:{},name:K,onChange:$,onBlur:$,ref:Ee=>{if(Ee){ft(K,fe),W=et(n,K);const be=xr(Ee.value)&&Ee.querySelectorAll&&Ee.querySelectorAll("input,select,textarea")[0]||Ee,Ve=ok(be),rt=W._f.refs||[];if(Ve?rt.find(ue=>ue===be):be===W._f.ref)return;ar(n,K,{_f:{...W._f,...Ve?{refs:[...rt.filter(Td),be,...Array.isArray(et(s,K))?[{}]:[]],ref:{type:be.type,name:K}}:{ref:be}}}),k(K,!1,void 0,be)}else W=et(n,K,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||fe.shouldUnregister)&&!(XA(o.array,K)&&a.action)&&o.unMount.add(K)}}},At=()=>t.shouldFocusError&&uo(n,le,o.mount),Le=K=>{Xn(K)&&(f.state.next({disabled:K}),uo(n,(fe,W)=>{const Ce=et(n,W);Ce&&(fe.disabled=Ce._f.disabled||K,Array.isArray(Ce._f.refs)&&Ce._f.refs.forEach(Ee=>{Ee.disabled=Ce._f.disabled||K}))},0,!1))},Ut=(K,fe)=>async W=>{let Ce;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let Ee=vn(i);if(f.state.next({isSubmitting:!0}),t.resolver){const{errors:be,values:Ve}=await V();r.errors=be,Ee=Ve}else await L(n);if(Sr(r.errors,"root"),tn(r.errors)){f.state.next({errors:{}});try{await K(Ee,W)}catch(be){Ce=be}}else fe&&await fe({...r.errors},W),At(),setTimeout(At);if(f.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:tn(r.errors)&&!Ce,submitCount:r.submitCount+1,errors:r.errors}),Ce)throw Ce},tt=(K,fe={})=>{et(n,K)&&(xr(fe.defaultValue)?ge(K,vn(et(s,K))):(ge(K,fe.defaultValue),ar(s,K,vn(fe.defaultValue))),fe.keepTouched||Sr(r.touchedFields,K),fe.keepDirty||(Sr(r.dirtyFields,K),r.isDirty=fe.defaultValue?F(K,vn(et(s,K))):F()),fe.keepError||(Sr(r.errors,K),d.isValid&&w()),f.state.next({...r}))},ct=(K,fe={})=>{const W=K?vn(K):s,Ce=vn(W),Ee=tn(K),be=Ee?s:Ce;if(fe.keepDefaultValues||(s=W),!fe.keepValues){if(fe.keepDirtyValues){const Ve=new Set([...o.mount,...Object.keys(Qa(s,i))]);for(const rt of Array.from(Ve))et(r.dirtyFields,rt)?ar(be,rt,et(i,rt)):ge(rt,et(be,rt))}else{if(Zh&&xr(K))for(const Ve of o.mount){const rt=et(n,Ve);if(rt&&rt._f){const ue=Array.isArray(rt._f.refs)?rt._f.refs[0]:rt._f.ref;if(vc(ue)){const Se=ue.closest("form");if(Se){Se.reset();break}}}}n={}}i=e.shouldUnregister?fe.keepDefaultValues?vn(s):{}:vn(be),f.array.next({values:{...be}}),f.values.next({values:{...be}})}o={mount:fe.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!d.isValid||!!fe.keepIsValid||!!fe.keepDirtyValues,a.watch=!!e.shouldUnregister,f.state.next({submitCount:fe.keepSubmitCount?r.submitCount:0,isDirty:Ee?!1:fe.keepDirty?r.isDirty:!!(fe.keepDefaultValues&&!$s(K,s)),isSubmitted:fe.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Ee?{}:fe.keepDirtyValues?fe.keepDefaultValues&&i?Qa(s,i):r.dirtyFields:fe.keepDefaultValues&&K?Qa(s,K):fe.keepDirty?r.dirtyFields:{},touchedFields:fe.keepTouched?r.touchedFields:{},errors:fe.keepErrors?r.errors:{},isSubmitSuccessful:fe.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},ht=(K,fe)=>ct(Cs(K)?K(i):K,fe);return{control:{register:ft,unregister:We,getFieldState:ye,handleSubmit:Ut,setError:Qe,_executeSchema:V,_getWatch:Q,_getDirty:F,_updateV
2alid:w,_removeUnmounted:H,_updateFieldArray:C,_updateDisabledField:dt,_getFieldArray:J,_reset:ct,_resetDefaultValues:()=>Cs(t.defaultValues)&&t.defaultValues().then(K=>{ht(K,t.resetOptions),f.state.next({isLoading:!1})}),_updateFormState:K=>{r={...r,...K}},_disableForm:Le,_subjects:f,_proxyFormState:d,_setErrors:I,get _fields(){return n},get _formValues(){return i},get _state(){return a},set _state(K){a=K},get _defaultValues(){return s},get _names(){return o},set _names(K){o=K},get _formState(){return r},set _formState(K){r=K},get _options(){return t},set _options(K){t={...t,...K}}},trigger:B,register:ft,handleSubmit:Ut,watch:pt,setValue:ge,getValues:Te,reset:ht,resetField:tt,clearErrors:U,unregister:We,setError:Qe,setFocus:(K,fe={})=>{const W=et(n,K),Ce=W&&W._f;if(Ce){const Ee=Ce.refs?Ce.refs[0]:Ce.ref;Ee.focus&&(Ee.focus(),fe.shouldSelect&&Ee.select())}},getFieldState:ye}}function mk(e={}){const t=_e.useRef(),r=_e.useRef(),[n,s]=_e.useState({isDirty:!1,isValidating:!1,isLoading:Cs(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:Cs(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...pk(e),formState:n});const i=t.current.control;return i._options=e,tk({subject:i._subjects.state,next:a=>{ek(a,i._proxyFormState,i._updateFormState)&&s({...i._formState})}}),_e.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),_e.useEffect(()=>{if(i._proxyFormState.isDirty){const a=i._getDirty();a!==n.isDirty&&i._subjects.state.next({isDirty:a})}},[i,n.isDirty]),_e.useEffect(()=>{e.values&&!$s(e.values,r.current)?(i._reset(e.values,i._options.resetOptions),r.current=e.values,s(a=>({...a}))):i._resetDefaultValues()},[e.values,i]),_e.useEffect(()=>{e.errors&&i._setErrors(e.errors)},[e.errors,i]),_e.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),_e.useEffect(()=>{e.shouldUnregister&&i._subjects.values.next({values:i._getWatch()})},[e.shouldUnregister,i]),_e.useEffect(()=>{t.current&&(t.current.watch=t.current.watch.bind({}))},[n]),t.current.formState=ZA(n,i),t.current}var np="Progress",sp=100,[gk,HH]=Vo(np),[yk,vk]=gk(np),kb=N.forwardRef((e,t)=>{const{__scopeProgress:r,value:n=null,max:s,getValueLabel:i=xk,...a}=e;(s||s===0)&&!Bg(s)&&console.error(bk(`${s}`,"Progress"));const o=Bg(s)?s:sp;n!==null&&!Dg(n,o)&&console.error(wk(`${n}`,"Progress"));const l=Dg(n,o)?n:null,c=wc(l)?i(l,o):void 0;return u.jsx(yk,{scope:r,value:l,max:o,children:u.jsx(Lr.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":wc(l)?l:void 0,"aria-valuetext":c,role:"progressbar","data-state":Pb(l,o),"data-value":l??void 0,"data-max":o,...a,ref:t})})});kb.displayName=np;var Nb="ProgressIndicator",Rb=N.forwardRef((e,t)=>{const{__scopeProgress:r,...n}=e,s=vk(Nb,r);return u.jsx(Lr.div,{"data-state":Pb(s.value,s.max),"data-value":s.value??void 0,"data-max":s.max,...n,ref:t})});Rb.displayName=Nb;function xk(e,t){return`${Math.round(e/t*100)}%`}function Pb(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function wc(e){return typeof e=="number"}function Bg(e){return wc(e)&&!isNaN(e)&&e>0}function Dg(e,t){return wc(e)&&!isNaN(e)&&e<=t&&e>=0}function bk(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${sp}\`.`}function wk(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be:
3  - a positive number
4  - less than the value passed to \`max\` (or ${sp} if no \`max\` prop is set)
5  - \`null\` or \`undefined\` if the progress is indeterminate.
6
7Defaulting to \`null\`.`}var jb=kb,Ck=Rb;const ip=N.forwardRef(({className:e,value:t,...r},n)=>u.jsx(jb,{ref:n,className:ze("relative h-4 w-full overflow-hidden rounded-full bg-secondary",e),...r,children:u.jsx(Ck,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));ip.displayName=jb.displayName;var nc={linear:function(e,t,r,n){var s=r-t;return s*e/n+t},easeInQuad:function(e,t,r,n){var s=r-t;return s*(e/=n)*e+t},easeOutQuad:function(e,t,r,n){var s=r-t;return-s*(e/=n)*(e-2)+t},easeInOutQuad:function(e,t,r,n){var s=r-t;return(e/=n/2)<1?s/2*e*e+t:-s/2*(--e*(e-2)-1)+t},easeInCubic:function(e,t,r,n){var s=r-t;return s*(e/=n)*e*e+t},easeOutCubic:function(e,t,r,n){var s=r-t;return s*((e=e/n-1)*e*e+1)+t},easeInOutCubic:function(e,t,r,n){var s=r-t;return(e/=n/2)<1?s/2*e*e*e+t:s/2*((e-=2)*e*e+2)+t},easeInQuart:function(e,t,r,n){var s=r-t;return s*(e/=n)*e*e*e+t},easeOutQuart:function(e,t,r,n){var s=r-t;return-s*((e=e/n-1)*e*e*e-1)+t},easeInOutQuart:function(e,t,r,n){var s=r-t;return(e/=n/2)<1?s/2*e*e*e*e+t:-s/2*((e-=2)*e*e*e-2)+t},easeInQuint:function(e,t,r,n){var s=r-t;return s*(e/=n)*e*e*e*e+t},easeOutQuint:function(e,t,r,n){var s=r-t;return s*((e=e/n-1)*e*e*e*e+1)+t},easeInOutQuint:function(e,t,r,n){var s=r-t;return(e/=n/2)<1?s/2*e*e*e*e*e+t:s/2*((e-=2)*e*e*e*e+2)+t},easeInSine:function(e,t,r,n){var s=r-t;return-s*Math.cos(e/n*(Math.PI/2))+s+t},easeOutSine:function(e,t,r,n){var s=r-t;return s*Math.sin(e/n*(Math.PI/2))+t},easeInOutSine:function(e,t,r,n){var s=r-t;return-s/2*(Math.cos(Math.PI*e/n)-1)+t},easeInExpo:function(e,t,r,n){var s=r-t;return e==0?t:s*Math.pow(2,10*(e/n-1))+t},easeOutExpo:function(e,t,r,n){var s=r-t;return e==n?t+s:s*(-Math.pow(2,-10*e/n)+1)+t},easeInOutExpo:function(e,t,r,n){var s=r-t;return e===0?t:e===n?t+s:(e/=n/2)<1?s/2*Math.pow(2,10*(e-1))+t:s/2*(-Math.pow(2,-10*--e)+2)+t},easeInCirc:function(e,t,r,n){var s=r-t;return-s*(Math.sqrt(1-(e/=n)*e)-1)+t},easeOutCirc:function(e,t,r,n){var s=r-t;return s*Math.sqrt(1-(e=e/n-1)*e)+t},easeInOutCirc:function(e,t,r,n){var s=r-t;return(e/=n/2)<1?-s/2*(Math.sqrt(1-e*e)-1)+t:s/2*(Math.sqrt(1-(e-=2)*e)+1)+t},easeInElastic:function(e,t,r,n){var s=r-t,i,a,o;return o=1.70158,a=0,i=s,e===0?t:(e/=n)===1?t+s:(a||(a=n*.3),i<Math.abs(s)?(i=s,o=a/4):o=a/(2*Math.PI)*Math.asin(s/i),-(i*Math.pow(2,10*(e-=1))*Math.sin((e*n-o)*(2*Math.PI)/a))+t)},easeOutElastic:function(e,t,r,n){var s=r-t,i,a,o;return o=1.70158,a=0,i=s,e===0?t:(e/=n)===1?t+s:(a||(a=n*.3),i<Math.abs(s)?(i=s,o=a/4):o=a/(2*Math.PI)*Math.asin(s/i),i*Math.pow(2,-10*e)*Math.sin((e*n-o)*(2*Math.PI)/a)+s+t)},easeInOutElastic:function(e,t,r,n){var s=r-t,i,a,o;return o=1.70158,a=0,i=s,e===0?t:(e/=n/2)===2?t+s:(a||(a=n*(.3*1.5)),i<Math.abs(s)?(i=s,o=a/4):o=a/(2*Math.PI)*Math.asin(s/i),e<1?-.5*(i*Math.pow(2,10*(e-=1))*Math.sin((e*n-o)*(2*Math.PI)/a))+t:i*Math.pow(2,-10*(e-=1))*Math.sin((e*n-o)*(2*Math.PI)/a)*.5+s+t)},easeInBack:function(e,t,r,n,s){var i=r-t;return s===void 0&&(s=1.70158),i*(e/=n)*e*((s+1)*e-s)+t},easeOutBack:function(e,t,r,n,s){var i=r-t;return s===void 0&&(s=1.70158),i*((e=e/n-1)*e*((s+1)*e+s)+1)+t},easeInOutBack:function(e,t,r,n,s){var i=r-t;return s===void 0&&(s=1.70158),(e/=n/2)<1?i/2*(e*e*(((s*=1.525)+1)*e-s))+t:i/2*((e-=2)*e*(((s*=1.525)+1)*e+s)+2)+t},easeInBounce:function(e,t,r,n){var s=r-t,i;return i=nc.easeOutBounce(n-e,0,s,n),s-i+t},easeOutBounce:function(e,t,r,n){var s=r-t;return(e/=n)<1/2.75?s*(7.5625*e*e)+t:e<2/2.75?s*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?s*(7.5625*(e-=2.25/2.75)*e+.9375)+t:s*(7.5625*(e-=2.625/2.75)*e+.984375)+t},easeInOutBounce:function(e,t,r,n){var s=r-t,i;return e<n/2?(i=nc.easeInBounce(e*2,0,s,n),i*.5+t):(i=nc.easeOutBounce(e*2-n,0,s,n),i*.5+s*.5+t)}},Sk=nc;function Ek(e){return e*Math.PI/180}function hn(e,t){return e+Math.random()*(t-e)}function Tk(e,t){return Math.floor(e+Math.random()*(t-e+1))}var fo;(function(e){e[e.Circle=0]="Circle",e[e.Square=1]="Square",e[e.Strip=2]="Strip"})(fo||(fo={}));var Us;(function(e){e[e.Positive=1]="Positive",e[e.Negative=-1]="Negative"})(Us||(Us={}));class _k{constructor(t,r,n,s){this.getOptions=r;const{colors:i,initialVelocityX:a,initialVelocityY:o}=this.getOptions();this.context=t,this.x=n,this.y=s,this.w=hn(5,20),this.h=hn(5,20),this.radius=hn(5,10),this.vx=typeof a=="number"?hn(-a,a):hn(a.min,a.max),this.vy=typeof o=="number"?hn(-o,0
7):hn(o.min,o.max),this.shape=Tk(0,2),this.angle=Ek(hn(0,360)),this.angularSpin=hn(-.2,.2),this.color=i[Math.floor(Math.random()*i.length)],this.rotateY=hn(0,1),this.rotationDirection=hn(0,1)?Us.Positive:Us.Negative}update(){const{gravity:t,wind:r,friction:n,opacity:s,drawShape:i}=this.getOptions();this.x+=this.vx,this.y+=this.vy,this.vy+=t,this.vx+=r,this.vx*=n,this.vy*=n,this.rotateY>=1&&this.rotationDirection===Us.Positive?this.rotationDirection=Us.Negative:this.rotateY<=-1&&this.rotationDirection===Us.Negative&&(this.rotationDirection=Us.Positive);const a=.1*this.rotationDirection;if(this.rotateY+=a,this.angle+=this.angularSpin,this.context.save(),this.context.translate(this.x,this.y),this.context.rotate(this.angle),this.context.scale(1,this.rotateY),this.context.rotate(this.angle),this.context.beginPath(),this.context.fillStyle=this.color,this.context.strokeStyle=this.color,this.context.globalAlpha=s,this.context.lineCap="round",this.context.lineWidth=2,i&&typeof i=="function")i.call(this,this.context);else switch(this.shape){case fo.Circle:{this.context.beginPath(),this.context.arc(0,0,this.radius,0,2*Math.PI),this.context.fill();break}case fo.Square:{this.context.fillRect(-this.w/2,-this.h/2,this.w,this.h);break}case fo.Strip:{this.context.fillRect(-this.w/6,-this.h/2,this.w/3,this.h);break}}this.context.closePath(),this.context.restore()}}class Ik{constructor(t,r){this.x=0,this.y=0,this.w=0,this.h=0,this.lastNumberOfPieces=0,this.tweenInitTime=Date.now(),this.particles=[],this.particlesGenerated=0,this.removeParticleAt=s=>{this.particles.splice(s,1)},this.getParticle=()=>{const s=hn(this.x,this.w+this.x),i=hn(this.y,this.h+this.y);return new _k(this.context,this.getOptions,s,i)},this.animate=()=>{const{canvas:s,context:i,particlesGenerated:a,lastNumberOfPieces:o}=this,{run:l,recycle:c,numberOfPieces:d,debug:f,tweenFunction:h,tweenDuration:m}=this.getOptions();if(!l)return!1;const g=this.particles.length,v=c?g:a,w=Date.now();if(v<d){o!==d&&(this.tweenInitTime=w,this.lastNumberOfPieces=d);const{tweenInitTime:b}=this,C=w-b>m?m:Math.max(0,w-b),T=h(C,v,d,m),I=Math.round(T-v);for(let k=0;k<I;k++)this.particles.push(this.getParticle());this.particlesGenerated+=I}return f&&(i.font="12px sans-serif",i.fillStyle="#333",i.textAlign="right",i.fillText(`Particles: ${g}`,s.width-10,s.height-20)),this.particles.forEach((b,C)=>{b.update(),(b.y>s.height||b.y<-100||b.x>s.width+100||b.x<-100)&&(c&&v<=d?this.particles[C]=this.getParticle():this.removeParticleAt(C))}),g>0||v<d},this.canvas=t;const n=this.canvas.getContext("2d");if(!n)throw new Error("Could not get canvas context");this.context=n,this.getOptions=r}}const ap={width:typeof window<"u"?window.innerWidth:300,height:typeof window<"u"?window.innerHeight:200,numberOfPieces:200,friction:.99,wind:0,gravity:.1,initialVelocityX:4,initialVelocityY:10,colors:["#f44336","#e91e63","#9c27b0","#673ab7","#3f51b5","#2196f3","#03a9f4","#00bcd4","#009688","#4CAF50","#8BC34A","#CDDC39","#FFEB3B","#FFC107","#FF9800","#FF5722","#795548"],opacity:1,debug:!1,tweenFunction:Sk.easeInOutQuad,tweenDuration:5e3,recycle:!0,run:!0};class Ak{constructor(t,r){this.lastFrameTime=Date.now(),this.setOptionsWithDefaults=s=>{const i={confettiSource:{x:0,y:0,w:this.canvas.width,h:0}};this._options={...i,...ap,...s},Object.assign(this,s.confettiSource)},this.update=()=>{const{options:{run:s,onConfettiComplete:i,frameRate:a},canvas:o,context:l}=this;if(a){const c=Date.now(),d=c-this.lastFrameTime;if(d<1e3/a){this.rafId=requestAnimationFrame(this.update);return}this.lastFrameTime=c-d%a}s&&(l.fillStyle="white",l.clearRect(0,0,o.width,o.height)),this.generator.animate()?this.rafId=requestAnimationFrame(this.update):(i&&typeof i=="function"&&this.generator.particlesGenerated>0&&i.call(this,this),this._options.run=!1)},this.reset=()=>{this.generator&&this.generator.particlesGenerated>0&&(this.generator.particlesGenerated=0,this.generator.particles=[],this.generator.lastNumberOfPieces=0)},this.stop=()=>{this.options={run:!1},this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=void 0)},this.canvas=t;const n=this.canvas.getContext("2d");if(!n)throw new Error("Could not get canvas context");this.context=n,this.generator=new Ik(this.canvas,()=>this.options),this.options=r,this.update()}get options(){return this._options}set options(t){const r=this._options?.run,n=this._options?.recycle;this.setOptionsWithDefaults(t),this.generator&&(Object.assign(this.generator,this.options.confettiSource),typeof t.recycle=="boolean"&&t.recycle&&n===!1&&(this.generator.lastNumberOfPieces=this.generator.particles.length)),typeof t.run=="boolean"&&t.run&&r===!1&&this.update()}}const kk=_e.createRef();class op extends _e.Component{constructor(t){super(t),this.canvas=_e.createRef(),this.canvas=t.canvasRef||kk}componentDidMount(){if(this.canvas.current){const t=Id(this.props)[0];this.confetti=new Ak(this.canvas.current,t)}}componentDidUpdate(){const t=Id(this.props)[0];
7this.confetti&&(this.confetti.options=t)}componentWillUnmount(){this.confetti&&this.confetti.stop(),this.confetti=void 0}render(){const[t,r]=Id(this.props),n={zIndex:2,position:"absolute",pointerEvents:"none",top:0,left:0,bottom:0,right:0,...r.style};return u.jsx("canvas",{width:t.width,height:t.height,ref:this.canvas,...r,style:n})}}op.defaultProps={...ap};op.displayName="ReactConfetti";function Id(e){const t={},r={},n={},s=[...Object.keys(ap),"confettiSource","drawShape","onConfettiComplete","frameRate"],i=["canvasRef"];for(const a in e){const o=e[a];s.includes(a)?t[a]=o:i.includes(a)?i[a]=o:n[a]=o}return[t,n,r]}const Bb=_e.forwardRef((e,t)=>u.jsx(op,{canvasRef:t,...e})),Nk=({progress:e,deploymentStatus:t,onComplete:r})=>{const n=Sa(),[s,i]=N.useState(!1);return N.useEffect(()=>{e>=100&&(i(!0),r())},[e,r]),s?u.jsxs("div",{className:"fixed inset-0 flex items-center justify-center bg-background/95",children:[u.jsx(Bb,{width:window.innerWidth,height:window.innerHeight,recycle:!1,numberOfPieces:500,gravity:.2}),u.jsxs("div",{className:"text-center z-10",children:[u.jsx("h3",{className:"text-2xl font-bold mb-4",children:"🎉 Congratulations!"}),u.jsx("p",{className:"mb-6",children:"Your Bitcoin Secured Agent is deployed"}),u.jsx(yt,{onClick:()=>n("/my-agents"),className:"w-48",children:"Go to My Agents"})]})]}):u.jsxs("div",{className:"min-h-screen flex flex-col items-center justify-center",children:[u.jsx("img",{src:"/uploads/ce03328c-face-4f4b-a572-ac58a0a494b1.png",alt:"Deployment Animation",className:"w-48 h-48 mb-8 animate-pulse"}),u.jsxs("div",{className:"w-full max-w-md",children:[u.jsx(ip,{value:e,className:"h-2"}),u.jsx("p",{className:"text-sm text-muted-foreground mt-2 text-center",children:t})]})]})};var lp="Radio",[Rk,Db]=Vo(lp),[Pk,lu]=Rk(lp);
7function Lb(e){const{__scopeRadio:t,checked:r=!1,children:n,disabled:s,form:i,name:a,onCheck:o,required:l,value:c="on",internal_do_not_use_render:d}=e,[f,h]=N.useState(null),[m,g]=N.useState(null),v=N.useRef(!1),w=f?!!i||!!f.closest("form"):!0,b={checked:r,disabled:s,required:l,name:a,form:i,value:c,control:f,setControl:h,hasConsumerStoppedPropagationRef:v,isFormControl:w,bubbleInput:m,setBubbleInput:g,onCheck:()=>o?.()};return u.jsx(Pk,{scope:t,...b,children:Bk(d)?d(b):n})}var Mb="RadioTrigger",cp=N.forwardRef(({__scopeRadio:e,onClick:t,...r},n)=>{const{checked:s,disabled:i,value:a,setControl:o,onCheck:l,hasConsumerStoppedPropagationRef:c,isFormControl:d,bubbleInput:f}=lu(Mb,e),h=on(n,o);return u.jsx(Lr.button,{type:"button",role:"radio","aria-checked":s,"data-state":Vb(s),"data-disabled":i?"":void 0,disabled:i,value:a,...r,ref:h,onClick:Rt(t,m=>{s||l(),f&&d&&(c.current=m.isPropagationStopped(),c.current||m.stopPropagation())})})});cp.displayName=Mb;var jk=N.forwardRef((e,t)=>{const{__scopeRadio:r,name:n,checked:s,required:i,disabled:a,value:o,onCheck:l,form:c,...d}=e;return u.jsx(Lb,{__scopeRadio:r,checked:s,disabled:a,required:i,onCheck:l,name:n,form:c,value:o,internal_do_not_use_render:({isFormControl:f})=>u.jsxs(u.Fragment,{children:[u.jsx(cp,{...d,ref:t,__scopeRadio:r}),f&&u.jsx(up,{__scopeRadio:r})]})})});jk.displayName=lp;var Ob="RadioIndicator",Fb=N.forwardRef((e,t)=>{const{__scopeRadio:r,forceMount:n,...s}=e,i=lu(Ob,r);return u.jsx(Vh,{present:n||i.checked,children:u.jsx(Lr.span,{"data-state":Vb(i.checked),"data-disabled":i.disabled?"":void 0,...s,ref:t})})});Fb.displayName=Ob;var Ub="RadioBubbleInput",up=N.forwardRef(({__scopeRadio:e,...t},r)=>{const{control:n,checked:s,required:i,disabled:a,name:o,value:l,form:c,bubbleInput:d,setBubbleInput:f,hasConsumerStoppedPropagationRef:h}=lu(Ub,e),m=on(r,f),g=cx(s),v=ux(n);N.useEffect(()=>{const b=d;if(!b)return;const C=window.HTMLInputElement.prototype,I=Object.getOwnPropertyDescriptor(C,"checked").set,k=!h.current;if(g!==s&&I){const _=new Event("click",{bubbles:k});I.call(b,s),b.dispatchEvent(_)}},[d,g,s,h]);const w=N.useRef(s);return u.jsx(Lr.input,{type:"radio","aria-hidden":!0,defaultChecked:w.current,required:i,disabled:a,name:o,value:l,form:c,...t,tabIndex:-1,ref:m,style:{...t.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});up.displayName=Ub;function Bk(e){return typeof e=="function"}function Vb(e){return e?"checked":"unchecked"}var Dk=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],cu="RadioGroup",[Lk,GH]=Vo(cu,[dx,Db]),$b=dx(),uu=Db(),[Mk,Ok]=Lk(cu),dp=N.forwardRef((e,t)=>{const{__scopeRadioGroup:r,name:n,form:s,defaultValue:i,value:a,required:o=!1,disabled:l=!1,orientation:c,dir:d,loop:f=!0,onValueChange:h,...m}=e,g=$b(r),v=_T(d),[w,b]=Uh({prop:a,defaultProp:i??null,onChange:h,caller:cu}),[C,T]=N.useState(null),I=on(t,T),k=N.useRef(w);return N.useEffect(()=>{const _=s?C?.ownerDocument.getElementById(s):C?.closest("form");if(_ instanceof HTMLFormElement){const M=()=>b(k.current);return _.addEventListener("reset",M),()=>_.removeEventListener("reset",M)}},[C,s,b]),u.jsx(Mk,{scope:r,name:n,form:s,required:o,disabled:l,value:w,onValueChange:b,children:u.jsx(IT,{asChild:!0,...g,orientation:c,dir:v,loop:f,children:u.jsx(Lr.div,{role:"radiogroup","aria-required":o,"aria-orientation":c,"data-disabled":l?"":void 0,dir:v,...m,ref:I})})})});dp.displayName=cu;var Fk="RadioGroupItem",Uk="RadioGroupItemProvider",zb="RadioGroupItemTrigger",Vk="RadioGroupItemBubbleInput";function $k(e){const{__scopeRadioGroup:t,value:r,disabled:n,children:s,internal_do_not_use_render:i}=e,a=Ok(Uk,t),o=uu(t),l=a.disabled||n;return u.jsx(Lb,{...o,checked:a.value===r,disabled:l,required:a.required,name:a.name,form:a.form,value:r,onCheck:()=>a.onValueChange(r),internal_do_not_use_render:i,children:s})}var Kb=N.forwardRef((e,t)=>{const{__scopeRadioGroup:r,...n}=e,s=$b(r),i=uu(r),{checked:a,disabled:o}=lu(zb,i.__scopeRadio),l=N.useRef(null),c=on(t,l),d=N.useRef(!1);return N.useEffect(()=>{const f=m=>{Dk.includes(m.key)&&(d.current=!0)},h=()=>d.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",h),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",h)}},[]),u.jsx(AT,{asChild:!0,...s,focusable:!o,active:a,children:u.jsx(cp,{...i,...n,ref:c,onKeyDown:Rt(n.onKeyDown,f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:Rt(n.onFocus,()=>{d.current&&l.current?.click()})})})});Kb.displayName=zb;var fp=N.forwardRef((e,t)=>
7{const{__scopeRadioGroup:r,value:n,disabled:s,...i}=e;return u.jsx($k,{__scopeRadioGroup:r,value:n,disabled:s,internal_do_not_use_render:({isFormControl:a})=>u.jsxs(u.Fragment,{children:[u.jsx(Kb,{...i,ref:t,__scopeRadioGroup:r}),a&&u.jsx(qb,{__scopeRadioGroup:r})]})})});fp.displayName=Fk;var qb=N.forwardRef((e,t)=>{const{__scopeRadioGroup:r,...n}=e,s=uu(r);return u.jsx(up,{...s,...n,ref:t})});qb.displayName=Vk;var zk="RadioGroupIndicator",Hb=N.forwardRef((e,t)=>{const{__scopeRadioGroup:r,...n}=e,s=uu(r);return u.jsx(Fb,{...s,...n,ref:t})});Hb.displayName=zk;const sc=N.forwardRef(({className:e,...t},r)=>u.jsx(dp,{className:ze("grid gap-2",e),...t,ref:r}));sc.displayName=dp.displayName;const na=N.forwardRef(({className:e,...t},r)=>u.jsx(fp,{ref:r,className:ze("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:u.jsx(Hb,{className:"flex items-center justify-center",children:u.jsx(xx,{className:"h-2.5 w-2.5 fill-current text-current"})})}));na.displayName=fp.displayName;var Kk="Label",Gb=N.forwardRef((e,t)=>u.jsx(Lr.label,{...e,ref:t,onMouseDown:r=>{r.target.closest("button, input, select, textarea")||(e.onMouseDown?.(r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));Gb.displayName=Kk;var Wb=Gb;const qk=Ea("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),hr=N.forwardRef(({className:e,...t},r)=>u.jsx(Wb,{ref:r,className:ze(qk(),e),...t}));hr.displayName=Wb.displayName;const Lg=BT,Mg=DT,Mf=N.forwardRef(({className:e,children:t,...r},n)=>u.jsxs(fx,{ref:n,className:ze("flex h-10 w-full items-center justify-between rounded-lg border border-white/10 bg-red px-3 py-2 text-sm r
7ing-offset-background placeholder:text-muted-foreground hover:bg-white/[0.04] focus:outline-none focus:ring-2 focus:ring-[#98fe00]/20 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...r,children:[t,u.jsx(kT,{asChild:!0,children:u.jsx(ri,{className:"h-4 w-4 opacity-50"})})]}));Mf.displayName=fx.displayName;const Yb=N.forwardRef(({className:e,...t},r)=>u.jsx(hx,{ref:r,className:ze("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(zh,{className:"h-4 w-4"})}));Yb.displayName=hx.displayName;const Qb=N.forwardRef(({className:e,...t},r)=>u.jsx(px,{ref:r,className:ze("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ri,{className:"h-4 w-4"})}));Qb.displayName=px.displayName;const Of=N.forwardRef(({className:e,children:t,position:r="popper",...n},s)=>u.jsx(NT,{children:u.jsxs(mx,{ref:s,className:ze("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-lg border border-white/10 bg-black text-popover-foreground shadow-md backdrop-blur-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...n,children:[u.jsx(Yb,{}),u.jsx(RT,{className:ze("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(Qb,{})]})}));Of.displayName=mx.displayName;const Hk=N.forwardRef(({className:e,...t},r)=>u.jsx(gx,{ref:r,className:ze("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Hk.displayName=gx.displayName;const so=N.forwardRef(({className:e,children:t,...r},n)=>u.jsxs(yx,{ref:n,className:ze("relative flex w-full cursor-default select-none items-center rounded-md py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-[black]/10 focus:text-[black] data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(PT,{children:u.jsx(jr,{className:"h-4 w-4"})})}),u.jsx(jT,{children:t})]}));so.displayName=yx.displayName;const Gk=N.forwardRef(({className:e,...t},r)=>u.jsx(vx,{ref:r,className:ze("-mx-1 my-1 h-px bg-muted",e),...t}));Gk.displayName=vx.displayName;var du="Checkbox",[Wk,WH]=Vo(du),[Yk,hp]=Wk(du);function Qk(e){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:s,disabled:i,form:a,name:o,onCheckedChange:l,required:c,value:d="on",internal_do_not_use_render:f}=e,[h,m]=Uh({prop:r,defaultProp:s??!1,onChange:l,caller:du}),[g,v]=N.useState(null),[w,b]=N.useState(null),C=N.useRef(!1),T=g?!!a||!!g.closest("form"):!0,I={checked:h,disabled:i,setChecked:m,control:g,setControl:v,name:o,form:a,value:d,hasConsumerStoppedPropagationRef:C,required:c,defaultChecked:Xs(s)?!1:s,isFormControl:T,bubbleInput:w,setBubbleInput:b};return u.jsx(Yk,{scope:t,...I,children:Xk(f)?f(I):n})}var Xb="CheckboxTrigger",Jb=N.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:r,...n},s)=>{const{control:i,value:a,disabled:o,checked:l,required:c,setControl:d,setChecked:f,hasConsumerStoppedPropagationRef:h,isFormControl:m,bubbleInput:g}=hp(Xb,e),v=on(s,d),w=N.useRef(l);return N.useEffect(()=>{const b=i?.form;if(b){const C=()=>f(w.current);return b.addEventListener("reset",C),()=>b.removeEventListener("reset",C)}},[i,f]),u.jsx(Lr.button,{type:"button",role:"checkbox","aria-checked":Xs(l)?"mixed":l,"aria-required":c,"data-state":n1(l),"data-disabled":o?"":void 0,disabled:o,value:a,...n,ref:v,onKeyDown:Rt(t,b=>{b.key==="Enter"&&b.preventDefault()}),onClick:Rt(r,b=>{f(C=>Xs(C)?!0:!C),g&&m&&(h.current=b.isPropagationStopped(),h.current||b.stopPropagation())})})});Jb.displayName=Xb;var pp=N.forwardRef((e,t)=>{const{__scopeCheckbox:r,name:n,checked:s,defaultChecked:i,required:a,disabled:o,value:l,onCheckedChange:c,form:d,...f}=e;return u.jsx(Qk,{__scopeCheckbox:r,checked:s,defaultChecked:i,disabled:o,required:a,onCheckedChange:c,name:n,form:d,value:l,internal_do_not_use_render:({isFormControl:h})=>u.jsxs(u.Fragment,{children:[u.jsx(Jb,{...f,ref:t,__scopeCheckbox:r}),h&&u.jsx(r1,{__scopeCheckbox:r})]})})});pp.displayName=du;var Zb="CheckboxIndicator",e1=N.forwardRef((e,t)=>
7{const{__scopeCheckbox:r,forceMount:n,...s}=e,i=hp(Zb,r);return u.jsx(Vh,{present:n||Xs(i.checked)||i.checked===!0,children:u.jsx(Lr.span,{"data-state":n1(i.checked),"data-disabled":i.disabled?"":void 0,...s,ref:t,style:{pointerEvents:"none",...e.style}})})});e1.displayName=Zb;var t1="CheckboxBubbleInput",r1=N.forwardRef(({__scopeCheckbox:e,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:s,checked:i,defaultChecked:a,required:o,disabled:l,name:c,value:d,form:f,bubbleInput:h,setBubbleInput:m}=hp(t1,e),g=on(r,m),v=cx(i),w=ux(n);N.useEffect(()=>{const C=h;if(!C)return;const T=window.HTMLInputElement.prototype,k=Object.getOwnPropertyDescriptor(T,"checked").set,_=!s.current;if(v!==i&&k){const M=new Event("click",{bubbles:_});C.indeterminate=Xs(i),k.call(C,Xs(i)?!1:i),C.dispatchEvent(M)}},[h,v,i,s]);const b=N.useRef(Xs(i)?!1:i);return u.jsx(Lr.input,{type:"checkbox","aria-hidden":!0,defaultChecked:a??b.current,required:o,disabled:l,name:c,value:d,form:f,...t,tabIndex:-1,ref:g,style:{...t.style,...w,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});r1.displayName=t1;function Xk(e){return typeof e=="function"}function Xs(e){return e==="indeterminate"}function n1(e){return Xs(e)?"indeterminate":e?"checked":"unchecked"}const ic=N.forwardRef(({className:e,...t},r)=>u.jsx(pp,{ref:r,className:ze("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",e),...t,children:u.jsx(e1,{className:ze("flex items-center justify-center text-current"),children:u.jsx(jr,{className:"h-4 w-4"})})}));ic.displayName=pp.displayName;const rn=N.forwardRef(({className:e,type:t,...r},n)=>u.jsx("input",{type:t,className:ze("flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[#98fe00]/50 focus-visible:border-[#98fe00]/30 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-600 disabled:border-gray-200 transition-colors",e),ref:n,...r}));rn.displayName="Input";const Jk=Ea("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),s1=N.forwardRef(({className:e,variant:t,...r},n)=>u.jsx("div",{ref:n,role:"alert",className:ze(Jk({variant:t}),e),...r}));s1.displayName="Alert";const Zk=N.forwardRef(({className:e,...t},r)=>u.jsx("h5",{ref:r,className:ze("mb-1 font-medium leading-none tracking-tight",e),...t}));Zk.displayName="AlertTitle";const i1=N.forwardRef(({className:e,...t},r)=>u.jsx("div",{ref:r,className:ze("text-sm [&_p]:leading-relaxed",e),...t}));i1.displayName="AlertDescription";const eN=({step:e,form:t,operators:r,agentType:n})=>{const{data:s}=b_({queryKey:["agentConfiguration",n],queryFn:async()=>{const{data:a,error:o}=await En.from("agent_configurations").select("*").eq("agent_type",n).single();if(o)throw o;return a}});return(()=>{switch(e){case 1:return n==="CEX_SPOT"||n==="CEX_LEVERAGE"?u.jsxs("div",{className:"space-y-4",children:[u.jsxs(s1,{children:[u.jsx($T,{className:"h-4 w-4"}),u.jsx(i1,{children:"Please create a new Binance sub-account and use its API key for better security."})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(hr,{htmlFor:"binanceApiKey",children:"Binance API Key"}),u.jsx(rn,{id:"binanceApiKey",type:"password",...t.register("binanceApiKey")})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(hr,{htmlFor:"binanceApiSecret",children:"Binance API Secret"}),u.jsx(rn,{id:"binanceApiSecret",type:"password",...t.register("binanceApiSecret")})]})]}):s?.chain_options?u.jsxs("div",{className:"space-y-4",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Select Blockchain"}),u.jsx(sc,{defaultValue:t.getValues("chain"),onValueChange:a=>t.setValue("chain",a),className:"space-y-2",children:s.chain_options.map(a=>u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(na,{value:a,id:a}),u.jsx(hr,{htmlFor:a,children:a})]},a))})]}):n==="SOCIAL"?u.jsxs("div",{className:"space-y-4",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Select Social Platforms"}),u.jsx("div",{className:"space-y-2",children:["TWITTER","FARCASTER","LENS","TELEGRAM","DISCORD"].map(a=>u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(ic,{id:a,onCheckedChange:o=>{const l=t.getValues("socialPlatforms")||[];o?t.setValue("socialPlatforms",[...l,a]):t.setValue("socialPlatforms",l.filter(c=>c!==a))}}),u.jsx("label",{htmlFor:a,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:a.charAt(0)+a.slice(1).toLowerCase()})]},a))})]}):null;case 2:return u.jsxs("div",{className:"space-y-4",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Select Environment"}),u.jsx("div",{className:"mb-4",children:u.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose your deployment environment and associated costs"})}),u.jsxs(sc,{defaultValue:t.getValues("environment"),onValueChange:a=>t.setValue("environment",a),className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(na,{value:"verifiable",id:"verifiable"}),u.jsx(hr,{htmlFor:"verifiable",children:"Verifiable (TEE) - $20/month"})]}),u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(na,{value:"non-verifiable",id:"non-verifiable"}),u.jsx(hr,{htmlFor:"non-verifiable",children:"Non-Verifiable - $10/month"})]})]})]});case 3:if(s?.dex_options&&s.chain_options){const a=t.getValues("chain"),o=a?s.dex_options[a]||[]:[];return n==="ARBITRAGE"?u.jsxs("div",{className:"space-y-4",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Select DEXs for Arbitrage"}
7),u.jsx("div",{className:"space-y-2",children:o.map(l=>u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(ic,{id:l,onCheckedChange:c=>{const d=t.getValues("dex")||[];c?t.setValue("dex",[...d,l]):t.setValue("dex",d.filter(f=>f!==l))}}),u.jsx("label",{htmlFor:l,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:l})]},l))})]}):u.jsxs("div",{className:"space-y-4",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Select DEX"}),u.jsxs(Lg,{onValueChange:l=>t.setValue("dex",l),children:[u.jsx(Mf,{children:u.jsx(Mg,{placeholder:"Select a DEX"})}),u.jsx(Of,{children:o.map(l=>u.jsx(so,{value:l,children:l},l))})]})]})}return null;case 4:return u.jsxs("div",{className:"space-y-4",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Select Operators"}),u.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"You can select multiple operators for better scalability"}),u.jsx("div",{className:"space-y-2",children:r.map(a=>u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(ic,{id:a,onCheckedChange:o=>{const l=t.getValues("operators")||[];o?t.setValue("operators",[...l,a]):t.setValue("operators",l.filter(c=>c!==a))}}),u.jsx("label",{htmlFor:a,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:a})]},a))})]});case 5:return u.jsxs("div",{className:"space-y-4",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"LLM Configuration"}),u.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Choose your LLM provider"}),u.jsxs(sc,{defaultValue:"slinky",onValueChange:a=>t.setValue("llmChoice",a),className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(na,{value:"slinky",id:"slinky-llm"}),u.jsx(hr,{htmlFor:"slinky-llm",children:"Use Slinky Layer Private LLM ($10 per 1M tokens)"})]}),u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(na,{value:"own",id:"own-llm"}),u.jsx(hr,{htmlFor:"own-llm",children:"Use Own API Key"})]})]}),t.getValues("llmChoice")==="own"&&u.jsxs("div",{className:"mt-4 space-y-4",children:[u.jsxs(Lg,{onValueChange:a=>t.setValue("llmProvider",a),defaultValue:"openai",children:[u.jsx(Mf,{children:u.jsx(Mg,{placeholder:"Select API Provider"})}),u.jsxs(Of,{children:[u.jsx(so,{value:"openai",children:"OpenAI"}),u.jsx(so,{value:"groq",children:"Groq"}),u.jsx(so,{value:"anthropic",children:"Anthropic"})]})]}),u.jsxs("div",{children:[u.jsx(hr,{htmlFor:"api-key",children:"API Key"}),u.jsx(rn,{type:"password",id:"api-key",className:"w-full mt-1",onChange:a=>t.setValue("llmApiKey",a.target.value)})]})]})]});default:return null}})()},tN=({basePrice:e,llmPrice:t,operators:r})=>{const n=r?.length||1,s=(t!==void 0?e+t:e)*n;return u.jsx("div",{className:"absolute top-4 right-[48px] bg-green-100 rounded-full px-3 py-1.5 shadow-sm border border-green-200",children:u.jsxs("span",{className:"text-sm font-semibold text-green-800",children:["$",s]})})},rN=({customAgentName:e,setCustomAgentName:t})=>u.jsxs("div",{className:"space-y-2",children:[u.jsx(hr,{htmlFor:"agentName",children:"Agent Name"}),u.jsx(rn,{id:"agentName",value:e,onChange:r=>t(r.target.value),placeholder:"Enter a name for your agent",className:"w-full"})]}),nN=(e,t,r)=>{const[n,s]=N.useState(0),[i,a]=N.useState("");return N.useEffect(()=>{let o;return e&&(o=setInterval(()=>{s(l=>{if(l>=100)return clearInterval(o),100;const c=Math.floor(Math.random()*15)+5,d=Math.min(l+c,100),f=Math.floor(l/100*t.length);return a(t[f]),d>=100&&(clearInterval(o),r&&r()),d})},1e3)),()=>{o&&clearInterval(o)}},[e,t]),{progress:n,deploymentStatus:i}},sN=({open:e,onOpenChange:t,agentName:r,walletAddress:n,agentType:s,onDeploy:i,onComplete:a})=>{const[o,l]=N.useState(1),[c,d]=N.useState(!1),[f,h]=N.useState(r),[m,g]=N.useState(!1),v=mk({defaultValues:{environment:"non-verifiable",llmChoice:"slinky",operators:[]}}),w=["Initiating memory chain...","Connecting to Slinky Layer...","Creating Bitcoin secured agent...","Configuring secure runtime environment...","Establishing operator connections...","Finalizing deployment..."],{progress:b,deploymentStatus:C}=nN(c,w,()=>{g(!0),a()}),T=()=>{const _=v.watch("environment")==="verifiable"?20:10,M=v.watch("llmChoice")==="slinky"?10:0,V=v.watch("operators")||[];return{basePrice:_,llmPrice:M,operators:V}},I=async()=>{d(!0);const{data:_}
7=await En.from("agent_configurations").select("id").eq("agent_type",s).single();if(!_)return;const M=v.getValues(),{error:V}=await En.from("deployed_agents").insert({user_id:n,config_id:_.id,name:f,status:"active",configuration:JSON.parse(JSON.stringify(M))});V||i()},k=s==="ANALYSIS"?5:6;return u.jsx(zo,{open:e,onOpenChange:_=>{m||t(_)},children:u.jsxs(_a,{className:"sm:max-w-[425px]",children:[u.jsxs(Ko,{children:[u.jsxs(qo,{children:["Deploy ",f]}),u.jsx(au,{children:c?"Setting up your agent. Please wait while we complete the process.":"Configure your agent deployment settings."})]}),c?u.jsx(Nk,{progress:b,deploymentStatus:C,onComplete:a}):u.jsxs("div",{className:"mt-4 space-y-4",children:[o===1&&u.jsx(rN,{customAgentName:f,setCustomAgentName:h}),o>1&&u.jsx(eN,{step:o-1,form:v,operators:["Animoca Brands","Phala Cloud","Validation Cloud","Everstake","P-OPS Team","HashKey Cloud"],agentType:s}),o>2&&u.jsx(tN,{...T()}),u.jsxs("div",{className:"flex justify-between mt-4",children:[u.jsx(yt,{variant:"outline",onClick:()=>l(_=>Math.max(1,_-1)),disabled:o===1,children:"Back"}),u.jsx(yt,{onClick:()=>{o<k?l(_=>_+1):I()},disabled:o===1&&!f.trim(),children:o===k?"Deploy":"Next"})]})]})]})})},iN=e=>({CEX_SPOT:"Advanced trading bot for centralized exchanges with real-time market analysis",CEX_LEVERAGE:"Specialized trading bot for margin trading on centralized exchanges",DEX_SPOT:"Decentralized exchange trading bot with cross-chain capabilities",DEX_LEVERAGE:"Decentralized margin trading bot with advanced risk management",ARBITRAGE:"Cross-exchange arbitrage opportunities finder and executor",ANALYSIS:"Advanced trading signal provider with no wallet connection required",SOCIAL:"Automated social media engagement and analytics"})[e]||"Intelligent agent with advanced capabilities",aN=e=>({DEX_SPOT:["Solana","Base","Aptos"],DEX_LEVERAGE:["Base","Movement"],ARBITRAGE:["Solana","Base","Movement"],CEX_SPOT:["Binance"],CEX_LEVERAGE:["Binance","Bybit"],ANALYSIS:["All Chains"],SOCIAL:["All Platforms"],ASSISTANT:["All Chains"]})[e]||["Ethereum"],oN=e=>!e||e.length<10?e||"0x000...000":`${e.substring(0,6)}...${e.substring(e.length-4)}`,lN=e=>{switch(e.toLowerCase()){case"ethereum":return u.jsx(ys,{className:"w-3 h-3 text-[#627EEA]"});case"solana":return u.jsx(ys,{className:"w-3 h-3 text-[#9945FF]"});case"base":return u.jsx(ys,{className:"w-3 h-3 text-[#0052FF]"});case"aptos":return u.jsx(ys,{className:"w-3 h-3 text-[#2CDFD2]"});case"movement":return u.jsx(ys,{className:"w-3 h-3 text-[#FF5CAA]"});case"binance":return u.jsx(ys,{className:"w-3 h-3 text-[#F0B90B]"});case"bybit":return u.jsx(ys,{className:"w-3 h-3 text-[#FCD535]"});case"all chains":case"all platforms":return u.jsx(ys,{className:"w-3 h-3 text-[#A8A8A8]"});default:return u.jsx(ys,{className:"w-3 h-3 text-[#A8A8A8]"})}},cN=({agent:e,walletAddress:t})=>{const{toast:r}=jn(),n=Sa(),[s,i]=N.useState(!1),[a,o]=N.useState(!1),l=e.description||iN(e.type),c=e.blockchains||aN(e.type),d=e.creator,f=e.status||"active",h=()=>{r({title:"Chat initiated",description:`Opening chat with ${e.name}`}),n(`/featured/${e.appId}-${e.id}/chat`)},m=()=>{e?.twitter?.username&&window.open(`https://twitter.com/${e?.twitter.username.toLowerCase()}`,"_blank")},g=()=>{e?.telegram?.username&&window.open(`https://t.me/${e?.telegram?.username.toLowerCase()}`,"_blank")};return u.jsxs("div",{className:"bg-[#151A29]/80 rounded-lg overflow-hidden h-full flex flex-col shadow-lg border border-white/10 transition-all duration-300 hover:shadow-xl hover:border-[#98fe00]/30",children:[s&&u.jsx(Bb,{recycle:!1,onConfettiComplete:()=>i(!1),style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",zIndex:1e3}}),u.jsxs("div",{className:"p-4 sm:p-6 flex-1 flex flex-col",children:[u.jsxs("div",{className:"flex items-start mb-4",children:[u.jsx("div",{className:"p-2 sm:p-3 bg-[#98fe00]/20 rounded-lg mr-3 sm:mr-4 shadow-inner self-center",children:u.jsx(nu,{className:"w-7 h-7 text-[#98fe00] drop-shadow-md animate-bounce-subtle"})}),u.jsx("div",{className:"flex-1 min-w-0",children:u.jsx("div",{className:"flex flex-wrap items-center justify-between gap-2",children:u.jsxs("div",{className:"flex-1 min-w-0 pr-2",children:[u.jsx("h3",{className:"text-lg sm:text-xl font-semibold text-white truncate",children:e.name==="Moonad_10143"?"Moonad":e.name==="molly_psyops_config"?"Molly":e.name}),u.jsx("div",{className:`mt-1 px-2 py-0.5 inline-block rounded-full text-xs font-medium ${f==="active"?"bg-green-500/20 text-green-400 border border-green-500/30":f==="inactive"?"bg-red-500/20 text-red-400 border border-red-500/30":"bg-yellow-500/20 text-yellow-400 border border-yellow-500/30"}`,children:f})]})})})]}),u.jsx("div",{className:"mb-4 sm:mb-6 bg-[black]/30 p-2 rounded-lg border border-[#242B3D]/50",children:u.jsx("p",{className:"text-gray-300 line-clamp-3 text-xs sm:text-sm",children:l})}),u.jsx("div",{className:"mb-4",children:u.jsxs("div",{className:"inline-flex space-x-2 bg-black/30 rounded-full px-3 py-1.5 border border-[#242B3D]/50",children:[u.jsx(yt,{variant:"ghost",size:"sm",className:"rounded-full h-7 w-7 p-0 text-[#98fe00] hover:text-white hover:bg-[#98fe00]/20 transition-colors duration-300 flex-shrink-0",onClick:m,title:"Visit on X (Twitter)",children:u.jsx(WA,{className:"w-3.5 h-3.5"})}),u.jsx(yt,{variant:"ghost",size:"sm",className:"rounded-full h-7 w-7 p-0 text-[#98fe00] hover:text-white hover:bg-[#98fe00]/20 transition-colors duration-300 flex-shrink-0",onClick:g,title:"Chat on Telegram",children:u.jsx(wx,{className:"w-3.5 h-3.5"})}),u.jsx(yt,{variant:"ghost",size:"sm",className:"rounded-full h-7 w-7 p-0 text-[#98fe00] hover:text-white hover:bg-[#98fe00]/20 transition-colors duration-300 flex-shrink-0",onClick:h,title:"Chat with Agent",children:u.jsx(zT,{className:"w-3.5 h-3.5"})})]})}),u.jsxs("div",{className:"space-y-2 sm:space-y-3 mt-auto",children:[u.jsxs("div",{className:"flex flex-wrap items-start gap-1",children:[u.jsx("span",{className:"text-gray-400 w-14 sm:w-20 text-xs sm:text-sm font-medium flex-shrink-0",children:"Chain:"}),u.jsx("div",{className:"flex flex-wrap gap-1",children:c.map((v,w)=>u.jsxs("span",{className:"bg-[black] text-xs py-0.5 sm:py-1 px-1.5 sm:px-2 rounded-full text-gray-300 border border-[#242B3D] flex items-center gap-1.5",children:[lN(v),u.jsx("span",{className:"text-xs hidden xs:inline",children:v})]},w))})]}),u.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[u.jsx("span",{className:"text-gray-400 w-14 sm:w-20 text-xs sm:text-sm font-medium flex-shrink-0",children:"Address:"}),u.jsx("span",{className:"font-mono text-gray-300 text-xs bg-[black]/30 px-2 py-0.5 
7sm:py-1 rounded-md truncate max-w-[140px] sm:max-w-none",children:oN(d)})]}),u.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[u.jsx("span",{className:"text-gray-400 w-14 sm:w-20 text-xs sm:text-sm font-medium flex-shrink-0",children:"Type:"}),u.jsx("span",{className:"bg-gradient-to-r from-[#98fe00]/30 to-[#98fe00]/10 text-[#98fe00] text-xs py-0.5 sm:py-1 px-2 sm:px-3 rounded-full font-medium border border-[#98fe00]/20",children:e.type.replace(/_/g," ")})]})]})]}),u.jsx(sN,{open:a,onOpenChange:o,agentName:e.name,walletAddress:t,agentType:e.type,onDeploy:()=>{},onComplete:()=>i(!0)})]})},uN=()=>u.jsxs("div",{className:"text-center mb-16 relative",children:[u.jsx("div",{className:"absolute -top-10 right-1/4 transform rotate-12",children:u.jsx(ya,{className:"w-24 h-24 text-[#98fe00]/10"})}),u.jsx("div",{className:"absolute top-0 left-1/4 transform -rotate-12",children:u.jsx(Ef,{className:"w-16 h-16 text-[#98fe00]/10"})}),u.jsx("div",{className:"absolute bottom-0 right-1/3",children:u.jsx(KT,{className:"w-12 h-12 text-[#98fe00]/10"})}),u.jsx("div",{children:u.jsxs("h1",{className:"text-6xl font-bold mb-6 relative",children:[u.jsx("img",{src:"/uploads/0ca35f7c-d6a1-49eb-9a3e-bf2c2e7194c3.png",alt:"SlinkyLayer",className:"h-[50px] mx-auto dark:block hidden object-contain"}),u.jsx("span",{className:"text-[#98fe00] dark:hidden",children:"SlinkyLayer"}),u.jsx("div",{className:"absolute -top-6 -right-6",children:u.jsx(Ef,{className:"w-8 h-8 text-[#98fe00] animate-pulse"})})]})}),u.jsxs("p",{className:"text-xl text-[#605F5B] max-w-2xl mx-auto mb-8 animate-fade-in delay-200 relative",children:["Launch powerful AI trading agents across multiple blockchains with one click",u.jsx("div",{className:"absolute -bottom-4 right-0",children:u.jsx(ya,{className:"w-6 h-6 text-[#98fe00]/20"})})]})]}),dN=[{id:1,name:"CEX Spot Trading Agent",description:"Advanced trading bot for centralized exchanges with real-time market analysis",icon:u.jsx(qT,{className:"w-8 h-8"}),type:"CEX_SPOT",features:["Real-time market analysis","Multiple trading strategies","Risk management system","Automated portfolio rebalancing","24/7 operation capability"],platforms:[{name:"Binance",logo:"https://assets.coingecko.com/markets/images/52/small/binance.jpg"}]},{id:2,name:"CEX Leverage Trading Agent",description:"Specialized trading bot for margin trading on centralized exchanges",icon:u.jsx(HT,{className:"w-8 h-8"}),type:"CEX_LEVERAGE",features:["Leverage optimization","Risk control systems","Position sizing","Stop-loss management","Margin level monitoring"],platforms:[{name:"Binance",logo:"https://assets.coingecko.com/markets/images/52/small/binance.jpg"},{name:"Bybit",logo:"https://assets.coingecko.com/markets/images/698/small/bybit_logo.png"}]},{id:3,name:"DEX Spot Trading Agent",description:"Decentralized exchange trading bot with cross-chain capabilities",icon:u.jsx(GT,{className:"w-8 h-8"}),type:"DEX_SPOT",features:["Multi-DEX integration","Gas optimization","Smart contract interaction","Liquidity pool analysis","Cross-chain trading"],platforms:[{name:"Solana",logo:"https://assets.coingecko.com/coins/images/4128/small/solana.png"},{name:"Aptos",logo:"https://assets.coingecko.com/coins/images/26455/small/aptos_round.png"},{name:"Base",logo:"https://assets.coingecko.com/coins/images/32375/small/base.png"}]},{id:4,name:"Arbitrage Agent",description:"Cross-exchange arbitrage opportunities finder and executor",icon:u.jsx(Cx,{className:"w-8 h-8"}),type:"ARBITRAGE",features:["Real-time price monitoring","Cross-DEX arbitrage","Flash loan integration","Gas optimization","Profit calculation"],platforms:[{name:"Solana",logo:"https://assets.coingecko.com/coins/images/4128/small/solana.png"},{name:"Movement",logo:"https://assets.coingecko.com/coins/images/31179/small/token-logo.png"},{name:"Base",logo:"https://assets.coingecko.com/coins/images/32375/small/base.png"}]},{id:5,name:"DEX Leverage Trading Agent",description:"Decentralized margin trading bot with advanced risk management",icon:u.jsx(WT,{className:"w-8 h-8"}),type:"DEX_LEVERAGE",features:["Leverage position management","Liquidation protection","Automated margin calls","Risk asse
7ssment","Protocol-specific optimizations"],platforms:[{name:"Base",logo:"https://assets.coingecko.com/coins/images/32375/small/base.png"},{name:"Movement",logo:"https://assets.coingecko.com/coins/images/31179/small/token-logo.png"}]},{id:6,name:"Analysis Agent",description:"Advanced trading signal provider with no wallet connection required",icon:u.jsx(nu,{className:"w-8 h-8"}),type:"ANALYSIS",features:["Technical analysis","Market sentiment analysis","Trading signals","Risk assessment","Performance tracking"],platforms:[{name:"All Chains",logo:"https://cdn-icons-png.flaticon.com/512/7838/7838652.png"}]},{id:7,name:"Social Agent",description:"Automated social media engagement and analytics",icon:u.jsx($h,{className:"w-8 h-8"}),type:"SOCIAL",features:["Multi-platform management","Automated engagement","Content analysis","Sentiment tracking","Performance analytics"],platforms:[{name:"All Platforms",logo:"https://cdn-icons-png.flaticon.com/512/7838/7838652.png"}]}],fN=({walletAddress:e})=>u.jsx("div",{className:"min-h-screen bg-[#0B0F1C] relative overflow-hidden",children:u.jsxs("div",{className:"container mx-auto px-6 py-12 relative",children:[u.jsx(uN,{}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:dN.map((t,r)=>u.jsx("div",{className:"animate-fade-in",style:{animationDelay:`${r*.1}s`,transform:`rotate(${Math.random()*1-.5}deg)`},children:u.jsx(cN,{agent:t,walletAddress:e})},t.id))})]})}),hN=({title:e,description:t})=>u.jsxs("div",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-[#0b0f14] mb-2",children:e}),u.jsx("p",{className:"text-[#667085]",children:t})]}),es=N.forwardRef(({className:e,...t},r)=>u.jsx("div",{ref:r,className:ze("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));es.displayName="Card";const oa=N.forwardRef(({className:e,...t},r)=>u.jsx("div",{ref:r,className:ze("flex flex-col space-y-1.5 p-6",e),...t}));oa.displayName="CardHeader";const la=N.forwardRef(({className:e,...t},r)=>u.jsx("h3",{ref:r,className:ze("text-2xl font-semibold leading-none tracking-tight",e),...t}));la.displayName="CardTitle";const a1=N.forwardRef(({className:e,...t},r)=>u.jsx("p",{ref:r,className:ze("text-sm text-muted-foreground",e),...t}));a1.displayName="CardDescription";const Ks=N.forwardRef(({className:e,...t},r)=>u.jsx("div",{ref:r,className:ze("p-6 pt-0",e),...t}));Ks.displayName="CardContent";const pN=N.forwardRef(({className:e,...t},r)=>u.jsx("div",{ref:r,className:ze("flex items-center p-6 pt-0",e),...t}));pN.displayName="CardFooter";const mN=Ea("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function cs({className:e,variant:t,...r}){return u.jsx("div",{className:ze(mN({variant:t}),e),...r})}const gN=({walletAddress:e,walletType:t,userProfile:r,onUpdateProfile:n,onLinkWallet:s})=>{const{toast:i}=jn(),[a,o]=N.useState(!1),[l,c]=N.useState(r?.username||""),[d,f]=N.useState(!1),h=(b,C)=>{navigator.clipboard.writeText(b),i({title:"Copied",description:`${C} copied to clipboard`})},m=()=>{n&&l.trim()&&(n({username:l.trim()}),o(!1))},g=()=>{c(r?.username||""),o(!1)},v=b=>b==="evm"?"bg-[#eff6ff] text-[#1d4ed8] border border-[#dbeafe]":"bg-[#faf5ff] text-[#7c3aed] border border-[#e9d5ff]",w=b=>`${b.slice(0,8)}...${b.slice(-6)}`;return u.jsxs(u.Fragment,{children:[u.jsxs(es,{className:"bg-white border border-[#e5e7eb] rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)]",children:[u.jsxs(oa,{className:"p-6 pb-3",children:[u.jsxs(la,{className:"flex items-center gap-4 text-[#0b0f14] text-lg font-semibold",children:[u.jsx("div",{className:"p-3 rounded-xl bg-black",children:u.jsx(Ts,{className:"h-5 w-5 text-white"})}),u.jsx("div",{children:u.jsx("h2",{className:"text-lg font-semibold text-[#0b0f14]",children:"Account Details"})})]}),u.jsx(a1,{className:"text-[#667085]",children:"Manage your profile and connected wallets"})]}),u.jsxs(Ks,{className:"space-y-6 px-6 pb-6",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(hr,{className:"text-[#0b0f14] font-medium",children:"Username"}),a?u.jsxs("div",{className:"flex gap-2",children:[u.jsx(rn,{value:l,onCh
7ange:b=>c(b.target.value),className:"bg-[#f8fafc] border-[#e2e8f0] text-[#0b0f14] focus:border-[#0b0f14] focus:ring-1 focus:ring-[#0b0f14]",placeholder:"Enter username"}),u.jsx(yt,{onClick:m,size:"sm",className:"bg-[#dcfce7] text-[#166534] hover:bg-[#bbf7d0] border border-[#bbf7d0]",children:u.jsx(YT,{className:"w-4 h-4"})}),u.jsx(yt,{onClick:g,size:"sm",variant:"outline",className:"border-[#e2e8f0] text-[#667085] hover:bg-[#f8fafc]",children:u.jsx(tu,{className:"w-4 h-4"})})]}):u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("div",{className:"bg-[#f8fafc] border border-[#e2e8f0] rounded-md px-3 py-2 text-[#0b0f14] flex-1",children:r?.username||"Not set"}),u.jsx(yt,{onClick:()=>o(!0),size:"sm",variant:"outline",className:"border-black/30 text-black hover:bg-black/5",children:u.jsx(QT,{className:"w-4 h-4"})})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(hr,{className:"text-[#0b0f14] font-medium",children:"Email"}),u.jsx("div",{className:"bg-[#f8fafc] border border-[#e2e8f0] rounded-md px-3 py-2 text-[#0b0f14]",children:r?.email||"Not available"})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(hr,{className:"text-[#0b0f14] font-medium",children:"Connected Wallets"}),u.jsxs(yt,{onClick:()=>f(!0),size:"sm",className:"bg-black/10 text-black hover:bg-black/15 border border-black/20",children:[u.jsx(XT,{className:"w-4 h-4 mr-2"}),"Link Wallet"]})]}),e&&t&&u.jsxs("div",{className:"bg-[#f8fafc] border border-[#e2e8f0] rounded-lg p-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("div",{className:"w-2 h-2 rounded-full bg-[#16a34a]"}),u.jsx("span",{className:"text-[#0b0f14] font-medium",children:"Active Wallet"}),u.jsx(cs,{className:v(t),children:t.toUpperCase()})]}),u.jsx(yt,{onClick:()=>h(e,"Wallet address"),size:"sm",variant:"ghost",className:"text-[#667085] hover:text-[#0b0f14] hover:bg-[#f1f5f9]",children:u.jsx(zn,{className:"w-3 h-3"})})]}),u.jsx("div",{className:"font-mono text-sm text-[#667085]",children:w(e)})]}),r?.evm_wallet_address&&u.jsxs("div",{className:"bg-[#f8fafc] border border-[#e2e8f0] rounded-lg p-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[t==="evm"&&e===r.evm_wallet_address?u.jsx("div",{className:"w-2 h-2 rounded-full bg-[#16a34a]"}):u.jsx("div",{className:"w-2 h-2 rounded-full bg-[#9ca3af]"}),u.jsx("span",{className:"text-[#0b0f14] font-medium",children:"EVM Wallet"}),u.jsx(cs,{className:"bg-[#eff6ff] text-[#1d4ed8] border border-[#dbeafe]",children:"EVM"})]}),u.jsx(yt,{onClick:()=>h(r.evm_wallet_address,"EVM wallet address"),size:"sm",variant:"ghost",className:"text-[#667085] hover:text-[#0b0f14] hover:bg-[#f1f5f9]",children:u.jsx(zn,{className:"w-3 h-3"})})]}),u.jsx("div",{className:"font-mono text-sm text-[#667085]",children:w(r.evm_wallet_address)})]}),r?.solana_wallet_address&&u.jsxs("div",{className:"bg-[#f8fafc] border border-[#e2e8f0] rounded-lg p-4",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[t==="solana"&&e===r.solana_wallet_address?u.jsx("div",{className:"w-2 h-2 rounded-full bg-[#16a34a]"}):u.jsx("div",{className:"w-2 h-2 rounded-full bg-[#9ca3af]"}),u.jsx("span",{className:"text-[#0b0f14] font-medium",children:"Solana Wallet"}),u.jsx(cs,{className:"bg-[#faf5ff] text-[#7c3aed] border border-[#e9d5ff]",children:"SOLANA"})]}),u.jsx(yt,{onClick:()=>h(r.solana_wallet_address,"Solana wallet address"),size:"sm",variant:"ghost",className:"text-[#667085] hover:text-[#0b0f14] hover:bg-[#f1f5f9]",children:u.jsx(zn,{className:"w-3 h-3"})})]}),u.jsx("div",{className:"font-mono text-sm text-[#667085]",children:w(r.solana_wallet_address)})]}),r?.preferred_wallet_type&&u.jsxs("div",{className:"text-sm text-[#667085]",children:["Preferred wallet type: ",u.jsx("span",{className:"text-[#0b0f14] font-medium capitalize",children:r.preferred_wallet_type})]})]})]})]}),u.jsx(Jh,{isOpen:d,onClose:()=>f(!1),onWalletConnected:b=>{s&&s(b)}})]})},yN=({createdAt:e})=>u.jsxs(es,{className:"bg-white border border-[#e5e7eb] rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)] p-6",children:[u.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[u.jsx("div",{className:"p-3 rounded-xl bg-black",children:u.jsx(Sx,{className:"h-5 w-5 text-white"})}),u.jsxs("div",{children:[u.jsx("h2",{className:"text-lg font-semibold text-[#0b0f14]",children:"Activity"}),u.jsx("p",{className:"text-sm text-[#667085]",children:"Recent updates"})]})]}),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"bg-[#f8fafc] rounded-xl p-4 border border-[#e2e8f0]",children:[u.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[u.jsx(JT,{className:"h-4 w-4 text-[#667085]"}),u.jsx("p",{className:"text-sm text-[#667085]",children:"Member Since"})]}),u.jsx("p",{className:"font-medium text-[#0b0f14]",children:e?new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):"Loading..."})]}),u.jsxs("div",{className:"bg-[#f8fafc] rounded-xl p-4 border border-[#e2e8f0]",children:[u.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[u.jsx(Ex,{className:"h-4 w-4 text-[#667085]"}),u.jsx("p",{className:"text-sm text-[#667085]",children:"Last Active"})]}),u.jsx("p",{className:"font-medium text-[#0b0f14]",children:"2 hours ago"})]})]})]}),vN=({walletAddress:e,walletType:t})=>{const{toast:r}=jn(),[n,s]=N.useState(null),[i,a]=N.useState(!0);N.useState({total:0,active:0,inactive:0}),N.useEffect(()=>{(async()=>
7{if(!e){a(!1);return}try{const{data:{user:d}}=await En.auth.getUser();if(!d){a(!1);return}const{data:f,error:h}=await En.from("profiles").select("*").eq("id",d.id).maybeSingle();if(h){r({title:"Error",description:"Failed to load profile data",variant:"destructive"});return}if(f){const m={...f,preferred_wallet_type:f.preferred_wallet_type};s(m)}else{const m=Eo(),g={id:d.id,email:d.email,username:d.email?.split("@")[0],evm_wallet_address:m?.type==="evm"?m.address:null,solana_wallet_address:m?.type==="solana"?m.address:null,preferred_wallet_type:m?.type||"evm"},{data:v,error:w}=await En.from("profiles").insert(g).select().single();if(!w){const b={...v,preferred_wallet_type:v.preferred_wallet_type};s(b)}}}catch{}finally{a(!1)}})()},[e,t,r]);const o=async c=>{if(n)try{const{data:d,error:f}=await En.from("profiles").update(c).eq("id",n.id).select().single();if(f)throw f;const h={...d,preferred_wallet_type:d.preferred_wallet_type};s(h),r({title:"Profile Updated",description:"Your profile has been updated successfully"})}catch(d){r({title:"Error",description:d.message||"Failed to update profile",variant:"destructive"})}},l=async c=>{if(n)try{const d={};c.type==="evm"?d.evm_wallet_address=c.address:d.solana_wallet_address=c.address,await o(d),r({title:"Wallet Linked",description:`${c.type.toUpperCase()} wallet linked successfully`})}catch{}};return i?u.jsx("div",{className:"min-h-screen bg-background",children:u.jsx("div",{className:"container mx-auto py-6 px-4 max-w-5xl",children:u.jsx("div",{className:"flex items-center justify-center h-64",children:u.jsx("div",{className:"text-[#667085]",children:"Loading profile..."})})})}):u.jsx("div",{className:"min-h-screen bg-background",children:u.jsxs("div",{className:"container mx-auto py-6 px-4 max-w-5xl",children:[u.jsx(hN,{title:"Profile Overview",description:"Manage your account and view your activity"}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-6",children:u.jsxs("div",{className:"md:col-span-8 space-y-6",children:[u.jsx(gN,{walletAddress:e,walletType:t,userProfile:n,onUpdateProfile:o,onLinkWallet:l}),u.jsx(yN,{createdAt:n?.created_at})]})})]})})},xN=()=>u.jsxs("div",{className:"space-y-2 mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Explore the Tool Network"}),u.jsx("p",{className:"text-muted-foreground",children:"Discover specialist capabilities for research, markets, blockchain data, and onchain activity."})]}),bN=({votes:e,state:t="up",className:r,modelName:n="Model",onClick:s})=>{jn();const i=t==="up"?Tx:t==="down"?ZT:e_,a={up:"!bg-emerald-50 !border-emerald-200 !text-emerald-500 dark:bg-emerald-500/10 dark:border-emerald-400/20 dark:text-emerald-300",down:"bg-rose-50    border-rose-200    text-rose-700    dark:bg-rose-500/10    dark:border-rose-400/20    dark:text-rose-300",flat:"bg-slate-50   border-slate-200   text-slate-700   dark:bg-slate-500/10   dark:border-slate-400/20   dark:text-slate-300"};return u.jsxs("div",{className:ze("inline-flex items-center gap-1 px-2 py-1 rounded border text-xs font-medium ml-auto tabular-nums cursor-pointer opacity-100 hover:brightness-95 transition",a[t],r),onClick:o=>{o.stopPropagation(),s?.()},children:[u.jsx(i,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Vote"})]})},Og=({api:e,rank:t})=>{const r=Sa();return u.jsxs("div",{className:"flex items-center justify-between py-1.5 hover:bg-[#f9fafb]/50 transition-colors",children:[u.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[u.jsx("span",{className:"text-xs font-medium text-[#667085] w-4 flex-shrink-0",children:t}),u.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#f3f4f6] flex items-center justify-center flex-shrink-0",children:u.jsx("span",{className:"text-[#0b0f14] font-bold text-xs",children:e.name.charAt(0)})}),u.jsx("span",{className:"text-sm font-medium text-[#0b0f14] truncate flex-1",children:e.name})]}),u.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(ya,{className:"h-4 w-4 fill-yellow-300 text-yellow-400"}),u.jsxs("span",{className:"font-medium text-sm text-gray-900",children:[" ",e.rating," "]})]}),u.jsx(bN,{votes:e.votes||0,state:"up",modelName:e.name,onClick:()=>{r(`/tools/${e.id}`)}})]})]})};var Pt={options:{usePureJavaScript:!1}},mp={},wN=mp,Fg={};mp.encode=function(e,t,r){if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');if(r!==void 0&&typeof r!="number")throw new TypeError('"maxline" must be a number.');var n="";if(!(e instanceof Uint8Array))n=CN(e,t);else{var s=0,i=t.length,a=t.charAt(0),o=[0];for(s=0;s<e.length;++s){for(var l=0,c=e[s];l<o.length;++l)c+=o[l]<<8,o[l]=c%i,c=c/i|0;for(;c>0;)o.push(c%i),c=c/i|0}for(s=0;e[s]===0&&s<e.length-1;++s)n+=a;for(s=o.length-1;s>=0;--s)n+=t[o[s]]}if(r){var d=new RegExp(".{1,"+r+"}","g");n=n.match(d).join(`\r
8`)}return n};mp.decode=function(e,t){if(typeof e!="string")throw new TypeError('"input" must be a string.');if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');var r=Fg[t];if(!r){r=Fg[t]=[];for(var n=0;n<t.length;++n)r[t.charCodeAt(n)]=n}e=e.replace(/\s/g,"");for(var s=t.length,i=t.charAt(0),a=[0],n=0;n<e.length;n++){var o=r[e.charCodeAt(n)];if(o===void 0)return;for(var l=0,c=o;l<a.length;++l)c+=a[l]*s,a[l]=c&255,c>>=8;for(;c>0;)a.push(c&255),c>>=8}for(var d=0;e[d]===i&&d<e.length-1;++d)a.push(0);return typeof Buffer<"u"?Buffer.from(a.reverse()):new Uint8Array(a.reverse())};function CN(e,t){var r=0,n=t.length,s=t.charAt(0),i=[0];for(r=0;r<e.length();++r){for(var a=0,o=e.at(r);a<i.length;++a)o+=i[a]<<8,i[a]=o%n,o=o/n|0;for(;o>0;)i.push(o%n),o=o/n|0}var l="";for(r=0;e.at(r)===0&&r<e.length()-1;++r)l+=s;for(r=i.length-1;r>=0;--r)l+=t[i[r]];return l}var Ug=Pt,Vg=wN,Z=Ug.util=Ug.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){Z.nextTick=process.nextTick,typeof setImmediate=="function"?Z.setImmediate=setImmediate:Z.setImmediate=Z.nextTick;return}if(typeof setImmediate=="function"){Z.setImmediate=function(){return setImmediate.apply(void 0,arguments)},Z.nextTick=function(a){return setImmediate(a)};return}if(Z.setImmediate=function(a){setTimeout(a,0)},typeof window<"u"&&typeof window.postMessage=="function"){let a=function(o){if
8(o.source===window&&o.data===e){o.stopPropagation();var l=t.slice();t.length=0,l.forEach(function(c){c()})}};var e="forge.setImmediate",t=[];Z.setImmediate=function(o){t.push(o),t.length===1&&window.postMessage(e,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver<"u"){var r=Date.now(),n=!0,s=document.createElement("div"),t=[];new MutationObserver(function(){var o=t.slice();t.length=0,o.forEach(function(l){l()})}).observe(s,{attributes:!0});var i=Z.setImmediate;Z.setImmediate=function(o){Date.now()-r>15?(r=Date.now(),i(o)):(t.push(o),t.length===1&&s.setAttribute("a",n=!n))}}Z.nextTick=Z.setImmediate})();Z.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;Z.globalScope=function(){return Z.isNodejs?Ni:typeof self>"u"?window:self}();Z.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};Z.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};Z.isArrayBufferView=function(e){return e&&Z.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function Go(e){if(!(e===8||e===16||e===24||e===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}Z.ByteBuffer=gp;function gp(e){if(this.data="",this.read=0,typeof e=="string")this.data=e;else if(Z.isArrayBuffer(e)||Z.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch{for(var r=0;r<t.length;++r)this.putByte(t[r])}}else(e instanceof gp||typeof e=="object"&&typeof e.data=="string"&&typeof e.read=="number")&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}Z.ByteStringBuffer=gp;var SN=4096;Z.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>SN&&(this.data.substr(0,1),this._constructedStringLength=0)};Z.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};Z.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};Z.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};Z.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)t&1&&(r+=e),t>>>=1,t>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this};Z.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};Z.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(Z.encodeUtf8(e))};Z.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};Z.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};Z.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};Z.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};Z.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};Z.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};Z.ByteStringBuffer.prototype.putInt=function(e,t){Go(t);var r="";do t-=8,r+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(r)};Z.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)};Z.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};Z.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};Z.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};Z.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};Z.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};Z.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};Z.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};Z.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};Z.ByteStringBuffer.prototype.getInt=function(e){Go(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};Z.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t};Z.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};Z.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};Z.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};Z.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};Z.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};Z.ByteStringBuffer.prototype.copy=function(){var e=Z.createBuffer(this.data);return e.read=this.read,e};Z.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};Z.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};Z.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};Z.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var r=this.data.charCodeAt(t);r<16&&(e+="0"),e+=r.toString(16)}return e};Z.ByteStringBuffer.prototype.toString=function(){return Z.decodeUtf8(this.bytes())};function EN(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var r=Z.isArrayBuffer(e),n=Z.isArrayBufferView(e);if(r||n){r?this.data=new DataView(e):this.data=new DataView(e.buffer,e.byteOffset,e.byteLength),this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!=null&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)}Z.DataBuffer=EN;Z.DataBuffer.prototype.length=function(){return this.write-this.read};Z.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};Z.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);
8var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this};Z.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};Z.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r<t;++r)this.data.setUint8(e);return this};Z.DataBuffer.prototype.putBytes=function(e,t){if(Z.isArrayBufferView(e)){var r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=r.byteLength-r.byteOffset;this.accommodate(n);var s=new Uint8Array(this.data.buffer,this.write);return s.set(r),this.write+=n,this}if(Z.isArrayBuffer(e)){var r=new Uint8Array(e);this.accommodate(r.byteLength);var s=new Uint8Array(this.data.buffer);return s.set(r,this.write),this.write+=r.byteLength,this}if(e instanceof Z.DataBuffer||typeof e=="object"&&typeof e.read=="number"&&typeof e.write=="number"&&Z.isArrayBufferView(e.data)){var r=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(r.byteLength);var s=new Uint8Array(e.data.byteLength,this.write);return s.set(r),this.write+=r.byteLength,this}if(e instanceof Z.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary",typeof e=="string"){var i;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),i=new Uint8Array(this.data.buffer,this.write),this.write+=Z.binary.hex.decode(e,i,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),i=new Uint8Array(this.data.buffer,this.write),this.write+=Z.binary.base64.decode(e,i,this.write),this;if(t==="utf8"&&(e=Z.encodeUtf8(e),t="binary"),t==="binary"||t==="raw")return this.accommodate(e.length),i=new Uint8Array(this.data.buffer,this.write),this.write+=Z.binary.raw.decode(i),this;if(t==="utf16")return this.accommodate(e.length*2),i=new Uint16Array(this.data.buffer,this.write),this.write+=Z.text.utf16.encode(i),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};Z.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};Z.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};Z.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};Z.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};Z.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};Z.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};Z.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};Z.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};Z.DataBuffer.prototype.putInt=function(e,t){Go(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};Z.DataBuffer.prototype.putSignedInt=function(e,t){return Go(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)};Z.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};Z.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};Z.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};Z.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};Z.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};Z.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};Z.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};Z.DataBuffer.prototype.getInt=function(e){Go(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};Z.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t};Z.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};Z.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};Z.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};Z.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};Z.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};Z.DataBuffer.prototype.copy=function(){return new Z.DataBuffer(this)};Z.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};Z.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};Z.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};Z.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var r=this.data.getUint8(t);r<16&&(e+="0"),e+=r.toString(16)}return e};Z.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return Z.binary.raw.encode(t);if(e==="hex")return Z.binary.hex.encode(t);if(e==="base64")return Z.binary.base64.encode(t);if(e==="utf8")return Z.text.utf8.decode(t);if(e==="utf16")return Z.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)};Z.createBuffer=function(e,t){return t=t||"raw",e!==void 0&&t==="utf8"&&(e=Z.encodeUtf8(e)),new Z.ByteBuffer(e)};Z.fillString=function(e,t){for(var r="";t>0;)t&1&&(r+=e),t>>>=1,t>0&&(e+=e);return r};Z.xorBytes=function(e,t,r){for(var n="",s="",i="",a=0,o=0;r>0;--r,++a)s=e.charCodeAt(a)^t.charCodeAt(a),o>=10&&(n+=i,i="",o=0),i+=String.fromCharCode(s),++o;return n+=i,n};Z.hexToBytes=function(e){var t="",r=0;for(e.length&!0&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r<e.length;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t};Z.bytesToHex=function(e){return Z.createBuffer(e).toHex()};Z.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var qs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
8+/=",Hs=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],o1="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";Z.encode64=function(e,t){for(var r="",n="",s,i,a,o=0;o<e.length;)s=e.charCodeAt(o++),i=e.charCodeAt(o++),a=e.charCodeAt(o++),r+=qs.charAt(s>>2),r+=qs.charAt((s&3)<<4|i>>4),isNaN(i)?r+="==":(r+=qs.charAt((i&15)<<2|a>>6),r+=isNaN(a)?"=":qs.charAt(a&63)),t&&r.length>t&&(n+=r.substr(0,t)+`\r
9`,r=r.substr(t));return n+=r,n};Z.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t="",r,n,s,i,a=0;a<e.length;)r=Hs[e.charCodeAt(a++)-43],n=Hs[e.charCodeAt(a++)-43],s=Hs[e.charCodeAt(a++)-43],i=Hs[e.charCodeAt(a++)-43],t+=String.fromCharCode(r<<2|n>>4),s!==64&&(t+=String.fromCharCode((n&15)<<4|s>>2),i!==64&&(t+=String.fromCharCode((s&3)<<6|i)));return t};Z.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};Z.decodeUtf8=function(e){return decodeURIComponent(escape(e))};Z.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Vg.encode,decode:Vg.decode}};Z.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};Z.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var s=r,i=0;i<e.length;++i)n[s++]=e.charCodeAt(i);return t?s-r:n};Z.binary.hex.encode=Z.bytesToHex;Z.binary.hex.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/2))),r=r||0;var s=0,i=r;for(e.length&1&&(s=1,n[i++]=parseInt(e[0],16));s<e.length;s+=2)n[i++]=parseInt(e.substr(s,2),16);return t?i-r:n};Z.binary.base64.encode=function(e,t){for(var r="",n="",s,i,a,o=0;o<e.byteLength;)s=e[o++],i=e[o++],a=e[o++],r+=qs.charAt(s>>2),r+=qs.charAt((s&3)<<4|i>>4),isNaN(i)?r+="==":(r+=qs.charAt((i&15)<<2|a>>6),r+=isNaN(a)?"=":qs.charAt(a&63)),t&&r.length>t&&(n+=r.substr(0,t)+`\r
10`,r=r.substr(t));return n+=r,n};Z.binary.base64.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/4)*3)),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),r=r||0;for(var s,i,a,o,l=0,c=r;l<e.length;)s=Hs[e.charCodeAt(l++)-43],i=Hs[e.charCodeAt(l++)-43],a=Hs[e.charCodeAt(l++)-43],o=Hs[e.charCodeAt(l++)-43],n[c++]=s<<2|i>>4,a!==64&&(n[c++]=(i&15)<<4|a>>2,o!==64&&(n[c++]=(a&3)<<6|o));return t?c-r:n.subarray(0,c)};Z.binary.base58.encode=function(e,t){return Z.binary.baseN.encode(e,o1,t)};Z.binary.base58.decode=function(e,t){return Z.binary.baseN.decode(e,o1,t)};Z.text={utf8:{},utf16:{}};Z.text.utf8.encode=function(e,t,r){e=Z.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var s=r,i=0;i<e.length;++i)n[s++]=e.charCodeAt(i);return t?s-r:n};Z.text.utf8.decode=function(e){return Z.decodeUtf8(String.fromCharCode.apply(null,e))};Z.text.utf16.encode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length*2));var s=new Uint16Array(n.buffer);r=r||0;for(var i=r,a=r,o=0;o<e.length;++o)s[a++]=e.charCodeAt(o),i+=2;return t?i-r:n};Z.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};Z.deflate=function(e,t,r){if(t=Z.decode64(e.deflate(Z.encode64(t)).rval),r){var n=2,s=t.charCodeAt(1);s&32&&(n=6),t=t.substring(n,t.length-4)}return t};Z.inflate=function(e,t,r){var n=e.inflate(Z.encode64(t)).rval;return n===null?null:Z.decode64(n)};var yp=function(e,t,r){if(!e)throw new Error("WebStorage not available.");var n;if(r===null?n=e.removeItem(t):(r=Z.encode64(JSON.stringify(r)),n=e.setItem(t,r)),typeof n<"u"&&n.rval!==!0){var s=new Error(n.error.message);throw s.id=n.error.id,s.name=n.error.name,s}},vp=function(e,t){if(!e)throw new Error("WebStorage not available.");var r=e.getItem(t);if(e.init)if(r.rval===null){if(r.error){var n=new Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}r=null}else r=r.rval;return r!==null&&(r=JSON.parse(Z.decode64(r))),r},TN=function(e,t,r,n){var s=vp(e,t);s===null&&(s={}),s[r]=n,yp(e,t,s)},_N=function(e,t,r){var n=vp(e,t);return n!==null&&(n=r in n?n[r]:null),n},IN=function(e,t,r){var n=vp(e,t);if(n!==null&&r in n){delete n[r];var s=!0;for(var i in n){s=!1;break}
10s&&(n=null),yp(e,t,n)}},AN=function(e,t){yp(e,t,null)},fu=function(e,t,r){var n=null;typeof r>"u"&&(r=["web","flash"]);var s,i=!1,a=null;for(var o in r){s=r[o];try{if(s==="flash"||s==="both"){if(t[0]===null)throw new Error("Flash local storage not available.");n=e.apply(this,t),i=s==="flash"}(s==="web"||s==="both")&&(t[0]=localStorage,n=e.apply(this,t),i=!0)}catch(l){a=l}if(i)break}if(!i)throw a;return n};Z.setItem=function(e,t,r,n,s){fu(TN,arguments,s)};Z.getItem=function(e,t,r,n){return fu(_N,arguments,n)};Z.removeItem=function(e,t,r,n){fu(IN,arguments,n)};Z.clearItems=function(e,t,r){fu(AN,arguments,r)};Z.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};Z.format=function(e){for(var t=/%./g,r,n,s=0,i=[],a=0;r=t.exec(e);){n=e.substring(a,t.lastIndex-2),n.length>0&&i.push(n),a=t.lastIndex;var o=r[0][1];switch(o){case"s":case"o":s<arguments.length?i.push(arguments[s+++1]):i.push("<?>");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(a)),i.join("")};Z.formatNumber=function(e,t,r,n){var s=e,i=isNaN(t=Math.abs(t))?2:t,a=r===void 0?",":r,o=n===void 0?".":n,l=s<0?"-":"",c=parseInt(s=Math.abs(+s||0).toFixed(i),10)+"",d=c.length>3?c.length%3:0;return l+(d?c.substr(0,d)+o:"")+c.substr(d).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?a+Math.abs(s-c).toFixed(i).slice(2):"")};Z.formatSize=function(e){return e>=1073741824?e=Z.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?e=Z.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?e=Z.formatNumber(e/1024,0)+" KiB":e=Z.formatNumber(e,0)+" bytes",e};Z.bytesFromIP=function(e){return e.indexOf(".")!==-1?Z.bytesFromIPv4(e):e.indexOf(":")!==-1?Z.bytesFromIPv6(e):null};Z.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;for(var t=Z.createBuffer(),r=0;r<e.length;++r){var n=parseInt(e[r],10);if(isNaN(n))return null;t.putByte(n)}return t.getBytes()};Z.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(a){return a.length===0&&++t,!0});for(var r=(8-e.length+t)*2,n=Z.createBuffer(),s=0;s<8;++s){if(!e[s]||e[s].length===0){n.fillWithByte(0,r),r=0;continue}var i=Z.hexToBytes(e[s]);i.length<2&&n.putByte(0),n.putBytes(i)}return n.getBytes()};Z.bytesToIP=function(e){return e.length===4?Z.bytesToIPv4(e):e.length===16?Z.bytesToIPv6(e):null};Z.bytesToIPv4=function(e){if(e.length!==4)return null;for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t.join(".")};Z.bytesToIPv6=function(e){if(e.length!==16)return null;for(var t=[],r=[],n=0,s=0;s<e.length;s+=2){for(var i=Z.bytesToHex(e[s]+e[s+1]);i[0]==="0"&&i!=="0";)i=i.substr(1);if(i==="0"){var a=r[r.length-1],o=t.length;!a||o!==a.end+1?r.push({start:o,end:o}):(a.end=o,a.end-a.start>r[n].end-r[n].start&&(n=r.length-1))}t.push(i)}if(r.length>0){var l=r[n];l.end-l.start>0&&(t.splice(l.start,l.end-l.start+1,""),l.start===0&&t.unshift(""),l.end===7&&t.push(""))}return t.join(":")};Z.estimateCores=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},"cores"in Z&&!e.update)return t(null,Z.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return Z.cores=navigator.hardwareConcurrency,t(null,Z.cores);if(typeof Worker>"u")return Z.cores=1,t(null,Z.cores);if(typeof Blob>"u")return Z.cores=2,t(null,Z.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(a){var o=Date.now(),l=o+4;self.postMessage({st:o,et:l})})}.toString(),")()"],{type:"application/javascript"}));n([],5,16);function n(a,o,l){if(o===0){var c=Math.floor(a.reduce(function(d,f){return d+f},0)/a.length);return Z.cores=Math.max(1,c),URL.revokeObjectURL(r),t(null,Z.cores)}s(l,function(d,f){a.push(i(l,f)),n(a,o-1,l)})}function s(a,o){for(var l=[],c=[],d=0;d<a;++d){var f=new Worker(r);f.addEventListener("message",function(h){if(c.push(h.data),c.length===a){for(var m=0;m<a;++m)l[m].terminate();o(null,c)}}),l.push(f)}for(var d=0;d<a;++d)l[d].postMessage(d)}function i(a,o){for(var l=[],c=0;c<a;++c)for(var d=o[c],f=l[c]=[],h=0;h<a;++h)if(c!==h){var m=o[h];(d.st>m.st&&d.st<m.et||m.st>d.st&&m.st<d.et)&&f.push(h)}return l.reduce(function(g,v){return Math.max(g,v.length)},0)}};var kr=Pt;kr.cipher=kr.cipher||{};kr.cipher.algorithms=kr.cipher.algorithms||{};kr.cipher.createCipher=function(e,t){var r=e;if(typeof r=="string"&&(r=kr.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+e);return new kr.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})};kr.cipher.createDecipher=function(e,t){var r=e;if(typeof r=="string"&&(r=kr.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+e);return new kr.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})};kr.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),kr.cipher.algorithms[e]=t};kr.cipher.getAlgorithm=function(e){return e=e.toUpperCase(),e in kr.cipher.algorithms?kr.cipher.algorithms[e]:null};var xp=kr.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};xp.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=kr.util.createBuffer(),this.output=e.output||kr.util.createBuffer(),this.mode.start(t)};xp.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};xp.prototype.finish=function(e){e&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(r){return e(this.blockSize,r,!1)},this.mode.unpad=function(r){return e(this.blockSize,r,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,t))};var Ar=Pt;Ar.cipher=Ar.cipher||{};var Lt=Ar.cipher.modes=Ar.cipher.modes||{};Lt.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Lt.ecb.prototype.start=function(e){};Lt.ecb.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])};Lt.ecb.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])};Lt.ecb.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0};Lt.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return n>this.blockSize<<2?!1:(e.truncate(n),!0)};Lt.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Lt.cbc.prototype.start=function(e){if(e.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in e)this._iv=hu(e.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};Lt.cbc.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=this._prev[n]^e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]);this._prev=this._outBlock};Lt.cbc.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._prev[n]^this._outBlock[n]);this._prev=this._inBlock.slice(0)};Lt.cbc.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0};Lt.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return n>this.blockSize<<2?!1:(e.truncate(n),!0)};Lt.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=Ar.util.createBuffer(),this._partialBytes=0};Lt.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=hu(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Lt.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(n===0)return!0;
10if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var s=0;s<this._ints;++s)this._inBlock[s]=e.getInt32()^this._outBlock[s],t.putInt32(this._inBlock[s]);return}var i=(this.blockSize-n)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var s=0;s<this._ints;++s)this._partialBlock[s]=e.getInt32()^this._outBlock[s],this._partialOutput.putInt32(this._partialBlock[s]);if(i>0)e.read-=this.blockSize;else for(var s=0;s<this._ints;++s)this._inBlock[s]=this._partialBlock[s];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Lt.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var s=0;s<this._ints;++s)this._inBlock[s]=e.getInt32(),t.putInt32(this._inBlock[s]^this._outBlock[s]);return}var i=(this.blockSize-n)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var s=0;s<this._ints;++s)this._partialBlock[s]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[s]^this._outBlock[s]);if(i>0)e.read-=this.blockSize;else for(var s=0;s<this._ints;++s)this._inBlock[s]=this._partialBlock[s];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Lt.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Ar.util.createBuffer(),this._partialBytes=0};Lt.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=hu(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Lt.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(e.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var s=0;s<this._ints;++s)t.putInt32(e.getInt32()^this._outBlock[s]),this._inBlock[s]=this._outBlock[s];return}var i=(this.blockSize-n)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var s=0;s<this._ints;++s)this._partialOutput.putInt32(e.getInt32()^this._outBlock[s]);if(i>0)e.read-=this.blockSize;else for(var s=0;s<this._ints;++s)this._inBlock[s]=this._outBlock[s];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Lt.ofb.prototype.decrypt=Lt.ofb.prototype.encrypt;Lt.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Ar.util.createBuffer(),this._partialBytes=0};Lt.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=hu(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Lt.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize)for(var s=0;s<this._ints;++s)t.putInt32(e.getInt32()^this._outBlock[s]);else{var i=(this.blockSize-n)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var s=0;s<this._ints;++s)this._partialOutput.putInt32(e.getInt32()^this._outBlock[s]);if(i>0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}pu(this._inBlock)};Lt.ctr.prototype.decrypt=Lt.ctr.prototype.encrypt;Lt.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=Ar.util.createBuffer(),this._partialBytes=0,this._R=3774873600};Lt.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t=Ar.util.createBuffer(e.iv);this._cipherLength=0;var r;if("additionalData"in e?r=Ar.util.createBuffer(e.additionalData):r=Ar.util.createBuffer(),"tagLength"in e?this._tagLength=e.tagLength:this._tagLength=128,this._tag=null,e.decrypt&&(this._tag=Ar.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=t.length();if(n===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{for(this._j0=[0,0,0,0];t.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(Ff(n*8)))}this._inBlock=this._j0.slice(0),pu(this._inBlock),this._partialBytes=0,r=Ar.util.createBuffer(r),this._aDataLength=Ff(r.length()*8);var s=r.length()%this.blockSize;for(s&&r.fillWithByte(0,this.blockSize-s),this._s=[0,0,0,0];r.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()])};Lt.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(n===0)return!0;
10if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var s=0;s<this._ints;++s)t.putInt32(this._outBlock[s]^=e.getInt32());this._cipherLength+=this.blockSize}else{var i=(this.blockSize-n)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var s=0;s<this._ints;++s)this._partialOutput.putInt32(e.getInt32()^this._outBlock[s]);if(i<=0||r){if(r){var a=n%this.blockSize;this._cipherLength+=a,this._partialOutput.truncate(this.blockSize-a)}else this._cipherLength+=this.blockSize;for(var s=0;s<this._ints;++s)this._outBlock[s]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),pu(this._inBlock)};Lt.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n<this.blockSize&&!(r&&n>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),pu(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var s=0;s<this._ints;++s)t.putInt32(this._outBlock[s]^this._hashBlock[s]);n<this.blockSize?this._cipherLength+=n%this.blockSize:this._cipherLength+=this.blockSize};Lt.gcm.prototype.afterFinish=function(e,t){var r=!0;t.decrypt&&t.overflow&&e.truncate(this.blockSize-t.overflow),this.tag=Ar.util.createBuffer();var n=this._aDataLength.concat(Ff(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,n);var s=[];this.cipher.encrypt(this._j0,s);for(var i=0;i<this._ints;++i)this.tag.putInt32(this._s[i]^s[i]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag&&(r=!1),r};Lt.gcm.prototype.multiply=function(e,t){for(var r=[0,0,0,0],n=t.slice(0),s=0;s<128;++s){var i=e[s/32|0]&1<<31-s%32;i&&(r[0]^=n[0],r[1]^=n[1],r[2]^=n[2],r[3]^=n[3]),this.pow(n,n)}return r};Lt.gcm.prototype.pow=function(e,t){for(var r=e[3]&1,n=3;n>0;--n)t[n]=e[n]>>>1|(e[n-1]&1)<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)};Lt.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=r/8|0,s=e[n]>>>(7-r%8)*4&15,i=this._m[r][s];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t};Lt.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)};Lt.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,s=16*r,i=new Array(s),a=0;a<s;++a){var o=[0,0,0,0],l=a/n|0,c=(n-1-a%n)*t;o[l]=1<<t-1<<c,i[a]=this.generateSubHashTable(this.multiply(o,e),t)}return i};Lt.gcm.prototype.generateSubHashTable=function(e,t){var r=1<<t,n=r>>>1,s=new Array(r);s[n]=e.slice(0);for(var i=n>>>1;i>0;)this.pow(s[2*i],s[i]=[]),i>>=1;for(i=2;i<n;){for(var a=1;a<i;++a){var o=s[i],l=s[a];s[i+a]=[o[0]^l[0],o[1]^l[1],o[2]^l[2],o[3]^l[3]]}i*=2}for(s[0]=[0,0,0,0],i=n+1;i<r;++i){var c=s[i^n];s[i]=[e[0]^c[0],e[1]^c[1],e[2]^c[2],e[3]^c[3]]}return s};function hu(e,t){if(typeof e=="string"&&(e=Ar.util.createBuffer(e)),Ar.util.isArray(e)&&e.length>4){var r=e;e=Ar.util.createBuffer();for(var n=0;n<r.length;++n)e.putByte(r[n])}if(e.length()<t)throw new Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!Ar.util.isArray(e)){for(var s=[],i=t/4,n=0;n<i;++n)s.push(e.getInt32());e=s}return e}function pu(e){e[e.length-1]=e[e.length-1]+1&4294967295}function Ff(e){return[e/4294967296|0,e&4294967295]}var nr=Pt;nr.aes=nr.aes||{};nr.aes.startEncrypting=function(e,t,r,n){var s=mu({key:e,output:r,decrypt:!1,mode:n});return s.start(t),s};nr.aes.createEncryptionCipher=function(e,t){return mu({key:e,output:null,decrypt:!1,mode:t})};nr.aes.startDecrypting=function(e,t,r,n){var s=mu({key:e,output:r,decrypt:!0,mode:n});return s.start(t),s};nr.aes.createDecryptionCipher=function(e,t){return mu({key:e,output:null,decrypt:!0,mode:t})};nr.aes.Algorithm=function(e,t){bp||c1();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(n,s){return Vf(r._w,n,s,!1)},decrypt:function(n,s){return Vf(r._w,n,s,!0)}}}),r._init=!1};
10nr.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t=e.key,r;if(typeof t=="string"&&(t.length===16||t.length===24||t.length===32))t=nr.util.createBuffer(t);else if(nr.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){r=t,t=nr.util.createBuffer();for(var n=0;n<r.length;++n)t.putByte(r[n])}if(!nr.util.isArray(t)){r=t,t=[];var s=r.length();if(s===16||s===24||s===32){s=s>>>2;for(var n=0;n<s;++n)t.push(r.getInt32())}}if(!nr.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw new Error("Invalid key parameter.");var i=this.mode.name,a=["CFB","OFB","CTR","GCM"].indexOf(i)!==-1;this._w=u1(t,e.decrypt&&!a),this._init=!0}};nr.aes._expandKey=function(e,t){return bp||c1(),u1(e,t)};nr.aes._updateBlock=Vf;Ia("AES-ECB",nr.cipher.modes.ecb);Ia("AES-CBC",nr.cipher.modes.cbc);Ia("AES-CFB",nr.cipher.modes.cfb);Ia("AES-OFB",nr.cipher.modes.ofb);Ia("AES-CTR",nr.cipher.modes.ctr);Ia("AES-GCM",nr.cipher.modes.gcm);function Ia(e,t){var r=function(){return new nr.aes.Algorithm(e,t)};nr.cipher.registerAlgorithm(e,r)}var bp=!1,Zi=4,qr,Uf,l1,_i,Vn;function c1(){bp=!0,l1=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;qr=new Array(256),Uf=new Array(256),_i=new Array(4),Vn=new Array(4);for(var t=0;t<4;++t)_i[t]=new Array(256),Vn[t]=new Array(256);for(var r=0,n=0,s,i,a,o,l,c,d,t=0;t<256;++t){o=n^n<<1^n<<2^n<<3^n<<4,o=o>>8^o&255^99,qr[r]=o,Uf[o]=r,l=e[o],s=e[r],i=e[s],a=e[i],c=l<<24^o<<16^o<<8^(o^l),d=(s^i^a)<<24^(r^a)<<16^(r^i^a)<<8^(r^s^a);for(var f=0;f<4;++f)_i[f][r]=c,Vn[f][o]=d,c=c<<24|c>>>8,d=d<<24|d>>>8;r===0?r=n=1:(r=s^e[e[e[s^a]]],n^=e[e[n]])}}function u1(e,t){for(var r=e.slice(0),n,s=1,i=r.length,a=i+6+1,o=Zi*a,l=i;l<o;++l)n=r[l-1],l%i===0?(n=qr[n>>>16&255]<<24^qr[n>>>8&255]<<16^qr[n&255]<<8^qr[n>>>24]^l1[s]<<24,s++):i>6&&l%i===4&&(n=qr[n>>>24]<<24^qr[n>>>16&255]<<16^qr[n>>>8&255]<<8^qr[n&255]),r[l]=r[l-i]^n;if(t){var c,d=Vn[0],f=Vn[1],h=Vn[2],m=Vn[3],g=r.slice(0);o=r.length;for(var l=0,v=o-Zi;l<o;l+=Zi,v-=Zi)if(l===0||l===o-Zi)g[l]=r[v],g[l+1]=r[v+3],g[l+2]=r[v+2],g[l+3]=r[v+1];else for(var w=0;w<Zi;++w)c=r[v+w],g[l+(3&-w)]=d[qr[c>>>24]]^f[qr[c>>>16&255]]^h[qr[c>>>8&255]]^m[qr[c&255]];r=g}return r}function Vf(e,t,r,n){var s=e.length/4-1,i,a,o,l,c;n?(i=Vn[0],a=Vn[1],o=Vn[2],l=Vn[3],c=Uf):(i=_i[0],a=_i[1],o=_i[2],l=_i[3],c=qr);var d,f,h,m,g,v,w;d=t[0]^e[0],f=t[n?3:1]^e[1],h=t[2]^e[2],m=t[n?1:3]^e[3];for(var b=3,C=1;C<s;++C)g=i[d>>>24]^a[f>>>16&255]^o[h>>>8&255]^l[m&255]^e[++b],v=i[f>>>24]^a[h>>>16&255]^o[m>>>8&255]^l[d&255]^e[++b],w=i[h>>>24]^a[m>>>16&255]^o[d>>>8&255]^l[f&255]^e[++b],m=i[m>>>24]^a[d>>>16&255]^o[f>>>8&255]^l[h&255]^e[++b],d=g,f=v,h=w;r[0]=c[d>>>24]<<24^c[f>>>16&255]<<16^c[h>>>8&255]<<8^c[m&255]^e[++b],r[n?3:1]=c[f>>>24]<<24^c[h>>>16&255]<<16^c[m>>>8&255]<<8^c[d&255]^e[++b],r[2]=c[h>>>24]<<24^c[m>>>16&255]<<16^c[d>>>8&255]<<8^c[f&255]^e[++b],r[n?1:3]=c[m>>>24]<<24^c[d>>>16&255]<<16^c[f>>>8&255]<<8^c[h&255]^e[++b]}function mu(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),r="AES-"+t,n;e.decrypt?n=nr.cipher.createDecipher(r,e.key):n=nr.cipher.createCipher(r,e.key);var s=n.start;return n.start=function(i,a){var o=null;a instanceof nr.util.ByteBuffer&&(o=a,a={}),a=a||{},a.output=o,a.iv=i,s.call(n,a)},n}var ho=Pt;ho.pki=ho.pki||{};var $f=ho.pki.oids=ho.oids=ho.oids||{};function je(e,t){$f[e]=t,$f[t]=e}function Yt(e,t){$f[e]=t}je("1.2.840.113549.1.1.1","rsaEncryption");je("1.2.840.113549.1.1.4","md5WithRSAEncryption");je("1.2.840.113549.1.1.5","sha1WithRSAEncryption");je("1.2.840.113549.1.1.7","RSAES-OAEP");je("1.2.840.113549.1.1.8","mgf1");
10je("1.2.840.113549.1.1.9","pSpecified");je("1.2.840.113549.1.1.10","RSASSA-PSS");je("1.2.840.113549.1.1.11","sha256WithRSAEncryption");je("1.2.840.113549.1.1.12","sha384WithRSAEncryption");je("1.2.840.113549.1.1.13","sha512WithRSAEncryption");je("1.3.101.112","EdDSA25519");je("1.2.840.10040.4.3","dsa-with-sha1");je("1.3.14.3.2.7","desCBC");je("1.3.14.3.2.26","sha1");je("1.3.14.3.2.29","sha1WithRSASignature");je("2.16.840.1.101.3.4.2.1","sha256");je("2.16.840.1.101.3.4.2.2","sha384");je("2.16.840.1.101.3.4.2.3","sha512");je("2.16.840.1.101.3.4.2.4","sha224");je("2.16.840.1.101.3.4.2.5","sha512-224");je("2.16.840.1.101.3.4.2.6","sha512-256");je("1.2.840.113549.2.2","md2");je("1.2.840.113549.2.5","md5");je("1.2.840.113549.1.7.1","data");je("1.2.840.113549.1.7.2","signedData");je("1.2.840.113549.1.7.3","envelopedData");je("1.2.840.113549.1.7.4","signedAndEnvelopedData");je("1.2.840.113549.1.7.5","digestedData");je("1.2.840.113549.1.7.6","encryptedData");je("1.2.840.113549.1.9.1","emailAddress");je("1.2.840.113549.1.9.2","unstructuredName");je("1.2.840.113549.1.9.3","contentType");je("1.2.840.113549.1.9.4","messageDigest");je("1.2.840.113549.1.9.5","signingTime");je("1.2.840.113549.1.9.6","counterSignature");je("1.2.840.113549.1.9.7","challengePassword");je("1.2.840.113549.1.9.8","unstructuredAddress");je("1.2.840.113549.1.9.14","extensionRequest");je("1.2.840.113549.1.9.20","friendlyName");je("1.2.840.113549.1.9.21","localKeyId");je("1.2.840.113549.1.9.22.1","x509Certificate");je("1.2.840.113549.1.12.10.1.1","keyBag");je("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");je("1.2.840.113549.1.12.10.1.3","certBag");je("1.2.840.113549.1.12.10.1.4","crlBag");je("1.2.840.113549.1.12.10.1.5","secretBag");je("1.2.840.113549.1.12.10.1.6","safeContentsBag");je("1.2.840.113549.1.5.13","pkcs5PBES2");je("1.2.840.113549.1.5.12","pkcs5PBKDF2");je("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");je("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");je("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");je("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");je("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");je("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");je("1.2.840.113549.2.7","hmacWithSHA1");je("1.2.840.113549.2.8","hmacWithSHA224");je("1.2.840.113549.2.9","hmacWithSHA256");je("1.2.840.113549.2.10","hmacWithSHA384");je("1.2.840.113549.2.11","hmacWithSHA512");je("1.2.840.113549.3.7","des-EDE3-CBC");je("2.16.840.1.101.3.4.1.2","aes128-CBC");je("2.16.840.1.101.3.4.1.22","aes192-CBC");
10je("2.16.840.1.101.3.4.1.42","aes256-CBC");je("2.5.4.3","commonName");je("2.5.4.4","surname");je("2.5.4.5","serialNumber");je("2.5.4.6","countryName");je("2.5.4.7","localityName");je("2.5.4.8","stateOrProvinceName");je("2.5.4.9","streetAddress");je("2.5.4.10","organizationName");je("2.5.4.11","organizationalUnitName");je("2.5.4.12","title");je("2.5.4.13","description");je("2.5.4.15","businessCategory");je("2.5.4.17","postalCode");je("2.5.4.42","givenName");je("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");je("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");je("2.16.840.1.113730.1.1","nsCertType");je("2.16.840.1.113730.1.13","nsComment");Yt("2.5.29.1","authorityKeyIdentifier");Yt("2.5.29.2","keyAttributes");Yt("2.5.29.3","certificatePolicies");Yt("2.5.29.4","keyUsageRestriction");Yt("2.5.29.5","policyMapping");Yt("2.5.29.6","subtreesConstraint");Yt("2.5.29.7","subjectAltName");Yt("2.5.29.8","issuerAltName");Yt("2.5.29.9","subjectDirectoryAttributes");Yt("2.5.29.10","basicConstraints");Yt("2.5.29.11","nameConstraints");Yt("2.5.29.12","policyConstraints");Yt("2.5.29.13","basicConstraints");je("2.5.29.14","subjectKeyIdentifier");je("2.5.29.15","keyUsage");Yt("2.5.29.16","privateKeyUsagePeriod");je("2.5.29.17","subjectAltName");je("2.5.29.18","issuerAltName");je("2.5.29.19","basicConstraints");Yt("2.5.29.20","cRLNumber");Yt("2.5.29.21","cRLReason");Yt("2.5.29.22","expirationDate");Yt("2.5.29.23","instructionCode");
10Yt("2.5.29.24","invalidityDate");Yt("2.5.29.25","cRLDistributionPoints");Yt("2.5.29.26","issuingDistributionPoint");Yt("2.5.29.27","deltaCRLIndicator");Yt("2.5.29.28","issuingDistributionPoint");Yt("2.5.29.29","certificateIssuer");Yt("2.5.29.30","nameConstraints");je("2.5.29.31","cRLDistributionPoints");je("2.5.29.32","certificatePolicies");Yt("2.5.29.33","policyMappings");Yt("2.5.29.34","policyConstraints");je("2.5.29.35","authorityKeyIdentifier");Yt("2.5.29.36","policyConstraints");je("2.5.29.37","extKeyUsage");Yt("2.5.29.46","freshestCRL");Yt("2.5.29.54","inhibitAnyPolicy");je("1.3.6.1.4.1.11129.2.4.2","timestampList");je("1.3.6.1.5.5.7.1.1","authorityInfoAccess");je("1.3.6.1.5.5.7.3.1","serverAuth");je("1.3.6.1.5.5.7.3.2","clientAuth");je("1.3.6.1.5.5.7.3.3","codeSigning");je("1.3.6.1.5.5.7.3.4","emailProtection");je("1.3.6.1.5.5.7.3.8","timeStamping");var or=Pt,qe=or.asn1=or.asn1||{};qe.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};qe.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};qe.create=function(e,t,r,n,s){if(or.util.isArray(n)){for(var i=[],a=0;a<n.length;++a)n[a]!==void 0&&i.push(n[a]);n=i}var o={tagClass:e,type:t,constructed:r,composed:r||or.util.isArray(n),value:n};return s&&"bitStringContents"in s&&(o.bitStringContents=s.bitStringContents,o.original=qe.copy(o)),o};qe.copy=function(e,t){var r;if(or.util.isArray(e)){r=[];for(var n=0;n<e.length;++n)r.push(qe.copy(e[n],t));return r}return typeof e=="string"?e:(r={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:qe.copy(e.value,t)},t&&!t.excludeBitStringContents&&(r.bitStringContents=e.bitStringContents),r)};qe.equals=function(e,t,r){if(or.util.isArray(e)){if(!or.util.isArray(t)||e.length!==t.length)return!1;for(var n=0;n<e.length;++n)if(!qe.equals(e[n],t[n]))return!1;return!0}if(typeof e!=typeof t)return!1;if(typeof e=="string")return e===t;var s=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&qe.equals(e.value,t.value);return r&&r.includeBitStringContents&&(s=s&&e.bitStringContents===t.bitStringContents),s};qe.getBerValueLength=function(e){var t=e.getByte();if(t!==128){var r,n=t&128;return n?r=e.getInt((t&127)<<3):r=t,r}};function io(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}var kN=function(e,t){var r=e.getByte();if(t--,r!==128){var n,s=r&128;if(!s)n=r;else{var i=r&127;io(e,t,i),n=e.getInt(i<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};qe.fromDer=function(e,t){t===void 0&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof t=="boolean"&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),typeof e=="string"&&(e=or.util.createBuffer(e));var r=e.length(),n=ac(e,e.length(),0,t);if(t.parseAllBytes&&e.length()!==0){var s=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw s.byteCount=r,s.remaining=e.length(),s}return n};function ac(e,t,r,n){var s;io(e,t,2);var i=e.getByte();t--;var a=i&192,o=i&31;s=e.length();var l=kN(e,t);if(t-=s-e.length(),l!==void 0&&l>t){if(n.strict){var c=new Error("Too few bytes to read ASN.1 value.");throw c.available=e.length(),c.remaining=t,c.requested=l,c}l=t}var d,f,h=(i&32)===32;if(h)if(d=[],l===void 0)for(;;){if(io(e,t,2),e.bytes(2)==="\0\0"){e.getBytes(2),t-=2;break}s=e.length(),d.push(ac(e,t,r+1,n)),t-=s-e.length()}else for(;l>0;)s=e.length(),d.push(ac(e,l,r+1,n)),t-=s-e.length(),l-=s-e.length();if(d===void 0&&a===qe.Class.UNIVERSAL&&o===qe.Type.BITSTRING&&(f=e.bytes(l)),d===void 0&&n.decodeBitStrings&&a===qe.Class.UNIVERSAL&&o===qe.Type.BITSTRING&&l>1){var m=e.read,g=t,v=0;if(o===qe.Type.BITSTRING&&(io(e,t,1),v=e.getByte(),t--),v===0)try{s=e.length();var w={strict:!0,decodeBitStrings:!0},b=ac(e,t,r+1,w),C=s-e.length();t-=C,o==qe.Type.BITSTRING&&C++;var T=b.tagClass;C===l&&(T===qe.Class.UNIVERSAL||T===qe.Class.CONTEXT_SPECIFIC)&&(d=[b])}catch{}d===void 0&&(e.read=m,t=g)}if(d===void 0){if(l===void 0){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");l=t}
10if(o===qe.Type.BMPSTRING)for(d="";l>0;l-=2)io(e,t,2),d+=String.fromCharCode(e.getInt16()),t-=2;else d=e.getBytes(l),t-=l}var I=f===void 0?null:{bitStringContents:f};return qe.create(a,o,h,d,I)}qe.toDer=function(e){var t=or.util.createBuffer(),r=e.tagClass|e.type,n=or.util.createBuffer(),s=!1;if("bitStringContents"in e&&(s=!0,e.original&&(s=qe.equals(e,e.original))),s)n.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:n.putByte(0);for(var i=0;i<e.value.length;++i)e.value[i]!==void 0&&n.putBuffer(qe.toDer(e.value[i]))}else if(e.type===qe.Type.BMPSTRING)for(var i=0;i<e.value.length;++i)n.putInt16(e.value.charCodeAt(i));else e.type===qe.Type.INTEGER&&e.value.length>1&&(e.value.charCodeAt(0)===0&&!(e.value.charCodeAt(1)&128)||e.value.charCodeAt(0)===255&&(e.value.charCodeAt(1)&128)===128)?n.putBytes(e.value.substr(1)):n.putBytes(e.value);if(t.putByte(r),n.length()<=127)t.putByte(n.length()&127);else{var a=n.length(),o="";do o+=String.fromCharCode(a&255),a=a>>>8;while(a>0);t.putByte(o.length|128);for(var i=o.length-1;i>=0;--i)t.putByte(o.charCodeAt(i))}return t.putBuffer(n),t};qe.oidToDer=function(e){var t=e.split("."),r=or.util.createBuffer();r.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var n,s,i,a,o=2;o<t.length;++o){n=!0,s=[],i=parseInt(t[o],10);do a=i&127,i=i>>>7,n||(a|=128),s.push(a),n=!1;while(i>0);for(var l=s.length-1;l>=0;--l)r.putByte(s[l])}return r};qe.derToOid=function(e){var t;typeof e=="string"&&(e=or.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var n=0;e.length()>0;)r=e.getByte(),n=n<<7,r&128?n+=r&127:(t+="."+(n+r),n=0);return t};qe.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,s=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),a=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var l=e.charAt(10),c=10;l!=="+"&&l!=="-"&&(o=parseInt(e.substr(10,2),10),c+=2)}if(t.setUTCFullYear(r,n,s),t.setUTCHours(i,a,o,0),c&&(l=e.charAt(c),l==="+"||l==="-")){var d=parseInt(e.substr(c+1,2),10),f=parseInt(e.substr(c+4,2),10),h=d*60+f;h*=6e4,l==="+"?t.setTime(+t-h):t.setTime(+t+h)}return t};qe.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,s=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),a=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),l=0,c=0,d=!1;e.charAt(e.length-1)==="Z"&&(d=!0);var f=e.length-5,h=e.charAt(f);if(h==="+"||h==="-"){var m=parseInt(e.substr(f+1,2),10),g=parseInt(e.substr(f+4,2),10);c=m*60+g,c*=6e4,h==="+"&&(c*=-1),d=!0}return e.charAt(14)==="."&&(l=parseFloat(e.substr(14),10)*1e3),d?(t.setUTCFullYear(r,n,s),t.setUTCHours(i,a,o,l),t.setTime(+t+c)):(t.setFullYear(r,n,s),t.setHours(i,a,o,l)),t};qe.dateToUtcTime=function(e){if(typeof e=="string")return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+="Z",t};qe.dateToGeneralizedTime=function(e){if(typeof e=="string")return e;var t="",r=[];r.push(""+e.getUTCFullYear()),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+="Z",t};qe.integerToDer=function(e){var t=or.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r};qe.derToInteger=function(e){typeof e=="string"&&(e=or.util.createBuffer(e));var t=e.length()*8;if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};qe.validate=function(e,t,r,n){var s=!1;if((e.tagClass===t.tagClass||typeof t.tagClass>"u")&&(e.type===t.type||typeof t.type>"u"))if(e.constructed===t.constructed||typeof t.constructed>"u"){if(s=!0,t.value&&or.util.isArray(t.value))for(var i=0,a=0;s&&a<t.value.length;++a)s=t.value[a].optional||!1,e.value[i]&&(s=qe.validate(e.value[i],t.value[a],r,n),s?++i:t.value[a].optional&&(s=!0)),!s&&n&&n.push("["+t.name+'] Tag class "'+t.tagClass+'", type "'+t.type+'" expected value length "'+t.value.length+'", got "'+e.value.length+'"');if(s&&r&&(t.capture&&(r[t.capture]=e.value),t.captureAsn1&&(r[t.captureAsn1]=e),t.captureBitStringContents&&"bitStringContents"in e&&(r[t.captureBitStringContents]=e.bitStringContents),t.captureBitStringValue&&"bitStringContents"in e))if(e.bitStringContents.length<2)r[t.captureBitStringValue]="";
10else{var o=e.bitStringContents.charCodeAt(0);if(o!==0)throw new Error("captureBitStringValue only supported for zero unused bits");r[t.captureBitStringValue]=e.bitStringContents.slice(1)}}else n&&n.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"');else n&&(e.tagClass!==t.tagClass&&n.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&n.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));return s};var $g=/[^\\u0000-\\u00ff]/;qe.prettyPrint=function(e,t,r){var n="";t=t||0,r=r||2,t>0&&(n+=`
11`);for(var s="",i=0;i<t*r;++i)s+=" ";switch(n+=s+"Tag: ",e.tagClass){case qe.Class.UNIVERSAL:n+="Universal:";break;case qe.Class.APPLICATION:n+="Application:";break;case qe.Class.CONTEXT_SPECIFIC:n+="Context-Specific:";break;case qe.Class.PRIVATE:n+="Private:";break}if(e.tagClass===qe.Class.UNIVERSAL)switch(n+=e.type,e.type){case qe.Type.NONE:n+=" (None)";break;case qe.Type.BOOLEAN:n+=" (Boolean)";break;case qe.Type.INTEGER:n+=" (Integer)";break;case qe.Type.BITSTRING:n+=" (Bit string)";break;case qe.Type.OCTETSTRING:n+=" (Octet string)";break;case qe.Type.NULL:n+=" (Null)";break;case qe.Type.OID:n+=" (Object Identifier)";break;case qe.Type.ODESC:n+=" (Object Descriptor)";break;case qe.Type.EXTERNAL:n+=" (External or Instance of)";break;case qe.Type.REAL:n+=" (Real)";break;case qe.Type.ENUMERATED:n+=" (Enumerated)";break;case qe.Type.EMBEDDED:n+=" (Embedded PDV)";break;case qe.Type.UTF8:n+=" (UTF8)";break;case qe.Type.ROID:n+=" (Relative Object Identifier)";break;case qe.Type.SEQUENCE:n+=" (Sequence)";break;case qe.Type.SET:n+=" (Set)";break;case qe.Type.PRINTABLESTRING:n+=" (Printable String)";break;case qe.Type.IA5String:n+=" (IA5String (ASCII))";break;case qe.Type.UTCTIME:n+=" (UTC time)";break;case qe.Type.GENERALIZEDTIME:n+=" (Generalized time)";break;case qe.Type.BMPSTRING:n+=" (BMP String)";break}else n+=e.type;if(n+=`
12`,n+=s+"Constructed: "+e.constructed+`
13`,e.composed){for(var a=0,o="",i=0;i<e.value.length;++i)e.value[i]!==void 0&&(a+=1,o+=qe.prettyPrint(e.value[i],t+1,r),i+1<e.value.length&&(o+=","));n+=s+"Sub values: "+a+o}else{if(n+=s+"Value: ",e.type===qe.Type.OID){var l=qe.derToOid(e.value);n+=l,or.pki&&or.pki.oids&&l in or.pki.oids&&(n+=" ("+or.pki.oids[l]+") ")}if(e.type===qe.Type.INTEGER)try{n+=qe.derToInteger(e.value)}catch{n+="0x"+or.util.bytesToHex(e.value)}else if(e.type===qe.Type.BITSTRING){if(e.value.length>1?n+="0x"+or.util.bytesToHex(e.value.slice(1)):n+="(none)",e.value.length>0){var c=e.value.charCodeAt(0);c==1?n+=" (1 unused bit shown)":c>1&&(n+=" ("+c+" unused bits shown)")}}else if(e.type===qe.Type.OCTETSTRING)$g.test(e.value)||(n+="("+e.value+") "),n+="0x"+or.util.bytesToHex(e.value);else if(e.type===qe.Type.UTF8)try{n+=or.util.decodeUtf8(e.value)}catch(d){if(d.message==="URI malformed")n+="0x"+or.util.bytesToHex(e.value)+" (malformed UTF8)";else throw d}else e.type===qe.Type.PRINTABLESTRING||e.type===qe.Type.IA5String?n+=e.value:$g.test(e.value)?n+="0x"+or.util.bytesToHex(e.value):e.value.length===0?n+="[null]":n+=e.value}return n};var Cc=Pt;Cc.md=Cc.md||{};Cc.md.algorithms=Cc.md.algorithms||{};var ws=Pt,NN=ws.hmac=ws.hmac||{};NN.create=function(){var e=null,t=null,r=null,n=null,s={};return s.start=function(i,a){if(i!==null)if(typeof i=="string")if(i=i.toLowerCase(),i in ws.md.algorithms)t=ws.md.algorithms[i].create();else throw new Error('Unknown hash algorithm "'+i+'"');else t=i;if(a===null)a=e;else{if(typeof a=="string")a=ws.util.createBuffer(a);else if(ws.util.isArray(a)){var o=a;a=ws.util.createBuffer();for(var l=0;l<o.length;++l)a.putByte(o[l])}var c=a.length();c>t.blockLength&&(t.start(),t.update(a.bytes()),a=t.digest()),r=ws.util.createBuffer(),n=ws.util.createBuffer(),c=a.length();for(var l=0;l<c;++l){var o=a.at(l);r.putByte(54^o),n.putByte(92^o)}if(c<t.blockLength)for(var o=t.blockLength-c,l=0;l<o;++l)r.putByte(54),n.putByte(92);e=a,r=r.bytes(),n=n.bytes()}t.start(),t.update(r)},s.update=function(i){t.update(i)},s.getMac=function(){var i=t.digest().bytes();return t.start(),t.update(n),t.update(i),t.digest()},s.digest=s.getMac,s};var ts=Pt,d1=ts.md5=ts.md5||{};ts.md.md5=ts.md.algorithms.md5=d1;d1.create=function(){f1||RN();var e=null,t=ts.util.createBuffer(),r=new Array(16),n={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var s=n.messageLengthSize/4,i=0;i<s;++i)n.fullMessageLength.push(0);return t=ts.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},n},n.start(),n.update=function(s,i){i==="utf8"&&(s=ts.util.encodeUtf8(s));var a=s.length;n.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=n.fullMessageLength.length-1;o>=0;--o)n.fullMessageLength[o]+=a[1],a[1]=a[0]+(n.fullMessageLength[o]/4294967296>>>0),n.fullMessageLength[o]=n.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),zg(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var s=ts.util.createBuffer();s.putBytes(t.bytes());var i=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,a=i&n.blockLength-1;s.putBytes(zf.substr(0,n.blockLength-a));for(var o,l=0,c=n.fullMessageLength.length-1;c>=0;--c)o=n.fullMessageLength[c]*8+l,l=o/4294967296>>>0,s.putInt32Le(o>>>0);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};zg(d,r,s);var f=ts.util.createBuffer();return f.putInt32Le(d.h0),f.putInt32Le(d.h1),f.putInt32Le(d.h2),f.putInt32Le(d.h3),f},n};var zf=null,oc=null,ao=null,ca=null,f1=!1;function RN(){zf="€",zf+=ts.util.fillString("\0",64),oc=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],ao=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],ca=new Array(64);for(var e=0;e<64;++e)ca[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);f1=!0}function zg(e,t,r){for(var n,s,i,a,o,l,c,d,f=r.length();f>=64;){for(s=e.h0,i=e.h1,a=e.h2,o=e.h3,d=0;d<16;++d)t[d]=r.getInt32Le(),l=o^i&(a^o),n=s+l+ca[d]+t[d],c=ao[d],s=o,o=a,a=i,i+=n<<c|n>>>32-c;for(;d<32;++d)l=a^o&(i^a),n=s+l+ca[d]+t[oc[d]],c=ao[d],s=o,o=a,a=i,i+=n<<c|n>>>32-c;for(;d<48;++d)l=i^a^o,n=s+l+ca[d]+t[oc[d]],c=ao[d],s=o,o=a,a=i,i+=n<<c|n>>>32-c;for(;d<64;++d)l=a^(i|~o),n=s+l+ca[d]+t[oc[d]],c=ao[d],s=o,o=a,a=i,i+=n<<c|n>>>32-c;e.h0=e.h0+s|0,e.h1=e.h1+i|0,e.h2=e.h2+a|0,e.h3=e.h3+o|0,f-=64}}var Sc=Pt,h1=Sc.pem=Sc.pem||{};h1.encode=function(e,t){t=t||{};var r="-----BEGIN "+e.type+`-----\r
14`,n;if(e.procType&&(n={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},r+=jl(n)),e.contentDomain&&(n={name:"Content-Domain",values:[e.contentDomain]},r+=jl(n)),e.dekInfo&&(n={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&n.values.push(e.dekInfo.parameters),r+=jl(n)),e.headers)for(var s=0;s<e.headers.length;++s)r+=jl(e.headers[s]);return e.procType&&(r+=`\r
15`),r+=Sc.util.encode64(e.body,t.maxline||64)+`\r
16`,r+="-----END "+e.type+`-----\r
17`,r};h1.decode=function(e){for(var t=[],r=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,n=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,s=/\r?\n/,i;i=r.exec(e),!!i;){var a=i[1];a==="NEW CERTIFICATE REQUEST"&&(a="CERTIFICATE REQUEST");var o={type:a,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Sc.util.decode64(i[3])};if(t.push(o),!!i[2]){for(var l=i[2].split(s),c=0;i&&c<l.length;){for(var d=l[c].replace(/\s+$/,""),f=c+1;f<l.length;++f){var h=l[f];if(!/\s/.test(h[0]))break;d+=h,c=f}if(i=d.match(n),i){for(var m={name:i[1],values:[]},g=i[2].split(","),v=0;v<g.length;++v)m.values.push(PN(g[v]));if(o.procType)if(!o.contentDomain&&m.name==="Content-Domain")o.contentDomain=g[0]||"";else if(!o.dekInfo&&m.name==="DEK-Info"){if(m.values.length===0)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');o.dekInfo={algorithm:g[0],parameters:g[1]||null}}else o.headers.push(m);else{if(m.name!=="Proc-Type")throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(m.values.length!==2)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');o.procType={version:g[0],type:g[1]}}}++c}if(o.procType==="ENCRYPTED"&&!o.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(t.length===0)throw new Error("Invalid PEM formatted message.");return t};function jl(e){for(var t=e.name+": ",r=[],n=function(l,c){return" "+c},s=0;s<e.values.length;++s)r.push(e.values[s].replace(/^(\S+\r\n)/,n));t+=r.join(",")+`\r
18`;for(var i=0,a=-1,s=0;s<t.length;++s,++i)if(i>65&&a!==-1){var o=t[a];o===","?(++a,t=t.substr(0,a)+`\r
19 `+t.substr(a)):t=t.substr(0,a)+`\r
20`+o+t.substr(a+1),i=s-a-1,a=-1,++s}else(t[s]===" "||t[s]==="	"||t[s]===",")&&(a=s);return t}function PN(e){return e.replace(/^\s+/,"")}var dr=Pt;
20dr.des=dr.des||{};dr.des.startEncrypting=function(e,t,r,n){var s=gu({key:e,output:r,decrypt:!1,mode:n||(t===null?"ECB":"CBC")});return s.start(t),s};dr.des.createEncryptionCipher=function(e,t){return gu({key:e,output:null,decrypt:!1,mode:t})};dr.des.startDecrypting=function(e,t,r,n){var s=gu({key:e,output:r,decrypt:!0,mode:n||(t===null?"ECB":"CBC")});return s.start(t),s};dr.des.createDecryptionCipher=function(e,t){return gu({key:e,output:null,decrypt:!0,mode:t})};dr.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(n,s){return Kg(r._keys,n,s,!1)},decrypt:function(n,s){return Kg(r._keys,n,s,!0)}}}),r._init=!1};dr.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=dr.util.createBuffer(e.key);if(this.name.indexOf("3DES")===0&&t.length()!==24)throw new Error("Invalid Triple-DES key size: "+t.length()*8);this._keys=VN(t),this._init=!0}};ds("DES-ECB",dr.cipher.modes.ecb);ds("DES-CBC",dr.cipher.modes.cbc);ds("DES-CFB",dr.cipher.modes.cfb);ds("DES-OFB",dr.cipher.modes.ofb);ds("DES-CTR",dr.cipher.modes.ctr);ds("3DES-ECB",dr.cipher.modes.ecb);ds("3DES-CBC",dr.cipher.modes.cbc);ds("3DES-CFB",dr.cipher.modes.cfb);ds("3DES-OFB",dr.cipher.modes.ofb);ds("3DES-CTR",dr.cipher.modes.ctr);function ds(e,t){var r=function(){return new dr.des.Algorithm(e,t)};dr.cipher.registerAlgorithm(e,r)}var jN=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],BN=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],DN=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],LN=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],MN=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],ON=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,164
2000,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],FN=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],UN=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function VN(e){for(var t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],s=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],i=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],c=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],d=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],m=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],v=e.length()>8?3:1,w=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],C=0,T,I=0;I<v;I++){var k=e.getInt32(),_=e.getInt32();T=(k>>>4^_)&252645135,_^=T,k^=T<<4,T=(_>>>-16^k)&65535,k^=T,_^=T<<-16,T=(k>>>2^_)&858993459,_^=T,k^=T<<2,T=(_>>>-16^k)&65535,k^=T,_^=T<<-16,T=(k>>>1^_)&1431655765,_^=T,k^=T<<1,T=(_>>>8^k)&16711935,k^=T,_^=T<<8,T=(k>>>1^_)&1431655765,_^=T,k^=T<<1,T=k<<8|_>>>20&240,k=_<<24|_<<8&16711680|_>>>8&65280|_>>>24&240,_=T;for(var M=0;M<b.length;++M){b[M]?(k=k<<2|k>>>26,_=_<<2|_>>>26):(k=k<<1|k>>>27,_=_<<1|_>>>27),k&=-15,_&=-15;var V=t[k>>>28]|r[k>>>24&15]|n[k>>>20&15]|s[k>>>16&15]|i[k>>>12&15]|a[k>>>8&15]|o[k>>>4&15],G=l[_>>>28]|c[_>>>24&15]|d[_>>>20&15]|f[_>>>16&15]|h[_>>>12&15]|m[_>>>8&15]|g[_>>>4&15];T=(G>>>16^V)&65535,w[C++]=V^T,w[C++]=G^T<<16}}return w}function Kg(e,t,r,n){var s=e.length===32?3:9,i;s===3?i=n?[30,-2,-2]:[0,32,2]:i=n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var a,o=t[0],l=t[1];a=(o>>>4^l)&252645135,l^=a,o^=a<<4,a=(o>>>16^l)&65535,l^=a,o^=a<<16,a=(l>>>2^o)&858993459,o^=a,l^=a<<2,a=(l>>>8^o)&16711935,o^=a,l^=a<<8,a=(o>>>1^l)&1431655765,l^=a,o^=a<<1,o=o<<1|o>>>31,l=l<<1|l>>>31;for(var c=0;c<s;c+=3){for(var d=i[c+1],f=i[c+2],h=i[c];h!=d;h+=f){var m=l^e[h],g=(l>>>4|l<<28)^e[h+1];a=o,o=l,l=a^(BN[m>>>24&63]|LN[m>>>16&63]|ON[m>>>8&63]|UN[m&63]|jN[g>>>24&63]|DN[g>>>16&63]|MN[g>>>8&63]|FN[g&63])}a=o,o=l,l=a}o=o>>>1|o<<31,l=l>>>1|l<<31,a=(o>>>1^l)&1431655765,l^=a,o^=a<<1,a=(l>>>8^o)&16711935,o^=a,l^=a<<8,a=(l>>>2^o)&858993459,o^=a,l^=a<<2,a=(o>>>16^l)&65535,l^=a,o^=a<<16,a=(o>>>4^l)&252645135,l^=a,o^=a<<4,r[0]=o,r[1]=l}function gu(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),r="DES-"+t,n;e.decrypt?n=dr.cipher.createDecipher(r,e.key):n=dr.cipher.createCipher(r,e.key);var s=n.start;return n.start=function(i,a){var o=null;a instanceof dr.util.ByteBuffer&&(o=a,a={}),a=a||{},a.output=o,a.iv=i,s.call(n,a)},n}var Hr=Pt,$N=Hr.pkcs5=Hr.pkcs5||{},bs;Hr.util.isNodejs&&!Hr.options.usePureJavaScript&&(bs=Fh);Hr.pbkdf2=$N.pbkdf2=function(e,t,r,n,s,i){if(typeof s=="function"&&(i=s,s=null),Hr.util.isNodejs&&!Hr.options.usePureJavaScript&&bs.pbkdf2&&(s===null||typeof s!="object")&&(bs.pbkdf2Sync.length>
204||!s||s==="sha1"))return typeof s!="string"&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),i?bs.pbkdf2Sync.length===4?bs.pbkdf2(e,t,r,n,function(T,I){if(T)return i(T);i(null,I.toString("binary"))}):bs.pbkdf2(e,t,r,n,s,function(T,I){if(T)return i(T);i(null,I.toString("binary"))}):bs.pbkdf2Sync.length===4?bs.pbkdf2Sync(e,t,r,n).toString("binary"):bs.pbkdf2Sync(e,t,r,n,s).toString("binary");if((typeof s>"u"||s===null)&&(s="sha1"),typeof s=="string"){if(!(s in Hr.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=Hr.md[s].create()}var a=s.digestLength;if(n>4294967295*a){var o=new Error("Derived key is too long.");if(i)return i(o);throw o}var l=Math.ceil(n/a),c=n-(l-1)*a,d=Hr.hmac.create();d.start(s,e);var f="",h,m,g;if(!i){for(var v=1;v<=l;++v){d.start(null,null),d.update(t),d.update(Hr.util.int32ToBytes(v)),h=g=d.digest().getBytes();for(var w=2;w<=r;++w)d.start(null,null),d.update(g),m=d.digest().getBytes(),h=Hr.util.xorBytes(h,m,a),g=m;f+=v<l?h:h.substr(0,c)}return f}var v=1,w;function b(){if(v>l)return i(null,f);d.start(null,null),d.update(t),d.update(Hr.util.int32ToBytes(v)),h=g=d.digest().getBytes(),w=2,C()}function C(){if(w<=r)return d.start(null,null),d.update(g),m=d.digest().getBytes(),h=Hr.util.xorBytes(h,m,a),g=m,++w,Hr.util.setImmediate(C);f+=v<l?h:h.substr(0,c),++v,b()}b()};var rs=Pt,p1=rs.sha256=rs.sha256||{};rs.md.sha256=rs.md.algorithms.sha256=p1;p1.create=function(){m1||zN();var e=null,t=rs.util.createBuffer(),r=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var s=n.messageLengthSize/4,i=0;i<s;++i)n.fullMessageLength.push(0);return t=rs.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},n},n.start(),n.update=function(s,i){i==="utf8"&&(s=rs.util.encodeUtf8(s));var a=s.length;n.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=n.fullMessageLength.length-1;o>=0;--o)n.fullMessageLength[o]+=a[1],a[1]=a[0]+(n.fullMessageLength[o]/4294967296>>>0),n.fullMessageLength[o]=n.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),qg(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var s=rs.util.createBuffer();s.putBytes(t.bytes());var i=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,a=i&n.blockLength-1;s.putBytes(Kf.substr(0,n.blockLength-a));for(var o,l,c=n.fullMessageLength[0]*8,d=0;d<n.fullMessageLength.length-1;++d)o=n.fullMessageLength[d+1]*8,l=o/4294967296>>>0,c+=l,s.putInt32(c>>>0),c=o>>>0;s.putInt32(c);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};qg(f,r,s);var h=rs.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},n};var Kf=null,m1=!1,g1=null;function zN(){Kf="€",Kf+=rs.util.fillString("\0",64),g1=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],m1=!0}function qg(e,t,r){for(var n,s,i,a,o,l,c,d,f,h,m,g,v,w,b,C=r.length();C>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=t[c-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,s=t[c-15],s=(s>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,t[c]=n+t[c-7]+s+t[c-16]|0;for(d=e.h0,f=e.h1,h=e.h2,m=e.h3,g=e.h4,v=e.h5,w=e.h6,b=e.h7,c=0;c<64;++c)a=(g>>>6|g<<26)^(g>>>11|g<<21)^(g>>>25|g<<7),o=w^g&(v^w),i=(d>>>2|d<<30)^(d>>>13|d<<19)^(d>>>22|d<<10),l=d&f|h&(d^f),n=b+a+o+g1[c]+t[c],s=i+l,b=w,w=v,v=g,g=m+n>>>0,m=h,h=f,f=d,d=n+s>>>0;e.h0=e.h0+d|0,e.h1=e.h1+f|0,e.h2=e.h2+h|0,e.h3=e.h3+m|0,e.h4=e.h4+g|0,e.h5=e.h5+v|0,e.h6=e.h6+w|0,e.h7=e.h7+b|0,C-=64}}var Jn=Pt,lc=null;Jn.util.isNodejs&&!Jn.options.usePureJavaScript&&!process.versions["node-webkit"]&&(lc=Fh);var KN=Jn.prng=Jn.prng||{};
20KN.create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,n=new Array(32),s=0;s<32;++s)n[s]=r.create();t.pools=n,t.pool=0,t.generate=function(c,d){if(!d)return t.generateSync(c);var f=t.plugin.cipher,h=t.plugin.increment,m=t.plugin.formatKey,g=t.plugin.formatSeed,v=Jn.util.createBuffer();t.key=null,w();function w(b){if(b)return d(b);if(v.length()>=c)return d(null,v.getBytes(c));if(t.generated>1048575&&(t.key=null),t.key===null)return Jn.util.nextTick(function(){i(w)});var C=f(t.key,t.seed);t.generated+=C.length,v.putBytes(C),t.key=m(f(t.key,h(t.seed))),t.seed=g(f(t.key,t.seed)),Jn.util.setImmediate(w)}},t.generateSync=function(c){var d=t.plugin.cipher,f=t.plugin.increment,h=t.plugin.formatKey,m=t.plugin.formatSeed;t.key=null;for(var g=Jn.util.createBuffer();g.length()<c;){t.generated>1048575&&(t.key=null),t.key===null&&a();var v=d(t.key,t.seed);t.generated+=v.length,g.putBytes(v),t.key=h(d(t.key,f(t.seed))),t.seed=m(d(t.key,t.seed))}return g.getBytes(c)};function i(c){if(t.pools[0].messageLength>=32)return o(),c();var d=32-t.pools[0].messageLength<<5;t.seedFile(d,function(f,h){if(f)return c(f);t.collect(h),o(),c()})}function a(){if(t.pools[0].messageLength>=32)return o();var c=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(c)),o()}function o(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var c=t.plugin.md.create();c.update(t.keyBytes);for(var d=1,f=0;f<32;++f)t.reseeds%d===0&&(c.update(t.pools[f].digest().getBytes()),t.pools[f].start()),d=d<<1;t.keyBytes=c.digest().getBytes(),c.start(),c.update(t.keyBytes);var h=c.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(h),t.generated=0}function l(c){var d=null,f=Jn.util.globalScope,h=f.crypto||f.msCrypto;h&&h.getRandomValues&&(d=function(k){return h.getRandomValues(k)});var m=Jn.util.createBuffer();if(d)for(;m.length()<c;){var g=Math.max(1,Math.min(c-m.length(),65536)/4),v=new Uint32Array(Math.floor(g));try{d(v);for(var w=0;w<v.length;++w)m.putInt32(v[w])}catch(k){if(!(typeof QuotaExceededError<"u"&&k instanceof QuotaExceededError))throw k}}if(m.length()<c)for(var b,C,T,I=Math.floor(Math.random()*65536);m.length()<c;){C=16807*(I&65535),b=16807*(I>>16),C+=(b&32767)<<16,C+=b>>15,C=(C&2147483647)+(C>>31),I=C&4294967295;for(var w=0;w<3;++w)T=I>>>(w<<3),T^=Math.floor(Math.random()*256),m.putByte(T&255)}return m.getBytes(c)}return lc?(t.seedFile=function(c,d){lc.randomBytes(c,function(f,h){if(f)return d(f);d(null,h.toString())})},t.seedFileSync=function(c){return lc.randomBytes(c).toString()}):(t.seedFile=function(c,d){try{d(null,l(c))}catch(f){d(f)}},t.seedFileSync=l),t.collect=function(c){for(var d=c.length,f=0;f<d;++f)t.pools[t.pool].update(c.substr(f,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(c,d){for(var f="",h=0;h<d;h+=8)f+=String.fromCharCode(c>>h&255);t.collect(f)},t.registerWorker=function(c){if(c===self)t.seedFile=function(f,h){function m(g){var v=g.data;v.forge&&v.forge.prng&&(self.removeEventListener("message",m),h(v.forge.prng.err,v.forge.prng.bytes))}self.addEventListener("message",m),self.postMessage({forge:{prng:{needed:f}}})};else{var d=function(f){var h=f.data;h.forge&&h.forge.prng&&t.seedFile(h.forge.prng.needed,function(m,g){c.postMessage({forge:{prng:{err:m,bytes:g}}})})};c.addEventListener("message",d)}},t};var _r=Pt;(function(){if(_r.random&&_r.random.getBytes){_r.random;return}(function(e){var t={},r=new Array(4),n=_r.util.createBuffer();t.formatKey=function(f){var h=_r.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),_r.aes._expandKey(f,!1)},t.formatSeed=function(f){var h=_r.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),f},t.cipher=function(f,h){return _r.aes._updateBlock(f,h,r,!1),n.putInt32(r[0]),n.putInt32(r[1]),n.putInt32(r[2]),n.putInt32(r[3]),n.getBytes()},t.increment=function(f){return++f[3],f},t.md=_r.md.sha256;function s(){var f=_r.prng.create(t);return f.getBytes=function(h,m){return f.generate(h,m)},f.getBytesSync=function(h){return f.generate(h)},f}var i=s(),a=null,o=_r.util.globalScope,l=o.crypto||o.msCrypto;if(l&&l.getRandomValues&&(a=function(f){return l.getRandomValues(f)}),_r.options.usePureJavaScript||!_r.util.isNodejs&&!a){if(i.collectInt(+new Date,32),typeof navigator<"u"){var c="";for(var d in navigator)try{typeof navigator[d]=="string"&&(c+=navigator[d])}catch{}i.collect(c),c=null}e&&(e().mousemove(function(f){i.collectInt(f.clientX,16),i.collectInt(f.clientY,16)}),e().keypress(function(f){i.collectInt(f.charCode,8)}))}if(!_r.random)_r.random=i;else for(var d in i)_r.random[d]=i[d];_r.random.createInstance=s,_r.random})(typeof jQuery<"u"?jQuery:null)})();var nn=Pt,Ad=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,23
206,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],Hg=[1,2,3,5],qN=function(e,t){return e<<t&65535|(e&65535)>>16-t},HN=function(e,t){return(e&65535)>>t|e<<16-t&65535};nn.rc2=nn.rc2||{};nn.rc2.expandKey=function(e,t){typeof e=="string"&&(e=nn.util.createBuffer(e)),t=t||128;var r=e,n=e.length(),s=t,i=Math.ceil(s/8),a=255>>(s&7),o;for(o=n;o<128;o++)r.putByte(Ad[r.at(o-1)+r.at(o-n)&255]);for(r.setAt(128-i,Ad[r.at(128-i)&a]),o=127-i;o>=0;o--)r.setAt(o,Ad[r.at(o+1)^r.at(o+i)]);return r};var y1=function(e,t,r){var n=!1,s=null,i=null,a=null,o,l,c,d,f=[];for(e=nn.rc2.expandKey(e,t),c=0;c<64;c++)f.push(e.getInt16Le());r?(o=function(g){for(c=0;c<4;c++)g[c]+=f[d]+(g[(c+3)%4]&g[(c+2)%4])+(~g[(c+3)%4]&g[(c+1)%4]),g[c]=qN(g[c],Hg[c]),d++},l=function(g){for(c=0;c<4;c++)g[c]+=f[g[(c+3)%4]&63]}):(o=function(g){for(c=3;c>=0;c--)g[c]=HN(g[c],Hg[c]),g[c]-=f[d]+(g[(c+3)%4]&g[(c+2)%4])+(~g[(c+3)%4]&g[(c+1)%4]),d--},l=function(g){for(c=3;c>=0;c--)g[c]-=f[g[(c+3)%4]&63]});var h=function(g){var v=[];for(c=0;c<4;c++){var w=s.getInt16Le();a!==null&&(r?w^=a.getInt16Le():a.putInt16Le(w)),v.push(w&65535)}d=r?0:63;for(var b=0;b<g.length;b++)for(var C=0;C<g[b][0];C++)g[b][1](v);for(c=0;c<4;c++)a!==null&&(r?a.putInt16Le(v[c]):v[c]^=a.getInt16Le()),i.putInt16Le(v[c])},m=null;return m={start:function(g,v){g&&typeof g=="string"&&(g=nn.util.createBuffer(g)),n=!1,s=nn.util.createBuffer(),i=v||new nn.util.createBuffer,a=g,m.output=i},update:function(g){for(n||s.putBuffer(g);s.length()>=8;)h([[5,o],[1,l],[6,o],[1,l],[5,o]])},finish:function(g){var v=!0;if(r)if(g)v=g(8,s,!r);else{var w=s.length()===8?8:8-s.length();s.fillWithByte(w,w)}if(v&&(n=!0,m.update()),!r&&(v=s.length()===0,v))if(g)v=g(8,i,!r);else{var b=i.length(),C=i.at(b-1);C>b?v=!1:i.truncate(C)}return v}},m};nn.rc2.startEncrypting=function(e,t,r){var n=nn.rc2.createEncryptionCipher(e,128);return n.start(t,r),n};nn.rc2.createEncryptionCipher=function(e,t){return y1(e,t,!0)};nn.rc2.startDecrypting=function(e,t,r){var n=nn.rc2.createDecryptionCipher(e,128);return n.start(t,r),n};nn.rc2.createDecryptionCipher=function(e,t){return y1(e,t,!1)};var qf=Pt;qf.jsbn=qf.jsbn||{};var Ss;function Ae(e,t,r){this.data=[],e!=null&&(typeof e=="number"?this.fromNumber(e,t,r):t==null&&typeof e!="string"?this.fromString(e,256):this.fromString(e,t))}qf.jsbn.BigInteger=Ae;function Kt(){return new Ae(null)}function GN(e,t,r,n,s,i){for(;--i>=0;){var a=t*this.data[e++]+r.data[n]+s;s=Math.floor(a/67108864),r.data[n++]=a&67108863}return s}function WN(e,t,r,n,s,i){for(var a=t&32767,o=t>>15;--i>=0;){var l=this.data[e]&32767,c=this.data[e++]>>15,d=o*l+c*a;l=a*l+((d&32767)<<15)+r.data[n]+(s&1073741823),s=(l>>>30)+(d>>>15)+o*c+(s>>>30),r.data[n++]=l&1073741823}return s}function Gg(e,t,r,n,s,i){for(var a=t&16383,o=t>>14;--i>=0;){var l=this.data[e]&16383,c=this.data[e++]>>14,d=o*l+c*a;l=a*l+((d&16383)<<14)+r.data[n]+s,s=(l>>28)+(d>>14)+o*c,r.data[n++]=l&268435455}return s}typeof navigator>"u"?(Ae.prototype.am=Gg,Ss=28):navigator.appName=="Microsoft Internet Explorer"?(Ae.prototype.am=WN,Ss=30):navigator.appName!="Netscape"?(Ae.prototype.am=GN,Ss=26):(Ae.prototype.am=Gg,Ss=28);Ae.prototype.DB=Ss;Ae.prototype.DM=(1<<Ss)-1;Ae.prototype.DV=1<<Ss;var wp=52;Ae.prototype.FV=Math.pow(2,wp);Ae.prototype.F1=wp-Ss;Ae.prototype.F2=2*Ss-wp;var YN="0123456789abcdefghijklmnopqrstuvwxyz",yu=new Array,Aa,Tn;Aa=48;for(Tn=0;Tn<=9;++Tn)yu[Aa++]=Tn;Aa=97;for(Tn=10;Tn<36;++Tn)yu[Aa++]=Tn;Aa=65;for(Tn=10;Tn<36;++Tn)yu[Aa++]=Tn;function Wg(e){return YN.charAt(e)}function v1(e,t){var r=yu[e.charCodeAt(t)];return r??-1}function QN(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function XN(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function Gs(e){var t=Kt();return t.fromInt(e),t}function JN(e,t){var r;if(t==16)r=4;else if(t==8)r=3;else if(t==256)r=8;else if(t==2)r=1;else if(t==32)r=5;else if(t==4)r=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var n=e.length,s=!1,i=0;--n>=0;){var a=r==8?e[n]&255:v1(e,n);if(a<0){e.charAt(n)=="-"&&(s=!0);continue}s=!1,i==0?this.data[this.t++]=a:i+r>this.DB?(this.data[this.t-1]|=(a&(1<<this.DB-i)-1)<<i,this.data[this.t++]=a>>this.DB-i):this.data[this.t-1]|=a<<i,i+=r,i>=this.DB&&(i-=this.DB)}r==8&&e[0]&128&&(this.s=-1,i>0&&(this.data[this.t-1]|=(1<<this.DB-i)-1<<i)),this.clamp(),s&&Ae.ZERO.subTo(this,this)}function ZN(){for(var e=this.s&this.DM;this.t>0&&this.data[this.t-1]==e;)--this.t}function e4(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var r=(1<<t)-1,n,s=!1,i="",a=this.t,o=this.DB-a*this.DB%t;if(a-- >0)for(o<this.DB&&(n=this.data[a]>>o)>0&&(s=!0,i=Wg(n));a>=0;)o<t?(n=(this.data[a]&(1<<o)-1)<<t-o,n|=this.data[--a]>>(o+=this.DB-t)):(n=this.data[a]>>(o-=t)&r,o<=0&&(o+=this.DB,--a)),n>0&&(s=!0),s&&(i+=Wg(n));return s?i:"0"}function t4(){var e=Kt();return Ae.ZERO.subTo(this,e),e}function r4(){return this.s<0?this.negate():this}function n4(e){var t=this.s-e.s;if(t!=0)return t;var r=this.t;if(t=r-e.t,t!=0)return this.s<0?-t:t;for(;--r>=0;)if((t=this.data[r]-e.data[r])!=0)return t;return 0}function vu(e){var t=1,r;return(r=e>>>16)!=0&&(e=r,t+=16),(r=e>>8)!=0&&(e=r,t+=8),(r=e>>4)!=0&&(e=r,t+=4),(r=e>>2)!=0&&(e=r,t+=2),(r=e>>1)!=0&&(e=r,t+=1),t}function s4(){return this.t<=0?0:this.DB*(this.t-1)+vu(this.data[this.t-1]^this.s&this.DM)}function i4(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s}function a4(e,t){for(var r=e;r<this.t;++r)t.data[r-e]=this.data[r];t.t=Math.max(this.t-e,0),t.s=this.s}function o4(e,t){var r=e%this.DB,n=this.DB-r,s=(1<<n)-1,i=Math.floor(e/this.DB),a=this.s<<r&this.DM,o;for(o=this.t-1;o>=0;--o)t.data[o+i+1]=this.data[o]>>n|a,a=(this.data[o]&s)<<r;for(o=i-1;o>=0;--o)t.data[o]=0;t.data[i]=a,t.t=this.t+i+1,t.s=this.s,t.clamp()}function l4(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t){t.t=0;return}var n=e%this.DB,s=this.DB-n,i=(1<<n)-1;t.data[0]=this.data[r]>>n;for(var a=r+1;a<this.t;++a)t.data[a-r-1]|=(this.data[a]&i)<<s,t.data[a-r]=this.data[a]>>n;n>0&&(t.data[this.t-r-1]|=(this.s&i)<<s),t.t=this.t-r,t.clamp()}function c4(e,t){for(var r=0,n=0,s=Math.min(e.t,this.t);r<s;)n+=this.data[r]-e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()}function u4(e,t){var r=this.abs(),n=e.abs(),s=r.t;for(t.t=s+n.t;--s>=0;)t.data[s]=0;for(s=0;s<n.t;++s)t.data[s+r.t]=r.am(0,n.data[s],t,s,0,r.t);t.s=0,t.clamp(),this.s!=e.s&&Ae.ZERO.subTo(t,t)}function d4(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e.data[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t.data[r],e,2*r,0,1);(e.data[r+t.t]+=t.am(r+1,2*t.data[r],e,2*r+1,n,t.t-r-1))>=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()}function f4(e,t,r){var n=e.abs();if(!(n.t<=0)){var s=this.abs();if(s.t<n.t){t?.fromInt(0),r!=null&&this.copyTo(r);return}r==null&&(r=Kt());var i=Kt(),a=this.s,o=e.s,l=this.DB-vu(n.data[n.t-1]);l>0?(n.lShiftTo(l,i),s.lShiftTo(l,r)):(n.copyTo(i),s.copyTo(r));var c=i.t,d=i.data[c-1];if(d!=0){var f=d*(1<<this.F1)+(c>1?i.data[c-2]>>this.F2:0),h=this.FV/f,m=(1<<this.F1)/f,g=1<<this.F2,v=r.t,w=v-c,b=t??Kt();for(i.dlShiftTo(w,b),r.compareTo(b)>=0&&(r.data[r.t++]=1,r.subTo(b,r)),Ae.ONE.dlShiftTo(c,b),b.subTo(i,i);i.t<c;)i.data[i.t++]=0;for(;--w>=0;
20){var C=r.data[--v]==d?this.DM:Math.floor(r.data[v]*h+(r.data[v-1]+g)*m);if((r.data[v]+=i.am(0,C,r,w,0,c))<C)for(i.dlShiftTo(w,b),r.subTo(b,r);r.data[v]<--C;)r.subTo(b,r)}t!=null&&(r.drShiftTo(c,t),a!=o&&Ae.ZERO.subTo(t,t)),r.t=c,r.clamp(),l>0&&r.rShiftTo(l,r),a<0&&Ae.ZERO.subTo(r,r)}}}function h4(e){var t=Kt();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(Ae.ZERO)>0&&e.subTo(t,t),t}function Di(e){this.m=e}function p4(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function m4(e){return e}function g4(e){e.divRemTo(this.m,null,e)}function y4(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function v4(e,t){e.squareTo(t),this.reduce(t)}Di.prototype.convert=p4;Di.prototype.revert=m4;Di.prototype.reduce=g4;Di.prototype.mulTo=y4;Di.prototype.sqrTo=v4;function x4(){if(this.t<1)return 0;var e=this.data[0];if(!(e&1))return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function Li(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function b4(e){var t=Kt();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(Ae.ZERO)>0&&this.m.subTo(t,t),t}function w4(e){var t=Kt();return e.copyTo(t),this.reduce(t),t}function C4(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=e.data[t]&32767,n=r*this.mpl+((r*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function S4(e,t){e.squareTo(t),this.reduce(t)}function E4(e,t,r){e.multiplyTo(t,r),this.reduce(r)}Li.prototype.convert=b4;Li.prototype.revert=w4;Li.prototype.reduce=C4;Li.prototype.mulTo=E4;Li.prototype.sqrTo=S4;function T4(){return(this.t>0?this.data[0]&1:this.s)==0}function _4(e,t){if(e>4294967295||e<1)return Ae.ONE;var r=Kt(),n=Kt(),s=t.convert(this),i=vu(e)-1;for(s.copyTo(r);--i>=0;)if(t.sqrTo(r,n),(e&1<<i)>0)t.mulTo(n,s,r);else{var a=r;r=n,n=a}return t.revert(r)}function I4(e,t){var r;return e<256||t.isEven()?r=new Di(t):r=new Li(t),this.exp(e,r)}Ae.prototype.copyTo=QN;Ae.prototype.fromInt=XN;Ae.prototype.fromString=JN;Ae.prototype.clamp=ZN;Ae.prototype.dlShiftTo=i4;Ae.prototype.drShiftTo=a4;Ae.prototype.lShiftTo=o4;Ae.prototype.rShiftTo=l4;Ae.prototype.subTo=c4;Ae.prototype.multiplyTo=u4;Ae.prototype.squareTo=d4;Ae.prototype.divRemTo=f4;Ae.prototype.invDigit=x4;Ae.prototype.isEven=T4;Ae.prototype.exp=_4;Ae.prototype.toString=e4;Ae.prototype.negate=t4;Ae.prototype.abs=r4;Ae.prototype.compareTo=n4;Ae.prototype.bitLength=s4;Ae.prototype.mod=h4;Ae.prototype.modPowInt=I4;Ae.ZERO=Gs(0);Ae.ONE=Gs(1);function A4(){var e=Kt();return this.copyTo(e),e}function k4(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function N4(){return this.t==0?this.s:this.data[0]<<24>>24}function R4(){return this.t==0?this.s:this.data[0]<<16>>16}function P4(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function j4(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function B4(e){if(e==null&&(e=10),this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=Gs(r),s=Kt(),i=Kt(),a="";for(this.divRemTo(n,s,i);s.signum()>0;)a=(r+i.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,i);return i.intValue().toString(e)+a}function D4(e,t){this.fromInt(0),t==null&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),s=!1,i=0,a=0,o=0;o<e.length;++o){var l=v1(e,o);if(l<0){e.charAt(o)=="-"&&this.signum()==0&&(s=!0);continue}a=t*a+l,++i>=r&&(this.dMultiply(n),this.dAddOffset(a,0),i=0,a=0)}i>0&&(this.dMultiply(Math.pow(t,i)),this.dAddOffset(a,0)),s&&Ae.ZERO.subTo(this,this)}function L4(e,t,r){if(typeof t=="number")if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(Ae.ONE.shiftLeft(e-1),Cp,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(Ae.ONE.shiftLeft(e-1),this);else{var n=new Array,s=e&7;n.length=(e>>3)+1,t.nextBytes(n),s>0?n[0]&=(1<<s)-1:n[0]=0,this.fromString(n,256)}}function M4(){var e=this.t,t=new Array;t[0]=this.s;var r=this.DB-e*this.DB%8,n,s=0;if(e-- >0)for(r<this.DB&&(n=this.data[e]>>r)!=(this.s&this.DM)>>r&&(t[s++]=n|this.s<<this.DB-r);e>=0;)r<8?(n=(this.data[e]&(1<<r)-1)<<8-r,n|=this.data[--e]>>(r+=this.DB-8)):(n=this.data[e]>>(r-=8)&255,r<=0&&(r+=this.DB,--e)),n&128&&(n|=-256),s==0&&(this.s&128)!=(n&128)&&++s,(s>0||n!=this.s)&&(t[s++]=n);return t}function O4(e){return this.compareTo(e)==0}
20function F4(e){return this.compareTo(e)<0?this:e}function U4(e){return this.compareTo(e)>0?this:e}function V4(e,t,r){var n,s,i=Math.min(e.t,this.t);for(n=0;n<i;++n)r.data[n]=t(this.data[n],e.data[n]);if(e.t<this.t){for(s=e.s&this.DM,n=i;n<this.t;++n)r.data[n]=t(this.data[n],s);r.t=this.t}else{for(s=this.s&this.DM,n=i;n<e.t;++n)r.data[n]=t(s,e.data[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()}function $4(e,t){return e&t}function z4(e){var t=Kt();return this.bitwiseTo(e,$4,t),t}function Cp(e,t){return e|t}function K4(e){var t=Kt();return this.bitwiseTo(e,Cp,t),t}function x1(e,t){return e^t}function q4(e){var t=Kt();return this.bitwiseTo(e,x1,t),t}function b1(e,t){return e&~t}function H4(e){var t=Kt();return this.bitwiseTo(e,b1,t),t}function G4(){for(var e=Kt(),t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e}function W4(e){var t=Kt();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t}function Y4(e){var t=Kt();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t}function Q4(e){if(e==0)return-1;var t=0;return e&65535||(e>>=16,t+=16),e&255||(e>>=8,t+=8),e&15||(e>>=4,t+=4),e&3||(e>>=2,t+=2),e&1||++t,t}function X4(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+Q4(this.data[e]);return this.s<0?this.t*this.DB:-1}function J4(e){for(var t=0;e!=0;)e&=e-1,++t;return t}function Z4(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=J4(this.data[r]^t);return e}function eR(e){var t=Math.floor(e/this.DB);return t>=this.t?this.s!=0:(this.data[t]&1<<e%this.DB)!=0}function tR(e,t){var r=Ae.ONE.shiftLeft(e);return this.bitwiseTo(r,t,r),r}function rR(e){return this.changeBit(e,Cp)}function nR(e){return this.changeBit(e,b1)}function sR(e){return this.changeBit(e,x1)}function iR(e,t){for(var r=0,n=0,s=Math.min(e.t,this.t);r<s;)n+=this.data[r]+e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()}function aR(e){var t=Kt();return this.addTo(e,t),t}function oR(e){var t=Kt();return this.subTo(e,t),t}function lR(e){var t=Kt();return this.multiplyTo(e,t),t}function cR(e){var t=Kt();return this.divRemTo(e,t,null),t}function uR(e){var t=Kt();return this.divRemTo(e,null,t),t}function dR(e){var t=Kt(),r=Kt();return this.divRemTo(e,t,r),new Array(t,r)}function fR(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function hR(e,t){if(e!=0){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function Wo(){}function w1(e){return e}function pR(e,t,r){e.multiplyTo(t,r)}function mR(e,t){e.squareTo(t)}Wo.prototype.convert=w1;Wo.prototype.revert=w1;Wo.prototype.mulTo=pR;Wo.prototype.sqrTo=mR;function gR(e){return this.exp(e,new Wo)}function yR(e,t,r){var n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var s;for(s=r.t-this.t;n<s;++n)r.data[n+this.t]=this.am(0,e.data[n],r,n,0,this.t);for(s=Math.min(e.t,t);n<s;++n)this.am(0,e.data[n],r,n,0,t-n);r.clamp()}function vR(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r.data[this.t+n-t]=this.am(t-n,e.data[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)}function ka(e){this.r2=Kt(),this.q3=Kt(),Ae.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function xR(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=Kt();return e.copyTo(t),this.reduce(t),t}function bR(e){return e}function wR(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function CR(e,t){e.squareTo(t),this.reduce(t)}function SR(e,t,r){e.multiplyTo(t,r),this.reduce(r)}ka.prototype.convert=xR;ka.prototype.revert=bR;ka.prototype.reduce=wR;ka.prototype.mulTo=SR;ka.prototype.sqrTo=CR;function ER(e,t){var r=e.bitLength(),n,s=Gs(1),i;if(r<=0)return s;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6,r<8?i=new Di(t):t.isEven()?i=new ka(t):i=new Li(t);var a=new Array,o=3,l=n-1,c=(1<<n)-1;if(a[1]=i.convert(this),n>1){var d=Kt();for(i.sqrTo(a[1],d);o<=c;)a[o]=Kt(),i.mulTo(d,a[o-2],a[o]),o+=2}var f=e.t-1,h,m=!0,g=Kt(),v;
20for(r=vu(e.data[f])-1;f>=0;){for(r>=l?h=e.data[f]>>r-l&c:(h=(e.data[f]&(1<<r+1)-1)<<l-r,f>0&&(h|=e.data[f-1]>>this.DB+r-l)),o=n;!(h&1);)h>>=1,--o;if((r-=o)<0&&(r+=this.DB,--f),m)a[h].copyTo(s),m=!1;else{for(;o>1;)i.sqrTo(s,g),i.sqrTo(g,s),o-=2;o>0?i.sqrTo(s,g):(v=s,s=g,g=v),i.mulTo(g,a[h],s)}for(;f>=0&&!(e.data[f]&1<<r);)i.sqrTo(s,g),v=s,s=g,g=v,--r<0&&(r=this.DB-1,--f)}return i.revert(s)}function TR(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var s=t.getLowestSetBit(),i=r.getLowestSetBit();if(i<0)return t;for(s<i&&(i=s),i>0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(s=t.getLowestSetBit())>0&&t.rShiftTo(s,t),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r}function _R(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(t==0)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r}function IR(e){var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return Ae.ZERO;for(var r=e.clone(),n=this.clone(),s=Gs(1),i=Gs(0),a=Gs(0),o=Gs(1);r.signum()!=0;){for(;r.isEven();)r.rShiftTo(1,r),t?((!s.isEven()||!i.isEven())&&(s.addTo(this,s),i.subTo(e,i)),s.rShiftTo(1,s)):i.isEven()||i.subTo(e,i),i.rShiftTo(1,i);for(;n.isEven();)n.rShiftTo(1,n),t?((!a.isEven()||!o.isEven())&&(a.addTo(this,a),o.subTo(e,o)),a.rShiftTo(1,a)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);r.compareTo(n)>=0?(r.subTo(n,r),t&&s.subTo(a,s),i.subTo(o,i)):(n.subTo(r,n),t&&a.subTo(s,a),o.subTo(i,o))}if(n.compareTo(Ae.ONE)!=0)return Ae.ZERO;if(o.compareTo(e)>=0)return o.subtract(e);if(o.signum()<0)o.addTo(e,o);else return o;return o.signum()<0?o.add(e):o}var Fn=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],AR=(1<<26)/Fn[Fn.length-1];function kR(e){var t,r=this.abs();if(r.t==1&&r.data[0]<=Fn[Fn.length-1]){for(t=0;t<Fn.length;++t)if(r.data[0]==Fn[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<Fn.length;){for(var n=Fn[t],s=t+1;s<Fn.length&&n<AR;)n*=Fn[s++];for(n=r.modInt(n);t<s;)if(n%Fn[t++]==0)return!1}return r.millerRabin(e)}function NR(e){var t=this.subtract(Ae.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n=t.shiftRight(r),s=RR(),i,a=0;a<e;++a){do i=new Ae(this.bitLength(),s);while(i.compareTo(Ae.ONE)<=0||i.compareTo(t)>=0);var o=i.modPow(n,this);if(o.compareTo(Ae.ONE)!=0&&o.compareTo(t)!=0){for(var l=1;l++<r&&o.compareTo(t)!=0;)if(o=o.modPowInt(2,this),o.compareTo(Ae.ONE)==0)return!1;if(o.compareTo(t)!=0)return!1}}return!0}function RR(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}Ae.prototype.chunkSize=P4;Ae.prototype.toRadix=B4;Ae.prototype.fromRadix=D4;Ae.prototype.fromNumber=L4;Ae.prototype.bitwiseTo=V4;Ae.prototype.changeBit=tR;Ae.prototype.addTo=iR;Ae.prototype.dMultiply=fR;Ae.prototype.dAddOffset=hR;Ae.prototype.multiplyLowerTo=yR;Ae.prototype.multiplyUpperTo=vR;Ae.prototype.modInt=_R;Ae.prototype.millerRabin=NR;Ae.prototype.clone=A4;Ae.prototype.intValue=k4;Ae.prototype.byteValue=N4;Ae.prototype.shortValue=R4;Ae.prototype.signum=j4;Ae.prototype.toByteArray=M4;Ae.prototype.equals=O4;Ae.prototype.min=F4;Ae.prototype.max=U4;Ae.prototype.and=z4;Ae.prototype.or=K4;Ae.prototype.xor=q4;Ae.prototype.andNot=H4;Ae.prototype.not=G4;Ae.prototype.shiftLeft=W4;Ae.prototype.shiftRight=Y4;Ae.prototype.getLowestSetBit=X4;Ae.prototype.bitCount=Z4;Ae.prototype.testBit=eR;Ae.prototype.setBit=rR;Ae.prototype.clearBit=nR;Ae.prototype.flipBit=sR;Ae.prototype.add=aR;Ae.prototype.subtract=oR;Ae.prototype.multiply=lR;Ae.prototype.divide=cR;Ae.prototype.remainder=uR;Ae.prototype.divideAndRemainder=dR;Ae.prototype.modPow=ER;Ae.prototype.modInverse=IR;Ae.prototype.pow=gR;Ae.prototype.gcd=TR;Ae.prototype.isProbablePrime=kR;var ns=Pt,C1=ns.sha1=ns.sha1||{};ns.md.sha1=ns.md.algorithms.sha1=C1;C1.create=function(){S1||PR();var e=null,t=ns.util.createBuffer(),r=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var s=n.messageLengthSize/4,i=0;i<s;++i)n.fullMessageLength.push(0);return t=ns.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},n},n.start(),n.update=function(s,i){i==="utf8"&&(s=ns.util.encodeUtf8(s));var a=s.length;n.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=n.fullMessageLength.length-1;o>=0;--o)n.fullMessageLength[o]+=a[1],a[1]=a[0]+(n.fullMessageLength[o]/4294967296>>>0),n.fullMessageLength[o]=n.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),Yg(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var s=ns.util.createBuffer();s.putBytes(t.bytes());var i=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,a=i&n.blockLength-1;s.putBytes(Hf.substr(0,n.blockLength-a));for(var o,l,c=n.fullMessageLength[0]*8,d=0;d<n.fullMessageLength.length-1;++d)o=n.fullMessageLength[d+1]*8,l=o/4294967296>>>0,c+=l,s.putInt32(c>>>0),c=o>>>0;s.putInt32(c);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};Yg(f,r,s);var h=ns.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},n};var Hf=null,S1=!1;function PR(){Hf="€",Hf+=ns.util.fillString("\0",64),S1=!0}function Yg(e,t,r){for(var n,s,i,a,o,l,c,d,f=r.length();f>=64;){for(s=e.h0,i=e.h1,a=e.h2,o=e.h3,l=e.h4,d=0;d<16;++d)n=r.getInt32(),t[d]=n,c=o^i&(a^o),n=(s<<5|s>>>27)+c+l+1518500249+n,l=o,o=a,a=(i<<30|i>>>2)>>>0,i=s,s=n;for(;d<20;++d)n=t[d-3]^t[d-8]^t[d-14]^t[d-16],n=n<<1|n>>>31,t[d]=n,c=o^i&(a^o),n=(s<<5|s>>>27)+c+l+1518500249+n,l=o,o=a,a=(i<<30|i>>>2)>>>0,i=s,s=n;for(;d<32;++d)n=t[d-3]^t[d-8]^t[d-14]^t[d-16],n=n<<1|n>>>31,t[d]=n,c=i^a^o,n=(s<<5|s>>>27)+c+l+1859775393+n,l=o,o=a,a=(i<<30|i>>>2)>>>0,i=s,s=n;for(;d<40;++d)n=t[d-6]^t[d-16]^t[d-28]^t[d-32],n=n<<2|n>>>30,t[d]=n,c=i^a^o,n=(s<<5|s>>>27)+c+l+1859775393+n,l=o,o=a,a=(i<<30|i>>>2)>>>0,i=s,s=n;for(;d<60;++d)n=t[d-6]^t[d-16]^t[d-28]^t[d-32],n=n<<2|n>>>30,t[d]=n,c=i&a|o&(i^a),n=(s<<5|s>>>27)+c+l+2400959708+n,l=o,o=a,a=(i<<30|i>>>2)>>>0,i=s,s=n;for(;d<80;++d)n=t[d-6]^t[d-16]^t[d-28]^t[d-32],n=n<<2|n>>>30,t[d]=n,c=i^a^o,n=(s<<5|s>>>27)+c+l+3395469782+n,l=o,o=a,a=(i<<30|i>>>2)>>>0,i=s,s=n;e.h0=e.h0+s|0,e.h1=e.h1+i|0,e.h2=e.h2+a|0,e.h3=e.h3+o|0,e.h4=e.h4+l|0,f-=64}}var as=Pt,E1=as.pkcs1=as.pkcs1||{};E1.encode_rsa_oaep=function(e,t,r){var n,s,i,a;typeof r=="string"?(n=r,s=arguments[3]||void 0,i=arguments[4]||void 0):r&&(n=r.label||void 0,s=r.seed||void 0,i=r.md||void 0,r.mgf1&&r.mgf1.md&&(a=r.mgf1.md)),i?i.start():i=as.md.sha1.create(),a||(a=i);var o=Math.ceil(e.n.bitLength()/8),l=o-2*i.digestLength-2;if(t.length>l){var c=new Error("RSAES-OAEP input message length is too long.");throw c.length=t.length,c.maxLength=l,c}n||(n=""),i.update(n,"raw");for(var d=i.digest(),f="",h=l-t.length,m=0;m<h;m++)f+="\0";var g=d.getBytes()+f+"�"+t;if(!s)s=as.random.getBytes(i.digestLength);else if(s.length!==i.digestLength){var c=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw c.seedLength=s.length,c.digestLength=i.digestLength,c}var v=Ec(s,o-i.digestLength-1,a),w=as.util.xorBytes(g,v,g.length),b=Ec(w,i.digestLength,a),C=as.util.xorBytes(s,b,s.length);return"\0"+C+w};E1.decode_rsa_oaep=function(e,t,r){var n,s,i;typeof r=="string"?(n=r,s=arguments[3]||void 0):r&&(n=r.label||void 0,s=r.md||void 0,r.mgf1&&r.mgf1.md&&(i=r.mgf1.md));var a=Math.ceil(e.n.bitLength()/8);if(t.length!==a){var w=new Error("RSAES-OAEP encoded message length is invali
20d.");throw w.length=t.length,w.expectedLength=a,w}if(s===void 0?s=as.md.sha1.create():s.start(),i||(i=s),a<2*s.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");n||(n=""),s.update(n,"raw");for(var o=s.digest().getBytes(),l=t.charAt(0),c=t.substring(1,s.digestLength+1),d=t.substring(1+s.digestLength),f=Ec(d,s.digestLength,i),h=as.util.xorBytes(c,f,c.length),m=Ec(h,a-s.digestLength-1,i),g=as.util.xorBytes(d,m,d.length),v=g.substring(0,s.digestLength),w=l!=="\0",b=0;b<s.digestLength;++b)w|=o.charAt(b)!==v.charAt(b);for(var C=1,T=s.digestLength,I=s.digestLength;I<g.length;I++){var k=g.charCodeAt(I),_=k&1^1,M=C?65534:0;w|=k&M,C=C&_,T+=C}if(w||g.charCodeAt(T)!==1)throw new Error("Invalid RSAES-OAEP padding.");return g.substring(T+1)};function Ec(e,t,r){r||(r=as.md.sha1.create());for(var n="",s=Math.ceil(t/r.digestLength),i=0;i<s;++i){var a=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,i&255);r.start(),r.update(e+a),n+=r.digest().getBytes()}return n.substring(0,t)}var Ms=Pt;(function(){if(Ms.prime){Ms.prime;return}var e=Ms.prime=Ms.prime||{},t=Ms.jsbn.BigInteger,r=[6,4,2,4,2,4,6,2],n=new t(null);n.fromInt(30);var s=function(f,h){return f|h};e.generateProbablePrime=function(f,h,m){typeof h=="function"&&(m=h,h={}),h=h||{};var g=h.algorithm||"PRIMEINC";typeof g=="string"&&(g={name:g}),g.options=g.options||{};var v=h.prng||Ms.random,w={nextBytes:function(b){for(var C=v.getBytesSync(b.length),T=0;T<b.length;++T)b[T]=C.charCodeAt(T)}};if(g.name==="PRIMEINC")return i(f,w,g.options,m);throw new Error("Invalid prime generation algorithm: "+g.name)};function i(f,h,m,g){return"workers"in m?l(f,h,m,g):a(f,h,m,g)}function a(f,h,m,g){var v=c(f,h),w=0,b=d(v.bitLength());"millerRabinTests"in m&&(b=m.millerRabinTests);var C=10;"maxBlockTime"in m&&(C=m.maxBlockTime),o(v,f,h,w,b,C,g)}function o(f,h,m,g,v,w,b){var C=+new Date;do{if(f.bitLength()>h&&(f=c(h,m)),f.isProbablePrime(v))return b(null,f);f.dAddOffset(r[g++%8],0)}while(w<0||+new Date-C<w);Ms.util.setImmediate(function(){o(f,h,m,g,v,w,b)})}function l(f,h,m,g){if(typeof Worker>"u")return a(f,h,m,g);var v=c(f,h),w=m.workers,b=m.workLoad||100,C=b*30/8,T=m.workerScript||"forge/prime.worker.js";if(w===-1)return Ms.util.estimateCores(function(k,_){k&&(_=2),w=_-1,I()});I();function I(){w=Math.max(1,w);for(var k=[],_=0;_<w;++_)k[_]=new Worker(T);for(var _=0;_<w;++_)k[_].addEventListener("message",V);var M=!1;function V(G){if(!M){var L=G.data;if(L.found){for(var H=0;H<k.length;++H)k[H].terminate();return M=!0,g(null,new t(L.prime,16))}v.bitLength()>f&&(v=c(f,h));var F=v.toString(16);G.target.postMessage({hex:F,workLoad:b}),v.dAddOffset(C,0)}}}}function c(f,h){var m=new t(f,h),g=f-1;return m.testBit(g)||m.bitwiseTo(t.ONE.shiftLeft(g),s,m),m.dAddOffset(31-m.mod(n).byteValue(),0),m}function d(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})();var it=Pt;if(typeof zt>"u")var zt=it.jsbn.BigInteger;var Gf=it.util.isNodejs?Fh:null,he=it.asn1,_n=it.util;it.pki=it.pki||{};it.pki.rsa=it.rsa=it.rsa||{};var St=it.pki,jR=[6,4,2,4,2,4,6,2],BR={name:"PrivateKeyInfo",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:he.Class.UNIVERSAL,type:he.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:he.Class.UNIVERSAL,type:he.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},DR={name:"RSAPrivateKey",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,c
20onstructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},LR={name:"RSAPublicKey",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:he.Class.UNIVERSAL,type:he.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},MR=it.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:he.Class.UNIVERSAL,type:he.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:he.Class.UNIVERSAL,type:he.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},OR={name:"DigestInfo",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:he.Class.UNIVERSAL,type:he.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:he.Class.UNIVERSAL,type:he.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:he.Class.UNIVERSAL,type:he.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:he.Class.UNIVERSAL,type:he.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},FR=function(e){var t;if(e.algorithm in St.oids)t=St.oids[e.algorithm];else{var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}var n=he.oidToDer(t).getBytes(),s=he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[]),i=he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[]);i.value.push(he.create(he.Class.UNIVERSAL,he.Type.OID,!1,n)),i.value.push(he.create(he.Class.UNIVERSAL,he.Type.NULL,!1,""));var a=he.create(he.Class.UNIVERSAL,he.Type.OCTETSTRING,!1,e.digest().getBytes());return s.value.push(i),s.value.push(a),he.toDer(s).getBytes()},T1=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(zt.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(zt.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));var n;do n=new zt(it.util.bytesToHex(it.random.getBytes(t.n.bitLength()/8)),16);while(n.compareTo(t.n)>=0||!n.gcd(t.n).equals(zt.ONE));e=e.multiply(n.modPow(t.e,t.n)).mod(t.n);for(var s=e.mod(t.p).modPow(t.dP,t.p),i=e.mod(t.q).modPow(t.dQ,t.q);s.compareTo(i)<0;)s=s.add(t.p);var a=s.subtract(i).multiply(t.qInv).mod(t.p).multiply(t.q).add(i);return a=a.multiply(n.modInverse(t.n)).mod(t.n),a};St.rsa.encrypt=function(e,t,r){var n=r,s,i=Math.ceil(t.n.bitLength()/8);r!==!1&&r!==!0?(n=r===2,s=_1(e,t,r)):(s=it.util.createBuffer(),s.putBytes(e));for(var a=new zt(s.toHex(),16),o=T1(a,t,n),l=o.toString(16),c=it.util.createBuffer(),d=i-Math.ceil(l.length/2);d>0;)c.putByte(0),--d;return c.putBytes(it.util.hexToBytes(l)),c.getBytes()};St.rsa.decrypt=function(e,t,r,n){var s=Math.ceil(t.n.bitLength()/8);if(e.length!==s){var i=new Error("Encrypted message length is invali
20d.");throw i.length=e.length,i.expected=s,i}var a=new zt(it.util.createBuffer(e).toHex(),16);if(a.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var o=T1(a,t,r),l=o.toString(16),c=it.util.createBuffer(),d=s-Math.ceil(l.length/2);d>0;)c.putByte(0),--d;return c.putBytes(it.util.hexToBytes(l)),n!==!1?Tc(c.getBytes(),t,r):c.getBytes()};St.rsa.createKeyPairGenerationState=function(e,t,r){typeof e=="string"&&(e=parseInt(e,10)),e=e||2048,r=r||{};var n=r.prng||it.random,s={nextBytes:function(o){for(var l=n.getBytesSync(o.length),c=0;c<o.length;++c)o[c]=l.charCodeAt(c)}},i=r.algorithm||"PRIMEINC",a;if(i==="PRIMEINC")a={algorithm:i,state:0,bits:e,rng:s,eInt:t||65537,e:new zt(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},a.e.fromInt(a.eInt);else throw new Error("Invalid key generation algorithm: "+i);return a};St.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new zt(null);r.fromInt(30);for(var n=0,s=function(f,h){return f|h},i=+new Date,a,o=0;e.keys===null&&(t<=0||o<t);){if(e.state===0){var l=e.p===null?e.pBits:e.qBits,c=l-1;e.pqState===0?(e.num=new zt(l,e.rng),e.num.testBit(c)||e.num.bitwiseTo(zt.ONE.shiftLeft(c),s,e.num),e.num.dAddOffset(31-e.num.mod(r).byteValue(),0),n=0,++e.pqState):e.pqState===1?e.num.bitLength()>l?e.pqState=0:e.num.isProbablePrime(VR(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(jR[n++%8],0):e.pqState===2?e.pqState=e.num.subtract(zt.ONE).gcd(e.e).compareTo(zt.ONE)===0?3:0:e.pqState===3&&(e.pqState=0,e.p===null?e.p=e.num:e.q=e.num,e.p!==null&&e.q!==null&&++e.state,e.num=null)}else if(e.state===1)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(e.state===2)e.p1=e.p.subtract(zt.ONE),e.q1=e.q.subtract(zt.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)e.phi.gcd(e.e).compareTo(zt.ONE)===0?++e.state:(e.p=null,e.q=null,e.state=0);else if(e.state===4)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(e.state===5){var d=e.e.modInverse(e.phi);e.keys={privateKey:St.rsa.setPrivateKey(e.n,e.e,d,e.p,e.q,d.mod(e.p1),d.mod(e.q1),e.q.modInverse(e.p)),publicKey:St.rsa.setPublicKey(e.n,e.e)}}a=+new Date,o+=a-i,i=a}return e.keys!==null};St.rsa.generateKeyPair=function(e,t,r,n){if(arguments.length===1?typeof e=="object"?(r=e,e=void 0):typeof e=="function"&&(n=e,e=void 0):arguments.length===2?typeof e=="number"?typeof t=="function"?(n=t,t=void 0):typeof t!="number"&&(r=t,t=void 0):(r=e,n=t,e=void 0,t=void 0):arguments.length===3&&(typeof t=="number"?typeof r=="function"&&(n=r,r=void 0):(n=r,r=t,t=void 0)),r=r||{},e===void 0&&(e=r.bits||2048),t===void 0&&(t=r.e||65537),!it.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(n){if(Qg("generateKeyPair"))return Gf.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(o,l,c){if(o)return n(o);n(null,{privateKey:St.privateKeyFromPem(c),publicKey:St.publicKeyFromPem(l)})});if(Xg("generateKey")&&Xg("exportKey"))return _n.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Zg(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(o){return _n.globalScope.crypto.subtle.exportKey("pkcs8",o.privateKey)}).then(void 0,function(o){n(o)}).then(function(o){if(o){var l=St.privateKeyFromAsn1(he.fromDer(it.util.createBuffer(o)));n(null,{privateKey:l,publicKey:St.setRsaPublicKey(l.n,l.e)})}});if(Jg("generateKey")&&Jg("exportKey")){var s=_n.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Zg(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);s.oncomplete=function(o){var l=o.target.result,c=_n.globalScope.msCrypto.subtle.exportKey("pkcs8",l.privateKey);c.oncomplete=function(d){var f=d.target.result,h=St.privateKeyFromAsn1(he.fromDer(it.util.createBuffer(f)));n(null,{privateKey:h,publicKey:St.setRsaPublicKey(h.n,h.e)})},c.onerror=function(d){n(d)}},s.onerror=function(o){n(o)};return}}else if(Qg("generateKeyPairSync")){var i=Gf.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}
20);return{privateKey:St.privateKeyFromPem(i.privateKey),publicKey:St.publicKeyFromPem(i.publicKey)}}}var a=St.rsa.createKeyPairGenerationState(e,t,r);if(!n)return St.rsa.stepKeyPairGenerationState(a,0),a.keys;UR(a,r,n)};St.setRsaPublicKey=St.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(n,s,i){if(typeof s=="string"?s=s.toUpperCase():s===void 0&&(s="RSAES-PKCS1-V1_5"),s==="RSAES-PKCS1-V1_5")s={encode:function(o,l,c){return _1(o,l,2).getBytes()}};else if(s==="RSA-OAEP"||s==="RSAES-OAEP")s={encode:function(o,l){return it.pkcs1.encode_rsa_oaep(l,o,i)}};else if(["RAW","NONE","NULL",null].indexOf(s)!==-1)s={encode:function(o){return o}};else if(typeof s=="string")throw new Error('Unsupported encryption scheme: "'+s+'".');var a=s.encode(n,r,!0);return St.rsa.encrypt(a,r,!0)},r.verify=function(n,s,i,a){typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSASSA-PKCS1-V1_5"),a===void 0&&(a={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in a||(a._parseAllDigestBytes=!0),i==="RSASSA-PKCS1-V1_5"?i={verify:function(l,c){c=Tc(c,r,!0);var d=he.fromDer(c,{parseAllBytes:a._parseAllDigestBytes}),f={},h=[];if(!he.validate(d,OR,f,h)){var m=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw m.errors=h,m}var g=he.derToOid(f.algorithmIdentifier);if(!(g===it.oids.md2||g===it.oids.md5||g===it.oids.sha1||g===it.oids.sha224||g===it.oids.sha256||g===it.oids.sha384||g===it.oids.sha512||g===it.oids["sha512-224"]||g===it.oids["sha512-256"])){var m=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw m.oid=g,m}if((g===it.oids.md2||g===it.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return l===f.digest}}:(i==="NONE"||i==="NULL"||i===null)&&(i={verify:function(l,c){return c=Tc(c,r,!0),l===c}});var o=St.rsa.decrypt(s,r,!0,!1);return i.verify(n,o,r.n.bitLength())},r};St.setRsaPrivateKey=St.rsa.setPrivateKey=function(e,t,r,n,s,i,a,o){var l={n:e,e:t,d:r,p:n,q:s,dP:i,dQ:a,qInv:o};return l.decrypt=function(c,d,f){typeof d=="string"?d=d.toUpperCase():d===void 0&&(d="RSAES-PKCS1-V1_5");var h=St.rsa.decrypt(c,l,!1,!1);if(d==="RSAES-PKCS1-V1_5")d={decode:Tc};else if(d==="RSA-OAEP"||d==="RSAES-OAEP")d={decode:function(m,g){return it.pkcs1.decode_rsa_oaep(g,m,f)}};else if(["RAW","NONE","NULL",null].indexOf(d)!==-1)d={decode:function(m){return m}};else throw new Error('Unsupported encryption scheme: "'+d+'".');return d.decode(h,l,!1)},l.sign=function(c,d){var f=!1;typeof d=="string"&&(d=d.toUpperCase()),d===void 0||d==="RSASSA-PKCS1-V1_5"?(d={encode:FR},f=1):(d==="NONE"||d==="NULL"||d===null)&&(d={encode:function(){return c}},f=1);var h=d.encode(c,l.n.bitLength());return St.rsa.encrypt(h,l,f)},l};St.wrapRsaPrivateKey=function(e){return he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,he.integerToDer(0).getBytes()),he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[he.create(he.Class.UNIVERSAL,he.Type.OID,!1,he.oidToDer(St.oids.rsaEncryption).getBytes()),he.create(he.Class.UNIVERSAL,he.Type.NULL,!1,"")]),he.create(he.Class.UNIVERSAL,he.Type.OCTETSTRING,!1,he.toDer(e).getBytes())])};St.privateKeyFromAsn1=function(e){var t={},r=[];if(he.validate(e,BR,t,r)&&(e=he.fromDer(it.util.createBuffer(t.privateKey))),t={},r=[],!he.validate(e,DR,t,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var s,i,a,o,l,c,d,f;return s=it.util.createBuffer(t.privateKeyModulus).toHex(),i=it.util.createBuffer(t.privateKeyPublicExponent).toHex(),a=it.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=it.util.createBuffer(t.privateKeyPrime1).toHex(),l=it.util.createBuffer(t.privateKeyPrime2).toHex(),c=it.util.createBuffer(t.privateKeyExponent1).toHex(),d=it.util.createBuffer(t.privateKeyExponent2).toHex(),f=it.util.createBuffer(t.privateKeyCoefficient).toHex(),St.setRsaPrivateKey(new zt(s,16),new zt(i,16),new zt(a,16),new zt(o,16),new zt(l,16),new zt(c,16),new zt(d,16),new zt(f,16))};St.privateKeyToAsn1=St.privateKeyToRSAPrivateKey=function(e){return he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,he.integerToDer(0).getBytes()),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.n)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.e)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.d)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.p)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.q)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.dP)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.dQ)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.qInv))])};St.publicKeyFromAsn1=function(e){var t={},r=[];if(he.validate(e,MR,t,r)){var n=he.derToOid(t.publicKeyOid);if(n!==St.oids.rsaEncryption){var s=new Error("Cannot read public key. Unknown OID.");throw s.oid=n,s}e=t.rsaPublicKey}if(r=[],!he.validate(e,LR,t,r)){var s=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw s.errors=r,s}var i=it.util.createBuffer(t.publicKeyModulus).toHex(),a=it.util.createBuffer(t.publicKeyExponent).toHex();return St.setRsaPublicKey(new zt(i,16),new zt(a,16))};St.publicKeyToAsn1=St.publicKeyToSubjectPublicKeyInfo=function(e){return he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[he.create(he.Class.UNIVERSAL,he.Type.OID,!1,he.oidToDer(St.oids.rsaEncryption).getBytes()),he.create(he.Class.UNIVERSAL,he.Type.NULL,!1,"")]),he.create(he.Class.UNIVERSAL,he.Type.BITSTRING,!1,[St.publicKeyToRSAPublicKey(e)])])};St.publicKeyToRSAPublicKey=function(e){return he.create(he.Class.UNIVERSAL,he.Type.SEQUENCE,!0,[he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.n)),he.create(he.Class.UNIVERSAL,he.Type.INTEGER,!1,Yn(e.e))])};function _1(e,t,r){var n=it.util.createBuffer(),s=Math.ceil(t.n.bitLength()/8);if(e.length>s-11){var i=new Error("Message is too long for PKCS#1 v1.5 padding.");throw i.length=e.length,i.max=s-11,i}n.putByte(0),n.putByte(r);var a=s-3-e.length,o;if(r===0||r===1){o=r===0?0:255;for(var l=0;l<a;++l)n.putByte(o)}else for(;a>0;){for(var c=0,d=it.random.getBytes(a),l=0;l<a;
20++l)o=d.charCodeAt(l),o===0?++c:n.putByte(o);a=c}return n.putByte(0),n.putBytes(e),n}function Tc(e,t,r,n){var s=Math.ceil(t.n.bitLength()/8),i=it.util.createBuffer(e),a=i.getByte(),o=i.getByte();if(a!==0||r&&o!==0&&o!==1||!r&&o!=2||r&&o===0&&typeof n>"u")throw new Error("Encryption block is invalid.");var l=0;if(o===0){l=s-3-n;for(var c=0;c<l;++c)if(i.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(o===1)for(l=0;i.length()>1;){if(i.getByte()!==255){--i.read;break}++l}else if(o===2)for(l=0;i.length()>1;){if(i.getByte()===0){--i.read;break}++l}var d=i.getByte();if(d!==0||l!==s-3-i.length())throw new Error("Encryption block is invalid.");return i.getBytes()}function UR(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};var n={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(n.prng=t.prng),s();function s(){i(e.pBits,function(o,l){if(o)return r(o);if(e.p=l,e.q!==null)return a(o,e.q);i(e.qBits,a)})}function i(o,l){it.prime.generateProbablePrime(o,n,l)}function a(o,l){if(o)return r(o);if(e.q=l,e.p.compareTo(e.q)<0){var c=e.p;e.p=e.q,e.q=c}if(e.p.subtract(zt.ONE).gcd(e.e).compareTo(zt.ONE)!==0){e.p=null,s();return}if(e.q.subtract(zt.ONE).gcd(e.e).compareTo(zt.ONE)!==0){e.q=null,i(e.qBits,a);return}if(e.p1=e.p.subtract(zt.ONE),e.q1=e.q.subtract(zt.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(zt.ONE)!==0){e.p=e.q=null,s();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,i(e.qBits,a);return}var d=e.e.modInverse(e.phi);e.keys={privateKey:St.rsa.setPrivateKey(e.n,e.e,d,e.p,e.q,d.mod(e.p1),d.mod(e.q1),e.q.modInverse(e.p)),publicKey:St.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}}function Yn(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=it.util.hexToBytes(t);return r.length>1&&(r.charCodeAt(0)===0&&!(r.charCodeAt(1)&128)||r.charCodeAt(0)===255&&(r.charCodeAt(1)&128)===128)?r.substr(1):r}function VR(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function Qg(e){return it.util.isNodejs&&typeof Gf[e]=="function"}function Xg(e){return typeof _n.globalScope<"u"&&typeof _n.globalScope.crypto=="object"&&typeof _n.globalScope.crypto.subtle=="object"&&typeof _n.globalScope.crypto.subtle[e]=="function"}function Jg(e){return typeof _n.globalScope<"u"&&typeof _n.globalScope.msCrypto=="object"&&typeof _n.globalScope.msCrypto.subtle=="object"&&typeof _n.globalScope.msCrypto.subtle[e]=="function"}function Zg(e){for(var t=it.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),n=0;n<t.length;++n)r[n]=t.charCodeAt(n);return r}var Ye=Pt;if(typeof $R>"u")var $R=Ye.jsbn.BigInteger;var we=Ye.asn1,It=Ye.pki=Ye.pki||{};It.pbe=Ye.pbe=Ye.pbe||{};var mi=It.oids,zR={name:"EncryptedPrivateKeyInfo",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:we.Class.UNIVERSAL,type:we.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:we.Class.UNIVERSAL,type:we.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},KR={name:"PBES2Algorithms",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:we.Class.UNIVERSAL,type:we.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:we.Class.UNIVERSAL,type:we.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:we.Class.UNIVERSAL,type:we.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:we.Class.UNIVERSAL,type:we.Type.INTEGER,c
20onstructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:we.Class.UNIVERSAL,type:we.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:we.Class.UNIVERSAL,type:we.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:we.Class.UNIVERSAL,type:we.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},qR={name:"pkcs-12PbeParams",tagClass:we.Class.UNIVERSAL,type:we.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:we.Class.UNIVERSAL,type:we.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:we.Class.UNIVERSAL,type:we.Type.INTEGER,constructed:!1,capture:"iterations"}]};It.encryptPrivateKeyInfo=function(e,t,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var n=Ye.random.getBytesSync(r.saltSize),s=r.count,i=we.integerToDer(s),a,o,l;if(r.algorithm.indexOf("aes")===0||r.algorithm==="des"){var c,d,f;switch(r.algorithm){case"aes128":a=16,c=16,d=mi["aes128-CBC"],f=Ye.aes.createEncryptionCipher;break;case"aes192":a=24,c=16,d=mi["aes192-CBC"],f=Ye.aes.createEncryptionCipher;break;case"aes256":a=32,c=16,d=mi["aes256-CBC"],f=Ye.aes.createEncryptionCipher;break;case"des":a=8,c=8,d=mi.desCBC,f=Ye.des.createEncryptionCipher;break;default:var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=r.algorithm,h}var m="hmacWith"+r.prfAlgorithm.toUpperCase(),g=A1(m),v=Ye.pkcs5.pbkdf2(t,n,s,a,g),w=Ye.random.getBytesSync(c),b=f(v);b.start(w),b.update(we.toDer(e)),b.finish(),l=b.output.getBytes();var C=HR(n,i,a,m);o=we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.OID,!1,we.oidToDer(mi.pkcs5PBES2).getBytes()),we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.OID,!1,we.oidToDer(mi.pkcs5PBKDF2).getBytes()),C]),we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.OID,!1,we.oidToDer(d).getBytes()),we.create(we.Class.UNIVERSAL,we.Type.OCTETSTRING,!1,w)])])])}else if(r.algorithm==="3des"){a=24;var T=new Ye.util.ByteBuffer(n),v=It.pbe.generatePkcs12Key(t,T,1,s,a),w=It.pbe.generatePkcs12Key(t,T,2,s,a),b=Ye.des.createEncryptionCipher(v);b.start(w),b.update(we.toDer(e)),b.finish(),l=b.output.getBytes(),o=we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.OID,!1,we.oidToDer(mi["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.OCTETSTRING,!1,n),we.create(we.Class.UNIVERSAL,we.Type.INTEGER,!1,i.getBytes())])])}else{var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=r.algorithm,h}var I=we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[o,we.create(we.Class.UNIVERSAL,we.Type.OCTETSTRING,!1,l)]);return I};It.decryptPrivateKeyInfo=function(e,t){var r=null,n={},s=[];if(!we.validate(e,zR,n,s)){var i=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=s,i}var a=we.derToOid(n.encryptionOid),o=It.pbe.getCipher(a,n.encryptionParams,t),l=Ye.util.createBuffer(n.encryptedData);return o.update(l),o.finish()&&(r=we.fromDer(o.output)),r};It.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:we.toDer(e).getBytes()};return Ye.pem.encode(r,{maxline:t})};It.encryptedPrivateKeyFromPem=function(e){var t=Ye.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return we.fromDer(t.body)};It.encryptRsaPrivateKey=function(e,t,r){if(r=r||{},!r.legacy){var n=It.wrapRsaPrivateKey(It.privateKeyToAsn1(e));return n=It.encryptPrivateKeyInfo(n,t,r),It.encryptedPrivateKeyToPem(n)}var s,i,a,o;switch(r.algorithm){case"aes128":s="AES-128-CBC",a=16,i=Ye.random.getBytesSync(16),o=Ye.aes.createEncryptionCipher;break;
20case"aes192":s="AES-192-CBC",a=24,i=Ye.random.getBytesSync(16),o=Ye.aes.createEncryptionCipher;break;case"aes256":s="AES-256-CBC",a=32,i=Ye.random.getBytesSync(16),o=Ye.aes.createEncryptionCipher;break;case"3des":s="DES-EDE3-CBC",a=24,i=Ye.random.getBytesSync(8),o=Ye.des.createEncryptionCipher;break;case"des":s="DES-CBC",a=8,i=Ye.random.getBytesSync(8),o=Ye.des.createEncryptionCipher;break;default:var l=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw l.algorithm=r.algorithm,l}var c=Ye.pbe.opensslDeriveBytes(t,i.substr(0,8),a),d=o(c);d.start(i),d.update(we.toDer(It.privateKeyToAsn1(e))),d.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:s,parameters:Ye.util.bytesToHex(i).toUpperCase()},body:d.output.getBytes()};return Ye.pem.encode(f)};It.decryptRsaPrivateKey=function(e,t){var r=null,n=Ye.pem.decode(e)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var s=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw s.headerType=s,s}if(n.procType&&n.procType.type==="ENCRYPTED"){var i,a;switch(n.dekInfo.algorithm){case"DES-CBC":i=8,a=Ye.des.createDecryptionCipher;break;case"DES-EDE3-CBC":i=24,a=Ye.des.createDecryptionCipher;break;case"AES-128-CBC":i=16,a=Ye.aes.createDecryptionCipher;break;case"AES-192-CBC":i=24,a=Ye.aes.createDecryptionCipher;break;case"AES-256-CBC":i=32,a=Ye.aes.createDecryptionCipher;break;case"RC2-40-CBC":i=5,a=function(f){return Ye.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":i=8,a=function(f){return Ye.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":i=16,a=function(f){return Ye.rc2.createDecryptionCipher(f,128)};break;default:var s=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw s.algorithm=n.dekInfo.algorithm,s}var o=Ye.util.hexToBytes(n.dekInfo.parameters),l=Ye.pbe.opensslDeriveBytes(t,o.substr(0,8),i),c=a(l);if(c.start(o),c.update(Ye.util.createBuffer(n.body)),c.finish())r=c.output.getBytes();else return r}else r=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?r=It.decryptPrivateKeyInfo(we.fromDer(r),t):r=we.fromDer(r),r!==null&&(r=It.privateKeyFromAsn1(r)),r};It.pbe.generatePkcs12Key=function(e,t,r,n,s,i){var a,o;if(typeof i>"u"||i===null){if(!("sha1"in Ye.md))throw new Error('"sha1" hash algorithm unavailable.');i=Ye.md.sha1.create()}var l=i.digestLength,c=i.blockLength,d=new Ye.util.ByteBuffer,f=new Ye.util.ByteBuffer;if(e!=null){for(o=0;o<e.length;o++)f.putInt16(e.charCodeAt(o));f.putInt16(0)}var h=f.length(),m=t.length(),g=new Ye.util.ByteBuffer;g.fillWithByte(r,c);var v=c*Math.ceil(m/c),w=new Ye.util.ByteBuffer;for(o=0;o<v;o++)w.putByte(t.at(o%m));var b=c*Math.ceil(h/c),C=new Ye.util.ByteBuffer;for(o=0;o<b;o++)C.putByte(f.at(o%h));var T=w;T.putBuffer(C);for(var I=Math.ceil(s/l),k=1;k<=I;k++){var _=new Ye.util.ByteBuffer;_.putBytes(g.bytes()),_.putBytes(T.bytes());for(var M=0;M<n;M++)i.start(),i.update(_.getBytes()),_=i.digest();var V=new Ye.util.ByteBuffer;for(o=0;o<c;o++)V.putByte(_.at(o%l));var G=Math.ceil(m/c)+Math.ceil(h/c),L=new Ye.util.ByteBuffer;for(a=0;a<G;a++){var H=new Ye.util.ByteBuffer(T.getBytes(c)),F=511;for(o=V.length()-1;o>=0;o--)F=F>>8,F+=V.at(o)+H.at(o),H.setAt(o,F&255);L.putBuffer(H)}T=L,d.putBuffer(_)}return d.truncate(d.length()-s),d};It.pbe.getCipher=function(e,t,r){switch(e){case It.oids.pkcs5PBES2:return It.pbe.getCipherForPBES2(e,t,r);case It.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case It.oids["pbewithSHAAnd40BitRC2-CBC"]:return It.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};It.pbe.getCipherForPBES2=function(e,t,r){var n={},s=[];if(!we.validate(t,KR,n,s)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=s,i}if(e=we.derToOid(n.kdfOid),e!==It.oids.pkcs5PBKDF2){var i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw i.oid=e,i.supportedOids=["pkcs5PBKDF2"],i}if(e=we.derToOid(n.encOid),e!==It.oids["aes128-CBC"]&&e!==It.oids["aes192-CBC"]&&e!==It.oids["aes256-CBC"]&&e!==It.oids["des-EDE3-CBC"]&&e!==It.oids.desCBC){var i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw i.oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i}var a=n.kdfSalt,o=Ye.util.createBuffer(n.kdfIterationCount);o=o.getInt(o.length()<<3);var l,c;switch(It.oids[e]){case"aes128-CBC":l=16,c=Ye.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,c=Ye.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,c=Ye.aes.createDecryptionCipher;break;
20case"des-EDE3-CBC":l=24,c=Ye.des.createDecryptionCipher;break;case"desCBC":l=8,c=Ye.des.createDecryptionCipher;break}var d=I1(n.prfOid),f=Ye.pkcs5.pbkdf2(r,a,o,l,d),h=n.encIv,m=c(f);return m.start(h),m};It.pbe.getCipherForPKCS12PBE=function(e,t,r){var n={},s=[];if(!we.validate(t,qR,n,s)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=s,i}var a=Ye.util.createBuffer(n.salt),o=Ye.util.createBuffer(n.iterations);o=o.getInt(o.length()<<3);var l,c,d;switch(e){case It.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:l=24,c=8,d=Ye.des.startDecrypting;break;case It.oids["pbewithSHAAnd40BitRC2-CBC"]:l=5,c=8,d=function(v,w){var b=Ye.rc2.createDecryptionCipher(v,40);return b.start(w,null),b};break;default:var i=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw i.oid=e,i}var f=I1(n.prfOid),h=It.pbe.generatePkcs12Key(r,a,1,o,l,f);f.start();var m=It.pbe.generatePkcs12Key(r,a,2,o,c,f);return d(h,m)};It.pbe.opensslDeriveBytes=function(e,t,r,n){if(typeof n>"u"||n===null){if(!("md5"in Ye.md))throw new Error('"md5" hash algorithm unavailable.');n=Ye.md.md5.create()}t===null&&(t="");for(var s=[e0(n,e+t)],i=16,a=1;i<r;++a,i+=16)s.push(e0(n,s[a-1]+e+t));return s.join("").substr(0,r)};function e0(e,t){return e.start().update(t).digest().getBytes()}function I1(e){var t;if(!e)t="hmacWithSHA1";else if(t=It.oids[we.derToOid(e)],!t){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}return A1(t)}function A1(e){var t=Ye.md;switch(e){case"hmacWithSHA224":t=Ye.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}function HR(e,t,r,n){var s=we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.OCTETSTRING,!1,e),we.create(we.Class.UNIVERSAL,we.Type.INTEGER,!1,t.getBytes())]);return n!=="hmacWithSHA1"&&s.value.push(we.create(we.Class.UNIVERSAL,we.Type.INTEGER,!1,Ye.util.hexToBytes(r.toString(16))),we.create(we.Class.UNIVERSAL,we.Type.SEQUENCE,!0,[we.create(we.Class.UNIVERSAL,we.Type.OID,!1,we.oidToDer(It.oids[n]).getBytes()),we.create(we.Class.UNIVERSAL,we.Type.NULL,!1,"")])),s}var va=Pt,He=va.asn1,Na=va.pkcs7asn1=va.pkcs7asn1||{};va.pkcs7=va.pkcs7||{};va.pkcs7.asn1=Na;var k1={name:"ContentInfo",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:He.Class.UNIVERSAL,type:He.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:He.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};Na.contentInfoValidator=k1;var N1={name:"EncryptedContentInfo",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:He.Class.UNIVERSAL,type:He.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:He.Class.UNIVERSAL,type:He.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:He.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:He.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};Na.envelopedDataValidator={name:"EnvelopedData",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:He.Class.UNIVERSAL,type:He.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:He.Class.UNIVERSAL,type:He.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(N1)};Na.encryptedDataValidator={name:"EncryptedData",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:He.Class.UNIVERSAL,type:He.Type.INTEGER,c
20onstructed:!1,capture:"version"}].concat(N1)};var GR={name:"SignerInfo",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:He.Class.UNIVERSAL,type:He.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:He.Class.UNIVERSAL,type:He.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:He.Class.UNIVERSAL,type:He.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:He.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:He.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:He.Class.UNIVERSAL,type:He.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:He.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};Na.signedDataValidator={name:"SignedData",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:He.Class.UNIVERSAL,type:He.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:He.Class.UNIVERSAL,type:He.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},k1,{name:"SignedData.Certificates",tagClass:He.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:He.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:He.Class.UNIVERSAL,type:He.Type.SET,capture:"signerInfos",optional:!0,value:[GR]}]};Na.recipientInfoValidator={name:"RecipientInfo",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:He.Class.UNIVERSAL,type:He.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:He.Class.UNIVERSAL,type:He.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:He.Class.UNIVERSAL,type:He.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:He.Class.UNIVERSAL,type:He.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:He.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:He.Class.UNIVERSAL,type:He.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]};var Ai=Pt;Ai.mgf=Ai.mgf||{};var WR=Ai.mgf.mgf1=Ai.mgf1=Ai.mgf1||{};WR.create=function(e){var t={generate:function(r,n){for(var s=new Ai.util.ByteBuffer,i=Math.ceil(n/e.digestLength),a=0;a<i;a++){var o=new Ai.util.ByteBuffer;o.putInt32(a),e.start(),e.update(r+o.getBytes()),s.putBuffer(e.digest())}return s.truncate(s.length()-n),s.getBytes()}};return t};var _c=Pt;_c.mgf=_c.mgf||{};_c.mgf.mgf1=_c.mgf1;var bi=Pt,YR=bi.pss=bi.pss||{};YR.create=function(e){arguments.length===3&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t=e.md,r=e.mgf,n=t.digestLength,s=e.salt||null;typeof s=="string"&&(s=bi.util.createBuffer(s));var i;if("saltLength"in e)i=e.saltLength;else if(s!==null)i=s.length();else throw new Error("Salt length not specified or specific salt not given.");if(s!==null&&s.length()!==i)throw new Error("Given salt length does not match length of given salt.");var a=e.prng||bi.random,o={};return o.encode=function(l,c){var d,f=c-1,h=Math.ceil(f/8),m=l.digest().getBytes();if(h<n+i+2)throw new Error("Message is too long to encrypt.");var g;s===null?g=a.getBytesSync(i):g=s.bytes();var v=new bi.util.ByteBuffer;v.fillWithByte(0,8),v.putBytes(m),v.putBytes(g),t.start(),t.update(v.getBytes());var w=t.digest().getBytes(),b=new bi.util.ByteBuffer;b.fillWithByte(0,h-i-n-2),b.putByte(1),b.putBytes(g);var C=b.getBytes(),T=h-n-1,I=r.generate(w,T),k="";for(d=0;d<T;d++)k+=String.fromCharCode(C.charCodeAt(d)^I.charCodeAt(d));var _=65280>>8*h-f&255;return k=String.fromCharCode(k.charCodeAt(0)&~_)+k.substr(1),k+w+"¼"},o.verify=function(l,c,d){var f,h=d-1,m=Math.ceil(h/8);if(c=c.substr(-m),m<n+i+2)throw new Error("Inconsistent parameters to PSS signature verification.");
20if(c.charCodeAt(m-1)!==188)throw new Error("Encoded message does not end in 0xBC.");var g=m-n-1,v=c.substr(0,g),w=c.substr(g,n),b=65280>>8*m-h&255;if(v.charCodeAt(0)&b)throw new Error("Bits beyond keysize not zero as expected.");var C=r.generate(w,g),T="";for(f=0;f<g;f++)T+=String.fromCharCode(v.charCodeAt(f)^C.charCodeAt(f));T=String.fromCharCode(T.charCodeAt(0)&~b)+T.substr(1);var I=m-n-i-2;for(f=0;f<I;f++)if(T.charCodeAt(f)!==0)throw new Error("Leftmost octets not zero as expected");if(T.charCodeAt(I)!==1)throw new Error("Inconsistent PSS signature, 0x01 marker not found");var k=T.substr(-i),_=new bi.util.ByteBuffer;_.fillWithByte(0,8),_.putBytes(l),_.putBytes(k),t.start(),t.update(_.getBytes());var M=t.digest().getBytes();return w===M},o};var at=Pt,R=at.asn1,Ue=at.pki=at.pki||{},Vt=Ue.oids,gr={};gr.CN=Vt.commonName;gr.commonName="CN";gr.C=Vt.countryName;gr.countryName="C";gr.L=Vt.localityName;gr.localityName="L";gr.ST=Vt.stateOrProvinceName;gr.stateOrProvinceName="ST";gr.O=Vt.organizationName;gr.organizationName="O";gr.OU=Vt.organizationalUnitName;gr.organizationalUnitName="OU";gr.E=Vt.emailAddress;gr.emailAddress="E";var R1=at.pki.rsa.publicKeyValidator,QR={name:"Certificate",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:R.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:R.Class.UNIVERSAL,type:R.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:R.Class.UNIVERSAL,type:R.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:R.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:R.Class.UNIVERSAL,type:R.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:R.Class.UNIVERSAL,type:R.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:R.Class.UNIVERSAL,type:R.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:R.Class.UNIVERSAL,type:R.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},R1,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:R.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:R.Class.UNIVERSAL,type:R.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:R.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:R.Class.UNIVERSAL,type:R.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:R.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:R.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParam
20s"}]},{name:"Certificate.signatureValue",tagClass:R.Class.UNIVERSAL,type:R.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},XR={name:"rsapss",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:R.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:R.Class.UNIVERSAL,type:R.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:R.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:R.Class.UNIVERSAL,type:R.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:R.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:R.Class.UNIVERSAL,type:R.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:R.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:R.Class.UNIVERSAL,type:R.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},JR={name:"CertificationRequestInfo",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:R.Class.UNIVERSAL,type:R.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},R1,{name:"CertificationRequestInfo.attributes",tagClass:R.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:R.Class.UNIVERSAL,type:R.Type.SET,constructed:!0}]}]}]},ZR={name:"CertificationRequest",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[JR,{name:"CertificationRequest.signatureAlgorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:R.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:R.Class.UNIVERSAL,type:R.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};Ue.RDNAttributesAsArray=function(e,t){for(var r=[],n,s,i,a=0;a<e.value.length;++a){n=e.value[a];for(var o=0;o<n.value.length;++o)i={},s=n.value[o],i.type=R.derToOid(s.value[0].value),i.value=s.value[1].value,i.valueTagClass=s.value[1].type,i.type in Vt&&(i.name=Vt[i.type],i.name in gr&&(i.shortName=gr[i.name])),t&&(t.update(i.type),t.update(i.value)),r.push(i)}return r};Ue.CRIAttributesAsArray=function(e){for(var t=[],r=0;r<e.length;++r)for(var n=e[r],s=R.derToOid(n.value[0].value),i=n.value[1].value,a=0;a<i.length;++a){var o={};if(o.type=s,o.value=i[a].value,o.valueTagClass=i[a].type,o.type in Vt&&(o.name=Vt[o.type],o.name in gr&&(o.shortName=gr[o.name])),o.type===Vt.extensionRequest){o.extensions=[];for(var l=0;l<o.value.length;++l)o.extensions.push(Ue.certificateExtensionFromAsn1(o.value[l]))}t.push(o)}return t};function si(e,t){typeof t=="string"&&(t={shortName:t});for(var r=null,n,s=0;r===null&&s<e.attributes.length;++s)n=e.attributes[s],(t.type&&t.type===n.type||t.name&&t.name===n.name||t.shortName&&t.shortName===n.shortName)&&(r=n);return r}var Ic=function(e,t,r){var n={};if(e!==Vt["RSASSA-PSS"])return n;r&&(n={hash:{algorithmOid:Vt.sha1},mgf:{algorithmOid:Vt.mgf1,hash:{algorithmOid:Vt.sha1}},saltLength:20});var s={},i=[];if(!R.validate(t,XR,s,i)){var a=new Error("Cannot read RSASSA-PSS parameter block.");throw a.errors=i,a}return s.hashOid!==void 0&&(n.hash=n.hash||{},n.hash.algorithmOid=R.derToOid(s.hashOid)),s.maskGenOid!==void 0&&(n.mgf=n.mgf||{},n.mgf.algorithmOid=R.derToOid(s.maskGenOid),n.mgf.hash=n.mgf.hash||{},n.mgf.hash.algorithmOid=R.derToOid(s.maskGenHashOid)),s.saltLength!==void 0&&(n.saltLength=s.saltLength.charCodeAt(0)),n},xu=function(e){switch(Vt[e.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return at.md.sha1.create();case"md5WithRSAEncryption":return at.md.md5.create();case"sha256WithRSAEncryption":return at.md.sha256.create();case"sha384WithRSAEncryption":return at.md.sha384.create();case"sha512WithRSAEncryption":return at.md.sha512.create();case"RSASSA-PSS":return at.md.sha256.create();default:var t=new Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},P1=function(e){var t=e.certificate,r;switch(t.signatureOid){case Vt.sha1WithRSAEncryption:case Vt.sha1WithRSASignature:break;case Vt["RSASSA-PSS"]:var n,s;if(n=Vt[t.signatureParameters.mgf.hash.algorithmOid],n===void 0||at.md[n]===void 0){var i=new Error("Unsupported MGF hash function.");throw i.oid=t.signatureParameters.mgf.hash.algorithmOid,i.name=n,i}if(s=Vt[t.signatureParameters.mgf.algorithmOid],s===void 0||at.mgf[s]===void 0){var i=new Error("Unsupported MGF function.");throw i.oid=t.signatureParameters.mgf.algorithmOid,i.name=s,i}if(s=at.mgf[s].create(at.md[n].create()),n=Vt[t.signatureParameters.hash.algorithmOid],n===void 0||at.md[n]===void 0){var i=new Error("Unsupported RSASSA-PSS hash function.");throw i.oid=t.signatureParameters.hash.algorithmOid,i.name=n,i}r=at.pss.create(at.md[n].create(),s,t.signatureParameters.saltLength);break}return t.publicKey.verify(e.md.digest().getBytes(),e.signature,r)};Ue.certificateFromPem=function(e,t,r){var n=at.pem.decode(e)[0];if(n.type!=="CERTIFICATE"&&n.type!=="X509 CERTIFICATE"&&n.type!=="TRUSTED CERTIFICATE"){var s=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw s.headerType=n.type,s}if(n.procType&&n.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var i=R.fromDer(n.body,r);return Ue.certificateFromAsn1(i,t)};Ue.certificateToPem=function(e,t){var r={type:"CERTIFICATE",body:R.toDer(Ue.certificateToAsn1(e)).getBytes()};return at.pem.encode(r,{maxline:t})};Ue.publicKeyFromPem=function(e){var t=at.pem.decode(e)[0];if(t.type!=="PUBLIC KEY"&&t.type!=="RSA PUBLIC KEY"){var r=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw r.headerType=t.type,r}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert public key from PEM; PEM is encrypted.");var n=R.fromDer(t.body);return Ue.publicKeyFromAsn1(n)};Ue.publicKeyToPem=function(e,t){var r={type:"PUBLIC KEY",body:R.toDer(Ue.publicKeyToAsn1(e)).getBytes()};return at.pem.encode(r,{maxline:t})};Ue.publicKeyToRSAPublicKeyPem=function(e,t){var r={type:"RSA PUBLIC KEY",body:R.toDer(Ue.publicKeyToRSAPublicKey(e)).getBytes()};return at.pem.encode(r,{maxline:t})};Ue.getPublicKeyFingerprint=function(e,t){t=t||{};var r=t.md||at.md.sha1.create(),n=t.type||"RSAPublicKey",s;switch(n){case"RSAPublicKey":s=R.toDer(Ue.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":s=R.toDer(Ue.publicKeyToAsn1(e)).getBytes();break;default:throw new Error('Unknown fingerprint type "'+t.type+'".')}r.start(),r.update(s);var i=r.digest();if(t.encoding==="hex"){var a=i.toHex();return t.delimiter?a.match(/.{2}/g).join(t.delimiter):a}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};Ue.certificationRequestFromPem=function(e,t,r){var n=at.pem.decode(e)[0];if(n.type!=="CERTIFICATE REQUEST"){var s=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw s.headerType=n.type,s}if(n.procType&&n.procType.type==="ENCRYPTED")throw new Error("Could not convert certification request from PEM; PEM is encrypted.");var i=R.fromDer(n.body,r);return Ue.certificationRequestFromAsn1(i,t)};Ue.certificationRequestToPem=function(e,t){var r={type:"CERTIFICATE REQUEST",body:R.toDer(Ue.certificationRequestToAsn1(e)).getBytes()};return at.pem.encode(r,{maxline:t})};Ue.createCertificate=function(){var e={};return e.version=2,e.serialNumber="00",e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.validity={},e.validity.notBefore=new Date,e.validity.notAfter=new Date,e.issuer={},e.issuer.getField=function(t){return si(e.issuer,t)},e.issuer.addField=function(t){In([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return si(e.subject,t)},e.subject.addField=function(t){In([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.extensions=[],e.publicKey=null,e.md=null,e.setSubject=function(t,r){In(t),e.subject.attributes=t,delete e.subject.uniqueId,r&&(e.subject.uniqueId=r),e.subject.hash=null},e.setIssuer=function(t,r){In(t),e.issuer.attributes=t,delete e.issuer.uniqueId,r&&(e.issuer.uniqueId=r),e.issuer.hash=null},e.setExtensions=function(t){for(var r=0;r<t.length;++r)j1(t[r],{cert:e});e.extensions=t},e.getExtension=function(t){typeof t=="string"&&(t={name:t});for(var r=null,n,s=0;r===null&&s<e.extensions.length;++s)n=e.extensions[s],(t.id&&n.id===t.id||t.name&&n.name===t.name)&&(r=n);return r},e.sign=function(t,r){e.md=r||at.md.sha1.create();var n=Vt[e.md.algorithm+"WithRSAEncryption"];if(!n){var s=new Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw s.algorithm=e.md.algorithm,s}e.signatureOid=e.siginfo.algorithmOid=n,e.tbsCertificate=Ue.getTBSCertificate(e);
20var i=R.toDer(e.tbsCertificate);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(t){var r=!1;if(!e.issued(t)){var n=t.issuer,s=e.subject,i=new Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw i.expectedIssuer=s.attributes,i.actualIssuer=n.attributes,i}var a=t.md;if(a===null){a=xu({signatureOid:t.signatureOid,type:"certificate"});var o=t.tbsCertificate||Ue.getTBSCertificate(t),l=R.toDer(o);a.update(l.getBytes())}return a!==null&&(r=P1({certificate:e,md:a,signature:t.signature})),r},e.isIssuer=function(t){var r=!1,n=e.issuer,s=t.subject;if(n.hash&&s.hash)r=n.hash===s.hash;else if(n.attributes.length===s.attributes.length){r=!0;for(var i,a,o=0;r&&o<n.attributes.length;++o)i=n.attributes[o],a=s.attributes[o],(i.type!==a.type||i.value!==a.value)&&(r=!1)}return r},e.issued=function(t){return t.isIssuer(e)},e.generateSubjectKeyIdentifier=function(){return Ue.getPublicKeyFingerprint(e.publicKey,{type:"RSAPublicKey"})},e.verifySubjectKeyIdentifier=function(){for(var t=Vt.subjectKeyIdentifier,r=0;r<e.extensions.length;++r){var n=e.extensions[r];if(n.id===t){var s=e.generateSubjectKeyIdentifier().getBytes();return at.util.hexToBytes(n.subjectKeyIdentifier)===s}}return!1},e};Ue.certificateFromAsn1=function(e,t){var r={},n=[];if(!R.validate(e,QR,r,n)){var s=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw s.errors=n,s}var i=R.derToOid(r.publicKeyOid);if(i!==Ue.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var a=Ue.createCertificate();a.version=r.certVersion?r.certVersion.charCodeAt(0):0;var o=at.util.createBuffer(r.certSerialNumber);a.serialNumber=o.toHex(),a.signatureOid=at.asn1.derToOid(r.certSignatureOid),a.signatureParameters=Ic(a.signatureOid,r.certSignatureParams,!0),a.siginfo.algorithmOid=at.asn1.derToOid(r.certinfoSignatureOid),a.siginfo.parameters=Ic(a.siginfo.algorithmOid,r.certinfoSignatureParams,!1),a.signature=r.certSignature;var l=[];if(r.certValidity1UTCTime!==void 0&&l.push(R.utcTimeToDate(r.certValidity1UTCTime)),r.certValidity2GeneralizedTime!==void 0&&l.push(R.generalizedTimeToDate(r.certValidity2GeneralizedTime)),r.certValidity3UTCTime!==void 0&&l.push(R.utcTimeToDate(r.certValidity3UTCTime)),r.certValidity4GeneralizedTime!==void 0&&l.push(R.generalizedTimeToDate(r.certValidity4GeneralizedTime)),l.length>2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(l.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(a.validity.notBefore=l[0],a.validity.notAfter=l[1],a.tbsCertificate=r.tbsCertificate,t){a.md=xu({signatureOid:a.signatureOid,type:"certificate"});var c=R.toDer(a.tbsCertificate);a.md.update(c.getBytes())}var d=at.md.sha1.create(),f=R.toDer(r.certIssuer);d.update(f.getBytes()),a.issuer.getField=function(g){return si(a.issuer,g)},a.issuer.addField=function(g){In([g]),a.issuer.attributes.push(g)},a.issuer.attributes=Ue.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(a.issuer.uniqueId=r.certIssuerUniqueId),a.issuer.hash=d.digest().toHex();var h=at.md.sha1.create(),m=R.toDer(r.certSubject);return h.update(m.getBytes()),a.subject.getField=function(g){return si(a.subject,g)},a.subject.addField=function(g){In([g]),a.subject.attributes.push(g)},a.subject.attributes=Ue.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(a.subject.uniqueId=r.certSubjectUniqueId),a.subject.hash=h.digest().toHex(),r.certExtensions?a.extensions=Ue.certificateExtensionsFromAsn1(r.certExtensions):a.extensions=[],a.publicKey=Ue.publicKeyFromAsn1(r.subjectPublicKeyInfo),a};Ue.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r<e.value.length;++r)for(var n=e.value[r],s=0;s<n.value.length;++s)t.push(Ue.certificateExtensionFromAsn1(n.value[s]));return t};Ue.certificateExtensionFromAsn1=function(e){var t={};if(t.id=R.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===R.Type.BOOLEAN?(t.critical=e.value[1].value.charCodeAt(0)!==0,t.value=e.value[2].value):t.value=e.value[1].value,t.id in Vt){if(t.name=Vt[t.id],t.name==="keyUsage"){var r=R.fromDer(t.value),n=0,s=0;r.value.length>1&&(n=r.value.charCodeAt(1),s=r.value.length>2?r.value.charCodeAt(2):0),t.digitalSignature=(n&128)===128,t.nonRepudiation=(n&64)===64,t.keyEncipherment=(n&32)===32,t.dataEncipherment=(n&16)===16,t.keyAgreement=(n&8)===8,t.keyCertSign=(n&4)===4,t.cRLSign=(n&2)===2,t.encipherOnly=(n&1)===1,t.decipherOnly=(s&128)===128}else if(t.name==="basicConstraints"){var r=R.fromDer(t.value);r.value.length>0&&r.value[0].type===R.Type.BOOLEAN?t.cA=r.value[0].value.charCodeAt(0)!==0:t.cA=!1;var i=null;r.value.length>0&&r.value[0].type===R.Type.INTEGER?i=r.value[0].value:r.value.length>1&&(i=r.value[1].value),i!==null&&(t.pathLenConstraint=R.derToInteger(i))}else if(t.name==="extKeyUsage")for(var r=R.fromDer(t.value),a=0;a<r.value.length;++a){var o=R.derToOid(r.value[a].value);o in Vt?t[Vt[o]]=!0:t[o]=!0}else if(t.name==="nsCertType"){var r=R.fromDer(t.value),n=0;r.value.length>1&&(n=r.value.charCodeAt(1)),t.client=(n&128)===128,t.server=(n&64)===64,t.email=(n&32)===32,t.objsign=(n&16)===16,t.reserved=(n&8)===8,t.sslCA=(n&4)===4,t.emailCA=(n&2)===2,t.objCA=(n&1)===1}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.altNames=[];for(var l,r=R.fromDer(t.value),c=0;c<r.value.length;++c){l=r.value[c];var d={type:l.type,value:l.value};switch(t.altNames.push(d),l.type){case 1:case 2:case 6:break;case 7:d.ip=at.util.bytesToIP(l.value);break;case 8:d.oid=R.derToOid(l.value);break}}}else if(t.name==="subjectKeyIdentifier"){var r=R.fromDer(t.value);t.subjectKeyIdentifier=at.util.bytesToHex(r.value)}}return t};Ue.certificationRequestFromAsn1=function(e,t){var r={},n=[];if(!R.validate(e,ZR,r,n)){var s=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw s.errors=n,s}var i=R.derToOid(r.publicKeyOid);if(i!==Ue.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var a=Ue.createCertificationRequest();if(a.version=r.csrVersion?r.csrVersion.charCodeAt(0):0,a.signatureOid=at.asn1.derToOid(r.csrSignatureOid),a.signatureParameters=Ic(a.signatureOid,r.csrSignatureParam
20s,!0),a.siginfo.algorithmOid=at.asn1.derToOid(r.csrSignatureOid),a.siginfo.parameters=Ic(a.siginfo.algorithmOid,r.csrSignatureParams,!1),a.signature=r.csrSignature,a.certificationRequestInfo=r.certificationRequestInfo,t){a.md=xu({signatureOid:a.signatureOid,type:"certification request"});var o=R.toDer(a.certificationRequestInfo);a.md.update(o.getBytes())}var l=at.md.sha1.create();return a.subject.getField=function(c){return si(a.subject,c)},a.subject.addField=function(c){In([c]),a.subject.attributes.push(c)},a.subject.attributes=Ue.RDNAttributesAsArray(r.certificationRequestInfoSubject,l),a.subject.hash=l.digest().toHex(),a.publicKey=Ue.publicKeyFromAsn1(r.subjectPublicKeyInfo),a.getAttribute=function(c){return si(a,c)},a.addAttribute=function(c){In([c]),a.attributes.push(c)},a.attributes=Ue.CRIAttributesAsArray(r.certificationRequestInfoAttributes||[]),a};Ue.createCertificationRequest=function(){var e={};return e.version=0,e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.subject={},e.subject.getField=function(t){return si(e.subject,t)},e.subject.addField=function(t){In([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return si(e,t)},e.addAttribute=function(t){In([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){In(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){In(t),e.attributes=t},e.sign=function(t,r){e.md=r||at.md.sha1.create();var n=Vt[e.md.algorithm+"WithRSAEncryption"];if(!n){var s=new Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw s.algorithm=e.md.algorithm,s}e.signatureOid=e.siginfo.algorithmOid=n,e.certificationRequestInfo=Ue.getCertificationRequestInfo(e);var i=R.toDer(e.certificationRequestInfo);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,r=e.md;if(r===null){r=xu({signatureOid:e.signatureOid,type:"certification request"});var n=e.certificationRequestInfo||Ue.getCertificationRequestInfo(e),s=R.toDer(n);r.update(s.getBytes())}return r!==null&&(t=P1({certificate:e,md:r,signature:e.signature})),t},e};function xa(e){for(var t=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]),r,n,s=e.attributes,i=0;i<s.length;++i){r=s[i];var a=r.value,o=R.Type.PRINTABLESTRING;"valueTagClass"in r&&(o=r.valueTagClass,o===R.Type.UTF8&&(a=at.util.encodeUtf8(a))),n=R.create(R.Class.UNIVERSAL,R.Type.SET,!0,[R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(r.type).getBytes()),R.create(R.Class.UNIVERSAL,o,!1,a)])]),t.value.push(n)}return t}function In(e){for(var t,r=0;r<e.length;++r){if(t=e[r],typeof t.name>"u"&&(t.type&&t.type in Ue.oids?t.name=Ue.oids[t.type]:t.shortName&&t.shortName in gr&&(t.name=Ue.oids[gr[t.shortName]])),typeof t.type>"u")if(t.name&&t.name in Ue.oids)t.type=Ue.oids[t.name];else{var n=new Error("Attribute type not specified.");throw n.attribute=t,n}if(typeof t.shortName>"u"&&t.name&&t.name in gr&&(t.shortName=gr[t.name]),t.type===Vt.extensionRequest&&(t.valueConstructed=!0,t.valueTagClass=R.Type.SEQUENCE,!t.value&&t.extensions)){t.value=[];for(var s=0;s<t.extensions.length;++s)t.value.push(Ue.certificateExtensionToAsn1(j1(t.extensions[s])))}if(typeof t.value>"u"){var n=new Error("Attribute value not specified.");throw n.attribute=t,n}}}function j1(e,t){if(t=t||{},typeof e.name>"u"&&e.id&&e.id in Ue.oids&&(e.name=Ue.oids[e.id]),typeof e.id>"u")if(e.name&&e.name in Ue.oids)e.id=Ue.oids[e.name];else{var r=new Error("Extension ID not specified.");throw r.extension=e,r}if(typeof e.value<"u")return e;if(e.name==="keyUsage"){var n=0,s=0,i=0;e.digitalSignature&&(s|=128,n=7),e.nonRepudiation&&(s|=64,n=6),e.keyEncipherment&&(s|=32,n=5),e.dataEncipherment&&(s|=16,n=4),e.keyAgreement&&(s|=8,n=3),e.keyCertSign&&(s|=4,n=2),e.cRLSign&&(s|=2,n=1),e.encipherOnly&&(s|=1,n=0),e.decipherOnly&&(i|=128,n=7);var a=String.fromCharCode(n);i!==0?a+=String.fromCharCode(s)+String.fromCharCode(i):s!==0&&(a+=String.fromCharCode(s)),e.value=R.create(R.Class.UNIVERSAL,R.Type.BITSTRING,!1,a)}else if(e.name==="basicConstraints")e.value=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]),e.cA&&e.value.value.push(R.create(R.Class.UNIVERSAL,R.Type.BOOLEAN,!1,"ÿ")),"pathLenConstraint"in e&&e.value.value.push(R.create(R.Class.UNIVERSAL,R.Type.INTEGER,!1,R.integerToDer(e.pathLenConstraint).getBytes()));else if(e.name==="extKeyUsage"){e.value=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]);var o=e.value.value;for(var l in e)e[l]===!0&&(l in Vt?o.push(R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(Vt[l]).getBytes())):l.indexOf(".")!==-1&&o.push(R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(l).getBytes())))}else if(e.name==="nsCertType"){var n=0,s=0;e.client&&(s|=128,n=7),e.server&&(s|=64,n=6),e.email&&(s|=32,n=5),e.objsign&&(s|=16,n=4),e.reserved&&(s|=8,n=3),e.sslCA&&(s|=4,n=2),e.emailCA&&(s|=2,n=1),e.objCA&&(s|=1,n=0);var a=String.fromCharCode(n);s!==0&&(a+=String.fromCharCode(s)),e.value=R.create(R.Class.UNIVERSAL,R.Type.BITSTRING,!1,a)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]);for(var c,d=0;d<e.altNames.length;++d){c=e.altNames[d];var a=c.value;if(c.type===7&&c.ip){if(a=at.util.bytesFromIP(c.ip),a===null){var r=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw r.extension=e,r}}else c.type===8&&(c.oid?a=R.oidToDer(R.oidToDer(c.oid)):a=R.oidToDer(a));e.value.value.push(R.create(R.Class.CONTEXT_SPECIFIC,c.type,!1,a))}}else if(e.name==="nsComment"&&t.cert){if(!/^[\x00-\x7F]*$/.test(e.comment)||e.comment.length<1||e.comment.length>128)throw new Error('Invalid "nsComment" content.');e.value=R.create(R.Class.UNIVERSAL,R.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var f=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=f.toHex(),e.value=R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,f.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]);var o=e.value.value;
20if(e.keyIdentifier){var h=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;o.push(R.create(R.Class.CONTEXT_SPECIFIC,0,!1,h))}if(e.authorityCertIssuer){var m=[R.create(R.Class.CONTEXT_SPECIFIC,4,!0,[xa(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];o.push(R.create(R.Class.CONTEXT_SPECIFIC,1,!0,m))}if(e.serialNumber){var g=at.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);o.push(R.create(R.Class.CONTEXT_SPECIFIC,2,!1,g))}}else if(e.name==="cRLDistributionPoints"){e.value=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]);for(var o=e.value.value,v=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]),w=R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[]),c,d=0;d<e.altNames.length;++d){c=e.altNames[d];var a=c.value;if(c.type===7&&c.ip){if(a=at.util.bytesFromIP(c.ip),a===null){var r=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw r.extension=e,r}}else c.type===8&&(c.oid?a=R.oidToDer(R.oidToDer(c.oid)):a=R.oidToDer(a));w.value.push(R.create(R.Class.CONTEXT_SPECIFIC,c.type,!1,a))}v.value.push(R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[w])),o.push(v)}if(typeof e.value>"u"){var r=new Error("Extension value not specified.");throw r.extension=e,r}return e}function Sp(e,t){switch(e){case Vt["RSASSA-PSS"]:var r=[];return t.hash.algorithmOid!==void 0&&r.push(R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(t.hash.algorithmOid).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.NULL,!1,"")])])),t.mgf.algorithmOid!==void 0&&r.push(R.create(R.Class.CONTEXT_SPECIFIC,1,!0,[R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(t.mgf.algorithmOid).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(t.mgf.hash.algorithmOid).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.NULL,!1,"")])])])),t.saltLength!==void 0&&r.push(R.create(R.Class.CONTEXT_SPECIFIC,2,!0,[R.create(R.Class.UNIVERSAL,R.Type.INTEGER,!1,R.integerToDer(t.saltLength).getBytes())])),R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,r);default:return R.create(R.Class.UNIVERSAL,R.Type.NULL,!1,"")}}function e3(e){var t=R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[]);if(e.attributes.length===0)return t;for(var r=e.attributes,n=0;n<r.length;++n){var s=r[n],i=s.value,a=R.Type.UTF8;"valueTagClass"in s&&(a=s.valueTagClass),a===R.Type.UTF8&&(i=at.util.encodeUtf8(i));var o=!1;"valueConstructed"in s&&(o=s.valueConstructed);var l=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(s.type).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.SET,!0,[R.create(R.Class.UNIVERSAL,a,o,i)])]);t.value.push(l)}return t}var t3=new Date("1950-01-01T00:00:00Z"),r3=new Date("2050-01-01T00:00:00Z");function t0(e){return e>=t3&&e<r3?R.create(R.Class.UNIVERSAL,R.Type.UTCTIME,!1,R.dateToUtcTime(e)):R.create(R.Class.UNIVERSAL,R.Type.GENERALIZEDTIME,!1,R.dateToGeneralizedTime(e))}Ue.getTBSCertificate=function(e){var t=t0(e.validity.notBefore),r=t0(e.validity.notAfter),n=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[R.create(R.Class.UNIVERSAL,R.Type.INTEGER,!1,R.integerToDer(e.version).getBytes())]),R.create(R.Class.UNIVERSAL,R.Type.INTEGER,!1,at.util.hexToBytes(e.serialNumber)),R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(e.siginfo.algorithmOid).getBytes()),Sp(e.siginfo.algorithmOid,e.siginfo.parameters)]),xa(e.issuer),R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[t,r]),xa(e.subject),Ue.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&n.value.push(R.create(R.Class.CONTEXT_SPECIFIC,1,!0,[R.create(R.Class.UNIVERSAL,R.Type.BITSTRING,!1,"\0"+e.issuer.uniqueId)])),e.subject.uniqueId&&n.value.push(R.create(R.Class.CONTEXT_SPECIFIC,2,!0,[R.create(R.Class.UNIVERSAL,R.Type.BITSTRING,!1,"\0"+e.subject.uniqueId)])),e.extensions.length>0&&n.value.push(Ue.certificateExtensionsToAsn1(e.extensions)),n};Ue.getCertificationRequestInfo=function(e){var t=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.INTEGER,!1,R.integerToDer(e.version).getBytes()),xa(e.subject),Ue.publicKeyToAsn1(e.publicKey),e3(e)]);return t};Ue.distinguishedNameToAsn1=function(e){return xa(e)};Ue.certificateToAsn1=function(e){var t=e.tbsCertificate||Ue.getTBSCertificate(e);return R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[t,R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(e.signatureOid).getBytes()),Sp(e.signatureOid,e.signatureParameters)]),R.create(R.Class.UNIVERSAL,R.Type.BITSTRING,!1,"\0"+e.signature)])};Ue.certificateExtensionsToAsn1=function(e){var t=R.create(R.Class.CONTEXT_SPECIFIC,3,!0,[]),r=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]);t.value.push(r);for(var n=0;n<e.length;++n)r.value.push(Ue.certificateExtensionToAsn1(e[n]));return t};Ue.certificateExtensionToAsn1=function(e){var t=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[]);t.value.push(R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(e.id).getBytes())),e.critical&&t.value.push(R.create(R.Class.UNIVERSAL,R.Type.BOOLEAN,!1,"ÿ"));var r=e.value;return typeof e.value!="string"&&(r=R.toDer(r).getBytes()),t.value.push(R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,r)),t};Ue.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||Ue.getCertificationRequestInfo(e);return R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[t,R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(e.signatureOid).getBytes()),Sp(e.signatureOid,e.signatureParameters)]),R.create(R.Class.UNIVERSAL,R.Type.BITSTRING,!1,"\0"+e.signature)])};Ue.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(a){var o=r(a.issuer);return o}
20,t.addCertificate=function(a){if(typeof a=="string"&&(a=at.pki.certificateFromPem(a)),n(a.subject),!t.hasCertificate(a))if(a.subject.hash in t.certs){var o=t.certs[a.subject.hash];at.util.isArray(o)||(o=[o]),o.push(a),t.certs[a.subject.hash]=o}else t.certs[a.subject.hash]=a},t.hasCertificate=function(a){typeof a=="string"&&(a=at.pki.certificateFromPem(a));var o=r(a.subject);if(!o)return!1;at.util.isArray(o)||(o=[o]);for(var l=R.toDer(Ue.certificateToAsn1(a)).getBytes(),c=0;c<o.length;++c){var d=R.toDer(Ue.certificateToAsn1(o[c])).getBytes();if(l===d)return!0}return!1},t.listAllCertificates=function(){var a=[];for(var o in t.certs)if(t.certs.hasOwnProperty(o)){var l=t.certs[o];if(!at.util.isArray(l))a.push(l);else for(var c=0;c<l.length;++c)a.push(l[c])}return a},t.removeCertificate=function(a){var o;if(typeof a=="string"&&(a=at.pki.certificateFromPem(a)),n(a.subject),!t.hasCertificate(a))return null;var l=r(a.subject);if(!at.util.isArray(l))return o=t.certs[a.subject.hash],delete t.certs[a.subject.hash],o;for(var c=R.toDer(Ue.certificateToAsn1(a)).getBytes(),d=0;d<l.length;++d){var f=R.toDer(Ue.certificateToAsn1(l[d])).getBytes();c===f&&(o=l[d],l.splice(d,1))}return l.length===0&&delete t.certs[a.subject.hash],o};function r(a){return n(a),t.certs[a.hash]||null}function n(a){if(!a.hash){var o=at.md.sha1.create();a.attributes=Ue.RDNAttributesAsArray(xa(a),o),a.hash=o.digest().toHex()}}if(e)for(var s=0;s<e.length;++s){var i=e[s];t.addCertificate(i)}return t};Ue.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};Ue.verifyCertificateChain=function(e,t,r){typeof r=="function"&&(r={verify:r}),r=r||{},t=t.slice(0);var n=t.slice(0),s=r.validityCheckDate;typeof s>"u"&&(s=new Date);var i=!0,a=null,o=0;do{var l=t.shift(),c=null,d=!1;if(s&&(s<l.validity.notBefore||s>l.validity.notAfter)&&(a={message:"Certificate is not valid yet or has expired.",error:Ue.certificateError.certificate_expired,notBefore:l.validity.notBefore,notAfter:l.validity.notAfter,now:s}),a===null){if(c=t[0]||e.getIssuer(l),c===null&&l.isIssuer(l)&&(d=!0,c=l),c){var f=c;at.util.isArray(f)||(f=[f]);for(var h=!1;!h&&f.length>0;){c=f.shift();try{h=c.verify(l)}catch{}}h||(a={message:"Certificate signature is invalid.",error:Ue.certificateError.bad_certificate})}a===null&&(!c||d)&&!e.hasCertificate(l)&&(a={message:"Certificate is not trusted.",error:Ue.certificateError.unknown_ca})}if(a===null&&c&&!l.isIssuer(c)&&(a={message:"Certificate issuer is invalid.",error:Ue.certificateError.bad_certificate}),a===null)for(var m={keyUsage:!0,basicConstraints:!0},g=0;a===null&&g<l.extensions.length;++g){var v=l.extensions[g];v.critical&&!(v.name in m)&&(a={message:"Certificate has an unsupported critical extension.",error:Ue.certificateError.unsupported_certificate})}if(a===null&&(!i||t.length===0&&(!c||d))){var w=l.getExtension("basicConstraints"),b=l.getExtension("keyUsage");if(b!==null&&(!b.keyCertSign||w===null)&&(a={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:Ue.certificateError.bad_certificate}),a===null&&w!==null&&!w.cA&&(a={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:Ue.certificateError.bad_certificate}),a===null&&b!==null&&"pathLenConstraint"in w){var C=o-1;C>w.pathLenConstraint&&(a={message:"Certificate basicConstraints pathLenConstraint violated.",error:Ue.certificateError.bad_certificate})}}var T=a===null?!0:a.error,I=r.verify?r.verify(T,o,n):T;if(I===!0)a=null;else throw T===!0&&(a={message:"The application rejected the certificate.",error:Ue.certificateError.bad_certificate}),(I||I===0)&&(typeof I=="object"&&!at.util.isArray(I)?(I.message&&(a.message=I.message),I.error&&(a.error=I.error)):typeof I=="str
20ing"&&(a.error=I)),a;i=!1,++o}while(t.length>0);return!0};var rr=Pt,z=rr.asn1,jt=rr.pki,To=rr.pkcs12=rr.pkcs12||{},B1={name:"ContentInfo",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:z.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},n3={name:"PFX",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:z.Class.UNIVERSAL,type:z.Type.INTEGER,constructed:!1,capture:"version"},B1,{name:"PFX.macData",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:z.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:z.Class.UNIVERSAL,type:z.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:z.Class.UNIVERSAL,type:z.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:z.Class.UNIVERSAL,type:z.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},s3={name:"SafeBag",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:z.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:z.Class.UNIVERSAL,type:z.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},i3={name:"Attribute",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:z.Class.UNIVERSAL,type:z.Type.SET,constructed:!0,capture:"values"}]},a3={name:"CertBag",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:z.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:z.Class.UNIVERSAL,type:z.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Ja(e,t,r,n){for(var s=[],i=0;i<e.length;i++)for(var a=0;a<e[i].safeBags.length;a++){var o=e[i].safeBags[a];if(!(n!==void 0&&o.type!==n)){if(t===null){s.push(o);continue}o.attributes[t]!==void 0&&o.attributes[t].indexOf(r)>=0&&s.push(o)}}return s}To.pkcs12FromAsn1=function(e,t,r){typeof t=="string"?(r=t,t=!0):t===void 0&&(t=!0);var n={},s=[];if(!z.validate(e,n3,n,s)){var i=new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw i.errors=i,i}var a={version:n.version.charCodeAt(0),safeContents:[],getBags:function(w){var b={},C;return"localKeyId"in w?C=w.localKeyId:"localKeyIdHex"in w&&(C=rr.util.hexToBytes(w.localKeyIdHex)),C===void 0&&!("friendlyName"in w)&&"bagType"in w&&(b[w.bagType]=Ja(a.safeContents,null,null,w.bagType)),C!==void 0&&(b.localKeyId=Ja(a.safeContents,"localKeyId",C,w.bagType)),"friendlyName"in w&&(b.friendlyName=Ja(a.safeContents,"friendlyName",w.friendlyName,w.bagType)),b},getBagsByFriendlyName:function(w,b){return Ja(a.safeContents,"friendlyName",w,b)},getBagsByLocalKeyId:function(w,b){return Ja(a.safeContents,"localKeyId",w,b)}};if(n.version.charCodeAt(0)!==3){var i=new Error("PKCS#12 PFX of version other than 3 not supported.");throw i.version=n.version.charCodeAt(0),i}if(z.derToOid(n.contentType)!==jt.oids.data){var i=new Error("Only PKCS#12 PFX in password integrity mode supported.");throw i.oid=z.derToOid(n.contentType),i}var o=n.content.value[0];if(o.tagClass!==z.Class.UNIVERSAL||o.type!==z.Type.OCTETSTRING)throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(o=Ep(o),n.mac){var l=null,c=0,d=z.derToOid(n.macAlgorithm);switch(d){case jt.oids.sha1:l=rr.md.sha1.create(),c=20;break;case jt.oids.sha256:l=rr.md.sha256.create(),c=32;break;case jt.oids.sha384:l=rr.md.sha384.create(),c=48;break;case jt.oids.sha512:l=rr.md.sha512.create(),c=64;break;case jt.oids.md5:l=rr.md.md5.create(),c=16;break}if(l===null)throw new Error("PKCS#12 uses unsupported MAC algorithm: "+d);var f=new rr.util.ByteBuffer(n.macSalt),h="macIterations"in n?parseInt(rr.util.bytesToHex(n.macIterations),16):1,m=To.generateKey(r,f,3,h,c,l),g=rr.hmac.create();g.start(l,m),g.update(o.value);var v=g.getMac();if(v.getBytes()!==n.macDigest)throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}return o3(a,o.value,t,r),a};function Ep(e){if(e.composed||e.constructed){for(var t=rr.util.createBuffer(),r=0;r<e.value.length;++r)t.putBytes(e.value[r].value);e.composed=e.constructed=!1,e.value=t.getBytes()}return e}function o3(e,t,r,n){if(t=z.fromDer(t,r),t.tagClass!==z.Class.UNIVERSAL||t.type!==z.Type.SEQUENCE||t.constructed!==!0)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var s=0;s<t.value.length;s++){var i=t.value[s],a={},o=[];if(!z.validate(i,B1,a,o)){var l=new Error("Cannot read ContentInfo.");throw l.errors=o,l}var c={encrypted:!1},d=null,f=a.content.value[0];switch(z.derToOid(a.contentType)){case jt.oids.data:if(f.tagClass!==z.Class.UNIVERSAL||f.type!==z.Type.OCTETSTRING)throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");d=Ep(f).value;break;case jt.oids.encryptedData:d=l3(f,n),c.encrypted=!0;break;default:var l=new Error("Unsupported PKCS#12 contentType.");throw l.contentType=z.derToOid(a.contentType),l}c.safeBags=c3(d,r,n),e.safeContents.push(c)}}function l3(e,t){var r={},n=[];if(!z.validate(e,rr.pkcs7.asn1.encryptedDataValidator,r,n)){var s=new Error("Cannot read EncryptedContentInfo.");throw s.errors=n,s}var i=z.derToOid(r.contentType);if(i!==jt.oids.data){var s=new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw s.oid=i,s}i=z.derToOid(r.encAlgorithm);
20var a=jt.pbe.getCipher(i,r.encParameter,t),o=Ep(r.encryptedContentAsn1),l=rr.util.createBuffer(o.value);if(a.update(l),!a.finish())throw new Error("Failed to decrypt PKCS#12 SafeContents.");return a.output.getBytes()}function c3(e,t,r){if(!t&&e.length===0)return[];if(e=z.fromDer(e,t),e.tagClass!==z.Class.UNIVERSAL||e.type!==z.Type.SEQUENCE||e.constructed!==!0)throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");for(var n=[],s=0;s<e.value.length;s++){var i=e.value[s],a={},o=[];if(!z.validate(i,s3,a,o)){var l=new Error("Cannot read SafeBag.");throw l.errors=o,l}var c={type:z.derToOid(a.bagId),attributes:u3(a.bagAttributes)};n.push(c);var d,f,h=a.bagValue.value[0];switch(c.type){case jt.oids.pkcs8ShroudedKeyBag:if(h=jt.decryptPrivateKeyInfo(h,r),h===null)throw new Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case jt.oids.keyBag:try{c.key=jt.privateKeyFromAsn1(h)}catch{c.key=null,c.asn1=h}continue;case jt.oids.certBag:d=a3,f=function(){if(z.derToOid(a.certId)!==jt.oids.x509Certificate){var g=new Error("Unsupported certificate type, only X.509 supported.");throw g.oid=z.derToOid(a.certId),g}var v=z.fromDer(a.cert,t);try{c.cert=jt.certificateFromAsn1(v,!0)}catch{c.cert=null,c.asn1=v}};break;default:var l=new Error("Unsupported PKCS#12 SafeBag type.");throw l.oid=c.type,l}if(d!==void 0&&!z.validate(h,d,a,o)){var l=new Error("Cannot read PKCS#12 "+d.name);throw l.errors=o,l}f()}return n}function u3(e){var t={};if(e!==void 0)for(var r=0;r<e.length;++r){var n={},s=[];if(!z.validate(e[r],i3,n,s)){var i=new Error("Cannot read PKCS#12 BagAttribute.");throw i.errors=s,i}var a=z.derToOid(n.oid);if(jt.oids[a]!==void 0){t[jt.oids[a]]=[];for(var o=0;o<n.values.length;++o)t[jt.oids[a]].push(n.values[o].value)}}return t}To.toPkcs12Asn1=function(e,t,r,n){n=n||{},n.saltSize=n.saltSize||8,n.count=n.count||2048,n.algorithm=n.algorithm||n.encAlgorithm||"aes128","useMac"in n||(n.useMac=!0),"localKeyId"in n||(n.localKeyId=null),"generateLocalKeyId"in n||(n.generateLocalKeyId=!0);var s=n.localKeyId,i;if(s!==null)s=rr.util.hexToBytes(s);else if(n.generateLocalKeyId)if(t){var a=rr.util.isArray(t)?t[0]:t;typeof a=="string"&&(a=jt.certificateFromPem(a));var o=rr.md.sha1.create();o.update(z.toDer(jt.certificateToAsn1(a)).getBytes()),s=o.digest().getBytes()}else s=rr.random.getBytes(20);var l=[];s!==null&&l.push(z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.localKeyId).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.SET,!0,[z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,s)])])),"friendlyName"in n&&l.push(z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.friendlyName).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.SET,!0,[z.create(z.Class.UNIVERSAL,z.Type.BMPSTRING,!1,n.friendlyName)])])),l.length>0&&(i=z.create(z.Class.UNIVERSAL,z.Type.SET,!0,l));var c=[],d=[];t!==null&&(rr.util.isArray(t)?d=t:d=[t]);for(var f=[],h=0;h<d.length;++h){t=d[h],typeof t=="string"&&(t=jt.certificateFromPem(t));var m=h===0?i:void 0,g=jt.certificateToAsn1(t),v=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.certBag).getBytes()),z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.x509Certificate).getBytes()),z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,z.toDer(g).getBytes())])])]),m]);f.push(v)}if(f.length>0){var w=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,f),b=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.data).getBytes()),z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,z.toDer(w).getBytes())])]);c.push(b)}var C=null;if(e!==null){var T=jt.wrapRsaPrivateKey(jt.privateKeyToAsn1(e));r===null?C=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.keyBag).getBytes()),z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[T]),i]):C=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.pkcs8ShroudedKeyBag).getBytes()),z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[jt.encryptPrivateKeyInfo(T,r,n)]),i]);var I=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[C]),k=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.data).getBytes()),z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,z.toDer(I).getBytes())])]);c.push(k)}var _=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,c),M;if(n.useMac){var o=rr.md.sha1.create(),V=new rr.util.ByteBuffer(rr.random.getBytes(n.saltSize)),G=n.count,e=To.generateKey(r,V,3,G,20),L=rr.hmac.create();L.start(o,e),L.update(z.toDer(_).getBytes());var H=L.getMac();M=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.sha1).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.
20NULL,!1,"")]),z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,H.getBytes())]),z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,V.getBytes()),z.create(z.Class.UNIVERSAL,z.Type.INTEGER,!1,z.integerToDer(G).getBytes())])}return z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.INTEGER,!1,z.integerToDer(3).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(jt.oids.data).getBytes()),z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,z.toDer(_).getBytes())])]),M])};To.generateKey=rr.pbe.generatePkcs12Key;var ii=Pt,Tp=ii.asn1,ba=ii.pki=ii.pki||{};ba.pemToDer=function(e){var t=ii.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PEM to DER; PEM is encrypted.");return ii.util.createBuffer(t.body)};ba.privateKeyFromPem=function(e){var t=ii.pem.decode(e)[0];if(t.type!=="PRIVATE KEY"&&t.type!=="RSA PRIVATE KEY"){var r=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert private key from PEM; PEM is encrypted.");var n=Tp.fromDer(t.body);return ba.privateKeyFromAsn1(n)};ba.privateKeyToPem=function(e,t){var r={type:"RSA PRIVATE KEY",body:Tp.toDer(ba.privateKeyToAsn1(e)).getBytes()};return ii.pem.encode(r,{maxline:t})};ba.privateKeyInfoToPem=function(e,t){var r={type:"PRIVATE KEY",body:Tp.toDer(e).getBytes()};return ii.pem.encode(r,{maxline:t})};var Ie=Pt,bu=function(e,t,r,n){var s=Ie.util.createBuffer(),i=e.length>>1,a=i+(e.length&1),o=e.substr(0,a),l=e.substr(i,a),c=Ie.util.createBuffer(),d=Ie.hmac.create();r=t+r;var f=Math.ceil(n/16),h=Math.ceil(n/20);d.start("MD5",o);var m=Ie.util.createBuffer();c.putBytes(r);for(var g=0;g<f;++g)d.start(null,null),d.update(c.getBytes()),c.putBuffer(d.digest()),d.start(null,null),d.update(c.bytes()+r),m.putBuffer(d.digest());d.start("SHA1",l);var v=Ie.util.createBuffer();c.clear(),c.putBytes(r);for(var g=0;g<h;++g)d.start(null,null),d.update(c.getBytes()),c.putBuffer(d.digest()),d.start(null,null),d.update(c.bytes()+r),v.putBuffer(d.digest());return s.putBytes(Ie.util.xorBytes(m.getBytes(),v.getBytes(),n)),s},d3=function(e,t,r){var n=Ie.hmac.create();n.start("SHA1",e);var s=Ie.util.createBuffer();return s.putInt32(t[0]),s.putInt32(t[1]),s.putByte(r.type),s.putByte(r.version.major),s.putByte(r.version.minor),s.putInt16(r.length),s.putBytes(r.fragment.bytes()),n.update(s.getBytes()),n.digest().getBytes()},f3=function(e,t,r){var n=!1;try{var s=e.deflate(t.fragment.getBytes());t.fragment=Ie.util.createBuffer(s),t.length=s.length,n=!0}catch{}return n},h3=function(e,t,r){var n=!1;try{var s=e.inflate(t.fragment.getBytes());t.fragment=Ie.util.createBuffer(s),t.length=s.length,n=!0}catch{}return n},mn=function(e,t){var r=0;switch(t){case 1:r=e.getByte();break;case 2:r=e.getInt16();break;case 3:r=e.getInt24();break;case 4:r=e.getInt32();break}return Ie.util.createBuffer(e.getBytes(r))},bn=function(e,t,r){e.putInt(r.length(),t<<3),e.putBuffer(r)},j={};j.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};j.SupportedVersions=[j.Versions.TLS_1_1,j.Versions.TLS_1_0];j.Version=j.SupportedVersions[0];j.MaxFragment=15360;j.ConnectionEnd={server:0,client:1};j.PRFAlgorithm={tls_prf_sha256:0};j.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};j.CipherType={stream:0,block:1,aead:2};j.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};j.CompressionMethod={none:0,deflate:1};j.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};j.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};j.Alert={};j.Alert.Level={warning:1,fatal:2};j.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_de
20nied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};j.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};j.CipherSuites={};j.getCipherSuite=function(e){var t=null;for(var r in j.CipherSuites){var n=j.CipherSuites[r];if(n.id[0]===e.charCodeAt(0)&&n.id[1]===e.charCodeAt(1)){t=n;break}}return t};j.handleUnexpected=function(e,t){var r=!e.open&&e.entity===j.ConnectionEnd.client;r||e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.unexpected_message}})};j.handleHelloRequest=function(e,t,r){!e.handshaking&&e.handshakes>0&&(j.queue(e,j.createAlert(e,{level:j.Alert.Level.warning,description:j.Alert.Description.no_renegotiation})),j.flush(e)),e.process()};j.parseHelloMessage=function(e,t,r){var n=null,s=e.entity===j.ConnectionEnd.client;if(r<38)e.error(e,{message:s?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.illegal_parameter}});else{var i=t.fragment,a=i.length();if(n={version:{major:i.getByte(),minor:i.getByte()},random:Ie.util.createBuffer(i.getBytes(32)),session_id:mn(i,1),extensions:[]},s?(n.cipher_suite=i.getBytes(2),n.compression_method=i.getByte()):(n.cipher_suites=mn(i,2),n.compression_methods=mn(i,1)),a=r-(a-i.length()),a>0){for(var o=mn(i,2);o.length()>0;)n.extensions.push({type:[o.getByte(),o.getByte()],data:mn(o,2)});if(!s)for(var l=0;l<n.extensions.length;++l){var c=n.extensions[l];if(c.type[0]===0&&c.type[1]===0)for(var d=mn(c.data,2);d.length()>0;){var f=d.getByte();if(f!==0)break;e.session.extensions.server_name.serverNameList.push(mn(d,2).getBytes())}}}if(e.session.version&&(n.version.major!==e.session.version.major||n.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.protocol_version}});if(s)e.session.cipherSuite=j.getCipherSuite(n.cipher_suite);else for(var h=Ie.util.createBuffer(n.cipher_suites.bytes());h.length()>0&&(e.session.cipherSuite=j.getCipherSuite(h.getBytes(2)),e.session.cipherSuite===null););if(e.session.cipherSuite===null)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.handshake_failure},cipherSuite:Ie.util.bytesToHex(n.cipher_suite)});s?e.session.compressionMethod=n.compression_method:e.session.compressionMethod=j.CompressionMethod.none}return n};j.createSecurityParameters=function(e,t){var r=e.entity===j.ConnectionEnd.client,n=t.random.bytes(),s=r?e.session.sp.client_random:n,i=r?n:j.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:j.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:s,server_random:i}};j.handleServerHello=function(e,t,r){var n=j.parseHelloMessage(e,t,r);if(!e.fail){if(n.version.minor<=e.version.minor)e.version.minor=n.version.minor;else return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.protocol_version}});e.session.version=e.version;var s=n.session_id.bytes();s.length>0&&s===e.session.id?(e.expect=D1,e.session.resuming=!0,e.session.sp.server_random=n.random.bytes()):(e.expect=m3,e.session.resuming=!1,j.createSecurityParameters(e,n)),e.session.id=s,e.process()}};j.handleClientHello=function(e,t,r){var n=j.parseHelloMessage(e,t,r);if(!e.fail){var s=n.session_id.bytes(),i=null;if(e.sessionCache&&(i=e.sessionCache.getSession(s),i===null?s="":(i.version.major!==n.version.major||i.version.minor>n.version.minor)&&(i=null,s="")),s.length===0&&(s=Ie.random.getBytes(32)),e.session.id=s,e.session.clientHelloVersion=n.version,e.session.sp={},i)e.version=e.session.version=i.version,e.session.sp=i.sp;else{for(var a,o=1;o<j.SupportedVersions.length&&(a=j.SupportedVersions[o],!(a.minor<=n.version.minor));++o);e.version={major:a.major,minor:a.minor},e.session.version=e.version}i!==null?(e.expect=_p,e.session.resuming=!0,e.session.sp.client_random=n.random.bytes()):(e.expect=e.verifyClient!==!1?C3:Wf,e.session.resuming=!1,j.createSecurityParameters(e,n)),e.open=!0,j.queue(e,j.createRecord(e,{type:j.ContentType.handshake,data:j.createServerHello(e)})),e.session.resuming?(j.queue(e,j.createRecord(e,{type:j.ContentType.change_cipher_spec,data:j.createChangeCipherSpec()})),e.state.pending=j.createConnectionState(e),e.state.current.write=e.state.pending.write,j.queue(e,j.createRecord(e,{type:j.ContentType.handshake,data:j.createFinished(e)}))):(j.queue(e,j.createRecord(e,{type:j.ContentType.handshake,data:j.createCertificate(e)})),e.fail||(j.queue(e,j.createRecord(e,{type:j.ContentType.handshake,data:j.createServerKeyExchange(e)}
20)),e.verifyClient!==!1&&j.queue(e,j.createRecord(e,{type:j.ContentType.handshake,data:j.createCertificateRequest(e)})),j.queue(e,j.createRecord(e,{type:j.ContentType.handshake,data:j.createServerHelloDone(e)})))),j.flush(e),e.process()}};j.handleCertificate=function(e,t,r){if(r<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.illegal_parameter}});var n=t.fragment,s={certificate_list:mn(n,3)},i,a,o=[];try{for(;s.certificate_list.length()>0;)i=mn(s.certificate_list,3),a=Ie.asn1.fromDer(i),i=Ie.pki.certificateFromAsn1(a,!0),o.push(i)}catch(c){return e.error(e,{message:"Could not parse certificate list.",cause:c,send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.bad_certificate}})}var l=e.entity===j.ConnectionEnd.client;(l||e.verifyClient===!0)&&o.length===0?e.error(e,{message:l?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.illegal_parameter}}):o.length===0?e.expect=l?r0:Wf:(l?e.session.serverCertificate=o[0]:e.session.clientCertificate=o[0],j.verifyCertificateChain(e,o)&&(e.expect=l?r0:Wf)),e.process()};j.handleServerKeyExchange=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.unsupported_certificate}});e.expect=g3,e.process()};j.handleClientKeyExchange=function(e,t,r){if(r<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.unsupported_certificate}});var n=t.fragment,s={enc_pre_master_secret:mn(n,2).getBytes()},i=null;if(e.getPrivateKey)try{i=e.getPrivateKey(e,e.session.serverCertificate),i=Ie.pki.privateKeyFromPem(i)}catch(l){e.error(e,{message:"Could not get private key.",cause:l,send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.internal_error}})}if(i===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.internal_error}});try{var a=e.session.sp;a.pre_master_secret=i.decrypt(s.enc_pre_master_secret);var o=e.session.clientHelloVersion;if(o.major!==a.pre_master_secret.charCodeAt(0)||o.minor!==a.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch{a.pre_master_secret=Ie.random.getBytes(48)}e.expect=_p,e.session.clientCertificate!==null&&(e.expect=S3),e.process()};j.handleCertificateRequest=function(e,t,r){if(r<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.illegal_parameter}});var n=t.fragment,s={certificate_types:mn(n,1),certificate_authorities:mn(n,2)};e.session.certificateRequest=s,e.expect=y3,e.process()};j.handleCertificateVerify=function(e,t,r){if(r<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.illegal_parameter}});var n=t.fragment;n.read-=4;var s=n.bytes();n.read+=4;var i={signature:mn(n,2).getBytes()},a=Ie.util.createBuffer();a.putBuffer(e.session.md5.digest()),a.putBuffer(e.session.sha1.digest()),a=a.getBytes();try{var o=e.session.clientCertificate;if(!o.publicKey.verify(a,i.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(s),e.session.sha1.update(s)}catch{return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.handshake_failure}})}e.expect=_p,e.process()};j.handleServerHelloDone=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.record_overflow}});if(e.serverCertificate===null){var n={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.insufficient_security}},s=0,i=e.verify(e,n.alert.description,s,[]);if(i!==!0)return(i||i===0)&&(typeof i=="object"&&!Ie.util.isArray(i)?(i.message&&(n.message=i.message),i.alert&&(n.alert.description=i.alert)):typeof i=="number"&&(n.alert.description=i)),e.error(e,n)}e.session.certificateRequest!==null&&(t=j.createRecord(e,{type:j.ContentType.handshake,data:j.createCertificate(e)}),j.queue(e,t)),t=j.createRecord(e,{type:j.ContentType.handshake,data:j.createClientKeyExchange(e)}
20),j.queue(e,t),e.expect=b3;var a=function(o,l){o.session.certificateRequest!==null&&o.session.clientCertificate!==null&&j.queue(o,j.createRecord(o,{type:j.ContentType.handshake,data:j.createCertificateVerify(o,l)})),j.queue(o,j.createRecord(o,{type:j.ContentType.change_cipher_spec,data:j.createChangeCipherSpec()})),o.state.pending=j.createConnectionState(o),o.state.current.write=o.state.pending.write,j.queue(o,j.createRecord(o,{type:j.ContentType.handshake,data:j.createFinished(o)})),o.expect=D1,j.flush(o),o.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return a(e,null);j.getClientSignature(e,a)};j.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.illegal_parameter}});var r=e.entity===j.ConnectionEnd.client;(e.session.resuming&&r||!e.session.resuming&&!r)&&(e.state.pending=j.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&r||e.session.resuming&&!r)&&(e.state.pending=null),e.expect=r?v3:E3,e.process()};j.handleFinished=function(e,t,r){var n=t.fragment;n.read-=4;var s=n.bytes();n.read+=4;var i=t.fragment.getBytes();n=Ie.util.createBuffer(),n.putBuffer(e.session.md5.digest()),n.putBuffer(e.session.sha1.digest());var a=e.entity===j.ConnectionEnd.client,o=a?"server finished":"client finished",l=e.session.sp,c=12,d=bu;if(n=d(l.master_secret,o,n.getBytes(),c),n.getBytes()!==i)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.decrypt_error}});e.session.md5.update(s),e.session.sha1.update(s),(e.session.resuming&&a||!e.session.resuming&&!a)&&(j.queue(e,j.createRecord(e,{type:j.ContentType.change_cipher_spec,data:j.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,j.queue(e,j.createRecord(e,{type:j.ContentType.handshake,data:j.createFinished(e)}))),e.expect=a?x3:T3,e.handshaking=!1,++e.handshakes,e.peerCertificate=a?e.session.serverCertificate:e.session.clientCertificate,j.flush(e),e.isConnected=!0,e.connected(e),e.process()};j.handleAlert=function(e,t){var r=t.fragment,n={level:r.getByte(),description:r.getByte()},s;switch(n.description){case j.Alert.Description.close_notify:s="Connection closed.";break;case j.Alert.Description.unexpected_message:s="Unexpected message.";break;case j.Alert.Description.bad_record_mac:s="Bad record MAC.";break;case j.Alert.Description.decryption_failed:s="Decryption failed.";break;case j.Alert.Description.record_overflow:s="Record overflow.";break;case j.Alert.Description.decompression_failure:s="Decompression failed.";break;case j.Alert.Description.handshake_failure:s="Handshake failure.";break;case j.Alert.Description.bad_certificate:s="Bad certificate.";break;case j.Alert.Description.unsupported_certificate:s="Unsupported certificate.";break;case j.Alert.Description.certificate_revoked:s="Certificate revoked.";break;case j.Alert.Description.certificate_expired:s="Certificate expired.";break;case j.Alert.Description.certificate_unknown:s="Certificate unknown.";break;case j.Alert.Description.illegal_parameter:s="Illegal parameter.";break;case j.Alert.Description.unknown_ca:s="Unknown certificate authority.";break;case j.Alert.Description.access_denied:s="Access denied.";break;case j.Alert.Description.decode_error:s="Decode error.";break;case j.Alert.Description.decrypt_error:s="Decrypt error.";break;case j.Alert.Description.export_restriction:s="Export restriction.";break;case j.Alert.Description.protocol_version:s="Unsupported protocol version.";break;case j.Alert.Description.insufficient_security:s="Insufficient security.";break;case j.Alert.Description.internal_error:s="Internal error.";break;case j.Alert.Description.user_canceled:s="User canceled.";break;case j.Alert.Description.no_renegotiation:s="Renegotiation not supported.";break;default:s="Unknown error.";break}if(n.description===j.Alert.Description.close_notify)return e.close();e.error(e,{message:s,send:!1,origin:e.entity===j.ConnectionEnd.client?"server"
20:"client",alert:n}),e.process()};j.handleHandshake=function(e,t){var r=t.fragment,n=r.getByte(),s=r.getInt24();if(s>r.length())return e.fragmented=t,t.fragment=Ie.util.createBuffer(),r.read-=4,e.process();e.fragmented=null,r.read-=4;var i=r.bytes(s+4);r.read+=4,n in Ac[e.entity][e.expect]?(e.entity===j.ConnectionEnd.server&&!e.open&&!e.fail&&(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:Ie.md.md5.create(),sha1:Ie.md.sha1.create()}),n!==j.HandshakeType.hello_request&&n!==j.HandshakeType.certificate_verify&&n!==j.HandshakeType.finished&&(e.session.md5.update(i),e.session.sha1.update(i)),Ac[e.entity][e.expect][n](e,t,s)):j.handleUnexpected(e,t)};j.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};j.handleHeartbeat=function(e,t){var r=t.fragment,n=r.getByte(),s=r.getInt16(),i=r.getBytes(s);if(n===j.HeartbeatMessageType.heartbeat_request){if(e.handshaking||s>i.length)return e.process();j.queue(e,j.createRecord(e,{type:j.ContentType.heartbeat,data:j.createHeartbeat(j.HeartbeatMessageType.heartbeat_response,i)})),j.flush(e)}else if(n===j.HeartbeatMessageType.heartbeat_response){if(i!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,Ie.util.createBuffer(i))}e.process()};var p3=0,m3=1,r0=2,g3=3,y3=4,D1=5,v3=6,x3=7,b3=8,w3=0,C3=1,Wf=2,S3=3,_p=4,E3=5,T3=6,P=j.handleUnexpected,L1=j.handleChangeCipherSpec,Nr=j.handleAlert,Wr=j.handleHandshake,M1=j.handleApplicationData,Rr=j.handleHeartbeat,Ip=[];Ip[j.ConnectionEnd.client]=[[P,Nr,Wr,P,Rr],[P,Nr,Wr,P,Rr],[P,Nr,Wr,P,Rr],[P,Nr,Wr,P,Rr],[P,Nr,Wr,P,Rr],[L1,Nr,P,P,Rr],[P,Nr,Wr,P,Rr],[P,Nr,Wr,M1,Rr],[P,Nr,Wr,P,Rr]];Ip[j.ConnectionEnd.server]=[[P,Nr,Wr,P,Rr],[P,Nr,Wr,P,Rr],[P,Nr,Wr,P,Rr],[P,Nr,Wr,P,Rr],[L1,Nr,P,P,Rr],[P,Nr,Wr,P,Rr],[P,Nr,Wr,M1,Rr],[P,Nr,Wr,P,Rr]];var Os=j.handleHelloRequest,_3=j.handleServerHello,O1=j.handleCertificate,n0=j.handleServerKeyExchange,kd=j.handleCertificateRequest,Bl=j.handleServerHelloDone,F1=j.handleFinished,Ac=[];Ac[j.ConnectionEnd.client]=[[P,P,_3,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P],[Os,P,P,P,P,P,P,P,P,P,P,O1,n0,kd,Bl,P,P,P,P,P,P],[Os,P,P,P,P,P,P,P,P,P,P,P,n0,kd,Bl,P,P,P,P,P,P],[Os,P,P,P,P,P,P,P,P,P,P,P,P,kd,Bl,P,P,P,P,P,P],[Os,P,P,P,P,P,P,P,P,P,P,P,P,P,Bl,P,P,P,P,P,P],[Os,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P],[Os,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,F1],[Os,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P],[Os,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P]];var I3=j.handleClientHello,A3=j.handleClientKeyExchange,k3=j.handleCertificateVerify;Ac[j.ConnectionEnd.server]=[[P,I3,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P],[P,P,P,P,P,P,P,P,P,P,P,O1,P,P,P,P,P,P,P,P,P],[P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,A3,P,P,P,P],[P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,k3,P,P,P,P,P],[P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P],[P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,F1],[P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P],[P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P]];j.generateKeys=function(e,t){var r=bu,n=t.client_random+t.server_random;e.session.resuming||(t.master_secret=r(t.pre_master_secret,"master secret",n,48).bytes(),t.pre_master_secret=null),n=t.server_random+t.client_random;var s=2*t.mac_key_length+2*t.enc_key_length,i=e.version.major===j.Versions.TLS_1_0.major&&e.version.minor===j.Versions.TLS_1_0.minor;i&&(s+=2*t.fixed_iv_length);var a=r(t.master_secret,"key expansion",n,s),o={client_write_MAC_key:a.getBytes(t.mac_key_length),server_write_MAC_key:a.getBytes(t.mac_key_length),client_write_key:a.getBytes(t.enc_key_length),server_write_key:a.getBytes(t.enc_key_length)};return i&&(o.client_write_IV=a.getBytes(t.fixed_iv_length),o.server_write_IV=a.getBytes(t.fixed_iv_length)),o};j.createConnectionState=function(e){var t=e.entity===j.ConnectionEnd.client,r=function(){var i={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(a){return!0},compressionState:null,compressFunction:function(a){return!0},updateSequenceNumber:function(){i.sequenceNumber[1]===4294967295?(i.sequenceNumber[1]=0,++i.sequenceNumber[0]):++i.sequenceNumber[1]}};return i},n={read:r(),write:r()};if(n.read.update=function(i,a){return n.read.cipherFunction(a,n.read)?n.read.compressFunction(i,a,n.read)||i.error(i,{message:"Could not decompress record.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.decompression_failure}}):i.error(i,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.bad_record_mac}}),!i.fail},n.write.update=function(i,a){return n.write.compressFunction(i,a,n.write)?n.write.cipherFunction(a,n.write)||i.error(i,{message:"Could not encrypt record.",send:!1,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.internal_error}}):i.error(i,{message:"Could not compress record.",send:!1,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.internal_error}}),!i.fail},e.session){var s=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(s),s.keys=j.generateKeys(e,s),n.read.macKey=t?s.keys.server_write_MAC_key:s.keys.client_write_MAC_key,n.write.macKey=t?s.keys.client_write_MAC_key:s.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(n,e,s),s.compression_algorithm){case j.CompressionMethod.none:break;case j.CompressionMethod.deflate:n.read.compressFunction=h3,n.write.compressFunction=f3;break;default:throw new Error("Unsupported compression algorithm.")}}return n};j.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*6e4,r=Ie.util.createBuffer();return r.putInt32(t),r.putBytes(Ie.random.getBytes(28)),r};j.createRecord=function(e,t){if(!t.data)return null;var r={type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data};return r};j.createAlert=function(e,t){var r=Ie.util.createBuffer();return r.putByte(t.level),r.putByte(t.description),j.createRecord(e,{type:j.ContentType.alert,data:r})};j.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=Ie.util.createBuffer(),r=0;r<e.cipherSuites.length;++r){var n=e.cipherSuites[r];t.putByte(n.id[0]),t.putByte(n.id[1])}var s=t.length(),i=Ie.util.createBuffer();i.putByte(j.CompressionMethod.none);var a=i.length(),o=Ie.util.createBuffer();if(e.virtualHost){var l=Ie.util.createBuffer();l.putByte(0),l.putByte(0);var c=Ie.util.createBuffer();c.putByte(0),bn(c,2,Ie.util.createBuffer(e.virtualHost));var d=Ie.util.createBuffer();bn(d,2,c),bn(l,2,d),o.putBuffer(l)}var f=o.length();f>0&&(f+=2);var h=e.session.id,m=h.length+1+2+4+28+2+s+1+a+f,g=Ie.util.createBuffer();return g.putByte(j.HandshakeType.client_hello),g.putInt24(m),g.putByte(e.version.major),g.putByte(e.version.minor),g.putBytes(e.session.sp.client_random),bn(g,1,Ie.util.createBuffer(h)),bn(g,2,t),bn(g,1,i),f>0&&bn(g,2,o),g};j.createServerHello=function(e){var t=e.session.id,r=t.length+1+2+4+28+2+1,n=Ie.util.createBuffer();return n.putByte(j.HandshakeType.server_hello),n.putInt24(r),n.putByte(e.version.major),n.putByte(e.version.minor),n.putBytes(e.session.sp.server_random),bn(n,1,Ie.util.createBuffer(t)),n.putByte(e.session.cipherSuite.id[0]),n.putByte(e.session.cipherSuite.id[1]),n.putByte(e.session.compressionMethod),n};j.createCertificate=function(e){var t=e.entity===j.ConnectionEnd.client,r=null;if(e.getCertificate){var n;t?n=e.session.certificateRequest:n=e.session.extensions.server_name.serverNameList,r=e.getCertificate(e,n)}var s=Ie.util.createBuffer();if(r!==null)try{Ie.util.isArray(r)||(r=[r]);for(var i=null,a=0;a<r.length;++a){var o=Ie.pem.decode(r[a])[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE"){var l=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw l.headerType=o.type,l}if(o.procType&&o.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var c=Ie.util.createBuffer(o.body);i===null&&(i=Ie.asn1.fromDer(c.bytes(),!1));var d=Ie.util.createBuffer();bn(d,3,c),s.putBuffer(d)}r=Ie.pki.certificateFromAsn1(i),t?e.session.clientCertificate=r:e.session.serverCertificate=r}catch(m){return e.error(e,{message:"Could not send certificate list.",cause:m,send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.bad_certificate}})}var f=3+s.length(),h=Ie.util.createBuffer();return h.putByte(j.HandshakeType.certificate),h.putInt24(f),bn(h,3,s),h};j.createClientKeyExchange=function(e){var t=Ie.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(Ie.random.getBytes(46));var r=e.session.sp;r.pre_master_secret=t.getBytes();var n=e.session.serverCertificate.publicKey;
20t=n.encrypt(r.pre_master_secret);var s=t.length+2,i=Ie.util.createBuffer();return i.putByte(j.HandshakeType.client_key_exchange),i.putInt24(s),i.putInt16(t.length),i.putBytes(t),i};j.createServerKeyExchange=function(e){var t=Ie.util.createBuffer();return t};j.getClientSignature=function(e,t){var r=Ie.util.createBuffer();r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest()),r=r.getBytes(),e.getSignature=e.getSignature||function(n,s,i){var a=null;if(n.getPrivateKey)try{a=n.getPrivateKey(n,n.session.clientCertificate),a=Ie.pki.privateKeyFromPem(a)}catch(o){n.error(n,{message:"Could not get private key.",cause:o,send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.internal_error}})}a===null?n.error(n,{message:"No private key set.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.internal_error}}):s=a.sign(s,null),i(n,s)},e.getSignature(e,r,t)};j.createCertificateVerify=function(e,t){var r=t.length+2,n=Ie.util.createBuffer();return n.putByte(j.HandshakeType.certificate_verify),n.putInt24(r),n.putInt16(t.length),n.putBytes(t),n};j.createCertificateRequest=function(e){var t=Ie.util.createBuffer();t.putByte(1);var r=Ie.util.createBuffer();for(var n in e.caStore.certs){var s=e.caStore.certs[n],i=Ie.pki.distinguishedNameToAsn1(s.subject),a=Ie.asn1.toDer(i);r.putInt16(a.length()),r.putBuffer(a)}var o=1+t.length()+2+r.length(),l=Ie.util.createBuffer();return l.putByte(j.HandshakeType.certificate_request),l.putInt24(o),bn(l,1,t),bn(l,2,r),l};j.createServerHelloDone=function(e){var t=Ie.util.createBuffer();return t.putByte(j.HandshakeType.server_hello_done),t.putInt24(0),t};j.createChangeCipherSpec=function(){var e=Ie.util.createBuffer();return e.putByte(1),e};j.createFinished=function(e){var t=Ie.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var r=e.entity===j.ConnectionEnd.client,n=e.session.sp,s=12,i=bu,a=r?"client finished":"server finished";t=i(n.master_secret,a,t.getBytes(),s);var o=Ie.util.createBuffer();return o.putByte(j.HandshakeType.finished),o.putInt24(t.length()),o.putBuffer(t),o};j.createHeartbeat=function(e,t,r){typeof r>"u"&&(r=t.length);var n=Ie.util.createBuffer();n.putByte(e),n.putInt16(r),n.putBytes(t);var s=n.length(),i=Math.max(16,s-r-3);return n.putBytes(Ie.random.getBytes(i)),n};j.queue=function(e,t){if(t&&!(t.fragment.length()===0&&(t.type===j.ContentType.handshake||t.type===j.ContentType.alert||t.type===j.ContentType.change_cipher_spec))){if(t.type===j.ContentType.handshake){var r=t.fragment.bytes();e.session.md5.update(r),e.session.sha1.update(r),r=null}var n;if(t.fragment.length()<=j.MaxFragment)n=[t];else{n=[];for(var s=t.fragment.bytes();s.length>j.MaxFragment;)n.push(j.createRecord(e,{type:t.type,data:Ie.util.createBuffer(s.slice(0,j.MaxFragment))})),s=s.slice(j.MaxFragment);s.length>0&&n.push(j.createRecord(e,{type:t.type,data:Ie.util.createBuffer(s)}))}for(var i=0;i<n.length&&!e.fail;++i){var a=n[i],o=e.state.current.write;o.update(e,a)&&e.records.push(a)}}};j.flush=function(e){for(var t=0;t<e.records.length;++t){var r=e.records[t];e.tlsData.putByte(r.type),e.tlsData.putByte(r.version.major),e.tlsData.putByte(r.version.minor),e.tlsData.putInt16(r.fragment.length()),e.tlsData.putBuffer(e.records[t].fragment)}return e.records=[],e.tlsDataReady(e)};var Nd=function(e){switch(e){case!0:return!0;case Ie.pki.certificateError.bad_certificate:return j.Alert.Description.bad_certificate;case Ie.pki.certificateError.unsupported_certificate:return j.Alert.Description.unsupported_certificate;case Ie.pki.certificateError.certificate_revoked:return j.Alert.Description.certificate_revoked;case Ie.pki.certificateError.certificate_expired:return j.Alert.Description.certificate_expired;case Ie.pki.certificateError.certificate_unknown:return j.Alert.Description.certificate_unknown;case Ie.pki.certificateError.unknown_ca:return j.Alert.Description.unknown_ca;default:return j.Alert.Description.bad_certificate}},N3=function(e){switch(e){case!0:return!0;case j.Alert.Description.bad_certificate:return Ie.pki.certificateError.bad_certificate;case j.Alert.Description.unsupported_certificate:return Ie.pki.certificateError.unsupported_certificate;case j.Alert.Description.certificate_revoked:return Ie.pki.certificateError.certificate_revoked;case j.Alert.Description.certificate_expired:return Ie.pki.certificateError.certificate_expired;case j.Alert.Description.certificate_unknown:return Ie.pki.certificateError.certificate_unknown;case j.Alert.Description.unknown_ca:return Ie.pki.certificateError.unknown_ca;default:return Ie.pki.certificateError.bad_certificate}};j.verifyCertificateChain=function(e,t){try{var r={};for(var n in e.verifyOptions)r[n]=e.verifyOptions[n];r.verify=function(i,a,o){var l=Nd(i),c=e.verify(e,i,a,o);if(c!==!0){if(typeof c=="object"&&!Ie.util.isArray(c)){var d=new Error("The application rejected the certificate.");throw d.send=!0,d.alert={level:j.Alert.Level.fatal,description:j.Alert.Description.bad_certificate},c.message&&(d.message=c.message),c.alert&&(d.alert.description=c.alert),d}c!==i&&(c=N3(c))}return c},Ie.pki.verifyCertificateChain(e.caStore,t,r)}catch(i){var s=i;(typeof s!="object"||Ie.util.isArray(s))&&(s={send:!0,alert:{level:j.Alert.Level.fatal,description:Nd(i)}}),"send"in s||(s.send=!0),"alert"in s||(s.alert={level:j.Alert.Level.fatal,description:Nd(s.error)}),e.error(e,s)}return!e.fail};j.createSessionCache=function(e,t){var r=null;if(e&&e.getSession&&e.setSession&&e.order)r=e;else{r={},r.cache=e||{},r.capacity=Math.max(t||100,1),r.order=[];for(var n in e)r.order.length<=t?r.order.push(n):delete e[n];r.getSession=function(s){var i=null,a=null;if(s?a=Ie.util.bytesToHex(s):r.order.length>
200&&(a=r.order[0]),a!==null&&a in r.cache){i=r.cache[a],delete r.cache[a];for(var o in r.order)if(r.order[o]===a){r.order.splice(o,1);break}}return i},r.setSession=function(s,i){if(r.order.length===r.capacity){var a=r.order.shift();delete r.cache[a]}var a=Ie.util.bytesToHex(s);r.order.push(a),r.cache[a]=i}}return r};j.createConnection=function(e){var t=null;e.caStore?Ie.util.isArray(e.caStore)?t=Ie.pki.createCaStore(e.caStore):t=e.caStore:t=Ie.pki.createCaStore();var r=e.cipherSuites||null;if(r===null){r=[];for(var n in j.CipherSuites)r.push(j.CipherSuites[n])}var s=e.server?j.ConnectionEnd.server:j.ConnectionEnd.client,i=e.sessionCache?j.createSessionCache(e.sessionCache):null,a={version:{major:j.Version.major,minor:j.Version.minor},entity:s,sessionId:e.sessionId,caStore:t,sessionCache:i,cipherSuites:r,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(d,f,h,m){return f},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:Ie.util.createBuffer(),tlsData:Ie.util.createBuffer(),data:Ie.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(d,f){f.origin=f.origin||(d.entity===j.ConnectionEnd.client?"client":"server"),f.send&&(j.queue(d,j.createAlert(d,f.alert)),j.flush(d));var h=f.fatal!==!1;h&&(d.fail=!0),e.error(d,f),h&&d.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};a.reset=function(d){a.version={major:j.Version.major,minor:j.Version.minor},a.record=null,a.session=null,a.peerCertificate=null,a.state={pending:null,current:null},a.expect=a.entity===j.ConnectionEnd.client?p3:w3,a.fragmented=null,a.records=[],a.open=!1,a.handshakes=0,a.handshaking=!1,a.isConnected=!1,a.fail=!(d||typeof d>"u"),a.input.clear(),a.tlsData.clear(),a.data.clear(),a.state.current=j.createConnectionState(a)},a.reset();var o=function(d,f){var h=f.type-j.ContentType.change_cipher_spec,m=Ip[d.entity][d.expect];h in m?m[h](d,f):j.handleUnexpected(d,f)},l=function(d){var f=0,h=d.input,m=h.length();if(m<5)f=5-m;else{d.record={type:h.getByte(),version:{major:h.getByte(),minor:h.getByte()},length:h.getInt16(),fragment:Ie.util.createBuffer(),ready:!1};var g=d.record.version.major===d.version.major;g&&d.session&&d.session.version&&(g=d.record.version.minor===d.version.minor),g||d.error(d,{message:"Incompatible TLS version.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.protocol_version}})}return f},c=function(d){var f=0,h=d.input,m=h.length();if(m<d.record.length)f=d.record.length-m;else{d.record.fragment.putBytes(h.getBytes(d.record.length)),h.compact();var g=d.state.current.read;g.update(d,d.record)&&(d.fragmented!==null&&(d.fragmented.type===d.record.type?(d.fragmented.fragment.putBuffer(d.record.fragment),d.record=d.fragmented):d.error(d,{message:"Invalid fragmented record.",send:!0,alert:{level:j.Alert.Level.fatal,description:j.Alert.Description.unexpected_message}})),d.record.ready=!0)}return f};return a.handshake=function(d){if(a.entity!==j.ConnectionEnd.client)a.error(a,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(a.handshaking)a.error(a,{message:"Handshake already in progress.",fatal:!1});else{a.fail&&!a.open&&a.handshakes===0&&(a.fail=!1),a.handshaking=!0,d=d||"";var f=null;d.length>0&&(a.sessionCache&&(f=a.sessionCache.getSession(d)),f===null&&(d="")),d.length===0&&a.sessionCache&&(f=a.sessionCache.getSession(),f!==null&&(d=f.id)),a.session={id:d,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:Ie.md.md5.create(),sha1:Ie.md.sha1.create()},f&&(a.version=f.version,a.session.sp=f.sp),a.session.sp.client_random=j.createRandom().getBytes(),a.open=!0,j.queue(a,j.createRecord(a,{type:j.ContentType.handshake,data:j.createClientHello(a)})),j.flush(a)}},a.process=function(d){var f=0;return d&&a.input.putBytes(d),a.fail||(a.record!==null&&a.record.ready&&a.record.fragment.isEmpty()&&(a.record=null),a.record===null&&(f=l(a)),!a.fail&&a.record!==null&&!a.record.ready&&(f=c(a)),!a.fail&&a.record!==null&&a.record.ready&&o(a,a.record)),f}
20,a.prepare=function(d){return j.queue(a,j.createRecord(a,{type:j.ContentType.application_data,data:Ie.util.createBuffer(d)})),j.flush(a)},a.prepareHeartbeatRequest=function(d,f){return d instanceof Ie.util.ByteBuffer&&(d=d.bytes()),typeof f>"u"&&(f=d.length),a.expectedHeartbeatPayload=d,j.queue(a,j.createRecord(a,{type:j.ContentType.heartbeat,data:j.createHeartbeat(j.HeartbeatMessageType.heartbeat_request,d,f)})),j.flush(a)},a.close=function(d){if(!a.fail&&a.sessionCache&&a.session){var f={id:a.session.id,version:a.session.version,sp:a.session.sp};f.sp.keys=null,a.sessionCache.setSession(f.id,f)}a.open&&(a.open=!1,a.input.clear(),(a.isConnected||a.handshaking)&&(a.isConnected=a.handshaking=!1,j.queue(a,j.createAlert(a,{level:j.Alert.Level.warning,description:j.Alert.Description.close_notify})),j.flush(a)),a.closed(a)),a.reset(d)},a};Ie.tls=Ie.tls||{};for(var Rd in j)typeof j[Rd]!="function"&&(Ie.tls[Rd]=j[Rd]);Ie.tls.prf_tls1=bu;Ie.tls.hmac_sha1=d3;Ie.tls.createSessionCache=j.createSessionCache;Ie.tls.createConnection=j.createConnection;var Js=Pt,An=Js.tls;An.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=An.BulkCipherAlgorithm.aes,e.cipher_type=An.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=An.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:U1};An.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=An.BulkCipherAlgorithm.aes,e.cipher_type=An.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=An.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:U1};function U1(e,t,r){var n=t.entity===Js.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:Js.cipher.createDecipher("AES-CBC",n?r.keys.server_write_key:r.keys.client_write_key),iv:n?r.keys.server_write_IV:r.keys.client_write_IV},e.write.cipherState={init:!1,cipher:Js.cipher.createCipher("AES-CBC",n?r.keys.client_write_key:r.keys.server_write_key),iv:n?r.keys.client_write_IV:r.keys.server_write_IV},e.read.cipherFunction=B3,e.write.cipherFunction=R3,e.read.macLength=e.write.macLength=r.mac_length,e.read.macFunction=e.write.macFunction=An.hmac_sha1}function R3(e,t){var r=!1,n=t.macFunction(t.macKey,t.sequenceNumber,e);e.fragment.putBytes(n),t.updateSequenceNumber();var s;e.version.minor===An.Versions.TLS_1_0.minor?s=t.cipherState.init?null:t.cipherState.iv:s=Js.random.getBytesSync(16),t.cipherState.init=!0;var i=t.cipherState.cipher;return i.start({iv:s}),e.version.minor>=An.Versions.TLS_1_1.minor&&i.output.putBytes(s),i.update(e.fragment),i.finish(P3)&&(e.fragment=i.output,e.length=e.fragment.length(),r=!0),r}function P3(e,t,r){if(!r){var n=e-t.length()%e;t.fillWithByte(n-1,n)}return!0}function j3(e,t,r){var n=!0;if(r){for(var s=t.length(),i=t.last(),a=s-1-i;a<s-1;++a)n=n&&t.at(a)==i;n&&t.truncate(i+1)}return n}function B3(e,t){var r=!1,n;e.version.minor===An.Versions.TLS_1_0.minor?n=t.cipherState.init?null:t.cipherState.iv:n=e.fragment.getBytes(16),t.cipherState.init=!0;var s=t.cipherState.cipher;s.start({iv:n}),s.update(e.fragment),r=s.finish(j3);var i=t.macLength,a=Js.random.getBytesSync(i),o=s.output.length();o>=i?(e.fragment=s.output.getBytes(o-i),a=s.output.getBytes(i)):e.fragment=s.output.getBytes(),e.fragment=Js.util.createBuffer(e.fragment),e.length=e.fragment.length();var l=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),r=D3(t.macKey,a,l)&&r,r}function D3(e,t,r){var n=Js.hmac.create();return n.start("SHA1",e),n.update(t),t=n.digest().getBytes(),n.start(null,null),n.update(r),r=n.digest().getBytes(),t===r}var lr=Pt,Yo=lr.sha512=lr.sha512||{};lr.md.sha512=lr.md.algorithms.sha512=Yo;var V1=lr.sha384=lr.sha512.sha384=lr.sha512.sha384||{};V1.create=function(){return Yo.create("SHA-384")};lr.md.sha384=lr.md.algorithms.sha384=V1;lr.sha512.sha256=lr.sha512.sha256||{create:function(){return Yo.create("SHA-512/256")}};lr.md["sha512/256"]=lr.md.algorithms["sha512/256"]=lr.sha512.sha256;lr.sha512.sha224=lr.sha512.sha224||{create:function(){return Yo.create("SHA-512/224")}};lr.md["sha512/224"]=lr.md.algorithms["sha512/224"]=lr.sha512.sha224;Yo.create=function(e){if($1||L3(),typeof e>"u"&&(e="SHA-512"),!(e in wi))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=wi[e],r=null,n=lr.util.createBuffer(),s=new Array(80),i=0;i<80;++i)s[i]=new Array(2);var a=64;switch(e){case"SHA-384":a=48;break;case"SHA-512/256":a=32;break;case"SHA-512/224":a=28;break}var o={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:a,messageLength:0,fullMessageLength:null,messageLengthSize:16};return o.start=function(){o.messageLength=0,o.fullMessageLength=o.messageLength128=[];for(var l=o.messageLengthSize/4,c=0;c<l;++c)o.fullMessageLength.push(0);n=lr.util.createBuffer(),r=new Array(t.length);for(var c=0;c<t.length;++c)r[c]=t[c].slice(0);return o},o.start(),o.update=function(l,c){c==="utf8"&&(l=lr.util.encodeUtf8(l));var d=l.length;o.messageLength+=d,d=[d/4294967296>>>0,d>>>0];for(var f=o.fullMessageLength.length-1;f>=0;--f)o.fullMessageLength[f]+=d[1],d[1]=d[0]+(o.fullMessageLength[f]/4294967296>>>0),o.fullMessageLength[f]=o.fullMessageLength[f]>>>0,d[0]=d[1]/4294967296>>>0;return n.putBytes(l),s0(r,s,n),(n.read>2048||n.length()===0)&&n.compact(),o},o.digest=function(){var l=lr.util.createBuffer();l.putBytes(n.bytes());var c=o.fullMessageLength[o.fullMessageLength.length-1]+o.messageLengthSize,d=c&o.blockLength-1;l.putBytes(Yf.substr(0,o.blockLength-d));for(var f,h,m=o.fullMessageLength[0]*8,g=0;g<o.fullMessageLength.length-1;++g)f=o.fullMessageLength[g+1]*8,h=f/4294967296>>>0,m+=h,l.putInt32(m>>>0),m=f>>>0;l.putInt32(m);for(var v=new Array(r.length),g=0;g<r.length;++g)v[g]=r[g].slice(0);s0(v,s,l);var w=lr.util.createBuffer(),b;e==="SHA-512"?b=v.length:e==="SHA-384"?b=v.length-2:b=v.length-4;for(var g=0;g<b;++g)w.putInt32(v[g][0]),(g!==b-1||e!=="SHA-512/224")&&w.putInt32(v[g][1]);return w},o};var Yf=null,$1=!1,Qf=null,wi=null;function L3(){Yf="€",Yf+=lr.util.fillString("\0",128),Qf=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],wi={},wi["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],wi["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],wi["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,28279439
2007],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],wi["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],$1=!0}function s0(e,t,r){for(var n,s,i,a,o,l,c,d,f,h,m,g,v,w,b,C,T,I,k,_,M,V,G,L,H,F,Q,J,oe,xe,ge,$,le,B,Te,ye=r.length();ye>=128;){for(oe=0;oe<16;++oe)t[oe][0]=r.getInt32()>>>0,t[oe][1]=r.getInt32()>>>0;for(;oe<80;++oe)$=t[oe-2],xe=$[0],ge=$[1],n=((xe>>>19|ge<<13)^(ge>>>29|xe<<3)^xe>>>6)>>>0,s=((xe<<13|ge>>>19)^(ge<<3|xe>>>29)^(xe<<26|ge>>>6))>>>0,B=t[oe-15],xe=B[0],ge=B[1],i=((xe>>>1|ge<<31)^(xe>>>8|ge<<24)^xe>>>7)>>>0,a=((xe<<31|ge>>>1)^(xe<<24|ge>>>8)^(xe<<25|ge>>>7))>>>0,le=t[oe-7],Te=t[oe-16],ge=s+le[1]+a+Te[1],t[oe][0]=n+le[0]+i+Te[0]+(ge/4294967296>>>0)>>>0,t[oe][1]=ge>>>0;for(v=e[0][0],w=e[0][1],b=e[1][0],C=e[1][1],T=e[2][0],I=e[2][1],k=e[3][0],_=e[3][1],M=e[4][0],V=e[4][1],G=e[5][0],L=e[5][1],H=e[6][0],F=e[6][1],Q=e[7][0],J=e[7][1],oe=0;oe<80;++oe)c=((M>>>14|V<<18)^(M>>>18|V<<14)^(V>>>9|M<<23))>>>0,d=((M<<18|V>>>14)^(M<<14|V>>>18)^(V<<23|M>>>9))>>>0,f=(H^M&(G^H))>>>0,h=(F^V&(L^F))>>>0,o=((v>>>28|w<<4)^(w>>>2|v<<30)^(w>>>7|v<<25))>>>0,l=((v<<4|w>>>28)^(w<<30|v>>>2)^(w<<25|v>>>7))>>>0,m=(v&b|T&(v^b))>>>0,g=(w&C|I&(w^C))>>>0,ge=J+d+h+Qf[oe][1]+t[oe][1],n=Q+c+f+Qf[oe][0]+t[oe][0]+(ge/4294967296>>>0)>>>0,s=ge>>
20>0,ge=l+g,i=o+m+(ge/4294967296>>>0)>>>0,a=ge>>>0,Q=H,J=F,H=G,F=L,G=M,L=V,ge=_+s,M=k+n+(ge/4294967296>>>0)>>>0,V=ge>>>0,k=T,_=I,T=b,I=C,b=v,C=w,ge=s+a,v=n+i+(ge/4294967296>>>0)>>>0,w=ge>>>0;ge=e[0][1]+w,e[0][0]=e[0][0]+v+(ge/4294967296>>>0)>>>0,e[0][1]=ge>>>0,ge=e[1][1]+C,e[1][0]=e[1][0]+b+(ge/4294967296>>>0)>>>0,e[1][1]=ge>>>0,ge=e[2][1]+I,e[2][0]=e[2][0]+T+(ge/4294967296>>>0)>>>0,e[2][1]=ge>>>0,ge=e[3][1]+_,e[3][0]=e[3][0]+k+(ge/4294967296>>>0)>>>0,e[3][1]=ge>>>0,ge=e[4][1]+V,e[4][0]=e[4][0]+M+(ge/4294967296>>>0)>>>0,e[4][1]=ge>>>0,ge=e[5][1]+L,e[5][0]=e[5][0]+G+(ge/4294967296>>>0)>>>0,e[5][1]=ge>>>0,ge=e[6][1]+F,e[6][0]=e[6][0]+H+(ge/4294967296>>>0)>>>0,e[6][1]=ge>>>0,ge=e[7][1]+J,e[7][0]=e[7][0]+Q+(ge/4294967296>>>0)>>>0,e[7][1]=ge>>>0,ye-=128}}var Ap={},M3=Pt,Ir=M3.asn1;Ap.privateKeyValidator={name:"PrivateKeyInfo",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};Ap.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:Ir.Class.UNIVERSAL,type:Ir.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]};var Br=Pt,z1=Ap,O3=z1.publicKeyValidator,F3=z1.privateKeyValidator;if(typeof U3>"u")var U3=Br.jsbn.BigInteger;var Xf=Br.util.ByteBuffer,an=typeof Buffer>"u"?Uint8Array:Buffer;Br.pki=Br.pki||{};Br.pki.ed25519=Br.ed25519=Br.ed25519||{};var Bt=Br.ed25519;Bt.constants={};Bt.constants.PUBLIC_KEY_BYTE_LENGTH=32;Bt.constants.PRIVATE_KEY_BYTE_LENGTH=64;Bt.constants.SEED_BYTE_LENGTH=32;Bt.constants.SIGN_BYTE_LENGTH=64;Bt.constants.HASH_BYTE_LENGTH=64;Bt.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=Br.random.getBytesSync(Bt.constants.SEED_BYTE_LENGTH);else if(typeof t=="string"){if(t.length!==Bt.constants.SEED_BYTE_LENGTH)throw new TypeError('"seed" must be '+Bt.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');t=Es({message:t,encoding:"binary"});for(var r=new an(Bt.constants.PUBLIC_KEY_BYTE_LENGTH),n=new an(Bt.constants.PRIVATE_KEY_BYTE_LENGTH),s=0;s<32;++s)n[s]=t[s];return K3(r,n),{publicKey:r,privateKey:n}};Bt.privateKeyFromAsn1=function(e){var t={},r=[],n=Br.asn1.validate(e,F3,t,r);if(!n){var s=new Error("Invalid Key.");throw s.errors=r,s}var i=Br.asn1.derToOid(t.privateKeyOid),a=Br.oids.EdDSA25519;if(i!==a)throw new Error('Invalid OID "'+i+'"; OID must be "'+a+'".');var o=t.privateKey,l=Es({message:Br.asn1.fromDer(o).value,encoding:"binary"});return{privateKeyBytes:l}};Bt.publicKeyFromAsn1=function(e){var t={},r=[],n=Br.asn1.validate(e,O3,t,r);if(!n){var s=new Error("Invalid Key.");throw s.errors=r,s}var i=Br.asn1.derToOid(t.publicKeyOid),a=Br.oids.EdDSA25519;if(i!==a)throw new Error('Invalid OID "'+i+'"; OID must be "'+a+'".');var o=t.ed25519PublicKey;if(o.length!==Bt.constants.PUBLIC_KEY_BYTE_LENGTH)throw new Error("Key length is invalid.");return Es({message:o,encoding:"binary"})};Bt.publicKeyFromPrivateKey=function(e){e=e||{};var t=Es({message:e.privateKey,encoding:"binary"});if(t.length!==Bt.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+Bt.constants.PRIVATE_KEY_BYTE_LENGTH);for(var r=new an(Bt.constants.PUBLIC_KEY_BYTE_LENGTH),n=0;n<r.length;++n)r[n]=t[32+n];return r};Bt.sign=function(e){e=e||{};var t=Es(e),r=Es({message:e.privateKey,encoding:"binary"});if(r.length===Bt.constants.SEED_BYTE_LENGTH){var n=Bt.generateKeyPair({seed:r});r=n.privateKey}else if(r.length!==Bt.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+
20Bt.constants.SEED_BYTE_LENGTH+" or "+Bt.constants.PRIVATE_KEY_BYTE_LENGTH);var s=new an(Bt.constants.SIGN_BYTE_LENGTH+t.length);q3(s,t,t.length,r);for(var i=new an(Bt.constants.SIGN_BYTE_LENGTH),a=0;a<i.length;++a)i[a]=s[a];return i};Bt.verify=function(e){e=e||{};var t=Es(e);if(e.signature===void 0)throw new TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var r=Es({message:e.signature,encoding:"binary"});if(r.length!==Bt.constants.SIGN_BYTE_LENGTH)throw new TypeError('"options.signature" must have a byte length of '+Bt.constants.SIGN_BYTE_LENGTH);var n=Es({message:e.publicKey,encoding:"binary"});if(n.length!==Bt.constants.PUBLIC_KEY_BYTE_LENGTH)throw new TypeError('"options.publicKey" must have a byte length of '+Bt.constants.PUBLIC_KEY_BYTE_LENGTH);var s=new an(Bt.constants.SIGN_BYTE_LENGTH+t.length),i=new an(Bt.constants.SIGN_BYTE_LENGTH+t.length),a;for(a=0;a<Bt.constants.SIGN_BYTE_LENGTH;++a)s[a]=r[a];for(a=0;a<t.length;++a)s[a+Bt.constants.SIGN_BYTE_LENGTH]=t[a];return H3(i,s,s.length,n)>=0};function Es(e){var t=e.message;if(t instanceof Uint8Array||t instanceof an)return t;var r=e.encoding;if(t===void 0)if(e.md)t=e.md.digest().getBytes(),r="binary";else throw new TypeError('"options.message" or "options.md" not specified.');if(typeof t=="string"&&!r)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof t=="string"){if(typeof Buffer<"u")return Buffer.from(t,r);t=new Xf(t,r)}else if(!(t instanceof Xf))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var n=new an(t.length()),s=0;s<n.length;++s)n[s]=t.at(s);return n}var Jf=ut(),kc=ut([1]),V3=ut([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),$3=ut([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),i0=ut([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),a0=ut([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),Pd=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),z3=ut([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function po(e,t){var r=Br.md.sha512.create(),n=new Xf(e);r.update(n.getBytes(t),"binary");var s=r.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(s,"binary");for(var i=new an(Bt.constants.HASH_BYTE_LENGTH),a=0;a<64;++a)i[a]=s.charCodeAt(a);return i}function K3(e,t){var r=[ut(),ut(),ut(),ut()],n,s=po(t,32);for(s[0]&=248,s[31]&=127,s[31]|=64,Np(r,s),kp(e,r),n=0;n<32;++n)t[n+32]=e[n];return 0}function q3(e,t,r,n){var s,i,a=new Float64Array(64),o=[ut(),ut(),ut(),ut()],l=po(n,32);l[0]&=248,l[31]&=127,l[31]|=64;var c=r+64;for(s=0;s<r;++s)e[64+s]=t[s];for(s=0;s<32;++s)e[32+s]=l[32+s];var d=po(e.subarray(32),r+32);for(Zf(d),Np(o,d),kp(e,o),s=32;s<64;++s)e[s]=n[s];var f=po(e,r+64);for(Zf(f),s=32;s<64;++s)a[s]=0;for(s=0;s<32;++s)a[s]=d[s];for(s=0;s<32;++s)for(i=0;i<32;i++)a[s+i]+=f[s]*l[i];return K1(e.subarray(32),a),c}function H3(e,t,r,n){var s,i,a=new an(32),o=[ut(),ut(),ut(),ut()],l=[ut(),ut(),ut(),ut()];if(i=-1,r<64||G3(l,n))return-1;for(s=0;s<r;++s)e[s]=t[s];for(s=0;s<32;++s)e[s+32]=n[s];var c=po(e,r);if(Zf(c),G1(o,l,c),Np(l,t.subarray(32)),eh(o,l),kp(a,o),r-=64,q1(t,0,a,0)){for(s=0;s<r;++s)e[s]=0;return-1}for(s=0;s<r;++s)e[s]=t[s+64];return i=r,i}function K1(e,t){var r,n,s,i;for(n=63;n>=32;--n){for(r=0,s=n-32,i=n-12;s<i;++s)t[s]+=r-16*t[n]*Pd[s-(n-32)],r=t[s]+128>>8,t[s]-=r*256;t[s]+=r,t[n]=0}for(r=0,s=0;s<32;++s)t[s]+=r-(t[31]>>4)*Pd[s],r=t[s]>>8,t[s]&=255;for(s=0;s<32;++s)t[s]-=r*Pd[s];for(n=0;n<32;++n)t[n+1]+=t[n]>>8,e[n]=t[n]&255}function Zf(e){for(var t=new Float64Array(64),r=0;r<64;++r)t[r]=e[r],e[r]=0;K1(e,t)}function eh(e,t){var r=ut(),n=ut(),s=ut(),i=ut(),a=ut(),o=ut(),l=ut(),c=ut(),d=ut();ua(r,e[1],e[0]),ua(d,t[1],t[0]),Zt(r,r,d),sa(n,e[0],e[1]),sa(d,t[0],t[1]),Zt(n,n,d),Zt(s,e[3],t[3]),Zt(s,s,$3),Zt(i,e[2],t[2]),sa(i,i,i),ua(a,n,r),ua(o,i,s),sa(l,i,s),sa(c,n,r),Zt(e[0],a,o),Zt(e[1],c,l),Zt(e[2],l,o),Zt(e[3],a,c)}function o0(e,t,r){for(var n=0;n<4;++n)W1(e[n],t[n],r)}function kp(e,t){var r=ut(),n=ut(),s=ut();X3(s,t[2]),Zt(r,t[0],s),Zt(n,t[1],s),Nc(e,n),e[31]^=H1(r)<<7}function Nc(e,t){var r,n,s,i=ut(),a=ut();for(r=0;r<16;++r)a[r]=t[r];for(jd(a),jd(a),jd(a),n=0;n<2;++n){for(i[0]=a[0]-65517,r=1;r<15;++r)i[r]=a[r]-65535-(i[r-1]>>16&1),i[r-1]&=65535;i[15]=a[15]-32767-(i[14]>>16&1),s=i[15]>>16&1,i[14]&=65535,W1(a,i,1-s)}for(r=0;r<16;r++)e[2*r]=a[r]&255,e[2*r+1]=a[r]>>8}function G3(e,t){var r=ut(),n=ut(),s=ut(),i=ut(),a=ut(),o=ut(),l=ut();return Ws(e[2],kc),W3(e[1],t),Ci(s,e[1]),Zt(i,s,V3),ua(s,s,e[2]),sa(i,e[2],i),Ci(a,i),Ci(o,a),Zt(l,o,a),Zt(r,l,s),Zt(r,r,i),Y3(r,r),Zt(r,r,s),Zt(r,r,i),Zt(r,r,i),Zt(e[0],r,i),Ci(n,e[0]),Zt(n,n,i),l0(n,s)&&Zt(e[0],e[0],z3),Ci(n,e[0]),Zt(n,n,i),l0(n,s)?-1:(H1(e[0])===t[3
201]>>7&&ua(e[0],Jf,e[0]),Zt(e[3],e[0],e[1]),0)}function W3(e,t){var r;for(r=0;r<16;++r)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function Y3(e,t){var r=ut(),n;for(n=0;n<16;++n)r[n]=t[n];for(n=250;n>=0;--n)Ci(r,r),n!==1&&Zt(r,r,t);for(n=0;n<16;++n)e[n]=r[n]}function l0(e,t){var r=new an(32),n=new an(32);return Nc(r,e),Nc(n,t),q1(r,0,n,0)}function q1(e,t,r,n){return Q3(e,t,r,n,32)}function Q3(e,t,r,n,s){var i,a=0;for(i=0;i<s;++i)a|=e[t+i]^r[n+i];return(1&a-1>>>8)-1}function H1(e){var t=new an(32);return Nc(t,e),t[0]&1}function G1(e,t,r){var n,s;for(Ws(e[0],Jf),Ws(e[1],kc),Ws(e[2],kc),Ws(e[3],Jf),s=255;s>=0;--s)n=r[s/8|0]>>(s&7)&1,o0(e,t,n),eh(t,e),eh(e,e),o0(e,t,n)}function Np(e,t){var r=[ut(),ut(),ut(),ut()];Ws(r[0],i0),Ws(r[1],a0),Ws(r[2],kc),Zt(r[3],i0,a0),G1(e,r,t)}function Ws(e,t){var r;for(r=0;r<16;r++)e[r]=t[r]|0}function X3(e,t){var r=ut(),n;for(n=0;n<16;++n)r[n]=t[n];for(n=253;n>=0;--n)Ci(r,r),n!==2&&n!==4&&Zt(r,r,t);for(n=0;n<16;++n)e[n]=r[n]}function jd(e){var t,r,n=1;for(t=0;t<16;++t)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-n*65536;e[0]+=n-1+37*(n-1)}function W1(e,t,r){for(var n,s=~(r-1),i=0;i<16;++i)n=s&(e[i]^t[i]),e[i]^=n,t[i]^=n}function ut(e){var t,r=new Float64Array(16);if(e)for(t=0;t<e.length;++t)r[t]=e[t];return r}function sa(e,t,r){for(var n=0;n<16;++n)e[n]=t[n]+r[n]}function ua(e,t,r){for(var n=0;n<16;++n)e[n]=t[n]-r[n]}function Ci(e,t){Zt(e,t,t)}function Zt(e,t,r){var n,s,i=0,a=0,o=0,l=0,c=0,d=0,f=0,h=0,m=0,g=0,v=0,w=0,b=0,C=0,T=0,I=0,k=0,_=0,M=0,V=0,G=0,L=0,H=0,F=0,Q=0,J=0,oe=0,xe=0,ge=0,$=0,le=0,B=r[0],Te=r[1],ye=r[2],U=r[3],Qe=r[4],pt=r[5],We=r[6],dt=r[7],ft=r[8],At=r[9],Le=r[10],Ut=r[11],tt=r[12],ct=r[13],ht=r[14],kt=r[15];n=t[0],i+=n*B,a+=n*Te,o+=n*ye,l+=n*U,c+=n*Qe,d+=n*pt,f+=n*We,h+=n*dt,m+=n*ft,g+=n*At,v+=n*Le,w+=n*Ut,b+=n*tt,C+=n*ct,T+=n*ht,I+=n*kt,n=t[1],a+=n*B,o+=n*Te,l+=n*ye,c+=n*U,d+=n*Qe,f+=n*pt,h+=n*We,m+=n*dt,g+=n*ft,v+=n*At,w+=n*Le,b+=n*Ut,C+=n*tt,T+=n*ct,I+=n*ht,k+=n*kt,n=t[2],o+=n*B,l+=n*Te,c+=n*ye,d+=n*U,f+=n*Qe,h+=n*pt,m+=n*We,g+=n*dt,v+=n*ft,w+=n*At,b+=n*Le,C+=n*Ut,T+=n*tt,I+=n*ct,k+=n*ht,_+=n*kt,n=t[3],l+=n*B,c+=n*Te,d+=n*ye,f+=n*U,h+=n*Qe,m+=n*pt,g+=n*We,v+=n*dt,w+=n*ft,b+=n*At,C+=n*Le,T+=n*Ut,I+=n*tt,k+=n*ct,_+=n*ht,M+=n*kt,n=t[4],c+=n*B,d+=n*Te,f+=n*ye,h+=n*U,m+=n*Qe,g+=n*pt,v+=n*We,w+=n*dt,b+=n*ft,C+=n*At,T+=n*Le,I+=n*Ut,k+=n*tt,_+=n*ct,M+=n*ht,V+=n*kt,n=t[5],d+=n*B,f+=n*Te,h+=n*ye,m+=n*U,g+=n*Qe,v+=n*pt,w+=n*We,b+=n*dt,C+=n*ft,T+=n*At,I+=n*Le,k+=n*Ut,_+=n*tt,M+=n*ct,V+=n*ht,G+=n*kt,n=t[6],f+=n*B,h+=n*Te,m+=n*ye,g+=n*U,v+=n*Qe,w+=n*pt,b+=n*We,C+=n*dt,T+=n*ft,I+=n*At,k+=n*Le,_+=n*Ut,M+=n*tt,V+=n*ct,G+=n*ht,L+=n*kt,n=t[7],h+=n*B,m+=n*Te,g+=n*ye,v+=n*U,w+=n*Qe,b+=n*pt,C+=n*We,T+=n*dt,I+=n*ft,k+=n*At,_+=n*Le,M+=n*Ut,V+=n*tt,G+=n*ct,L+=n*ht,H+=n*kt,n=t[8],m+=n*B,g+=n*Te,v+=n*ye,w+=n*U,b+=n*Qe,C+=n*pt,T+=n*We,I+=n*dt,k+=n*ft,_+=n*At,M+=n*Le,V+=n*Ut,G+=n*tt,L+=n*ct,H+=n*ht,F+=n*kt,n=t[9],g+=n*B,v+=n*Te,w+=n*ye,b+=n*U,C+=n*Qe,T+=n*pt,I+=n*We,k+=n*dt,_+=n*ft,M+=n*At,V+=n*Le,G+=n*Ut,L+=n*tt,H+=n*ct,F+=n*ht,Q+=n*kt,n=t[10],v+=n*B,w+=n*Te,b+=n*ye,C+=n*U,T+=n*Qe,I+=n*pt,k+=n*We,_+=n*dt,M+=n*ft,V+=n*At,G+=n*Le,L+=n*Ut,H+=n*tt,F+=n*ct,Q+=n*ht,J+=n*kt,n=t[11],w+=n*B,b+=n*Te,C+=n*ye,T+=n*U,I+=n*Qe,k+=n*pt,_+=n*We,M+=n*dt,V+=n*ft,G+=n*At,L+=n*Le,H+=n*Ut,F+=n*tt,Q+=n*ct,J+=n*ht,oe+=n*kt,n=t[12],b+=n*B,C+=n*Te,T+=n*ye,I+=n*U,k+=n*Qe,_+=n*pt,M+=n*We,V+=n*dt,G+=n*ft,L+=n*At,H+=n*Le,F+=n*Ut,Q+=n*tt,J+=n*ct,oe+=n*ht,xe+=n*kt,n=t[13],C+=n*B,T+=n*Te,I+=n*ye,k+=n*U,_+=n*Qe,M+=n*pt,V+=n*We,G+=n*dt,L+=n*ft,H+=n*At,F+=n*Le,Q+=n*Ut,J+=n*tt,oe+=n*ct,xe+=n*ht,ge+=n*kt,n=t[14],T+=n*B,I+=n*Te,k+=n*ye,_+=n*U,M+=n*Qe,V+=n*pt,G+=n*We,L+=n*dt,H+=n*ft,F+=n*At,Q+=n*Le,J+=n*Ut,oe+=n*tt,xe+=n*ct,ge+=n*ht,$+=n*kt,n=t[15],I+=n*B,k+=n*Te,_+=n*ye,M+=n*U,V+=n*Qe,G+=n*pt,L+=n*We,H+=n*dt,F+=n*ft,Q+=n*At,J+=n*Le,oe+=n*Ut,xe+=n*tt,ge+=n*ct,$+=n*ht,le+=n*kt,i+=38*k,a+=38*_,o+=38*M,l+=38*V,c+=38*G,d+=38*L,f+=38*H,h+=38*F,m+=38*Q,g+=38*J,v+=38*oe,w+=38*xe,b+=38*ge,C+=38*$,T+=38*le,s=1,n=i+s+65535,s=Math.floor(n/65536),i=n-s*65536,n=a+s+65535,s=Math.floor(n/65536),a=n-s*65536,n=o+s+65535,s=Math.floor(n/65536),o=n-s*65536,n=l+s+65535,s=Math.floor(n/65536),l=n-s*65536,n=c+s+65535,s=Math.floor(n/65536),c=n-s*65536,n=d+s+65535,s=Math.floor(n/65536),d=n-s*65536,n=f+s+65535,s=Math.floor(n/65536),f=n-s*65536,n=h+s+65535,s=Math.floor(n/65536),h=n-s*65536,n=m+s+65535,s=Math.floor(n/65536),m=n-s*65536,n=g+s+65535,s=Math.floor(n/65536),g=n-s*65536,n=v+s+65535,s=Math.floor(n/65536),v=n-s*65536,n=w+s+65535,s=Math.floor(n/65536),w=n-s*65536,n=b+s+65535,s=Math.floor(n/65536),b=n-s*65536,n=C+s+65535,s=Math.floor(n/65536),C=n-s*65536,n=T+s+65535,s=Math.floor(n/65536),T=n-s*65536,n=I+s+65535,s=Math.floor(n/65536),I=n-s*65536,i+=s-1+37*(s-1),s=1,n=i+s+65535,s=Math.floor(n/65536),i=n-s*65536,n=a+s+65535,s=Math.floor(n/65536),a=n-s*65536,n=o+s+65535,s=Math.floor(n/65536),o=n-s*65536,n=l+s+65535,s=Math.floor(n/65536),l=n-s*65536,n=c+s+65535,s=Math.floor(n/65536),c=n-s*65536,n=d+s+65535,s=Math.floor(n/65536),d=n-s*65536,n=f+s+65535,s=Math.floor(n/65536),f=n-s*65536,n=h+s+65535,s=Math.floor(n/65536),h=n-s*65536,n=m+s+65535,s=Math.floor(n/65536),m=n-s*65536,n=g+s+65535,s=Math.floor(n/65536),g=n-s*65536,n=v+s+65535,s=Math.floor(n/65536),v=n-s*65536,n=w+s+65535,s=Math.floor(n/65536),w=n-s*65536,n=b+s+65535,s=Math.floor(n/65536),b=n-s*65536,n=C+s+65535,s=Math.floor(n/65536),C=n-s*65536,n=T+s+65535,s=Math.floor(n/65536),T=n-s*65536,n=I+s+65535,s=Math.floor(n/65536),I=n-s*65536,i+=s-1+37*(s-1),e[0]=i,e[1]=a,e[2]=o,e[3]=l,e[4]=c,e[5]=d,e[6]=f,e[7]=h,e[8]=m,e[9]=g,e[10]=v,e[11]=w,e[12]=b,e[13]=C,e[14]=T,e[15]=I}var gn=Pt;gn.kem=gn.kem||{};var c0=gn.jsbn.BigInteger;gn.kem.rsa={};gn.kem.rsa.create=function(e,t){t=t||{};var r=t.prng||gn.random,n={};return n.encrypt=function(s,i){var a=Math.ceil(s.n.bitLength()/8),o;do o=new c0(gn.util.bytesToHex(r.getBytesSync(a)),16).mod(s.n);while(o.compareTo(c0.ONE)<=0);o=gn.util.hexToBytes(o.toString(16));var l=a-o.length;l>0&&(o=gn.util.fillString("\0",l)+o);
20var c=s.encrypt(o,"NONE"),d=e.generate(o,i);return{encapsulation:c,key:d}},n.decrypt=function(s,i,a){var o=s.decrypt(i,"NONE");return e.generate(o,a)},n};gn.kem.kdf1=function(e,t){Y1(this,e,0,t||e.digestLength)};gn.kem.kdf2=function(e,t){Y1(this,e,1,t||e.digestLength)};function Y1(e,t,r,n){e.generate=function(s,i){for(var a=new gn.util.ByteBuffer,o=Math.ceil(i/n)+r,l=new gn.util.ByteBuffer,c=r;c<o;++c){l.putInt32(c),t.start(),t.update(s+l.getBytes());var d=t.digest();a.putBytes(d.getBytes(n))}return a.truncate(a.length()-i),a.getBytes()}}var Ot=Pt;Ot.log=Ot.log||{};Ot.log.levels=["none","error","warning","info","debug","verbose","max"];var Rc={},th=[],mo=null;Ot.log.LEVEL_LOCKED=2;Ot.log.NO_LEVEL_CHECK=4;Ot.log.INTERPOLATE=8;for(var Ys=0;Ys<Ot.log.levels.length;++Ys){var u0=Ot.log.levels[Ys];Rc[u0]={index:Ys,name:u0.toUpperCase()}}Ot.log.logMessage=function(e){for(var t=Rc[e.level].index,r=0;r<th.length;++r){var n=th[r];if(n.flags&Ot.log.NO_LEVEL_CHECK)n.f(e);else{var s=Rc[n.level].index;t<=s&&n.f(n,e)}}};Ot.log.prepareStandard=function(e){"standard"in e||(e.standard=Rc[e.level].name+" ["+e.category+"] "+e.message)};Ot.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=Ot.util.format.apply(this,t)}};Ot.log.prepareStandardFull=function(e){"standardFull"in e||(Ot.log.prepareStandard(e),e.standardFull=e.standard)};for(var d0=["error","warning","info","debug","verbose"],Ys=0;Ys<d0.length;++Ys)(function(t){Ot.log[t]=function(r,n){var s=Array.prototype.slice.call(arguments).slice(2),i={timestamp:new Date,level:t,category:r,message:n,arguments:s};Ot.log.logMessage(i)}})(d0[Ys]);Ot.log.makeLogger=function(e){var t={flags:0,f:e};return Ot.log.setLevel(t,"none"),t};Ot.log.setLevel=function(e,t){var r=!1;if(e&&!(e.flags&Ot.log.LEVEL_LOCKED))for(var n=0;n<Ot.log.levels.length;++n){var s=Ot.log.levels[n];if(t==s){e.level=t,r=!0;break}}return r};Ot.log.lock=function(e,t){typeof t>"u"||t?e.flags|=Ot.log.LEVEL_LOCKED:e.flags&=~Ot.log.LEVEL_LOCKED};Ot.log.addLogger=function(e){th.push(e)};if(typeof console<"u"&&"log"in console){var Za;if(console.error&&console.warn&&console.info&&console.debug){var J3={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Rp=function(e,t){Ot.log.prepareStandard(t);var r=J3[t.level],n=[t.standard];n=n.concat(t.arguments.slice()),r.apply(console,n)};Za=Ot.log.makeLogger(Rp)}else{var Rp=function(t,r){Ot.log.prepareStandardFull(r),console.log(r.standardFull)};Za=Ot.log.makeLogger(Rp)}Ot.log.setLevel(Za,"debug"),Ot.log.addLogger(Za),mo=Za}else console={log:function(){}};if(mo!==null&&typeof window<"u"&&window.location){var Dl=new URL(window.location.href).searchParams;if(Dl.has("console.level")&&Ot.log.setLevel(mo,Dl.get("console.level").slice(-1)[0]),Dl.has("console.lock")){var Z3=Dl.get("console.lock").slice(-1)[0];Z3=="true"&&Ot.log.lock(mo)}}Ot.log.consoleLogger=mo;var Ke=Pt,Y=Ke.asn1,Yr=Ke.pkcs7=Ke.pkcs7||{};Yr.messageFromPem=function(e){var t=Ke.pem.decode(e)[0];if(t.type!=="PKCS7"){var r=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw r.headerType=t.type,r}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var n=Y.fromDer(t.body);return Yr.messageFromAsn1(n)};Yr.messageToPem=function(e,t){var r={type:"PKCS7",body:Y.toDer(e.toAsn1()).getBytes()};return Ke.pem.encode(r,{maxline:t})};Yr.messageFromAsn1=function(e){var t={},r=[];if(!Y.validate(e,Yr.asn1.contentInfoValidator,t,r)){var n=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw n.errors=r,n}var s=Y.derToOid(t.contentType),i;switch(s){case Ke.pki.oids.envelopedData:i=Yr.createEnvelopedData();break;case Ke.pki.oids.encryptedData:i=Yr.createEncryptedData();break;case Ke.pki.oids.signedData:i=Yr.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+s+" is not (yet) supported.")}return i.fromAsn1(t.content.value[0]),i};Yr.createSignedData=function(){var e=null;
20return e={type:Ke.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(n){if(Pp(e,n,Yr.asn1.signedDataValidator),e.certificates=[],e.crls=[],e.digestAlgorithmIdentifiers=[],e.contentInfo=null,e.signerInfos=[],e.rawCapture.certificates)for(var s=e.rawCapture.certificates.value,i=0;i<s.length;++i)e.certificates.push(Ke.pki.certificateFromAsn1(s[i]))},toAsn1:function(){e.contentInfo||e.sign();for(var n=[],s=0;s<e.certificates.length;++s)n.push(Ke.pki.certificateToAsn1(e.certificates[s]));var i=[],a=Y.create(Y.Class.CONTEXT_SPECIFIC,0,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.INTEGER,!1,Y.integerToDer(e.version).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);return n.length>0&&a.value[0].value.push(Y.create(Y.Class.CONTEXT_SPECIFIC,0,!0,n)),i.length>0&&a.value[0].value.push(Y.create(Y.Class.CONTEXT_SPECIFIC,1,!0,i)),a.value[0].value.push(Y.create(Y.Class.UNIVERSAL,Y.Type.SET,!0,e.signerInfos)),Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.type).getBytes()),a])},addSigner:function(n){var s=n.issuer,i=n.serialNumber;if(n.certificate){var a=n.certificate;typeof a=="string"&&(a=Ke.pki.certificateFromPem(a)),s=a.issuer.attributes,i=a.serialNumber}var o=n.key;if(!o)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof o=="string"&&(o=Ke.pki.privateKeyFromPem(o));var l=n.digestAlgorithm||Ke.pki.oids.sha1;switch(l){case Ke.pki.oids.sha1:case Ke.pki.oids.sha256:case Ke.pki.oids.sha384:case Ke.pki.oids.sha512:case Ke.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+l)}var c=n.authenticatedAttributes||[];if(c.length>0){for(var d=!1,f=!1,h=0;h<c.length;++h){var m=c[h];if(!d&&m.type===Ke.pki.oids.contentType){if(d=!0,f)break;continue}if(!f&&m.type===Ke.pki.oids.messageDigest){if(f=!0,d)break;continue}}if(!d||!f)throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}e.signers.push({key:o,version:1,issuer:s,serialNumber:i,digestAlgorithm:l,signatureAlgorithm:Ke.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:c,unauthenticatedAttributes:[]})},sign:function(n){if(n=n||{},(typeof e.content!="object"||e.contentInfo===null)&&(e.contentInfo=Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(Ke.pki.oids.data).getBytes())]),"content"in e)){var s;e.content instanceof Ke.util.ByteBuffer?s=e.content.bytes():typeof e.content=="string"&&(s=Ke.util.encodeUtf8(e.content)),n.detached?e.detachedContent=Y.create(Y.Class.UNIVERSAL,Y.Type.OCTETSTRING,!1,s):e.contentInfo.value.push(Y.create(Y.Class.CONTEXT_SPECIFIC,0,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OCTETSTRING,!1,s)]))}if(e.signers.length!==0){var i=t();r(i)}},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(n){typeof n=="string"&&(n=Ke.pki.certificateFromPem(n)),e.certificates.push(n)},addCertificateRevokationList:function(n){throw new Error("PKCS#7 CRL support not yet implemented.")}},e;function t(){for(var n={},s=0;s<e.signers.length;++s){var i=e.signers[s],a=i.digestAlgorithm;a in n||(n[a]=Ke.md[Ke.pki.oids[a]].create()),i.authenticatedAttributes.length===0?i.md=n[a]:i.md=Ke.md[Ke.pki.oids[a]].create()}e.digestAlgorithmIdentifiers=[];for(var a in n)e.digestAlgorithmIdentifiers.push(Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(a).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.NULL,!1,"")]));return n}function r(n){var s;if(e.detachedContent?s=e.detachedContent:(s=e.contentInfo.value[1],s=s.value[0]),!s)throw new Error("Could not sign PKCS#7 message; there is no content to sign.");var i=Y.derToOid(e.contentInfo.value[0].value),a=Y.toDer(s);a.getByte(),Y.getBerValueLength(a),a=a.getBytes();for(var o in n)n[o].start().update(a);for(var l=new Date,c=0;c<e.signers.length;++c){var d=e.signers[c];if(d.authenticatedAttributes.length===0){if(i!==Ke.pki.oids.data)throw new Error("Invalid signer;
20 authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{d.authenticatedAttributesAsn1=Y.create(Y.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var f=Y.create(Y.Class.UNIVERSAL,Y.Type.SET,!0,[]),h=0;h<d.authenticatedAttributes.length;++h){var m=d.authenticatedAttributes[h];m.type===Ke.pki.oids.messageDigest?m.value=n[d.digestAlgorithm].digest():m.type===Ke.pki.oids.signingTime&&(m.value||(m.value=l)),f.value.push(rh(m)),d.authenticatedAttributesAsn1.value.push(rh(m))}a=Y.toDer(f).getBytes(),d.md.start().update(a)}d.signature=d.key.sign(d.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=i5(e.signers)}};Yr.createEncryptedData=function(){var e=null;return e={type:Ke.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:Ke.pki.oids["aes256-CBC"]},fromAsn1:function(t){Pp(e,t,Yr.asn1.encryptedDataValidator)},decrypt:function(t){t!==void 0&&(e.encryptedContent.key=t),Q1(e)}},e};Yr.createEnvelopedData=function(){var e=null;return e={type:Ke.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:Ke.pki.oids["aes256-CBC"]},fromAsn1:function(t){var r=Pp(e,t,Yr.asn1.envelopedDataValidator);e.recipients=r5(r.recipientInfos.value)},toAsn1:function(){return Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.type).getBytes()),Y.create(Y.Class.CONTEXT_SPECIFIC,0,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.INTEGER,!1,Y.integerToDer(e.version).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.SET,!0,n5(e.recipients)),Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,a5(e.encryptedContent))])])])},findRecipient:function(t){for(var r=t.issuer.attributes,n=0;n<e.recipients.length;++n){var s=e.recipients[n],i=s.issuer;if(s.serialNumber===t.serialNumber&&i.length===r.length){for(var a=!0,o=0;o<r.length;++o)if(i[o].type!==r[o].type||i[o].value!==r[o].value){a=!1;break}if(a)return s}}return null},decrypt:function(t,r){if(e.encryptedContent.key===void 0&&t!==void 0&&r!==void 0)switch(t.encryptedContent.algorithm){case Ke.pki.oids.rsaEncryption:case Ke.pki.oids.desCBC:var n=r.decrypt(t.encryptedContent.content);e.encryptedContent.key=Ke.util.createBuffer(n);break;default:throw new Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}Q1(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:Ke.pki.oids.rsaEncryption,key:t.publicKey}})},encrypt:function(t,r){if(e.encryptedContent.content===void 0){r=r||e.encryptedContent.algorithm,t=t||e.encryptedContent.key;var n,s,i;switch(r){case Ke.pki.oids["aes128-CBC"]:n=16,s=16,i=Ke.aes.createEncryptionCipher;break;case Ke.pki.oids["aes192-CBC"]:n=24,s=16,i=Ke.aes.createEncryptionCipher;break;case Ke.pki.oids["aes256-CBC"]:n=32,s=16,i=Ke.aes.createEncryptionCipher;break;case Ke.pki.oids["des-EDE3-CBC"]:n=24,s=8,i=Ke.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+r)}if(t===void 0)t=Ke.util.createBuffer(Ke.random.getBytes(n));else if(t.length()!=n)throw new Error("Symmetric key has wrong length; got "+t.length()+" bytes, expected "+n+".");e.encryptedContent.algorithm=r,e.encryptedContent.key=t,e.encryptedContent.parameter=Ke.util.createBuffer(Ke.random.getBytes(s));var a=i(t);if(a.start(e.encryptedContent.parameter.copy()),a.update(e.content),!a.finish())throw new Error("Symmetric encryption failed.");e.encryptedContent.content=a.output}for(var o=0;o<e.recipients.length;++o){var l=e.recipients[o];if(l.encryptedContent.content===void 0)switch(l.encryptedContent.algorithm){case Ke.pki.oids.rsaEncryption:l.encryptedContent.content=l.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw new Error("Unsupported asymmetric cipher, OID "+l.encryptedContent.algorithm)}}}},e};function e5(e){var t={},r=[];if(!Y.validate(e,Yr.asn1.recipientInfoValidator,t,r)){var n=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw n.errors=r,n}return{version:t.version.charCodeAt(0),issuer:Ke.pki.RDNAttributesAsArray(t.issuer),serialNumber:Ke.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:Y.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function t5(e){return Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.INTEGER,!1,Y.integerToDer(e.version).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Ke.pki.distinguishedNameToAsn1({attributes:e.issuer}),Y.create(Y.Class.UNIVERSAL,Y.Type.INTEGER,!1,Ke.util.hexToBytes(e.serialNumber))]),Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.encryptedContent.algorithm).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.NULL,!1,"")]),Y.create(Y.Class.UNIVERSAL,Y.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function r5(e){for(var t=[],r=0;r<e.length;++r)t.push(e5(e[r]));return t}function n5(e){for(var t=[],r=0;r<e.length;++r)t.push(t5(e[r]));return t}function s5(e){var t=Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.INTEGER,!1,Y.integerToDer(e.version).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Ke.pki.distinguishedNameToAsn1({attributes:e.issuer}),Y.create(Y.Class.UNIVERSAL,Y.Type.INTEGER,!1,Ke.util.hexToBytes(e.serialNumber))]),Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.digestAlgorithm).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1&&t.value.push(e.authenticatedAttributesAsn1),t.value.push(Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.signatureAlgorithm).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.NULL,!1,"")])),t.value.push(Y.create(Y.Class.UNIVERSAL,Y.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){for(var r=Y.create(Y.Class.CONTEXT_SPECIFIC,1,!0,[]),n=0;n<e.unauthenticatedAttributes.length;++n){var s=e.unauthenticatedAttributes[n];r.values.push(rh(s))}t.value.push(r)}return t}function i5(e){for(var t=[],r=0;r<e.length;++r)t.push(s5(e[r]));return t}function rh(e){var t;if(e.type===Ke.pki.oids.contentType)t=Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.value).getBytes());else if(e.type===Ke.pki.oids.messageDigest)t=Y.create(Y.Class.UNIVERSAL,Y.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===Ke.pki.oids.signingTime){var r=new Date("1950-01-01T00:00:00Z"),n=new Date("2050-01-01T00:00:00Z"),s=e.value;if(typeof s=="string"){var i=Date.parse(s);isNaN(i)?s.length===13?s=Y.utcTimeToDate(s):s=Y.generalizedTimeToDate(s):s=new Date(i)}s>=r&&s<n?t=Y.create(Y.Class.UNIVERSAL,Y.Type.UTCTIME,!1,Y.dateToUtcTime(s)):t=Y.create(Y.Class.UNIVERSAL,Y.Type.GENERALIZEDTIME,!1,Y.dateToGeneralizedTime(s))}return Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.type).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.SET,!0,[t])])}function a5(e){return[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(Ke.pki.oids.data).getBytes()),Y.create(Y.Class.UNIVERSAL,Y.Type.SEQUENCE,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OID,!1,Y.oidToDer(e.algorithm).getBytes()),e.parameter?Y.create(Y.Class.UNIVERSAL,Y.Type.OCTETSTRING,!1,e.parameter.getBytes()):void 0]),Y.create(Y.Class.CONTEXT_SPECIFIC,0,!0,[Y.create(Y.Class.UNIVERSAL,Y.Type.OCTETSTRING,!1,e.content.getBytes())])]}function Pp(e,t,r){var n={},s=[];if(!Y.validate(t,r,n,s)){var i=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw i.errors=i,i}var a=Y.derToOid(n.contentType);if(a!==Ke.pki.oids.data)throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");
20if(n.encryptedContent){var o="";if(Ke.util.isArray(n.encryptedContent))for(var l=0;l<n.encryptedContent.length;++l){if(n.encryptedContent[l].type!==Y.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");o+=n.encryptedContent[l].value}else o=n.encryptedContent;e.encryptedContent={algorithm:Y.derToOid(n.encAlgorithm),parameter:Ke.util.createBuffer(n.encParameter.value),content:Ke.util.createBuffer(o)}}if(n.content){var o="";if(Ke.util.isArray(n.content))for(var l=0;l<n.content.length;++l){if(n.content[l].type!==Y.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");o+=n.content[l].value}else o=n.content;e.content=Ke.util.createBuffer(o)}return e.version=n.version.charCodeAt(0),e.rawCapture=n,n}function Q1(e){if(e.encryptedContent.key===void 0)throw new Error("Symmetric key not available.");if(e.content===void 0){var t;switch(e.encryptedContent.algorithm){case Ke.pki.oids["aes128-CBC"]:case Ke.pki.oids["aes192-CBC"]:case Ke.pki.oids["aes256-CBC"]:t=Ke.aes.createDecryptionCipher(e.encryptedContent.key);break;case Ke.pki.oids.desCBC:case Ke.pki.oids["des-EDE3-CBC"]:t=Ke.des.createDecryptionCipher(e.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+e.encryptedContent.algorithm)}if(t.start(e.encryptedContent.parameter),t.update(e.encryptedContent.content),!t.finish())throw new Error("Symmetric decryption failed.");e.content=t.output}}var Cr=Pt,wu=Cr.ssh=Cr.ssh||{};wu.privateKeyToPutty=function(e,t,r){r=r||"",t=t||"";var n="ssh-rsa",s=t===""?"none":"aes256-cbc",i="PuTTY-User-Key-File-2: "+n+`\r
21`;i+="Encryption: "+s+`\r
22`,i+="Comment: "+r+`\r
23`;var a=Cr.util.createBuffer();da(a,n),Zn(a,e.e),Zn(a,e.n);var o=Cr.util.encode64(a.bytes(),64),l=Math.floor(o.length/66)+1;i+="Public-Lines: "+l+`\r
24`,i+=o;var c=Cr.util.createBuffer();Zn(c,e.d),Zn(c,e.p),Zn(c,e.q),Zn(c,e.qInv);var d;if(!t)d=Cr.util.encode64(c.bytes(),64);else{var f=c.length()+16-1;f-=f%16;var h=Ll(c.bytes());h.truncate(h.length()-f+c.length()),c.putBuffer(h);var m=Cr.util.createBuffer();m.putBuffer(Ll("\0\0\0\0",t)),m.putBuffer(Ll("\0\0\0�",t));var g=Cr.aes.createEncryptionCipher(m.truncate(8),"CBC");g.start(Cr.util.createBuffer().fillWithByte(0,16)),g.update(c.copy()),g.finish();var v=g.output;v.truncate(16),d=Cr.util.encode64(v.bytes(),64)}l=Math.floor(d.length/66)+1,i+=`\r
25Private-Lines: `+l+`\r
26`,i+=d;var w=Ll("putty-private-key-file-mac-key",t),b=Cr.util.createBuffer();da(b,n),da(b,s),da(b,r),b.putInt32(a.length()),b.putBuffer(a),b.putInt32(c.length()),b.putBuffer(c);var C=Cr.hmac.create();return C.start("sha1",w),C.update(b.bytes()),i+=`\r
27Private-MAC: `+C.digest().toHex()+`\r
28`,i};wu.publicKeyToOpenSSH=function(e,t){var r="ssh-rsa";t=t||"";var n=Cr.util.createBuffer();return da(n,r),Zn(n,e.e),Zn(n,e.n),r+" "+Cr.util.encode64(n.bytes())+" "+t};wu.privateKeyToOpenSSH=function(e,t){return t?Cr.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"}):Cr.pki.privateKeyToPem(e)};wu.getPublicKeyFingerprint=function(e,t){t=t||{};var r=t.md||Cr.md.md5.create(),n="ssh-rsa",s=Cr.util.createBuffer();da(s,n),Zn(s,e.e),Zn(s,e.n),r.start(),r.update(s.getBytes());var i=r.digest();if(t.encoding==="hex"){var a=i.toHex();return t.delimiter?a.match(/.{2}/g).join(t.delimiter):a}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};function Zn(e,t){var r=t.toString(16);r[0]>="8"&&(r="00"+r);var n=Cr.util.hexToBytes(r);e.putInt32(n.length),e.putBytes(n)}function da(e,t){e.putInt32(t.length),e.putString(t)}function Ll(){for(var e=Cr.md.sha1.create(),t=arguments.length,r=0;r<t;++r)e.update(arguments[r]);return e.digest()}const o5={bitcoin:"BTCUSDT",btc:"BTCUSDT",ethereum:"ETHUSDT",eth:"ETHUSDT",binancecoin:"BNBUSDT",bnb:"BNBUSDT",ripple:"XRPUSDT",xrp:"XRPUSDT",cardano:"ADAUSDT",ada:"ADAUSDT",solana:"SOLUSDT",sol:"SOLUSDT",dogecoin:"DOGEUSDT",doge:"DOGEUSDT",polkadot:"DOTUSDT",dot:"DOTUSDT"};new Set(Object.values(o5));const l5=e=>!!(!e.response&&e.request||e.response?.status>=500||e.code==="ECONNABORTED"||e.code==="ETIMEDOUT");
28class c5 extends Error{constructor(t="Unable to connect to the server"){super(t),this.name="ServiceDownError"}}const u5=()=>{window.dispatchEvent(new CustomEvent("service-down"))},d5=()=>{window.dispatchEvent(new CustomEvent("service-up"))},f5=async()=>{const{data:e,error:t}=await En.rpc("get_api_url");if(t)throw t;if(!e)throw new Error("API URL is null or undefined");const r=new URL(e);return`${r.origin}${r.pathname}`};let Ml=null;const Qo=async()=>{try{if(Ml||(Ml=await f5()),!Ml)throw new Error("Failed to get API URL");const e=localStorage.getItem("web3_jwt"),t=qh.create({baseURL:Ml,headers:{"ngrok-skip-browser-warning":"1",...e?{Authorization:`Bearer ${e}`}:{}}});return t.interceptors.request.use(r=>(r.headers={...r.headers,"ngrok-skip-browser-warning":"1"},r.headers.Authorization,r)),t.interceptors.response.use(r=>(d5(),r),r=>!r.config?.bypassServiceDownCheck&&l5(r)?(u5(),Promise.reject(new c5)):(r.response?.status,r.response?.status,Promise.reject(r))),t}catch(e){throw e}},f0=async e=>{try{return(await(await Qo()).post("/users",{walletAddress:e})).data}catch(t){throw t}},h5=async e=>{try{return(await(await Qo()).post("/ratings",{entity_type:e.entityType,entity_id:e.entityId,entity_version:e.entityVersion??null,overall:e.overall,criteria:e.criteria??null,comment:e.comment??null,usage_proof_id:e.usageProofId})).data}catch(t){throw t}},X1=async()=>{try{return(await(await Qo()).get("/registry")).data}catch(e){throw e}},J1=async({apiId:e,resourceId:t,jobId:r})=>{try{return(await(await Qo()).get(`/proxy/${e}/${t}/job/${r}`,{bypassServiceDownCheck:!0})).data}catch(n){throw n}},p5=async e=>{try{return(await(await Qo()).get(`/registry/${e}`)).data}catch(t){throw t}},m5=({isOpen:e,message:t="Loading",logo:r="/uploads/slinky-logo.png"})=>u.jsx(zo,{open:e,children:u.jsxs(_a,{hideCloseButton:!0,className:"sm:max-w-md bg-white border-gray-200 flex flex-col items-center py-8",children:[u.jsx("div",{className:"mb-6 animate-pulse",children:u.jsx("img",{src:r,alt:"Loading",className:"h-16 w-auto"})}),u.jsx("div",{className:"mb-6",children:u.jsx(ls,{className:"h-12 w-12 animate-spin text-[#98fe00]"})}),u.jsxs("div",{className:"text-center space-y-2",children:[u.jsx("p",{className:"text-lg font-medium text-[#0b0f14]",children:t}),u.jsxs("div",{className:"flex items-center justify-center gap-1",children:[u.jsx("span",{className:"h-2 w-2 bg-[#98fe00] rounded-full animate-bounce [animation-delay:-0.3s]"}),u.jsx("span",{className:"h-2 w-2 bg-[#98fe00] rounded-full animate-bounce [animation-delay:-0.15s]"}),u.jsx("span",{className:"h-2 w-2 bg-[#98fe00] rounded-full animate-bounce"})]})]})]})}),g5=()=>{const e=Sa(),[t,r]=N.useState(""),[n,s]=N.useState("All"),[i,a]=N.useState("All"),[o,l]=N.useState(!1),[c,d]=N.useState([]),[f,h]=N.useState(!0),[m,g]=N.useState(null),[v,w]=N.useState(0),b=window.localStorage.getItem("wallet_address");N.useEffect(()=>{(async()=>{try{h(!0);const H=await X1();d(H.apis||H||[]),b&&w(0),g(null)}catch{g("Failed to load tools. Please try again later."),d([])}finally{h(!1)}})()},[]);const C=[...c].sort((L,H)=>H.requestsToday-L.requestsToday).slice(0,5),T=c.slice(3,8);[...c].sort((L,H)=>parseFloat(H.uptime)-parseFloat(L.uptime)).slice(0,5);const I=["All",...Array.from(new Set(c.flatMap(L=>L.categories))).sort()],k=c.filter(L=>{const H=L.name.toLowerCase().includes(t.toLowerCase())||L.description.toLowerCase().includes(t.toLowerCase()),F=n==="All"||L.categories.includes(n),Q=i==="All"||L.method===i;return H&&F&&Q}),_=L=>({active:"bg-green-100 text-green-700",beta:"bg-blue-100 text-blue-700",deprecated:"bg-red-100 text-red-700"})[L]||"bg-gray-100 text-gray-700",M=["bg-blue-50 text-blue-700 border border-blue-100","bg-amber-50 text-amber-700 border border-amber-100","bg-emerald-50 text-emerald-700 border border-emerald-100","bg-violet-50 text-violet-700 border border-violet-100","bg-rose-50 text-rose-700 border border-rose-100","bg-purple-50 text-purple-700 border border-purple-100","bg-cyan-50 text-cyan-700 border border-cyan-100","bg-pink-50 text-pink-700 border border-pink-100","bg-orange-50 text-orange-700 border border-orange-100","bg-sky-50 text-sky-700 border border-sky-100","bg-teal-50 text-teal-700 border border-teal-100","bg-lime-50 text-lime-700 border border-lime-100","bg-fuchsia-50 text-fuchsia-700 border border-fuchsia-100","bg-indigo-50 text-indigo-700 border border-indigo-100","bg-red-50 text-red-700 border border-red-100"],V=L=>{let H=0;for(let F=0;F<L.length;F++)H=H*31+L.charCodeAt(F)>>>0;return H},G=L=>({All:"bg-gray-50 text-gray-700 border border-gray-200",Trading:"bg-blue-50 text-blue-700 border border-blue-100",Analytics:"bg-amber-50 text-amber-700 border border-amber-100",Blockchain:"bg-emerald-50 text-emerald-700 border border-emerald-100",Portfolio:"bg-violet-50 text-violet-700 border border-violet-100","AI/ML":"bg-rose-50 text-rose-700 border border-rose-100",AI:"bg-purple-50 text-purple-700 border border-purple-100","Data Extraction":"bg-cyan-50 text-cyan-700 border border-cyan-100",Marketing:"bg-pink-50 text-pink-700 border border-pink-100","Content Moderation":"bg-orange-50 text-orange-700 border border-orange-100",Security:"bg-red-50 text-red-700 border border-red-100",SEO:"bg-green-50 text-green-700 border border-green-100",Travel:"bg-sky-50 text-sky-700 border border-sky-100","Content Detection":"bg-indigo-50 text-indigo-700 border border-indigo-100",Image:"bg-fuchsia-50 text-fuchsia-700 border border-fuchsia-100","Image Generation":"bg-fuchsia-50 text-fuchsia-700 border border-fuchsia-100","Data Privacy":"bg-slate-50 text-slate-700 border border-slate-100","Text Analysis":"bg-teal-50 text-teal-700 border border-teal-100","Sentiment Analysis":"bg-lime-50 text-lime-700 border border-lime-100",Chat:"bg-gray-50 text-gray-700 border border-gray-200",Multimodal:"bg-indigo-50 text-indigo-700 border border-indigo-100"})[L]||M[V(L)%M.length];return u.jsx("div",{className:"min-h-screen bg-white",children:u.jsxs("div",{className:"container mx-auto px-6 py-8",children:[u.jsx(xN,{}),u.jsx(m5,{isOpen:f,message:"Loading Tools..."}),m&&!f&&u.jsx("div",{className:"max-w-[1440px] mx-auto mb-6",children:u.jsx("div",{className:"bg-red-50 border border-red-200 rounded-xl p-4",children:u.jsx("p",{className:"text-red-800",children:m})})}),!f&&!m&&u.jsxs("div",{className:"max-w-[1440px] mx-auto",children:[u.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-4 gap-6",children:[u.jsxs("div",{className:"xl:col-span-3 space-y-6",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-8",children:[u.jsxs(es,{className:"bg-white border border-[#e5e7eb] rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)] min-h-[300px]",children:[u.jsxs(oa,{
28className:"pb-3 flex flex-row items-center justify-between p-4",children:[u.jsx(la,{className:"text-lg font-semibold text-[#0b0f14]",children:"Popular Tools"}),u.jsx(t_,{className:"h-5 w-5 text-[#667085]"})]}),u.jsx(Ks,{className:"px-4 pb-4",children:C.map((L,H)=>u.jsx(Og,{api:L,rank:H+1},L.id))})]}),u.jsxs(es,{className:"bg-white border border-[#e5e7eb] rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)] min-h-[300px]",children:[u.jsxs(oa,{className:"pb-3 flex flex-row items-center justify-between p-4",children:[u.jsx(la,{className:"text-lg font-semibold text-[#0b0f14]",children:"Recent Added"}),u.jsx(ya,{className:"h-5 w-5 text-[#667085]"})]}),u.jsx(Ks,{className:"px-4 pb-4",children:T.map((L,H)=>u.jsx(Og,{api:L,rank:H+1},L.id))})]})]}),u.jsxs("div",{className:"mb-6",children:[u.jsxs("div",{className:"relative mb-4",children:[u.jsx(r_,{className:"absolute left-4 top-1/2 transform -translate-y-1/2 text-[#667085] w-5 h-5"}),u.jsx(rn,{placeholder:"Search Tools...",value:t,onChange:L=>r(L.target.value),className:"pl-12 pr-4 bg-white border-[#e5e7eb] h-12 text-base rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)] focus:border-[#0b0f14] focus:ring-1 focus:ring-[#0b0f14] transition-all duration-200"})]}),u.jsx("div",{className:"flex flex-wrap gap-4",children:u.jsx("div",{className:"flex-1 min-w-0",children:u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsx("span",{className:"text-sm font-semibold text-[#374151] whitespace-nowrap mt-1.5",children:"Category:"}),u.jsx("div",{className:ze("flex flex-wrap gap-1 items-center flex-1 transition-[max-height] duration-200 ease-in-out overflow-hidden",o?"max-h-[500px]":"max-h-9"),children:I.map(L=>u.jsx(yt,{variant:"ghost",size:"sm",onClick:()=>s(L),className:ze("h-8 px-3 rounded-full text-xs font-medium transition-all duration-200",n===L?"bg-[#0b0f14] text-white hover:bg-[#0b
280f14]/90":G(L)),children:L},L))}),I.length>8&&u.jsx(yt,{variant:"ghost",size:"sm",onClick:()=>l(L=>!L),className:"h-8 px-3 rounded-full text-xs font-medium text-[#64748b] hover:bg-[#f1f5f9] shrink-0",children:o?u.jsxs(u.Fragment,{children:["Show less ",u.jsx(zh,{className:"ml-1 h-3 w-3"})]}):u.jsxs(u.Fragment,{children:["Show all ",u.jsx(ri,{className:"ml-1 h-3 w-3"})]})})]})})})]})]}),u.jsxs("div",{className:"xl:col-span-1 space-y-6",children:[u.jsxs(es,{className:"bg-white border border-[#e5e7eb] rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)]",children:[u.jsx(oa,{className:"p-4 pb-3",children:u.jsx(la,{className:"text-lg font-semibold text-[#0b0f14]",children:"Quick Actions"})}),u.jsxs(Ks,{className:"px-4 pb-4 space-y-2",children:[u.jsx(yt,{className:"w-full bg-[#0b0f14] text-white hover:bg-[#98fe00] hover:text-black h-10 font-medium rounded-xl",children:"Add New API"}),u.jsx(yt,{variant:"outline",onClick:()=>e("/account"),className:"w-full h-10 font-medium text-black rounded-xl border-[#e5e7eb] hover:bg-[#98fe00] hover:text-black",children:"My Usage"})]})]}),u.jsxs(es,{className:"bg-white border border-[#e5e7eb] rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)]",children:[u.jsx(oa,{className:"p-4 pb-3",children:u.jsx(la,{className:"text-lg font-semibold text-[#0b0f14]",children:"SLINKY Balance"})}),u.jsx(Ks,{className:"px-4 pb-4",children:u.jsxs("div",{className:"text-center space-y-3",children:[u.jsxs("div",{children:[u.jsx("div",{className:"text-4xl font-bold text-[#0b0f14]",children:v.toLocaleString()}),u.jsx("div",{className:"text-xs text-[#9ca3af] mt-1",children:"SLINKY"})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(yt,{className:"flex-1 bg-[#0b0f14] text-white hover:bg-[#98fe00] hover:text-black h-9 font-medium rounded-lg",children:"Stake"}),u.jsx(yt,{variant:"outline",className:"flex-1 h-9 font-medium text-black rounded-lg border-[#e5e7eb] hover:bg-[#98fe00] hover:text-black",children:"Unstake"})]})]})})]})]})]}),u.jsx("div",{className:"mt-6",children:u.jsx(es,{className:"bg-white border border-[#e5e7eb] rounded-xl shadow-[0_1px_2px_rgba(16,24,40,0.04)]",children:u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full",children:[u.jsx("thead",{className:"border-b border-[#e5e7eb]",children:u.jsxs("tr",{children:[u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"#"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"API Name"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"Category"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"Total Requests"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"Fees Generated"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"Unique Users"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"Rating"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"Status"}),u.jsx("th",{className:"text-left p-4 text-xs font-medium text-[#667085] uppercase",children:"Action"})]})}),u.jsx("tbody",{children:k.map((L,H)=>u.jsxs("tr",{className:"border-b border-[#e5e7eb] hover:bg-[#f9fafb] transition-colors",children:[u.jsx("td",{className:"p-4 text-sm text-[#667085]",children:H+1}),u.jsx("td",{className:"p-4",children:u.jsxs("div",{children:[u.jsx("div",{className:"font-semibold text-[#0b0f14] text-sm",children:L.name}),u.jsx("div",{className:"text-xs text-[#667085] truncate max-w-xs",children:L.description})]})}),u.jsx("td",{className:"p-4",children:u.jsx("div",{className:"flex flex-wrap gap-1.5",children:L.categories.slice(0,3).map(F=>u.jsx("span",{className:ze("text-xs px-2.5 py-1 rounded-full inline-flex items-center",G(F)),children:F},F))})}),u.jsx("td",{className:"p-4",children:u.jsxs("div",{className:"flex items-center gap-2 text-sm text-[#344054]",children:[u.jsx(Tx,{className:"h-4 w-4 text-blue-600"}),u.jsx("span",{className:"font-medium",children:"-"})]})}),u.jsx("td",{className:"p-4",children:u.jsxs("div",{className:"flex items-center gap-2 text-sm text-[#344054]",children:[u.jsx(n_,{className:"h-4 w-4 text-emerald-600"}),u.jsx("span",{className:"font-medium",children:"-"})]})}),u.jsx("td",{className:"p-4",children:u.jsxs("div",{className:"flex items-center gap-2 text-sm text-[#344054]",children:[u.jsx(s_,{className:"h-4 w-4 text-violet-600"}),u.jsx("span",{className:"font-medium",children:"-"})]})}),u.jsx("td",{className:"p-4 text-sm font-medium text-[#0b0f14]",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(ya,{className:"h-4 w-4 fill-yellow-300 text-yellow-400"}),u.jsx("span",{className:"font-medium text-sm text-gray-900",children:L.rating})]})}),u.jsx("td",{className:"p-4",children:u.jsx("span",{className:`text-xs px-2 py-1 rounded ${_(L.status)}`,children:L.status})}),u.jsx("td",{className:"p-4",children:u.jsx(yt,{size:"sm",onClick:()=>e(`/tools/${L.id}`),className:"bg-black text-white hover:bg-[#98fe00] hover:text-black transition-all duration-300",children:"Use Tool"})})]},L.id))})]})})})})]})]})})},y5=({isOpen:e,onClose:t,modelName:r,usageProofId:n,onConfirm:s})=>{const[i,a]=N.useState(0),[o,l]=N.useState(""),[c,d]=N.useState(!1),[f,h]=N.useState(0),[m,g]=N.useState(0),[v,w]=N.useState(!1),b=!!n&&i>0&&!v,C=N.useMemo(()=>
28{if(!c)return null;const I={};return f&&(I.accuracy=f),m&&(I.latency=m),Object.keys(I).length?I:null},[c,f,m]),T=async()=>{if(b){w(!0);try{s?.({overall:i,criteria:C,comment:o.trim()?o.trim():null}),t()}finally{w(!1)}}};return u.jsx("div",{className:"px-3",children:u.jsx(zo,{open:e,onOpenChange:t,children:u.jsxs(_a,{className:"sm:max-w-md bg-white border-gray-200",children:[u.jsx(Ko,{className:"pb-4",children:u.jsx(qo,{className:"text-xl font-semibold text-gray-900",children:"Rate this model"})}),u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:r}),u.jsx("p",{className:"text-sm text-gray-600",children:"Your rating helps others discover reliable models. Only verified users can rate."})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-sm font-medium text-gray-900",children:"Overall rating"}),u.jsx(Bd,{value:i,onChange:a,size:"lg"}),u.jsx("div",{className:"text-xs text-gray-500",children:i===0?"Select a rating to continue.":n?"Verified via recent usage":u.jsx("span",{className:"text-red-600",children:"Use the model to unlock rating."})})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("label",{className:"text-sm font-medium text-gray-900",children:"Comment (optional)"}),u.jsx("textarea",{value:o,onChange:I=>l(I.target.value),placeholder:"What worked well? What could be better?",rows:4,className:"w-full rounded-xl border border-gray-300 p-3 text-sm focus:outline-none focus:ring-2 focus:ring-black/70"})]}),u.jsx("div",{className:"space-y-3",children:u.jsxs("div",{className:"rounded-xl overflow-hidden",children:[u.jsxs("button",{type:"button",onClick:()=>d(I=>!I),className:"flex w-full items-center justify-between bg-gray-50 px-3 py-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm font-medium text-gray-900",children:"Advanced"}),u.jsx("span",{className:"ml-2 text-xs text-gray-500",children:"(optional)"})]}),c?u.jsx(ri,{className:"h-4 w-4 text-gray-500"}):u.jsx(ru,{className:"h-4 w-4 text-gray-500"})]}),c&&u.jsxs("div",{className:"p-3",children:[u.jsxs("div",{className:"flex items-center justify-between py-2",children:[u.jsx("span",{className:"text-sm text-gray-700",children:"Accuracy"}),u.jsx(Bd,{value:f,onChange:h,size:"md"})]}),u.jsx("div",{className:"h-px bg-gray-100"}),u.jsxs("div",{className:"flex items-center justify-between py-2",children:[u.jsx("span",{className:"text-sm text-gray-700",children:"Latency"}),u.jsx(Bd,{value:m,onChange:g,size:"md"})]})]})]})}),u.jsxs("div",{className:"flex space-x-3 pt-2",children:[u.jsx(yt,{variant:"outline",onClick:t,className:"flex-1 bg-white border-gray-300 text-gray-700 hover:bg-gray-50",children:"Cancel"}),u.jsx(yt,{onClick:T,disabled:!b,className:"flex-1 bg-black text-white hover:bg-gray-800 disabled:opacity-50",children:v?"Saving…":"Submit Rating"})]})]})]})})})};function Bd({value:e,onChange:t,size:r="md",readOnly:n}){const s=r==="lg"?"h-7 w-7":r==="sm"?"h-4 w-4":"h-5 w-5";return u.jsxs("div",{className:"flex items-center gap-1",children:[[1,2,3,4,5].map(i=>{const a=i<=Math.round(e);return u.jsx("button",{type:"button","aria-label":`rate-${i}`,disabled:n,onClick:()=>t(i),className:"disabled:cursor-default",children:u.jsx("svg",{className:a?`${s} fill-yellow-400`:`${s} fill-gray-300/70`,viewBox:"0 0 20 20",children:u.jsx("path",{d:"M10 15.27L16.18 19l-1.64-7.03L20 7.24l-7.19-.61L10 0 7.19 6.63 0 7.24l5.46 4.73L3.82 19z"})})},i)}),u.jsxs("span",{className:"ml-2 text-sm text-gray-700",children:[Math.round(e),"/5"]})]})}var Sn=Xt().min(1),jp=ni(Ri()),Cu=ni(Ri()).optional().nullable(),Bp=Sn,Z1=Xt().min(3).refine(e=>e.includes(":"),{message:"Network must be in CAIP-2 format (e.g., 'eip155:84532')"});Rx([Bp,Z1]);var h0=/^[\x20-\x7e]+$/,ew=Gn({url:Sn,description:Xt().optional(),mimeType:Xt().optional(),serviceName:Xt().min(1).max(32).regex(h0).optional(),tags:fa(Xt().min(1).max(32).regex(h0)).max(5).optional(),iconUrl:Xt().max(2048).optional()}),tw=Gn({scheme:Sn,network:Bp,maxAmountRequired:Sn,resource:Sn,description:Xt(),mimeType:Xt().optional(),outputSc
28hema:jp.optional().nullable(),payTo:Sn,maxTimeoutSeconds:Hh().positive(),asset:Sn,extra:Cu}),v5=Gn({x402Version:su(1),error:Xt().optional(),accepts:fa(tw).min(1)}),x5=Gn({x402Version:su(1),scheme:Sn,network:Bp,payload:jp}),Dp=Gn({scheme:Sn,network:Z1,amount:Sn,asset:Sn,payTo:Sn,maxTimeoutSeconds:Hh().positive(),extra:Cu}),b5=Gn({x402Version:su(2),error:Xt().optional(),resource:ew,accepts:fa(Dp).min(1),extensions:Cu}),w5=Gn({x402Version:su(2),resource:ew.optional(),accepted:Dp,payload:jp,extensions:Cu});Rx([tw,Dp]);Px("x402Version",[v5,b5]);Px("x402Version",[x5,w5]);var C5=2,S5=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),E5=e=>{const t=S5(e).replace(/\\\*/g,".*");return new RegExp(`^${t}$`)},T5=(e,t)=>E5(e).test(t),rw=(e,t)=>{let r=e.get(t);if(!r){for(const[n,s]of e.entries())if(T5(n,t)){r=s;break}}return r},p0=(e,t,r)=>rw(e,r)?.get(t),nw=/^[A-Za-z0-9+/]*={0,2}$/;function _5(e){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){const t=new TextEncoder().encode(e),r=Array.from(t,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(e,"utf8").toString("base64")}function sw(e){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){const t=globalThis.atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return new TextDecoder("utf-8").decode(r)}return Buffer.from(e,"base64").toString("utf-8")}Gn({isValid:jx(),invalidReason:Xt().nullish().transform(e=>e??void 0),invalidMessage:Xt().nullish().transform(e=>e??void 0),payer:Xt().nullish().transform(e=>e??void 0),extensions:ni(Xt(),Ri()).nullish().transform(e=>e??void 0),extra:ni(Xt(),Ri()).nullish().transform(e=>e??void 0)});Gn({success:jx(),errorReason:Xt().nullish().transform(e=>e??void 0),errorMessage:Xt().nullish().transform(e=>e??void 0),payer:Xt().nullish().transform(e=>e??void 0),transaction:Xt(),network:Bx(e=>typeof e=="string"),amount:Xt().nullish().transform(e=>e??void 0),extensions:ni(Xt(),Ri()).nullish().transform(e=>e??void 0),extra:ni(Xt(),Ri()).nullish().transform(e=>e??void 0)});var I5=Gn({x402Version:Hh(),scheme:Xt(),network:Bx(e=>typeof e=="string"),extra:ni(Xt(),Ri()).nullish().transform(e=>e??void 0)});Gn({kinds:fa(I5),extensions:fa(Xt()).default([]),signers:ni(Xt(),fa(Xt())).default({})});var m0=class{constructor(e){this.client=e,this.paymentRequiredHooks=[]}onPaymentRequired(e){return this.paymentRequiredHooks.push(e),this}async handlePaymentRequired(e){for(const t of this.getPaymentRequiredHooks(e)){const r=await t({paymentRequired:e});if(r?.headers)return r.headers}return null}encodePaymentSignatureHeader(e){switch(e.x402Version){case 2:return{"PAYMENT-SIGNATURE":g0(e)};case 1:return{"X-PAYMENT":g0(e)};default:throw new Error(`Unsupported x402 version: ${e.x402Version}`)}}getPaymentRequiredResponse(e,t){const r=e("PAYMENT-REQUIRED");if(r)return A5(r);if(t&&t instanceof Object&&"x402Version"in t&&t.x402Version===1)return t;throw new Error("Invalid payment required response")}getPaymentSettleResponse(e){const t=e("PAYMENT-RESPONSE");if(t)return Pc(t);const r=e("X-PAYMENT-RESPONSE");if(r)return Pc(r);throw new Error("Payment response header not found")}async createPaymentPayload(e){return this.client.createPaymentPayload(e)}async processPaymentResult(e,t,r){let n;try{n=this.getPaymentSettleResponse(t)}catch{}if(e.x402Version===1)return{recovered:!1,settleResponse:n};let s;if(!n&&r===402)try{s=this.getPaymentRequiredResponse(t)}catch{}const i=e.accepted;if(!i)throw new Error("Invalid x402 v2 payment payload: missing `accepted`");const a={paymentPayload:e,requirements:i,...n?{settleResponse:n}:{},...s?{paymentRequired:s}:{}};return{recovered:(await this.client.handlePaymentResponse(a))?.recovered===!0,settleResponse:n}}parsePaymentResult(e){const{status:t,getHeader:r,body:n}=e;let s;try{s=this.getPaymentSettleResponse(r)}catch{if(t===402)try{s=this.getPaymentRequiredResponse(r,n)}catch{}}let i="none";return s&&!("success"in s)&&(i="payment_required"),s&&"success"in s&&(i=s.success?"settled":"settle_failed"),{status:t,paymentStatus:i,body:n,header:s}}async processResponse(e){const t=s=>e.headers.get(s),n=(e.headers.get("content-type")??"").includes("application/json")?await e.json():await e.text();return this.parsePaymentResult({status:e.status,getHeader:t,body:n})}getPaymentRequiredHooks(e){const t=[...this.paymentRequiredHooks],r=e.extensions;
28if(!r)return t;for(const n of this.client.getExtensions()){const i=n.transportHooks?.http?.onPaymentRequired;!i||!(n.key in r)||t.push(a=>i(r[n.key],a))}return t}};function g0(e){return _5(JSON.stringify(e))}function A5(e){if(!nw.test(e))throw new Error("Invalid payment required header");return JSON.parse(sw(e))}function Pc(e){if(!nw.test(e))throw new Error("Invalid payment response header");return JSON.parse(sw(e))}var iw=class aw{constructor(t){this.registeredClientSchemes=new Map,this.schemeClientHookAdapters=new Map,this.policies=[],this.registeredExtensions=new Map,this.beforePaymentCreationHooks=[],this.afterPaymentCreationHooks=[],this.onPaymentCreationFailureHooks=[],this.paymentResponseHooks=[],this.paymentRequirementsSelector=t||((r,n)=>n[0])}static fromConfig(t){const r=new aw(t.paymentRequirementsSelector);return t.schemes.forEach(n=>{n.x402Version===1?r.registerV1(n.network,n.client):r.register(n.network,n.client)}),t.policies?.forEach(n=>{r.registerPolicy(n)}),r}register(t,r){return this._registerScheme(C5,t,r)}registerV1(t,r){return this._registerScheme(1,t,r)}registerPolicy(t){return this.policies.push(t),this}registerExtension(t){return this.registeredExtensions.set(t.key,t),this}getExtensions(){return Array.from(this.registeredExtensions.values())}onBeforePaymentCreation(t){return this.beforePaymentCreationHooks.push(t),this}onAfterPaymentCreation(t){return this.afterPaymentCreationHooks.push(t),this}onPaymentCreationFailure(t){return this.onPaymentCreationFailureHooks.push(t),this}onPaymentResponse(t){return this.paymentResponseHooks.push(t),this}async handlePaymentResponse(t){for(const r of this.getLabeledHooks("onPaymentResponse",t.paymentPayload.x402Version,t.requirements,t.paymentRequired?.extensions??t.paymentPayload.extensions)){const n=await r(t);if(n&&"recovered"in n&&n.recovered)return{recovered:!0}}}async createPaymentPayload(t){const r=this.registeredClientSchemes.get(t.x402Version);if(!r)throw new Error(`No client registered for x402 version: ${t.x402Version}`);const n=this.selectPaymentRequirements(t.x402Version,t.accepts),s={paymentRequired:t,selectedRequirements:n};for(const i of this.getLabeledHooks("beforePaymentCreation",t.x402Version,n,t.extensions)){const a=await i(s);if(a&&"abort"in a&&a.abort)throw new Error(`Payment creation aborted: ${a.reason}`)}try{const i=p0(r,n.scheme,n.network);if(!i)throw new Error(`No client registered for scheme: ${n.scheme} and network: ${n.network}`);const a=await i.createPaymentPayload(t.x402Version,n,{extensions:t.extensions});let o;if(a.x402Version==1)o=a;else{const c=this.mergeExtensions(t.extensions,a.extensions);o={x402Version:a.x402Version,payload:a.payload,extensions:c,resource:t.resource,accepted:n}}o=await this.enrichPaymentPayloadWithExtensions(o,t);const l={...s,paymentPayload:o};for(const c of this.getLabeledHooks("afterPaymentCreation",t.x402Version,n,t.extensions))await c(l);return o}catch(i){const a={...s,error:i};for(const o of this.getLabeledHooks("onPaymentCreationFailure",t.x402Version,n,t.extensions)){const l=await o(a);if(l&&"recovered"in l&&l.recovered)return l.payload}throw i}}mergeExtensions(t,r){if(!r)return t;if(!t)return r;const n={...t};for(const[s,i]of Object.entries(r)){const a=n[s];if(a===null||typeof a!="object"||Array.isArray(a)||i===null||typeof i!="object"||Array.isArray(i)){n[s]=i;continue}const o=a,l=i,c={...o},d=[{target:c,source:l}];for(const f of d)for(const[h,m]of Object.entries(f.source)){const g=f.target[h];if(g!==null&&typeof g=="object"&&!Array.isArray(g)&&m!==null&&typeof m=="object"&&!Array.isArray(m)){const v={...g};f.target[h]=v,d.push({target:v,source:m});continue}Object.prototype.hasOwnProperty.call(f.target,h)||(f.target[h]=m)}n[s]=c}return n}async enrichPaymentPayloadWithExtensions(t,r){if(!r.extensions||this.registeredExtensions.size===0)return t;let n=t;for(const[s,i]of this.registeredExtensions)s in r.extensions&&i.enrichPaymentPayload&&(n=await i.enrichPaymentPayload(n,r));return{...n,extensions:this.mergeExtensions(r.extensions,n.extensions)}}selectPaymentRequirements(t,r){const n=this.registeredClientSchemes.get(t);if(!n)throw new Error(`No client registered for x402 version: ${t}`);const s=r.filter(a=>{let o=rw(n,a.network);return o?o.has(a.scheme):!1});if(s.length===0)throw new Error(`No network/scheme registered for x402 version: ${t} which comply with the payment requirements. ${JSON.stringify({x402Version:t,paymentRequirements:r,x4
2802Versions:Array.from(this.registeredClientSchemes.keys()),networks:Array.from(n.keys()),schemes:Array.from(n.values()).map(a=>Array.from(a.keys())).flat()})}`);let i=s;for(const a of this.policies)if(i=a(t,i),i.length===0)throw new Error(`All payment requirements were filtered out by policies for x402 version: ${t}`);return this.paymentRequirementsSelector(t,i)}_registerScheme(t,r,n){this.registeredClientSchemes.has(t)||this.registeredClientSchemes.set(t,new Map);const s=this.registeredClientSchemes.get(t);s.has(r)||s.set(r,new Map),s.get(r).set(n.scheme,n),this.schemeClientHookAdapters.has(t)||this.schemeClientHookAdapters.set(t,new Map);const a=this.schemeClientHookAdapters.get(t);a.has(r)||a.set(r,new Map);const o=a.get(r),l=n.schemeHooks;if(!l)return o.delete(n.scheme),this;const c={};return l.onBeforePaymentCreation&&(c.beforePaymentCreation=l.onBeforePaymentCreation),l.onAfterPaymentCreation&&(c.afterPaymentCreation=l.onAfterPaymentCreation),l.onPaymentCreationFailure&&(c.onPaymentCreationFailure=l.onPaymentCreationFailure),l.onPaymentResponse&&(c.onPaymentResponse=l.onPaymentResponse),Object.keys(c).length>0?o.set(n.scheme,c):o.delete(n.scheme),this}getLabeledHooks(t,r,n,s){let i;switch(t){case"beforePaymentCreation":i=this.beforePaymentCreationHooks;break;case"afterPaymentCreation":i=this.afterPaymentCreationHooks;break;case"onPaymentCreationFailure":i=this.onPaymentCreationFailureHooks;break;case"onPaymentResponse":i=this.paymentResponseHooks;break}const a=[...i],o=this.schemeClientHookAdapters.get(r),c=(o?p0(o,n.scheme,n.network):void 0)?.[t];if(c!==void 0&&a.push(c),!s)return a;const d=this.getClientExtensionHookKey(t);for(const[f,h]of this.registeredExtensions){if(!(f in s))continue;const m=h.hooks?.[d];m&&a.push(async g=>m(s[f],g))}return a}getClientExtensionHookKey(t){switch(t){case"beforePaymentCreation":return"onBeforePaymentCreation";case"afterPaymentCreation":return"onAfterPaymentCreation";case"onPaymentCreationFailure":return"onPaymentCreationFailure";case"onPaymentResponse":return"onPaymentResponse"}}};function k5(e){const t=typeof e.toJSON=="function"?e.toJSON():e;return Object.entries(t).reduce((r,[n,s])=>(s!=null&&typeof s!="function"&&(r[n]=String(s)),r),{})}function eo(e,t,r){e[t]=r}function Dd(e){const t=e.validateStatus;return{...e,headers:k5(e.headers),validateStatus:r=>r===402?!0:t?t(r):r>=200&&r<300}}function ow(e,t){const r=t instanceof m0?t:new m0(t);return e.interceptors.response.use(n=>n,async n=>{if(!n.response||n.response.status!==402)return Promise.reject(n);const s=n.config;if(!s||!s.headers)return Promise.reject(new Error("Missing axios request configuration"));if(s.__is402Retry)return Promise.reject(n);try{let i;try{const m=n.response,g=w=>{const b=m.headers[w]??m.headers[w.toLowerCase()];return typeof b=="string"?b:void 0},v=m.data;i=r.getPaymentRequiredResponse(g,v)}catch(m){return Promise.reject(new Error(`Failed to parse payment requirements: ${m instanceof Error?m.message:"Unknown error"}`))}const a=await r.handlePaymentRequired(i);if(a){const m=Dd(s);Object.entries(a).forEach(([v,w])=>{eo(m.headers,v,w)});const g=await e.request(m);if(g.status!==402)return g}let o;try{o=await t.createPaymentPayload(i)}catch(m){return Promise.reject(new Error(`Failed to create payment payload: ${m instanceof Error?m.message:"Unknown error"}`))}const l=r.encodePaymentSignatureHeader(o),c=Dd(s);c.__is402Retry=!0,Object.entries(l).forEach(([m,g])=>{eo(c.headers,m,g)}),eo(c.headers,"Access-Control-Expose-Headers","PAYMENT-RESPONSE,X-PAYMENT-RESPONSE");const d=await e.request(c),f=m=>{const g=d.headers[m]??d.headers[m.toLowerCase()];return typeof g=="string"?g:void 0};if((await r.processPaymentResult(o,f,d.status)).recovered){const m=await t.createPaymentPayload(i),g=r.encodePaymentSignatureHeader(m),v=Dd(s);Object.entries(g).forEach(([C,T])=>{eo(v.headers,C,T)}),eo(v.headers,"Access-Control-Expose-Headers","PAYMENT-RESPONSE,X-PAYMENT-RESPONSE");const w=await e.request(v),b=C=>{const T=w.headers[C]??w.headers[C.toLowerCase()];return typeof T=="string"?T:void 0};return await r.processPaymentResult(m,b,w.status),w}return d}catch(i){return Promise.reject(i)}}),e}var lw={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},N5={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},R5={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},P5=[{type:"function",name:"nonces",inputs:[{name:"owner",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"view"}],j5=[{type:"function",name:"approve",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}],stateMutability:"nonpayable"}
28],cw=[{type:"function",name:"allowance",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"view"}],B5=70000n,D5=1000000000n,L5=100000000n,Xo="0x000000000022D473030F116dDEE9F6B43aC78BA3",M5="0x402085c248EeA27D92E8b30b2C58ed07f9E20001";function Jo(e){if(e.startsWith("eip155:")){const t=e.split(":")[1],r=parseInt(t,10);if(isNaN(r))throw new Error(`Invalid CAIP-2 chain ID: ${e}`);return r}throw new Error(`Unsupported network format: ${e} (expected eip155:CHAIN_ID)`)}function uw(){const e=globalThis.crypto;if(!e)throw new Error("Crypto API not available");return e}function dw(){return $v(uw().getRandomValues(new Uint8Array(32)))}function O5(){const e=uw().getRandomValues(new Uint8Array(32));return BigInt($v(e)).toString()}var y0="eip2612GasSponsoring",v0="erc20ApprovalGasSponsoring",F5="1";async function U5(e,t,r,n,s,i,a){const o=e.address,l=Pr(Xo),c=await e.readContract({address:t,abi:P5,functionName:"nonces",args:[o]}),d={name:r,version:n,chainId:s,verifyingContract:t},f=BigInt(a),h={owner:o,spender:l,value:f,nonce:c,deadline:BigInt(i)},m=await e.signTypedData({domain:d,types:R5,primaryType:"Permit",message:h});return{from:o,asset:t,spender:l,amount:f.toString(),nonce:c.toString(),deadline:i,signature:m,version:"1"}}async function V5(e,t,r){const n=e.address,s=Pr(Xo),i=sT({abi:j5,functionName:"approve",args:[s,hg]}),a=await e.getTransactionCount({address:n});let o,l;try{const d=await e.estimateFeesPerGas?.();if(!d)throw new Error("no fee estimates available");o=d.maxFeePerGas,l=d.maxPriorityFeePerGas}catch{o=D5,l=L5}const c=await e.signTransaction({to:t,data:i,nonce:a,gas:B5,maxFeePerGas:o,maxPriorityFeePerGas:l,chainId:r});return{from:n,asset:t,spender:s,amount:hg.toString(),signedTransaction:c,version:F5}}var x0=new Map;function $5(e){const t=Object.keys(e);return t.length>0&&t.every(r=>/^\d+$/.test(r))}function z5(e){const t=x0.get(e);if(t)return t;const r=iT({transport:aT(e)});return x0.set(e,r),r}function K5(e,t){if(t){if($5(t)){const r=Jo(e);return t[r]?.rpcUrl}return t.rpcUrl}}function fw(e,t,r){const n={signTransaction:t.signTransaction,readContract:t.readContract,getTransactionCount:t.getTransactionCount,estimateFeesPerGas:t.estimateFeesPerGas};if(!(!n.readContract||!n.getTransactionCount||!n.estimateFeesPerGas))return n;const i=K5(e,r);if(!i)return n;const a=z5(i);return n.readContract||(n.readContract=o=>a.readContract(o)),n.getTransactionCount||(n.getTransactionCount=async o=>a.getTransactionCount({address:o.address})),n.estimateFeesPerGas||(n.estimateFeesPerGas=async()=>a.estimateFeesPerGas()),n}async function q5(e,t,r,n,s,i){const a=fw(r.network,e,t);if(!a.readContract||!s?.extensions?.[y0])return;const o=r.extra?.name,l=r.extra?.version;if(!o||!l)return;const c=Jo(r.network),d=Pr(r.asset),f=r.amount;try{if(await a.readContract({address:d,abi:cw,functionName:"allowance",args:[e.address,Xo]})>=BigInt(f))return}catch{}const m=n.payload?.permit2Authorization?.deadline??Math.floor(Date.now()/1e3+r.maxTimeoutSeconds).toString(),g=await U5({address:e.address,signTypedData:v=>e.signTypedData(v),readContract:a.readContract},d,o,l,c,m,f);return{[y0]:{info:g}}}async function H5(e,t,r,n,s){const i=fw(r.network,e,t);if(!i.readContract||!n?.extensions?.[v0]||!i.signTransaction||!i.getTransactionCount)return;const a=Jo(r.network),o=Pr(r.asset),l=r.amount;try{if(await i.readContract({address:o,abi:cw,functionName:"allowance",args:[e.address,Xo]})>=BigInt(l))return}catch{}const c=await V5({address:e.address,signTransaction:i.signTransaction,getTransactionCount:i.getTransactionCount,estimateFeesPerGas:i.estimateFeesPerGas},o,a);return{[v0]:{info:c}}}var G5=class{constructor(e){this.signer=e,this.scheme="exact"}async createPaymentPayload(e,t){const r=t,n=dw(),s=Math.floor(Date.now()/1e3),i={from:this.signer.address,to:Pr(r.payTo),value:r.maxAmountRequired,validAfter:(s-600).toString(),validBefore:(s+r.maxTimeoutSeconds).toString(),nonce:n},a=await this.signAuthorization(i,r),o={authorization:i,signature:a};return{x402Version:e,scheme:r.scheme,network:r.network,payload:o}}async signAuthorization(e,t){const r=Y5(t.network);if(!t.extra?.name||!t.extra?.version)throw new Error(`EIP-712 domain parameters (name, version) are required in payment requirements for asset ${t.asset}`);const{name:n,version:s}=t.extra,i={name:n,version:s,chainId:r,verifyingContract:Pr(t.asset)},a={from:Pr(e.from),to:Pr(e.to),value:BigInt(e.value),validAfter:BigInt(e.validAfter),validBefore:BigInt(e.validBefore),nonce:e.nonce};return await this.signer.signTypedData({domain:i,types:lw,primaryType:"TransferWithAuthorization",message:a})}},hw={ethereum:1,sepolia:11155111,abstract:2741,"abstract-testnet"
28:11124,"base-sepolia":84532,base:8453,"avalanche-fuji":43113,avalanche:43114,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338,story:1514,educhain:41923,"skale-base-sepolia":324705682,megaeth:4326,monad:143,stable:988,"stable-testnet":2201},W5=Object.keys(hw);function Y5(e){const t=hw[e];if(!t)throw new Error(`Unsupported v1 network: ${e}`);return t}async function Q5(e,t,r,n){const s=Math.floor(Date.now()/1e3),i=O5(),a="0",o=(s+n.maxTimeoutSeconds).toString(),l={from:t.address,permitted:{token:Pr(n.asset),amount:n.amount},spender:e,nonce:i,deadline:o,witness:{to:Pr(n.payTo),validAfter:a}},c=await X5(t,l,n);return{x402Version:r,payload:{signature:c,permit2Authorization:l}}}async function X5(e,t,r){const n=Jo(r.network);return await e.signTypedData({domain:{name:"Permit2",chainId:n,verifyingContract:Xo},types:N5,primaryType:"PermitWitnessTransferFrom",message:{permitted:{token:Pr(t.permitted.token),amount:BigInt(t.permitted.amount)},spender:Pr(t.spender),nonce:BigInt(t.nonce),deadline:BigInt(t.deadline),witness:{to:Pr(t.witness.to),validAfter:BigInt(t.witness.validAfter)}}})}BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");async function J5(e,t,r){return Q5(M5,e,t,r)}async function Z5(e,t,r){const n=dw(),s=Math.floor(Date.now()/1e3),i={from:e.address,to:Pr(r.payTo),value:r.amount,validAfter:"0",validBefore:(s+r.maxTimeoutSeconds).toString(),nonce:n},a=await eP(e,i,r);return{x402Version:t,payload:{authorization:i,signature:a}}}async function eP(e,t,r){const n=Jo(r.network);if(!r.extra?.name||!r.extra?.version)throw new Error(`EIP-712 domain parameters (name, version) are required in payment requirements for asset ${r.asset}`);const{name:s,version:i}=r.extra,a={name:s,version:i,chainId:n,verifyingContract:Pr(r.asset)},o={from:Pr(t.from),to:Pr(t.to),value:BigInt(t.value),validAfter:BigInt(t.validAfter),validBefore:BigInt(t.validBefore),nonce:t.nonce};return await e.signTypedData({domain:a,types:lw,primaryType:"TransferWithAuthorization",message:o})}var tP=class{constructor(e,t){this.signer=e,this.options=t,this.scheme="exact"}async createPaymentPayload(e,t,r){if((t.extra?.assetTransferMethod??"eip3009")==="permit2"){const s=await J5(this.signer,e,t),i=await q5(this.signer,this.options,t,s,r);if(i)return{...s,extensions:i};const a=await H5(this.signer,this.options,t,r);return a?{...s,extensions:a}:s}return Z5(this.signer,e,t)}};function pw(e,t){const r=new tP(t.signer,t.schemeOptions);return t.networks&&t.networks.length>0?t.networks.forEach(n=>{e.register(n,r)}):e.register("eip155:*",r),W5.forEach(n=>{e.registerV1(n,new G5(t.signer))}),t.policies&&t.policies.forEach(n=>{e.registerPolicy(n)}),e}const cc=N.forwardRef(({className:e,...t},r)=>u.jsx("textarea",{className:ze("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm r
28ing-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[#98fe00]/50 focus-visible:border-[#98fe00]/30 disabled:cursor-not-allowed disabled:opacity-50 transition-colors",e),ref:r,...t}));cc.displayName="Textarea";const rP=LT,nP=MT,sP=OT,iP="https://x402.slinkylayer.ai",aP=e=>({GET:"bg-emerald-500 text-white",POST:"bg-blue-500 text-white",PUT:"bg-amber-500 text-white",DELETE:"bg-red-500 text-white",PATCH:"bg-purple-500 text-white"})[e]||"bg-gray-500 text-white",oP=e=>({active:"bg-emerald-100 text-emerald-700 border-emerald-300",maintenance:"bg-amber-100 text-amber-700 border-amber-300",deprecated:"bg-red-100 text-red-700 border-red-300"})[e]||"bg-gray-100 text-gray-700",lP=({resource:e,defaultOpen:t=!1,api:r})=>{const[n,s]=N.useState(t),[i,a]=N.useState(!1),[o,l]=N.useState({}),[c,d]=N.useState(!1),[f,h]=N.useState(null),[m,g]=N.useState(null),[v,w]=N.useState(null),[b,C]=N.useState(!1),[T,I]=N.useState(null),[k,_]=N.useState(""),[M,V]=N.useState(!1),{toast:G}=jn(),L=`slinky_jobid_${r.id}_${e.id}`;N.useEffect(()=>{const $=localStorage.getItem(L);$&&w($)},[L]);const H=()=>{if(!e.requestExample)return{};const $={};return e.requestExample.body&&Object.entries(e.requestExample.body).forEach(([le,B])=>{Array.isArray(B.value)?$[le]=JSON.stringify(B.value,null,2):typeof B.value=="object"&&B.value!==null?$[le]=B.value:$[le]=B.value??""}),e.requestExample.query&&Object.entries(e.requestExample.query).forEach(([le,B])=>{Array.isArray(B.value)?$[le]=JSON.stringify(B.value,null,2):typeof B.value=="object"&&B.value!==null?$[le]=B.value:$[le]=B.value??""}),e.requestExample.path&&Object.entries(e.requestExample.path).forEach(([le,B])=>{Array.isArray(B.value)?$[le]=JSON.stringify(B.value,null,2):typeof B.value=="object"&&B.value!==null?$[le]=B.value:$[le]=B.value??""}),$},F=($,le)=>{l(B=>({...B,[$]:le}))},Q=($,le,B)=>{l(Te=>({...Te,[$]:{...Te[$]||{},[le]:B}}))},J=async({apiId:$,resource:le})=>{let B=null;try{const Te=window.ethereum;if(!Te){G({description:"No wallet provider found",duration:2e3});return}const[ye]=await Te.request({method:"eth_requestAccounts"});try{await Te.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x2105"}]})}catch(ct){if(ct?.code===4902)await Te.request({method:"wallet_addEthereumChain",params:[{chainId:"0x2105",chainName:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://mainnet.base.org"],blockExplorerUrls:["https://basescan.org"]}]});else return}const U=zv({account:ye,chain:Kv,transport:qv(Te)}),Qe={address:ye,async signTypedData(ct){const ht={...ct.types};return delete ht.EIP712Domain,U.signTypedData({account:ye,domain:ct.domain,types:ht,primaryType:ct.primaryType,message:ct.message})}},pt=new iw;pw(pt,{signer:Qe});const We=ow(qh.create(),pt),dt=new URL(`${iP}/api/v1/proxy/${$}/${le.id}`);let ft="GET",At,Le;if(le.requestExample.query&&Object.keys(le.requestExample.query).forEach(ct=>{const ht=o[ct];ht==null||ht===""||dt.searchParams.append(ct,typeof ht=="string"?ht:String(ht))}),le.requestExample.path&&Object.keys(le.requestExample.path).forEach(ct=>{const ht=o[ct];ht==null||ht===""||dt.searchParams.append(ct,typeof ht=="string"?ht:String(ht))}),le.requestExample.body){ft="POST";const ct={};Object.entries(o).forEach(([ht,kt])=>{if(typeof kt=="string")try{ct[ht]=JSON.parse(kt)}catch{ct[ht]=kt}else ct[ht]=kt}),Le={"Content-Type":"application/json"},At=ct}const Ut=await We.request({url:dt.toString(),method:ft,headers:Le,data:At}),tt=Ut.headers["payment-response"];if(tt){const ht=Pc(tt).transaction}B=Ut.data}catch{G({title:"Failed to load signals",description:"Please try again later",variant:"destructive",duration:2e3})}finally{}return B},oe=async()=>{try{d(!0),g(null),h(null),w(null),I(null);const $=(e.method==="GET",o),le=await J({apiId:r.id,resource:e});h(le);let B=le?.job_id||le?.run_id;B?(w(B),localStorage.setItem(L,B),G({title:"Job Created",description:"Use 'Check Status' to see the result."})):G({title:"API Call Successful",description:"Your API request completed successfully."})}catch($){const le=$?.response?.data?.message||$?.message||"API call failed";g(le),G({title:"API Call Failed",description:le,variant:"destructive"})}finally{d(!1)}},xe=async()=>
28{if(v)try{C(!0),g(null),I(null);const $=await J1({apiId:r.id,resourceId:e.id,jobId:v});I($),($?.status==="completed"||$?.status==="failed")&&localStorage.removeItem(L),G({title:"Status Retrieved",description:"Job status fetched successfully."})}catch($){const le=$?.code==="ECONNABORTED"||$?.code==="ETIMEDOUT"||$?.message?.includes("timeout");let B=$?.response?.data?.message||$?.message||"Failed to check status";le&&(B="Request timed out. The job may still be processing. Please try again."),g(B),G({title:le?"Request Timed Out":"Status Check Failed",description:B,variant:"destructive"})}finally{C(!1)}},ge=$=>{$.stopPropagation(),s(!0),a(!0),Object.keys(o).length===0&&l(H())};return u.jsx(rP,{open:n,onOpenChange:s,children:u.jsxs("div",{className:"bg-white border rounded-lg hover:shadow-md transition-shadow",children:[u.jsx(nP,{className:"w-full",children:u.jsxs("div",{className:"p-4 flex items-center justify-between gap-4",children:[u.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[u.jsx(cs,{className:`${aP(e.method)} px-3 py-1`,children:e.method}),u.jsx("code",{className:"text-sm font-mono text-gray-900",children:e.endpoint}),u.jsx(cs,{variant:"outline",className:"text-xs text-gray-700 bg-gray-100",children:e.category})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs(yt,{size:"sm",onClick:ge,className:"bg-black text-white hover:bg-[#98fe00] hover:text-black transition-all duration-200",children:["Use Tool - $",e.perCallPrice]}),u.jsx(cs,{className:`${oP(e.status)} h-9 px-3 flex items-center justify-center`,children:e.status}),n?u.jsx(zh,{className:"h-5 w-5 text-gray-600"}):u.jsx(ri,{className:"h-5 w-5 text-gray-600"})]})]})}),u.jsx(sP,{children:u.jsxs("div",{className:"px-4 pb-4 pt-2 border-t",children:[u.jsx("p",{className:"text-sm text-gray-600 mt-2 mb-4",children:e.description}),i&&e.requestExample&&u.jsxs("div",{className:"space-y-4 bg-gray-50 p-4 rounded-lg",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("h4",{className:"font-semibold text-sm text-gray-900",children:"Test API"}),u.jsx(yt,{variant:"ghost",size:"sm",onClick:()=>{a(!1),h(null),g(null)},children:"Cancel"})]}),u.jsxs("div",{className:"space-y-3",children:[e.requestExample.body&&Object.entries(e.requestExample.body).map(([$,le])=>typeof le.value=="object"&&le.value!==null&&!Array.isArray(le.value)&&Object.keys(le.value).length>0?u.jsxs("div",{className:"space-y-2",children:[u.jsxs(hr,{className:"text-xs text-gray-700 font-medium",children:[$," ",le.required?u.jsx("span",{className:"text-red-500",children:"*"}):u.jsx("span",{className:"text-gray-500",children:"(optional)"})]}),le.more&&u.jsx("p",{className:"text-xs text-gray-500 mt-0.5 mb-1",children:le.more}),u.jsx("div",{className:"ml-4 space-y-3 p-3 bg-gray-50 rounded border border-gray-200",children:Object.entries(le.value).map(([ye,U])=>u.jsxs("div",{children:[u.jsx(hr,{htmlFor:`${$}_${ye}`,className:"text-xs text-gray-600",children:ye}),u.jsx(rn,{id:`${$}_${ye}`,type:"text",value:o[$]?.[ye]??"",onChange:Qe=>Q($,ye,Qe.target.value),placeholder:`Enter ${ye}`,className:"mt-1"})]},ye))})]},$):Array.isArray(le.value)?u.jsxs("div",{children:[u.jsxs(hr,{htmlFor:$,className:"text-xs text-gray-700 font-medium",children:[$," ",le.required?u.jsx("span",{className:"text-red-500",children:"*"}):u.jsx("span",{className:"text-gray-500",children:"(optional)"})]}),le.more&&u.jsx("p",{className:"text-xs text-gray-500 mt-0.5 mb-1",children:le.more}),u.jsx(cc,{id:$,value:o[$]??"",onChange:ye=>F($,ye.target.value),placeholder:`Enter ${$} as JSON`,className:"mt-1 font-mono text-xs",rows:6,required:le.required})]},$):u.jsxs("div",{children:[u.jsxs(hr,{htmlFor:$,className:"text-xs text-gray-700 font-medium",children:[$," ",le.required?u.jsx("span",{className:"text-red-500",children:"*"}):u.jsx("span",{className:"text-gray-500",children:"(optional)"})]}),le.more&&u.jsx("p",{className:"text-xs text-gray-500 mt-0.5 mb-1",children:le.more}),$==="content"||$==="text"?u.jsx(cc,{id:$,value:o[$]??"",onChange:ye=>F($,ye.target.value),placeholder:`Enter ${$}`,className:"mt-1",rows:3,required:le.required}):u.jsx(rn,{id:$,type:le.type===Number?"number":"text",value:o[$]??"",onChange:ye=>F($,le.type===Number?Number(ye.target.value):ye.target.value),placeholder:`Enter ${$}`,className:"mt-1",required:le.required})]},$)),e.requestExample.query&&Object.entries(e.requestExample.query).map(([$,le])=>typeof le.value=="object"&&le.value!==null&&!Array.isArray(le.value)&&Object.keys(le.value).length>0?u.jsxs("div",{className:"space-y-2",children:[u.jsxs(hr,{className:"text-xs text-gray-700 font-medium",children:[$," (query parameter) ",le.required?u.jsx("span",{className:"text-red-500",children:"*"}):u.jsx("span",{className:"text-gray-500",children:"(optional)"})]}),le.more&&u.jsx("p",{className:"text-xs text-gray-500 mt-0.5 mb-1",children:le.more}),u.jsx("div",{className:"ml-4 space-y-3 p-3 bg-gray-50 rounded border border-gray-200",children:Object.entries(le.value).map(([ye,U])=>u.jsxs("div",{children:[u.jsx(hr,{htmlFor:`${$}_${ye}`,className:"text-xs text-gray-600",children:ye}),u.jsx(rn,{id:`${$}_${ye}`,type:"text",value:o[$]?.[ye]??"",onChange:Qe=>Q($,ye,Qe.target.value),placeholder:`Enter ${ye}`,className:"mt-1"})]},ye))})]},$):Array.isArray(le.value)?u.jsxs("div",{children:[u.jsxs(hr,{htmlFor:$,className:"text-xs text-gray-700 font-medium",children:[$," (query parameter) ",le.required?u.jsx("span",{className:"text-red-500",children:"*"}):u.jsx("span",{className:"text-gray-500",children:"(optional)"})]}),le.more&&u.jsx("p",{className:"text-xs text-gray-500 mt-0.5 mb-1",children:le.more}),u.jsx(cc,{id:$,value:o[$]??"",onChange:ye=>F($,ye.target.value),placeholder:`Enter ${$} as JSON`,className:"mt-1 font-mono text-xs",rows:6,required:le.required})]},$):u.jsxs("div",{children:[u.jsxs(hr,{htmlFor:$,className:"text-xs text-gray-700 font-medium",children:[$," (query parameter) ",le.required?u.jsx("span",{className:"text-red-500",children:"*"}):u.jsx("span",{className:"text-gray-500",children:"(optional)"})]}),le.more&&u.jsx("p",{className:"text-xs text-gray-500 mt-0.5 mb-1",children:le.more}),u.jsx(rn,{id:$,type:le.type===Number?"number":"text",value:o[$]??"",onChange:ye=>F($,le.type===Number?Number(ye.target.value):ye.target.value),placeholder:`Enter ${$}`,className:"mt-1",required:le.required})]},$)),e.requestExample.path&&Object.entries(e.requestExample.path).map(([$,le])=>u.jsxs("div",{children:[u.jsxs(hr,{htmlFor:`path-${$}`,className:"text-xs text-gray-700 font-medium",children:[$," (parameter) ",le.required?u.jsx("span",{className:"text-red-500",children:"*"}):u.jsx("span",{className:"text-gray-500",children:"(optional)"})]}),le.more&&u.jsx("p",{className:"text-xs text-gray-500 mt-0.5 mb-1",children:le.more}),u.jsx(rn,{id:`path-${$}`,type:le.type===Number?"number":"text",value:o[$]??"",onChange:B=>F($,le.type===Number?Number(B.target.value):B.target.value),placeholder:`Enter ${$}`,className:"mt-1",required:le.required})]},`path-${$}`))]}
28),u.jsx(yt,{onClick:oe,disabled:c,className:"w-full bg-black text-white hover:bg-[#98fe00] hover:text-black",children:c?u.jsxs(u.Fragment,{children:[u.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Calling API..."]}):"Call API"}),!v&&u.jsxs("div",{className:"mt-4 p-3 bg-gray-50 border border-gray-200 rounded",children:[u.jsx("button",{onClick:()=>V(!M),className:"text-sm text-blue-600 text-gray-800 hover:text-blue-800 font-medium",children:M?"− Hide":"+ Check existing job ID"}),M&&u.jsxs("div",{className:"mt-3 space-y-2",children:[u.jsx(hr,{htmlFor:"manualJobId",className:"text-xs text-gray-700 font-medium",children:"Enter Job ID"}),u.jsx(rn,{id:"manualJobId",value:k,onChange:$=>_($.target.value),placeholder:"e.g., 64f1bb8f-d831-4b7c-9907-00fcff473bc5",className:"font-mono text-sm"}),u.jsx(yt,{onClick:()=>{k.trim()&&(w(k.trim()),localStorage.setItem(L,k.trim()),_(""),V(!1),G({title:"Job ID Set",description:"Click 'Check Status' to retrieve the result."}))},disabled:!k.trim(),className:"w-full bg-black text-white hover:bg-[#98fe00] hover:text-black",children:"Load Job ID"})]})]}),f&&!v&&u.jsxs("div",{className:"mt-4 p-3 bg-green-50 border border-green-200 rounded",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[u.jsx(yd,{className:"h-4 w-4 text-green-600"}),u.jsx("span",{className:"text-sm font-semibold text-green-900",children:"Success"})]}),u.jsx("pre",{className:"text-xs text-gray-800 overflow-auto max-h-48",children:JSON.stringify(f,null,2)})]}),v&&u.jsxs("div",{className:"mt-4 space-y-3",children:[u.jsxs("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(yd,{className:"h-4 w-4 text-blue-600"}),u.jsx("span",{className:"text-sm font-semibold text-blue-900",children:"Job Created"})]}),u.jsx("button",{onClick:()=>{w(null),I(null),localStorage.removeItem(L),G({description:"Job ID cleared"})},className:"text-xs text-gray-500 hover:text-red-600",children:"Clear"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsxs("p",{className:"text-xs text-blue-800",children:["Job ID: ",u.jsx("code",{className:"bg-blue-100 px-2 py-1 rounded",children:v})]}),u.jsx("p",{className:"text-xs text-gray-600",children:'Click "Check Status" to retrieve the result.'})]})]}),u.jsx(yt,{onClick:xe,disabled:b,className:"w-full bg-blue-600 text-white hover:bg-blue-700",children:b?u.jsxs(u.Fragment,{children:[u.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Checking Status..."]}):"Check Status"}),T&&u.jsxs("div",{className:"p-3 bg-green-50 border border-green-200 rounded",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[u.jsx(yd,{className:"h-4 w-4 text-green-600"}),u.jsx("span",{className:"text-sm font-semibold text-green-900",children:"Result"})]}),u.jsx("pre",{className:"text-xs text-gray-800 overflow-auto max-h-48",children:JSON.stringify(T,null,2)})]})]}),m&&u.jsxs("div",{className:"mt-4 p-3 bg-red-50 border border-red-200 rounded",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(_x,{className:"h-4 w-4 text-red-600"}),u.jsx("span",{className:"text-sm font-semibold text-red-900",children:"Error"})]}),v&&u.jsx("button",{onClick:()=>g(null),className:"text-xs text-gray-500 hover:text-gray-700",children:"Dismiss"})]}),u.jsx("p",{className:"text-xs text-red-800 mb-2",children:m}),v&&u.jsx("p",{className:"text-xs text-gray-600",children:'You can try checking the status again using the "Check Status" button above.'})]})]})]})})]})})},b0=({icon:e,title:t,value:r,iconColor:n,iconBgColor:s="bg-gray-50"})=>u.jsx(es,{className:"shadow-sm hover:shadow-md transition-shadow border bg-white",children:u.jsx(Ks,{className:"pt-6",children:u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx("div",{className:`rounded-full p-3 ${s}`,children:u.jsx(e,{className:`h-6 w-6 ${n}`})}),u.jsxs("div",{children:[u.jsx("p",{className:"text-sm text-gray-600 mb-1",children:t}),u.jsx("p",{className:"text-3xl font-bold text-gray-900",children:r})]})]})})}),cP=()=>{const{apiId:e}=C_(),t=Sa(),{toast:r}=jn();N.useState(null),N.useState(""),N.useState(""),N.useState(!1);const[n,s]=N.useState(!1),[i,a]=N.useState(!1),o="temp-api-usage-proof",[l,c]=N.useState(null),[d,f]=N.useState(!0),[h,m]=N.useState(null),[g,v]=N.useState(localStorage.getItem("wallet_address"));if(N.useEffect(()=>{const C=()=>{v(localStorage.getItem("wallet_address"))};return window.addEventListener("storage",C),window.addEventListener("walletConnected",C),window.addEventListener("walletDisconnected",C),()=>{window.removeEventListener("storage",C),window.removeEventListener("walletConnected",C),window.removeEventListener("walletDisconnected",C)}},[]),N.useEffect(()=>{(async()=>
28{if(e){if(!g){m("Please connect your wallet to view API details"),f(!1);return}try{f(!0),m(null);const T=await p5(e);c(T)}catch{m("Failed to load API details"),c(null)}finally{f(!1)}}})()},[e,g]),d)return u.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:u.jsx("div",{className:"inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"})});if(h||!l)return u.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:u.jsxs("div",{className:"text-center",children:[u.jsx("h2",{className:"text-2xl font-bold text-[#0b0f14] mb-4",children:h||"API Not Found"}),u.jsx(yt,{className:"text-black",onClick:()=>t("/tools"),children:"Back to Tools"})]})});const w=C=>({GET:"bg-green-500/20 text-green-600 border-green-500/30",POST:"bg-blue-500/20 text-blue-600 border-blue-500/30",PUT:"bg-yellow-500/20 text-yellow-600 border-yellow-500/30",DELETE:"bg-red-500/20 text-red-600 border-red-500/30",PATCH:"bg-purple-500/20 text-purple-600 border-purple-500/30"})[C]||"bg-gray-500/20 text-gray-600 border-gray-500/30",b=C=>({active:"bg-green-100 text-green-700",beta:"bg-blue-100 text-blue-700",deprecated:"bg-red-100 text-red-700"})[C]||"bg-gray-100 text-gray-700";return`${l.method}${l.endpoint}`,l.method,`${l.endpoint}${l.method}`,l.method,`${l.endpoint}`,l.method!=="GET"?`${l.method.toLowerCase()}`:`${l.method.toLowerCase()}`,u.jsxs("div",{className:"min-h-screen bg-white",children:[u.jsxs("div",{className:"container mx-auto px-4 py-8",children:[u.jsxs(yt,{variant:"ghost",onClick:()=>t("/tools"),className:"mb-6 gap-2 text-black",children:[u.jsx(i_,{className:"h-4 w-4"}),"Back to Tools"]}),u.jsx(es,{className:"mb-6 relative bg-white",children:u.jsx(Ks,{className:"pt-6",children:u.jsx("div",{className:"flex items-start justify-between",children:u.jsxs("div",{className:"flex-1",children:[u.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:l.name}),u.jsx(cs,{className:w(l.method),children:l.method}),u.jsx(cs,{className:b(l.status),children:l.status})]}),u.jsx(yt,{onClick:()=>r({description:"Voting will be enabled soon",duration:2e3}),className:"bg-black text-white hover:bg-[#98fe00] hover:text-black transition-all duration-200",children:"Vote ↑"})]}),u.jsx("p",{className:"text-gray-600 mb-4",children:l.description}),u.jsxs("div",{className:"flex items-center gap-6 text-sm flex-wrap",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(ya,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"}),u.jsx("span",{className:"font-semibold text-gray-900",children:" - "})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(Sx,{className:"h-4 w-4 text-gray-500"}),u.jsx("span",{className:"text-gray-700",children:" - "})]}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"text-gray-600",children:[l.resources.length," Resources"]})}),u.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:l.categories.map(C=>u.jsx(cs,{variant:"secondary",className:"text-xs text-gray-700 bg-gray-100",children:C},C))})]})]})})})}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-6",children:[u.jsx(b0,{icon:Ex,title:"Latency",value:l.latency,iconColor:"text-blue-600",iconBgColor:"bg-blue-50"}),u.jsx(b0,{icon:Ix,title:"Uptime",value:l.uptime,iconColor:"text-green-600",iconBgColor:"bg-green-50"})]}),u.jsxs("div",{className:"mb-6",children:[u.jsx("h2",{className:"text-2xl font-bold mb-4",children:"API Resources"}),u.jsx("div",{className:"space-y-3",children:l.resources.map((C,T)=>u.jsx(lP,{resource:C,api:l,defaultOpen:T===0},C.id))})]})]}),u.jsx(y5,{isOpen:n,onClose:()=>s(!1),modelName:l.name,usageProofId:o,onConfirm:async({overall:C,criteria:T,comment:I})=>{if(!i){a(!0);try{await h5({entityType:"api",entityId:l.id.toString(),entityVersion:null,overall:C,criteria:T||void 0,comment:I,usageProofId:o}),r({title:"Thanks for your rating!",description:"Your rating has been recorded.",duration:2e3}),s(!1)}catch{r({title:"Couldn't submit rating",description:"Please try again.",variant:"destructive",duration:2500})}finally{a(!1)}}}})]})};let pa=null;function uP(e,t){e.currentIndex=0,e.wipContextDeps=null,e.wipCommitCallbacks=[];const r=pa;pa=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{pa=r}}function ai(){if(!pa)throw new Error("No resource fiber available");return pa}function Mi(){return pa}const Lp=Symbol("tap.Context.defaultValue"),dP=e=>e;let ss=new Map;const Si=new Set,mw=()=>new Map(ss),Ld=(e,t)=>{const r=ss;ss=e;try{return t()}finally{ss=r}},gw=(e,t)=>{e[Lp]=t},yw=e=>typeof e=="object"&&e!==null&&Lp in e,vw=e=>typeof e=="object"&&e!==null&&"$$typeof"in e&&e.$$typeof===Symbol.for("react.context"),Mp=e=>yw(e)||vw(e),xw=e=>{if(!yw(e)){if(vw(e)){gw(e,e._currentValue??e._currentValue2);return}throw new Error("A tap resource's `use()` only accepts a tap context.")}},bw=(e,t,r)=>{if(typeof e!="object"||e===null)throw new Error("useContextProvider only accepts a React context.");xw(e);const n=e,s=ai(),i=wt(void 0),a=i.current===void 0||!Object.is(i.current.value,t);ot(()=>{i.current={value:t}},[t]);const o=ss.get(n),l=o!==void 0||ss.has(n);ss.set(n,{value:t,source:s});try{return fP(n,a,r)}finally{l?ss.set(n,o):ss.delete(n)}},fP=(e,t,r)=>{const n=Si.has(e);t?Si.add(e):Si.delete(e);try{return r()}finally{n?Si.add(e):Si.delete(e)}},hP=e=>{xw(e);const t=e,r=pP(t,e),n=ai();return(n.wipContextDeps??(n.wipContextDeps=new Map)).set(t,r.source),r.value},pP=(e,t)=>
28ss.get(e)??{value:dP(t)[Lp],source:null},mP=(e,t,r,n)=>{if(!n)return r;let s=r;for(const[i,a]of n)a===t||a===e||(s??(s=new Map)).set(i,a);return s},ww=(e,t=e.wipContextDeps)=>{const r=Mi();!r||!t||(r.wipContextDeps=mP(r,e,r.wipContextDeps,t))},Cw=()=>Si.size>0,Op=e=>{if(!e.contextDeps||!Cw())return!1;for(const t of Si.keys())if(e.contextDeps.has(t))return!0;return!1},gP=[0,1,2,3];function w0(e){const t=[];for(const r of gP){const n=e[r];if(n!==void 0)for(let s=0;s<n.length;s++)try{n[s]()}catch(i){t.push(i)}}if(t.length>0){if(t.length===1)throw t[0];for(const r of t)console.error(r);throw new AggregateError(t,"Errors during commit")}}function Sw(e){const t=[];for(const r of e.cells)if(r?.type==="effect"&&(r.deps=null,r.cleanup))try{r.cleanup?.()}catch(n){t.push(n)}finally{r.cleanup=void 0}if(t.length>0){if(t.length===1)throw t[0];for(const r of t)console.error(r);throw new AggregateError(t,"Errors during cleanup")}}const Rn=typeof process<"u"&&!1,Ew=e=>({version:0,committedVersion:0,context:mw(),dispatchUpdate:e,changelog:[],rollbackCallbacks:[]}),jc=e=>{e.committedVersion=e.version,e.changelog.length=0,e.rollbackCallbacks.length=0},go=(e,t)=>{const r=e.version>t;if(e.version=t,r){for(let n=0;n<e.rollbackCallbacks.length;n++)e.rollbackCallbacks[n]();if(e.rollbackCallbacks.length=0,t===e.committedVersion)e.changelog.length=0;else{if(e.committedVersion>t)throw new Error("Version is less than committed version");for(;e.committedVersion+e.changelog.length>t;)e.changelog.pop();for(let n=0;n<e.changelog.length;n++)Tw(e.changelog[n]);jc(e)}}},Tw=e=>{var t;Iw(e.fiber,e.cell),e.queued||(e.queued=!0,((t=e.cell).queue??(t.queue=[])).push(e))},_o=(e,t,r)=>{const n=e.wipCommitCallbacks;(n[t]??(n[t]=[])).push(r)},_w=(e,t)=>{e.rollbackCallbacks.push(t)},Iw=(e,t)=>{t.isDirty||(t.isDirty=!0,e.markDirty?.(),_w(e.root,()=>{if(t.queue!==null){for(const r of t.queue)r.queued=!1;t.queue=null}t.workInProgress=t.current,t.isDirty=!1}))},Fp=()=>{throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.")},Up=()=>{throw new Error("Hook order changed between renders")},yP=(e,t,r)=>{if(e.isNeverMounted)throw new Error("Resource updated before mount");let n=!1,s=!0;e.root.dispatchUpdate(()=>(n||(n=!0,r&&e.root.changelog.length===0&&!t.cell.isDirty&&!t.hasEagerState&&(t.eagerState=r(t.cell.workInProgress,t.action),t.hasEagerState=!0,s=!Object.is(t.cell.current,t.eagerState))),s),()=>(n=!0,s=!0,Tw(t),e.root.changelog.push(t),!0))},vP=(e,t,r,n,s)=>{const i=n?n(r):r;Rn&&e.devStrictMode&&n&&n(r);const a={type:"reducer",workInProgress:i,current:i,isDirty:!1,queue:null,renderQueue:null,reducer:t,dispatch:o=>{const l=Mi();if(l!==null){if(l!==e)throw new Error("Cannot update a resource while rendering a different resource.");(e.renderPendingCells??(e.renderPendingCells=new Set)).add(a),(a.renderQueue??(a.renderQueue=[])).push(o)}else yP(e,{fiber:e,cell:a,action:o,hasEagerState:!1,eagerState:void 0,queued:!1},s?t:void 0)}};return a};function Aw(e,t,r,n){const s=ai(),i=s.currentIndex++,a=s.cells[i],o=(()=>{if(a!==void 0)return a.type==="reducer"?a:Up();!s.isFirstRender&&i>=s.cells.length&&Fp();const c=vP(s,e,t,r,n);return s.cells[i]=c,c})(),l=o.queue;if(l!==null){const c=e===o.reducer;for(let d=0;d<l.length;d++){const f=l[d];!f.hasEagerState||!c?(f.eagerState=e(o.workInProgress,f.action),f.hasEagerState=!0,Rn&&s.devStrictMode&&(f.eagerState=e(o.workInProgress,f.action))):Rn&&s.devStrictMode&&e(o.workInProgress,f.action),f.queued=!1,o.workInProgress=f.eagerState}o.queue=null}if(o.reducer=e,o.renderQueue!==null){let c=o.workInProgress;for(const d of o.renderQueue)c=e(c,d);o.renderQueue=null,s.renderPendingCells?.delete(o),Object.is(c,o.workInProgress)||(Iw(s,o),o.workInProgress=c)}return o.isDirty&&_o(s,0,()=>{o.current=o.workInProgress,o.isDirty=!1}),[o.workInProgress,o.dispatch]}function kw(e,t,r){return Aw(e,t,r,!1)}const xP=(e,t)=>typeof t=="function"?t(e):t,bP=e=>e===void 0?void 0:typeof e=="function"?e():e;function Vp(e){return Aw(xP,e,bP,!0)}const Su=(e,t)=>{Rn&&e.length!==t.length&&console.error(`The final argument passed to a hook changed size between renders. The order and size of this array must remain constant.
29
30Previous: [${e.join(", ")}]
31Incoming: [${t.join(", ")}]`);for(let r=0;r<e.length&&r<t.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},C0=(e,t)=>{_o(e,0,()=>{t.current=t.wip,t.currentDeps=t.wipDeps,t.isDirty=!1})},Eu=(e,t)=>{const r=ai(),n=r.currentIndex++;let s=r.cells[n];if(s===void 0){!r.isFirstRender&&n>=r.cells.length&&Fp();const o=e();return Rn&&r.devStrictMode&&e(),s={type:"memo",current:o,currentDeps:t,wip:o,wipDeps:t,isDirty:!1},r.cells[n]=s,o}s.type!=="memo"&&Up();const i=s;
31if(Su(i.wipDeps,t))return i.isDirty&&C0(r,i),i.wip;const a=e();return Rn&&r.devStrictMode&&e(),i.wip=a,i.wipDeps=t,i.isDirty||(i.isDirty=!0,_w(r.root,()=>{i.wip=i.current,i.wipDeps=i.currentDeps,i.isDirty=!1})),C0(r,i),a};function Tu(e){return Eu(()=>({current:e}),[])}const $p=(e,t)=>Eu(()=>e,t),wP=()=>({type:"effect",cleanup:void 0,deps:null});function ma(e,t){const r=ai(),n=r.currentIndex++,s=r.cells[n],i=s===void 0?wP():s.type==="effect"?s:Up();if(s===void 0&&(!r.isFirstRender&&n>=r.cells.length&&Fp(),r.cells[n]=i),!(t&&i.deps&&Su(i.deps,t))){if(i.deps!==null&&!!t!=!!i.deps)throw new Error("useEffect called with and without dependencies across re-renders");_o(r,2,()=>{try{i.cleanup?.()}finally{i.cleanup=void 0}}),_o(r,3,()=>{try{const a=e();if(a!==void 0&&typeof a!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof a}`);i.cleanup=a}finally{i.deps=t}})}}function zp(e){const t=ai(),r=Tu(e);return r.current!==e&&_o(t,1,()=>{r.current=e}),$p((...n)=>{if(Rn&&Mi())throw new Error("useEffectEvent cannot be called during render");return r.current(...n)},[])}const Bc=e=>{if(!Mp(e))throw new Error("A tap resource's `use()` only accepts a tap context.");return hP(e)},Nw=(e,t,r=t)=>{const n=Tu(!0),s=n.current?r():t();n.current=!1;const[,i]=Vp(0),a=zp(()=>{Object.is(s,t())||i(o=>o+1)});return ma(()=>(a(),e(a)),[e]),s},Rw=(e,t)=>{},CP=_e;function SP(e){const t=N.useRef(e);return N.useInsertionEffect(()=>{t.current=e}),N.useCallback((...r)=>t.current(...r),[])}const EP=CP.useEffectEvent??SP,Bn=()=>Mi()!==null,Dn=_e,pr=e=>Bn()?Vp(e):Dn.useState(e),TP=(e,t,r)=>Bn()?kw(e,t,r):Dn.useReducer(e,t,r),wt=e=>Bn()?Tu(e):Dn.useRef(e),Gt=(e,t)=>Bn()?Eu(e,t):Dn.useMemo(e,t),Zs=(e,t)=>Bn()?$p(e,t):Dn.useCallback(e,t),ot=(e,t)=>Bn()?ma(e,t):Dn.useEffect(e,t),Io=(e,t)=>Bn()?ma(e,t):Dn.useLayoutEffect(e,t),kn=e=>Bn()?zp(e):EP(e),Oi=(e,t,r)=>Bn()?Nw(e,t,r):Dn.useSyncExternalStore(e,t,r),Pw=(e,t)=>Bn()?Rw():Dn.useDebugValue(e,t),Ln=e=>{const t=Dn.createContext(e);return gw(t,e),t},jw=e=>Bn()&&Mp(e)?Bc(e):Dn.use(e),Mn=e=>Bn()&&Mp(e)?Bc(e):Dn.useContext(e),Bw=_e,Dw=Symbol.for("react.memo_cache_sentinel"),Lw=e=>new Array(e).fill(Dw),_P=e=>Bw.useMemo(()=>{const t=Lw(e);return t[Dw]=!0,t},[]),ce=e=>{const t=Mi();if(t===null)return(Bw.__COMPILER_RUNTIME?.c??_P)(e);const r=t.memoCache;let n=r.workInProgress;if(n===null){const a=r.current;n=a===null?[]:a.map(o=>o.slice()),r.workInProgress=n}const s=r.index++;let i=n[s];return i===void 0?(i=Lw(e),n[s]=i):Rn&&i.length!==e&&console.error(`Expected a constant size argument for each invocation of c(). The previous cache was allocated with size ${i.length} but size ${e} was requested.`),i};function qt(e){return(...t)=>({hook:e,args:t})}function qn(e,t,r){return r?{...t,key:e,deps:r}:{...t,key:e}}const IP=50;let os={schedulers:new Set([]),isScheduled:!1};var AP=class{constructor(e){q(this,"_task");q(this,"_isDirty",!1);this._task=e}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,os.schedulers.add(this),kP()}runTask(){this._isDirty=!1,this._task()}};const kP=()=>{os.isScheduled||(os.isScheduled=!0,NP())},nh=()=>{try{const e=[];let t=0;for(const r of os.schedulers)if(os.schedulers.delete(r),!!r.isDirty){if(t++,t>IP)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside useEffect.");try{r.runTask()}catch(n){e.push(n)}}if(e.length>0){if(e.length===1)throw e[0];for(const r of e)console.error(r);throw new AggregateError(e,"Errors occurred during flushSync")}}finally{os.schedulers.clear(),os.isScheduled=!1}},NP=(()=>{if(typeof MessageChannel<"u"){const e=new MessageChannel;return e.port1.onmessage=nh,()=>e.port2.postMessage(null)}return()=>setTimeout(nh,0)})(),S0=e=>{const t=os;os={schedulers:new Set([]),isScheduled:!0};try{const r=e();return nh(),r}finally{os=t}},RP={useState:Vp,useReducer:kw,useRef:Tu,useMemo:Eu,useCallback:$p,useEffect:ma,useLayoutEffect:ma,useInsertionEffect:ma,useEffectEvent:zp,useContext:Bc,use:Bc,useSyncExternalStore:Nw,useDebugValue:Rw},E0=_e,gi=E0.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE??E0.__SECRET_INT
31ERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Ol=gi==null?null:"H"in gi?{get current(){return gi.H},set current(e){gi.H=e}}:"ReactCurrentDispatcher"in gi?{get current(){return gi.ReactCurrentDispatcher.current},set current(e){gi.ReactCurrentDispatcher.current=e}}:null;function PP(e){if(!Ol)return e();const t=Ol.current;Ol.current=RP;try{return e()}finally{Ol.current=t}}function Mw(e,t,r=void 0,n){return{hook:e,root:t,markDirty:r,devStrictMode:n,cells:[],contextDeps:null,wipContextDeps:null,commitCallbacks:null,wipCommitCallbacks:null,memoCache:{current:null,workInProgress:null,index:0},renderPendingCells:null,currentIndex:0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function ga(e){if(!e.isMounted)throw new Error("Tried to unmount a fiber that is already unmounted");e.isMounted=!1,Sw(e)}function ei(e,t){if(e.memoCache.workInProgress=null,e.renderPendingCells!==null){for(const s of e.renderPendingCells)s.renderQueue=null;e.renderPendingCells.clear()}let r=0,n;do{if(++r>25)throw new Error("Too many re-renders. tap limits the number of renders to prevent an infinite loop.");e.memoCache.index=0,uP(e,()=>{n=PP(()=>e.hook(...t))})}while((e.renderPendingCells?.size??0)>0);return ww(e),n}function Ao(e){const t=e.wipCommitCallbacks??e.commitCallbacks??[];e.wipCommitCallbacks=null,e.commitCallbacks=t,e.isMounted=!0,e.contextDeps=e.wipContextDeps,jc(e.root),e.memoCache.workInProgress!==null&&(e.memoCache.current=e.memoCache.workInProgress,e.memoCache.workInProgress=null),Rn&&e.isNeverMounted&&e.devStrictMode==="root"&&(e.isNeverMounted=!1,w0(t),Sw(e)),e.isNeverMounted=!1,w0(t)}const jP=()=>{const e=ai();return e.devStrictMode?e.isFirstRender?"child":"root":null},BP=()=>"child",T0=()=>null,DP=()=>{if(!Rn)return T0;const e=wt(0);return pr(()=>e.current++),e.current!==2?T0:BP},Ow=()=>Mi()?jP:DP(),LP=e=>e(),MP=e=>{const t=Gt(()=>new AP(()=>m()),[]),r=Gt(()=>[],[]),n=Ow(),s=Gt(()=>{const g=Ew((v,w)=>{if(!t.isDirty){if(!v())return;w()}go(g,g.committedVersion+g.changelog.length),r.push(w),t.markDirty()});return Mw(LP,g,void 0,n())},[r,t,n]),i=mw(),a=s.root.version-s.root.committedVersion,o=Ld(i,()=>ei(s,[e])),l=wt(!1),c=wt([e]),d=wt(o),f=Gt(()=>new Set,[]),h=g=>{t.isDirty||d.current===g||(d.current=g,f.forEach(v=>v()))},m=kn(()=>{go(s.root,s.root.committedVersion),r.forEach(v=>{Rn&&s.devStrictMode&&v(),v()}),go(s.root,s.root.committedVersion+s.root.changelog.length),Rn&&s.devStrictMode&&Ld(s.root.context,()=>ei(s,c.current));const g=Ld(s.root.context,()=>ei(s,c.current));if(t.isDirty)throw new Error("Scheduler is dirty, this should never happen");jc(s.root),r.length=0,l.current&&Ao(s),h(g)});return ot(()=>(l.current=!0,()=>{l.current=!1,ga(s)}),[s]),ot(()=>{c.current=[e],jc(s.root),r.splice(0,a),s.root.context=i,Ao(s),h(o)}),Gt(()=>({getValue:()=>d.current,subscribe:g=>(f.add(g),()=>f.delete(g))}),[f])},OP=()=>{const e=wt(0),t=e.current,r=ai();return{version:t,markDirty:Gt(()=>()=>{e.current++,r?.markDirty?.()},[r]),root:r.root}},FP=()=>{const e=Gt(()=>Ew((s,i)=>{let a=!1;n(o=>(a=!s(),a?o:o+1)),a||r(i)}),[]),[t,r]=TP((s,i)=>(go(e,s),s+(i()?1:0)),0),[,n]=pr(0);return go(e,t),{root:e,version:t,markDirty:void 0}},Kp=()=>{const e=Ow(),{root:t,version:r,markDirty:n}=Mi()?OP():FP();return{version:r,createFiber:Zs((s,i,a)=>Mw(s,t,a?()=>{a(),n?.()}:n,e()),[])}},Fw=(e,t,r)=>{const n=wt(null),s=n.current??(n.current={wipDeps:null,wip:null,currentDeps:null,current:null});return s.wipDeps=s.currentDeps,s.wip=s.current,ot(()=>{s.currentDeps=s.wipDeps,s.current=s.wip}),!r&&s.currentDeps&&Su(s.currentDeps,t)?s.current:(s.wipDeps=t,s.wip=e(),s.wip)};function sn(e){const{version:t,createFiber:r}=Kp(),n=Gt(()=>r(e.hook,e.key),[e.hook,e.key,r]),s=Fw(()=>({value:ei(n,e.args)}),[n,t,e.args],Op(n));return ot(()=>()=>ga(n),[n]),ot(()=>{Ao(n)},[n,s]),s.value}const _0=(e,t)=>{const r=e.get(t);r&&(r.isDirty=!0)},UP=(e,t)=>!e.isDirty&&!Op(e.fiber)&&t!==void 0&&e.committedDeps!==void 0&&Su(e.committedDeps,t),VP=e=>{if(!Cw())return!1;for(const{fiber:t}of e.values())if(Op(t))return!0;return!1};function _u(e){const t=Gt(()=>new Map,[]),{version:r,createFiber:n}=Kp(),s=VP(t),i=Fw(()=>{const a=new Set,o=[];let l=0;for(let c=0;c<e.length;c++){const d=e[c],f=d.key;if(f===void 0)throw new Error(`useResources did not provide a key for array at index ${c}`);if(a.has(f))throw new Error(`Duplicate key ${f} in useResources`);a.add(f);let h=t.get(f);if(h)if(h.fiber.hook!==d.hook){const m=n(d.hook,d.key,()=>_0(t,f)),g=ei(m,d.args);h.next={value:g,deps:d.deps,remount:m}}else if(UP(h,d.deps))h.fiber.contextDeps&&ww(h.fiber,h.fiber.contextDeps),h.next="skip";else{const m=ei(h.fiber,d.args);h.next={value:m,deps:d.deps}}else{const m=n(d.hook,d.key,()=>_0(t,f));h={fiber:m,next:{value:ei(m,d.args),deps:d.deps},isDirty:!1,committedDeps:void 0,committedValue:void 0},l++,t.set(f,h)}o.push(typeof h.next=="object"?h.next.value:h.committedValue)}if(t.size>o.length-l)for(const c of t.keys())a.has(c)||(t.get(c).next="delete");return o},[e,t,n,r],s);return ot(()=>()=>{for(const a of t.keys()){const o=t.get(a).fiber;ga(o)}},[t]),ot(()=>
31{for(const[a,o]of t.entries()){const l=o.next;l==="delete"?(o.fiber.isMounted&&ga(o.fiber),t.delete(a)):l==="skip"||(l.remount&&(ga(o.fiber),o.fiber=l.remount),Ao(o.fiber),o.committedDeps=l.deps,o.committedValue=l.value,o.isDirty=!1)}},[i,t]),i}const $P=e=>e(),zP=e=>{const{createFiber:t}=Kp(),r=Gt(()=>t($P,void 0),[t]),n=ei(r,[e]);ot(()=>()=>{ga(r)},[r]);let s=!1;const i=()=>{s&&r.isMounted||(s=!0,Ao(r))};return ot(i),{value:n,effects:i}},KP=()=>{const e=ce(4),[t,r]=pr(HP);let n;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=(l,c)=>(r(d=>({...d,renderers:{...d.renderers,[l]:[...d.renderers[l]??[],c]}})),()=>{r(d=>({...d,renderers:{...d.renderers,[l]:d.renderers[l]?.filter(f=>f!==c)??[]}}))}),e[0]=n):n=e[0];const s=n;let i;e[1]===Symbol.for("react.memo_cache_sentinel")?(i=l=>(r(c=>({...c,fallbacks:[...c.fallbacks,l]})),()=>{r(c=>({...c,fallbacks:c.fallbacks.filter(d=>d!==l)}))}),e[1]=i):i=e[1];const a=i;let o;return e[2]!==t?(o={getState:()=>t,setDataUI:s,setFallbackDataUI:a},e[2]=t,e[3]=o):o=e[3],o},qP=qt(KP);function HP(){return{renderers:{},fallbacks:[]}}const GP=e=>{const t=Array.from(e).map(n=>n.getModelContext()).sort((n,s)=>(s.priority??0)-(n.priority??0)),r={};return t.reduce((n,s)=>{const i=s.priority??0;if(s.system&&(n.system?n.system+=`
32
33${s.system}`:n.system=s.system),s.tools)for(const[a,o]of Object.entries(s.tools)){const l=n.tools?.[a];if(l&&l!==o){const c=r[a];if(c===i)throw new Error(`You tried to define a tool with the name ${a}, but it already exists.`);const d=c>i?l:o,f=c>i?o:l;n.tools[a]={...f,...d},r[a]=Math.max(c,i);continue}n.tools||(n.tools={}),n.tools[a]=o,r[a]??(r[a]=i)}return s.config&&(n.config={...n.config,...s.config}),s.callSettings&&(n.callSettings={...n.callSettings,...s.callSettings}),s.unstable_composerMetadata&&(n.unstable_composerMetadata={...n.unstable_composerMetadata,...s.unstable_composerMetadata}),n},{})};var Uw=class{constructor(){q(this,"_providers",new Set);q(this,"_subscribers",new Set)}getModelContext(){return GP(this._providers)}registerModelContextProvider(e){this._providers.add(e);const t=e.subscribe?.(()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t?.(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}};const sh=[],WP={modelName:void 0,toolNames:sh},YP=(e,t)=>e===t||e.length===t.length&&e.every((r,n)=>r===t[n]),Fl=(e,t)=>{const r=e.getModelContext(),n=r.config?.modelName,s=r.tools?Object.keys(r.tools).sort():sh,i=s.length?s:sh;return n===t.modelName&&YP(i,t.toolNames)?t:{modelName:n,toolNames:i}},QP=()=>{const e=ce(11);let t;e[0]===Symbol.for("react.memo_cache_sentinel")?(t=new Uw,e[0]=t):t=e[0];const r=t;let n;e[1]===Symbol.for("react.memo_cache_sentinel")?(n=()=>Fl(r,WP),e[1]=n):n=e[1];const[s,i]=pr(n);let a,o;e[2]===Symbol.for("react.memo_cache_sentinel")?(a=()=>(i(m=>Fl(r,m)),r.subscribe(()=>{i(m=>Fl(r,m))})),o=[r],e[2]=a,e[3]=o):(a=e[2],o=e[3]),ot(a,o);let l;e[4]!==s?(l=()=>Fl(r,s),e[4]=s,e[5]=l):l=e[5];let c,d,f;e[6]===Symbol.for("react.memo_cache_sentinel")?(c=()=>r.getModelContext(),d=m=>r.subscribe(m),f=m=>r.registerModelContextProvider(m),e[6]=c,e[7]=d,e[8]=f):(c=e[6],d=e[7],f=e[8]);let h;return e[9]!==l?(h={getState:l,getModelContext:c,subscribe:d,register:f},e[9]=l,e[10]=h):h=e[10],h},Vw=qt(QP),XP=e=>e.display!==void 0?e.display==="standalone":e.type==="human",JP=(e,t)=>{if(!(t.status?.type==="running"||t.status?.type==="requires-action")){const n=e.complete;return typeof n!="function"?n??null:n({args:t.args,result:t.result})}const r=e.running;return typeof r!="function"?r??null:r({args:t.args})},ZP=e=>function(r){return JP(e,r)},ih=Symbol("assistant-ui.store.clientIndex"),ej=e=>e[ih],$w=Ln([]),qp=()=>jw($w),tj=(e,t)=>{const r=ce(3),n=qp();let s;return r[0]!==e||r[1]!==n?(s=[...n,e],r[0]=e,r[1]=n,r[2]=s):s=r[2],bw($w,s,t)},rj=new Set(["$$typeof","nodeType","then"]),Iu=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!="symbol"){if(e==="toJSON")return()=>t;if(!rj.has(e))return!1}};var Hp=class{getOwnPropertyDescriptor(e,t){const r=this.get(e,t);if(r!==void 0)return{value:r,writable:!1,enumerable:!0,configurable:!1}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}};const Dc=Symbol("assistant-ui.store.getValue"),nj=e=>{const t=e[Dc];if(!t)throw new Error("Client scope contains a non-client resource. Ensure your Derived get() returns a client created with useClientResource(), not a plain resource.");return t.getState?.()},I0=new Map;function sj(e){let t=I0.get(e);return t||(t=function(...r){if(!this||typeof this!="object")throw new Error(`Method "${String(e)}" called without proper context. This may indicate the function was called 
33incorrectly.`);const n=this[Dc];if(!n)throw new Error(`Method "${String(e)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);const s=n[e];if(!s)throw new Error(`Method "${String(e)}" is not implemented.`);if(typeof s!="function")throw new Error(`"${String(e)}" is not a function.`);return s(...r)},I0.set(e,t)),t}var ij=class extends Hp{constructor(t,r){super();q(this,"outputRef");q(this,"index");q(this,"boundFns");q(this,"cachedReceiver");this.outputRef=t,this.index=r}get(t,r,n){if(r===Dc)return this.outputRef.current;if(r===ih)return this.index;const s=Iu(r,"ClientProxy");if(s!==!1)return s;const i=this.outputRef.current[r];if(typeof i=="function"){this.cachedReceiver!==n&&(this.boundFns=new Map,this.cachedReceiver=n);let a=this.boundFns.get(r);return a||(a=sj(r).bind(n),this.boundFns.set(r,a)),a}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(t,r){return r===Dc||r===ih?!0:r in this.outputRef.current}};const Zo=e=>{const t=wt(null),r=qp().length,n=Gt(()=>new Proxy({},new ij(t,r)),[r]),s=tj(n,function(){return sn(e)});return t.current||(t.current=s),ot(()=>{t.current=s}),{methods:n,state:s.getState?.(),key:e.key}},aj=qt(Zo),yo=Symbol("assistant-ui.store.proxiedAssistantState"),Md=e=>e==="on"||e==="subscribe"||typeof e=="symbol",zw=e=>{class t extends Hp{get(n,s){const i=Iu(s,"AssistantState");if(i!==!1)return i;const a=s;if(!Md(a))return nj(e[a]())}ownKeys(){return Object.keys(e).filter(n=>!Md(n))}has(n,s){return!Md(s)&&s in e}}return new Proxy({},new t)},oj=e=>e[yo],A0=()=>()=>{},Kw=e=>{const t=()=>{throw new Error(e)};return t.source=null,t.query=null,t};var lj=class extends Hp{get(e,t){if(t==="subscribe"||t==="on")return A0;if(t===yo)return cj;const r=Iu(t,"DefaultAssistantClient");return r!==!1?r:Kw("You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.")}ownKeys(){return["subscribe","on",yo]}has(e,t){return t==="subscribe"||t==="on"||t===yo}};const Au=new Proxy({},new lj),cj=zw(Au),uj=()=>new Proxy({},{get(e,t){const r=Iu(t,"AssistantClient");return r!==!1?r:Kw(`The current scope does not have a "${String(t)}" property.`)}}),qw=Ln(Au),Hw=Symbol("assistant-ui.store.useEffects"),dj=()=>{},fj=e=>e[Hw]??dj,hj=()=>{"use no memo";return ot(fj(Gw())),null},Gw=()=>Mn(qw),Pn=({value:e,children:t})=>{"use no memo";return u.jsxs(qw.Provider,{value:e,children:[u.jsx(hj,{}),t]})},ah=e=>null,Nn=qt(ah),oh=Symbol("assistant-ui.transform-scopes");function Ww(e,t){const r=e;if(r[oh])throw new Error("transformScopes is already attached to this resource");r[oh]=t}function pj(e){return e[oh]}const Yw=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},Qw=Ln(null),mj=(e,t)=>bw(Qw,e,t),Xw=()=>{const e=jw(Qw);if(!e)throw new Error("AssistantTapContext is not available");return e},Jw=()=>Xw().clientRef,Gp=()=>{const e=ce(3),{emit:t}=Xw(),r=qp();let n;return e[0]!==r||e[1]!==t?(n=(s,i)=>{t(s,i,r)},e[0]=r,e[1]=t,e[2]=n):n=e[2],kn(n)};function gj(e,t){const r={...e},n=new Set;let s=!0;for(;s;){s=!1;for(const o of Object.values(r)){if(o.hook===ah||n.has(o.hook))continue;n.add(o.hook);const l=pj(o.hook);if(l){l(r,t),s=!0;break}}}const i={},a={};for(const[o,l]of Object.entries(r))l.hook===ah?a[o]=l:i[o]=l;return{rootClients:i,derivedClients:a}}const k0=e=>Gt(()=>e,[...Object.entries(e).flat()]),yj=(e,t)=>{const r=ce(6);let n;r[0]!==t||r[1]!==e?(n=gj(e,t),r[0]=t,r[1]=e,r[2]=n):n=r[2];const{rootClients:s,derivedClients:i}=n,a=k0(s),o=k0(i);let l;return r[3]!==a||r[4]!==o?(l={rootClients:a,derivedClients:o},r[3]=a,r[4]=o,r[5]=l):l=r[5],l},vj=()=>{const e=ce(3);let t;e[0]===Symbol.for("react.memo_cache_sentinel")?(t=new Map,e[0]=t):t=e[0];const r=t;let n;e[1]===Symbol.for("react.memo_cache_sentinel")?(n=new Set,e[1]=n):n=e[1];const s=n;let i;if(e[2]===Symbol.for("react.memo_cache_sentinel")){const a=new Set;i={on(o,l){const c=l;if(o==="*")return s.add(c),()=>s.delete(c);let d=r.get(o);return d||(d=new Set,r.set(o,d)),d.add(c),()=>{d.delete(c),d.size===0&&r.delete(o)}},emit(o,l,c){const d=r.get(o);!d&&s.size===0||queueMicrotask(()=>{const f=[];if(d)for(const h of d)try{h(l,c)}catch(m){const g=m;f.push(g)}if(s.size>0){const h={event:o,payload:l};for(const m of s)try{m(h,c)}catch(g){const v=g;
33f.push(v)}}if(f.length>0){if(f.length===1)throw f[0];for(const h of f)console.error(h);throw new AggregateError(f,"Errors occurred during event emission")}})},subscribe(o){return a.add(o),()=>a.delete(o)},notifySubscribers(){for(const o of a)try{o()}catch(l){console.error("NotificationManager: subscriber callback error",l)}}},e[2]=i}else i=e[2];return i},xj=qt(vj),Zw=e=>Gt(()=>e,e),bj=({element:e,emit:t,clientRef:r})=>{const{methods:n,state:s}=mj({clientRef:r,emit:t},function(){return Zo(e)});return Gt(()=>({state:s,methods:n}),[n,s])},wj=({element:e,notifications:t,clientRef:r,name:n})=>{const s=MP(function(){return bj({element:e,emit:t.emit,clientRef:r})});return ot(()=>s.subscribe(t.notifySubscribers),[s,t]),Gt(()=>{const i=()=>s.getValue().methods;return Object.defineProperties(i,{source:{value:"root",writable:!1},query:{value:{},writable:!1},name:{value:n,configurable:!0}}),i},[s,n])},Cj=qt(wj),Sj=()=>{const e=ce(2);let t;e[0]===Symbol.for("react.memo_cache_sentinel")?(t=[],e[0]=t):t=e[0];let r;return e[1]===Symbol.for("react.memo_cache_sentinel")?(r={clients:t,subscribe:void 0,on:void 0},e[1]=r):r=e[1],r},Ej=qt(Sj),Tj=e=>{const t=ce(14),{clients:r,clientRef:n}=e;let s;t[0]===Symbol.for("react.memo_cache_sentinel")?(s=xj(),t[0]=s):s=t[0];const i=sn(s);let a;t[1]!==n.parent||t[2]!==i.notifySubscribers?(a=()=>n.parent.subscribe(i.notifySubscribers),t[1]=n.parent,t[2]=i.notifySubscribers,t[3]=a):a=t[3];let o;t[4]!==n||t[5]!==i?(o=[n,i],t[4]=n,t[5]=i,t[6]=o):o=t[6],ot(a,o);let l;t[7]!==n||t[8]!==r||t[9]!==i?(l=Object.keys(r).map(f=>qn(f,Cj({element:r[f],notifications:i,clientRef:n,name:f}))),t[7]=n,t[8]=r,t[9]=i,t[10]=l):l=t[10];const c=Zw(_u(l));let d;return t[11]!==i||t[12]!==c?(d={notifications:i,results:c},t[11]=i,t[12]=c,t[13]=d):d=t[13],d},_j=e=>{const{clientRef:t}=e,{notifications:r,results:n}=Tj(e);return Gt(()=>({clients:n,subscribe:r.subscribe,on:function(s,i){if(!this)throw new Error("const { on } = useAui() is not supported. Use aui.on() instead.");const{scope:a,event:o}=Yw(s);if(a!=="*"&&this[a].source===null)throw new Error(`Scope "${a}" is not available. Use { scope: "*", event: "${o}" } to listen globally.`);const l=r.on(o,(d,f)=>{if(a==="*"){i(d);return}const h=this[a]();h===f[ej(h)]&&i(d)});if(a!=="*"&&t.parent[a].source===null)return l;const c=t.parent.on(s,i);return()=>{l(),c()}}}),[n,r,t])},Ij=qt(_j),Aj=({element:e,clientRef:t,name:r})=>{const n=wt(e.args[0]);return n.current=e.args[0],Gt(()=>{const s=()=>n.current.get(t.current);return Object.defineProperties(s,{source:{value:n.current.source},query:{value:n.current.query},name:{value:r,configurable:!0}}),s},[t,r])},kj=qt(Aj),Nj=(e,t)=>{let r;try{const n={};for(const s of Object.keys(t.query).sort())n[s]=t.query[s];r=JSON.stringify(n)}catch{r=String(t.query)}return`${e}::${t.source}::${r}`},Rj=e=>{const t=ce(3),{clients:r,clientRef:n}=e;let s;return t[0]!==n||t[1]!==r?(s=Object.keys(r).map(i=>{const a=i,o=r[a];return qn(Nj(a,o.args[0]),kj({element:o,clientRef:n,name:a}))}),t[0]=n,t[1]=r,t[2]=s):s=t[2],Zw(_u(s))},Pj=e=>{const t=ce(3),{rootClients:r,clientRef:n}=e;let s;return t[0]!==n||t[1]!==r?(s=Object.keys(r).length>0?Ij({clients:r,clientRef:n}):Ej(),t[0]=n,t[1]=r,t[2]=s):s=t[2],sn(s)},jj=({parent:e,clients:t})=>{const{rootClients:r,derivedClients:n}=yj(t,e),s=wt({parent:e,current:null}).current;ot(()=>{s.current=o});const i=Pj({rootClients:r,clientRef:s}),a=Rj({clients:n,clientRef:s}),o=Gt(()=>{const l=e===Au?uj():e,c=Object.create(l);Object.assign(c,{subscribe:i.subscribe??e.subscribe,on:i.on??e.on,[yo]:zw(c)});for(const d of i.clients)c[d.name]=d;for(const d of a)c[d.name]=d;return c},[e,i,a]);return s.current===null&&(s.current=o),o},Bj=e=>{const{value:t,effects:r}=zP(function(){return jj(e)});return t[Hw]=r,t};function vt(e,{parent:t}={parent:Gw()}){if(e)return Bj({parent:t??Au,clients:e});if(t===null)throw new Error("received null parent, this usage is not allowed");return t}const Fe=e=>{const t=ce(6),r=vt();let n;t[0]!==r?(n=oj(r),t[0]=r,t[1]=n):n=t[1];const s=n;let i,a;t[2]!==s||t[3]!==e?(i=()=>e(s),a=()=>e(s),t[2]=s,t[3]=e,t[4]=i,t[5]=a):(i=t[4],a=t[5]);const o=Oi(r.subscribe,i,a);if(o===s)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return Pw(o),o},Dj=e=>{const t=vt(),r=wt(!1),n=r.current?null:e(t);return Fe(()=>r.current?e(t):n),()=>(r.current=!0,e(t))},Lj=Object.freeze({});function Ra(e){const t=ce(3),{getItemState:r,children:n}=e,s=Dj(r);let i;return t[0]!==n||t[1]!==s?(i=n(s),t[0]=n,t[1]=s,t[2]=i):i=t[2],Mj(i)}const Mj=e=>{const t=typeof e=="object"&&e!=null&&"type"in e?e:null,r=t?.type,n=t?.key;return Gt(()=>t,[r,n,typeof t?.props=="object"&&t.props!=null&&Object.entries(t.props).length===0?Lj:t?.props])??e},Oj=_e.createContext(!0);function N0(){throw new Error("A function wrapped in useEffectEvent can't be called during rendering.")}const Fj="use"in _e?()=>{try{return _e.use(Oj)}catch{return!1}}:()=>!1;function Uj(e){const t=_e.useRef(N0);return _e.useInsertionEffect(()=>{t.current=e},[e]),(...r)=>{Fj()&&N0();const n=t.current;return n(...r)}}const Lc=(e,t)=>{const r=ce(11),n=vt(),s=Uj(t);let i;r[0]!==e?(i=Yw(e),r[0]=e,r[1]=i):i=r[1];const{scope:a,event:o}=i;let l;r[2]!==n||r[3]!==s||r[4]!==o||r[5]!==a?(l=()=>n.on({scope:a,event:o},s),r[2]=n,r[3]=s,r[4]=o,r[5]=a,r[6]=l):l=r[6];let c;r[7]!==n||r[8]!==o||r[9]!==a?(c=[n,a,o],r[7]=n,r[8]=o,r[9]=a,r[10]=c):c=r[10],ot(l,c)},Vj=e=>{if(e.key===void 0)throw new Error("useClientLookup: Element has no key");return e.key};function Pi(e){const t=ce(15);let r;t[0]!==e?(r=e.map(Kj),t[0]=e,t[1]=r):r=t[1];const n=_u(r);let s;t[2]!==n?(s=Object.keys(n),t[2]=n,t[3]=s):s=t[3];const i=s;let a;t[4]!==n?(a=n.reduce(zj,{}),t[4]=n,t[5]=a):a=t[5];const o=a;let l;t[6]!==n?(l=n.map($j),t[6]=n,t[7]=l):l=t[7];const c=l;let d;t[8]!==o||t[9]!==i||t[10]!==n?(d=h=>{if("index"in h){if(h.index<0||h.index>=i.length)throw new Error(`useClientLookup: Index ${h.index} out of bounds (length: ${i.length})`);return n[h.index].methods}const m=o[h.key];if(m===void 0)throw new Error(`useClientLookup: Key "${h.key}" not found`);return n[m].methods},t[8]=o,t[9]=i,t[10]=n,t[11]=d):d=t[11];let f;return t[12]!==c||t[13]!==d?(f={state:c,get:d},t[12]=c,t[13]=d,t[14]=f):f=t[14],f}function $j(e){return e.state}function zj(e,t,r){return e[t.key]=r,e}function Kj(e){return qn(Vj(e),aj(e),e.deps)}const eC=e=>{const t=ce(15),{toolkit:r,mcpApp:n}=e;let s;t[0]!==n?(s=n?[qn("mcpApp",n)]:[],t[0]=n,t[1]=s):s=t[1];const i=_u(s)[0],[a,o]=pr(Hj);let l;t[2]!==a?(l=Object.fromEntries(Object.entries(a).map(Wj)),t[2]=a,t[3]=l):l=t[3];let c;t[4]!==i||t[5]!==l||t[6]!==a?(c={toolUIs:a,mcpApp:i,tools:l},t[4]=i,t[5]=l,t[6]=a,t[7]=c):c=t[7];const d=c,f=Jw();let h;t[8]===Symbol.for("react.memo_cache_sentinel")?(h=(b,C,T)=>{const I={render:C,standalone:T?.standalone??!1};return o(k=>({...k,[b]:[...k[b]??[],I]})),()=>{o(k=>{const _=k[b]?.filter(V=>V!==I)??[];if(_.length>0)return{...k,[b]:_};const M={...k};return delete M[b],M})}},t[8]=h):h=t[8];const m=h;let g,v;t[9]!==f||t[10]!==r?(g=()=>{if(!r)return;const b=[];for(const[T,I]of Object.entries(r)){const k="render"in I?I.render:void 0,_="renderText"in I?I.renderText:void 0,M=k??(_?ZP(_):void 0);M&&b.push(m(T,M,{standalone:XP(I)}))}const C=Object.entries(r).reduce(Yj,{});return b.push(f.current.modelContext().register({getModelContext:()=>({tools:C})}
33)),()=>{b.forEach(Qj)}},v=[r,m,f],t[9]=f,t[10]=r,t[11]=g,t[12]=v):(g=t[11],v=t[12]),ot(g,v);let w;return t[13]!==d?(w={getState:()=>d,setToolUI:m},t[13]=d,t[14]=w):w=t[14],w},qj=qt(eC);Ww(eC,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=Vw())});function Hj(){return{}}function Gj(e){return e.render}function Wj(e){const[t,r]=e;return[t,r.map(Gj)]}function Yj(e,t){const[r,n]=t;if(n.type==="mcp")return e;const{display:s,render:i,renderText:a,...o}=n;return e[r]=o,e}function Qj(e){return e()}const Fi=e=>Oi(e.subscribe,e.getState),Xj=e=>{const t=ce(8),{runtime:r}=e,n=Fi(r);let s;t[0]!==n?(s=()=>n,t[0]=n,t[1]=s):s=t[1];let i;t[2]!==r?(i=()=>r,t[2]=r,t[3]=i):i=t[3];let a;return t[4]!==r.remove||t[5]!==s||t[6]!==i?(a={getState:s,remove:r.remove,__internal_getRuntime:i},t[4]=r.remove,t[5]=s,t[6]=i,t[7]=a):a=t[7],a},tC=qt(Xj),Jj=e=>{const t=ce(5),{runtime:r,index:n}=e;let s;t[0]!==n||t[1]!==r?(s=r.getAttachmentByIndex(n),t[0]=n,t[1]=r,t[2]=s):s=t[2];const i=s;let a;return t[3]!==i?(a=tC({runtime:i}
33),t[3]=i,t[4]=a):a=t[4],sn(a)},Zj=qt(Jj),eB=({item:e,onSteer:t,onRemove:r})=>({getState:()=>e,steer:t,remove:r}),tB=qt(eB),rB=e=>{const t=ce(55),{threadIdRef:r,messageIdRef:n,runtime:s}=e,i=Fi(s),a=Gp();let o,l;t[0]!==a||t[1]!==n||t[2]!==s||t[3]!==r?(o=()=>{const M=[];for(const V of["send","attachmentAdd"]){const G=s.unstable_on(V,()=>{a(`composer.${V}`,{threadId:r.current,...n&&{messageId:n.current}})});M.push(G)}return M.push(s.unstable_on("attachmentAddError",V=>{a("composer.attachmentAddError",{threadId:r.current,...n&&{messageId:n.current},...V.attachmentId&&{attachmentId:V.attachmentId},reason:V.reason,message:V.message})})),()=>{for(const V of M)V()}},l=[s,a,r,n],t[0]=a,t[1]=n,t[2]=s,t[3]=r,t[4]=o,t[5]=l):(o=t[4],l=t[5]),ot(o,l);let c;if(t[6]!==s||t[7]!==i.attachments){let M;t[9]!==s?(M=(V,G)=>qn(V.id,Zj({runtime:s,index:G}),[s,G]),t[9]=s,t[10]=M):M=t[10],c=i.attachments.map(M),t[6]=s,t[7]=i.attachments,t[8]=c}else c=t[8];const d=Pi(c),f=i.queue;let h;if(t[11]!==f||t[12]!==s){let M;t[14]!==s?(M=V=>qn(V.id,tB({item:V,onSteer:()=>s.steerQueueItem(V.id),onRemove:()=>s.removeQueueItem(V.id)})),t[14]=s,t[15]=M):M=t[15],h=f.map(M),t[11]=f,t[12]=s,t[13]=h}else h=t[13];const m=Pi(h),g=i.type??"thread";let v;t[16]!==d.state||t[17]!==f||t[18]!==i.attachmentAccept||t[19]!==i.canCancel||t[20]!==i.canSend||t[21]!==i.dictation||t[22]!==i.isEditing||t[23]!==i.isEmpty||t[24]!==i.quote||t[25]!==i.role||t[26]!==i.runConfig||t[27]!==i.text||t[28]!==g?(v={text:i.text,role:i.role,attachments:d.state,runConfig:i.runConfig,isEditing:i.isEditing,canCancel:i.canCancel,canSe
33nd:i.canSend,attachmentAccept:i.attachmentAccept,isEmpty:i.isEmpty,type:g,dictation:i.dictation,quote:i.quote,queue:f},t[16]=d.state,t[17]=f,t[18]=i.attachmentAccept,t[19]=i.canCancel,t[20]=i.canSend,t[21]=i.dictation,t[22]=i.isEditing,t[23]=i.isEmpty,t[24]=i.quote,t[25]=i.role,t[26]=i.runConfig,t[27]=i.text,t[28]=g,t[29]=v):v=t[29];const w=v;let b;t[30]!==w?(b=()=>w,t[30]=w,t[31]=b):b=t[31];const C=s.beginEdit??nB;let T;t[32]!==d?(T=M=>"id"in M?d.get({key:M.id}):d.get(M),t[32]=d,t[33]=T):T=t[33];let I;t[34]!==m?(I=M=>m.get(M),t[34]=m,t[35]=I):I=t[35];let k;t[36]!==s?(k=()=>s,t[36]=s,t[37]=k):k=t[37];let _;return t[38]!==s.addAttachment||t[39]!==s.cancel||t[40]!==s.clearAttachments||t[41]!==s.reset||t[42]!==s.send||t[43]!==s.setQuote||t[44]!==s.setRole||t[45]!==s.setRunConfig||t[46]!==s.setText||t[47]!==s.startDictation||t[48]!==s.stopDictation||t[49]!==I||t[50]!==k||t[51]!==b||t[52]!==C||t[53]!==T?(_={getState:b,setText:s.setText,setRole:s.setRole,setRunConfig:s.setRunConfig,addAttachment:s.addAttachment,reset:s.reset,clearAttachments:s.clearAttachments,send:s.send,cancel:s.cancel,beginEdit:C,startDictation:s.startDictation,stopDictation:s.stopDictation,setQuote:s.setQuote,attachment:T,queueItem:I,__internal_getRuntime:k},t[38]=s.addAttachment,t[39]=s.cancel,t[40]=s.clearAttachments,t[41]=s.reset,t[42]=s.send,t[43]=s.setQuote,t[44]=s.setRole,t[45]=s.setRunConfig,t[46]=s.setText,t[47]=s.startDictation,t[48]=s.stopDictation,t[49]=I,t[50]=k,t[51]=b,t[52]=C,t[53]=T,t[54]=_):_=t[54],_},rC=qt(rB);function nB(){throw new Error("beginEdit is not supported in this runtime")}const nC=e=>({get current(){return e()}}),sB=e=>{const t=ce(13),{runtime:r}=e,n=Fi(r);let s;t[0]!==n?(s=()=>n,t[0]=n,t[1]=s):s=t[1];let i,a,o,l;t[2]!==r?(i=d=>r.addToolResult(d),a=d=>r.resumeToolCall(d),o=d=>r.respondToToolApproval(d),l=()=>r,t[2]=r,t[3]=i,t[4]=a,t[5]=o,t[6]=l):(i=t[3],a=t[4],o=t[5],l=t[6]);let c;return t[7]!==s||t[8]!==i||t[9]!==a||t[10]!==o||t[11]!==l?(c={getState:s,addToolResult:i,resumeToolCall:a,respondToToolApproval:o,__internal_getRuntime:l},t[7]=s,t[8]=i,t[9]=a,t[10]=o,t[11]=l,t[12]=c):c=t[12],c},iB=qt(sB),aB=e=>{const t=ce(5),{runtime:r,index:n}=e;let s;t[0]!==n||t[1]!==r?(s=r.getAttachmentByIndex(n),t[0]=n,t[1]=r,t[2]=s):s=t[2];const i=s;let a;return t[3]!==i?(a=tC({runtime:i}),t[3]=i,t[4]=a):a=t[4],sn(a)},oB=qt(aB),lB=e=>{const t=ce(5),{runtime:r,index:n}=e;let s;t[0]!==n||t[1]!==r?(s=r.getMessagePartByIndex(n),t[0]=n,t[1]=r,t[2]=s):s=t[2];const i=s;let a;return t[3]!==i?(a=iB({runtime:i}),t[3]=i,t[4]=a):a=t[4],sn(a)},cB=qt(lB),uB=e=>{const t=ce(55),{runtime:r,threadIdRef:n}=e,s=Fi(r),[i,a]=pr(!1),[o,l]=pr(!1);let c;t[0]!==r?(c=nC(()=>r.getState().id),t[0]=r,t[1]=c):c=t[1];const d=c;let f;t[2]!==d||t[3]!==r.composer||t[4]!==n?(f=rC({runtime:r.composer,threadIdRef:n,messageIdRef:d}),t[2]=d,t[3]=r.composer,t[4]=n,t[5]=f):f=t[5];const h=Zo(f);let m;if(t[6]!==r||t[7]!==s.content){let $;t[9]!==r?($=(le,B)=>qn("toolCallId"in le&&le.toolCallId!=null?`toolCallId-${le.toolCallId}`:`index-${B}`,cB({runtime:r,index:B}),[r,B]),t[9]=r,t[10]=$):$=t[10],m=s.content.map($),t[6]=r,t[7]=s.content,t[8]=m}else m=t[8];const g=Pi(m);let v;t[11]!==s.attachments?(v=s.attachments??[],t[11]=s.attachments,t[12]=v):v=t[12];let w;if(t[13]!==r||t[14]!==v){let $;t[16]!==r?($=(le,B)=>qn(le.id,oB({runtime:r,index:B}),[r,B]),t[16]=r,t[17]=$):$=t[17],w=v.map($),t[13]=r,t[14]=v,t[15]=w}else w=t[15];const b=Pi(w),C=s;let T;t[18]!==h.state||t[19]!==i||t[20]!==o||t[21]!==g.state||t[22]!==C?(T={...C,parts:g.state,composer:h.state,isCopied:i,isHovering:o},t[18]=h.state,t[19]=i,t[20]=o,t[21]=g.state,t[22]=C,t[23]=T):T=t[23];const I=T;let k;t[24]!==I?(k=()=>I,t[24]=I,t[25]=k):k=t[25];let _;t[26]!==h.methods?(_=()=>h.methods,t[26]=h.methods,t[27]=_):_=t[27];let M,V,G,L,H,F,Q;t[28]!==r?(M=()=>r.delete(),V=$=>r.reload($),G=()=>r.speak(),L=()=>r.stopSpeaking(),H=$=>r.submitFeedback($),F=$=>r.switchToBranch($),Q=()=>r.unstable_getCopyText(),t[28]=r,t[29]=M,t[30]=V,t[31]=G,t[32]=L,t[33]=H,t[34]=F,t[35]=Q):(M=t[29],V=t[30],G=t[31],L=t[32],H=t[33],F=t[34],Q=t[35]);let J;t[36]!==g?(J=$=>"index"in $?g.get({index:$.index}):g.get({key:`toolCallId-${$.toolCallId}`}
33),t[36]=g,t[37]=J):J=t[37];let oe;t[38]!==b?(oe=$=>"id"in $?b.get({key:$.id}):b.get($),t[38]=b,t[39]=oe):oe=t[39];let xe;t[40]!==r?(xe=()=>r,t[40]=r,t[41]=xe):xe=t[41];let ge;return t[42]!==M||t[43]!==V||t[44]!==G||t[45]!==L||t[46]!==H||t[47]!==F||t[48]!==Q||t[49]!==J||t[50]!==oe||t[51]!==xe||t[52]!==k||t[53]!==_?(ge={getState:k,composer:_,delete:M,reload:V,speak:G,stopSpeaking:L,submitFeedback:H,switchToBranch:F,getCopyText:Q,part:J,attachment:oe,setIsCopied:a,setIsHovering:l,__internal_getRuntime:xe},t[42]=M,t[43]=V,t[44]=G,t[45]=L,t[46]=H,t[47]=F,t[48]=Q,t[49]=J,t[50]=oe,t[51]=xe,t[52]=k,t[53]=_,t[54]=ge):ge=t[54],ge},dB=qt(uB),fB=e=>{const t=ce(6),{runtime:r,id:n,threadIdRef:s}=e;let i;t[0]!==n||t[1]!==r?(i=r.getMessageById(n),t[0]=n,t[1]=r,t[2]=i):i=t[2];const a=i;let o;return t[3]!==a||t[4]!==s?(o=dB({runtime:a,threadIdRef:s}),t[3]=a,t[4]=s,t[5]=o):o=t[5],sn(o)},hB=qt(fB),pB=e=>{const t=ce(58),{runtime:r}=e,n=Fi(r),s=Gp();let i,a;t[0]!==s||t[1]!==r?(i=()=>{const k=[];for(const _ of["runStart","runEnd","initialize","modelContextUpdate"]){const M=r.unstable_on(_,()=>{const V=r.getState()?.threadId||"unknown";s(`thread.${_}`,{threadId:V})});k.push(M)}return()=>{for(const _ of k)_()}},a=[r,s],t[0]=s,t[1]=r,t[2]=i,t[3]=a):(i=t[2],a=t[3]),ot(i,a);let o;t[4]!==r?(o=nC(()=>r.getState().threadId),t[4]=r,t[5]=o):o=t[5];const l=o;let c;t[6]!==r.composer||t[7]!==l?(c=rC({runtime:r.composer,threadIdRef:l}),t[6]=r.composer,t[7]=l,t[8]=c):c=t[8];const d=Zo(c);let f;if(t[9]!==r||t[10]!==n.messages||t[11]!==l){let k;t[13]!==r||t[14]!==l?(k=_=>qn(_.id,hB({runtime:r,id:_.id,threadIdRef:l}),[r,_.id,l]),t[13]=r,t[14]=l,t[15]=k):k=t[15],f=n.messages.map(k),t[9]=r,t[10]=n.messages,t[11]=l,t[12]=f}else f=t[12];const h=Pi(f),m=h.state.length===0&&!n.isLoading;let g;t[16]!==d.state||t[17]!==h.state||t[18]!==n.capabilities||t[19]!==n.extras||t[20]!==n.isDisabled||t[21]!==n.isLoading||t[22]!==n.isRunning||t[23]!==n.speech||t[24]!==n.state||t[25]!==n.suggestions||t[26]!==n.voice||t[27]!==m?(g={isEmpty:m,isDisabled:n.isDisabled,isLoading:n.isLoading,isRunning:n.isRunning,capabilities:n.capabilities,state:n.state,suggestions:n.suggestions,extras:n.extras,speech:n.speech,voice:n.voice,composer:d.state,messages:h.state},t[16]=d.state,t[17]=h.state,t[18]=n.capabilities,t[19]=n.extras,t[20]=n.isDisabled,t[21]=n.isLoading,t[22]=n.isRunning,t[23]=n.speech,t[24]=n.state,t[25]=n.suggestions,t[26]=n.voice,t[27]=m,t[28]=g):g=t[28];const v=g;let w;t[29]!==v?(w=()=>v,t[29]=v,t[30]=w):w=t[30];let b;t[31]!==d.methods?(b=()=>d.methods,t[31]=d.methods,t[32]=b):b=t[32];let C;t[33]!==h?(C=k=>"id"in k?h.get({key:k.id}):h.get(k),t[33]=h,t[34]=C):C=t[34];let T;t[35]!==r?(T=()=>r,t[35]=r,t[36]=T):T=t[36];let I;return t[37]!==r.append||t[38]!==r.cancelRun||t[39]!==r.connectVoice||t[40]!==r.deleteMessage||t[41]!==r.disconnectVoice||t[42]!==r.export||t[43]!==r.getModelContext||t[44]!==r.getVoiceVolume||t[45]!==r.import||t[46]!==r.muteVoice||t[47]!==r.reset||t[48]!==r.resumeRun||t[49]!==r.startRun||t[50]!==r.stopSpeaking||t[51]!==r.subscribeVoiceVolume||t[52]!==r.unmuteVoice||t[53]!==C||t[54]!==T||t[55]!==w||t[56]!==b?(I={getState:w,composer:b,append:r.append,deleteMessage:r.deleteMessage,startRun:r.startRun,resumeRun:r.resumeRun,cancelRun:r.cancelRun,getModelContext:r.getModelContext,export:r.export,import:r.import,reset:r.reset,stopSpeaking:r.stopSpeaking,connectVoice:r.connectVoice,disconnectVoice:r.disconnectVoice,getVoiceVolume:r.getVoiceVolume,subscribeVoiceVolume:r.subscribeVoiceVolume,muteVoice:r.muteVoice,unmuteVoice:r.unmuteVoice,message:C,__internal_getRuntime:T},t[37]=r.append,t[38]=r.cancelRun,t[39]=r.connectVoice,t[40]=r.deleteMessage,t[41]=r.disconnectVoice,t[42]=r.export,t[43]=r.getModelContext,t[44]=r.getVoiceVolume,t[45]=r.import,t[46]=r.muteVoice,t[47]=r.reset,t[48]=r.resumeRun,t[49]=r.startRun,t[50]=r.stopSpeaking,t[51]=r.subscribeVoiceVolume,t[52]=r.unmuteVoice,t[53]=C,t[54]=T,t[55]=w,t[56]=b,t[57]=I):I=t[57],I},mB=qt(pB),gB=e=>{const t=ce(20),{runtime:r}=e,n=Fi(r),s=Gp();let i,a;t[0]!==s||t[1]!==r?(i=()=>{const d=[];for(const f of["switchedTo","switchedAway"]){const h=r.unstable_on(f,()=>{s(`threadListItem.${f}`,{threadId:r.getState().id})});d.push(h)}return()=>{for(const f of d)f()}},a=[r,s],t[0]=s,t[1]=r,t[2]=i,t[3]=a):(i=t[2],a=t[3]),ot(i,a);let o;t[4]!==n?(o=()=>n,t[4]=n,t[5]=o):o=t[5];let l;t[6]!==r?(l=()=>r,t[6]=r,t[7]=l):l=t[7];let c;return t[8]!==r.archive||t[9]!==r.delete||t[10]!==r.detach||t[11]!==r.generateTitle||t[12]!==r.initialize||t[13]!==r.rename||t[14]!==r.switchTo||t[15]!==r.unarchive||t[16
33]!==r.updateCustom||t[17]!==o||t[18]!==l?(c={getState:o,switchTo:r.switchTo,rename:r.rename,updateCustom:r.updateCustom,archive:r.archive,unarchive:r.unarchive,delete:r.delete,generateTitle:r.generateTitle,initialize:r.initialize,detach:r.detach,__internal_getRuntime:l},t[8]=r.archive,t[9]=r.delete,t[10]=r.detach,t[11]=r.generateTitle,t[12]=r.initialize,t[13]=r.rename,t[14]=r.switchTo,t[15]=r.unarchive,t[16]=r.updateCustom,t[17]=o,t[18]=l,t[19]=c):c=t[19],c},sC=qt(gB),yB=e=>{const t=ce(5),{runtime:r,id:n}=e;let s;t[0]!==n||t[1]!==r?(s=r.getItemById(n),t[0]=n,t[1]=r,t[2]=s):s=t[2];const i=s;let a;return t[3]!==i?(a=sC({runtime:i}),t[3]=i,t[4]=a):a=t[4],sn(a)},vB=qt(yB),xB=e=>{const t=ce(40),{runtime:r,__internal_assistantRuntime:n}=e,s=Fi(r);let i;t[0]!==r.main?(i=mB({runtime:r.main}),t[0]=r.main,t[1]=i):i=t[1];const a=Zo(i);let o;t[2]!==r||t[3]!==s.threadItems?(o=Object.keys(s.threadItems).map(_=>qn(_,vB({runtime:r,id:_}),[r,_])),t[2]=r,t[3]=s.threadItems,t[4]=o):o=t[4];const l=Pi(o),c=s.newThreadId??null;let d;t[5]!==a.state||t[6]!==s.archivedThreadIds||t[7]!==s.hasMore||t[8]!==s.isLoading||t[9]!==s.isLoadingMore||t[10]!==s.mainThreadId||t[11]!==s.threadIds||t[12]!==c||t[13]!==l.state?(d={mainThreadId:s.mainThreadId,newThreadId:c,isLoading:s.isLoading,isLoadingMore:s.isLoadingMore,hasMore:s.hasMore,threadIds:s.threadIds,archivedThreadIds:s.archivedThreadIds,threadItems:l.state,main:a.state},t[5]=a.state,t[6]=s.archivedThreadIds,t[7]=s.hasMore,t[8]=s.isLoading,t[9]=s.isLoadingMore,t[10]=s.mainThreadId,t[11]=s.threadIds,t[12]=c,t[13]=l.state,t[14]=d):d=t[14];const f=d;let h;t[15]!==f?(h=()=>f,t[15]=f,t[16]=h):h=t[16];let m;t[17]!==a.methods?(m=()=>a.methods,t[17]=a.methods,t[18]=m):m=t[18];let g;t[19]!==f||t[20]!==l?(g=_=>{if(_==="main")return l.get({key:f.mainThreadId});if("id"in _)return l.get({key:_.id});const{index:M,archived:V}=_,G=V!==void 0&&V?f.archivedThreadIds[M]:f.threadIds[M];return l.get({key:G})},t[19]=f,t[20]=l,t[21]=g):g=t[21];let v,w,b,C,T;t[22]!==r?(C=async(_,M)=>{await r.switchToThread(_,M)},T=async()=>{await r.switchToNewThread()},v=()=>r.getLoadThreadsPromise(),w=()=>r.reload(),b=()=>r.loadMore(),t[22]=r,t[23]=v,t[24]=w,t[25]=b,t[26]=C,t[27]=T):(v=t[23],w=t[24],b=t[25],C=t[26],T=t[27]);let I;t[28]!==n?(I=()=>n,t[28]=n,t[29]=I):I=t[29];let k;return t[30]!==v||t[31]!==w||t[32]!==b||t[33]!==I||t[34]!==h||t[35]!==m||t[36]!==g||t[37]!==C||t[38]!==T?(k={getState:h,thread:m,item:g,switchToThread:C,switchToNewThread:T,getLoadThreadsPromise:v,reload:w,loadMore:b,__internal_getAssistantRuntime:I},t[30]=v,t[31]=w,t[32]=b,t[33]=I,t[34]=h,t[35]=m,t[36]=g,t[37]=C,t[38]=T,t[39]=k):k=t[39],k},bB=qt(xB),wB=e=>({getState:()=>e}),CB=qt(wB),SB=e=>{const t=ce(11);let r;t[0]!==e?(r=()=>({suggestions:(e??[]).map(TB)}),t[0]=e,t[1]=r):r=t[1];const[n]=pr(r);let s;t[2]!==n.suggestions?(s=n.suggestions.map(_B),t[2]=n.suggestions,t[3]=s):s=t[3];const i=Pi(s);let a;t[4]!==n?(a=()=>n,t[4]=n,t[5]=a):a=t[5];let o;t[6]!==i?(o=c=>{const{index:d}=c;return i.get({index:d})},t[6]=i,t[7]=o):o=t[7];let l;return t[8]!==a||t[9]!==o?(l={getState:a,suggestion:o},t[8]=a,t[9]=o,t[10]=l):l=t[10],l},EB=qt(SB);function TB(e){return typeof e=="string"?{title:e,label:"",prompt:e}:{title:e.title,label:e.label,prompt:e.prompt}}function _B(e,t){return qn(t,CB(e),[e])}const IB=(e,t)=>{e.thread??(e.thread=Nn({source:"threads",query:{type:"main"},get:r=>r.threads().thread("main")})),e.threadListItem??(e.threadListItem=Nn({source:"threads",query:{type:"main"},get:r=>r.threads().item("main")})),e.composer??(e.composer=Nn({source:"thread",query:{},get:r=>r.threads().thread("main").composer()})),!e.modelContext&&t.modelContext.source===null&&(e.modelContext=Vw()),!e.suggestions&&t.suggestions.source===null&&(e.suggestions=EB())},iC=e=>{const t=ce(6),r=Jw();let n,s;t[0]!==r||t[1]!==e?(n=()=>e.registerModelContextProvider(r.current.modelContext()),s=[e,r],t[0]=r,t[1]=e,t[2]=n,t[3]=s):(n=t[2],s=t[3]),ot(n,s);let i;return t[4]!==e?(i=bB({runtime:e.threads,__internal_assistantRuntime:e}),t[4]=e,t[5]=i):i=t[5],sn(i)},AB=qt(iC);Ww(iC,(e,t)=>{IB(e,t),!e.tools&&t.tools.source===null&&(e.tools=qj({})),!e.dataRenderers&&t.dataRenderers.source===null&&(e.dataRenderers=qP())});const kB=e=>e._core?.RenderComponent,NB=N.memo(({runtime:e,aui:t=null,children:r})=>{"use no memo";const n=vt({threads:AB(e)},{parent:t}),s=kB(e),i=u.jsxs(Pn,{value:n,children:[s&&u.jsx(s,{}),r]});return t?u.jsx(Pn,{value:t,children:i}):i}
33),R0=e=>{let t;const r=new Set,n=(c,d)=>{const f=typeof c=="function"?c(t):c;if(!Object.is(f,t)){const h=t;t=d??(typeof f!="object"||f===null)?f:Object.assign({},t,f),r.forEach(m=>m(t,h))}},s=()=>t,o={setState:n,getState:s,getInitialState:()=>l,subscribe:c=>(r.add(c),()=>r.delete(c))},l=t=e(n,s,o);return o},RB=e=>e?R0(e):R0,PB=e=>e;function jB(e,t=PB){const r=_e.useSyncExternalStore(e.subscribe,_e.useCallback(()=>t(e.getState()),[e,t]),_e.useCallback(()=>t(e.getInitialState()),[e,t]));return _e.useDebugValue(r),r}const P0=e=>{const t=RB(e),r=n=>jB(t,n);return Object.assign(r,t),r},ko=e=>e?P0(e):P0;function Dr(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function No(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(r=>No(r,t+1)):Dr(e)?Object.entries(e).every(([r,n])=>typeof r=="string"&&No(n,t+1)):!1}const BB=100,lh=(e,t,r)=>{if(e===t)return!0;if(r>BB||e==null||t==null)return!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((i,a)=>lh(i,t[a],r+1));if(Array.isArray(t)||!Dr(e)||!Dr(t))return!1;const n=Object.keys(e),s=Object.keys(t);return n.length!==s.length?!1:n.every(i=>Object.hasOwn(t,i)&&lh(e[i],t[i],r+1))},aC=(e,t)=>!No(e)||!No(t)?!1:lh(e,t,0);function DB(e){const t=e.metadata;if(!t||typeof t!="object")return;const r=t.custom;if(!r||typeof r!="object")return;const n=r.interactables;return Array.isArray(n)?n:void 0}function LB(e){return`update_${e.replace(/[^a-zA-Z0-9_-]/g,"_")}`}const j0=e=>{if(!Dr(e))return;const t=e.id;return typeof t=="string"||typeof t=="number"?t:void 0};function MB(e,t,r){let n=Array.isArray(t.set)?[...t.set]:[...e];if(t.clear===!0&&(n=[]),Array.isArray(t.remove)&&t.remove.length>0){const i=new Set(t.remove);n=n.filter(a=>{const o=j0(a);return o!==void 0?!i.has(o):!i.has(a)})}const s=t.update;if(Array.isArray(s)&&s.length>0&&(n=n.map(i=>{const a=j0(i);if(a===void 0||!Dr(i))return i;const o=s.find(l=>Dr(l)&&l.id===a);return o?{...i,...o}:i})),Array.isArray(t.add)&&t.add.length>0){const i=r?t.add.map(a=>{if(!Dr(a)||a.id!==void 0)return a;const o=r();return o===void 0?a:{...a,id:o}}):t.add;n=[...n,...i]}return n}function Od(e,t,r){if(!Dr(e)||!Dr(t))return t;const n=Dr(r?.arrayBaseline)?r.arrayBaseline:e,s={...e};for(const[i,a]of Object.entries(t)){const o=n[i];Array.isArray(o)&&Dr(a)?s[i]=MB(o,a,r?.idFactory&&(r.idKeyedFields===void 0||r.idKeyedFields.has(i))?()=>r.idFactory?.(i):void 0):s[i]=a}return s}function OB(e,t){if(!Dr(e)||!Dr(t))return;for(const s of Object.keys(e))if(!(s in t))return;const r={};for(const[s,i]of Object.entries(t))(!(s in e)||!aC(e[s],i))&&(r[s]=i);const n=Object.keys(r).length;if(!(n===0||n===Object.keys(t).length))return r}const FB=e=>{if(!e||typeof e!="object")return;const t=e;return t.type==="tool-call"?t:void 0},UB=(e,t)=>{if(!e.args||typeof e.args!="object")return!1;const r=Dr(e.result)?e.result:void 0;if(r?.success===!1)return!1;if(typeof r?.id=="string")return r.id===t;const n=e.args.id;return n===t||n===void 0},VB=e=>{const t=Dr(e)?e.addedItemIds:void 0;if(!Dr(t))return;const r=new Map;for(const[n,s]of Object.entries(t)){if(!Array.isArray(s))continue;const i=s.filter(a=>typeof a=="string");i.length>0&&r.set(n,i)}if(r.size!==0)return n=>r.get(n)?.shift()},B0=new WeakMap;function $B(e,t,r){let n=B0.get(e);n||(n=new Map,B0.set(e,n));let s=n.get(r);s||(s=new Map,n.set(r,s));const i=s.get(t);if(i)return i;const a=LB(r),o=[],l=()=>o[o.length-1];for(const c of e){if(c.role==="user"){const d=DB(c)?.find(f=>f.id===t);if(!d)continue;if(d.partial){const f=l();f&&o.push({state:Od(f.state,d.state),origin:"user-edit"})}else o.push({state:d.state,origin:"user-edit"});continue}if(c.role==="assistant")for(const d of c.content??[]){const f=FB(d);if(f){if(f.toolCallId===t&&f.toolName===r)f.args&&typeof f.args=="object"&&o.push({state:f.args,origin:"create",toolCallId:t});else if(f.toolName===a&&UB(f,t)){const h=l();if(h){const{id:m,...g}=f.args,v=VB(f.result);o.push({state:v?Od(h.state,g,{idFactory:v}):Od(h.state,g),origin:"update",toolCallId:f.toolCallId})}}}}}return s.set(t,o),o}function zB(e,t,r){const n=$B(e,t,r),s=n[n.length-1];return s?{state:s.state}:void 0}function oC(e,t){if(!e)return;const{interactables:r,...n}=e,s={...n};if(Array.isArray(r)){const i=[];for(const a of r){const o=zB(t,a.id,a.name);if(!o){i.push({id:a.id,name:a.name,state:a.state});continue}if(aC(a.state,o.state))continue;const l=OB(o.state,a.state);i.push(l?{id:a.id,name:a.name,state:l,partial:!0}:{id:a.id,name:a.name,state:a.state})}i.length&&(s.interactables=i)}return Object.keys(s).length?s:void 0}const ch={toResponse(e,t){return new Response(ch.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return ch.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},lC=()=>{let e,t;const r=new Promise((n,s)=>{e=n,t=s});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},KB=()=>{const e=[];let t=!1,r,n;const s=i=>{i.promise||(i.promise=i.reader.read().then(({done:a,value:o})=>{i.promise=void 0,a?(e.splice(e.indexOf(i),1),t&&e.length===0&&r.close()):r.enqueue(o),n?.resolve(),n=void 0}).catch(a=>{console.error(a),e.forEach(o=>{o.reader.cancel()}),e.length=0,r.error(a),n?.reject(a),n=void 0}))};return{readable:new ReadableStream({start(i){r=i}
33,pull(){return n=lC(),e.forEach(i=>{s(i)}),n.promise},cancel(){e.forEach(i=>{i.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(i){if(t)throw new Error("Cannot add streams after the run callback has settled.");const a={reader:i.getReader()};e.push(a),s(a)},enqueue(i){this.addStream(new ReadableStream({start(a){a.enqueue(i),a.close()}}))}}};var D0=class{constructor(e){q(this,"_controller");q(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}};const cC=e=>new ReadableStream({start(t){return e.start?.(new D0(t))},pull(t){return e.pull?.(new D0(t))},cancel(t){return e.cancel?.(t)}}),L0=()=>{let e;return[cC({start(t){e=t}}),e]};var M0=class{constructor(e){q(this,"_controller");q(this,"_isClosed",!1);q(this,"_mergeTask");q(this,"_argsTextController");this._controller=e;const t=cC({start:n=>{this._argsTextController=n}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":r=!0,this._controller.enqueue(n);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${n.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1,...e.modelContent!==void 0?{modelContent:e.modelContent}:{},...e.messages!==void 0?{messages:e.messages}:{}})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}};const qB=e=>new ReadableStream({start(t){return e.start?.(new M0(t))},pull(t){return e.pull?.(new M0(t))},cancel(t){return e.cancel?.(t)}}),HB=()=>{let e;return[qB({start(t){e=t}}),e]};var uC=class{constructor(){q(this,"value",-1)}up(){return++this.value}},GB=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue({...t,path:[e,...t.path]})}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[n,...s]}=t;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);r.enqueue({...t,path:s})}})}});var WB=class extends TransformStream{constructor(e){const t=new uC,r=new Map;super({transform(n,s){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[i,...a]=n.path;if(i===void 0){s.enqueue(n);return}const o=r.get(i);if(o===void 0)throw new Error("Path not found");s.enqueue({...n,path:[o,...a]})}})}},YB=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}};let dC=(e,t=21)=>(r=t)=>{let n="",s=r|0;for(;s-- >0;)n+=e[Math.random()*e.length|0];return n};const fC=dC("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);var QB=class hC{constructor(t){q(this,"_state");q(this,"_parentId");this._state=t||{merger:KB(),contentCounter:new uC}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new GB(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new WB(this._state.contentCounter)))}appendText(t){(this._state.append?.kind!=="text"||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:"text",parentId:this._parentId,controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){(this._state.append?.kind!=="reasoning"||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:"reasoning",parentId:this._parentId,controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=L0();return this._addPart(this._withParentIdOption({type:"text"}),t),r}addReasoningPart(){const[t,r]=L0();return this._addPart(this._withParentIdOption({type:"reasoning"}),t),r}addToolCallPart(t){const r=typeof t=="string"?{toolName:t}:t,n=r.toolName,s=r.toolCallId??fC(),[i,a]=HB();return this._addPart({type:"tool-call",toolName:n,toolCallId:s,...this._parentId&&{parentId:this._parentId}},i),r.argsText!==void 0&&(a.argsText.append(r.argsText),a.argsText.close()),r.args!==void 0&&(a.argsText.append(JSON.stringify(r.args)),a.argsText.close()),r.response!==void 0&&a.setResponse(r.response),a}_finishedPartStream(){return new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}})}_withParentIdOption(t){return this._parentId?{...t,parentId:this._parentId}:t}appendSource(t){this._addPart(this._withParentIdOption(t),this._finishedPartStream())}appendFile(t){this._addPart(this._withParentIdOption(t),this._finishedPartStream())}appendData(t){this._addPart(this._withParentIdOption(t),this._finishedPartStream())}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new hC(this._state);return r._parentId=t,r}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function XB(e){const t=new QB;return(async()=>{try{await e(t)}catch(n){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(n)}),n}finally{t.__internal_isClosed||t.close()}})(),t.__internal_getReadable()}function JB(){const{resolve:e,promise:t}=lC();let r;return[XB(n=>(r=n,r.__internal_subscribeToClose(e),t)),r]}var ZB=class extends TransformStream{constructor(e,t,r){const[n,s]=JB();let i;super({start(a){return i=n.pipeTo(new WritableStream({write(o){a.enqueue(o)},abort(o){a.error(o)},close(){a.terminate()}})).catch(o=>{a.error(o)}),e.start?.(s)},transform(a){return e.transform?.(a,s)},async flush(){await e.flush?.(s),s.close(),await i}},t,r)}};function eD(e){const t=["ROOT"];let r=-1,n=null;const s=[];let i;function a(){i!==void 0&&(s.push(JSON.parse(`"${i}"`)),i=void 0)}function o(f,h,m){switch(f){case'"':r=h,t.pop(),t.push(m),t.push("INSIDE_STRING"),a();break;case"f":case"t":case"n":r=h,n=h,t.pop(),t.push(m),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(m),t.push("INSIDE_NUMBER"),a();break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":r=h,t.pop(),t.push(m),t.push("INSIDE_NUMBER"),a();break;case"{":r=h,t.pop(),t.push(m),t.push("INSIDE_OBJECT_START"),a();break;case"[":r=h,t.pop(),t.push(m),t.push("INSIDE_ARRAY_START"),a();break}}function l(f,h){switch(f){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":r=h,t.pop(),i=s.pop();break}}function c(f,h){switch(f){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break;case"]":r=h,t.pop(),i=s.pop();break}}for(let f=0;f<e.length;f++){const h=e[f];switch(t[t.length-1]){case"ROOT":o(h,f,"FINISH");break;case"INSIDE_OBJECT_START":switch(h){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break;case"}":r=f,t.pop(),i=s.pop();break}break;case"INSIDE_OBJECT_AFTER_COMMA":switch(h){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}break;case"INSIDE_OBJECT_KEY":switch(h){case'"':t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"\\":t.push("INSIDE_STRING_ESCAPE"),i+=h;break;default:i+=h;break}break;case"INSIDE_OBJECT_AFTER_KEY":switch(h){case":":t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}break;case"INSIDE_OBJECT_BEFORE_VALUE":o(h,f,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":l(h,f);break;
33case"INSIDE_STRING":switch(h){case'"':t.pop(),r=f,i=s.pop();break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:r=f}break;case"INSIDE_ARRAY_START":switch(h){case"]":r=f,t.pop(),i=s.pop();break;default:r=f,i="0",o(h,f,"INSIDE_ARRAY_AFTER_VALUE");break}break;case"INSIDE_ARRAY_AFTER_VALUE":switch(h){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break;case"]":r=f,t.pop(),i=s.pop();break;default:r=f;break}break;case"INSIDE_ARRAY_AFTER_COMMA":o(h,f,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),t[t.length-1]==="INSIDE_STRING"?r=f:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(i+=h);break;case"INSIDE_NUMBER":switch(h){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":r=f;break;case"e":case"E":case"-":case".":break;case",":t.pop(),i=s.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&c(h,f),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,f);break;case"}":t.pop(),i=s.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,f);break;case"]":t.pop(),i=s.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&c(h,f);break;default:t.pop(),i=s.pop();break}break;case"INSIDE_LITERAL":{const m=e.substring(n,f+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(h,f):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&c(h,f)):r=f;break}}}let d=e.slice(0,r+1);for(let f=t.length-1;f>=0;f--)switch(t[f]){case"INSIDE_STRING":d+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":d+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":d+="]";break;case"INSIDE_LITERAL":{const h=e.substring(n,e.length);"true".startsWith(h)?d+="true".slice(h.length):"false".startsWith(h)?d+="false".slice(h.length):"null".startsWith(h)&&(d+="null".slice(h.length))}}return[d,s]}var Pa={exports:{}};const tD=typeof Buffer<"u",O0=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,F0=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function pC(e,t,r){r==null&&t!==null&&typeof t=="object"&&(r=t,t=void 0),tD&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));const n=JSON.parse(e,t);if(n===null||typeof n!="object")return n;const s=r&&r.protoAction||"error",i=r&&r.constructorAction||"error";if(s==="ignore"&&i==="ignore")return n;if(s!=="ignore"&&i!=="ignore"){if(O0.test(e)===!1&&F0.test(e)===!1)return n}else if(s!=="ignore"&&i==="ignore"){if(O0.test(e)===!1)return n}else if(F0.test(e)===!1)return n;return mC(n,{protoAction:s,constructorAction:i,safe:r&&r.safe})}function mC(e,{protoAction:t="error",constructorAction:r="error",safe:n}={}){let s=[e];for(;s.length;){const i=s;s=[];for(const a of i){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"__proto__")){if(n===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.__proto__}if(r!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"constructor")&&a.constructor!==null&&typeof a.constructor=="object"&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype")){if(n===!0)return null;if(r==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.constructor}for(const o in a){const l=a[o];l&&typeof l=="object"&&s.push(l)}}}return e}function Wp(e,t,r){const{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return pC(e,t,r)}finally{Error.stackTraceLimit=n}}function rD(e,t){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return pC(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=r}}Pa.exports=Wp;Pa.exports.default=Wp;Pa.exports.parse=Wp;Pa.exports.safeParse=rD;Pa.exports.scan=mC;var nD=Pa.exports;const U0=Qc(nD),Fd=Symbol("aui.parse-partial-json-object.meta"),gC=e=>{if(e.length===0)return{[Fd]:{state:"partial",partialPath:[]}};try{const t=U0.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Fd]={state:"complete",partialPath:[]},t}catch{try{const[t,r]=eD(e),n=U0.parse(t);if(typeof n!="object"||n===null)throw new Error("argsText is expected to be an object");return n[Fd]={state:"partial",partialPath:r},n}catch{return}}};var sD=class ia{constructor(t=null){q(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>ia.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return ia.updatePath(t,r.path,()=>r.value);case"append-text":return ia.updatePath(t,r.path,s=>
33{if(typeof s!="string")throw new Error(`Expected string at path [${r.path.join(", ")}]`);return s+r.value});default:throw new Error(`Invalid operation type: ${n}`)}}static updatePath(t,r,n){if(r.length===0)return n(t);if(t??(t={}),typeof t!="object")throw new Error(`Invalid path: [${r.join(", ")}]`);const[s,...i]=r;if(Array.isArray(t)){const o=Number(s);if(Number.isNaN(o))throw new Error(`Expected array index at [${r.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=ia.updatePath(l[o],i,n),l}const a={...t};return a[s]=ia.updatePath(a[s],i,n),a}},iD=class{constructor(){q(this,"_streamStartTime");q(this,"_firstTokenTime");q(this,"_totalChunks",0);q(this,"_toolCallIds",new Set);this._streamStartTime=Date.now()}recordChunk(){this._totalChunks++}recordFirstToken(){this._firstTokenTime===void 0&&(this._firstTokenTime=Date.now())}recordToolCallStart(e){this._toolCallIds.add(e)}getTiming(e,t){const r=Date.now()-this._streamStartTime,n=e&&e>0?e:t?Math.ceil(t.length/4):void 0,s=n&&r>0?n/r*1e3:void 0;return{streamStartTime:this._streamStartTime,...this._firstTokenTime!==void 0?{firstTokenTime:this._firstTokenTime-this._streamStartTime}:void 0,totalStreamTime:r,...n!==void 0?{tokenCount:n}:void 0,...s!==void 0?{tokensPerSecond:s}:void 0,totalChunks:this._totalChunks,toolCallCount:this._toolCallIds.size}}};const aD=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),ku=(e,t,r)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const n=t.path[0],s=r(e.parts[n]);return{...e,parts:[...e.parts.slice(0,n),s,...e.parts.slice(n+1)],get content(){return this.parts}}},oD=(e,t)=>{const r=t.part;if(r.type==="text"||r.type==="reasoning"){const n={type:r.type,text:"",status:{type:"running"},...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,n],get content(){return this.parts}}}else if(r.type==="tool-call"){const n={type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{},timing:{startedAt:Date.now()},...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,n],get content(){return this.parts}}}else if(r.type==="source"){const n={type:"source",sourceType:r.sourceType,id:r.id,url:r.url,...r.title?{title:r.title}:void 0,...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,n],get content(){return this.parts}}}else if(r.type==="file"){const n={type:"file",mimeType:r.mimeType,data:r.data,...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,n],get content(){return this.parts}}}else if(r.type==="data"){const n={type:"data",name:r.name,data:r.data,...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,n],get content(){return this.parts}}}else throw new Error(`Unsupported part type: ${r.type}`)},lD=(e,t)=>ku(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:{...r,state:"call"}}),cD=(e,t)=>ku(e,t,r=>({...r,status:{type:"complete",reason:"unknown"}})),uD=(e,t)=>ku(e,t,r=>{if(r.type==="text"||r.type==="reasoning")return{...r,text:r.text+t.textDelta};if(r.type==="tool-call"){const n=r.argsText+t.textDelta,s=gC(n)??r.args;return{...r,argsText:n,args:s}}else throw new Error("text-delta received but part is neither text nor tool-call")}),dD=(e,t)=>ku(e,t,r=>{if(r.type==="tool-call")return{...r,state:"result",...r.timing!==void 0?{timing:{...r.timing,completedAt:r.timing.completedAt??Date.now()}}:{},...t.artifact!==void 0?{artifact:t.artifact}:{},result:t.result,isError:t.isError??!1,...t.modelContent!==void 0?{modelContent:t.modelContent}:{},...t.messages!==void 0?{messages:t.messages}:{},status:{type:"complete",reason:"stop"}};throw new Error("Result chunk received but part is not a tool-call")}),V0=(e,t)=>{if(e.status?.type==="incomplete"&&e.status?.reason==="error")return e;const r=fD(t);return{...e,status:r}},fD=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}
33:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},hD=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),pD=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),mD=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]}}),gD=(e,t)=>{const r=e.metadata.steps.slice(),n=r.length-1;return r.length>0&&r[n]?.state==="started"?r[n]={...r[n],state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}:r.push({state:"finished",messageId:fC(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:r}}},yD=(e,t)=>({...e,status:{type:"incomplete",reason:"error",error:t.error}}),vD=(e,t)=>{const r=new sD(e.metadata.unstable_state);return r.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:r.state}}},$0=(e,t)=>{let r=0;for(const s of t.metadata.steps)s.state==="finished"&&s.usage&&(r+=s.usage.outputTokens);let n="";
33for(const s of t.parts)(s.type==="text"||s.type==="reasoning")&&(n+=s.text);return e.getTiming(r>0?r:void 0,n||void 0)},xD=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}};var bD=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e??aD();const s=new iD;let i;const a=t?xD(()=>{i?.enqueue(n)}):()=>{i?.enqueue(n)};super({start(o){i=o},transform(o){s.recordChunk();const l=o.type;switch(l){case"part-start":n=oD(n,o),o.part.type==="tool-call"&&s.recordToolCallStart(o.part.toolCallId);break;case"tool-call-args-text-finish":n=lD(n,o);break;case"part-finish":n=cD(n,o);break;case"text-delta":n=uD(n,o),s.recordFirstToken();break;case"result":n=dD(n,o);break;case"message-finish":n=V0(n,o);break;case"annotations":n=hD(n,o);break;case"data":n=pD(n,o);break;case"step-start":n=mD(n,o);break;case"step-finish":n=gD(n,o);break;case"error":n=yD(n,o),r?.(o.error);break;case"update-state":n=vD(n,o);break;default:throw new Error(`Unsupported chunk type: ${l}`)}n.status.type!=="running"&&(n={...n,metadata:{...n.metadata,timing:$0(s,n)}}),a()},flush(o){if(n.status?.type==="running"){const l=n.parts?.some(c=>c.type==="tool-call"&&(c.state==="call"||c.state==="partial-call")&&c.result===void 0)??!1;n=V0(n,{type:"message-finish",path:[],finishReason:l?"tool-calls":"unknown",usage:{inputTokens:0,outputTokens:0}}),n={...n,metadata:{...n.metadata,timing:$0(s,n)}},o.enqueue(n)}}})}},wD=class extends YB{constructor(){super(e=>{const t=new ZB({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},CD=class uc{constructor(t){q(this,"readable");this.readable=t,this.readable=t}static fromAssistantStream(t){return new uc(t.pipeThrough(new bD))}async unstable_result(){let t;for await(const r of this)t=r;return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){const t=this.readable.getReader();return{async next(){const{done:r,value:n}=await t.read();return r?{done:!0,value:void 0}:{done:!1,value:n}}}}tee(){const[t,r]=this.readable.tee();return[new uc(t),new uc(r)]}};const z0=Symbol.for("aui.tool-response");var SD=class uh{constructor(t){q(this,"artifact");q(this,"result");q(this,"isError");q(this,"modelContent");q(this,"messages");t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=t.isError??!1,t.modelContent!==void 0&&(this.modelContent=t.modelContent),t.messages!==void 0&&(this.messages=t.messages)}get[z0](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&z0 in t}static toResponse(t){return t instanceof uh?t:new uh({result:t===void 0?"<no result>":t})}};const us=dC("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),yC=e=>{const t=ce(7),{index:r,children:n}=e;let s;t[0]!==r?(s=Nn({source:"message",query:{type:"index",index:r},get:l=>l.message().attachment({index:r})}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==s?(i={attachment:s},t[2]=s,t[3]=i):i=t[3];const a=vt(i);let o;return t[4]!==a||t[5]!==n?(o=u.jsx(Pn,{value:a,children:n}),t[4]=a,t[5]=n,t[6]=o):o=t[6],o},vC=e=>{const t=ce(7),{index:r,children:n}=e;let s;t[0]!==r?(s=Nn({source:"composer",query:{type:"index",index:r},get:l=>l.composer().attachment({index:r})}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==s?(i={attachment:s},t[2]=s,t[3]=i):i=t[3];const a=vt(i);let o;return t[4]!==a||t[5]!==n?(o=u.jsx(Pn,{value:a,children:n}),t[4]=a,t[5]=n,t[6]=o):o=t[6],o},ED=e=>{const t=ce(7),{runtime:r,children:n}=e;let s;t[0]!==r?(s=sC({runtime:r}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==s?(i={threadListItem:s},t[2]=s,t[3]=i):i=t[3];const a=vt(i);let o;return t[4]!==a||t[5]!==n?(o=u.jsx(Pn,{value:a,children:n}),t[4]=a,t[5]=n,t[6]=o):o=t[6],o},xC=e=>{const t=ce(10),{index:r,children:n}=e;let s;t[0]!==r?(s=Nn({source:"thread",query:{type:"index",index:r},get:c=>c.thread().message({index:r})}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==r?(i=Nn({source:"message",query:{},get:c=>c.thread().message({index:r}).composer()}),t[2]=r,t[3]=i):i=t[3];let a;t[4]!==s||t[5]!==i?(a={message:s,composer:i},t[4]=s,t[5]=i,t[6]=a):a=t[6];const o=vt(a);let l;return t[7]!==o||t[8]!==n?(l=u.jsx(Pn,{value:o,children:n}),t[7]=o,t[8]=n,t[9]=l):l=t[9],l},Yp=e=>{const t=ce(7),{index:r,children:n}=e;let s;t[0]!==r?(s=Nn({source:"message",query:{type:"index",index:r},get:l=>l.message().part({index:r})}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==s?(i={part:s},t[2]=s,t[3]=i):i=t[3];const a=vt(i);let o;return t[4]!==a||t[5]!==n?(o=u.jsx(Pn,{value:a,children:n}),t[4]=a,t[5]=n,t[6]=o):o=t[6],o},TD=e=>{const t=ce(7),{text:r,isRunning:n}=e;let s;t[0]!==n?(s=n?{type:"running"}:{type:"complete"},t[0]=n,t[1]=s):s=t[1];let i;t[2]!==s||t[3]!==r?(i={type:"text",text:r,status:s},t[2]=s,t[3]=r,t[4]=i):i=t[4];const a=i;let o;return t[5]!==a?(o={getState:()=>a,addToolResult:ID,resumeToolCall:AD,respondToToolApproval:kD},t[5]=a,t[6]=o):o=t[6],o},_D=qt(TD),Qp=e=>{const t=ce(8),{text:r,isRunning:n,children:s}=e,i=n===void 0?!1:n;let a;t[0]!==i||t[1]!==r?(a=_D({text:r,isRunning:i}),t[0]=i,t[1]=r,t[2]=a):a=t[2];let o;t[3]!==a?(o={part:a},t[3]=a,t[4]=o):o=t[4];const l=vt(o);let c;return t[5]!==l||t[6]!==s?(c=u.jsx(Pn,{value:l,children:s}),t[5]=l,t[6]=s,t[7]=c):c=t[7],c};function ID(){throw new Error("Not supported")}function AD(){throw new Error("Not supported")}function kD(){throw new Error("Not supported")}const ND=Object.freeze({type:"complete"}),RD=e=>
33{const t=ce(9),{parts:r,getMessagePart:n}=e,[s,i]=pr(!0),a=r[r.length-1]?.status??ND;let o;t[0]!==s||t[1]!==r||t[2]!==a?(o={parts:r,collapsed:s,status:a},t[0]=s,t[1]=r,t[2]=a,t[3]=o):o=t[3];const l=o;let c;t[4]!==l?(c=()=>l,t[4]=l,t[5]=c):c=t[5];let d;return t[6]!==n||t[7]!==c?(d={getState:c,setCollapsed:i,part:n},t[6]=n,t[7]=c,t[8]=d):d=t[8],d},PD=qt(RD),jD=e=>{const t=ce(5),{startIndex:r,endIndex:n,children:s}=e,i=Fe(BD).slice(r,n+1),a=vt(),o=PD({parts:i,getMessagePart:f=>{const{index:h}=f;if(h<0||h>=i.length)throw new Error(`ChainOfThought part index ${h} is out of bounds (0..${i.length-1})`);return a.message().part({index:r+h})}});let l;t[0]!==o?(l={chainOfThought:o},t[0]=o,t[1]=l):l=t[1];const c=vt(l);let d;return t[2]!==c||t[3]!==s?(d=u.jsx(Pn,{value:c,children:s}),t[2]=c,t[3]=s,t[4]=d):d=t[4],d};function BD(e){return e.message.parts}const bC=e=>{const t=ce(7),{index:r,children:n}=e;let s;t[0]!==r?(s=Nn({source:"suggestions",query:{index:r},get:l=>l.suggestions().suggestion({index:r})}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==s?(i={suggestion:s},t[2]=s,t[3]=i):i=t[3];const a=vt(i);let o;return t[4]!==a||t[5]!==n?(o=u.jsx(Pn,{value:a,children:n}),t[4]=a,t[5]=n,t[6]=o):o=t[6],o},DD=e=>{const t=ce(7),{index:r,children:n}=e;let s;t[0]!==r?(s=Nn({source:"composer",query:{index:r},get:l=>l.composer().queueItem({index:r})}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==s?(i={queueItem:s},t[2]=s,t[3]=i):i=t[3];const a=vt(i);let o;return t[4]!==a||t[5]!==n?(o=u.jsx(Pn,{value:a,children:n}),t[4]=a,t[5]=n,t[6]=o):o=t[6],o},Mc=Symbol("innerMessage"),Hn=Symbol("skip-update");function LD(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const r of Object.keys(e)){const n=e[r],s=t[r];if(!Object.is(n,s))return!1}return!0}var el=class{constructor(){q(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(r){e.push(r)}if(e.length>0){if(e.length===1)throw e[0];for(const t of e)console.error(t);throw new AggregateError(e)}}},Nu=class{constructor(){q(this,"_subscriptions",new Set);q(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(e){for(const t of this._subscriptions)t(e)}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else this._connection?.(),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},$n=class extends Nu{constructor(t){super();q(this,"binding");q(this,"_previousState");q(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===Hn)throw new Error("Entry not available in the store");this._previousState=r}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===Hn||LD(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Xp=class extends Nu{constructor(t){super();q(this,"binding");q(this,"_previousStateDirty",!0);q(this,"_previousState");q(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Hn&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},Oc=class extends Nu{constructor(t){super();q(this,"binding");this.binding=t}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let r=this.binding.getState(),n=r?.subscribe(t);const s=()=>{const a=this.binding.getState();a!==r&&(r=a,n?.(),n=a?.subscribe(t),t())},i=this.outerSubscribe(s);return()=>{i?.(),n?.()}}},wC=class extends Nu{constructor(t){super();q(this,"config");this.config=t}getState(){return this.config.binding.getState()}outerSubscribe(t){return this.config.binding.subscribe(t)}_connect(){const t=a=>{this.notifySubscribers(a)};let r=this.config.binding.getState(),n=r?.unstable_on(this.config.event,t);const s=()=>{const a=this.config.binding.getState();a!==r&&(r=a,n?.(),n=a?.unstable_on(this.config.event,t))},i=this.outerSubscribe(s);return()=>{i?.(),n?.()}}},CC=class{constructor(e){q(this,"_core");this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}
33__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},SC=class extends CC{constructor(t,r){super(t);q(this,"_composerApi");this._composerApi=r}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},MD=class extends SC{get source(){return"thread-composer"}},OD=class extends SC{get source(){return"edit-composer"}},FD=class extends CC{get source(){return"message"}remove(){throw new Error("Message attachments cannot be removed")}};const Fc=Object.freeze([]),EC=Object.freeze({}),UD=e=>Object.freeze({type:"thread",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??Fc,text:e?.text??"",role:e?.role??"user",runConfig:e?.runConfig??EC,attachmentAccept:e?.attachmentAccept??"",dictation:e?.dictation,quote:e?.quote,queue:e?.queue??Fc,value:e?.text??""}),VD=e=>Object.freeze({type:"edit",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??"",role:e?.role??"user",attachments:e?.attachments??Fc,runConfig:e?.runConfig??EC,attachmentAccept:e?.attachmentAccept??"",dictation:e?.dictation,quote:e?.quote,queue:e?.queue??Fc,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??""});var TC=class{constructor(e){q(this,"_core");q(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.steerQueueItem=this.steerQueueItem.bind(this),this.removeQueueItem=this.removeQueueItem.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.send(e)}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}steerQueueItem(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.steerQueueItem(e)}removeQueueItem(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.removeQueueItem(e)}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}startDictation(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.startDictation()}stopDictation(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.stopDictation()}setQuote(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new wC({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},$D=class extends TC{constructor(t){const r=new Xp({path:t.path,getState:()=>UD(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});q(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new MD(new $n({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}.attachments[${t}]`}
33,getState:()=>{const r=this.getState().attachments[t];return r?{...r,source:"thread-composer"}:Hn},subscribe:r=>this._core.subscribe(r)}),this._core)}},zD=class extends TC{constructor(t,r){const n=new Xp({path:t.path,getState:()=>VD(t.getState()),subscribe:s=>t.subscribe(s)});super({path:t.path,getState:()=>t.getState(),subscribe:s=>n.subscribe(s)});q(this,"_beginEdit");q(this,"_getState");this._beginEdit=r,this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new OD(new $n({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}.attachments[${t}]`},getState:()=>{const r=this.getState().attachments[t];return r?{...r,source:"edit-composer"}:Hn},subscribe:r=>this._core.subscribe(r)}),this._core)}};const Ro=e=>e.content.filter(t=>t.type==="text").map(t=>t.text).join(`
34
35`),K0={"allow-once":!0,"allow-always":!0,"reject-once":!1,"reject-always":!1},KD=(e,t)=>{let r,n;if("optionId"in t){const s=e.options?.find(i=>i.id===t.optionId);if(!s)throw new Error(`Tool approval has no option with id "${t.optionId}"`);if("approved"in t)r=t.approved;else{if(!Object.hasOwn(K0,s.kind))throw new Error(`Tool approval option "${s.id}" has a custom kind "${s.kind}"; respond with an explicit approved value instead`);r=K0[s.kind]}n=s.id}else r=t.approved;return{approvalId:e.id,approved:r,...n!==void 0&&{optionId:n},...t.reason!=null&&{reason:t.reason}}};var q0=class{constructor(e,t,r){q(this,"contentBinding");q(this,"messageApi");q(this,"threadApi");this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.respondToToolApproval=this.respondToToolApproval.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const n=t.toolName,s=t.toolCallId,i=SD.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:s,result:i.result,artifact:i.artifact,isError:i.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}respondToToolApproval(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to respond to tool approval on non-tool message part");if(!t.approval||t.approval.approved!==void 0||t.approval.resolution!==void 0)throw new Error("Tool call has no pending approval");if(!this.threadApi)throw new Error("Thread API is not available");this.threadApi.getState().respondToToolApproval(KD(t.approval,e))}subscribe(e){return this.contentBinding.subscribe(e)}};const Ul=Object.freeze({type:"complete"}),qD=(e,t,r)=>{if(e.role!=="assistant")return Ul;if(r.type==="tool-call")return r.result?Ul:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Ul:n?e.status:Ul},H0=(e,t)=>{const r=e.content[t];if(!r)return Hn;const n=qD(e,t,r);return Object.freeze({...r,[Mc]:r[Mc],status:n})};var HD=class{constructor(e,t){q(this,"_core");q(this,"_threadBinding");q(this,"composer");q(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new zD(new Oc({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.delete=this.delete.bind(this),this.get
35State=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}delete(){const e=this._core.getState();return this._threadBinding.getState().deleteMessage(e.id)}reload(e={}){const t=this._getEditComposerRuntimeCore(),r=t??this._threadBinding.getState().composer,n=t??r,{runConfig:s=n.runConfig}=e,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:s})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){const e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const r=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");
35if(!t&&!e)throw new Error("Must specify either branchId or position");const n=this._threadBinding.getState().getBranches(r.id);let s=t;if(e==="previous"?s=n[r.branchNumber-2]:e==="next"&&(s=n[r.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return Ro(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new q0(new $n({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}},getState:()=>H0(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new q0(new $n({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}},getState:()=>{const t=this._core.getState(),r=t.content.findIndex(n=>n.type==="tool-call"&&n.toolCallId===e);return r===-1?Hn:H0(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new FD(new $n({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}},getState:()=>{const t=this.getState().attachments?.[e];return t?{...t,source:"message"}:Hn},subscribe:t=>this._core.subscribe(t)}))}};const GD=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),WD=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),YD=(e,t)=>typeof t=="string"?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId??e.at(-1)?.id??null,sourceId:t.sourceId??null,role:t.role??"user",content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},QD=(e,t)=>{const r=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:e.isRunning??(r?.role!=="assistant"?!1:r.status.type==="running"),messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice})};var XD=class{constructor(e,t){q(this,"_threadBinding");q(this,"composer");q(this,"_eventSubscriptionSubjects",new Map);const r=new $n({path:e.path,getState:()=>QD(e.getState(),t.getState()),subscribe:n=>{const s=e.subscribe(n),i=t.subscribe(n);return()=>{s(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new $D(new Oc({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:n=>this._threadBinding.subscribe(n)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.deleteMessage=this.deleteMessage.bind(this),this.resumeRun=this.resumeRun.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.get
35State=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(YD(this._threadBinding.getState().messages,e))}deleteMessage(e){return this._threadBinding.getState().deleteMessage(e)}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(WD(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(GD(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}},()=>{const t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new HD(new $n({path:e,getState:()=>{const{message:r,parentId:n,index:s}=t()??{},{messages:i,speech:a}=this._threadBinding.getState();if(!r||n===void 0||s===void 0)return Hn;const o=this._threadBinding.getState().getBranches(r.id);return{...r,[Mc]:r[Mc],index:s,isLast:i.at(-1)?.id===r.id,parentId:n,branchNumber:o.indexOf(r.id)+1,branchCount:o.length,speech:a?.messageId===r.id?a:void 0}},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new wC({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}};const dh=Ln(null),_C=e=>{const t=ce(6),{adapters:r,children:n}=e,s=Mn(dh);let i;t[0]!==r||t[1]!==s?(i={...s,...r},t[0]=r,t[1]=s,t[2]=i):i=t[2];const a=i;let o;return t[3]!==n||t[4]!==a?(o=u.jsx(dh.Provider,{value:a,children:n}),t[3]=n,t[4]=a,t[5]=o):o=t[5],o},JD=()=>Mn(dh);var Vl=class{constructor(e,t){q(this,"_core");q(this,"_threadListBinding");this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.updateCustom=this.updateCustom.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(e){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id,e)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}updateCustom(e){const t=this._core.getState();if(!this._threadListBinding.updateCustom)throw new Error("Thread list runtime does not support updating custom metadata");return this._threadListBinding.updateCustom(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,n=this._core.getState().id;return this.subscribe(()=>{const s=this._core.getState(),i=s.isMain,a=s.id;r===i&&n===a||(r=i,n=a,!(e==="switchedTo"&&!i)&&(e==="switchedAway"&&i||t({})))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};const G0=Promise.resolve(),ZD=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),$l=(e,t)=>
35{if(t===void 0)return Hn;const r=e.getItemById(t);return r?{id:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,lastMessageAt:r.lastMessageAt,custom:r.custom,isMain:r.id===e.mainThreadId}:Hn};var IC=class{constructor(e,t=XD){q(this,"_core");q(this,"_runtimeFactory");q(this,"_getState");q(this,"_mainThreadListItemRuntime");q(this,"main");this._core=e,this._runtimeFactory=t;const r=new Xp({path:{},getState:()=>ZD(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new Vl(new $n({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>$l(this._core,this._core.mainThreadId),subscribe:n=>this._core.subscribe(n)}),this._core),this.main=new t(new Oc({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:n=>e.subscribe(n)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.reload=this.reload.bind(this),this.loadMore=this.loadMore.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e,t){return this._core.switchToThread(e,t)}switchToNewThread(){return this._core.switchToNewThread()}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??G0}loadMore(){return this._core.loadMore?.()??G0}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new Oc({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new Vl(new $n({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>$l(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Vl(new $n({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>$l(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Vl(new $n({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>$l(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},AC=class{constructor(e){q(this,"_core");q(this,"threads");q(this,"_thread");this._core=e,this.threads=new IC(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},kC=class{constructor(){q(this,"_contextProvider",new Uw)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}};const Ud=(e,t)=>{if(e.startsWith("data-"))return{type:"data",name:e.substring(5),data:t}},Uc=(e,t,r)=>{const{role:n,id:s,createdAt:i,attachments:a,status:o,metadata:l}=e,c={id:s??t,createdAt:i??new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,f=({image:h,...m})=>typeof h!="string"?null:h.match(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,(.*)$/)?{...m,image:h}:/^(https:\/\/|blob:)/.test(h)?{...m,image:h}:(console.warn("Invalid image data format detected"),null);if(n!=="user"&&a?.length)throw new Error("attachments are only supported for user messages");if(n!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(n!=="assistant"&&l?.steps)throw new Error("metadata.steps is only supported for assistant messages");switch(n){case"assistant":return{...c,role:n,content:d.map(h=>{const m=h.type;switch(m){case"text":case"reasoning":return h.text?.trim()?h:null;case"file":case"source":return h;case"image":return f(h);case"data":return h;case"generative-ui":return h;case"tool-call":{const{parentId:g,messages:v,...w}=h,b={...w,toolCallId:h.toolCallId??`tool-${us()}`,...g!==void 0&&{parentId:g},...v!==void 0&&{messages:v}};return h.args?{...b,args:h.args,argsText:h.argsText??JSON.stringify(h.args)}:{...b,args:gC(h.argsText??"")??{},argsText:h.argsText??""}}default:{const g=Ud(m,h.data);if(g)return g;throw new Error(`Unsupported assistant message part type: ${m}`)}}}).filter(h=>!!h),status:o??r,metadata:{unstable_state:l?.unstable_state??null,unstable_annotations:l?.unstable_annotations??[],unstable_data:l?.unstable_data??[],custom:l?.custom??{},steps:l?.steps??[],...l?.timing&&{timing:l.timing},...l?.submittedFeedback&&{submittedFeedback:l.submittedFeedback},...l?.isOptimistic&&{isOptimistic:!0}}};case"user":return{...c,role:n,content:d.map(h=>{const m=h.type;switch(m){case"text":case"image":case"audio":case"file":case"data":return h;default:{const g=Ud(m,h.data);if(g)return g;throw new Error(`Unsupported user message part type: ${m}`)}}}),attachments:(a??[]).map(h=>({...h,content:h.content.map(m=>Ud(m.type,m.data)??m)})),metadata:{custom:l?.custom??{}}};case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return{...c,role:n,content:d,metadata:{custom:l?.custom??{}}};default:throw new Error(`Unknown message role: ${n}`)}},tl=Symbol("autoStatus"),e6=Object.freeze(Object.assign({type:"running"},{[tl]:!0})),t6=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[tl]:!0})),r6=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[tl]:!0})),n6=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[tl]:!0})),W0=(e,t,r,n,s)=>e&&s?Object.assign({type:"incomplete",reason:"error",error:s},{[tl]:!0}):e&&t?e6:r?n6:n?r6:t6,NC={fromArray:e=>{const t=e.map(r=>Uc(r,us(),W0(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}},fromBranchableArray:(e,t)=>{const r=W0(!1,!1,!1,!1,void 0);return{...t?.headId!==void 0?{headId:t.headId}:void 0,messages:e.map(({message:n,parentId:s})=>
35{if(!n.id)throw new Error("ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.");return{parentId:s,message:Uc(n,n.id,r)}})}}},dc=e=>e.next?dc(e.next):"current"in e?e:null;var s6=class{constructor(e){q(this,"func");q(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},i6=class{constructor(){q(this,"messages",new Map);q(this,"head",null);q(this,"root",{children:[],next:null});q(this,"_messages",new s6(()=>{const e=new Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e}))}updateLevels(e,t){e.level=t;for(const r of e.children){const n=this.messages.get(r);n&&this.updateLevels(n,t+1)}}performOp(e,t,r){const n=t.prev??this.root,s=e??this.root;if(!(r==="relink"&&n===s)){if(r!=="link"&&(n.children=n.children.filter(i=>i!==t.current.id),n.next===t)){const i=n.children.at(-1),a=i?this.messages.get(i):null;if(a===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");n.next=a}if(r!=="cut"){for(let a=e;a;a=a.prev)if(a.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");s.children=[...s.children,t.current.id],(dc(t)===this.head||s.next===null)&&(s.next=t),t.prev=e;const i=e?e.level+1:0;this.updateLevels(t,i)}}}get headId(){return this.head?.current.id??null}get canonicalHeadId(){let e=this.head;for(;e?.current.metadata?.isOptimistic;)e=e.prev;return e?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const r=new Array(t.level+1);for(let n=t;n;n=n.prev)r[n.level]=n.current;return r}addOrUpdateMessage(e,t){const r=this.messages.get(t.id),n=e?this.messages.get(e):null;if(n===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(n,r,"relink"),this._messages.dirty();return}const s={prev:n,current:t,next:null,children:[],level:n?n.level+1:0};this.messages.set(t.id,s),this.performOp(n,s,"link"),this.head===n&&(this.head=s),this._messages.dirty()}getMessage(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}deleteMessage(e,t){const r=this.messages.get(e);if(!r)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const n=t===void 0?r.prev:t===null?null:this.messages.get(t);if(n===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const s of r.children){const i=this.messages.get(s);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,i,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=dc(n??this.root)),this._messages.dirty()}getBranches(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:r}=t.prev??this.root;return r}evictOffBranchOptimisticMessages(e,t){if(!e)return;const r=new Set;for(let s=t;s;s=s.prev)r.add(s.current.id);const n=[];for(let s=e;s&&!r.has(s.current.id);s=s.prev)s.current.metadata?.isOptimistic&&n.push(s.current.id);for(const s of n)this.messages.has(s)&&this.deleteMessage(s)}switchToBranch(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const r=this.head,n=t.prev??this.root;n.next=t,this.head=dc(t),this.evictOffBranchOptimisticMessages(r,this.head),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");const r=this.head;if(t.children.length>0){const n=s=>{for(const i of s.children){const a=this.messages.get(i);a&&(n(a),this.messages.delete(i))}};n(t),t.children=[],t.next=null}this.head=t;for(let n=t;n;n=n.prev)n.prev?n.prev.next=n:this.root.next=n;this.evictOffBranchOptimisticMessages(r,this.head),this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){const e=[];for(const[,t]of this.messages)t.current.metadata?.isOptimistic||e.push({message:t.current,parentId:t.prev?.current.id??null});return{headId:this.canonicalHeadId,messages:e}}import({headId:e,messages:t}){for(const{message:r,parentId:n}of t)this.addOrUpdateMessage(n,r);this.resetHead(e??t.at(-1)?.message.id??null)}};const Po=Object.freeze([]);function Y0(e,t){if(t==="*")return!0;const r=t.split(",").map(i=>i.trim().toLowerCase()),n=`.${e.name.split(".").pop().toLowerCase()}`,s=e.type.toLowerCase();for(const i of r){if(i.startsWith(".")&&i===n||i.includes("/")&&i===s)return!0;
35if(i.endsWith("/*")){const a=i.split("/")[0];if(s.startsWith(`${a}/`))return!0}}return!1}function a6(e,t){return e.length!==t.length?!1:e.every((r,n)=>r.id===t[n].id)}function o6(e){const t=us();return e.type==="image"?{id:t,type:"image",name:e.filename??"image",content:[e],status:{type:"complete"}}:e.type==="file"?{id:t,type:"document",name:e.filename??"document",contentType:e.mimeType,content:[e],status:{type:"complete"}}:e.type==="audio"?{id:t,type:"audio",name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:"complete"}}:{id:t,type:"data",name:e.name,content:[e],status:{type:"complete"}}}function l6(e){const t=[];for(const r of e)r.type!=="text"&&t.push(o6(r));return t}const Vd=e=>e.status.type==="complete";var RC=class extends el{constructor(){super(...arguments);q(this,"isEditing",!0);q(this,"_attachments",[]);q(this,"_text","");q(this,"_role","user");q(this,"_runConfig",{});q(this,"_quote");q(this,"_dictation");q(this,"_dictationSession");q(this,"_dictationUnsubscribes",[]);q(this,"_dictationBaseText","");q(this,"_currentInterimText","");q(this,"_dictationSessionIdCounter",0);q(this,"_activeDictationSessionId");q(this,"_isCleaningDictation",!1);q(this,"_eventSubscribers",new Map)}enrichWithComposerMetadata(t,r){return r?{...t,metadata:{...t.metadata,custom:{...t.metadata?.custom,...r}}}:t}get attachmentAccept(){return this.getAttachmentAdapter()?.accept??"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}get quote(){return this._quote}setQuote(t){this._quote!==t&&(this._quote=t,this._notifySubscribers())}setText(t){if(this._text!==t){if(this._text=t,this._dictation){this._dictationBaseText=t,this._currentInterimText="";const{status:r,inputDisabled:n}=this._dictation;this._dictation=n?{status:r,inputDisabled:n}:{status:r}}this._notifySubscribers()}}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const t=this.getAttachmentAdapter();if(t){const r=this._attachments.filter(n=>!Vd(n));await Promise.all(r.map(n=>t.remove(n)))}}async reset(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0&&this._quote===void 0)return;this._role="user",this._runConfig={},this._quote=void 0;const t=this._onClearAttachments();this._emptyTextAndAttachments(),await t}async clearAttachments(){const t=this._onClearAttachments();this.setAttachments([]),await t}async send(t){if(!this.canSend)return;this._dictationSession&&(this._dictationSession.cancel(),this._cleanupDictation());const r=this.getAttachmentAdapter(),n=this.attachments.length>0?Promise.all(this.attachments.map(async o=>{if(Vd(o))return o;if(!r)throw new Error("Attachments are not supported");return await r.send(o)})):[],s=this.text,i=this._quote;this._quote=void 0,this._emptyTextAndAttachments();const a={createdAt:new Date,role:this.role,content:s?[{type:"text",text:s}]:[],attachments:await n,runConfig:this.runConfig,metadata:{custom:{...i?{quote:i}:{}}}};this.handleSend(a,t),this._notifyEventSubscribers("send",{})}cancel(){this.handleCancel()}get queue(){return Po}steerQueueItem(t){}removeQueueItem(t){}async addAttachment(t){if(!(t instanceof File)){const i=this.getAttachmentAdapter();if(i&&!Y0({name:t.name,type:t.contentType??""},i.accept)){const o=`File type ${t.contentType||"unknown"} is not accepted. Accepted types: ${i.accept}`,l=new Error(o);throw this._safeEmitAttachmentAddError("not-accepted",o,void 0,l),l}const a={id:t.id??us(),type:t.type??"document",name:t.name,contentType:t.contentType,content:t.content,status:{type:"complete"}};this._attachments=[...this._attachments,a],this._notifySubscribers(),this._notifyEventSubscribers("attachmentAdd",{});return}const r=i=>{const a=this._attachments.findIndex(o=>o.id===i.id);a!==-1?this._attachments=[...this._attachments.slice(0,a),i,...this._attachments.slice(a+1)]:this._attachments=[...this._attachments,i],this._notifySubscribers()},n=this.getAttachmentAdapter();if(!n){const i="Attachments are not supported",a=new Error(i);throw this._safeEmitAttachmentAddError("no-adapter",i,void 0,a),a}if(!Y0({name:t.name,type:t.type},n.accept)){const i=`File type ${t.type||"unknown"} is not accepted. Accepted types: ${n.accept}`,a=new Error(i);throw this._safeEmitAttachmentAddError("not-accepted",i,void 0,a),a}let s;try{const i=n.add({file:t});if(Symbol.asyncIterator in i)for await(const a of i)s=a,r(a);else s=await i,r(s)}catch(i){throw s&&r({...s,status:{type:"incomplete",reason:"error"}}),this._safeEmitAttachmentAddError("adapter-error",i instanceof Error?i.message:String(i),s?.id,i instanceof Error?i:void 0),i}s?.status.type==="incomplete"&&s.status.reason==="error"?this._safeEmitAttachmentAddError("adapter-error","Attachment upload did not complete successfully.",s?.id):this._notifyEventSubscribers("attachmentAdd",{})}_safeEmitAttachmentAddError(t,r,n,s){try{this._notifyEventSubscribers("attachmentAddError",{reason:t,message:r,...n!==void 0&&{attachmentId:n},...s!==void 0&&{error:s}})}catch(i){console.error("[assistant-ui] attachmentAddError subscriber threw:",i)}}async removeAttachment(t){const r=this._attachments.findIndex(s=>s.id===t);if(r===-1)throw new Error("Attachment not found");const n=this._attachments[r];if(!Vd(n)){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");await s.remove(n)}this._attachments=this._attachments.filter(s=>s.id!==t),this._notifySubscribers()}get dictation(){return this._dictation}_isActiveSession(t,r){return this._activeDictationSessionId===t&&this._dictationSession===r}startDictation(){const t=this.getDictationAdapter();if(!t)throw new Error("Dictation adapter not configured");if(this._dictationSession){for(const c of this._dictationUnsubscribes)c();this._dictationUnsubscribes=[],this._dictationSession.stop().catch(()=>{}),this._dictationSession=void 0}const r=t.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText="";const n=t.listen();this._dictationSession=n;const s=++this._dictationSessionIdCounter;this._activeDictationSessionId=s,this._dictation={status:n.status,inputDisabled:r},this._notifySubscribers();const i=n.onSpeech(c=>{if(!this._isActiveSession(s,n))return;const d=c.isFinal!==!1,f=this._dictationBaseText&&!this._dictationBaseText.endsWith(" ")&&c.transcript?" ":"";
35if(d){if(this._dictationBaseText=this._dictationBaseText+f+c.transcript,this._currentInterimText="",this._text=this._dictationBaseText,this._dictation){const{transcript:h,...m}=this._dictation;this._dictation=m}this._notifySubscribers()}else this._currentInterimText=f+c.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&(this._dictation={...this._dictation,transcript:c.transcript}),this._notifySubscribers()});this._dictationUnsubscribes.push(i);const a=n.onSpeechStart(()=>{this._isActiveSession(s,n)&&(this._dictation={status:{type:"running"},inputDisabled:r,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(a);const o=n.onSpeechEnd(()=>{this._cleanupDictation({sessionId:s})});this._dictationUnsubscribes.push(o);const l=setInterval(()=>{this._isActiveSession(s,n)&&n.status.type==="ended"&&this._cleanupDictation({sessionId:s})},100);this._dictationUnsubscribes.push(()=>clearInterval(l))}stopDictation(){if(!this._dictationSession)return;const t=this._dictationSession,r=this._activeDictationSessionId;t.stop().finally(()=>{this._cleanupDictation({sessionId:r})})}_cleanupDictation(t){if(!(t?.sessionId!==void 0&&t.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)){this._isCleaningDictation=!0;try{for(const r of this._dictationUnsubscribes)r();this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText="",this._currentInterimText="",this._notifySubscribers()}finally{this._isCleaningDictation=!1}}}_notifyEventSubscribers(t,r){const n=this._eventSubscribers.get(t);if(n)for(const s of n)s(r)}unstable_on(t,r){const n=r;let s=this._eventSubscribers.get(t);return s||(s=new Set,this._eventSubscribers.set(t,s)),s.add(n),()=>{this._eventSubscribers.get(t)?.delete(n)}}},c6=class extends RC{constructor(t){super();q(this,"runtime");q(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get canSend(){return!this.isEmpty&&!this.runtime.isSendDisabled}get queue(){return this.runtime.getQueueItems?.()??Po}steerQueueItem(t){this.runtime.steerQueueItem?.(t)}removeQueueItem(t){this.runtime.removeQueueItem?.(t)}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}connect(){let t=this.runtime.isSendDisabled,r=this.queue;return this.runtime.subscribe(()=>{let n=!1;this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,n=!0),t!==this.runtime.isSendDisabled&&(t=this.runtime.isSendDisabled,n=!0),r!==this.queue&&(r=this.queue,n=!0),n&&this._notifySubscribers()})}async handleSend(t,r){const n=oC(this.runtime.getModelContext().unstable_composerMetadata,this.runtime.messages),s=this.enrichWithComposerMetadata(t,n);this.runtime.append({...s,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:r?.startRun,steer:r?.steer})}async handleCancel(){this.runtime.cancelRun()}},u6=class extends RC{constructor(t,r,{parentId:n,message:s}){super();q(this,"runtime");q(this,"endEditCallback");q(this,"_previousText");q(this,"_previousAttachments");q(this,"_nonTextPassthrough");q(this,"_parentId");q(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=s.id,this._previousText=Ro(s),this.setText(this._previousText),this.setRole(s.role),s.role==="user"?(this._previousAttachments=[...s.attachments??[],...l6(s.content)],this._nonTextPassthrough=[]):(this._previousAttachments=s.attachments??[],this._nonTextPassthrough=s.content.filter(i=>i.type!=="text")),this.setAttachments(this._previousAttachments),this.setRunConfig({...t.composer.runConfig})}get canCancel(){return!0}get canSend(){return!this.isEmpty}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(t,r){const n=Ro(t),s=!a6(t.attachments??[],this._previousAttachments);if(n!==this._previousText||s||r?.startRun){const i=this._nonTextPassthrough.length>0?[...t.content,...this._nonTextPassthrough]:t.content,a=this.runtime.messages,o=this._parentId===null?-1:a.findIndex(d=>d.id===this._parentId),l=oC(this.runtime.getModelContext().unstable_composerMetadata,a.slice(0,o+1)),c=this.enrichWithComposerMetadata(t,l);this.runtime.append({...c,content:i,parentId:this._parentId,sourceId:this._sourceId,startRun:r?.startRun})}this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},d6=class{constructor(e){q(this,"_contextProvider");q(this,"_subscriptions",new Set);q(this,"_isInitialized",!1);q(this,"repository",new i6);q(this,"_voiceMessages",[]);q(this,"_voiceGeneration",0);q(this,"_cachedMergedMessages",null);q(this,"_cachedVoiceGeneration",-1);q(this,"_cachedMergedBase",null);q(this,"composer",new c6(this));q(this,"_editComposers",new Map);q(this,"_stopSpeaking");q(this,"speech");q(this,"_voiceSession");q(this,"_voiceUnsubs",[]);q(this,"voice");q(this,"_voiceVolume",0);q(this,"_voiceVolumeSubscribers",new Set);q(this,"getVoiceVolume",()=>this._voiceVolume);q(this,"subscribeVoiceVolume",e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e)));q(this,"_currentAssistantMsg",null);q(this,"_eventSubscribers",new Map);this._contextProvider=e}
35_markVoiceMessagesDirty(){this._voiceGeneration++,this._cachedMergedMessages=null}_getBaseMessages(){return this.repository.getMessages()}get messages(){if(this._voiceMessages.length===0)return this._getBaseMessages();const e=this._getBaseMessages();return(this._cachedVoiceGeneration!==this._voiceGeneration||this._cachedMergedBase!==e)&&(this._cachedMergedMessages=[...e,...this._voiceMessages],this._cachedVoiceGeneration=this._voiceGeneration,this._cachedMergedBase=e),this._cachedMergedMessages}get state(){let e;for(const t of this.messages)t.role==="assistant"&&(e=t);return e?.metadata.unstable_state??null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new u6(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{const t=this.repository.getMessages(),r=this._voiceMessages.findIndex(n=>n.id===e);return r!==-1?{parentId:r>0?this._voiceMessages[r-1].id:t.at(-1)?.id??null,message:this._voiceMessages[r],index:t.length+r}:void 0}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e,t){const r=this._eventSubscribers.get(e);if(r)for(const n of r)n(t)}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){const r=this.adapters?.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:n,parentId:s}=this.repository.getMessage(e);if(r.submit({message:n,type:t}),n.role==="assistant"){const i={...n,metadata:{...n.metadata,submittedFeedback:{type:t}}};this.repository.addOrUpdateMessage(s,i)}this._notifySubscribers()}speak(e){const t=this.adapters?.speech;if(!t)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(e);this._stopSpeaking?.();const n=t.speak(Ro(r)),s=n.subscribe(()=>{n.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:n.status},this._notifySubscribers()});this.speech={messageId:e,status:n.status},this._notifySubscribers(),this._stopSpeaking=()=>{n.cancel(),s(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}connectVoice(){const e=this.adapters?.voice;if(!e)throw new Error("Voice adapter not configured");this.disconnectVoice();const t=e.connect({});this._voiceSession=t;const r=[];let n="listening";this.voice={status:t.status,isMuted:t.isMuted,mode:n},this._voiceVolume=0,this._notifySubscribers(),r.push(t.onStatusChange(s=>{s.type==="ended"?(this._finishVoiceAssistantMessage(),this._voiceSession=void 0,this.voice=void 0):this.voice={status:s,isMuted:t.isMuted,mode:n},this._notifySubscribers()})),r.push(t.onModeChange(s=>{n=s,this.voice&&(this.voice={...this.voice,mode:s},this._notifySubscribers())})),r.push(t.onVolumeChange(s=>{this._voiceVolume=s;for(const i of this._voiceVolumeSubscribers)i()})),r.push(t.onTranscript(s=>{this._handleVoiceTranscript(s)})),this._voiceUnsubs=r}_handleVoiceTranscript(e){if(this.ensureInitialized(),e.role==="user")this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null,e.isFinal&&(this._voiceMessages.push({id:us(),role:"user",content:[{type:"text",text:e.text}],metadata:{custom:{}},createdAt:new Date,status:{type:"complete",reason:"unknown"},attachments:[]}),this._markVoiceMessagesDirty(),this._notifySubscribers());else{if(!this._currentAssistantMsg)this._currentAssistantMsg={id:us(),role:"assistant",content:[{type:"text",text:e.text}],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},status:{type:"running"},createdAt:new Date},this._voiceMessages.push(this._currentAssistantMsg);else{const t=this._voiceMessages.indexOf(this._currentAssistantMsg);if(t===-1)return;const r={...this._currentAssistantMsg,content:[{type:"text",text:e.text}],...e.isFinal?{status:{type:"complete",reason:"stop"}}:{}};this._voiceMessages[t]=r,this._currentAssistantMsg=r}e.isFinal&&(this._currentAssistantMsg=null),this._markVoiceMessagesDirt
35y(),this._notifySubscribers()}}_finishVoiceAssistantMessage(){const e=this._voiceMessages.at(-1);if(e?.role==="assistant"&&e.status.type==="running"){const t=this._voiceMessages.length-1;this._voiceMessages[t]={...e,status:{type:"complete",reason:"stop"}},this._markVoiceMessagesDirty(),this._notifySubscribers()}}disconnectVoice(){this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null;for(const e of this._voiceUnsubs)e();this._voiceUnsubs=[],this._voiceSession?.disconnect(),this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;for(const e of this._voiceVolumeSubscribers)e();this._voiceMessages=[],this._markVoiceMessagesDirty(),this._notifySubscribers()}muteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this._notifySubscribers()}unmuteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize",{}))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(NC.fromArray(e??[]))}unstable_on(e,t){const r=t;if(e==="modelContextUpdate")return this._contextProvider.subscribe?.(()=>r({}))??(()=>{});let n=this._eventSubscribers.get(e);return n||(n=new Set,this._eventSubscribers.set(e,n)),n.add(r),e==="initialize"&&this._isInitialized&&queueMicrotask(()=>{n.has(r)&&r({})}),()=>{this._eventSubscribers.get(e)?.delete(r)}}};const f6=e=>{const t=ce(3),{detectorRef:r}=e;let n,s;return t[0]!==r?(n=()=>{r.current=!0},s=[r],t[0]=r,t[1]=n,t[2]=s):(n=t[1],s=t[2]),Io(n,s),null};var h6=class extends el{constructor(t,r){super();q(this,"useRuntimeHook");q(this,"instances",new Map);q(this,"useAliveThreadsKeysChanged",ko(()=>({})));q(this,"parent");q(this,"_RuntimeBinder",({threadId:t,children:r})=>{const{useRuntime:n}=this.useRuntimeHook(),s=n(),i=s.thread.__internal_threadBinding,a=Zs(()=>{const f=this.instances.get(t);if(!f)throw new Error("Thread not found. This is a bug in assistant-ui.");f.runtime=i.getState(),this._notifySubscribers()},[t,i]),o=wt(!1);o.current||a(),ot(()=>(o.current=!0,a(),i.outerSubscribe(a)),[i,a]);const l=vt(),c=wt(void 0),d=wt(!1);return ot(()=>{const f=i.getState(),h=f.__internal_setGetInitializePromise;typeof h=="function"&&h.call(f,()=>c.current)},[i]),ot(()=>(d.current=!1,s.threads.main.unstable_on("initialize",()=>{if(d.current||l.threadListItem().getState().status!=="new")return;d.current=!0,c.current=l.threadListItem().initialize();const f=s.thread.unstable_on("runEnd",()=>{f(),l.threadListItem().generateTitle()})})),[s,l]),u.jsx(u.Fragment,{children:r})});q(this,"_OuterActiveThreadProvider",N.memo(({threadId:t,provider:r})=>{const n=Gt(()=>new IC(this.parent).getItemById(t),[t]),s=wt(!1);return ot(()=>{},[r]),u.jsx(ED,{runtime:n,children:u.jsx(r,{children:u.jsx(this._RuntimeBinder,{threadId:t,children:u.jsx(f6,{detectorRef:s})})})})}));q(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>u.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:t},r))));this.parent=r,this.useRuntimeHook=ko(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const s=()=>{const a=this.instances.get(t);if(!a)i(),n(new Error("Thread was deleted before runtime was started"));else if(a.runtime)i(),r(a.runtime);else return},i=this.subscribe(s);s()})}getThreadRuntimeCore(t){const r=this.instances.get(t);if(r)return r.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}};const Q0=(e,t,r)=>r.reduce((n,s)=>s?.(n,t)??n,e);var p6=class extends el{constructor(t){super();q(this,"_pendingTransforms",[]);q(this,"_completedOptimistics",[]);q(this,"_baseValue");q(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}
35_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>Q0(t,r.task,[r.loading,r.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}async optimisticUpdate(t){const r=t.execute(),n={...t,task:r};try{this._pendingTransforms.push(n),this._updateState();const s=await r;this._baseValue=Q0(this._baseValue,s,[t.optimistic,t.then]);for(const i of this._completedOptimistics)this._baseValue=i(this._baseValue);return t.optimistic&&this._completedOptimistics.push(t.optimistic),s}finally{const s=this._pendingTransforms.indexOf(n);s>-1&&this._pendingTransforms.splice(s,1),this._pendingTransforms.length===0&&(this._completedOptimistics.length=0),this._updateState()}}};const Qt=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),m6={getMessageById(){},getBranches(){return[]},switchToBranch(){throw Qt},append(){throw Qt},deleteMessage(){throw Qt},startRun(){throw Qt},resumeRun(){throw Qt},cancelRun(){throw Qt},addToolResult(){throw Qt},resumeToolCall(){throw Qt},respondToToolApproval(){throw Qt},speak(){throw Qt},stopSpeaking(){throw Qt},connectVoice(){throw Qt},disconnectVoice(){throw Qt},getVoiceVolume:()=>0,subscribeVoiceVolume:()=>()=>{},muteVoice(){throw Qt},unmuteVoice(){throw Qt},submitFeedback(){throw Qt},getModelContext(){return{}},exportExternalState(){throw Qt},importExternalState(){throw Qt},composer:{attachments:[],attachmentAccept:"*",async addAttachment(){throw Qt},async removeAttachment(){throw Qt},isEditing:!0,canCancel:!1,canSend:!1,isEmpty:!0,text:"",setText(){throw Qt},role:"user",setRole(){throw Qt},runConfig:{},setRunConfig(){throw Qt},async reset(){},async clearAttachments(){},send(){throw Qt},cancel(){},queue:[],steerQueueItem(){},removeQueueItem(){},dictation:void 0,startDictation(){throw Qt},stopDictation(){},quote:void 0,setQuote(){throw Qt},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw Qt},speech:void 0,voice:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,delete:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1},isDisabled:!1,isSendDisabled:!1,isLoading:!0,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw Qt},export(){return{messages:[]}},reset(){throw Qt},unstable_on(){return()=>{}}};const X0=e=>e||void 0,J0=(e,t)=>{for(const r of e){if(t.threadIdMap[r.remoteId]!==void 0)continue;switch(r.status){case"regular":t.threadIds.push(r.remoteId);break;case"archived":t.archivedThreadIds.push(r.remoteId);break;default:{const s=r.status;throw new Error(`Unsupported state: ${s}`)}}const n=r.remoteId;t.threadIdMap[r.remoteId]=n,t.threadData[n]={id:r.remoteId,remoteId:r.remoteId,externalId:r.externalId,status:r.status,title:r.title,lastMessageAt:r.lastMessageAt,custom:r.custom,initializeTask:Promise.resolve({remoteId:r.remoteId,externalId:r.externalId})}}return t},vi=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},zl=(e,t,r)=>{const n=vi(e,t);if(!n)return e;const{id:s,remoteId:i,status:a}=n;if(a===r)return e;const o={...e};switch(a){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==s);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==s);break;default:throw new Error(`Unsupported state: ${a}`)}switch(r){case"regular":o.threadIds=[s,...o.threadIds];break;case"archived":o.archivedThreadIds=[s,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==s)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==s&&l!==i));break;default:throw new Error(`Unsupported state: ${r}`)}return r!=="deleted"&&(o.threadData={...o.threadData,[s]:{...n,status:r}}),o};var g6=class extends el{constructor(t,r){super();q(this,"_options");q(this,"_hookManager");q(this,"_loadThreadsPromise");q(this,"_loadMorePromise");q(this,"_loadGeneration",0);q(this,"_mainThreadId");
35q(this,"_state",new p6({isLoading:!0,isLoadingMore:!1,cursor:void 0,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));q(this,"contextProvider");q(this,"_initialThreadLoaded",!1);q(this,"useProvider");q(this,"_lastNotifiedThreadId");q(this,"initialize",async t=>{if(this._state.value.newThreadId!==t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:r=>zl(r,t,"regular"),loading:(r,n)=>{const s=t;return{...r,threadData:{...r.threadData,[s]:{...r.threadData[s],initializeTask:n}}}},then:(r,{remoteId:n,externalId:s})=>{const i=vi(r,t);if(!i)return r;const a=t;return{...r,threadIdMap:{...r.threadIdMap,[n]:a},threadData:{...r.threadData,[a]:{...i,initializeTask:Promise.resolve({remoteId:n,externalId:s}),remoteId:n,externalId:s}}}}})});q(this,"generateTitle",async t=>{const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:n}=await r.initializeTask,s=this._hookManager.getThreadRuntimeCore(r.id);if(!s)return;const i=s.messages,a=await this._options.adapter.generateTitle(n,i),o=CD.fromAssistantStream(a);for await(const l of o){const c=l.parts.filter(h=>h.type==="text")[0]?.text,d=this._state.baseValue,f=vi(d,r.id);f&&this._state.update({...d,threadData:{...d.threadData,[f.id]:{...f,title:c}}})}});q(this,"useBoundIds",ko(()=>[]));q(this,"__internal_RenderComponent",()=>{const t=N.useId();ot(()=>(this.useBoundIds.setState(i=>[...i,t],!0),()=>{this.useBoundIds.setState(i=>i.filter(a=>a!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),s={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&u.jsx(_C,{adapters:s,children:u.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>{this._notifySubscribers(),this._notifyThreadIdChange()}),this._hookManager=new h6(t.runtimeHook,this),this.useProvider=ko(()=>({Provider:t.adapter.unstable_Provider??N.Fragment})),this.__internal_setOptions(t),this.switchToNewThread()}get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){if(!this._loadThreadsPromise){const t=this._loadGeneration;this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:r=>({...r,isLoading:!0}),then:(r,n)=>{if(t!==this._loadGeneration)return r;const s=J0(n.threads,{threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}});return{...r,isLoading:!1,cursor:X0(n.nextCursor),threadIds:s.threadIds,archivedThreadIds:s.archivedThreadIds,threadIdMap:{...r.threadIdMap,...s.threadIdMap},threadData:{...r.threadData,...s.threadData}}}}).catch(r=>{t===this._loadGeneration&&(console.error("[assistant-ui] thread list load failed:",r),this._loadThreadsPromise=void 0,this._state.update({...this._state.baseValue,isLoading:!1}))}).then(()=>{})}return this._loadThreadsPromise}loadMore(){if(this._loadMorePromise)return this._loadMorePromise;const t=this._state.value;if(t.cursor===void 0||t.isLoading)return Promise.resolve();const r=this._loadGeneration,n=this._options.adapter,s=t.cursor,i=this._state.optimisticUpdate({execute:()=>n.list({after:s}),loading:a=>({...a,isLoadingMore:!0}),then:(a,o)=>{if(r!==this._loadGeneration||n!==this._options.adapter)return a;const l=J0(o.threads,{threadIds:[...a.threadIds],archivedThreadIds:[...a.archivedThreadIds],threadIdMap:{...a.threadIdMap},threadData:{...a.threadData}});return{...a,isLoadingMore:!1,cursor:X0(o.nextCursor),threadIds:l.threadIds,archivedThreadIds:l.archivedThreadIds,threadIdMap:l.threadIdMap,threadData:l.threadData}}}).catch(a=>{console.error("[assistant-ui] thread list loadMore failed:",a)}).then(()=>{this._loadMorePromise===i&&(this._loadMorePromise=void 0)});return this._loadMorePromise=i,i}__internal_setOptions(t){if(this._options===t)return;const r=this._options!==void 0&&this._options.adapter!==t.adapter;this._options=t;const n=t.adapter.unstable_Provider??N.Fragment;n!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:n},!0),this._hookManager.setRuntimeHook(t.runtimeHook),r&&(this._loadGeneration++,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._state.update({...this._state.baseValue,cursor:void 0}))}__internal_load(){this.getLoadThreadsPromise();const t=this._options.threadId??this._options.initialThreadId;!this._initialThreadLoaded&&t&&(this._initialThreadLoaded=!0,this.switchToThread(t).cat
35ch(()=>{}))}reload(){return this._loadGeneration++,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._state.update({...this._state.baseValue,cursor:void 0}),this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get isLoadingMore(){return this._state.value.isLoadingMore}get hasMore(){return this._state.value.cursor!==void 0}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}get _mainThreadRemoteId(){if(this._mainThreadId!==void 0)return vi(this._state.value,this._mainThreadId)?.remoteId}_notifyThreadIdChange(){const t=this._mainThreadRemoteId;this._lastNotifiedThreadId!==t&&(this._lastNotifiedThreadId=t,this._options.onThreadIdChange?.(t))}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||m6}getThreadRuntimeCore(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");const n=this._hookManager.getThreadRuntimeCore(r.id);if(!n)throw new Error("Thread not found");return n}getItemById(t){return vi(this._state.value,t)}async switchToThread(t,r){let n=this.getItemById(t);if(!n){const i=await this._options.adapter.fetch(t),a=this._state.value,o=i.remoteId,l={...a.threadData,[o]:{id:o,initializeTask:Promise.resolve({remoteId:i.remoteId,externalId:i.externalId}),remoteId:i.remoteId,externalId:i.externalId,status:i.status,title:i.title,lastMessageAt:i.lastMessageAt,custom:i.custom}},c={...a.threadIdMap,[i.remoteId]:o},d=a.threadIds.filter(g=>g!==i.remoteId),f=a.archivedThreadIds.filter(g=>g!==i.remoteId),h=i.status==="regular"?[...d,i.remoteId]:d,m=i.status==="archived"?[...f,i.remoteId]:f;this._state.update({...a,threadIds:h,archivedThreadIds:m,threadIdMap:c,threadData:l}),n=this.getItemById(t)}if(!n)throw new Error("Thread not found");if(this._mainThreadId===n.id)return;const s=this._hookManager.startThreadRuntime(n.id);this.mainThreadId!==void 0?await s:s.then(()=>this._notifySubscribers()),n.status==="archived"&&r?.unarchive!==!1&&await this.unarchive(n.id),this._mainThreadId=n.id,this._notifySubscribers(),this._notifyThreadIdChange()}async switchToNewThread(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)await this._state.waitForUpdate();const t=this._state.value;let r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${us()}`;while(t.threadIdMap[r]);const n=r;this._state.update({...t,newThreadId:r,threadIdMap:{...t.threadIdMap,[r]:n},threadData:{...t.threadData,[n]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0,custom:void 0}}})}return this.switchToThread(r)}rename(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:async()=>{const{remoteId:s}=await n.initializeTask;return this._options.adapter.rename(s,r)},optimistic:s=>{const i=vi(s,t);return i?{...s,threadData:{...s.threadData,[i.id]:{...i,title:r}}}:s}})}updateCustom(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");if(!this._options.adapter.updateCustom)throw new Error("Remote thread list adapter does not support updating custom metadata");return this._state.optimisticUpdate({execute:async()=>{const{remoteId:s}=await n.initializeTask,i=this._options.adapter;if(!i.updateCustom)throw new Error("Remote thread list adapter does not support updating custom metadata");return i.updateCustom(s,r)},optimistic:s=>{const i=vi(s,t);return i?{...s,threadData:{...s.threadData,[i.id]:{...i,custom:r}}}:s}})}async _ensureThreadIsNotMain(t){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&await this.switchToNewThread()}async archive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return await this._ensureThreadIsNotMain(r.id),this._state.optimisticUpdate({execute:async()=>{const{remoteId:n}=await r.initializeTask;return this._options.adapter.archive(n)},optimistic:n=>zl(n,r.id,"archived")})}unarchive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:async()=>{try{const{remoteId:n}=await r.initializeTask;return await this._options.adapter.unarchive(n)}catch(n){throw await this._ensureThreadIsNotMain(r.id),n}},optimistic:n=>zl(n,r.id,"regular")})}async delete(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return await this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id),this._state.optimisticUpdate({execute:async()=>{const{remoteId:n}=await r.initializeTask;return await this._options.adapter.delete(n)},optimistic:n=>zl(n,r.id,"deleted")})}async detach(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");await this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)}},y6=class extends kC{constructor(t){super();q(this,"threads");this.threads=new g6(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}};const v6=e=>{const t=ce(10);let r;t[0]!==e?(r=()=>new y6(e),t[0]=e,t[1]=r):r=t[1];const[n]=pr(r);let s;t[2]!==e||t[3]!==n.threads?(s=()=>{n.threads.__internal_setOptions(e),n.threads.__internal_load()},t[2]=e,t[3]=n.threads,t[4]=s):s=t[4];let i;t[5]!==e||t[6]!==n?(i=[n,e],t[5]=e,t[6]=n,t[7]=i):i=t[7],ot(s,i);let a;return t[8]!==n?(a=new AC(n),t[8]=n,t[9]=a):a=t[9],a},x6=e=>{const t=wt(e.runtimeHook);t.current=e.runtimeHook;const r=wt(e.threadId??e.initialThreadId),n=Zs(()=>t.current(),[]),s=kn(l=>{e.onThreadIdChange?.(l)}),i=Gt(()=>({adapter:e.adapter,allowNesting:e.allowNesting,initialThreadId:r.current,runtimeHook:n,onThreadIdChange:s}),[e.adapter,e.allowNesting,n]);if(vt().threadListItem.source!==null){if(!i.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return n()}const a=v6(i),o=wt(e.threadId);return ot(()=>{e.threadId!==o.current&&(o.current=e.threadId,e.threadId?a.threads.switchToThread(e.threadId).catch(()=>{}):a.threads.switchToNewThread().catch(()=>{}))},[a,e.threadId]),a};function b6(e){const t=e.status?.type==="running"?{type:"incomplete",reason:"cancelled"}:e.status;return{role:e.role,content:e.content.map(r=>{const n=r.type;switch(n){case"text":return{type:"text",text:r.text};case"reasoning":return{type:"reasoning",text:r.text};case"source":return r.sourceType==="url"?{type:"source",sourceType:"url",id:r.id,url:r.url,...r.title!=null?{title:r.title}:void 0,...r.providerMetadata!=null?{providerMetadata:r.providerMetadata}:void 0}:{type:"source",sourceType:"document",id:r.id,title:r.title,mediaType:r.mediaType,...r.filename!=null?{filename:r.filename}:void 0,...r.providerMetadata!=null?{providerMetadata:r.providerMetadata}:void 0};case"tool-call":return No(r.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(r)}`),{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,...JSON.stringify(r.args)===r.argsText?{args:r.args}:{argsText:r.argsText},...r.result?{result:r.result}:void 0,...r.isError?{isError:!0}:void 0};case"image":return{type:"image",image:r.image};case"file":return{type:"file",data:r.data,mimeType:r.mimeType,...r.filename?{filename:r.filename}:void 0};default:throw new Error(`Message part type not supported by aui/v0: ${n}`)}}),metadata:e.metadata,...t?{status:t}:void 0}}function w6(e){const t=e.content,r=Uc({id:e.id,createdAt:e.created_at,...t},e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}}const Z0=e=>{try{const t=e.split(".")[1];if(!t)throw new Error("Invalid JWT format");let r=t.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4!==0;)r+="=";const n=atob(r),s=JSON.parse(n).exp;if(!s||typeof s!="number")throw new Error('JWT does not contain a valid "exp" field');return s*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}};var Mo,Uv,PC=(Uv=class{constructor(e){q(this,"strategy","jwt");
35q(this,"cachedToken",null);q(this,"tokenExpiry",null);Ha(this,Mo);Ga(this,Mo,e)}async getAuthHeaders(){const e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const t=await qa(this,Mo).call(this);return t?(this.cachedToken=t,this.tokenExpiry=Z0(t),{Authorization:`Bearer ${t}`}):!1}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[r,n]=t.split(" ");if(r!=="Bearer"||!n)throw new Error("Invalid auth header received");this.cachedToken=n,this.tokenExpiry=Z0(n)}},Mo=new WeakMap,Uv),Oo,Fo,Uo,Vv,C6=(Vv=class{constructor(e,t,r){q(this,"strategy","api-key");Ha(this,Oo);Ha(this,Fo);Ha(this,Uo);Ga(this,Oo,e),Ga(this,Fo,t),Ga(this,Uo,r)}async getAuthHeaders(){return{Authorization:`Bearer ${qa(this,Oo)}`,"Aui-User-Id":qa(this,Fo),"Aui-Workspace-Id":qa(this,Uo)}}readAuthHeaders(){}},Oo=new WeakMap,Fo=new WeakMap,Uo=new WeakMap,Vv);const Kl="aui:refresh_token";var S6=class{constructor(e){q(this,"strategy","anon");q(this,"baseUrl");q(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new PC(async()=>{const t=Date.now(),r=localStorage.getItem(Kl),n=r?JSON.parse(r):void 0;if(n)if(new Date(n.expires_at).getTime()-t>30*1e3){const o=await fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n.token})});if(o.ok){const{access_token:l,refresh_token:c}=await o.json();return c&&localStorage.setItem(Kl,JSON.stringify(c)),l}}else localStorage.removeItem(Kl);const s=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!s.ok)return null;const{access_token:i,refresh_token:a}=await s.json();return!i||!a?null:(localStorage.setItem(Kl,JSON.stringify(a)),i)})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},ey=class extends Error{constructor(e){super(e),this.name="APIError"}},E6=class{constructor(e){q(this,"_auth");q(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new PC(e.authToken);else if("apiKey"in e)this._baseUrl=(e.baseUrl??"https://backend.assistant-api.com").replace(/\/$/,""),this._auth=new C6(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new S6(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}async initializeAuth(){return!!this._auth.getAuthHeaders()}async makeRawRequest(e,t={}){const r=await this._auth.getAuthHeaders();if(!r)throw new Error("Authorization failed");const n={...r,...t.headers,"Content-Type":"application/json"},s=new URLSearchParams;if(t.query)for(const[o,l]of Object.entries(t.query))l!==!1&&(l===!0?s.set(o,"true"):s.set(o,l.toString()));const i=new URL(`${this._baseUrl}/v1${e}`);i.search=s.toString();const a=await fetch(i,{method:t.method??"GET",headers:n,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(a.headers),!a.ok){const o=await a.text();try{throw new ey(JSON.parse(o).message)}catch(l){throw l instanceof ey?l:new Error(`Request failed with status ${a.status}, ${o}`)}}return a}async makeRequest(e,t={}){return(await this.makeRawRequest(e,t)).json()}},T6=class{constructor(e){q(this,"cloud");this.cloud=e}async create(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})}},_6=class{constructor(e){q(this,"cloud");this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:async()=>{const t=await this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return{...t,Accept:"text/plain"}},body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}async stream(e){const t=await this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return ch.fromResponse(t,new wD)}async report(e){return this.cloud.makeRequest("/runs",{method:"POST",body:e})}},I6=class{constructor(e){q(this,"cloud");this.cloud=e}async list(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})}
35async create(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})}async update(e,t,r){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}`,{method:"PUT",body:r})}},A6=class{constructor(e){q(this,"cloud");q(this,"messages");this.cloud=e,this.messages=new I6(e)}async list(e){return this.cloud.makeRequest("/threads",{query:e})}async get(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)}async create(e){return this.cloud.makeRequest("/threads",{method:"POST",body:e})}async update(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})}async delete(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})}},k6=class{constructor(e){q(this,"cloud");this.cloud=e}async pdfToImages(e){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})}async generatePresignedUploadUrl(e){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})}},N6=class{constructor(e){q(this,"threads");q(this,"auth");q(this,"runs");q(this,"files");q(this,"telemetry");const t=new E6(e);this.threads=new A6(t),this.auth={tokens:new T6(t)},this.runs=new _6(t),this.files=new k6(t);const r=e.telemetry;this.telemetry=r===!1?{enabled:!1}:r===!0||r===void 0?{enabled:!0}:{enabled:r.enabled!==!1,...r}}},R6=class{constructor(e){q(this,"cloud");q(this,"idMapping",{});this.cloud=e}async append(e,t,r,n,s){const i=r?await this.idMapping[r]??r:null,a=this.cloud.threads.messages.create(e,{parent_id:i,format:n,content:s}).then(({message_id:o})=>(this.idMapping[t]=o,o)).catch(o=>{throw this.idMapping[t]===a&&delete this.idMapping[t],o});return this.idMapping[t]=a,a.then(()=>{})}async update(e,t,r,n){const s=await this.getRemoteId(t);s&&await this.cloud.threads.messages.update(e,s,{content:n})}isPersisted(e){return e in this.idMapping}async getRemoteId(e){const t=this.idMapping[e];if(t)return t}async load(e,t){const{messages:r}=await this.cloud.threads.messages.list(e,t?{format:t}:void 0);for(const n of r)this.idMapping[n.id]=n.id;return r}reset(){this.idMapping={}}};const P6=(e,t)=>({append:async(r,n)=>{const s=t.getId(n.message),i=t.encode(n);return e.append(r,s,n.parentId,t.format,i)},update:e.update?async(r,n,s)=>{const i=t.encode(n);return e.update(r,s,t.format,i)}:void 0,load:async r=>({messages:(await e.load(r,t.format)).filter(n=>n.format===t.format).map(n=>t.decode({id:n.id,parent_id:n.parent_id,format:n.format,content:n.content})).reverse()}),isPersisted:r=>e.isPersisted(r)}),$d=new WeakMap;var j6=class{constructor(e,t){q(this,"cloudRef");q(this,"aui");this.cloudRef=e,this.aui=t}get _persistence(){const e=this.aui.threadListItem();return $d.has(e)||$d.set(e,new R6(this.cloudRef.current)),$d.get(e)}withFormat(e){const t=this,r=P6(this._persistence,e);return{async append(n){const{remoteId:s}=await t.aui.threadListItem().initialize();await r.append(s,n)},async update(n,s){const i=t.aui.threadListItem().getState().remoteId;i&&await r.update?.(i,n,s)},async delete(){throw new Error("Assistant Cloud does not support deleting thread messages yet.")},reportTelemetry(n,s){const i=n.map(a=>e.encode(a));t._reportRunTelemetry(e.format,i,s)},async load(){const n=t.aui.threadListItem().getState().remoteId;return n?r.load(n):{messages:[]}}}}async append({parentId:e,message:t}){const{remoteId:r}=await this.aui.threadListItem().initialize(),n=b6(t);await this._persistence.append(r,t.id,e,"aui/v0",n),this.cloudRef.current.telemetry.enabled&&this._maybeReportRun(r,"aui/v0",n)}async delete(){throw new Error("Assistant Cloud does not support deleting thread messages yet.")}async load(){const e=this.aui.threadListItem().getState().remoteId;return e?{messages:(await this._persistence.load(e,"aui/v0")).filter(t=>t.format==="aui/v0").map(w6).reverse()}:{messages:[]}}_reportRunTelemetry(e,t,r){if(!this.cloudRef.current.telemetry.enabled)return;const n=this.aui.threadListItem().getState().remoteId;if(!n)return;const s=M6(e,t);s&&this._sendReport(n,s,r?.durationMs,r?.stepTimestamps)}_maybeReportRun(e,t,r){const n=BC(t,r);n&&this._sendReport(e,n)}_sendReport(e,t,r,n){const s=L6(t.steps,n),i={thread_id:e,status:t.status,...t.totalSteps!=null?{total_steps:t.totalSteps}:void 0,...t.toolCalls?{tool_calls:t.toolCalls}:void 0,...s?{steps:s}:void 0,...t.inputTokens!=null?{input_tokens:t.inputTokens}:void 0,...t.outputTokens!=null?{output_tokens:t.outputTokens}:void 0,...t.reasoningTokens!=null?{reasoning_tokens:t.reasoningTokens}:void 0,...t.cachedInputTokens!=null?{cached_input_tokens:t.cachedInputTokens}:void 0,...r!=null?{duration_ms:r}:void 0,...t.outputText!=null?{output_text:t.outputText}:void 0,...t.metadata?{metadata:t.metadata}:void 0,...t.modelId?{model_id:t.modelId}:void 0},{beforeReport:a}=this.cloudRef.current.telemetry,o=a?a(i):i;o&&this.cloudRef.current.runs.report(o).catch(()=>{})}};const ty=5e4;function Ru(e){return e.length<=ty?e:e.slice(0,ty)}function fh(e){if(e!=null)try{return Ru(JSON.stringify(e))}catch{return}}const B6=/^[A-Za-z0-9+/]{100,}={0,2}$/;function D6(e){if(e!=null){try{const t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t)){const r=t.map(n=>{if(n&&typeof n=="object"&&n.type&&(n.type==="image"||n.type==="audio")&&typeof n.data=="str
35ing"&&B6.test(n.data.slice(0,200))){const s=(n.data.length*3/4/1024).toFixed(1);return{...n,data:`[${n.type}: ${s}KB]`}}return n});return Ru(JSON.stringify(r))}}catch{}return fh(e)}}function jC(e,t,r,n,s,i){const a={tool_name:e,tool_call_id:t},o=s??fh(r);o!==void 0&&(a.tool_args=o);const l=i==="mcp"?D6(n):fh(n);return l!==void 0&&(a.tool_result=l),i&&(a.tool_source=i),a}function L6(e,t){if(!t)return e;if(!e)return t.map(n=>({...n}));const r=Math.min(e.length,t.length);return e.map((n,s)=>({...n,...s<r?t[s]:void 0}))}function BC(e,t){switch(e){case"aui/v0":return F6(t);case"ai-sdk/v6":return K6(t);default:return null}}function M6(e,t){if(e==="ai-sdk/v6")return q6(t);for(let r=t.length-1;r>=0;r--){const n=BC(e,t[r]);if(n)return n}return null}const O6={error:"error",incomplete:"incomplete"};function F6(e){const t=e;if(t.role!=="assistant")return null;const r=t.content?.filter(v=>v.type==="tool-call"&&v.toolName&&v.toolCallId).map(v=>jC(v.toolName,v.toolCallId,v.args,v.result,v.argsText)),n=t.content?.filter(v=>v.type==="text"&&v.text),s=n&&n.length>0?Ru(n.map(v=>v.text).join("")):void 0,i=t.metadata?.steps;let a,o,l,c;if(i&&i.length>0){let v=0,w=0,b=0,C=0,T=!1,I=!1,k=!1,_=!1;for(const M of i)M.usage?.inputTokens!=null&&(v+=M.usage.inputTokens,T=!0),M.usage?.outputTokens!=null&&(w+=M.usage.outputTokens,I=!0),M.usage?.reasoningTokens!=null&&(b+=M.usage.reasoningTokens,k=!0),M.usage?.cachedInputTokens!=null&&(C+=M.usage.cachedInputTokens,_=!0);a=T?v:void 0,o=I?w:void 0,l=k?b:void 0,c=_?C:void 0}const d=t.status?.type,f=d&&O6[d]||"completed",h=t.metadata?.custom,m=t.metadata?.modelId??(typeof t.metadata?.custom?.modelId=="string"?t.metadata.custom.modelId:void 0),g=i&&i.length>1?i.map(v=>({...v.usage?.inputTokens!=null?{input_tokens:v.usage.inputTokens}:void 0,...v.usage?.outputTokens!=null?{output_tokens:v.usage.outputTokens}:void 0,...v.usage?.reasoningTokens!=null?{reasoning_tokens:v.usage.reasoningTokens}:void 0,...v.usage?.cachedInputTokens!=null?{cached_input_tokens:v.usage.cachedInputTokens}:void 0})):void 0;return{status:f,...r&&r.length>0?{toolCalls:r}:void 0,...i?.length?{totalSteps:i.length}:void 0,...a!=null?{inputTokens:a}:void 0,...o!=null?{outputTokens:o}:void 0,...l!=null?{reasoningTokens:l}:void 0,...c!=null?{cachedInputTokens:c}:void 0,...s!=null?{outputText:s}:void 0,...h?{metadata:h}:void 0,...g?{steps:g}:void 0,...m?{modelId:m}:void 0}}function U6(e){return e.toolCallId?e.type==="tool-call"||e.type==="dynamic-tool"?!!e.toolName:e.type.startsWith("tool-")||e.type.startsWith("dynamic-tool-"):!1}function V6(e){return e.type==="dynamic-tool"||e.type.startsWith("dynamic-tool-")}function $6(e){const t=V6(e)?"mcp":void 0;return jC(e.toolName??e.type.slice(5),e.toolCallId,e.args??e.input,e.result??e.output,void 0,t)}function DC(e){const t=[],r=[],n=[];let s=null;for(const i of e)if(i.type==="step-start")s!==null&&n.push({tool_calls:s}),s=[];else if(i.type==="text"&&i.text)t.push(i.text);else if(U6(i)){const a=$6(i);r.push(a),s!==null&&s.push(a)}return s!==null&&n.push({tool_calls:s}),{textParts:t,toolCalls:r,stepsData:n}}function z6(e){if(!e)return;if(typeof e.modelId=="string")return e.modelId;const t=e.custom;if(typeof t?.modelId=="string")return t.modelId}function LC(e,t,r,n,s,i){const a=e.length>0,o=a?Ru(e.join("")):void 0,l=z6(n),c=s&&s.length>1?s.map(d=>({...d.tool_calls.length>0?{tool_calls:d.tool_calls}:void 0})):void 0;return{status:a?"completed":"incomplete",...t.length>0?{toolCalls:t}:void 0,...r>0?{totalSteps:r}:void 0,...i?.inputTokens!=null?{inputTokens:i.inputTokens}:void 0,...i?.outputTokens!=null?{outputTokens:i.outputTokens}:void 0,...i?.reasoningTokens!=null?{reasoningTokens:i.reasoningTokens}:void 0,...i?.cachedInputTokens!=null?{cachedInputTokens:i.cachedInputTokens}:void 0,...o!=null?{outputText:o}:void 0,...n?{metadata:n}:void 0,...c?{steps:c}:void 0,...l?{modelId:l}:void 0}}function ry(e){const t=e.inputTokens??e.promptTokens,r=e.outputTokens??e.completionTokens;if(!(t==null&&r==null&&e.reasoningTokens==null&&e.cachedInputTokens==null))return{...t!=null?{inputTokens:t}:void 0,...r!=null?{outputTokens:r}:void 0,...e.reasoningTokens!=null?{reasoningTokens:e.reasoningTokens}:void 0,...e.cachedInputTokens!=null?{cachedInputTokens:e.cachedInputTokens}:void 0}}function MC(e){const t=e?.usage;if(t){const n=ry(t);if(n)return n}const r=e?.steps;if(r&&r.length>0){let n=0,s=0,i=0,a=0,o=!1,l=!1,c=!1,d=!1,f=!1;for(const h of r){if(!h.usage)continue;const m=ry(h.usage);m&&(m.inputTokens!=null&&(n+=m.inputTokens,o=!0),m.outputTokens!=null&&(s+=m.outputTokens,l=!0),m.reasoningTokens!=null&&(i+=m.reasoningTokens,c=!0),m.cachedInputTokens!=null&&(a+=m.cachedInputTokens,d=!0),f=!0)}if(f)return{...o?{inputTokens:n}:void 0,...l?{outputTokens:s}:void 0,...c?{reasoningTokens:i}:void 0,...d?{cachedInputTokens:a}:void 0}}}function K6(e){const t=e;if(t.role!=="assistant")return null;const{textParts:r,toolCalls:n,stepsData:s}=DC(t.parts??[]);return LC(r,n,s.length,t.metadata,s,MC(t.metadata))}function q6(e){const t=[],r=[],n=[];let s=!1,i,a=0,o=0,l=0,c=0,d=!1,f=!1,h=!1,m=!1;for(const g of e){const v=g;if(v.role!=="assistant")continue;s=!0;const{textParts:w,toolCalls:b,stepsData:C}=DC(v.parts??[]);t.push(...w),r.push(...b),n.push(...C),v.metadata&&(i=v.metadata);const T=MC(v.metadata);T&&(T.inputTokens!=null&&(a+=T.inputTokens,d=!0),T.outputTokens!=null&&(o+=T.outputTokens,f=!0),T.reasoningTokens!=null&&(l+=T.reasoningTokens,h=!0),T.cachedInputTokens!=null&&(c+=T.cachedInputTokens,m=!0))}return s?LC(t,r,n.length,i,n,{...d?{inputTokens:a}:void 0,...f?{outputTokens:o}:void 0,...h?{reasoningTokens:l}:void 0,...m?{cachedInputTokens:c}:void 0}):null}function H6(e){const t=ce(3),r=vt();let n;t[0]!==r||t[1]!==e?(n=()=>new j6(e,r),t[0]=r,t[1]=e,t[2]=n):n=t[2];const[s]=pr(n);return s}const G6=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file";var W6=class{constructor(e){q(this,"cloud");q(this,"accept","*");q(this,"uploadedUrls",new Map);this.cloud=e}async*add({file:e}){const t=crypto.randomUUID();let r={id:t,type:G6(e.type),name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield r;try{const{signedUrl:n,publicUrl:s}=await this.cloud.files.generatePresignedUploadUrl({filename:e.name});await fetch(n,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"}),this.uploadedUrls.set(t,s),r={...r,status:{type:"requires-action",reason:"composer-send"}},yield r}catch{r={...r,status:{type:"incomplete",reason:"error"}},yield r}}async remove(e){this.uploadedUrls.delete(e.id)}async send(e){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let r;return e.type==="image"?r=[{type:"image",image:t,filename:e.name}]:r=[{type:"file",data:t,mimeType:e.contentType??"",filename:e.name}],{...e,status:{type:"complete"},content:r}}},Y6=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}updateCustom(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(new Error("Thread not found"))}};const ny=e=>Dr(e)?e:void 0,sy=typeof process<"u"&&process?.env?.NEXT_PUBLIC_ASSISTANT_BASE_URL,zd=sy?new N6({baseUrl:sy,anonymous:!0}):void 0,Q6=e=>{const t=wt(e);ot(()=>{t.current=e},[e]);const r=Zs(function({children:i}){const a=H6({get current(){return t.current.cloud??zd}}),o=t.current.cloud??zd,l=Gt(()=>new W6(o),[o]);return u.jsx(_C,{adapters:Gt(()=>({history:a,attachments:l}),[a,l]),children:i})},[]),n=e.cloud??zd;if(!n){const s=t,i=new Y6;return i.initialize=async a=>({remoteId:a,externalId:(await s.current.create?.())?.externalId}),i}return{list:async()=>{const{threads:s}=await n.threads.list();return{threads:s.map(i=>({status:i.is_archived?"archived":"regular",remoteId:i.id,title:i.title,lastMessageAt:i.last_message_at?new Date(i.last_message_at):void 0,externalId:i.external_id??void 0,custom:ny(i.metadata)}))}},initialize:async()=>{const s=await(e.create?.()??Promise.resolve()),i=s?s.externalId:void 0,{thread_id:a}=await n.threads.create({last_message_at:new Date,external_id:i});return{externalId:i,remoteId:a}},rename:async(s,i)=>n.threads.update(s,{title:i}),updateCustom:async(s,i)=>n.threads.update(s,{metadata:i??null}),archive:async s=>n.threads.update(s,{is_archived:!0}),unarchive:async s=>n.threads.update(s,{is_archived:!1}),delete:async s=>(await e.delete?.(s),n.threads.delete(s)),generateTitle:async(s,i)=>{const a=i.map(o=>({...o,content:o.content.filter(l=>l.type==="text"||l.type==="tool-call")}
35));return n.runs.stream({thread_id:s,assistant_id:"system/thread_title",messages:a})},fetch:async s=>{const i=await n.threads.get(s);return{status:i.is_archived?"archived":"regular",remoteId:i.id,title:i.title,lastMessageAt:i.last_message_at?new Date(i.last_message_at):void 0,externalId:i.external_id??void 0,custom:ny(i.metadata)}},unstable_Provider:r}},X6=e=>{const t=ce(10),{id:r,children:n}=e;let s;t[0]!==r?(s=Nn({source:"thread",query:{type:"id",id:r},get:c=>c.thread().message({id:r})}),t[0]=r,t[1]=s):s=t[1];let i;t[2]!==r?(i=Nn({source:"message",query:{},get:c=>c.thread().message({id:r}).composer()}),t[2]=r,t[3]=i):i=t[3];let a;t[4]!==s||t[5]!==i?(a={message:s,composer:i},t[4]=s,t[5]=i,t[6]=a):a=t[6];const o=vt(a);let l;return t[7]!==o||t[8]!==n?(l=u.jsx(Pn,{value:o,children:n}),t[7]=o,t[8]=n,t[9]=l):l=t[9],l},Jp=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,J6=()=>null,iy=new WeakMap,Z6=(e,t)=>{let r=iy.get(e);return r||(r=new Set(e.map(n=>n.id)),iy.set(e,r)),r.has(t)},eL=(e,t,r)=>{switch(t){case"user":return r?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case"assistant":return r?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case"system":return r?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message:e.SystemMessage??e.Message??J6;default:throw new Error(`Unknown message role: ${t}`)}},Zp=e=>{const t=ce(6),{components:r}=e,n=Fe(rL),s=Fe(nL);let i;t[0]!==r||t[1]!==s||t[2]!==n?(i=eL(r,n,s),t[0]=r,t[1]=s,t[2]=n,t[3]=i):i=t[3];const a=i;let o;return t[4]!==a?(o=u.jsx(a,{}),t[4]=a,t[5]=o):o=t[5],o},OC=N.memo(e=>{const t=ce(5),{index:r,components:n}=e;let s;t[0]!==n?(s=u.jsx(Zp,{components:n}),t[0]=n,t[1]=s):s=t[1];let i;return t[2]!==r||t[3]!==s?(i=u.jsx(xC,{index:r,children:s}),t[2]=r,t[3]=s,t[4]=i):i=t[4],i},(e,t)=>e.index===t.index&&Jp(e.components,t.components));OC.displayName="ThreadPrimitive.MessageByIndex";const FC=N.memo(e=>{const t=ce(7),{messageId:r,components:n}=e;let s;if(t[0]!==r?(s=o=>Z6(o.thread.messages,r),t[0]=r,t[1]=s):s=t[1],!Fe(s))return null;let i;t[2]!==n?(i=u.jsx(Zp,{components:n}),t[2]=n,t[3]=i):i=t[3];let a;return t[4]!==r||t[5]!==i?(a=u.jsx(X6,{id:r,children:i}),t[4]=r,t[5]=i,t[6]=a):a=t[6],a},(e,t)=>e.messageId===t.messageId&&Jp(e.components,t.components));FC.displayName="ThreadPrimitive.Unstable_MessageById";const ay=({children:e})=>{const t=Fe(r=>r.thread.messages.length);return Gt(()=>t===0?null:Array.from({length:t},(r,n)=>u.jsx(xC,{index:n,children:u.jsx(Ra,{getItemState:s=>s.thread().message({index:n}).getState(),children:s=>e({get message(){return s()}})})},n)),[t,e])},UC=e=>{const t=ce(4),{components:r,children:n}=e;if(r){let i;return t[0]!==r?(i=u.jsx(ay,{children:()=>u.jsx(Zp,{components:r})}),t[0]=r,t[1]=i):i=t[1],i}let s;return t[2]!==n?(s=u.jsx(ay,{children:n}),t[2]=n,t[3]=s):s=t[3],s};UC.displayName="ThreadPrimitive.Messages";const tL=N.memo(UC,(e,t)=>e.children||t.children?e.children===t.children:Jp(e.components,t.components));function rL(e){return e.message.role}function nL(e){return e.message.composer.isEditing}const VC=e=>{const t=e.message.metadata;if(!(!t||typeof t!="object"))return t.custom?.quote};var sL=class extends Error{constructor(t,r=`Component "${t}" is not in the generative-ui allowlist.`){super(r);q(this,"componentName");this.name="GenerativeUIRenderError",this.componentName=t}};const iL=e=>typeof e=="object"&&e!==null,$C=(e,t,r,n)=>{if(e==null)return null;if(typeof e=="string")return e;if(!iL(e)||!("component"in e)||typeof e.component!="string")return typeof process<"u",null;const{component:s,props:i,children:a,key:o}=e,l=t[s];if(!l){if(r)return u.jsx(r,{component:s,props:i},o??n);throw new sL(s)}const c=a?.length?a.map((d,f)=>$C(d,t,r,`${n}/${f}`)):void 0;return N.createElement(l,{...i??{},key:o??n},...c??[])},aL=e=>{if(!e||e.root===void 0||e.root===null)return[];const t=e.root;return Array.isArray(t)?t:[t]},em=e=>{const t=ce(11),{spec:r,components:n,Fallback:s}=e;let i;t[0]!==r?(i=aL(r),t[0]=r,t[1]=i):i=t[1];const a=i;let o;if(t[2]!==s||t[3]!==n||t[4]!==a){let c;t[6]!==s||t[7]!==n?(c=(d,f)=>$C(d,n,s,`${f}`),t[6]=s,t[7]=n,t[8]=c):c=t[8],o=a.map(c),t[2]=s,t[3]=n,t[4]=a,t[5]=o}else o=t[5];let l;return t[9]!==o?(l=u.jsx(u.Fragment,{children:o}),t[9]=o,t[10]=l):l=t[10],l};em.displayName="GenerativeUIRender";const zC=e=>{const t=ce(4),{components:r,spec:n,Fallback:s}=e,i=Fe(oL),a=n??i;if(!a)return null;let o;return t[0]!==s||t[1]!==r||t[2]!==a?(o=u.jsx(em,{spec:a,components:r,Fallback:s}),t[0]=s,t[1]=r,t[2]=a,t[3]=o):o=t[3],o};zC.displayName="MessagePrimitive.GenerativeUI";function oL(e){const t=e.part;return t?.type==="generative-ui"?t.spec:void 0}const lL="ui://",cL=e=>!!e?.startsWith(lL),oy=e=>Symbol.iterator in e,ly=e=>"entries"in e,cy=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t
35:new Map(t.entries());if(r.size!==n.size)return!1;for(const[s,i]of r)if(!n.has(s)||!Object.is(i,n.get(s)))return!1;return!0},uL=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let s=r.next(),i=n.next();for(;!s.done&&!i.done;){if(!Object.is(s.value,i.value))return!1;s=r.next(),i=n.next()}return!!s.done&&!!i.done};function dL(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:oy(e)&&oy(t)?ly(e)&&ly(t)?cy(e,t):uL(e,t):cy({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function hh(e){const t=_e.useRef(void 0);return r=>{const n=e(r);return dL(t.current,n)?t.current:t.current=n}}const Kd=e=>{let t=-1;return{startGroup:r=>{t===-1&&(t=r)},endGroup:(r,n)=>{t!==-1&&(n.push({type:e,startIndex:t,endIndex:r}),t=-1)},finalize:(r,n)=>{t!==-1&&n.push({type:e,startIndex:t,endIndex:r})}}},fL=(e,t,r)=>{const n=[];if(t){const s=Kd("chainOfThoughtGroup");for(let i=0;i<e.length;i++){const a=e[i];a==="tool-call"||a==="reasoning"?s.startGroup(i):(s.endGroup(i-1,n),n.push({type:"single",index:i}))}s.finalize(e.length-1,n)}else{const s=Kd("toolGroup"),i=Kd("reasoningGroup");for(let a=0;a<e.length;a++){const o=e[a];o==="tool-call"?(i.endGroup(a-1,n),s.startGroup(a)):o==="reasoning"?(s.endGroup(a-1,n),i.startGroup(a)):(s.endGroup(a-1,n),i.endGroup(a-1,n),n.push({type:"single",index:a}))}s.finalize(e.length-1,n),i.finalize(e.length-1,n)}if(r){const s=new Set;for(const i of n){if(i.type==="single")continue;const a=r[i.startIndex];a!==void 0&&!s.has(a)&&(s.add(a),i.idKey=`id:${a}
35`)}}return n},hL=e=>{const t=ce(10),r=Fe(hh(NL)),n=Fe(hh(PL));let s;e:{if(r.length===0){let o;t[0]===Symbol.for("react.memo_cache_sentinel")?(o=[],t[0]=o):o=t[0];let l;t[1]!==n?(l={ranges:o,partIds:n},t[1]=n,t[2]=l):l=t[2],s=l;break e}let i;t[3]!==r||t[4]!==n||t[5]!==e?(i=fL(r,e,n),t[3]=r,t[4]=n,t[5]=e,t[6]=i):i=t[6];let a;t[7]!==n||t[8]!==i?(a={ranges:i,partIds:n},t[7]=n,t[8]=i,t[9]=a):a=t[9],s=a}return s},pL=e=>{const t=ce(9);let r,n;t[0]!==e?({Fallback:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]);let s;t[3]!==r||t[4]!==n.toolName?(s=o=>o.tools.toolUIs[n.toolName]?.[0]?.render??r,t[3]=r,t[4]=n.toolName,t[5]=s):s=t[5];const i=Fe(s);if(!i)return null;let a;return t[6]!==i||t[7]!==n?(a=u.jsx(i,{...n}),t[6]=i,t[7]=n,t[8]=a):a=t[8],a},tm=(e,t,r)=>{const n=e.renderers[t]?.[0];return n||(e.fallbacks[0]??r)},mL=e=>{const t=ce(9);let r,n;t[0]!==e?({Fallback:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]);let s;t[3]!==r||t[4]!==n.name?(s=o=>tm(o.dataRenderers,n.name,r),t[3]=r,t[4]=n.name,t[5]=s):s=t[5];const i=Fe(s);if(!i)return null;let a;return t[6]!==i||t[7]!==n?(a=u.jsx(i,{...n}),t[6]=i,t[7]=n,t[8]=a):a=t[8],a},Ur={Text:()=>null,Reasoning:()=>null,Source:()=>null,Image:()=>null,File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},gL=e=>{const t=ce(47),{components:r}=e;let n;t[0]!==r?(n=r===void 0?{}:r,t[0]=r,t[1]=n):n=t[1];const{Text:s,Reasoning:i,Image:a,Source:o,File:l,Unstable_Audio:c,tools:d,data:f,generativeUI:h}=n,m=s===void 0?Ur.Text:s,g=i===void 0?Ur.Reasoning:i,v=a===void 0?Ur.Image:a,w=o===void 0?Ur.Source:o,b=l===void 0?Ur.File:l,C=c===void 0?Ur.Unstable_Audio:c;let T;t[2]!==d?(T=d===void 0?{}:d,t[2]=d,t[3]=T):T=t[3];const I=T,k=vt(),_=Fe(jL),M=_.type;if(M==="tool-call"){let V;t[4]!==k?(V=k.part(),t[4]=k,t[5]=V):V=t[5];const G=V.addToolResult;let L;t[6]!==k?(L=k.part(),t[6]=k,t[7]=L):L=t[7];const H=L.resumeToolCall;let F;t[8]!==k?(F=k.part(),t[8]=k,t[9]=F):F=t[9];const Q=F.respondToToolApproval;if("Override"in I){let xe;return t[10]!==G||t[11]!==_||t[12]!==Q||t[13]!==H||t[14]!==I.Override?(xe=u.jsx(I.Override,{..._,addResult:G,resume:H,respondToApproval:Q}),t[10]=G,t[11]=_,t[12]=Q,t[13]=H,t[14]=I.Override,t[15]=xe):xe=t[15],xe}const J=I.by_name?.[_.toolName]??I.Fallback;let oe;return t[16]!==J||t[17]!==G||t[18]!==_||t[19]!==Q||t[20]!==H?(oe=u.jsx(pL,{..._,Fallback:J,addResult:G,resume:H,respondToApproval:Q}),t[16]=J,t[17]=G,t[18]=_,t[19]=Q,t[20]=H,t[21]=oe):oe=t[21],oe}if(_.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(M){case"text":{let V;return t[22]!==m||t[23]!==_?(V=u.jsx(m,{..._}),t[22]=m,t[23]=_,t[24]=V):V=t[24],V}case"reasoning":{let V;return t[25]!==g||t[26]!==_?(V=u.jsx(g,{..._}),t[25]=g,t[26]=_,t[27]=V):V=t[27],V}case"source":{let V;return t[28]!==w||t[29]!==_?(V=u.jsx(w,{..._}),t[28]=w,t[29]=_,t[30]=V):V=t[30],V}case"image":{let V;return t[31]!==v||t[32]!==_?(V=u.jsx(v,{..._}),t[31]=v,t[32]=_,t[33]=V):V=t[33],V}case"file":{let V;return t[34]!==b||t[35]!==_?(V=u.jsx(b,{..._}),t[34]=b,t[35]=_,t[36]=V):V=t[36],V}case"audio":{let V;return t[37]!==C||t[38]!==_?(V=u.jsx(C,{..._}),t[37]=C,t[38]=_,t[39]=V):V=t[39],V}case"data":{const V=f?.by_name?.[_.name]??f?.Fallback;let G;return t[40]!==V||t[41]!==_?(G=u.jsx(mL,{..._,Fallback:V}),t[40]=V,t[41]=_,t[42]=G):G=t[42],G}case"generative-ui":{if(!h?.components)return typeof process<"u",null;const V=_;let G;return t[43]!==h.Fallback||t[44]!==h.components||t[45]!==V.spec?(G=u.jsx(em,{spec:V.spec,components:h.components,Fallback:h.Fallback}),t[43]=h.Fallback,t[44]=h.components,t[45]=V.spec,t[46]=G):G=t[46],G}default:return console.warn(`Unknown message part type: ${M}`),null}},vo=N.memo(e=>{const t=ce(5),{index:r,components:n}=e;let s;t[0]!==n?(s=u.jsx(gL,{components:n}),t[0]=n,t[1]=s):s=t[1];let i;return t[2]!==r||t[3]!==s?(i=u.jsx(Yp,{index:r,children:s}),t[2]=r,t[3]=s,t[4]=i):i=t[4],i},(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.generativeUI===t.components?.generativeUI&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);vo.displayName="MessagePrimitive.PartByIndex";const yL=e=>{const t=ce(6),{status:r,component:n}=e,s=r.type==="running";let i;t[0]!==n||t[1]!==r?(i=u.jsx(n,{type:"text",text:"",status:r}),t[0]=n,t[1]=r,t[2]=i):i=t[2];let a;return t[3]!==s||t[4]!==i?(a=u.jsx(Qp,{text:"",isRunning:s,children:i}),t[3]=s,t[4]=i,t[5]=a):a=t[5],a},vL=Object.freeze({type:"complete"}),xL=Object.freeze({type:"running"}),bL=e=>{const t=ce(6),{components:r}=e,n=Fe(BL);if(r?.Empty){let a;return t[0]!==r.Empty||t[1]!==n?(a=u.jsx(r.Empty,{status:n}),t[0]=r.Empty,t[1]=n,t[2]=a):a=t[2],a}if(n.type!=="running")return null;const s=r?.Text??Ur.Text;let i;return t[3]!==n||t[4]!==s?(i=u.jsx(yL,{status:n,component:s}),t[3]=n,t[4]=s,t[5]=i):i=t[5],i},KC=N.memo(bL,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),wL=e=>{const t=ce(4),{components:r,enabled:n}=e;let s;if(t[0]!==n?(s=a=>{if(!n||a.message.parts.length===0)return!1;const o=a.message.parts[a.message.parts.length-1];return o?.type!=="text"&&o?.type!=="reasoning"},t[0]=n,t[1]=s):s=t[1],!Fe(s))return null;let i;return t[2]!==r?(i=u.jsx(KC,{components:r}),t[2]=r,t[3]=i):i=t[3],i},CL=N.memo(wL,(e,t)=>e.enabled===t.enabled&&e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),SL=e=>{const t=ce(4),{Quote:r}=e,n=Fe(VC);if(!n)return null;let s;return t[0]!==r||t[1]!==n.messageId||t[2]!==n.text?(s=u.jsx(r,{text:n.text,messageId:n.messageId}),t[0]=r,t[1]=n.messageId,t[2]=n.text,t[3]=s):s=t[3],s},EL=N.memo(SL);function qC(e,t){const r=e.toolUIs[t.toolName]?.[0]?.render??null;return r||(cL(t.mcp?.app?.resourceUri)&&e.mcpApp?e.mcpApp.render:null)}const HC=()=>{const e=ce(12),t=vt(),r=Fe(DL),n=Fe(LL);if(!n||r.type!=="tool-call")return null;let s;e[0]!==t?(s=t.part(),e[0]=t,e[1]=s):s=e[1];const i=s.addToolResult;let a;e[2]!==t?(a=t.part(),e[2]=t,e[3]=a):a=e[3];const o=a.resumeToolCall;let l;e[4]!==t?(l=t.part(),e[4]=t,e[5]=l):l=e[5];let c;return e[6]!==n||e[7]!==r||e[8]!==s.addToolResult||e[9]!==a.resumeToolCall||e[10]!==l.respondToToolApproval?(c=u.jsx(n,{...r,addResult:i,resume:o,respondToApproval:l.respondToToolApproval}),e[6]=n,e[7]=r,e[8]=s.addToolResult,e[9]=a.resumeToolCall,e[10]=l.respondToToolApproval,e[11]=c):c=e[11],c},GC=()=>{const e=ce(3),t=Fe(ML),r=Fe(OL);if(!r||t.type!=="data")return null;const n=t;let s;return e[0]!==r||e[1]!==n?(s=u.jsx(r,{...n}),e[0]=r,e[1]=n,e[2]=s):s=e[2],s},TL=()=>{const e=ce(2),t=Fe(FL);if(t==="tool-call"){let r;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=u.jsx(HC,{}),e[0]=r):r=e[0],r}if(t==="data"){let r;return e[1]===Symbol.for("react.memo_cache_sentinel")?(r=u.jsx(GC,{}),e[1]=r):r=e[1],r}return null},_L=Object.freeze({type:"text",text:"",status:xL}),WC=({index:e,children:t})=>{const r=vt(),n=Fe(s=>s.dataRenderers);return u.jsx(Yp,{index:e,children:u.jsx(Ra,{getItemState:s=>s.message().part({index:e}).getState(),children:s=>t({get part(){const i=s();if(i.type==="tool-call"){const a=qC(r.tools().getState(),i)!==null,o=r.message().part({index:e});return{...i,toolUI:a?u.jsx(HC,{}):null,addResult:o.addToolResult,resume:o.resumeToolCall,respondToApproval:o.respondToToolApproval}}if(i.type==="data"){const a=tm(n,i.name,void 0)!==void 0;return{...i,dataRendererUI:a?u.jsx(GC,{}):null}}return i}})})})},IL=e=>{const t=ce(9),{children:r}=e,n=Fe(UL),s=Fe(VL),i=n===0&&s;if(n===0){if(!i)return null;let o;t[0]!==r?(o=r({part:_L}),t[0]=r,t[1]=o):o=t[1];let l;return t[2]!==o?(l=u.jsx(Qp,{text:"",isRunning:!0,children:o}),t[2]=o,t[3]=l):l=t[3],l}let a;if(t[4]!==r||t[5]!==n){let o;t[7]!==r?(o=(l,c)=>u.jsx(WC,{index:c,children:d=>r(d)??u.jsx(TL,{})},c),t[7]=r,t[8]=o):o=t[8],a=u.jsx(u.Fragment,{children:Array.from({length:n},o)}),t[4]=r,t[5]=n,t[6]=a}else a=t[6];return a},ph=e=>{const t=ce(5),{components:r,unstable_showEmptyOnNonTextEnd:n,children:s}=e,i=n===void 0?!0:n;if(s){let o;return t[0]!==s?(o=u.jsx(IL,{children:s}),t[0]=s,t[1]=o):o=t[1],o}let a;return t[2]!==r||t[3]!==i?(a=u.jsx(AL,{components:r,unstable_showEmptyOnNonTextEnd:i}),t[2]=r,t[3]=i,t[4]=a):a=t[4],a};ph.displayName="MessagePrimitive.Parts";const AL=e=>{const t=ce(15),{components:r,unstable_showEmptyOnNonTextEnd:n}=e,s=Fe($L),{ranges:i,partIds:a}=hL(!!r?.ChainOfThought);let o;e:{if(s===0){let m;t[0]!==r?(m=u.jsx(KC,{components:r}),t[0]=r,t[1]=m):m=t[1],o=m;break e}let h;
35if(t[2]!==r||t[3]!==i||t[4]!==a){const m=new Set,g=v=>{const w=a[v];return w!==void 0&&!m.has(w)?(m.add(w),`part-id:${w}`):`part-${v}`};h=i.map(v=>{if(v.type==="single")return u.jsx(vo,{index:v.index,components:r},v.index);if(v.type==="chainOfThoughtGroup"){const w=r?.ChainOfThought;return w?u.jsx(jD,{startIndex:v.startIndex,endIndex:v.endIndex,children:u.jsx(w,{})},`chainOfThought-${v.idKey??v.startIndex}`):null}else return v.type==="toolGroup"?u.jsx(r?.ToolGroup??Ur.ToolGroup,{startIndex:v.startIndex,endIndex:v.endIndex,children:Array.from({length:v.endIndex-v.startIndex+1},(w,b)=>{const C=v.startIndex+b;return u.jsx(vo,{index:C,components:r},g(C))})},`tool-${v.idKey??v.startIndex}`):u.jsx(r?.ReasoningGroup??Ur.ReasoningGroup,{startIndex:v.startIndex,endIndex:v.endIndex,children:Array.from({length:v.endIndex-v.startIndex+1},(w,b)=>{const C=v.startIndex+b;return u.jsx(vo,{index:C,components:r},`part-${C}`)})},`reasoning-${v.startIndex}`)}),t[2]=r,t[3]=i,t[4]=a,t[5]=h}else h=t[5];o=h}const l=o;let c;t[6]!==r?(c=r?.Quote&&u.jsx(EL,{Quote:r.Quote}),t[6]=r,t[7]=c):c=t[7];let d;t[8]!==r||t[9]!==n?(d=u.jsx(CL,{components:r,enabled:n}),t[8]=r,t[9]=n,t[10]=d):d=t[10];let f;return t[11]!==l||t[12]!==c||t[13]!==d?(f=u.jsxs(u.Fragment,{children:[c,l,d]}),t[11]=l,t[12]=c,t[13]=d,t[14]=f):f=t[14],f};function kL(e){return e.type}function NL(e){return e.message.parts.map(kL)}function RL(e){return e.type==="tool-call"?e.toolCallId:void 0}function PL(e){return e.message.parts.map(RL)}function jL(e){return e.part}function BL(e){return e.message.status??vL}function DL(e){return e.part}function LL(e){return e.part.type==="tool-call"?qC(e.tools,e.part):null}function ML(e){return e.part}function OL(e){return e.part.type==="data"?tm(e.dataRenderers,e.part.name,void 0)??null:null}function FL(e){return e.part.type}function UL(e){return e.message.parts.length}function VL(e){return(e.message.status?.type??"complete")==="running"}function $L(e){return e.message.parts.length}const zL=Symbol.for("@assistant-ui/groupBy.memoKey"),uy=e=>{const t=e.nextChildIdx++;return e.nodeKey===""?String(t):`${e.nodeKey}.${t}`},dy=(e,t)=>{if(!(t===void 0||e.claimed.has(t)))return e.claimed.add(t),`id:${t}`},KL=(e,t)=>{const r={key:"",nodeKey:"",indices:[],children:[],nextChildIdx:0,claimed:new Set},n=[r],s=()=>{const i=n.pop(),a=n[n.length-1];a.children.push({type:"group",key:i.key,nodeKey:i.nodeKey,idKey:dy(a,t?.[i.indices[0]]),indices:i.indices,children:i.children})};for(let i=0;i<e.length;i++){const a=e[i];let o=0;for(;o<n.length-1&&o<a.length&&n[o+1].key===a[o];)o++;for(;n.length-1>o;)s();for(;n.length-1<a.length;){const c=n[n.length-1];n.push({key:a[n.length-1],nodeKey:uy(c),indices:[],children:[],nextChildIdx:0,claimed:new Set})}const l=n[n.length-1];l.children.push({type:"part",index:i,nodeKey:uy(l),idKey:dy(l,t?.[i])});for(let c=1;c<n.length;c++)n[c].indices.push(i)}for(;n.length>1;)s();return r.children},qL=Object.freeze({type:"complete"}),HL=(e,t,r)=>{if(!r)return!1;switch(e){case"never":return!1;case"always":return!0;case"empty":return t.length===0;case"no-text":{const n=t[t.length-1];return n===void 0||n.type!=="text"&&n.type!=="reasoning"}}},YC=()=>{throw new Error("MessagePrimitive.GroupedParts: rendered `children` under a leaf part. `children` is only meaningful for `group-…` cases — add a matching case for the part type or return `null` to skip it.")},QC=(e,t,r)=>{if(e.type==="part")return u.jsx(WC,{index:e.index,children:({part:s})=>r({part:s,children:u.jsx(YC,{})})},e.idKey?`part-${e.idKey}`:`part-${e.index}`);const n=t[e.indices.at(-1)]?.status??qL;return u.jsx(N.Fragment,{children:r({part:{type:e.key,status:n,indices:e.indices},children:u.jsx(u.Fragment,{children:e.children.map(s=>QC(s,t,r))})})},e.idKey??e.nodeKey)},XC=({groupBy:e,indicator:t="no-text",children:r})=>{const n=Fe(hh(a=>a.message.parts)),s=Fe(a=>a.tools.toolUIs),i=Fe(a=>t==="never"?!1:a.message.status?.type==="running");return u.jsxs(u.Fragment,{children:[Gt(()=>{const a={toolUIs:s};return KL(n.map(o=>e(o,a)??[]),n.map(o=>o.type==="tool-call"?o.toolCallId:void 0))},[n,e[zL]??e,s]).map(a=>QC(a,n,r)),HL(t,n,i)&&r({part:{type:"indicator"},children:u.jsx(YC,{})})]})};XC.displayName="MessagePrimitive.GroupedParts";const GL=e=>{const t=ce(5),{children:r}=e,n=Fe(VC);if(!n)return null;let s;t[0]!==r||t[1]!==n?(s=r(n),t[0]=r,t[1]=n,t[2]=s):s=t[2];let i;return t[3]!==s?(i=u.jsx(u.Fragment,{children:s}),t[3]=s,t[4]=i):i=t[4],i},JC=N.memo(GL);JC.displayName="MessagePrimitive.Quote";const ZC=(e,t)=>{switch(t.type){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:return e?.Attachment}},WL=e=>{const t=ce(5),{components:r}=e,n=Fe(YL);if(!n)return null;const s=n;let i;t[0]!==r||t[1]!==s?(i=ZC(r,s),t[0]=r,t[1]=s,t[2]=i):i=t[2];const a=i;if(!a)return null;let o;return t[3]!==a?(o=u.jsx(a,{}),t[3]=a,t[4]=o):o=t[4],o},eS=N.memo(e=>{const t=ce(5),{index:r,components:n}=e;let s;t[0]!==n?(s=u.jsx(WL,{components:n}
35),t[0]=n,t[1]=s):s=t[1];let i;return t[2]!==r||t[3]!==s?(i=u.jsx(yC,{index:r,children:s}),t[2]=r,t[3]=s,t[4]=i):i=t[4],i},(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);eS.displayName="MessagePrimitive.AttachmentByIndex";const fy=({children:e})=>{const t=Fe(r=>r.message.role!=="user"?0:(r.message.attachments??[]).length);return Gt(()=>Array.from({length:t},(r,n)=>u.jsx(yC,{index:n,children:u.jsx(Ra,{getItemState:s=>s.message().attachment({index:n}).getState(),children:s=>e({get attachment(){return s()}})})},n)),[t,e])},tS=e=>{const t=ce(4),{components:r,children:n}=e;if(r){let i;return t[0]!==r?(i=u.jsx(fy,{children:a=>{const{attachment:o}=a,l=ZC(r,o);return l?u.jsx(l,{}):null}}),t[0]=r,t[1]=i):i=t[1],i}let s;return t[2]!==n?(s=u.jsx(fy,{children:n}),t[2]=n,t[3]=s):s=t[3],s};tS.displayName="MessagePrimitive.Attachments";function YL(e){return e.attachment}const rS=(e,t)=>{switch(t.type){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:return e?.Attachment}},QL=e=>{const t=ce(5),{components:r}=e,n=Fe(XL);if(!n)return null;let s;t[0]!==n||t[1]!==r?(s=rS(r,n),t[0]=n,t[1]=r,t[2]=s):s=t[2];const i=s;
35if(!i)return null;let a;return t[3]!==i?(a=u.jsx(i,{}),t[3]=i,t[4]=a):a=t[4],a},nS=N.memo(e=>{const t=ce(5),{index:r,components:n}=e;let s;t[0]!==n?(s=u.jsx(QL,{components:n}),t[0]=n,t[1]=s):s=t[1];let i;return t[2]!==r||t[3]!==s?(i=u.jsx(vC,{index:r,children:s}),t[2]=r,t[3]=s,t[4]=i):i=t[4],i},(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);nS.displayName="ComposerPrimitive.AttachmentByIndex";const hy=({children:e})=>{const t=Fe(r=>r.composer.attachments.length);return Gt(()=>Array.from({length:t},(r,n)=>u.jsx(vC,{index:n,children:u.jsx(Ra,{getItemState:s=>s.composer().attachment({index:n}).getState(),children:s=>e({get attachment(){return s()}})})},n)),[t,e])},sS=e=>{const t=ce(4),{components:r,children:n}=e;if(r){let i;return t[0]!==r?(i=u.jsx(hy,{children:a=>{const{attachment:o}=a,l=rS(r,o);return l?u.jsx(l,{}):null}}),t[0]=r,t[1]=i):i=t[1],i}let s;return t[2]!==n?(s=u.jsx(hy,{children:n}),t[2]=n,t[3]=s):s=t[3],s};sS.displayName="ComposerPrimitive.Attachments";function XL(e){return e.attachment}const JL=({children:e})=>{const t=Fe(r=>r.composer.queue.length);return Gt(()=>Array.from({length:t},(r,n)=>u.jsx(DD,{index:n,children:u.jsx(Ra,{getItemState:s=>s.composer().queueItem({index:n}).getState(),children:s=>e({get queueItem(){return s()}})})},n)),[t,e])},iS=N.memo(JL);iS.displayName="ComposerPrimitive.Queue";const rm=e=>{const{children:t}=e;return Fe(ZL)?t:null};rm.displayName="MessagePartPrimitive.InProgress";function ZL(e){return e.part.status.type==="running"}const aS=e=>{const t=ce(2),{components:r}=e,n=r.Suggestion;let s;return t[0]!==n?(s=u.jsx(n,{}),t[0]=n,t[1]=s):s=t[1],s},oS=N.memo(e=>{const t=ce(5),{index:r,components:n}=e;let s;t[0]!==n?(s=u.jsx(aS,{components:n}),t[0]=n,t[1]=s):s=t[1];let i;return t[2]!==r||t[3]!==s?(i=u.jsx(bC,{index:r,children:s}),t[2]=r,t[3]=s,t[4]=i):i=t[4],i},(e,t)=>e.index===t.index&&e.components.Suggestion===t.components.Suggestion);oS.displayName="ThreadPrimitive.SuggestionByIndex";const py=({children:e})=>{const t=Fe(r=>r.suggestions.suggestions.length);return Gt(()=>t===0?null:Array.from({length:t},(r,n)=>u.jsx(bC,{index:n,children:u.jsx(Ra,{getItemState:s=>s.suggestions().suggestion({index:n}).getState(),children:s=>e({get suggestion(){return s()}})})},n)),[t,e])},lS=e=>{const t=ce(4),{components:r,children:n}=e;if(r){let i;return t[0]!==r?(i=u.jsx(py,{children:()=>u.jsx(aS,{components:r})}),t[0]=r,t[1]=i):i=t[1],i}let s;return t[2]!==n?(s=u.jsx(py,{children:n}),t[2]=n,t[3]=s):s=t[3],s};lS.displayName="ThreadPrimitive.Suggestions";const e8=N.memo(lS,(e,t)=>e.children||t.children?e.children===t.children:e.components.Suggestion===t.components.Suggestion),t8=e=>{const t=ce(3);let r;return t[0]!==e.dictation||t[1]!==e.editing?(r=n=>{if(e.editing===!0&&!n.composer.isEditing||e.editing===!1&&n.composer.isEditing)return!1;const s=n.composer.dictation!=null;return!(e.dictation===!0&&!s||e.dictation===!1&&s)},t[0]=e.dictation,t[1]=e.editing,t[2]=r):r=t[2],Fe(r)},cS=e=>{const t=ce(3);let r,n;return t[0]!==e?({children:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]),t8(n)?r:null};cS.displayName="ComposerPrimitive.If";const r8=()=>{const e=ce(5),t=vt(),r=Fe(n8);let n;e[0]!==t?(n=a=>{t.composer().send(a)},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={send:s,disabled:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i};function n8(e){return!e.composer.canSend||e.thread.isRunning&&!e.thread.capabilities.queue}const s8=()=>{const e=ce(5),t=vt(),r=Fe(i8);let n;e[0]!==t?(n=()=>{t.composer().cancel()},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==s||e[3]!==r?(i={cancel:s,disabled:r},e[2]=s,e[3]=r,e[4]=i):i=e[4],i};function i8(e){return!e.composer.canCancel}const a8=()=>{const e=ce(5),t=vt(),r=Fe(o8);let n;e[0]!==t?(n=()=>{t.composer().startDictation()},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={startDictation:s,disabled:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i};function o8(e){return e.composer.dictation!=null||!e.thread.capabilities.dictation||!e.composer.isEditing}const l8=()=>{const e=ce(5),t=vt(),r=Fe(c8);let n;e[0]!==t?(n=a=>t.composer().addAttachment(a),e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==s||e[3]!==r?(i={addAttachment:s,disabled:r},e[2]=s,e[3]=r,e[4]=i):i=e[4],i};function c8(e){return!e.composer.isEditing}const u8=e=>{const t=ce(12);let r;t[0]!==e?(r=e===void 0?{}:e,t[0]=e,t[1]=r):r=t[1];const{copiedDuration:n,copyToClipboard:s}=r,i=n===void 0?3e3:n,a=vt(),o=Fe(f8),l=Fe(h8),c=Fe(p8),d=Fe(m8);let f;t[2]!==a||t[3]!==d||t[4]!==i||t[5]!==s||t[6]!==c?(f=()=>{const g=c?d:a.message().getCopyText();if(!g)return;const v=s??g8;Promise.resolve(v(g)).then(()=>{a.message().setIsCopied(!0),setTimeout(()=>a.message().setIsCopied(!1),i)},y8)},t[2]=a,t[3]=d,t[4]=i,t[5]=s,t[6]=c,t[7]=f):f=t[7];const h=f;let m;return t[8]!==h||t[9]!==o||t[10]!==l?(m={copy:h,disabled:o,isCopied:l},t[8]=h,t[9]=o,t[10]=l,t[11]=m):m=t[11],m};function d8(e){return e.type==="text"&&e.text.length>0}function f8(e){return!((e.message.role!=="assistant"||e.message.status?.type!=="running")&&e.message.parts.some(d8))}function h8(e){return e.message.isCopied}function p8(e){return e.composer.isEditing}function m8(e){return e.composer.text}function g8(){}function y8(){}const v8=()=>{const e=ce(5),t=vt(),r=Fe(x8);let n;e[0]!==t?(n=()=>{t.composer().beginEdit()},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={edit:s,disabled:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i};function x8(e){return e.composer.isEditing}const b8=()=>{const e=ce(5),t=vt(),r=Fe(w8);let n;e[0]!==t?(n=()=>{t.message().reload()},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={reload:s,disabled:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i};function w8(e){return e.thread.isRunning||e.thread.isDisabled||e.message.role!=="assistant"}const C8=()=>{const e=ce(5),t=vt(),r=Fe(E8);let n;e[0]!==t?(n=()=>{t.message().submitFeedback({type:"positive"})},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={submit:s,isSubmitted:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i},S8=()=>{const e=ce(5),t=vt(),r=Fe(T8);let n;e[0]!==t?(n=()=>{t.message().submitFeedback({type:"negative"})},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={submit:s,isSubmitted:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i};function E8(e){return e.message.metadata.submittedFeedback?.type==="positive"}function T8(e){return e.message.metadata.submittedFeedback?.type==="negative"}const _8=()=>{const e=ce(5),t=vt(),r=Fe(A8);let n;e[0]!==t?(n=async()=>{t.message().speak()},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={speak:s,disabled:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i};function I8(e){return e.type==="text"&&e.text.length>0}function A8(e){return!((e.message.role!=="assistant"||e.message.status?.type!=="running")&&e.message.parts.some(I8))}const k8=()=>{const e=ce(5),t=vt(),r=Fe(N8);let n;e[0]!==t?(n=()=>{t.message().stopSpeaking()},e[0]=t,e[1]=n):n=e[1];const s=n;let i;return e[2]!==r||e[3]!==s?(i={stopSpeaking:s,disabled:r},e[2]=r,e[3]=s,e[4]=i):i=e[4],i};function N8(e){return e.message.speech==null}const R8=e=>{const t=ce(8),{prompt:r,send:n,clearComposer:s}=e,i=s===void 0?!0:s,a=vt(),o=Fe(P8),l=n??!1;let c;
35t[0]!==a||t[1]!==i||t[2]!==r||t[3]!==l?(c=()=>{const h=a.thread().getState().isRunning;if(l&&!h)a.thread().append({content:[{type:"text",text:r}],runConfig:a.composer().getState().runConfig}),i&&a.composer().setText("");else if(i)a.composer().setText(r);else{const m=a.composer().getState().text;a.composer().setText(m.trim()?`${m} ${r}`:r)}},t[0]=a,t[1]=i,t[2]=r,t[3]=l,t[4]=c):c=t[4];const d=c;let f;return t[5]!==o||t[6]!==d?(f={trigger:d,disabled:o},t[5]=o,t[6]=d,t[7]=f):f=t[7],f};function P8(e){return e.thread.isDisabled}const j8=()=>Fe(B8);function B8(e){return e.message.status?.type==="incomplete"&&e.message.status.reason==="error"?e.message.status.error??"An error occurred":void 0}const D8=e=>{let t=Po;const r=new Map,n=new Set;let s=!1,i=0;const a=()=>{for(const g of n)g()},o=g=>{t=g,m.items=g,a()},l=()=>{if(s||t.length===0)return;const g=t[0],v=r.get(g.id);r.delete(g.id),o(t.slice(1)),v&&(s=!0,e.run(v,{steer:!1}))},c=(g,{steer:v})=>{const w=us(),b=Ro(g);r.set(w,g),o([...t,{id:w,prompt:b}]),v?d(w):l()},d=g=>{if(!r.has(g))return;if(e.cancel&&s){const w=r.get(g);r.delete(g),o(t.filter(b=>b.id!==g)),i++,e.cancel(),s=!0,e.run(w,{steer:!0});return}const v=t.find(w=>w.id===g);v&&(o([v,...t.filter(w=>w.id!==g)]),l())},m={items:t,enqueue:c,steer:d,remove:g=>{r.delete(g)&&o(t.filter(v=>v.id!==g))},clear:()=>{t.length!==0&&(r.clear(),o(Po))}};return{adapter:m,notifyBusy:()=>{s=!0},notifyIdle:()=>{if(i>0){i--;return}s=!1,l()},subscribe:g=>(n.add(g),()=>{n.delete(g)})}},qd=(e,t)=>e.status?.type!=="requires-action"||e.status.reason!=="tool-calls"||e.content.some(r=>r.type==="tool-call"&&r.result===void 0&&r.approval!==void 0&&r.approval.approved===void 0&&r.approval.resolution===void 0)?!1:t===void 0?e.content.every(r=>r.type!=="tool-call"||!!r.result||r.approval!==void 0):e.content.every(r=>r.type!=="tool-call"||!!r.result||r.approval!==void 0||!t.includes(r.toolName));var Hd=class extends Error{constructor(t,r){super(r);q(this,"name","AbortError");q(this,"detach");this.detach=t}},L8=class extends d6{constructor(t,r){super(t);q(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,delete:!1,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1});q(this,"abortController",null);q(this,"_queue",null);q(this,"_queueRunInFlight",!1);q(this,"isDisabled",!1);q(this,"isSendDisabled",!1);q(this,"_isLoading",!1);q(this,"_suggestions",[]);q(this,"_suggestionsController",null);q(this,"_options");q(this,"_lastRunConfig",{});q(this,"_getThreadId");q(this,"_getInitializePromise");q(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}__internal_setGetThreadId(t){this._getThreadId=t}__internal_setGetInitializePromise(t){this._getInitializePromise=t}get extras(){}__internal_setOptions(t){if(this._options===t)return;this._options=t;let r=!1;const n=t.adapters?.speech!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,r=!0);const s=t.adapters?.dictation!==void 0;this.capabilities.dictation!==s&&(this.capabilities.dictation=s,r=!0);const i=t.adapters?.voice!==void 0;this.capabilities.voice!==i&&(this.capabilities.voice=i,r=!0);const a=t.adapters?.attachments!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const o=t.adapters?.feedback!==void 0;this.capabilities.feedback!==o&&(this.capabilities.feedback=o,r=!0);const l=t.adapters?.history?.delete!==void 0;this.capabilities.delete!==l&&(this.capabilities.delete=l,r=!0);const c=t.unstable_enableMessageQueue===!0;c&&!this._queue?(this._queue=D8({run:d=>{this._queueRunInFlight=!0,this._runAppend(d).finally(()=>{this._queueRunInFlight=!1,this._queue?.notifyIdle()}).catch(()=>{})}}),this._queue.subscribe(()=>this._notifySubscribers())):!c&&this._queue&&(this._queue.adapter.clear("cancel-run"),this._queue=null),this.capabilities.queue!==c&&(this.capabilities.queue=c,r=!0),r&&this._notifySubscribers()}__internal_load(){if(this._loadPromise)return this._loadPromise;const t=this.adapters.history?.load()??Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(r=>{if(!r)return;this.repository.import(r),r.messages.length>0&&this.ensureInitialized(),this._notifySubscribers();const n=this.adapters.history?.resume?.bind(this.adapters.history);r.unstable_resume&&n&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},n).catch(()=>{})}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}async append(t){const r=t.parentId===(this.messages.at(-1)?.id??null),n=t.startRun??t.role==="user";if(this._queue&&n&&r){this._queue.adapter.enqueue(t,{steer:t.steer??!1});return}return this._queue&&!r&&this._queue.adapter.clear("edit"),this._runAppend(t)}getQueueItems(){return this._queue?.adapter.items??Po}steerQueueItem(t){this._queue?.adapter.steer(t)}removeQueueItem(t){this._queue?.adapter.remove(t)}async _runAppend(t){this.ensureInitialized();const r=this._getInitializePromise?.();r&&await r;const n=Uc(t,us(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,n),this._options.adapters.history?.append({parentId:t.parentId,message:n,...t.runConfig!==void 0&&{runConfig:t.runConfig}}),t.startRun??t.role==="user"?await this.startRun({parentId:n.id,sourceId:t.sourceId,runConfig:t.runConfig??{}}):(this.repository.resetHead(n.id),this._notifySubscribers())}async deleteMessage(t){const r=this._options.adapters.history;if(!r?.delete)throw new Error("Runtime does not support deleting messages.");const n=this.repository.getMessages(),s=n.findIndex(o=>o.id===t);if(s===-1)throw new Error("Message not found.");const i=n[s],a=[{parentId:n[s-1]?.id??null,message:i}];await r.delete(a),this.repository.deleteMessage(t),this._notifySubscribers()}resumeRun({stream:t,...r}){if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,t)}exportExternalState(){throw new Error("Runtime does not support exporting external states.")}importExternalState(){throw new Error("Runtime does not support importing external states.")}async startRun({parentId:t,runConfig:r},n){this.ensureInitialized();const s={id:us(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};return this._runLoop(t,s,r,n)}async _runLoop(t,r,n,s){this._notifyEventSubscribers("runStart",{});try{this._queue?.notifyBusy(),this._suggestions=[],this._suggestionsController?.abort(),this._suggestionsController=null,this._notifySubscribers();do r=await this.performRoundtrip(t,r,n,s),s=void 0;while(qd(r,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("runEnd",{}),this._queueRunInFlight||queueMicrotask(()=>this._queue?.notifyIdle())}this._suggestionsController=new AbortController;const i=this._suggestionsController.signal;if(this.adapters.suggestion&&r.status?.type!=="requires-action"){const a=this.adapters.suggestion?.generate({messages:this.messages});if(Symbol.asyncIterator in a)for await(const o of a){if(i.aborted)break;this._suggestions=o,this._notifySubscribers()}else{const o=await a;if(i.aborted)return;this._suggestions=o,this._notifySubscribers()}}}async performRoundtrip(t,r,n,s){const i=t?this.repository.getMessages(t):[];this.abortController?.abort(),this.abortController=new AbortController;const a=r.content,o=r.metadata?.unstable_annotations,l=r.metadata?.unstable_data,c=r.metadata?.steps,d=r.metadata?.custom,f=m=>{const g=m.metadata?.steps,v=g?[...c??[],...g]:void 0,w=m.metadata?.unstable_annotations,b=m.metadata?.unstable_data,C=w?[...o??[],...w]:void 0,T=b?[...l??[],...b]:void 0;r={...r,...m.content?{content:[...a,...m.content??[]]}:void 0,status:m.status??r.status,...m.metadata?{metadata:{...r.metadata,...m.metadata.unstable_state?{unstable_state:m.metadata.unstable_state}:void 0,...C?{unstable_annotations:C}:void 0,...T?{unstable_data:T}:void 0,...v?{steps:v}:void 0,...m.metadata?.timing?{timing:m.metadata.timing}:void 0,...m.metadata?.custom?{custom:{...d??{},...m.metadata.custom}}:void 0}}:void 0},this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},h=this._options.maxSteps??2;if((r.metadata?.steps?.length??0)>=h)return f({status:{type:"incomplete",reason:"tool-calls"}}),r;f({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n??{};const{unstable_composerMetadata:m,...g}=this.getModelContext();s=s??this.adapters.chatModel.run.bind(this.adapters.chatModel);const v=this.abortController.signal,w=this._getThreadId?.(),b=s({messages:i,runConfig:this._lastRunConfig,abortSignal:v,context:g,unstable_assistantMessageId:r.id,unstable_threadId:w,unstable_parentId:t,unstable_getMessage(){return r}});if(Symbol.asyncIterator in b)for await(const C of b){if(v.aborted){f({status:{type:"incomplete",reason:"cancelled"}});break}f(C)}else f(await b);r.status.type==="running"&&f({status:{type:"complete",reason:"unknown"}})}catch(m){if(m instanceof Hd)f({status:{type:"incomplete",reason:"cancelled"}});else if(m instanceof Error&&m.name==="AbortError")f({status:{type:"incomplete",reason:"cancelled"}});else throw f({status:{type:"incomplete",reason:"error",error:m instanceof Error?m.message:`[${typeof m}] ${new String(m).toString()}`}}),m}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&await this._options.adapters.history?.append({parentId:t,message:r,runConfig:this._lastRunConfig})}return r}detach(){this._queue?.adapter.clear("cancel-run");const t=new Hd(!0);this.abortController?.abort(t),this.abortController=null}cancelRun(){this._queue?.adapter.clear("cancel-run");const t=new Hd(!1);this.abortController?.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:s,artifact:i}){const a=this.repository.getMessage(t),{parentId:o}=a;let{message:l}=a;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let c=!1,d=!1;const f=l.content.map(h=>h.type!=="tool-call"||h.toolCallId!==r?h:(d=!0,h.result||(c=!0),{...h,result:n,artifact:i,isError:s}));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l={...l,content:f},this.repository.addOrUpdateMessage(o,l),this._notifySubscribers(),c&&qd(l,this._options.unstable_humanToolNames)&&this._runLoop(o,l,this._lastRunConfig).catch(()=>{})}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.")}respondToToolApproval({approvalId:t,approved:r,optionId:n,reason:s}){let i=this.repository.getMessages().findLast(d=>d.role==="assistant"&&d.content.some(f=>f.type==="tool-call"&&f.approval?.id===t));if(!i)throw new Error("Tried to respond to a non-existing tool approval");if(this.abortController!==null)throw new Error("Tried to respond to a tool approval while a run is in progress");if(i.status?.type!=="requires-action")throw new Error("Tried to respond to a tool approval on a message whose status is not requires-action");const a=i.content.find(d=>d.type==="tool-call"&&d.approval?.id===t);if(a?.type!=="tool-call"||!a.approval)throw new Error("Tried to respond to a non-existing tool approval");if(a.approval.resolution!==void 0)throw new Error("Tried to respond to a tool approval that was cancelled or expired");if(a.approval.approved!==void 0)throw new Error("Tried to respond to an already decided tool approval");const o=a.approval,l=i.content.map(d=>{if(d!==a)return d;const f={...o,approved:r,...n!=null&&{optionId:n},...s!=null&&{reason:s}};return r?{...d,approval:f}:{...d,approval:f,result:{error:s||"Tool approval denied"},isError:!0}});i={...i,content:l};const{parentId:c}=this.repository.getMessage(i.id);this.repository.addOrUpdateMessage(c,i),this._notifySubscribers(),this.repository.headId===i.id&&qd(i,this._options.unstable_humanToolNames)&&this._runLoop(c,i,this._lastRunConfig).catch(()=>{})}};const my=Object.freeze([]),mh="__DEFAULT_ID__",M8=Object.freeze({[mh]:{id:mh,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}});var O8=class extends el{constructor(t){super();q(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){}get threadIds(){return my}get archivedThreadIds(){return my}get mainThreadId(){return mh}get threadItems(){return M8}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){return Promise.resolve()}getItemById(t){if(t===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}async switchToThread(){throw new Error("Method not implemented.")}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},F8=class extends kC{constructor(t,r){super();q(this,"threads");q(this,"Provider");q(this,"_options");this._options=t,this.threads=new O8(()=>new L8(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(NC.fromArray(r))}};const U8=(e,{initialMessages:t,...r})=>{const{modelContext:n,...s}=JD()??{},i={...r,adapters:{...s,...r.adapters,chatModel:e}},[a]=pr(()=>new F8(i,t)),o=wt(void 0);return o.current=Fe(l=>l.threadListItem.remoteId),ot(()=>{a.threads.getMainThreadRuntimeCore().__internal_setGetThreadId(()=>o.current)},[a]),ot(()=>()=>{a.threads.getMainThreadRuntimeCore().detach()},[a]),ot(()=>{a.threads.getMainThreadRuntimeCore().__internal_setOptions(i),a.threads.getMainThreadRuntimeCore().__internal_load()}),ot(()=>{if(n)return a.registerModelContextProvider(n)},[n,a]),Gt(()=>new AC(a),[a])},V8=(e,{cloud:t,...r}={})=>x6({runtimeHook:function(){return U8(e,r)},adapter:Q6({cloud:t}),allowNesting:!0}),$8=/:([\w-]{1,64})\[([^\]\n]{1,1024})\](?:\{name=([^}\n]{1,1024})\})?/gu,uS={serialize(e){const t=e.id!==e.label?`{name=${e.id}}`:"";return`:${e.type}[${e.label}]${t}`},parse(e){const t=[];let r=0;for(const n of e.matchAll($8)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});const s=n[2];t.push({kind:"mention",type:n[1],label:s,id:n[3]??s}),r=n.index+n[0].length}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}};function z8(e,t){function r(n){const s=Mn(e);if(!n?.optional&&!s)throw new Error(`This component must be used within ${t}.`);return s}return r}function dS(e,t){function r(s){const i=e(s);return i?i[t]:null}function n(s){let i=!1,a;typeof s=="function"?a=s:s&&typeof s=="object"&&(i=!!s.optional,a=s.selector);const o=r({optional:i});return o?a?o(a):o():null}return{[t]:n,[`${t}Store`]:r}}const fS=Ln(null),{useThreadViewport:Ui,useThreadViewportStore:Vi}=dS(z8(fS,"ThreadPrimitive.Viewport"),"useThreadViewport");let ea;const Gd=()=>
35{if(ea)return ea;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window>"u")return ea=e(),ea;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return ea=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,ea=r,r};var Cn,K8=(Cn=class{static register(t){const r=Gd();for(const o of r.apis.values())if(o.api===t)return()=>{};const n=r.nextId++,s={api:t,logs:[]},i=t.on?.("*",o=>{const l=r.apis.get(n);l&&(l.logs.push({time:new Date,event:o.event,data:o.payload}),l.logs.length>Cn.MAX_EVENT_LOGS_PER_API&&(l.logs=l.logs.slice(-Cn.MAX_EVENT_LOGS_PER_API)),Cn.notifyListeners(n))}),a=t.subscribe?.(()=>{Cn.notifyListeners(n)});return r.apis.set(n,s),Cn.notifyListeners(n),()=>{const o=Gd();o.apis.get(n)&&(i?.(),a?.(),o.apis.delete(n),Cn.notifyListeners(n))}}static notifyListeners(t){Gd().listeners.forEach(r=>r(t))}},q(Cn,"MAX_EVENT_LOGS_PER_API",200),Cn);const gy=e=>{const t=new Map,r=()=>{let n=0;for(const s of t.values())n+=s;e(n)};return{register:()=>{const n=Symbol();return t.set(n,0),{setHeight:s=>{t.get(n)!==s&&(t.set(n,s),r())},unregister:()=>{t.delete(n),r()}}}}},q8=(e={})=>{const t=new Set,r=gy(a=>
35{i.setState({height:{...i.getState().height,viewport:a}})}),n=gy(a=>{i.setState({height:{...i.getState().height,inset:a}})}),s=(a,o)=>(i.setState({element:{...i.getState().element,[a]:o}}),()=>{i.getState().element[a]===o&&i.setState({element:{...i.getState().element,[a]:null}})}),i=ko(()=>({isAtBottom:!0,scrollToBottom:({behavior:a="auto"}={})=>{for(const o of t)o({behavior:a})},onScrollToBottom:a=>(t.add(a),()=>{t.delete(a)}),turnAnchor:e.turnAnchor??"bottom",topAnchorMessageClamp:{tallerThan:e.topAnchorMessageClamp?.tallerThan??"10em",visibleHeight:e.topAnchorMessageClamp?.visibleHeight??"6em"},height:{viewport:0,inset:0},element:{viewport:null,anchor:null,target:null},targetConfig:null,topAnchorTurn:null,registerViewport:r.register,registerContentInset:n.register,registerViewportElement:a=>s("viewport",a),registerAnchorElement:a=>s("anchor",a),registerAnchorTargetElement:(a,o)=>(i.setState({element:{...i.getState().element,target:a},targetConfig:a&&o?o:null}),()=>{i.getState().element.target===a&&i.setState({element:{...i.getState().element,target:null},targetConfig:null})}),setTopAnchorTurn:a=>{i.setState({topAnchorTurn:a})}}));return i},Vc=e=>e,H8=e=>{const t=ce(11);let r;t[0]===Symbol.for("react.memo_cache_sentinel")?(r={optional:!0},t[0]=r):r=t[0];const n=Vi(r);let s;t[1]!==e?(s=()=>q8(e),t[1]=e,t[2]=s):s=t[2];const[i]=pr(s);let a,o;t[3]!==n||t[4]!==i?(a=()=>n?.getState().onScrollToBottom(()=>{i.getState().scrollToBottom()}),o=[n,i],t[3]=n,t[4]=i,t[5]=a,t[6]=o):(a=t[5],o=t[6]),ot(a,o);let l,c;return t[7]!==n||t[8]!==i?(l=()=>{if(n)return i.subscribe(d=>{n.getState().isAtBottom!==d.isAtBottom&&Vc(n).setState({isAtBottom:d.isAtBottom})})},c=[i,n],t[7]=n,t[8]=i,t[9]=l,t[10]=c):(l=t[9],c=t[10]),ot(l,c),i},nm=e=>{const t=ce(7),{children:r,options:n}=e;let s;t[0]!==n?(s=n===void 0?{}:n,t[0]=n,t[1]=s):s=t[1];const i=H8(s);let a;t[2]!==i?(a=()=>({useThreadViewport:i}),t[2]=i,t[3]=a):a=t[3];const[o]=pr(a);let l;return t[4]!==r||t[5]!==o?(l=u.jsx(fS.Provider,{value:o,children:r}),t[4]=r,t[5]=o,t[6]=l):l=t[6],l},G8=()=>{const e=ce(3),t=vt();let r,n;return e[0]!==t?(r=()=>{typeof process>"u"},n=[t],e[0]=t,e[1]=r,e[2]=n):(r=e[1],n=e[2]),ot(r,n),null},W8=e=>{const t=ce(7),{children:r,aui:n,runtime:s}=e,i=n??null;let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=u.jsx(G8,{}),t[0]=a):a=t[0];let o;t[1]!==r?(o=u.jsx(nm,{children:r}),t[1]=r,t[2]=o):o=t[2];let l;return t[3]!==s||t[4]!==i||t[5]!==o?(l=u.jsxs(NB,{runtime:s,aui:i,children:[a,o]}),t[3]=s,t[4]=i,t[5]=o,t[6]=l):l=t[6],l},Y8=N.memo(W8),Q8=e=>{const t=e;t.__isBound||(t.__internal_bindMethods?.(),t.__isBound=!0)};function X8(e,t){const r=ce(4),n=t===void 0?J8:t;Q8(e);let s,i;r[0]!==e||r[1]!==n?(s=()=>n(e.getState()),i=()=>n(e.getState()),r[0]=e,r[1]=n,r[2]=s,r[3]=i):(s=r[2],i=r[3]);const a=Oi(e.subscribe,s,i);return Pw(a),a}const J8=e=>e;function Z8(e){function t(r){let n=!1,s;typeof r=="function"?s=r:r&&(n=!!r.optional,s=r.selector);const i=e({optional:n});return i?X8(i,s):null}return t}function eM(e){const t=ce(2),r=vt();let n;t[0]!==r?(n=()=>r.message.source?r.message().__internal_getRuntime?.()??null:null,t[0]=r,t[1]=n):n=t[1];const s=Fe(n);if(!s&&!e?.optional)throw new Error("MessageRuntime is not available");return s}const wa=Z8(eM);function hS(e){const t=ce(2),r=vt();let n;t[0]!==r?(n=()=>r.thread.source?r.thread().__internal_getRuntime?.()??null:null,t[0]=r,t[1]=n):n=t[1];const s=Fe(n);if(!s&&!e?.optional)throw new Error("ThreadRuntime is not available");return s}var yy=Object.defineProperty,Pu=(e,t)=>{let r={};for(var n in e)yy(r,n,{get:e[n],enumerable:!0});return yy(r,Symbol.toStringTag,{value:"Module"}),r};const tM=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"];function rM(e){const t=N.forwardRef((r,n)=>{const s=ce(17);let i,a,o,l;s[0]!==r?({render:o,asChild:i,children:a,...l}=r,s[0]=r,s[1]=i,s[2]=a,s[3]=o,s[4]=l):(i=s[1],a=s[2],o=s[3],l=s[4]);const c=e;if(o&&N.isValidElement(o)){const h=a!==void 0?a:o.props.children,m=l;let g;s[5]!==o||s[6]!==h?(g=N.cloneElement(o,void 0,h),s[5]=o,s[6]=h,s[7]=g):g=s[7];let v;return s[8]!==n||s[9]!==m||s[10]!==g?(v=u.jsx(c,{...m,asChild:!0,ref:n,children:g}),s[8]=n,s[9]=m,s[10]=g,s[11]=v):v=s[11],v}const d=l;let f;return s[12]!==i||s[13]!==a||s[14]!==n||s[15]!==d?(f=u.jsx(c,{...d,asChild:i,ref:n,children:a}),s[12]=i,s[13]=a,s[14]=n,s[15]=d,s[16]=f):f=s[16],f});return t.displayName=typeof e=="string"?e:e.displayName??e.name??"Component",t}function nM(e){const t=Lr[e],r=rM(t);return r.displayName=`Primitive.${e}`,r}const fr=tM.reduce((e,t)=>
35(e[t]=nM(t),e),{}),sM=e=>{const t=ce(5),{hideWhenRunning:r,autohide:n,autohideFloat:s,forceVisible:i}=e;let a;return t[0]!==n||t[1]!==s||t[2]!==i||t[3]!==r?(a=o=>{if(r&&o.thread.isRunning)return"hidden";const l=n==="always"||n==="not-last"&&!o.message.isLast,c=i||o.message.isHovering;return l?c?s==="always"||s==="single-branch"&&o.message.branchCount<=1?"floating":"normal":"hidden":"normal"},t[0]=n,t[1]=s,t[2]=i,t[3]=r,t[4]=a):a=t[4],Fe(a)},iM=Ln(null),pS=N.forwardRef((e,t)=>{const r=ce(18);let n,s,i,a;r[0]!==e?({hideWhenRunning:i,autohide:n,autohideFloat:s,...a}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i,r[4]=a):(n=r[1],s=r[2],i=r[3],a=r[4]);const[o,l]=pr(0);let c;r[5]===Symbol.for("react.memo_cache_sentinel")?(c=()=>{let C=!1;return l(aM),()=>{C||(C=!0,l(oM))}},r[5]=c):c=r[5];const d=c;let f;r[6]===Symbol.for("react.memo_cache_sentinel")?(f={acquireInteractionLock:d},r[6]=f):f=r[6];const h=f,m=o>0;let g;r[7]!==n||r[8]!==s||r[9]!==i||r[10]!==m?(g={hideWhenRunning:i,autohide:n,autohideFloat:s,forceVisible:m},r[7]=n,r[8]=s,r[9]=i,r[10]=m,r[11]=g):g=r[11];const v=sM(g);if(v==="hidden")return null;let w;r[12]!==v?(w=v==="floating"?{"data-floating":"true"}:null,r[12]=v,r[13]=w):w=r[13];let b;return r[14]!==t||r[15]!==a||r[16]!==w?(b=u.jsx(iM.Provider,{value:h,children:u.jsx(fr.div,{...w,...a,ref:t})}),r[14]=t,r[15]=a,r[16]=w,r[17]=b):b=r[17],b});pS.displayName="ActionBarPrimitive.Root";function aM(e){return e+1}function oM(e){return Math.max(0,e-1)}const lM=e=>{const t=ce(4);let r;t[0]!==e?(r=e===void 0?{}:e,t[0]=e,t[1]=r):r=t[1];const{copiedDuration:n}=r,s=n===void 0?3e3:n;let i;t[2]!==s?(i={copiedDuration:s,copyToClipboard:cM},t[2]=s,t[3]=i):i=t[3];const{copy:a,disabled:o}=u8(i);return o?null:a},mS=N.forwardRef((e,t)=>{const r=ce(20);let n,s,i,a;r[0]!==e?({copiedDuration:n,onClick:i,disabled:s,...a}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i,r[4]=a):(n=r[1],s=r[2],i=r[3],a=r[4]);const o=Fe(uM);let l;r[5]!==n?(l={copiedDuration:n},r[5]=n,r[6]=l):l=r[6];const c=lM(l);let d;r[7]!==o?(d=o?{"data-copied":"true"}:{},r[7]=o,r[8]=d):d=r[8];const f=s||!c;let h;r[9]!==c?(h=()=>{c?.()},r[9]=c,r[10]=h):h=r[10];let m;r[11]!==i||r[12]!==h?(m=Rt(i,h),r[11]=i,r[12]=h,r[13]=m):m=r[13];let g;return r[14]!==t||r[15]!==a||r[16]!==d||r[17]!==f||r[18]!==m?(g=u.jsx(fr.button,{type:"button",...d,...a,ref:t,disabled:f,onClick:m}),r[14]=t,r[15]=a,r[16]=d,r[17]=f,r[18]=m,r[19]=g):g=r[19],g});mS.displayName="ActionBarPrimitive.Copy";function cM(e){return typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("Clipboard API is unavailable")):navigator.clipboard.writeText(e)}function uM(e){return e.message.isCopied}const fs=(e,t,r=[])=>{const n=N.forwardRef((s,i)=>{const a=ce(6),o={},l={};Object.keys(s).forEach(v=>{r.includes(v)?o[v]=s[v]:l[v]=s[v]});const c=t(o)??void 0,d=fr,f="button",h=l.disabled||!c,m=Rt(l.onClick,c);let g;return a[0]!==i||a[1]!==l||a[2]!==d.button||a[3]!==h||a[4]!==m?(g=u.jsx(d.button,{...l,type:f,ref:i,disabled:h,onClick:m}),a[0]=i,a[1]=l,a[2]=d.button,a[3]=h,a[4]=m,a[5]=g):g=a[5],g});return n.displayName=e,n},dM=()=>{const{disabled:e,reload:t}=b8();return e?null:t},fM=fs("ActionBarPrimitive.Reload",dM),hM=()=>{const{disabled:e,edit:t}=v8();return e?null:t},pM=fs("ActionBarPrimitive.Edit",hM),mM=()=>{const{disabled:e,speak:t}=_8();return e?null:t},gM=fs("ActionBarPrimitive.Speak",mM);function gS(e,t=globalThis?.document){const r=ti(e);N.useEffect(()=>{const n=s=>{s.key==="Escape"&&r(s)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}const yM=()=>{const{disabled:e,stopSpeaking:t}=k8();return e?null:t},yS=N.forwardRef((e,t)=>{const r=ce(12),n=yM();let s;r[0]!==n?(s=c=>{n&&(c.preventDefault(),n())},r[0]=n,r[1]=s):s=r[1],gS(s);const i=!n;let a;r[2]!==n?(a=()=>{n?.()},r[2]=n,r[3]=a):a=r[3];let o;r[4]!==e.onClick||r[5]!==a?(o=Rt(e.onClick,a),r[4]=e.onClick,r[5]=a,r[6]=o):o=r[6];let l;return r[7]!==e||r[8]!==t||r[9]!==i||r[10]!==o?(l=u.jsx(fr.button,{type:"button",disabled:i,...e,ref:t,onClick:o}),r[7]=e,r[8]=t,r[9]=i,r[10]=o,r[11]=l):l=r[11],l});yS.displayName="ActionBarPrimitive.StopSpeaking";const vM=()=>{const{submit:e}=C8();return e},vS=N.forwardRef((e,t)=>
35{const r=ce(17);let n,s,i;r[0]!==e?({onClick:s,disabled:n,...i}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i):(n=r[1],s=r[2],i=r[3]);const a=Fe(xM),o=vM();let l;r[4]!==a?(l=a?{"data-submitted":"true"}:{},r[4]=a,r[5]=l):l=r[5];const c=n||!o;let d;r[6]!==o?(d=()=>{o?.()},r[6]=o,r[7]=d):d=r[7];let f;r[8]!==s||r[9]!==d?(f=Rt(s,d),r[8]=s,r[9]=d,r[10]=f):f=r[10];let h;return r[11]!==t||r[12]!==i||r[13]!==l||r[14]!==c||r[15]!==f?(h=u.jsx(fr.button,{type:"button",...l,...i,ref:t,disabled:c,onClick:f}),r[11]=t,r[12]=i,r[13]=l,r[14]=c,r[15]=f,r[16]=h):h=r[16],h});vS.displayName="ActionBarPrimitive.FeedbackPositive";function xM(e){return e.message.metadata.submittedFeedback?.type==="positive"}const bM=()=>{const{submit:e}=S8();return e},xS=N.forwardRef((e,t)=>{const r=ce(17);let n,s,i;r[0]!==e?({onClick:s,disabled:n,...i}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i):(n=r[1],s=r[2],i=r[3]);const a=Fe(wM),o=bM();let l;r[4]!==a?(l=a?{"data-submitted":"true"}:{},r[4]=a,r[5]=l):l=r[5];const c=n||!o;let d;r[6]!==o?(d=()=>{o?.()},r[6]=o,r[7]=d):d=r[7];let f;r[8]!==s||r[9]!==d?(f=Rt(s,d),r[8]=s,r[9]=d,r[10]=f):f=r[10];let h;return r[11]!==t||r[12]!==i||r[13]!==l||r[14]!==c||r[15]!==f?(h=u.jsx(fr.button,{type:"button",...l,...i,ref:t,disabled:c,onClick:f}),r[11]=t,r[12]=i,r[13]=l,r[14]=c,r[15]=f,r[16]=h):h=r[16],h});xS.displayName="ActionBarPrimitive.FeedbackNegative";function wM(e){return e.message.metadata.submittedFeedback?.type==="negative"}const CM=e=>{const t=ce(6);let r;t[0]!==e?(r=e===void 0?{}:e,t[0]=e,t[1]=r):r=t[1];const{filename:n,onExport:s}=r,i=vt(),a=Fe(EM);let o;t[2]!==i||t[3]!==n||t[4]!==s?(o=async()=>{const c=i.message().getCopyText();if(!c)return;if(s){await s(c);return}const d=new Blob([c],{type:"text/markdown"}),f=URL.createObjectURL(d),h=document.createElement("a");h.href=f,h.download=n??`message-${Date.now()}.md`,h.click(),URL.revokeObjectURL(f)},t[2]=i,t[3]=n,t[4]=s,t[5]=o):o=t[5];const l=o;return a?l:null},bS=N.forwardRef((e,t)=>{const r=ce(19);let n,s,i,a,o;r[0]!==e?({filename:s,onExport:a,onClick:i,disabled:n,...o}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i,r[4]=a,r[5]=o):(n=r[1],s=r[2],i=r[3],a=r[4],o=r[5]);let l;r[6]!==s||r[7]!==a?(l={filename:s,onExport:a},r[6]=s,r[7]=a,r[8]=l):l=r[8];const c=CM(l),d=n||!c;let f;r[9]!==c?(f=()=>{c?.()},r[9]=c,r[10]=f):f=r[10];let h;r[11]!==i||r[12]!==f?(h=Rt(i,f),r[11]=i,r[12]=f,r[13]=h):h=r[13];let m;return r[14]!==t||r[15]!==o||r[16]!==d||r[17]!==h?(m=u.jsx(fr.button,{type:"button",...o,ref:t,disabled:d,onClick:h}),r[14]=t,r[15]=o,r[16]=d,r[17]=h,r[18]=m):m=r[18],m});bS.displayName="ActionBarPrimitive.ExportMarkdown";function SM(e){return e.type==="text"&&e.text.length>0}function EM(e){return(e.message.role!=="assistant"||e.message.status?.type!=="running")&&e.message.parts.some(SM)}var Wd=Pu({Copy:()=>mS,Edit:()=>pM,ExportMarkdown:()=>bS,FeedbackNegative:()=>xS,FeedbackPositive:()=>vS,Reload:()=>fM,Root:()=>pS,Speak:()=>gM,StopSpeaking:()=>yS});const TM=e=>{const t=ce(12);let r;return t[0]!==e.assistant||t[1]!==e.copied||t[2]!==e.hasAttachments||t[3]!==e.hasBranches||t[4]!==e.hasContent||t[5]!==e.last||t[6]!==e.lastOrHover||t[7]!==e.speaking||t[8]!==e.submittedFeedback||t[9]!==e.system||t[10]!==e.user?(r=n=>{const{role:s,attachments:i,parts:a,branchCount:o,isLast:l,speech:c,isCopied:d,isHovering:f}=n.message;return!(e.hasBranches===!0&&o<2||e.user&&s!=="user"||e.assistant&&s!=="assistant"||e.system&&s!=="system"||e.lastOrHover===!0&&!f&&!l||e.last!==void 0&&e.last!==l||e.copied===!0&&!d||e.copied===!1&&d||e.speaking===!0&&c==null||e.speaking===!1&&c!=null||e.hasAttachments===!0&&(s!=="user"||!i?.length)||e.hasAttachments===!1&&s==="user"&&i?.length||e.hasContent===!0&&a.length===0||e.hasContent===!1&&a.length>0||e.submittedFeedback!==void 0&&(n.message.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)},t[0]=e.assistant,t[1]=e.copied,t[2]=e.hasAttachments,t[3]=e.hasBranches,t[4]=e.hasContent,t[5]=e.last,t[6]=e.lastOrHover,t[7]=e.speaking,t[8]=e.submittedFeedback,t[9]=e.system,t[10]=e.user,t[11]=r):r=t[11],Fe(r)},wS=e=>{const t=ce(3);let r,n;return t[0]!==e?({children:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]),TM(n)?r:null};wS.displayName="MessagePrimitive.If";const CS=Ln(null),sm=()=>Mn(CS),_M=e=>{const t=ce(8),{children:r}=e;let n;t[0]===Symbol.for("react.memo_cache_sentinel")?(n=new Map,t[0]=n):n=t[0];const s=wt(n);let i;t[1]===Symbol.for("react.memo_cache_sentinel")?(i=[],t[1]=i):i=t[1];const a=wt(i);let o;t[2]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{const w=Array.from(s.current.entries());w.sort(IM),a.current=w.map(AM)},t[2]=o):o=t[2];const l=o;let c;t[3]===Symbol.for("react.memo_cache_sentinel")?(c=(w,b)=>{const C=b?.priority??0;
35return s.current.set(w,C),l(),()=>{s.current.delete(w),l()}},t[3]=c):c=t[3];const d=c;let f;t[4]===Symbol.for("react.memo_cache_sentinel")?(f=()=>a.current,t[4]=f):f=t[4];const h=f;let m;t[5]===Symbol.for("react.memo_cache_sentinel")?(m={register:d,getPlugins:h},t[5]=m):m=t[5];const g=m;let v;return t[6]!==r?(v=u.jsx(CS.Provider,{value:g,children:r}),t[6]=r,t[7]=v):v=t[7],v};function IM(e,t){return t[1]-e[1]}function AM(e){const[t]=e;return t}const im=Ln(null),SS=Ln(null),am=()=>{const e=Mn(im);if(!e)throw new Error("useTriggerPopoverRootContext must be used within ComposerPrimitive.TriggerPopoverRoot");return e},om=()=>Mn(im),kM=()=>{const e=Mn(SS);if(!e)throw new Error("useTriggerPopoverAriaPublish must be used within ComposerPrimitive.TriggerPopoverRoot");return e},NM=()=>{const e=am();return Oi(e.subscribe,e.getTriggers,e.getTriggers)},RM=new Map,ES=()=>()=>{},vy=()=>RM,PM=()=>{const e=om();return Oi(e?e.subscribe:ES,e?e.getTriggers:vy,e?e.getTriggers:vy)},xy=()=>null,jM=()=>{const e=om();return Oi(e?e.subscribeAria:ES,e?e.getActiveAria:xy,e?e.getActiveAria:xy)};function by(){const e=ce(4);let t;e[0]===Symbol.for("react.memo_cache_sentinel")?(t=new Set,e[0]=t):t=e[0];const r=wt(t);let n;e[1]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{for(const l of r.current)l()},e[1]=n):n=e[1];const s=n;let i;e[2]===Symbol.for("react.memo_cache_sentinel")?(i=l=>(r.current.add(l),()=>{r.current.delete(l)}),e[2]=i):i=e[2];const a=i;let o;return e[3]===Symbol.for("react.memo_cache_sentinel")?(o={notify:s,subscribe:a},e[3]=o):o=e[3],o}const wy=e=>{const t=ce(21),{children:r}=e;let n;t[0]===Symbol.for("react.memo_cache_sentinel")?(n=new Map,t[0]=n):n=t[0];const s=wt(n);let i;t[1]===Symbol.for("react.memo_cache_sentinel")?(i=new Set,t[1]=i):i=t[1];const a=wt(i),{notify:o,subscribe:l}=by();let c;t[2]!==o?(c=Q=>{const{char:J}=Q;if(s.current.has(J))return BM;const oe=new Map(s.current);oe.set(J,Q),s.current=oe,o();for(const xe of a.current)xe.added(Q);return()=>{const xe=new Map(s.current);xe.delete(J),s.current=xe,o();for(const ge of a.current)ge.removed(J)}},t[2]=o,t[3]=c):c=t[3];const d=c;let f;t[4]===Symbol.for("react.memo_cache_sentinel")?(f=()=>s.current,t[4]=f):f=t[4];const h=f;let m;t[5]===Symbol.for("react.memo_cache_sentinel")?(m=Q=>(a.current.add(Q),()=>{a.current.delete(Q)}),t[5]=m):m=t[5];const g=m,v=wt(null),w=wt(null),{notify:b,subscribe:C}=by();let T;t[6]!==b?(T=(Q,J)=>{if(J===null){if(w.current!==Q)return;v.current=null,w.current=null,b();return}const oe=v.current;w.current===Q&&oe!==null&&oe.popoverId===J.popoverId&&oe.highlightedItemId===J.highlightedItemId||(v.current=J,w.current=Q,b())},t[6]=b,t[7]=T):T=t[7];const I=T;let k;t[8]===Symbol.for("react.memo_cache_sentinel")?(k=()=>v.current,t[8]=k):k=t[8];const _=k;let M;
35t[9]!==d||t[10]!==l||t[11]!==C?(M={register:d,getTriggers:h,subscribe:l,subscribeLifecycle:g,getActiveAria:_,subscribeAria:C},t[9]=d,t[10]=l,t[11]=C,t[12]=M):M=t[12];const V=M;let G;t[13]!==I?(G={setActiveAria:I},t[13]=I,t[14]=G):G=t[14];const L=G;let H;t[15]!==L||t[16]!==r?(H=u.jsx(SS.Provider,{value:L,children:r}),t[15]=L,t[16]=r,t[17]=H):H=t[17];let F;return t[18]!==H||t[19]!==V?(F=u.jsx(im.Provider,{value:V,children:H}),t[18]=H,t[19]=V,t[20]=F):F=t[20],F},TS=e=>{const t=ce(4),{children:r}=e;if(sm()){let s;return t[0]!==r?(s=u.jsx(wy,{children:r}),t[0]=r,t[1]=s):s=t[1],s}let n;return t[2]!==r?(n=u.jsx(_M,{children:u.jsx(wy,{children:r})}),t[2]=r,t[3]=n):n=t[3],n};TS.displayName="ComposerPrimitive.TriggerPopoverRoot";function BM(){}const Cy=/\s/u;function DM(e,t,r){const n=e.slice(0,r);for(let s=n.length-1;s>=0;s--){const i=n[s];if(Cy.test(i))return null;if(n.startsWith(t,s)){if(s>0&&!Cy.test(n[s-1]))continue;return{query:n.slice(s+t.length),offset:s}}}return null}const LM=e=>{const t=ce(7),{text:r,triggerChar:n}=e,[s,i]=pr(r.length),a=Math.min(s,r.length);let o;t[0]!==a||t[1]!==r||t[2]!==n?(o=DM(r,n,a),t[0]=a,t[1]=r,t[2]=n,t[3]=o):o=t[3];const l=o,c=l?.query??"";let d;return t[4]!==c||t[5]!==l?(d={trigger:l,query:c,setCursorPosition:i},t[4]=c,t[5]=l,t[6]=d):d=t[6],d},MM=qt(LM);function OM(e){return"type"in e}const FM=e=>{const t=ce(25),{navigableList:r,isSearchMode:n,activeCategoryId:s,query:i,popoverId:a,open:o,selectItem:l,selectCategory:c,goBack:d,close:f}=e,[h,m]=pr(0);let g;t[0]===Symbol.for("react.memo_cache_sentinel")?(g=()=>{m(0)},t[0]=g):g=t[0];let v;t[1]!==r?(v=[r],t[1]=r,t[2]=v):v=t[2],ot(g,v);let w;t[3]===Symbol.for("react.memo_cache_sentinel")?(w=()=>{m(0)},t[3]=w):w=t[3];let b;t[4]!==s||t[5]!==n?(b=[n,s],t[4]=s,t[5]=n,t[6]=b):b=t[6],ot(w,b);let C;t[7]!==h||t[8]!==r.length?(C=G=>{G<0||G>=r.length||G!==h&&m(G)},t[7]=h,t[8]=r.length,t[9]=C):C=t[9];const T=kn(C);let I;t[10]!==s||t[11]!==f||t[12]!==d||t[13]!==h||t[14]!==r||t[15]!==o||t[16]!==i||t[17]!==c||t[18]!==l?(I=G=>{if(!o)return!1;switch(G.key){case"ArrowDown":return G.preventDefault(),m(L=>{const H=r.length;return H===0?0:L<H-1?L+1:0}),!0;case"ArrowUp":return G.preventDefault(),m(L=>{const H=r.length;return H===0?0:L>0?L-1:H-1}),!0;
35case"Enter":case"Tab":{if(G.shiftKey)return!1;G.preventDefault();const L=r[h];return L&&(OM(L)?l(L):c(L.id)),!0}case"Escape":return G.preventDefault(),f(),!0;case"Backspace":return s&&i===""?(G.preventDefault(),d(),!0):!1;default:return!1}},t[10]=s,t[11]=f,t[12]=d,t[13]=h,t[14]=r,t[15]=o,t[16]=i,t[17]=c,t[18]=l,t[19]=I):I=t[19];const k=kn(I),_=r[h],M=o&&_?`${a}-option-${_.id}`:void 0;let V;return t[20]!==k||t[21]!==T||t[22]!==h||t[23]!==M?(V={highlightedIndex:h,highlightedItemId:M,highlightIndex:T,handleKeyDown:k},t[20]=k,t[21]=T,t[22]=h,t[23]=M,t[24]=V):V=t[24],V},UM=qt(FM);function Sy(e,t){return e.id.toLowerCase().includes(t)||e.label.toLowerCase().includes(t)||(e.description?.toLowerCase().includes(t)??!1)}const VM=e=>{const t=ce(38),{adapter:r,query:n,open:s}=e,[i,a]=pr(null);let o,l;t[0]!==s?(o=()=>{s||a(null)},l=[s],t[0]=s,t[1]=o,t[2]=l):(o=t[1],l=t[2]),ot(o,l);let c;e:{if(!s||!r){let Q;t[3]===Symbol.for("react.memo_cache_sentinel")?(Q=[],t[3]=Q):Q=t[3],c=Q;break e}let F;t[4]!==r?(F=r.categories(),t[4]=r,t[5]=F):F=t[5],c=F}const d=c,f=s?i:null;let h;e:{if(!f||!r){let Q;t[6]===Symbol.for("react.memo_cache_sentinel")?(Q=[],t[6]=Q):Q=t[6],h=Q;break e}let F;t[7]!==r||t[8]!==f?(F=r.categoryItems(f),t[7]=r,t[8]=f,t[9]=F):F=t[9],h=F}const m=h;let g;e:{if(!s||!r||f){g=null;break e}if(!n&&d.length>0){g=null;break e}if(r.search){let Q;t[10]!==r||t[11]!==n?(Q=r.search(n),t[10]=r,t[11]=n,t[12]=Q):Q=t[12],g=Q;break e}let F;if(t[13]!==r||t[14]!==d||t[15]!==n){F=[];const Q=n.toLowerCase();for(const J of d)for(const oe of r.categoryItems(J.id))Sy(oe,Q)&&F.push(oe);t[13]=r,t[14]=d,t[15]=n,t[16]=F}else F=t[16];g=F}const v=g,w=v!==null;let b;e:{if(w){let Q;t[17]===Symbol.for("react.memo_cache_sentinel")?(Q=[],t[17]=Q):Q=t[17],b=Q;break e}if(!n){b=d;break e}let F;if(t[18]!==d||t[19]!==n){const Q=n.toLowerCase();F=d.filter(J=>J.label.toLowerCase().includes(Q)),t[18]=d,t[19]=n,t[20]=F}else F=t[20];b=F}const C=b;let T;e:{if(w){let Q;t[21]!==v?(Q=v??[],t[21]=v,t[22]=Q):Q=t[22],T=Q;break e}if(!n){T=m;break e}let F;if(t[23]!==m||t[24]!==n){const Q=n.toLowerCase();F=m.filter(J=>Sy(J,Q)),t[23]=m,t[24]=n,t[25]=F}else F=t[25];T=F}const I=T;let k;e:{if(w){let F;t[26]!==v?(F=v??[],t[26]=v,t[27]=F):F=t[27],k=F;break e}if(f){k=I;break e}k=C}const _=k;let M;t[28]===Symbol.for("react.memo_cache_sentinel")?(M=F=>{a(F)},t[28]=M):M=t[28];const V=kn(M);let G;t[29]===Symbol.for("react.memo_cache_sentinel")?(G=()=>{a(null)},t[29]=G):G=t[29];const L=kn(G);let H;return t[30]!==f||t[31]!==C||t[32]!==I||t[33]!==L||t[34]!==w||t[35]!==_||t[36]!==V?(H={categories:C,items:I,isSearchMode:w,activeCategoryId:f,navigableList:_,selectCategory:V,goBack:L},t[30]=f,t[31]=C,t[32]=I,t[33]=L,t[34]=w,t[35]=_,t[36]=V,t[37]=H):H=t[37],H},$M=qt(VM),zM=e=>{const t=ce(15),{behavior:r,trigger:n,aui:s,triggerChar:i,setCursorPosition:a,onSelected:o}=e,l=wt(null);let c;t[0]===Symbol.for("react.memo_cache_sentinel")?(c=w=>(l.current=w,()=>{l.current===w&&(l.current=null)}),t[0]=c):c=t[0];const d=kn(c);let f;t[1]!==s||t[2]!==r||t[3]!==o||t[4]!==n||t[5]!==i?(f=w=>{if(!n||!r)return;if(l.current?.(w)){o();return}const b=s.composer().getState().text,C=b.slice(0,n.offset),T=b.slice(n.offset+i.length+n.query.length),I=()=>{const k=r.formatter.serialize(w);s.composer().setText(C+k+(T.startsWith(" ")?T:` ${T}`))};r.kind==="directive"?(I(),r.onInserted?.(w)):(r.removeOnExecute?s.composer().setText(C+(T.startsWith(" ")?T.slice(1):T)):I(),r.onExecute(w)),o()},t[1]=s,t[2]=r,t[3]=o,t[4]=n,t[5]=i,t[6]=f):f=t[6];const h=kn(f);let m;t[7]!==o||t[8]!==a||t[9]!==n?(m=()=>{o(),n&&a(n.offset)},t[7]=o,t[8]=a,t[9]=n,t[10]=m):m=t[10];const g=kn(m);let v;return t[11]!==g||t[12]!==d||t[13]!==h?(v={selectItem:h,close:g,registerSelectItemOverride:d},t[11]=g,t[12]=d,t[13]=h,t[14]=v):v=t[14],v},KM=qt(zM),qM=e=>{const t=ce(46),{adapter:r,text:n,triggerChar:s,behavior:i,aui:a,popoverId:o,isLoading:l}=e;let c;t[0]!==n||t[1]!==s?(c=MM({text:n,triggerChar:s}),t[0]=n,t[1]=s,t[2]=c):c=t[2];const d=sn(c),f=d.trigger!==null&&r!==void 0&&i!==void 0;let h;t[3]!==r||t[4]!==d.query||t[5]!==f?(h=$M({adapter:r,query:d.query,open:f}),t[3]=r,t[4]=d.query,t[5]=f,t[6]=h):h=t[6];const m=sn(h);let g;t[7]!==m?(g=()=>{m.goBack()},t[7]=m,t[8]=g):g=t[8];const v=kn(g);let w;t[9]!==a||t[10]!==i||t[11]!==d.setCursorPosition||t[12]!==d.trigger||t[13]!==v||t[14]!==s?(w=KM({behavior:i,trigger:d.trigger,aui:a,triggerChar:s,setCursorPosition:d.setCursorPosition,onSelected:v}),t[9]=a,t[10]=i,t[11]=d.setCursorPosition,t[12]=d.trigger,t[13]=v,t[14]=s,t[15]=w):w=t[15];const b=sn(w);let C;t[16]!==d.query||t[17]!==m.activeCategoryId||t[18]!==m.goBack||t[19]!==m.isSearchMode||t[20]!==m.navigableList||t[21]!==m.selectCategory||t[22]!==f||t[23]!==o||t[24]!==b.close||t[25]!==b.selectItem?(C=UM({navigableList:m.navigableList,isSearchMode:m.isSearchMode,activeCategoryId:m.activeCategoryId,query:d.query,popoverId:o,open:f,selectItem:b.selectItem,selectCategory:m.selectCategory,goBack:m.goBack,close:b.close}),t[16]=d.query,t[17]=m.activeCategoryId,t[18]=m.goBack,t[19]=m.isSearchMode,t[20]=m.navigableList,t[21]=m.selectCategory,t[22]=f,t[23]=o,t[24]=b.close,t[25]=b.selectItem,t[26]=C):C=t[26];const T=sn(C);let I;return t[27]!==d.query||t[28]!==d.setCursorPosition||t[29]!==l||t[30]!==T.handleKeyDown||t[31]!==T.highlightIndex||t[32]!==T.highlightedIndex||t[33]!==T.highlightedItemId||t[34]!==m.activeCategoryId||t[35]!==m.categories||t[36]!==m.goBack||t[37]!==m.isSearchMode||t[38]!==m.items||t[39]!==m.selectCategory||t[40]!==f||t[41]!==o||t[42]!==b.close||t[43]!==b.registerSelectItemOverride||t[44]!==b.selectItem?(I={open:f,query:d.query,activeCategoryId:m.activeCategoryId,categories:m.categories,items:m.items,highlightedIndex:T.highlightedIndex,isSearchMode:m.isSearchMode,isLoading:l,popoverId:o,highlightedItemId:T.highlightedItemId,selectCategory:m.selectCategory,goBack:m.goBack,selectItem:b.selectItem,close:b.close,highlightIndex:T.highlightIndex,handleKeyDown:T.handleKeyDown,setCursorPosition:d.setCursorPosition,registerSelectItemOverride:b.registerSelectItemOverride},t[27]=d.query,t[28]=d.setCursorPosition,t[29]=l,t[30]=T.handleKeyDown,t[31]=T.highlightIndex,t[32]=T.highlightedIndex,t[33]=T.highlightedItemId,t[34]=m.activeCategoryId,t[35]=m.categories,t[36]=m.goBack,t[37]=m.isSearchMode,t[38]=m.items,t[39]=m.selectCategory,t[40]=f,t[41]=o,t[42]=b.close,t[43]=b.registerSelectItemOverride,t[44]=b.selectItem,t[45]=I):I=t[45],I},HM=qt(qM),lm=Ln(null),ja=()=>{const e=Mn(lm);if(!e)throw new Error("useTriggerPopoverScopeContext must be used within ComposerPrimitive.TriggerPopover");return e},GM=()=>Mn(lm),_S=Ln(null),IS=()=>{const e=Mn(_S);if(!e)throw new Error("TriggerPopover.Directive / TriggerPopover.Action must be rendered inside ComposerPrimitive.TriggerPopover");return e},AS=N.forwardRef((e,t)=>
35{const r=ce(61);let n,s,i,a,o,l;r[0]!==e?({char:i,adapter:n,isLoading:l,"aria-label":s,children:a,...o}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i,r[4]=a,r[5]=o,r[6]=l):(n=r[1],s=r[2],i=r[3],a=r[4],o=r[5],l=r[6]);const c=l===void 0?!1:l,d=vt(),f=Fe(WM),h=N.useId(),m=wt(null),[g,v]=pr(null),w=wt(0);let b;r[7]!==i?(b=pt=>(w.current=w.current+1,m.current=pt,v(pt),()=>{w.current=Math.max(0,w.current-1),m.current===pt&&(m.current=null,v(null))}),r[7]=i,r[8]=b):b=r[8];const C=b;let T;r[9]!==C?(T={register:C},r[9]=C,r[10]=T):T=r[10];const I=T,k=g??void 0;let _;r[11]!==n||r[12]!==d||r[13]!==i||r[14]!==c||r[15]!==h||r[16]!==k||r[17]!==f?(_=HM({adapter:n,text:f,triggerChar:i,behavior:k,aui:d,popoverId:h,isLoading:c}),r[11]=n,r[12]=d,r[13]=i,r[14]=c,r[15]=h,r[16]=k,r[17]=f,r[18]=_):_=r[18];const M=sn(_);let V;r[19]!==M?(V=()=>M,r[19]=M,r[20]=V):V=r[20];const G=kn(V),L=am();let H;r[21]!==g||r[22]!==i||r[23]!==G||r[24]!==L?(H=()=>L.register({char:i,...g?{behavior:g}:{},resource:G()}),r[21]=g,r[22]=i,r[23]=G,r[24]=L,r[25]=H):H=r[25];let F;r[26]!==g||r[27]!==i||r[28]!==L?(F=[L,i,g],r[26]=g,r[27]=i,r[28]=L,r[29]=F):F=r[29],ot(H,F);const Q=sm();let J;r[30]!==G||r[31]!==Q?(J=()=>{if(Q)return Q.register(G())},r[30]=G,r[31]=Q,r[32]=J):J=r[32];let oe;r[33]!==Q?(oe=[Q],r[33]=Q,r[34]=oe):oe=r[34],ot(J,oe);const xe=g!==null&&M.open,ge=kM();let $,le;r[35]!==ge||r[36]!==i||r[37]!==xe?($=()=>{if(xe)return()=>{ge.setActiveAria(i,null)}},le=[ge,i,xe],r[35]=ge,r[36]=i,r[37]=xe,r[38]=$,r[39]=le):($=r[38],le=r[39]),ot($,le);let B,Te;r[40]!==ge||r[41]!==i||r[42]!==xe||r[43]!==h||r[44]!==M.highlightedItemId?(B=()=>{xe&&ge.setActiveAria(i,{popoverId:h,highlightedItemId:M.highlightedItemId})},Te=[ge,i,h,xe,M.highlightedItemId],r[40]=ge,r[41]=i,r[42]=xe,r[43]=h,r[44]=M.highlightedItemId,r[45]=B,r[46]=Te):(B=r[45],Te=r[46]),ot(B,Te);let ye;r[47]!==s||r[48]!==a||r[49]!==t||r[50]!==xe||r[51]!==h||r[52]!==o||r[53]!==M.highlightedItemId?(ye=xe?u.jsx(fr.div,{role:"listbox",id:h,"aria-label":s??"Suggestions","aria-activedescendant":M.highlightedItemId,"data-state":"open",...o,ref:t,children:a}):a,r[47]=s,r[48]=a,r[49]=t,r[50]=xe,r[51]=h,r[52]=o,r[53]=M.highlightedItemId,r[54]=ye):ye=r[54];let U;r[55]!==M||r[56]!==ye?(U=u.jsx(lm.Provider,{value:M,children:ye}),r[55]=M,r[56]=ye,r[57]=U):U=r[57];let Qe;return r[58]!==I||r[59]!==U?(Qe=u.jsx(_S.Provider,{value:I,children:U}),r[58]=I,r[59]=U,r[60]=Qe):Qe=r[60],Qe});AS.displayName="ComposerPrimitive.TriggerPopover";function WM(e){return e.composer.text}const kS=()=>{const e=ce(2),{disabled:t,send:r}=r8();let n;e[0]!==r?(n=()=>r(),e[0]=r,e[1]=n):n=e[1];const s=n;return t?null:s},YM=fs("ComposerPrimitive.Send",kS),NS=N.forwardRef((e,t)=>{const r=ce(12);let n,s;r[0]!==e?({onSubmit:n,...s}=e,r[0]=e,r[1]=n,r[2]=s):(n=r[1],s=r[2]);const i=kS();let a;r[3]!==i?(a=d=>{d.preventDefault(),i&&i()},r[3]=i,r[4]=a):a=r[4];const o=a;let l;r[5]!==o||r[6]!==n?(l=Rt(n,o),r[5]=o,r[6]=n,r[7]=l):l=r[7];let c;return r[8]!==t||r[9]!==s||r[10]!==l?(c=u.jsx(fr.form,{...s,ref:t,onSubmit:l}),r[8]=t,r[9]=s,r[10]=l,r[11]=c):c=r[11],c});NS.displayName="ComposerPrimitive.Root";
35const RS=e=>{const t=ce(4),r=ti(e),n=Ui(QM);let s,i;t[0]!==r||t[1]!==n?(s=()=>n(r),i=[n,r],t[0]=r,t[1]=n,t[2]=s,t[3]=i):(s=t[2],i=t[3]),ot(s,i)};function QM(e){return e.onScrollToBottom}const XM=()=>!1,JM=()=>{},PS=e=>{const t=ce(4);let r;t[0]!==e?(r=i=>{if(typeof window>"u"||e===null||!window.matchMedia)return JM;const a=window.matchMedia(e);return a.addEventListener("change",i),()=>a.removeEventListener("change",i)},t[0]=e,t[1]=r):r=t[1];const n=r;let s;return t[2]!==e?(s=()=>typeof window>"u"||e===null||!window.matchMedia?!1:window.matchMedia(e).matches,t[2]=e,t[3]=s):s=t[3],Oi(n,s,XM)};function ZM(){return Fe(eO)}function eO(e){return e.composer.isEditing?e.composer.text:""}function tO(e){return!!Fe(rO)||!!e}function rO(e){return e.thread.isDisabled||e.composer.dictation?.inputDisabled}function nO(){const e=ce(4),t=jM();if(!t){let n;return e[0]===Symbol.for("react.memo_cache_sentinel")?(n={},e[0]=n):n=e[0],n}let r;return e[1]!==t.highlightedItemId||e[2]!==t.popoverId?(r={"aria-controls":t.popoverId,"aria-expanded":!0,"aria-haspopup":"listbox","aria-activedescendant":t.highlightedItemId},e[1]=t.highlightedItemId,e[2]=t.popoverId,e[3]=r):r=e[3],r}var sO=N.useLayoutEffect,iO=function(t){var r=_e.useRef(t);return sO(function(){r.current=t}),r},Ey=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},aO=function(t,r){var n=_e.useRef();return _e.useCallback(function(s){t.current=s,n.current&&Ey(n.current,null),n.current=r,r&&Ey(r,s)},[r])},Ty={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},oO=function(t){Object.keys(Ty).forEach(function(r){t.style.setProperty(r,Ty[r],"important")})},_y=oO,Kr=null,Iy=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function lO(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),Kr||(Kr=document.createElement("textarea"),Kr.setAttribute("tabindex","-1"),Kr.setAttribute("aria-hidden","true"),_y(Kr)),Kr.parentNode===null&&document.body.appendChild(Kr);var s=e.paddingSize,i=e.borderSize,a=e.sizingStyle,o=a.boxSizing;Object.keys(a).forEach(function(h){var m=h;Kr.style[m]=a[m]}),_y(Kr),Kr.value=t;var l=Iy(Kr,e);Kr.value=t,l=Iy(Kr,e),Kr.value="x";var c=Kr.scrollHeight-s,d=c*r;o==="border-box"&&(d=d+s+i),l=Math.max(d,l);var f=c*n;return o==="border-box"&&(f=f+s+i),l=Math.min(f,l),[l,c]}var Ay=function(){},cO=function(t,r){return t.reduce(function(n,s){return n[s]=r[s],n},{})},uO=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],dO=!!document.documentElement.currentStyle,fO=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=cO(uO,r),s=n.boxSizing;if(s==="")return null;dO&&s==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var i=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),a=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:i,borderSize:a}},hO=fO;function cm(e,t,r){var n=iO(r);N.useLayoutEffect(function(){var s=function(a){return n.current(a)};if(e)return e.addEventListener(t,s),function(){return e.removeEventListener(t,s)}},[])}var pO=function(t,r){cm(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},mO=function(t){cm(window,"resize",t)},gO=function(t){cm(document.fonts,"loadingdone",t)},yO=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],vO=function(t,r){var n=t.cacheMeasurements,s=t.maxRows,i=t.minRows,a=t.onChange,o=a===void 0?Ay:a,l=t.onHeightChange,c=l===void 0?Ay:l,d=dT(t,yO),f=d.value!==void 0,h=N.useRef(null),m=aO(h,r),g=N.useRef(0),v=N.useRef(),w=function(){var T=h.current,I=n&&v.current?v.current:hO(T);if(I){v.current=I;var k=lO(I,T.value||T.placeholder||"x",i,s),_=k[0],M=k[1];g.current!==_&&(g.current=_,T.style.setProperty("height",_+"px","important"),c(_,{rowHeight:M}))}},b=function(T){f||w(),o(T)};
35return N.useLayoutEffect(w),pO(h,function(){if(!f){var C=h.current.value;requestAnimationFrame(function(){var T=h.current;T&&C!==T.value&&w()})}}),mO(w),gO(w),N.createElement("textarea",fT({},d,{onChange:b,ref:m}))},xO=N.forwardRef(vO);const bO="(pointer: coarse) and (not (any-pointer: fine))",jS=N.forwardRef(({autoFocus:e=!1,asChild:t,render:r,disabled:n,onChange:s,onKeyDown:i,onPaste:a,onSelect:o,submitOnEnter:l,submitMode:c,cancelOnEscape:d=!0,unstable_focusOnRunStart:f=!0,unstable_focusOnScrollToBottom:h=!0,unstable_focusOnThreadSwitched:m=!0,unstable_insertNewlineOnTouchEnter:g=!1,addAttachmentOnPaste:v=!0,...w},b)=>{const C=vt(),T=sm(),I=c??(l===!1?"none":"enter"),k=PS(g?bO:null),_=g&&k&&I==="enter"?"none":I,M=ZM(),V=tO(n),G=wt(null),L=on(b,G),H=wt(!1);gS($=>{if(!G.current?.contains($.target))return;if(T){for(const B of T.getPlugins())if(B.handleKeyDown($))return}if(!d)return;const le=C.composer();le.getState().canCancel&&(le.cancel(),$.preventDefault())});const F=$=>{if(!V&&!$.nativeEvent.isComposing){if(T){for(const le of T.getPlugins())if(le.handleKeyDown($))return}if($.key==="Enter"){const le=C.thread().getState(),B=le.capabilities.queue;if($.shiftKey&&($.ctrlKey||$.metaKey)&&B&&I!=="none"&&C.composer().getState().canSend){$.preventDefault(),C.composer().send({steer:!0});return}if($.shiftKey||le.isRunning&&!B)return;let Te=!1;_==="ctrlEnter"?Te=$.ctrlKey||$.metaKey:_==="enter"&&(Te=!0),Te&&($.preventDefault(),G.current?.closest("form")?.requestSubmit())}}},Q=async $=>{if(!v)return;const le=C.thread().getState().capabilities,B=Array.from($.clipboardData?.files||[]);if(le.attachments&&B.length>0)try{$.preventDefault(),await Promise.all(B.map(Te=>C.composer().addAttachment(Te)))}catch(Te){console.error("Error adding attachment:",Te)}},J=e&&!V,oe=Zs(()=>{const $=G.current;!$||!J||($.focus({preventScroll:!0}),$.setSelectionRange($.value.length,$.value.length))},[J]);ot(()=>oe(),[oe]),RS(()=>{C.composer().getState().type==="thread"&&h&&oe()}),ot(()=>{if(!(C.composer().getState().type!=="thread"||!f))return C.on("thread.runStart",oe)},[f,oe,C]),ot(()=>{if(!(C.composer().getState().type!=="thread"||!m))return C.on("threadListItem.switchedTo",oe)},[m,oe,C]);const xe=nO(),ge={name:"input",value:M,...w,...xe,ref:L,disabled:V,onChange:Rt(s,$=>{if(!C.composer().getState().isEditing)return;const le=$.nativeEvent.isComposing===!0;H.current&&!le&&(H.current=!1);const B=le||H.current;if(S0(()=>{C.composer().setText($.target.value)}),B)return;const Te=$.target.selectionStart??$.target.value.length;if(T)for(const ye of T.getPlugins())ye.setCursorPosition(Te)}),onKeyDown:Rt(i,F),onCompositionStart:Rt(w.onCompositionStart,()=>{H.current=!0}),onCompositionEnd:Rt(w.onCompositionEnd,$=>{if(H.current=!1,!C.composer().getState().isEditing)return;const le=$.target;S0(()=>{C.composer().setText(le.value)});const B=le.selectionStart??le.value.length;if(T)for(const Te of T.getPlugins())Te.setCursorPosition(B)}),onSelect:Rt(o,$=>{if(H.current)return;const le=$.target,B=le.selectionStart??le.value.length;if(T)for(const Te of T.getPlugins())Te.setCursorPosition(B)}),onPaste:Rt(a,Q)};if(r&&N.isValidElement(r)){const $=w.children!==void 0?w.children:r.props.children;return u.jsx(Co,{...ge,children:N.cloneElement(r,void 0,$)})}return u.jsx(t?Co:xO,{...ge})});jS.displayName="ComposerPrimitive.Input";const wO=()=>{const{disabled:e,cancel:t}=s8();return e?null:t},CO=fs("ComposerPrimitive.Cancel",wO),SO=e=>{const t=ce(6);let r;t[0]!==e?(r=e===void 0?{}:e,t[0]=e,t[1]=r):r=t[1];const{multiple:n}=r,s=n===void 0?!0:n,{disabled:i,addAttachment:a}=l8(),o=vt();let l;t[2]!==a||t[3]!==o||t[4]!==s?(l=()=>{const d=document.createElement("input");d.type="file",d.multiple=s,d.hidden=!0;const f=o.composer().getState().attachmentAccept;f!=="*"&&(d.accept=f),document.body.appendChild(d),d.onchange=h=>{const m=h.target.files;if(m){for(const g of m)a(g);document.body.removeChild(d)}},d.oncancel=()=>{(!d.files||d.files.length===0)&&document.body.removeChild(d)},d.click()},t[2]=a,t[3]=o,t[4]=s,t[5]=l):l=t[5];const c=l;return i?null:c},EO=fs("ComposerPrimitive.AddAttachment",SO,["multiple"]),BS=N.forwardRef((e,t)=>
35{const r=ce(30),{disabled:n,asChild:s,render:i,children:a,...o}=e,l=s===void 0?!1:s,[c,d]=pr(!1),f=vt();let h;r[0]!==n?(h=Q=>{n||(Q.preventDefault(),d(!0))},r[0]=n,r[1]=h):h=r[1];const m=h;let g;r[2]!==n||r[3]!==c?(g=Q=>{n||(Q.preventDefault(),c||d(!0))},r[2]=n,r[3]=c,r[4]=g):g=r[4];const v=g;let w;r[5]!==n?(w=Q=>{if(n)return;Q.preventDefault();const J=Q.relatedTarget;J&&Q.currentTarget.contains(J)||d(!1)},r[5]=n,r[6]=w):w=r[6];const b=w;let C;r[7]!==f||r[8]!==n?(C=async Q=>{if(n)return;Q.preventDefault(),d(!1);const J=Array.from(Q.dataTransfer.files);await Promise.all(J.map(async oe=>{try{await f.composer().addAttachment(oe)}catch(xe){console.error("Failed to add attachment:",xe)}}))},r[7]=f,r[8]=n,r[9]=C):C=r[9];const T=C;let I;r[10]!==c?(I=c?{"data-dragging":"true"}:null,r[10]=c,r[11]=I):I=r[11];const k=Rt(o.onDragEnterCapture,m),_=Rt(o.onDragOverCapture,v),M=Rt(o.onDragLeaveCapture,b),V=Rt(o.onDropCapture,T);let G;r[12]!==t||r[13]!==o||r[14]!==V||r[15]!==I||r[16]!==k||r[17]!==_||r[18]!==M?(G={...I,...o,onDragEnterCapture:k,onDragOverCapture:_,onDragLeaveCapture:M,onDropCapture:V,ref:t},r[12]=t,r[13]=o,r[14]=V,r[15]=I,r[16]=k,r[17]=_,r[18]=M,r[19]=G):G=r[19];const L=G;if(i&&N.isValidElement(i)){const Q=a!==void 0?a:i.props.children;let J;r[20]!==i||r[21]!==Q?(J=N.cloneElement(i,void 0,Q),r[20]=i,r[21]=Q,r[22]=J):J=r[22];let oe;return r[23]!==L||r[24]!==J?(oe=u.jsx(Co,{...L,children:J}),r[23]=L,r[24]=J,r[25]=oe):oe=r[25],oe}const H=l?Co:"div";let F;return r[26]!==H||r[27]!==a||r[28]!==L?(F=u.jsx(H,{...L,children:a}),r[26]=H,r[27]=a,r[28]=L,r[29]=F):F=r[29],F});BS.displayName="ComposerPrimitive.AttachmentDropzone";const TO=()=>{const{disabled:e,startDictation:t}=a8();return e?null:t},_O=fs("ComposerPrimitive.Dictate",TO),IO=()=>{const e=ce(2),t=vt(),r=Fe(kO);let n;e[0]!==t?(n=()=>{t.composer().stopDictation()},e[0]=t,e[1]=n):n=e[1];const s=n;return r?s:null},AO=fs("ComposerPrimitive.StopDictation",IO);function kO(e){return e.composer.dictation!=null}const DS=N.forwardRef((e,t)=>{const r=ce(7);let n,s;r[0]!==e?({children:n,...s}=e,r[0]=e,r[1]=n,r[2]=s):(n=r[1],s=r[2]);const i=Fe(NO);if(!i)return null;const a=n??i;let o;return r[3]!==t||r[4]!==s||r[5]!==a?(o=u.jsx(fr.span,{...s,ref:t,children:a}),r[3]=t,r[4]=s,r[5]=a,r[6]=o):o=r[6],o});DS.displayName="ComposerPrimitive.DictationTranscript";function NO(e){return e.composer.dictation?.transcript}const LS=N.forwardRef((e,t)=>{const r=ce(3);if(!Fe(RO))return null;let n;return r[0]!==t||r[1]!==e?(n=u.jsx(fr.div,{...e,ref:t}),r[0]=t,r[1]=e,r[2]=n):n=r[2],n});LS.displayName="ComposerPrimitive.Quote";const MS=N.forwardRef((e,t)=>{const r=ce(7);let n,s;r[0]!==e?({children:n,...s}=e,r[0]=e,r[1]=n,r[2]=s):(n=r[1],s=r[2]);const i=Fe(PO);if(!i)return null;const a=n??i;let o;return r[3]!==t||r[4]!==s||r[5]!==a?(o=u.jsx(fr.span,{...s,ref:t,children:a}),r[3]=t,r[4]=s,r[5]=a,r[6]=o):o=r[6],o});MS.displayName="ComposerPrimitive.QuoteText";const OS=N.forwardRef((e,t)=>{const r=ce(12);let n,s;r[0]!==e?({onClick:n,...s}=e,r[0]=e,r[1]=n,r[2]=s):(n=r[1],s=r[2]);const i=vt();let a;r[3]!==i?(a=()=>{i.composer().setQuote(void 0)},r[3]=i,r[4]=a):a=r[4];const o=a;let l;r[5]!==o||r[6]!==n?(l=Rt(n,o),r[5]=o,r[6]=n,r[7]=l):l=r[7];let c;return r[8]!==t||r[9]!==s||r[10]!==l?(c=u.jsx(fr.button,{type:"button",...s,ref:t,onClick:l}),r[8]=t,r[9]=s,r[10]=l,r[11]=c):c=r[11],c});OS.displayName="ComposerPrimitive.QuoteDismiss";function RO(e){return e.composer.quote}function PO(e){return e.composer.quote?.text}const FS=N.forwardRef((e,t)=>{const r=ce(12);let n,s,i;r[0]!==e?({children:s,"aria-label":n,...i}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i):(n=r[1],s=r[2],i=r[3]);const{categories:a,activeCategoryId:o,isSearchMode:l,open:c}=ja();if(!c||o||l)return null;const d=n??"Categories";let f;r[4]!==a||r[5]!==s?(f=s(a),r[4]=a,r[5]=s,r[6]=f):f=r[6];let h;return r[7]!==t||r[8]!==i||r[9]!==d||r[10]!==f?(h=u.jsx(fr.div,{role:"group","aria-label":d,...i,ref:t,children:f}),r[7]=t,r[8]=i,r[9]=d,r[10]=f,r[11]=h):h=r[11],h});FS.displayName="ComposerPrimitive.TriggerPopoverCategories";const US=N.forwardRef((e,t)=>{const r=ce(30);let n,s,i,a;r[0]!==e?({categoryId:n,onClick:s,onMouseMove:i,...a}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i,r[4]=a):(n=r[1],s=r[2],i=r[3],a=r[4]);const{selectCategory:o,highlightIndex:l,categories:c,highlightedIndex:d,activeCategoryId:f,isSearchMode:h,popoverId:m}=ja();let g;r[5]!==n||r[6]!==o?(g=()=>{o(n)},r[5]=n,r[6]=o,r[7]=g):g=r[7];const v=g;let w;if(r[8]!==c||r[9]!==n){let L;r[11]!==n?(L=H=>H.id===n,r[11]=n,r[12]=L):L=r[12],w=c.findIndex(L),r[8]=c,r[9]=n,r[10]=w}else w=r[10];const b=w,C=!f&&!h&&b===d;let T;r[13]!==b||r[14]!==l?(T=()=>{l(b)},r[13]=b,r[14]=l,r[15]=T):T=r[15];const I=T,k=`${m}-option-${n}`,_=C?"":void 0;let M;r[16]!==v||r[17]!==s?(M=Rt(s,v),r[16]=v,r[17]=s,r[18]=M):M=r[18];let V;r[19]!==I||r[20]!==i?(V=Rt(i,I),r[19]=I,r[20]=i,r[21]=V):V=r[21];let G;return r[22]!==t||r[23]!==C||r[24]!==a||r[25]!==k||r[26]!==_||r[27]!==M||r[28]!==V?(G=u.jsx(fr.button,{type:"button",role:"option",id:k,"aria-selected":C,"data-highlighted":_,...a,ref:t,onClick:M,onMouseMove:V}),r[22]=t,r[23]=C,r[24]=a,r[25]=k,r[26]=_,r[27]=M,r[28]=V,r[29]=G):G=r[29],G});US.displayName="ComposerPrimitive.TriggerPopoverCategoryItem";const VS=N.forwardRef((e,t)=>
35{const r=ce(12);let n,s,i;r[0]!==e?({children:s,"aria-label":n,...i}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i):(n=r[1],s=r[2],i=r[3]);const{items:a,activeCategoryId:o,isSearchMode:l,open:c}=ja();if(!c||!o&&!l)return null;const d=n??"Items";let f;r[4]!==s||r[5]!==a?(f=s(a),r[4]=s,r[5]=a,r[6]=f):f=r[6];let h;return r[7]!==t||r[8]!==i||r[9]!==d||r[10]!==f?(h=u.jsx(fr.div,{role:"group","aria-label":d,...i,ref:t,children:f}),r[7]=t,r[8]=i,r[9]=d,r[10]=f,r[11]=h):h=r[11],h});VS.displayName="ComposerPrimitive.TriggerPopoverItems";const $S=N.forwardRef((e,t)=>{const r=ce(30);let n,s,i,a,o;r[0]!==e?({item:s,index:n,onClick:i,onMouseMove:a,...o}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i,r[4]=a,r[5]=o):(n=r[1],s=r[2],i=r[3],a=r[4],o=r[5]);const{selectItem:l,highlightIndex:c,items:d,highlightedIndex:f,activeCategoryId:h,isSearchMode:m,popoverId:g}=ja();let v;r[6]!==s||r[7]!==l?(v=()=>{l(s)},r[6]=s,r[7]=l,r[8]=v):v=r[8];const w=v;let b;r[9]!==n||r[10]!==s.id||r[11]!==d?(b=n??d.findIndex(H=>H.id===s.id),r[9]=n,r[10]=s.id,r[11]=d,r[12]=b):b=r[12];const C=b,T=(m||h!==null)&&C===f;let I;r[13]!==c||r[14]!==C?(I=()=>{c(C)},r[13]=c,r[14]=C,r[15]=I):I=r[15];const k=I,_=`${g}-option-${s.id}`,M=T?"":void 0;let V;r[16]!==w||r[17]!==i?(V=Rt(i,w),r[16]=w,r[17]=i,r[18]=V):V=r[18];let G;r[19]!==k||r[20]!==a?(G=Rt(a,k),r[19]=k,r[20]=a,r[21]=G):G=r[21];let L;return r[22]!==t||r[23]!==T||r[24]!==o||r[25]!==_||r[26]!==M||r[27]!==V||r[28]!==G?(L=u.jsx(fr.button,{type:"button",role:"option",id:_,"aria-selected":T,"data-highlighted":M,...o,ref:t,onClick:V,onMouseMove:G}),r[22]=t,r[23]=T,r[24]=o,r[25]=_,r[26]=M,r[27]=V,r[28]=G,r[29]=L):L=r[29],L});$S.displayName="ComposerPrimitive.TriggerPopoverItem";const zS=N.forwardRef((e,t)=>{const r=ce(10);let n,s;r[0]!==e?({onClick:n,...s}=e,r[0]=e,r[1]=n,r[2]=s):(n=r[1],s=r[2]);const{activeCategoryId:i,isSearchMode:a,goBack:o,open:l}=ja();if(!l||!i||a)return null;let c;r[3]!==o||r[4]!==n?(c=Rt(n,o),r[3]=o,r[4]=n,r[5]=c):c=r[5];let d;return r[6]!==t||r[7]!==s||r[8]!==c?(d=u.jsx(fr.button,{type:"button",...s,ref:t,onClick:c}),r[6]=t,r[7]=s,r[8]=c,r[9]=d):d=r[9],d});zS.displayName="ComposerPrimitive.TriggerPopoverBack";const KS=({formatter:e,onExecute:t,removeOnExecute:r})=>{const{register:n}=IS(),s=wt(t);return s.current=t,ot(()=>n({kind:"action",formatter:e??uS,onExecute:i=>s.current(i),...r!==void 0?{removeOnExecute:r}:{}}),[n,e,r]),null};KS.displayName="ComposerPrimitive.TriggerPopoverAction";const qS=({formatter:e,onInserted:t})=>{const{register:r}=IS(),n=wt(t);return n.current=t,ot(()=>r({kind:"directive",formatter:e??uS,onInserted:s=>n.current?.(s)}),[r,e]),null};qS.displayName="ComposerPrimitive.TriggerPopoverDirective";const jO=Object.assign(AS,{Directive:qS,Action:KS});var ql=Pu({AddAttachment:()=>EO,AttachmentByIndex:()=>nS,AttachmentDropzone:()=>BS,Attachments:()=>sS,Cancel:()=>CO,Dictate:()=>_O,DictationTranscript:()=>DS,If:()=>cS,Input:()=>jS,Queue:()=>iS,Quote:()=>LS,QuoteDismiss:()=>OS,QuoteText:()=>MS,Root:()=>NS,Send:()=>YM,StopDictation:()=>AO,Unstable_TriggerPopover:()=>jO,Unstable_TriggerPopoverBack:()=>zS,Unstable_TriggerPopoverCategories:()=>FS,Unstable_TriggerPopoverCategoryItem:()=>US,Unstable_TriggerPopoverItem:()=>$S,Unstable_TriggerPopoverItems:()=>VS,Unstable_TriggerPopoverRoot:()=>TS,unstable_useTriggerPopoverRootContext:()=>am,unstable_useTriggerPopoverRootContextOptional:()=>om,unstable_useTriggerPopoverScopeContext:()=>ja,unstable_useTriggerPopoverScopeContextOptional:()=>GM,unstable_useTriggerPopoverTriggers:()=>NM,unstable_useTriggerPopoverTriggersOptional:()=>PM});const BO=()=>Fe(DO);function DO(e){if(e.part.type!=="text"&&e.part.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return e.part}const LO=Ln(null);function MO(e){const t=Mn(LO);if(!e?.optional&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}const{useSmoothStatus:YH,useSmoothStatusStore:OO}=dS(MO,"useSmoothStatus"),HS=250,GS=5;var FO=class{constructor(e,t){q(this,"currentText");q(this,"setText");q(this,"animationFrameId",null);q(this,"lastUpdateTime",Date.now());q(this,"lastCommitTime",0);q(this,"targetText","");q(this,"drainMs",HS);q(this,"maxCharIntervalMs",GS);q(this,"maxCharsPerFrame",1/0);q(this,"minCommitMs",0);q(this,"animate",()=>{const e=Date.now();let t=e-this.lastUpdateTime;const r=this.targetText.length-this.currentText.length,n=Math.min(this.maxCharIntervalMs,this.drainMs/r),s=Math.min(r,this.maxCharsPerFrame);let i=0;for(;t>=n&&i<s;)i++,t-=n;i===s&&s===this.maxCharsPerFrame&&(t=0),i!==r?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),this.lastUpdateTime=e-t,(i===r||e-this.lastCommitTime>=this.minCommitMs)&&(this.lastCommitTime=e,this.setText(this.currentText)))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}};const Yd=Object.freeze({type:"running"}
35),Hl=(e,t)=>e!==void 0&&e>0?e:t,UO=(e,t=!1)=>{const{text:r}=e,n=PS("(prefers-reduced-motion: reduce)"),s=typeof t=="object"&&t!==null?t:void 0,i=t!==!1&&t!==null&&!n,a=Hl(s?.drainMs,HS),o=Hl(s?.maxCharIntervalMs,GS),l=Hl(s?.maxCharsPerFrame,1/0),c=Hl(s?.minCommitMs,0),[d,f]=pr(e.status.type==="running"?"":r),h=vt(),m=Fe(()=>h.part()),[g,v]=pr(m);(m!==g||!r.startsWith(d))&&(v(m),f(e.status.type==="running"?"":r));const w=OO({optional:!0}),b=ti(I=>{if(f(I),w){const k=d!==I||e.status.type==="running"?Yd:e.status;Vc(w).setState(k,!0)}});ot(()=>{if(w){const I=i&&(d!==r||e.status.type==="running")?Yd:e.status;Vc(w).setState(I,!0)}},[w,i,r,d,e.status]);const[C]=pr(new FO(d,b));ot(()=>{C.drainMs=a,C.maxCharIntervalMs=o,C.maxCharsPerFrame=l,C.minCommitMs=c},[C,a,o,l,c]);const T=wt(m);return ot(()=>{if(!i){C.stop();return}const I=T.current!==m;if(T.current=m,I||!r.startsWith(C.targetText)){e.status.type==="running"?(C.currentText="",C.targetText=r,C.lastCommitTime=0,C.start()):(C.currentText=r,C.targetText=r,C.stop());return}C.targetText=r,C.start()},[C,i,r,e.status.type,m]),ot(()=>()=>{C.stop()},[C]),Gt(()=>i?{...e,text:d,status:r===d?e.status:Yd}:e,[i,d,e,r])},VO=()=>Fe($O);function $O(e){if(e.part.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return e.part}const um=N.forwardRef((e,t)=>{const r=ce(10);let n,s,i;r[0]!==e?({smooth:s,component:i,...n}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i):(n=r[1],s=r[2],i=r[3]);const a=s===void 0?!0:s,o=i===void 0?"span":i,{text:l,status:c}=UO(BO(),a);let d;return r[4]!==o||r[5]!==t||r[6]!==n||r[7]!==c.type||r[8]!==l?(d=u.jsx(o,{"data-status":c.type,...n,ref:t,children:l}),r[4]=o,r[5]=t,r[6]=n,r[7]=c.type,r[8]=l,r[9]=d):d=r[9],d});um.displayName="MessagePartPrimitive.Text";const dm=N.forwardRef((e,t)=>{const r=ce(4),{image:n}=VO();let s;return r[0]!==t||r[1]!==n||r[2]!==e?(s=u.jsx(fr.img,{src:n,...e,ref:t}),r[0]=t,r[1]=n,r[2]=e,r[3]=s):s=r[3],s});dm.displayName="MessagePartPrimitive.Image";const $i=e=>{const t=ce(2),r=wt(void 0);let n;return t[0]!==e?(n=s=>{r.current&&(r.current(),r.current=void 0),s&&(r.current=e(s))},t[0]=e,t[1]=n):n=t[1],n},ky=(e,t)=>{const r=e.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(em|px|rem)$/);if(!r)return Number.POSITIVE_INFINITY;const n=Number(r[1]),s=r[2];return s==="px"?n:s==="em"?n*(parseFloat(getComputedStyle(t).fontSize)||16):s==="rem"?n*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16):Number.POSITIVE_INFINITY},zO=e=>e.dataset.messageId,KO=()=>{const e=document.createElement("div");return e.dataset.auiTopAnchorReserve="",e.style.height="0px",e.style.flexShrink="0",e.style.pointerEvents="none",e.setAttribute("aria-hidden","true"),e},Ny=(e,t)=>{const r=`${t}px`;return e.style.height!==r?(e.style.height=r,!0):!1},qO=e=>{const t=window.devicePixelRatio||1;return Math.round(e*t)/t},WS=()=>{const e=ce(4),t=vt();let r;e[0]!==t?(r=()=>t.message(),e[0]=t,e[1]=r):r=e[1];const n=Fe(r);let s;return e[2]!==n?(s=i=>{const a=()=>{n.setIsHovering(!0)},o=()=>{n.setIsHovering(!1)};return i.addEventListener("mouseenter",a),i.addEventListener("mouseleave",o),i.matches(":hover")&&queueMicrotask(()=>n.setIsHovering(!0)),()=>{i.removeEventListener("mouseenter",a),i.removeEventListener("mouseleave",o),n.setIsHovering(!1)}},e[2]=n,e[3]=s):s=e[3],$i(s)},HO=()=>{const e=ce(2),t=Ui(JO);let r;return e[0]!==t?(r=n=>n.message.role==="user"&&n.message.index>0&&n.message.index===n.thread.messages.length-2&&n.thread.messages.at(-1)?.role==="assistant"&&(n.message.id===t||n.thread.isRunning),e[0]=t,e[1]=r):r=e[1],Fe(r)},GO=()=>{const e=ce(2),t=Ui(ZO);let r;return e[0]!==t?(r=n=>n.message.isLast&&n.message.role==="assistant"&&n.message.index>=1&&n.thread.messages.at(n.message.index-1)?.role==="user"&&(n.message.id===t||n.thread.isRunning),e[0]=t,e[1]=r):r=e[1],Fe(r)},WO=(e,t)=>{const r=ce(3);let n;return r[0]!==e||r[1]!==t?(n=s=>{if(e)return t.getState().registerAnchorElement(s)},r[0]=e,r[1]=t,r[2]=n):n=r[2],$i(n)},YO=e=>{const t=ce(3),{active:r,threadViewportStore:n}=e;let s;return t[0]!==r||t[1]!==n?(s=i=>{if(!r)return;const a=n.getState(),o=a.topAnchorMessageClamp;return a.registerAnchorTargetElement(i,{tallerThan:ky(o.tallerThan,i),visibleHeight:ky(o.visibleHeight,i)})},t[0]=r,t[1]=n,t[2]=s):s=t[2],$i(s)},QO=e=>{const t=ce(7);let r,n;t[0]!==e?({forwardedRef:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]);const s=WS(),i=on(r,s),a=Fe(eF);let o;return t[3]!==a||t[4]!==n||t[5]!==i?(o=u.jsx(fr.div,{...n,ref:i,"data-message-id":a}),t[3]=a,t[4]=n,t[5]=i,t[6]=o):o=t[6],o},XO=e=>{const t=ce(13);let r,n,s;t[0]!==e?({forwardedRef:r,threadViewportStore:s,...n}=e,t[0]=e,t[1]=r,t[2]=n,t[3]=s):(r=t[1],n=t[2],s=t[3]);const i=WS(),a=HO(),o=GO(),l=WO(a,s);let c;t[4]!==o||t[5]!==s?(c={active:o,threadViewportStore:s},t[4]=o,t[5]=s,t[6]=c):c=t[6];const d=YO(c),f=on(r,i,l,d),h=Fe(tF),m=a?"":void 0,g=o?"":void 0;let v;return t[7]!==h||t[8]!==n||t[9]!==f||t[10]!==m||t[11]!==g?(v=u.jsx(fr.div,{...n,ref:f,"data-message-id":h,"data-aui-top-anchor-user":m,"data-aui-top-anchor-target":g}),t[7]=h,t[8]=n,t[9]=f,t[10]=m,t[11]=g,t[12]=v):v=t[12],v},YS=N.forwardRef((e,t)=>
35{const r=ce(7),n=Vi();if(n.getState().turnAnchor==="top"){let i;return r[0]!==t||r[1]!==e||r[2]!==n?(i=u.jsx(XO,{...e,forwardedRef:t,threadViewportStore:n}),r[0]=t,r[1]=e,r[2]=n,r[3]=i):i=r[3],i}let s;return r[4]!==t||r[5]!==e?(s=u.jsx(QO,{...e,forwardedRef:t}),r[4]=t,r[5]=e,r[6]=s):s=r[6],s});YS.displayName="MessagePrimitive.Root";function JO(e){return e.topAnchorTurn?.anchorId}function ZO(e){return e.topAnchorTurn?.targetId}function eF(e){return e.message.id}function tF(e){return e.message.id}const Qd={...Ur,Text:()=>u.jsxs("p",{style:{whiteSpace:"pre-line"},children:[u.jsx(um,{}),u.jsx(rm,{children:u.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Image:()=>u.jsx(dm,{})},gh=e=>{const t=ce(10);if("children"in e){let o;return t[0]!==e.children?(o=u.jsx(ph,{children:e.children}),t[0]=e.children,t[1]=o):o=t[1],o}let r,n;t[2]!==e?({components:r,...n}=e,t[2]=e,t[3]=r,t[4]=n):(r=t[3],n=t[4]);let s;t[5]!==r?(s=r?{Text:r.Text??Qd.Text,Image:r.Image??Qd.Image,Reasoning:r.Reasoning??Ur.Reasoning,Source:r.Source??Ur.Source,File:r.File??Ur.File,Unstable_Audio:r.Unstable_Audio??Ur.Unstable_Audio,..."ChainOfThought"in r?{ChainOfThought:r.ChainOfThought}:{tools:r.tools,data:r.data,ToolGroup:r.ToolGroup??Ur.ToolGroup,ReasoningGroup:r.ReasoningGroup??Ur.ReasoningGroup},Empty:r.Empty,Quote:r.Quote,generativeUI:r.generativeUI}:Qd,t[5]=r,t[6]=s):s=t[6];const i=s;let a;return t[7]!==n||t[8]!==i?(a=u.jsx(ph,{components:i,...n}),t[7]=n,t[8]=i,t[9]=a):a=t[9],a};gh.displayName="MessagePrimitive.Parts";const QS=e=>{const{children:t}=e;return j8()!==void 0?t:null};QS.displayName="MessagePrimitive.Error";const rF=e=>{const t=new Map;for(let n=0;n<e.length;n++){const s=e[n]?.parentId??`__ungrouped_${n}`,i=t.get(s)??[];i.push(n),t.set(s,i)}const r=[];for(const[n,s]of t){const i=n.startsWith("__ungrouped_")?void 0:n;r.push({groupKey:i,indices:s})}return r},nF=e=>{const t=ce(4),r=Fe(hF);let n;e:{if(r.length===0){let i;t[0]===Symbol.for("react.memo_cache_sentinel")?(i=[],t[0]=i):i=t[0],n=i;break e}let s;t[1]!==e||t[2]!==r?(s=e(r),t[1]=e,t[2]=r,t[3]=s):s=t[3],n=s}return n},sF=e=>{const t=ce(9);let r,n;t[0]!==e?({Fallback:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]);let s;t[3]!==r||t[4]!==n.toolName?(s=o=>{const l=o.tools.tools[n.toolName]??r;return Array.isArray(l)?l[0]??r:l},t[3]=r,t[4]=n.toolName,t[5]=s):s=t[5];const i=Fe(s);if(!i)return null;let a;return t[6]!==i||t[7]!==n?(a=u.jsx(i,{...n}),t[6]=i,t[7]=n,t[8]=a):a=t[8],a},iF=e=>{const t=ce(9);let r,n;t[0]!==e?({Fallback:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]);let s;t[3]!==r||t[4]!==n.name?(s=o=>{const l=o.dataRenderers.renderers[n.name]??r;return Array.isArray(l)?l[0]??r:l},t[3]=r,t[4]=n.name,t[5]=s):s=t[5];const i=Fe(s);if(!i)return null;let a;return t[6]!==i||t[7]!==n?(a=u.jsx(i,{...n}),t[6]=i,t[7]=n,t[8]=a):a=t[8],a},Vs={Text:()=>u.jsxs("p",{style:{whiteSpace:"pre-line"},children:[u.jsx(um,{}),u.jsx(rm,{children:u.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>u.jsx(dm,{}),File:()=>null,Unstable_Audio:()=>null,Group:({children:e})=>e},aF=e=>{const t=ce(43),{components:r}=e;let n;t[0]!==r?(n=r===void 0?{}:r,t[0]=r,t[1]=n):n=t[1];const{Text:s,Reasoning:i,Image:a,Source:o,File:l,Unstable_Audio:c,tools:d,data:f}=n,h=s===void 0?Vs.Text:s,m=i===void 0?Vs.Reasoning:i,g=a===void 0?Vs.Image:a,v=o===void 0?Vs.Source:o,w=l===void 0?Vs.File:l,b=c===void 0?Vs.Unstable_Audio:c;let C;t[2]!==d?(C=d===void 0?{}:d,t[2]=d,t[3]=C):C=t[3];const T=C,I=vt(),k=Fe(pF),_=k.type;if(_==="tool-call"){let M;t[4]!==I?(M=I.part(),t[4]=I,t[5]=M):M=t[5];const V=M.addToolResult;let G;t[6]!==I?(G=I.part(),t[6]=I,t[7]=G):G=t[7];const L=G.resumeToolCall;let H;t[8]!==I?(H=I.part(),t[8]=I,t[9]=H):H=t[9];const F=H.respondToToolApproval;if("Override"in T){let oe;return t[10]!==V||t[11]!==k||t[12]!==F||t[13]!==L||t[14]!==T.Override?(oe=u.jsx(T.Override,{...k,addResult:V,resume:L,respondToApproval:F}),t[10]=V,t[11]=k,t[12]=F,t[13]=L,t[14]=T.Override,t[15]=oe):oe=t[15],oe}const Q=T.by_name?.[k.toolName]??T.Fallback;let J;return t[16]!==Q||t[17]!==V||t[18]!==k||t[19]!==F||t[20]!==L?(J=u.jsx(sF,{...k,Fallback:Q,addResult:V,resume:L,respondToApproval:F}
35),t[16]=Q,t[17]=V,t[18]=k,t[19]=F,t[20]=L,t[21]=J):J=t[21],J}if(k.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(_){case"text":{let M;return t[22]!==h||t[23]!==k?(M=u.jsx(h,{...k}),t[22]=h,t[23]=k,t[24]=M):M=t[24],M}case"reasoning":{let M;return t[25]!==m||t[26]!==k?(M=u.jsx(m,{...k}),t[25]=m,t[26]=k,t[27]=M):M=t[27],M}case"source":{let M;return t[28]!==v||t[29]!==k?(M=u.jsx(v,{...k}),t[28]=v,t[29]=k,t[30]=M):M=t[30],M}case"image":{let M;return t[31]!==g||t[32]!==k?(M=u.jsx(g,{...k}),t[31]=g,t[32]=k,t[33]=M):M=t[33],M}case"file":{let M;return t[34]!==w||t[35]!==k?(M=u.jsx(w,{...k}),t[34]=w,t[35]=k,t[36]=M):M=t[36],M}case"audio":{let M;return t[37]!==b||t[38]!==k?(M=u.jsx(b,{...k}),t[37]=b,t[38]=k,t[39]=M):M=t[39],M}case"data":{const M=f?.by_name?.[k.name]??f?.Fallback;let V;return t[40]!==M||t[41]!==k?(V=u.jsx(iF,{...k,Fallback:M}),t[40]=M,t[41]=k,t[42]=V):V=t[42],V}default:return console.warn(`Unknown message part type: ${_}`),null}},oF=e=>{const t=ce(5),{partIndex:r,components:n}=e;let s;t[0]!==n?(s=u.jsx(aF,{components:n}),t[0]=n,t[1]=s):s=t[1];let i;return t[2]!==r||t[3]!==s?(i=u.jsx(Yp,{index:r,children:s}),t[2]=r,t[3]=s,t[4]=i):i=t[4],i},lF=N.memo(oF,(e,t)=>e.partIndex===t.partIndex&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.Group===t.components?.Group),cF=e=>{const t=ce(6),{status:r,component:n}=e,s=r.type==="running";let i;t[0]!==n||t[1]!==r?(i=u.jsx(n,{type:"text",text:"",status:r}),t[0]=n,t[1]=r,t[2]=i):i=t[2];let a;return t[3]!==s||t[4]!==i?(a=u.jsx(Qp,{text:"",isRunning:s,children:i}),t[3]=s,t[4]=i,t[5]=a):a=t[5],a},uF=Object.freeze({type:"complete"}),dF=e=>{const t=ce(6),{components:r}=e,n=Fe(mF);if(r?.Empty){let a;return t[0]!==r.Empty||t[1]!==n?(a=u.jsx(r.Empty,{status:n}),t[0]=r.Empty,t[1]=n,t[2]=a):a=t[2],a}const s=r?.Text??Vs.Text;let i;return t[3]!==n||t[4]!==s?(i=u.jsx(cF,{status:n,component:s}),t[3]=n,t[4]=s,t[5]=i):i=t[5],i},fF=N.memo(dF,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),fm=e=>{const t=ce(9),{groupingFunction:r,components:n}=e,s=Fe(gF),i=nF(r);let a;e:{if(s===0){let d;t[0]!==n?(d=u.jsx(fF,{components:n}),t[0]=n,t[1]=d):d=t[1],a=d;break e}let c;if(t[2]!==n||t[3]!==i){let d;t[5]!==n?(d=(f,h)=>u.jsx(n?.Group??Vs.Group,{groupKey:f.groupKey,indices:f.indices,children:f.indices.map(m=>u.jsx(lF,{partIndex:m,components:n},m))},`group-${h}-${f.groupKey??"ungrouped"}`),t[5]=n,t[6]=d):d=t[6],c=i.map(d),t[2]=n,t[3]=i,t[4]=c}else c=t[4];a=c}const o=a;let l;return t[7]!==o?(l=u.jsx(u.Fragment,{children:o}),t[7]=o,t[8]=l):l=t[8],l};fm.displayName="MessagePrimitive.Unstable_PartsGrouped";const XS=e=>{const t=ce(6);let r,n;t[0]!==e?({components:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]);let s;return t[3]!==r||t[4]!==n?(s=u.jsx(fm,{...n,components:r,groupingFunction:rF}),t[3]=r,t[4]=n,t[5]=s):s=t[5],s};XS.displayName="MessagePrimitive.Unstable_PartsGroupedByParentId";function hF(e){return e.message.parts}function pF(e){return e.part}function mF(e){return e.message.status??uF}function gF(e){return e.message.parts.length}var jo=Pu({AttachmentByIndex:()=>eS,Attachments:()=>tS,Content:()=>gh,Error:()=>QS,GenerativeUI:()=>zC,GroupedParts:()=>XC,If:()=>wS,PartByIndex:()=>vo,Parts:()=>gh,Quote:()=>JC,Root:()=>YS,Unstable_PartsGrouped:()=>fm,Unstable_PartsGroupedByParentId:()=>XS});const yF=e=>{const t=ce(2),r=ti(e);let n;return t[0]!==r?(n=s=>{const i=new ResizeObserver(()=>{r()}),a=new MutationObserver(o=>{o.some(vF)&&r()});return i.observe(s),a.observe(s,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{i.disconnect(),a.disconnect()}},t[0]=r,t[1]=n):n=t[1],$i(n)};function vF(e){return e.type!=="attributes"||e.attributeName!=="style"}const xF=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const s=wt(null),i=Fe(I=>I.thread.messages.length>0),a=wt(!1),o=wt(null),l=Vi();e===void 0&&(e=l.getState().turnAnchor!=="top");const c=wt(0),d=wt(0),f=wt(0),h=wt(0),m=wt(null),g=Zs(I=>
35{const k=s.current;k&&(m.current=I,k.scrollTo({top:k.scrollHeight,behavior:I}))},[]),v=Zs(I=>{m.current=I,o.current!==null&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{o.current=null,g(I)})},[g]);Io(()=>()=>{o.current!==null&&cancelAnimationFrame(o.current)},[]);const w=Zs(()=>{const I=l.getState();return I.turnAnchor==="top"&&I.element.viewport===s.current&&I.element.anchor!==null},[l]),b=()=>{const I=s.current;if(!I)return;const k=l.getState().isAtBottom,_=Math.abs(I.scrollHeight-I.scrollTop-I.clientHeight)<=1||I.scrollHeight<=I.clientHeight;!_&&c.current<I.scrollTop||(_?I.scrollHeight>I.clientHeight+1&&(m.current=null):c.current>I.scrollTop&&d.current===I.scrollHeight&&(m.current=null),(_||m.current===null)&&_!==k&&Vc(l).setState({isAtBottom:_})),c.current=I.scrollTop,d.current=I.scrollHeight},C=yF(()=>{const I=s.current;if(!I)return;const{scrollHeight:k,clientHeight:_}=I;if(k===f.current&&_===h.current)return;f.current=k,h.current=_;const M=m.current;M&&w()?m.current=null:M?g(M):e&&l.getState().isAtBottom&&g("instant"),b()}),T=$i(I=>{const k=()=>{m.current=null};return I.addEventListener("scroll",b),I.addEventListener("pointerdown",k),()=>{I.removeEventListener("scroll",b),I.removeEventListener("pointerdown",k)}});return Io(()=>{if(r){if(!i){a.current=!1;return}a.current||(a.current=!0,m.current===null&&v("instant"))}},[i,v,r]),RS(({behavior:I})=>{g(I)}),Lc("thread.runStart",()=>{t&&l.getState().turnAnchor!=="top"&&v("auto")}),Lc("threadListItem.switchedTo",()=>{n&&v("instant")}),on(C,T,s)},JS=N.forwardRef((e,t)=>{const r=ce(3);let n;return r[0]!==e||r[1]!==t?(n=u.jsx(fr.div,{...e,ref:t}),r[0]=e,r[1]=t,r[2]=n):n=r[2],n});JS.displayName="ThreadPrimitive.Root";const ZS=e=>{const{children:t}=e;return Fe(bF)?t:null};ZS.displayName="ThreadPrimitive.Empty";function bF(e){return e.thread.isEmpty}const wF=e=>{const t=ce(4);let r;return t[0]!==e.disabled||t[1]!==e.empty||t[2]!==e.running?(r=n=>!(e.empty===!0&&!n.thread.isEmpty||e.empty===!1&&n.thread.isEmpty||e.running===!0&&!n.thread.isRunning||e.running===!1&&n.thread.isRunning||e.disabled===!0&&!n.thread.isDisabled||e.disabled===!1&&n.thread.isDisabled),t[0]=e.disabled,t[1]=e.empty,t[2]=e.running,t[3]=r):r=t[3],Fe(r)},eE=e=>{const t=ce(3);let r,n;return t[0]!==e?({children:r,...n}=e,t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]),wF(n)?r:null};eE.displayName="ThreadPrimitive.If";const tE=(e,t)=>{const r=ce(3);let n;return r[0]!==t||r[1]!==e?(n=s=>{if(!e)return;const i=e(),a=()=>{const l=t?t(s):s.offsetHeight;i.setHeight(l)},o=new ResizeObserver(a);return o.observe(s),a(),()=>{o.disconnect(),i.unregister()}},r[0]=t,r[1]=e,r[2]=n):n=r[2],$i(n)},Ry=e=>{let t=0,r=e;for(;r;)t+=r.offsetTop,r=r.offsetParent;return t},CF=(e,t)=>{let r=0,n=e;for(;n&&n!==t;)r+=n.offsetTop,n=n.offsetParent;return n===t?r:Ry(e)-Ry(t)},rE=({viewport:e,anchor:t,tallerThan:r,visibleHeight:n})=>{const s=CF(t,e),i=t.offsetHeight;return s+Math.max(0,i-(i<=r?i:n))},SF=({scrollHeight:e,...t})=>{const{viewport:r}=t,n=rE(t)+r.clientHeight;return Math.max(0,n-e)},EF=({viewport:e,reserve:t,...r})=>SF({viewport:e,...r,scrollHeight:e.scrollHeight-t.offsetHeight}),TF=e=>{const t=new ResizeObserver(e),r=new MutationObserver(e);let n=null,s=null,i=null;const a=()=>{t.disconnect(),r.disconnect(),n=null,s=null,i=null};return{target:(o,l,c)=>{n===o&&s===l&&i===c||(a(),t.observe(o),t.observe(l),t.observe(c),r.observe(c,{childList:!0,subtree:!0,characterData:!0}),n=o,s=l,i=c)},disconnect:a}},_F=e=>{let t=null;return{schedule:()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))},cancel:()=>{t!==null&&(cancelAnimationFrame(t),t=null)}}},IF=e=>{let t=null,r;function n(){const o=e.getState(),{viewport:l,anchor:c,target:d}=o.element,f=o.targetConfig;if(o.turnAnchor!=="top"||!l||!c||!d||!f){i.disconnect(),t&&(Ny(t,0),t.remove());return}if(t??(t=KO()),(t.parentElement!==d.parentElement||t.previousElementSibling!==d)&&d.after(t),i.target(l,c,d),Ny(t,EF({viewport:l,anchor:c,reserve:t,...f}))){s.schedule();return}const h=zO(c);if(h!==void 0&&r===h)return;const m=qO(rE({viewport:l,anchor:c,...f}));Math.abs(l.scrollTop-m)>1&&l.scrollTo({top:m,behavior:"smooth"}),h!==void 0&&(r=h)}const s=_F(n),i=TF(s.schedule);s.schedule();const a=e.subscribe(s.schedule);return()=>{s.cancel(),a(),i.disconnect(),t?.remove()}},AF=e=>{const t=ce(4),r=Vi();let n,s;t[0]!==e||t[1]!==r?(n=()=>
35{if(e)return IF(r)},s=[e,r],t[0]=e,t[1]=r,t[2]=n,t[3]=s):(n=t[2],s=t[3]),Io(n,s)},nE=({isRunning:e,messages:t})=>{if(!e)return null;const r=t.at(-1),n=t.at(-2);return n?.role!=="user"||r?.role!=="assistant"?null:{anchorId:n.id,targetId:r.id}},kF=e=>nE(e)?.anchorId,NF=e=>nE(e)?.targetId,RF=()=>tE(Ui(BF),DF),PF=()=>$i(Ui(LF)),jF=e=>{const t=ce(13),r=Vi();let n;t[0]!==e?(n=m=>{if(e)return kF(m.thread)},t[0]=e,t[1]=n):n=t[1];const s=Fe(n);let i;t[2]!==e?(i=m=>{if(e)return NF(m.thread)},t[2]=e,t[3]=i):i=t[3];const a=Fe(i);let o;e:{if(!s||!a){o=null;break e}let m;t[4]!==s||t[5]!==a?(m={anchorId:s,targetId:a},t[4]=s,t[5]=a,t[6]=m):m=t[6],o=m}const l=o;let c,d;t[7]!==l||t[8]!==r?(c=()=>{if(!l)return;const m=r.getState(),g=m.topAnchorTurn;g?.anchorId===l.anchorId&&g.targetId===l.targetId||m.setTopAnchorTurn(l)},d=[l,r],t[7]=l,t[8]=r,t[9]=c,t[10]=d):(c=t[9],d=t[10]),Io(c,d);let f;t[11]!==r?(f=()=>{r.getState().setTopAnchorTurn(null)},t[11]=r,t[12]=f):f=t[12];const h=f;Lc("thread.initialize",h),Lc("threadListItem.switchedTo",h)},sE=N.forwardRef((e,t)=>{const r=ce(18);let n,s,i,a,o,l;r[0]!==e?({autoScroll:n,scrollToBottomOnRunStart:o,scrollToBottomOnInitialize:a,scrollToBottomOnThreadSwitch:l,children:s,...i}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i,r[4]=a,r[5]=o,r[6]=l):(n=r[1],s=r[2],i=r[3],a=r[4],o=r[5],l=r[6]);let c;r[7]!==n||r[8]!==a||r[9]!==o||r[10]!==l?(c={autoScroll:n,scrollToBottomOnRunStart:o,scrollToBottomOnInitialize:a,scrollToBottomOnThreadSwitch:l},r[7]=n,r[8]=a,r[9]=o,r[10]=l,r[11]=c):c=r[11];const d=xF(c),f=RF(),h=PF(),m=Vi();let g;r[12]!==m?(g=m.getState(),r[12]=m,r[13]=g):g=r[13];const v=g.turnAnchor==="top";jF(v),AF(v);const w=on(t,d,f,h);let b;return r[14]!==s||r[15]!==w||r[16]!==i?(b=u.jsx(fr.div,{...i,ref:w,children:s}),r[14]=s,r[15]=w,r[16]=i,r[17]=b):b=r[17],b});sE.displayName="ThreadPrimitive.ViewportScrollable";const iE=N.forwardRef((e,t)=>{const r=ce(13);let n,s,i;r[0]!==e?({turnAnchor:i,topAnchorMessageClamp:s,...n}=e,r[0]=e,r[1]=n,r[2]=s,r[3]=i):(n=r[1],s=r[2],i=r[3]);let a;r[4]!==s||r[5]!==i?(a={turnAnchor:i,topAnchorMessageClamp:s},r[4]=s,r[5]=i,r[6]=a):a=r[6];let o;r[7]!==n||r[8]!==t?(o=u.jsx(sE,{...n,ref:t}),r[7]=n,r[8]=t,r[9]=o):o=r[9];let l;return r[10]!==a||r[11]!==o?(l=u.jsx(nm,{options:a,children:o}),r[10]=a,r[11]=o,r[12]=l):l=r[12],l});iE.displayName="ThreadPrimitive.Viewport";function BF(e){return e.registerViewport}function DF(e){return e.clientHeight}function LF(e){return e.registerViewportElement}const aE=N.forwardRef((e,t)=>{const r=ce(3),n=on(t,tE(Ui(MF),OF));let s;return r[0]!==e||r[1]!==n?(s=u.jsx(fr.div,{...e,ref:n}),r[0]=e,r[1]=n,r[2]=s):s=r[2],s});aE.displayName="ThreadPrimitive.ViewportFooter";function MF(e){return e.registerContentInset}function OF(e){const t=parseFloat(getComputedStyle(e).marginTop)||0;return e.offsetHeight+t}const FF=e=>{const t=ce(5);let r;t[0]!==e?(r=e===void 0?{}:e,t[0]=e,t[1]=r):r=t[1];const{behavior:n}=r,s=Ui(VF),i=Vi();let a;t[2]!==n||t[3]!==i?(a=()=>{i.getState().scrollToBottom({behavior:n})},t[2]=n,t[3]=i,t[4]=a):a=t[4];const o=a;return s?null:o},UF=fs("ThreadPrimitive.ScrollToBottom",FF,["behavior"]);function VF(e){return e.isAtBottom}const $F=e=>{const t=ce(4),{prompt:r,send:n,clearComposer:s,autoSend:i}=e,a=n??i??!1;let o;t[0]!==s||t[1]!==r||t[2]!==a?(o={prompt:r,send:a,clearComposer:s},t[0]=s,t[1]=r,t[2]=a,t[3]=o):o=t[3];const{disabled:l,trigger:c}=R8(o);return l?null:c},zF=fs("ThreadPrimitive.Suggestion",$F,["prompt","send","clearComposer","autoSend","method"]);var Ii=Pu({Empty:()=>ZS,If:()=>eE,MessageByIndex:()=>OC,Messages:()=>tL,Root:()=>JS,ScrollToBottom:()=>UF,Suggestion:()=>zF,SuggestionByIndex:()=>oS,Suggestions:()=>e8,Unstable_MessageById:()=>FC,Viewport:()=>iE,ViewportFooter:()=>aE,ViewportProvider:()=>nm});const $c=new Map;function KF(e,t){const r=$c.get(e)??[];r.push(t),$c.set(e,r)}function qF(e){const t=$c.get(e)??[];return $c.delete(e),t}const yh=new Map;function HF(e,t){yh.set(e,t)}function GF(e){const t=yh.get(e)??null;return yh.delete(e),t}const vh=!0,ji="chatBandwidthExhausted",xh="chatBandwidthRestored",Bo="chatBandwidthRefreshRequested";
35class WF extends Error{constructor(){super("INSUFFICIENT_BANDWIDTH"),this.name="InsufficientBandwidthError"}}function YF(){typeof window>"u"||window.dispatchEvent(new CustomEvent(ji))}function QF(){typeof window>"u"||window.dispatchEvent(new CustomEvent(xh))}function XF(){typeof window>"u"||window.dispatchEvent(new CustomEvent(Bo))}function JF(e){return e.map(t=>{const r=t.content.map(s=>s.type==="text"?s.text:"").join(""),n=t?.metadata?.custom?.hidden===!0||t?.metadata?.hidden===!0;return{id:t.id,role:t.role,content:n?"":r,...n?{hidden:!0}:{}}})}async function*ZF(e,t,r){const n=localStorage.getItem("web3_jwt"),s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream","ngrok-skip-browser-warning":"true",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:r});if(s.status===402){let m="";try{const g=await s.text();m=String(JSON.parse(g)?.error??"")}catch{}if(!m||m==="INSUFFICIENT_BANDWIDTH")throw YF(),new WF}if(!s.ok||!s.body)throw new Error(`Chat request failed (${s.status})`);QF();const i=s.body.getReader(),a=new TextDecoder;let o="";const l=[];let c=!1;const d=()=>{const m=l[l.length-1];if(m&&m.type==="text")return m;const g={type:"text",text:""};return l.push(g),g},f=m=>{const g=m.replace(/\r$/,"");if(!g.startsWith("data:"))return;const v=g.slice(5).trim();if(!v||v==="[DONE]")return;let w;try{w=JSON.parse(v)}catch{return}if(!(!w||typeof w.type!="string")){if(w.type==="text-delta"&&typeof w.delta=="string"){const b=d();b.text+=w.delta,c=!0;return}if(w.type.startsWith("data-")){const b=w.type.slice(5);l.push({type:"data",name:b,data:w.data}),c=!0;return}}},h=()=>({content:l.map(m=>m.type==="text"?{type:"text",text:m.text}:{type:"data",name:m.name,data:m.data})});for(;!r.aborted;){const{done:m,value:g}=await i.read();if(m)break;o+=a.decode(g,{stream:!0});const v=o.split(`
36`);o=v.pop()??"",c=!1;for(const w of v)f(w);c&&(yield h())}o&&(c=!1,f(o),c&&(yield h())),r.aborted||XF()}const Py=new Map;function eU(){try{if(typeof crypto<"u"&&"randomUUID"in crypto)return crypto.randomUUID()}catch{}return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function tU(e,t){const r=JSON.stringify(t.map(i=>[i.id??"",i.role,i.content.length])),n=Py.get(e);if(n&&n.key===r)return n.requestId;const s=eU();return Py.set(e,{key:r,requestId:s}),s}function rU(e){return{async*run({messages:t,abortSignal:r}){const n=JF(t),s="https://x402.slinkylayer.ai/api/v1/chat",i=qF(e.threadId),a=GF(e.threadId),o=tU(e.threadId,n),l={threadId:e.threadId,requestId:o,messages:n,metadata:{selectedModel:"default",localOnly:!0,...e.getMetadata(),...a?{toolSetup:!0,selectedToolId:a}:{},...i.length?{toolResult:i}:{}}};yield*ZF(s,l,r)}}}var oE={exports:{}};(function(e,t){((r,n)=>{e.exports=n()})(Ni,function(){var r=function(p,y){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(x,S){x.__proto__=S}:function(x,S){for(var E in S)Object.prototype.hasOwnProperty.call(S,E)&&(x[E]=S[E])}))(p,y)},n=function(){return(n=Object.assign||function(p){for(var y,x=1,S=arguments.length;x<S;x++)for(var E in y=arguments[x])Object.prototype.hasOwnProperty.call(y,E)&&(p[E]=y[E]);return p}).apply(this,arguments)};function s(p,y,x){for(var S,E=0,A=y.length;E<A;E++)!S&&E in y||((S=S||Array.prototype.slice.call(y,0,E))[E]=y[E]);return p.concat(S||Array.prototype.slice.call(y))}var i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Ni,a=Object.keys,o=Array.isArray;function l(p,y){return typeof y=="object"&&a(y).forEach(function(x){p[x]=y[x]}),p}typeof Promise>"u"||i.Promise||(i.Promise=Promise);var c=Object.getPrototypeOf,d={}.hasOwnProperty;function f(p,y){return d.call(p,y)}function h(p,y){typeof y=="function"&&(y=y(c(p))),(typeof Reflect>
vendor: 23,885 bytes, lines 36-38
36"u"?a:Reflect.ownKeys)(y).forEach(function(x){g(p,x,y[x])})}var m=Object.defineProperty;function g(p,y,x,S){m(p,y,l(x&&f(x,"get")&&typeof x.get=="function"?{get:x.get,set:x.set,configurable:!0}:{value:x,configurable:!0,writable:!0},S))}function v(p){return{from:function(y){return p.prototype=Object.create(y.prototype),g(p.prototype,"constructor",p),{extend:h.bind(null,p.prototype)}}}}var w=Object.getOwnPropertyDescriptor,b=[].slice;function C(p,y,x){return b.call(p,y,x)}function T(p,y){return y(p)}function I(p){if(!p)throw new Error("Assertion Failed")}function k(p){i.setImmediate?setImmediate(p):setTimeout(p,0)}function _(p,y){if(typeof y=="string"&&f(p,y))return p[y];if(!y)return p;if(typeof y!="string"){for(var x=[],S=0,E=y.length;S<E;++S){var A=_(p,y[S]);x.push(A)}return x}var D,O=y.indexOf(".");return O===-1||(D=p[y.substr(0,O)])==null?void 0:_(D,y.substr(O+1))}function M(p,y,x){if(p&&y!==void 0&&!("isFrozen"in Object&&Object.isFrozen(p)))if(typeof y!="string"&&"length"in y){I(typeof x!="string"&&"length"in x);for(var S=0,E=y.length;S<E;++S)M(p,y[S],x[S])}else{var A=y.indexOf(".");if(A!==-1){var D=y.substr(0,A),A=y.substr(A+1);if(A==="")x===void 0?o(p)&&!isNaN(parseInt(D))?p.splice(D,1):delete p[D]:p[D]=x;else{var O=p[D];if(!O||!f(p,D)){if(x===void 0)return;O=p[D]={}}M(O,A,x)}}else x===void 0?o(p)&&!isNaN(parseInt(y))?p.splice(y,1):delete p[y]:p[y]=x}}function V(p){var y,x={};for(y in p)f(p,y)&&(x[y]=p[y]);return x}var G=[].concat;function L(p){return G.apply([],p)}var ye="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(L([8,16,32,64].map(function(p){return["Int","Uint","Float"].map(function(y){return y+p+"Array"})}))).filter(function(p){return i[p]}),H=new Set(ye.map(function(p){return i[p]})),F=null;function Q(p){return F=new WeakMap,p=function y(x){if(!x||typeof x!="object")return x;var S=F.get(x);if(S)return S;if(o(x)){S=[],F.set(x,S);for(var E=0,A=x.length;E<A;++E)S.push(y(x[E]))}else if(H.has(x.constructor))S=x;else{var D,O=c(x);for(D in S=O===Object.prototype?{}:Object.create(O),F.set(x,S),x)f(x,D)&&(S[D]=y(x[D]))}return S}(p),F=null,p}var J={}.toString;function oe(p){return J.call(p).slice(8,-1)}var xe=typeof Symbol<"u"?Symbol.iterator:"@@iterator",ge=typeof xe=="symbol"?function(p){var y;return p!=null&&(y=p[xe])&&y.apply(p)}:function(){return null};function $(p,y){y=p.indexOf(y),0<=y&&p.splice(y,1)}var le={};function B(p){var y,x,S,E;if(arguments.length===1){if(o(p))return p.slice();if(this===le&&typeof p=="string")return[p];if(E=ge(p))for(x=[];!(S=E.next()).done;)x.push(S.value);else{if(p==null)return[p];if(typeof(y=p.length)!="number")return[p];for(x=new Array(y);y--;)x[y]=p[y]}}else for(y=arguments.length,x=new Array(y);y--;)x[y]=arguments[y];return x}var Te=typeof Symbol<"u"?function(p){return p[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ye=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],ue=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ye),U={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Qe(p,y){this.name=p,this.message=y}function pt(p,y){return p+". Errors: "+Object.keys(y).map(function(x){return y[x].toString()}).filter(function(x,S,E){return E.indexOf(x)===S}).join(`
37`)}function We(p,y,x,S){this.failures=y,this.failedKeys=S,this.successCount=x,this.message=pt(p,y)}function dt(p,y){this.name="BulkError",this.failures=Object.keys(y).map(function(x){return y[x]}),this.failuresByPos=y,this.message=pt(p,this.failures)}v(Qe).from(Error).extend({toString:function(){return this.name+": "+this.message}}),v(We).from(Qe),v(dt).from(Qe);var ft=ue.reduce(function(p,y){return p[y]=y+"Error",p},{}),At=Qe,Le=ue.reduce(function(p,y){var x=y+"Error";function S(E,A){this.name=x,E?typeof E=="string"?(this.message="".concat(E).concat(A?`
38 `+A:""),this.inner=A||null):typeof E=="object"&&(this.message="".concat(E.name," ").concat(E.message),this.inner=E):(this.message=U[y]||x,this.inner=null)}return v(S).from(At),p[y]=S,p},{}),Ut=(Le.Syntax=SyntaxError,Le.Type=TypeError,Le.Range=RangeError,ye.reduce(function(p,y){return p[y+"Error"]=Le[y],p},{}));ye=ue.reduce(function(p,y){return["Syntax","Type","Range"].indexOf(y)===-1&&(p[y+"Error"]=Le[y]),p},{});function tt(){}function ct(p){return p}function ht(p,y){return p==null||p===ct?y:function(x){return y(p(x))}}function kt(p,y){return function(){p.apply(this,arguments),y.apply(this,arguments)}}function Xr(p,y){return p===tt?y:function(){var x=p.apply(this,arguments),S=(x!==void 0&&(arguments[0]=x),this.onsuccess),E=this.onerror,A=(this.onsuccess=null,this.onerror=null,y.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?kt(S,this.onsuccess):S),E&&(this.onerror=this.onerror?kt(E,this.onerror):E),A!==void 0?A:x}}function ps(p,y){return p===tt?y:function(){p.apply(this,arguments);var x=this.onsuccess,S=this.onerror;this.onsuccess=this.onerror=null,y.apply(this,arguments),x&&(this.onsuccess=this.onsuccess?kt(x,this.onsuccess):x),S&&(this.onerror=this.onerror?kt(S,this.onerror):S)}}function K(p,y){return p===tt?y:function(E){var S=p.apply(this,arguments),E=(l(E,S),this.onsuccess),A=this.onerror,D=(this.onsuccess=null,this.onerror=null,y.apply(this,arguments));return E&&(this.onsuccess=this.onsuccess?kt(E,this.onsuccess):E),A&&(this.onerror=this.onerror?kt(A,this.onerror):A),S===void 0?D===void 0?void 0:D:l(S,D)}}function fe(p,y){return p===tt?y:function(){return y.apply(this,arguments)!==!1&&p.apply(this,arguments)}}function W(p,y){return p===tt?y:function(){var x=p.apply(this,arguments);if(x&&typeof x.then=="function"){for(var S=this,E=arguments.length,A=new Array(E);E--;)A[E]=arguments[E];return x.then(function(){return y.apply(S,A)})}return y.apply(this,arguments)}}ye.ModifyError=We,ye.DexieError=Qe,ye.BulkError=dt;var Ce=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Ee(p){Ce=p}var be={},Ve=100,rt=typeof Promise>"u"?[]:(ue=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[rt=crypto.subtle.digest("SHA-512",new Uint8Array([0])),c(rt),ue]:[ue,c(ue),ue]),ue=rt[0],Qi=rt[1],Qi=Qi&&Qi.then,Se=ue&&ue.constructor,Ge=!!rt[2],st=function(p,y){Jr.push([p,y]),cr&&(queueMicrotask(R2),cr=!1)},Et=!0,cr=!0,Xe=[],bt=[],sr=ct,mr={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:tt,pgp:!1,env:{},finalize:tt},$e=mr,Jr=[],nt=0,Wt=[];function ke(p){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var y=this._PSD=$e;if(typeof p!="function"){if(p!==be)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&Is(this,this._value)}else this._state=null,this._value=null,++y.ref,function x(S,E){try{E(function(A){if(S._state===null){if(A===S)throw new TypeError("A promise cannot be resolved with itself.");var D=S._lib&&Ki();A&&typeof A.then=="function"?x(S,function(O,ee){A instanceof ke?A._then(O,ee):A.then(O,ee)}):(S._state=!0,S._value=A,al(S)),D&&qi()}},Is.bind(null,S))}catch(A){Is(S,A)}}(this,p)}var Zr={get:function(){var p=$e,y=ul;function x(S,E){var A=this,D=!p.global&&(p!==$e||y!==ul),O=D&&!ks(),ee=new ke(function(de,re){$u(A,new cn(Dm(S,p,D,O),Dm(E,p,D,O),de,re,p))});return this._consoleTask&&(ee._consoleTask=this._consoleTask),ee}return x.prototype=be,x},set:function(p){g(this,"then",p&&p.prototype===be?Zr:{get:function(){return p},set:Zr.set})}};function cn(p,y,x,S,E){this.onFulfilled=typeof p=="function"?p:null,this.onRejected=typeof y=="function"?y:null,this.resolve=x,this.reject=S,this.psd=E}function Is(p,y){var x,S;bt.push(y),p._state===null&&(x=p._lib&&Ki(),y=sr(y),p._state=!1,p._value=y,S=p,Xe.some(function(E){return E._value===S._value})||Xe.push(S),al(p),x)&&qi()}function al(p){var y=p._listeners;p._listeners=[];for(var x=0,S=y.length;x<S;++x)$u(p,y[x]);var E=p._PSD;--E.ref||E.finalize(),nt===0&&(++nt,st(function(){--nt==0&&zu()},[]))}function $u(p,y){if(p._state===null)p._listeners.push(y);else{var x=p._state?y.onFulfilled:y.onRejected;if(x===null)return(p._state?y.resolve:y.reject)(p._value);++y.psd.ref,++nt,st(N2,[x,p,y])}}function N2(p,y,x){try{var S,E=y._value;!y._state&&bt.length&&(bt=[]),S=Ce&&y._consoleTask?y._consoleTask.run(function(){return p(E)}):p(E),y._state||bt.indexOf(E)!==-1||(A=>{for(var D=Xe.length;D;)if(Xe[--D]._value===A._value)return Xe.splice(D,1)})(y),x.resolve(S)}catch(A){x.reject(A)}finally{--nt==0&&zu(),--x.psd.ref||x.psd.finalize()}}function R2(){li(mr,function(){Ki()&&qi()})}function Ki(){var p=Et;return cr=Et=!1,p}function qi(){var p,y,x;do for(;0<Jr.length;)for(p=Jr,Jr=[],x=p.length,y=0;y<x;++y){var S=p[y];S[0].apply(null,S[1])}while(0<Jr.length);cr=Et=!0}function zu(){for(var p=Xe,y=(Xe=[],p.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Wt.slice(0)),x=y.length;x;)y[--x]()}function ol(p){return new ke(be,!1,p)}function ur(p,y){var x=$e;return function(){var S=Ki(),E=$e;try{return Ns(x,!0),p.apply(this,arguments)}catch(A){y&&y(A)}finally{Ns(E,!1),S&&qi()}}}h(ke.prototype,{then:Zr,_then:function(p,y){$u(this,new cn(null,null,p,y,$e))},catch:function(p){var y,x;return arguments.length===1?this.then(null,p):(y=p,x=arguments[1],typeof y=="function"?this.then(null,function(S){return(S instanceof y?x:ol)(S)}):this.then(null,function(S){return(S&&S.name===y?x:ol)(S)}))},finally:function(p){return this.then(function(y){return ke.resolve(p()).then(function(){return y})},function(y){return ke.resolve(p()).then(function(){return ol(y)})})},timeout:function(p,y){var x=this;return p<1/0?new ke(function(S,E){var A=setTimeout(function(){return E(new Le.Timeout(y))},p);x.then(S,E).finally(clearTimeout.bind(null,A))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&g(ke.prototype,Symbol.toStringTag,"Dexie.Promise"),mr.env=Bm(),h(ke,{all:function(){var p=B.apply(null,arguments).map(dl);return new ke(function(y,x){p.length===0&&y([]);var S=p.length;p.forEach(function(E,A){return ke.resolve(E).then(function(D){p[A]=D,--S||y(p)},x)})})},resolve:function(p){return p instanceof ke?p:p&&typeof p.then=="function"?new ke(function(y,x){p.then(y,x)}):new ke(be,!0,p)},reject:ol,race:function(){var p=B.apply(null,arguments).map(dl);return new ke(function(y,x){p.map(function(S){return ke.resolve(S).then(y,x)})})},PSD:{get:function(){return $e},set:function(p){return $e=p}},totalEchoes:{get:function(){return ul}},newPSD:As,usePSD:li,scheduler:{get:function(){return st},set:function(p){st=p}},rejectionMapper:{get:function(){return sr},set:function(p){sr=p}},follow:function(p,y){return new ke(function(x,S){return As(function(E,A){var D=$e;D.unhandleds=[],D.onunhandled=A,D.finalize=kt(function(){var O,ee=this;O=function(){ee.unhandleds.length===0?E():A(ee.unhandleds[0])},Wt.push(function de(){O(),Wt.splice(Wt.indexOf(de),1)}),++nt,st(function(){--nt==0&&zu()},[])},D.finalize),p()},y,x,S)})}}),Se&&(Se.allSettled&&g(ke,"allSettled",function(){var p=B.apply(null,arguments).map(dl);return new ke(function(y){p.length===0&&y([]);var x=p.length,S=new Array(x);p.forEach(function(E,A){return ke.resolve(E).then(function(D){return S[A]={status:"fulfilled",value:D}},function(D){return S[A]={status:"rejected",reason:D}}).then(function(){return--x||y(S)})})})}),Se.any&&typeof AggregateError<"u"&&g(ke,"any",function(){var p=B.apply(null,arguments).map(dl);return new ke(function(y,x){p.length===0&&x(new AggregateError([]));var S=p.length,E=new Array(S);p.forEach(function(A,D){return ke.resolve(A).then(function(O){return y(O)},function(O){E[D]=O,--S||x(new AggregateError(E))})})})}),Se.withResolvers)&&(ke.withResolvers=Se.withResolvers);var Er={awaits:0,echoes:0,id:0},P2=0,ll=[],cl=0,ul=0,j2=0;function As(p,D,x,S){var E=$e,A=Object.create(E),D=(A.parent=E,A.ref=0,A.global=!1,A.id=++j2,mr.env,A.env=Ge?{Promise:ke,PromiseProp:{value:ke,configurable:!0,writable:!0},all:ke.all,race:ke.race,allSettled:ke.allSettled,any:ke.any,resolve:ke.resolve,reject:ke.reject}:{},D&&l(A,D),++E.ref,A.finalize=function(){--this.parent.ref||this.parent.finalize()},li(A,p,x,S));return A.ref===0&&A.finalize(),D}function Hi(){return Er.id||(Er.id=++P2),++Er.awaits,Er.echoes+=Ve,Er.id}function ks(){return!!Er.awaits&&(--Er.awaits==0&&(Er.id=0),Er.echoes=Er.awaits*Ve,!0)}function dl(p){return Er.echoes&&p&&p.constructor===Se?(Hi(),p.then(function(y){return ks(),y},function(y){return ks(),yr(y)})):p}function B2(){var p=ll[ll.length-1];ll.pop(),Ns(p,!1)}function Ns(p,y){var x,S,E=$e;(y?!Er.echoes||cl++&&p===$e:!cl||--cl&&p===$e)||queueMicrotask(y?function(A){++ul,Er.echoes&&--Er.echoes!=0||(Er.echoes=Er.awaits=Er.id=0),ll.push($e),Ns(A,!0)}.bind(null,p):B2),p!==$e&&($e=p,E===mr&&(mr.env=Bm()),Ge)&&(x=mr.env.Promise,S=p.env,E.global||p.global)&&(Object.defineProperty(i,"Promise",S.PromiseProp),x.all=S.all,x.race=S.race,x.resolve=S.resolve,x.reject=S.reject,S.allSettled&&(x.allSettled=S.allSettled),S.any)&&(x.any=S.any)}function Bm(){var p=i.Promise;return Ge?{Promise:p,PromiseProp:Object.getOwnPropertyDescriptor(i,"Promise"),all:p.all,race:p.race,allSettled:p.allSettled,any:p.any,resolve:p.resolve,reject:p.reject}:{}}function li(p,y,x,S,E){var A=$e;try{return Ns(p,!0),y(x,S,E)}finally{Ns(A,!1)}}function Dm(p,y,x,S){return typeof p!="function"?p:function(){var E=$e;x&&Hi(),Ns(y,!0);try{return p.apply(this,arguments)}finally{Ns(E,!1),S&&queueMicrotask(ks)}}}function Ku(p){Promise===Se&&Er.echoes===0?cl===0?p():enqueueNativeMicroTask(p):setTimeout(p,0)}(""+Qi).indexOf("[native code]")===-1&&(Hi=ks=tt);var yr=ke.reject,ci="ï¿¿",ms="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Lm="String expected.",fl="__dbnames",qu="readonly",Hu="readwrite";function ui(p,y){return p?y?function(){return p.apply(this,arguments)&&y.apply(this,arguments)}:p:y}var Mm={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function hl(p){return typeof p!="string"||/\./.test(p)?function(y){return y}:function(y){return y[p]===void 0&&p in y&&delete(y=Q(y))[p],y}}function Om(){throw Le.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function Ft(p,y){try{var x=Fm(p),S=Fm(y);if(x!==S)return x==="Array"?1:S==="Array"?-1:x==="binary"?1:S==="binary"?-1:x==="string"?1:S==="string"?-1:x==="Date"?1:S!=="Date"?NaN:-1;switch(x){case"number":case"Date":case"string":return y<p?1:p<y?-1:0;case"binary":for(var E=Um(p),A=Um(y),D=E.length,O=A.length,ee=D<O?D:O,de=0;de<ee;++de)if(E[de]!==A[de])return E[de]<A[de]?-1:1;return D===O?0:D<O?-1:1;case"Array":for(var re=p,X=y,te=re.length,ae=X.length,se=te<ae?te:ae,ne=0;ne<se;++ne){var ie=Ft(re[ne],X[ne]);if(ie!==0)return ie}return te===ae?0:te<ae?-1:1}}catch{}return NaN}function Fm(p){var y=typeof p;return y=="object"&&(ArrayBuffer.isView(p)||(y=oe(p))==="ArrayBuffer")?"binary":y}function Um(p){return p instanceof Uint8Array?p:ArrayBuffer.isView(p)?new Uint8Array(p.buffer,p.byteOffset,p.byteLength):new Uint8Array(p)}function pl(p,y,x){var S=p.schema.yProps;return S?(y&&0<x.numFailures&&(y=y.filter(function(E,A){return!x.failures[A]})),Promise.all(S.map(function(E){return E=E.updatesTable,y?p.db.table(E).where("k").anyOf(y).delete():p.db.table(E).clear()})).then(function(){return x})):x}Vm.prototype.execute=function(p){var y=this["@@propmod"];if(y.add!==void 0){var x=y.add;if(o(x))return s(s([],o(p)?p:[],!0),x).sort();if(typeof x=="number")return(Number(p)||0)+x;if(typeof x=="bigint")try{return BigInt(p)+x}catch{return BigInt(0)+x}throw new TypeError("Invalid term ".concat(x))}if(y.remove!==void 0){var S=y.remove;if(o(S))return o(p)?p.filter(function(E){return!S.includes(E)}).sort():[];if(typeof S=="number")return Number(p)-S;if(typeof S=="bigint")try{return BigInt(p)-S}catch{return BigInt(0)-S}throw new TypeError("Invalid subtrahend ".concat(S))}return x=(x=y.replacePrefix)==null?void 0:x[0],x&&typeof p=="string"&&p.startsWith(x)?y.replacePrefix[1]+p.substring(x.length):p};var La=Vm;function Vm(p){this["@@propmod"]=p}function $m(p,y){for(var x=a(y),S=x.length,E=!1,A=0;A<S;++A){var D=x[A],O=y[D],ee=_(p,D);O instanceof La?(M(p,D,O.execute(ee)),E=!0):ee!==O&&(M(p,D,O),E=!0)}return E}tr.prototype._trans=function(p,y,x){var S=this._tx||$e.trans,E=this.name,A=Ce&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(p==="readonly"?"read":"write"," ").concat(this.name));function D(de,re,X){if(X.schema[E])return y(X.idbtrans,X);throw new Le.NotFound("Table "+E+" not part of transaction")}var O=Ki();try{var ee=S&&S.db._novip===this.db._novip?S===$e.trans?S._promise(p,D,x):As(function(){return S._promise(p,D,x)},{trans:S,transless:$e.transless||$e}):function de(re,X,te,ae){if(re.idbdb&&(re._state.openComplete||$e.letThrough||re._vip)){var se=re._createTransaction(X,te,re._dbSchema);try{se.create(),re._state.PR1398_maxLoop=3}catch(ne){return ne.name===ft.InvalidState&&re.isOpen()&&0<--re._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),re.close({disableAutoOpen:!1}),re.open().then(function(){return de(re,X,te,ae)})):yr(ne)}return se._promise(X,function(ne,ie){return As(function(){return $e.trans=se,ae(ne,ie,se)})}).then(function(ne){if(X==="readwrite")try{se.idbtrans.commit()}catch{}return X==="readonly"?ne:se._completion.then(function(){return ne})})}if(re._state.openComplete)return yr(new Le.DatabaseClosed(re._state.dbOpenError));if(!re._state.isBeingOpened){if(!re._state.autoOpen)return yr(new Le.DatabaseClosed);re.open().catch(tt)}return re._state.dbReadyPromise.then(function(){return de(re,X,te,ae)})}(this.db,p,[this.name],D);return A&&(ee._consoleTask=A,ee=ee.catch(function(de){return console.trace(de),yr(de)})),ee}finally{O&&qi()}},tr.prototype.get=function(p,y){var x=this;return p&&p.constructor===Object?this.where(p).first(y):p==null?yr(new Le.Type("Invalid argument to Table.get()")):this._trans("readonly",function(S){return x.core.get({trans:S,key:p}).then(function(E){return x.hook.reading.fire(E)})}).then(y)},tr.prototype.where=function(p){if(typeof p=="string")return new this.db.WhereClause(this,p);if(o(p))return new this.db.WhereClause(this,"[".concat(p.join("+"),"]"));var y=a(p);if(y.length===1)return this.where(y[0]).equals(p[y[0]]);var x=this.schema.indexes.concat(this.schema.primKey).filter(function(O){if(O.compound&&y.every(function(de){return 0<=O.keyPath.indexOf(de)})){for(var ee=0;ee<y.length;++ee)if(y.indexOf(O.keyPath[ee])===-1)return!1;return!0}return!1}).sort(function(O,ee){return O.keyPath.length-ee.keyPath.length})[0];if(x&&this.db._maxKey!==ci)return D=x.keyPath.slice(0,y.length),this.where(D).equals(D.map(function(O){return p[O]}));!x&&Ce&&console.warn("The query ".concat(JSON.stringify(p)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(y.join("+"),"]"));var S=this.schema.idxByName;function E(O,ee){return Ft(O,ee)===0}var D=y.reduce(function(re,ee){var de=re[0],re=re[1],X=S[ee],te=p[ee];return[de||X,de||!X?ui(re,X&&X.multi?function(ae){return ae=_(ae,ee),o(ae)&&ae.some(function(se){return E(te,se)})}:function(ae){return E(te,_(ae,ee))}):re]},[null,null]),A=D[0],D=D[1];return A?this.where(A.name).equals(p[A.keyPath]).filter(D):x?this.filter(D):this.where(y).equals("")},tr.prototype.filter=function(p){return this.toCollection().and(p)},tr.prototype.count=function(p){return this.toCollection().count(p)},tr.prototype.offset=function(p){return this.toCollection().offset(p)},tr.prototype.limit=function(p){return this.toCollection().limit(p)},tr.prototype.each=function(p){return this.toCollection().each(p)},tr.prototype.toArray=function(p){return this.toCollection().toArray(p)},tr.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},tr.prototype.orderBy=function(p){return new this.db.Collection(new this.db.WhereClause(this,o(p)?"[".concat(p.join("+"),"]"):p))},tr.prototype.reverse=function(){return this.toCollection().reverse()},tr.prototype.mapToClass=function(p){for(var y=this.db,x=this.name,S=((this.schema.mappedClass=p).prototype instanceof Om&&(p=(D=>{var O=re,ee=D;if(typeof ee!="function"&&ee!==null)throw new TypeError("Class extends value "+String(ee)+" is not a constructor or null");function de(){this.constructor=O}function re(){return D!==null&&D.apply(this,arguments)||this}return r(O,ee),O.prototype=ee===null?Object.create(ee):(de.prototype=ee.prototype,new de),Object.defineProperty(re.prototype,"db",{get:function(){return y},enumerable:!1,configurable:!0}),re.prototype.table=function(){return x},re})(p)),new Set),E=p.prototype;E;E=c(E))Object.getOwnPropertyNames(E).forEach(function(D){return S.add(D)});function A(D){if(!D)return D;var O,ee=Object.create(p.prototype);for(O in D)if(!S.has(O))try{ee[O]=D[O]}catch{}return ee}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=A,this.hook("reading",A),p},tr.prototype.defineClass=function(){return this.mapToClass(function(p){l(this,p)})},tr.prototype.add=function(p,y){var x=this,S=this.schema.primKey,E=S.auto,A=S.keyPath,D=p;return A&&E&&(D=hl(A)(p)),this._trans("readwrite",function(O){return x.core.mutate({trans:O,type:"add",keys:y!=null?[y]:null,values:[D]})}).then(function(O){return O.numFailures?ke.reject(O.failures[0]):O.lastResult}).then(function(O){if(A)try{M(p,A,O)}catch{}return O})},tr.prototype.upsert=function(p,y){var x=this,S=this.schema.primKey.keyPath;return this._trans("readwrite",function(E){return x.core.get({trans:E,key:p}).then(function(A){var D=A??{};return $m(D,y),S&&M(D,S,p),x.core.mutate({trans:E,type:"put",values:[D],keys:[p],upsert:!0,updates:{keys:[p],changeSpecs:[y]}}).then(function(O){return O.numFailures?ke.reject(O.failures[0]):!!A})})})},tr.prototype.update=function(p,y){return typeof p!="object"||o(p)?this.where(":id").equals(p).modify(y):(p=_(p,this.schema.primKey.keyPath))===void 0?yr(new Le.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(p).modify(y)},tr.prototype.put=function(p,y){var x=this,S=this.schema.primKey,E=S.auto,A=S.keyPath,D=p;return A&&E&&(D=hl(A)(p)),this._trans("readwrite",function(O){return x.core.mutate({trans:O,type:"put",values:[D],keys:y!=null?[y]:null})}).then(function(O){return O.numFailures?ke.reject(O.failures[0]):O.lastResult}).then(function(O){if(A)try{M(p,A,O)}catch{}return O})},tr.prototype.delete=function(p){var y=this;return this._trans("readwrite",function(x){return y.core.mutate({trans:x,type:"delete",keys:[p]}).then(function(S){return pl(y,[p],S)}).then(function(S){return S.numFailures?ke.reject(S.failures[0]):void 0})})},tr.prototype.clear=function(){var p=this;return this._trans("readwrite",function(y){return p.core.mutate({trans:y,type:"deleteRange",range:Mm}).then(function(x){return pl(p,null,x)})}).then(function(y){return y.numFailures?ke.reject(y.failures[0]):void 0})},tr.prototype.bulkGet=function(p){var y=this;return this._trans("readonly",function(x){return y.core.getMany({keys:p,trans:x}).then(function(S){return S.map(function(E){return y.hook.reading.fire(E)})})})},tr.prototype.bulkAdd=function(p,y,x){var S=this,E=Array.isArray(y)?y:void 0,A=(x=x||(E?void 0:y))?x.allKeys:void 0;return this._trans("readwrite",function(D){var O=S.schema.primKey,de=O.auto,O=O.keyPath;if(O&&E)throw new Le.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbou
38nd keys");if(E&&E.length!==p.length)throw new Le.InvalidArgument("Arguments objects and keys must have the same length");var ee=p.length,de=O&&de?p.map(hl(O)):p;return S.core.mutate({trans:D,type:"add",keys:E,values:de,wantResults:A}).then(function(re){var X=re.numFailures,te=re.failures;if(X===0)return A?re.results:re.lastResult;throw new dt("".concat(S.name,".bulkAdd(): ").concat(X," of ").concat(ee," operations failed"),te)})})},tr.prototype.bulkPut=function(p,y,x){var S=this,E=Array.isArray(y)?y:void 0,A=(x=x||(E?void 0:y))?x.allKeys:void 0;return this._trans("readwrite",function(D){var O=S.schema.primKey,de=O.auto,O=O.keyPath;if(O&&E)throw new Le.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(E&&E.length!==p.length)throw new Le.InvalidArgument("Arguments objects and keys must have the same length");var ee=p.length,de=O&&de?p.map(hl(O)):p;return S.core.mutate({trans:D,type:"put",keys:E,values:de,wantResults:A}).then(function(re){var X=re.numFailures,te=re.failures;if(X===0)return A?re.results:re.lastResult;throw new dt("".concat(S.name,".bulkPut(): ").concat(X," of ").concat(ee," operations failed"),te)})})},tr.prototype.bulkUpdate=function(p){var y=this,x=this.core,S=p.map(function(D){return D.key}),E=p.map(function(D){return D.changes}),A=[];return this._trans("readwrite",function(D){return x.getMany({trans:D,keys:S,cache:"clone"}).then(function(O){var ee=[],de=[],re=(p.forEach(function(X,te){var ae=X.key,se=X.changes,ne=O[te];if(ne){for(var ie=0,me=Object.keys(se);ie<me.length;ie++){var pe=me[ie],ve=se[pe];if(pe===y.schema.primKey.keyPath){if(Ft(ve,ae)!==0)throw new Le.Constraint("Cannot update primary key in bulkUpdate()")}else M(ne,pe,ve)}A.push(te),ee.push(ae),de.push(ne)}}),ee.length);return x.mutate({trans:D,type:"put",keys:ee,values:de,updates:{keys:S,changeSpecs:E}}).then(function(X){var te=X.numFailures,ae=X.failures;if(te===0)return re;for(var se=0,ne=Object.keys(ae);se<ne.length;se++){var ie,me=ne[se],pe=A[Number(me)];pe!=null&&(ie=ae[me],delete ae[me],ae[pe]=ie)}throw new dt("".concat(y.name,".bulkUpdate(): ").concat(te," of ").concat(re," operations failed"),ae)})})})},tr.prototype.bulkDelete=function(p){var y=this,x=p.length;return this._trans("readwrite",function(S){return y.core.mutate({trans:S,type:"delete",keys:p}).then(function(E){return pl(y,p,E)})}).then(function(S){var E=S.numFailures,A=S.failures;if(E===0)return S.lastResult;throw new dt("".concat(y.name,".bulkDelete(): ").concat(E," of ").concat(x," operations failed"),A)})};var zm=tr;function tr(){}function Ma(p){function y(D,O){if(O){for(var ee=arguments.length,de=new Array(ee-1);--ee;)de[ee-1]=arguments[ee];return x[D].subscribe.apply(null,de),p}
vendor: 69,682 bytes, line 38
38if(typeof D=="string")return x[D]}var x={};y.addEventType=A;for(var S=1,E=arguments.length;S<E;++S)A(arguments[S]);return y;function A(D,O,ee){var de,re;if(typeof D!="object")return O=O||fe,re={subscribers:[],fire:ee=ee||tt,subscribe:function(X){re.subscribers.indexOf(X)===-1&&(re.subscribers.push(X),re.fire=O(re.fire,X))},unsubscribe:function(X){re.subscribers=re.subscribers.filter(function(te){return te!==X}),re.fire=re.subscribers.reduce(O,ee)}},x[D]=y[D]=re;a(de=D).forEach(function(X){var te=de[X];if(o(te))A(X,de[X][0],de[X][1]);else{if(te!=="asap")throw new Le.InvalidArgument("Invalid event config");var ae=A(X,ct,function(){for(var se=arguments.length,ne=new Array(se);se--;)ne[se]=arguments[se];ae.subscribers.forEach(function(ie){k(function(){ie.apply(null,ne)})})})}})}}function Oa(p,y){return v(y).from({prototype:p}),y}function Gi(p,y){return!(p.filter||p.algorithm||p.or)&&(y?p.justLimit:!p.replayFilter)}function Gu(p,y){p.filter=ui(p.filter,y)}function Wu(p,y,x){var S=p.replayFilter;p.replayFilter=S?function(){return ui(S(),y())}:y,p.justLimit=x&&!S}function ml(p,y){if(p.isPrimKey)return y.primaryKey;var x=y.getIndexByKeyPath(p.index);if(x)return x;throw new Le.Schema("KeyPath "+p.index+" on object store "+y.name+" is not indexed")}function Km(p,y,x){var S=ml(p,y.schema);return y.openCursor({trans:x,values:!p.keysOnly,reverse:p.dir==="prev",unique:!!p.unique,query:{index:S,range:p.range}})}function gl(p,y,x,S){var E,A,D=p.replayFilter?ui(p.filter,p.replayFilter()):p.filter;return p.or?(E={},A=function(O,ee,de){var re,X;D&&!D(ee,de,function(te){return ee.stop(te)},function(te){return ee.fail(te)})||((X=""+(re=ee.primaryKey))=="[object ArrayBuffer]"&&(X=""+new Uint8Array(re)),f(E,X))||(E[X]=!0,y(O,ee,de))},Promise.all([p.or._iterate(A,x),qm(Km(p,S,x),p.algorithm,A,!p.keysOnly&&p.valueMapper)])):qm(Km(p,S,x),ui(p.algorithm,D),y,!p.keysOnly&&p.valueMapper)}function qm(p,y,x,S){var E=ur(S?function(A,D,O){return x(S(A),D,O)}:x);return p.then(function(A){if(A)return A.start(function(){var D=function(){return A.continue()};y&&!y(A,function(O){return D=O},function(O){A.stop(O),D=tt},function(O){A.fail(O),D=tt})||E(A.value,A,function(O){return D=O}),D()})})}Ht.prototype._read=function(p,y){var x=this._ctx;return x.error?x.table._trans(null,yr.bind(null,x.error)):x.table._trans("readonly",p).then(y)},Ht.prototype._write=function(p){var y=this._ctx;return y.error?y.table._trans(null,yr.bind(null,y.error)):y.table._trans("readwrite",p,"locked")},Ht.prototype._addAlgorithm=function(p){var y=this._ctx;y.algorithm=ui(y.algorithm,p)},Ht.prototype._iterate=function(p,y){return gl(this._ctx,p,y,this._ctx.table.core)},Ht.prototype.clone=function(p){var y=Object.create(this.constructor.prototype),x=Object.create(this._ctx);return p&&l(x,p),y._ctx=x,y},Ht.prototype.raw=function(){return this._ctx.valueMapper=null,this},Ht.prototype.each=function(p){var y=this._ctx;return this._read(function(x){return gl(y,p,x,y.table.core)})},Ht.prototype.count=function(p){var y=this;return this._read(function(x){var S,E=y._ctx,A=E.table.core;return Gi(E,!0)?A.count({trans:x,query:{index:ml(E,A.schema),range:E.range}}).then(function(D){return Math.min(D,E.limit)}):(S=0,gl(E,function(){return++S,!1},x,A).then(function(){return S}))}).then(p)},Ht.prototype.sortBy=function(p,y){var x=p.split(".").reverse(),S=x[0],E=x.length-1;function A(ee,de){return de?A(ee[x[de]],de-1):ee[S]}var D=this._ctx.dir==="next"?1:-1;function O(ee,de){return Ft(A(ee,E),A(de,E))*D}return this.toArray(function(ee){return ee.slice().sort(O)}).then(y)},Ht.prototype.toArray=function(p){var y=this;return this._read(function(x){var S,E,A,D=y._ctx;return Gi(D,!0)&&0<D.limit?(S=D.valueMapper,E=ml(D,D.table.core.schema),D.table.core.query({trans:x,limit:D.limit,values:!0,direction:D.dir==="prev"?"prev":void 0,query:{index:E,range:D.range}}).then(function(O){return O=O.result,S?O.map(S):O})):(A=[],gl(D,function(O){return A.push(O)},x,D.table.core).then(function(){return A}))},p)},Ht.prototype.offset=function(p){var y=this._ctx;return p<=0||(y.offset+=p,Gi(y)?Wu(y,function(){var x=p;return function(S,E){return x===0||(x===1?--x:E(function(){S.advance(x),x=0}),!1)}}):Wu(y,function(){var x=p;return function(){return--x<0}})),this},Ht.prototype.limit=function(p){return this._ctx.limit=Math.min(this._ctx.limit,p),Wu(this._ctx,function(){var y=p;return function(x,S,E){return--y<=0&&S(E),0<=y}},!0),this},Ht.prototype.until=function(p,y){return Gu(this._ctx,function(x,S,E){return!p(x.value)||(S(E),y)}),this},Ht.prototype.first=function(p){return this.limit(1).toArray(function(y){return y[0]}).then(p)},Ht.prototype.last=function(p){return this.reverse().first(p)},Ht.prototype.filter=function(p){var y;return Gu(this._ctx,function(x){return p(x.value)}),(y=this._ctx).isMatch=ui(y.isMatch,p),this},Ht.prototype.and=function(p){return this.filter(p)},Ht.prototype.or=function(p){return new this.db.WhereClause(this._ctx.table,p,this)},Ht.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Ht.prototype.desc=function(){return this.reverse()},Ht.prototype.eachKey=function(p){var y=this._ctx;return y.keysOnly=!y.isMatch,this.each(function(x,S){p(S.key,S)})},Ht.prototype.eachUniqueKey=function(p){return this._ctx.unique="unique",this.eachKey(p)},Ht.prototype.eachPrimaryKey=function(p){var y=this._ctx;return y.keysOnly=!y.isMatch,this.each(function(x,S){p(S.primaryKey,S)})},Ht.prototype.keys=function(p){var y=this._ctx,x=(y.keysOnly=!y.isMatch,[]);return this.each(function(S,E){x.push(E.key)}).then(function(){return x}).then(p)},Ht.prototype.primaryKeys=function(p){var y=this._ctx;if(Gi(y,!0)&&0<y.limit)return this._read(function(S){var E=ml(y,y.table.core.schema);return y.table.core.query({trans:S,values:!1,limit:y.limit,direction:y.dir==="prev"?"prev":void 0,query:{index:E,range:y.range}})}).then(function(S){return S.result}).then(p);y.keysOnly=!y.isMatch;var x=[];return this.each(function(S,E){x.push(E.primaryKey)}).then(function(){return x}).then(p)},Ht.prototype.uniqueKeys=function(p){return this._ctx.unique="unique",this.keys(p)},Ht.prototype.firstKey=function(p){return this.limit(1).keys(function(y){return y[0]}).then(p)},Ht.prototype.lastKey=function(p){return this.reverse().firstKey(p)},Ht.prototype.distinct=function(){var p,y=this._ctx,y=y.index&&y.table.schema.idxByName[y.index];return y&&y.multi&&(p={},Gu(this._ctx,function(S){var S=S.primaryKey.toString(),E=f(p,S);return p[S]=!0,!E})),this},Ht.prototype.modify=function(p){var y=this,x=this._ctx;return this._write(function(S){function E(ne,ie){var me=ie.failures;te+=ne-ie.numFailures;for(var pe=0,ve=a(me);pe<ve.length;pe++){var Ne=ve[pe];X.push(me[Ne])}}var A=typeof p=="function"?p:function(ne){return $m(ne,p)},D=x.table.core,re=D.schema.primaryKey,O=re.outbound,ee=re.extractKey,de=200,re=y.db._options.modifyChunkSize,X=(re&&(de=typeof re=="object"?re[D.name]||re["*"]||200:re),[]),te=0,ae=[],se=p===Hm;return y.clone().primaryKeys().then(function(ne){function ie(pe){var ve=Math.min(de,ne.length-pe),Ne=ne.slice(pe,pe+ve);return(se?Promise.resolve([]):D.getMany({trans:S,keys:Ne,cache:"immutable"})).then(function(Pe){var Oe=[],Be=[],Je=O?[]:null,Me=se?Ne:[];if(!se)for(var Ze=0;Ze<ve;++Ze){var Re=Pe[Ze],mt={value:Q(Re),primKey:ne[pe+Ze]};A.call(mt,mt.value,mt)!==!1&&(mt.value==null?Me.push(ne[pe+Ze]):O||Ft(ee(Re),ee(mt.value))===0?(Be.push(mt.value),O&&Je.push(ne[pe+Ze])):(Me.push(ne[pe+Ze]),Oe.push(mt.value)))}return Promise.resolve(0<Oe.length&&D.mutate({trans:S,type:"add",values:Oe}).then(function(gt){for(var Tt in gt.failures)Me.splice(parseInt(Tt),1);E(Oe.length,gt)})).then(function(){return(0<Be.length||me&&typeof p=="object")&&D.mutate({trans:S,type:"put",keys:Je,values:Be,criteria:me,changeSpec:typeof p!="function"&&p,isAdditionalChunk:0<pe}).then(function(gt){return E(Be.length,gt)})}).then(function(){return(0<Me.length||me&&se)&&D.mutate({trans:S,type:"delete",keys:Me,criteria:me,isAdditionalChunk:0<pe}).then(function(gt){return pl(x.table,Me,gt)}).then(function(gt){return E(Me.length,gt)})}).then(function(){return ne.length>pe+ve&&ie(pe+de)})})}var me=Gi(x)&&x.limit===1/0&&(typeof p!="function"||se)&&{index:x.index,range:x.range};return ie(0).then(function(){if(0<X.length)throw new We("Error modifying one or more objects",X,te,ae);return ne.length})})})},Ht.prototype.delete=function(){var p=this._ctx,y=p.range;return!Gi(p)||p.table.schema.yProps||!p.isPrimKey&&y.type!==3?this.modify(Hm):this._write(function(x){var S=p.table.core.schema.primaryKey,E=y;return p.table.core.count({trans:x,query:{index:S,range:E}}).then(function(A){return p.table.core.mutate({trans:x,type:"deleteRange",range:E}).then(function(ee){var O=ee.failures,ee=ee.numFailures;if(ee)throw new We("Could not delete some values",Object.keys(O).map(function(de){return O[de]}),A-ee);return A-ee})})})};var D2=Ht;function Ht(){}var Hm=function(p,y){return y.value=null};function L2(p,y){return p<y?-1:p===y?0:1}function M2(p,y){return y<p?-1:p===y?0:1}function un(p,y,x){return p=p instanceof Wm?new p.Collection(p):p,p._ctx.error=new(x||TypeError)(y),p}function Wi(p){return new p.Collection(p,function(){return Gm("")}).limit(0)}function yl(ae,y,x,S){var E,A,D,O,ee,de,re,X=x.length;if(!x.every(function(ne){return typeof ne=="string"}))return un(ae,Lm);function te(ne){E=ne==="next"?function(me){return me.toUpperCase()}:function(me){return me.toLowerCase()},A=ne==="next"?function(me){return me.toLowerCase()}:function(me){return me.toUpperCase()},D=ne==="next"?L2:M2;var ie=x.map(function(me){return{lower:A(me),upper:E(me)}}).sort(function(me,pe){return D(me.lower,pe.lower)});O=ie.map(function(me){return me.upper}),ee=ie.map(function(me){return me.lower}),re=(de=ne)==="next"?"":S}te("next");var ae=new ae.Collection(ae,function(){return Rs(O[0],ee[X-1]+S)}),se=(ae._ondirectionchange=function(ne){te(ne)},0);return ae._addAlgorithm(function(ne,ie,me){var pe=ne.key;if(typeof pe=="string"){var ve=A(pe);if(y(ve,ee,se))return!0;for(var Ne=null,Pe=se;Pe<X;++Pe){var Oe=((Be,Je,Me,Ze,Re,mt)=>{for(var gt=Math.min(Be.length,Ze.length),Tt=-1,Mt=0;Mt<gt;++Mt){var dn=Je[Mt];if(dn!==Ze[Mt])return Re(Be[Mt],Me[Mt])<0?Be.substr(0,Mt)+Me[Mt]+Me.substr(Mt+1):Re(Be[Mt],Ze[Mt])<0?Be.substr(0,Mt)+Ze[Mt]+Me.substr(Mt+1):0<=Tt?Be.substr(0,Tt)+Je[Tt]+Me.substr(Tt+1):null;Re(Be[Mt],dn)<0&&(Tt=Mt)}return gt<Ze.length&&mt==="next"?Be+Me.substr(Be.length):gt<Be.length&&mt==="prev"?Be.substr(0,Me.length):Tt<0?null:Be.substr(0,Tt)+Ze[Tt]+Me.substr(Tt+1)})(pe,ve,O[Pe],ee[Pe],D,de);Oe===null&&Ne===null?se=Pe+1:(Ne===null||0<D(Ne,Oe))&&(Ne=Oe)}ie(Ne!==null?function(){ne.continue(Ne+re)}:me)}return!1}),ae}function Rs(p,y,x,S){return{type:2,lower:p,upper:y,lowerOpen:x,upperOpen:S}}function Gm(p){return{type:1,lower:p,upper:p}}Object.defineProperty(Tr.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),Tr.prototype.between=function(p,y,x,S){x=x!==!1,S=S===!0;try{return 0<this._cmp(p,y)||this._cmp(p,y)===0&&(x||S)&&(!x||!S)?Wi(this):new this.Collection(this,function(){return Rs(p,y,!x,!S)})}catch{return un(this,ms)}},Tr.prototype.equals=function(p){return p==null?un(this,ms):new this.Collection(this,function(){return Gm(p)})},Tr.prototype.above=function(p){return p==null?un(this,ms):new this.Collection(this,function(){return Rs(p,void 0,!0)})},Tr.prototype.aboveOrEqual=function(p){return p==null?un(this,ms):new this.Collection(this,function(){return Rs(p,void 0,!1)})},Tr.prototype.below=function(p){return p==null?un(this,ms):new this.Collection(this,function(){return Rs(void 0,p,!1,!0)})},Tr.prototype.belowOrEqual=function(p){return p==null?un(this,ms):new this.Collection(this,function(){return Rs(void 0,p)})},Tr.prototype.startsWith=function(p){return typeof p!="string"?un(this,Lm):this.between(p,p+ci,!0,!0)},Tr.prototype.startsWithIgnoreCase=function(p){return p===""?this.startsWith(p):yl(this,function(y,x){return y.indexOf(x[0])===0},[p],ci)},Tr.prototype.equalsIgnoreCase=function(p){return yl(this,function(y,x){return y===x[0]},[p],"")},Tr.prototype.anyOfIgnoreCase=function(){var p=B.apply(le,arguments);return p.length===0?Wi(this):yl(this,function(y,x){return x.indexOf(y)!==-1},p,"")},Tr.prototype.startsWithAnyOfIgnoreCase=function(){var p=B.apply(le,arguments);return p.length===0?Wi(this):yl(this,function(y,x){return x.some(function(S){return y.indexOf(S)===0})},p,ci)},Tr.prototype.anyOf=function(){var p,y,x=this,S=B.apply(le,arguments),E=this._cmp;try{S.sort(E)}catch{return un(this,ms)}return S.length===0?Wi(this):((p=new this.Collection(this,function(){return Rs(S[0],S[S.length-1])}))._ondirectionchange=function(A){E=A==="next"?x._ascending:x._descending,S.sort(E)},y=0,p._addAlgorithm(function(A,D,O){for(var ee=A.key;0<E(ee,S[y]);)if(++y===S.length)return D(O),!1;return E(ee,S[y])===0||(D(function(){A.continue(S[y])}),!1)}),p)},Tr.prototype.notEqual=function(p){return this.inAnyRange([[-1/0,p],[p,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},Tr.prototype.noneOf=function(){var p=B.apply(le,arguments);if(p.length===0)return new this.Collection(this);try{p.sort(this._ascending)}catch{return un(this,ms)}var y=p.reduce(function(x,S){return x?x.concat([[x[x.length-1][1],S]]):[[-1/0,S]]},null);return y.push([p[p.length-1],this.db._maxKey]),this.inAnyRange(y,{includeLowers:!1,includeUppers:!1})},Tr.prototype.inAnyRange=function(p,me){var x=this,S=this._cmp,E=this._ascending,A=this._descending,D=this._min,O=this._max;if(p.length===0)return Wi(this);if(!p.every(function(pe){return pe[0]!==void 0&&pe[1]!==void 0&&E(pe[0],pe[1])<=0}))return un(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Le.InvalidArgument);var ee=!me||me.includeLowers!==!1,de=me&&me.includeUppers===!0,re,X=E;function te(pe,ve){return X(pe[0],ve[0])}try{(re=p.reduce(function(pe,ve){for(var Ne=0,Pe=pe.length;Ne<Pe;++Ne){var Oe=pe[Ne];if(S(ve[0],Oe[1])<0&&0<S(ve[1],Oe[0])){Oe[0]=D(Oe[0],ve[0]),Oe[1]=O(Oe[1],ve[1]);break}}return Ne===Pe&&pe.push(ve),pe},[])).sort(te)}catch{return un(this,ms)}var ae=0,se=de?function(pe){return 0<E(pe,re[ae][1])}:function(pe){return 0<=E(pe,re[ae][1])},ne=ee?function(pe){return 0<A(pe,re[ae][0])}:function(pe){return 0<=A(pe,re[ae][0])},ie=se,me=new this.Collection(this,function(){return Rs(re[0][0],re[re.length-1][1],!ee,!de)});return me._ondirectionchange=function(pe){X=pe==="next"?(ie=se,E):(ie=ne,A),re.sort(te)},me._addAlgorithm(function(pe,ve,Ne){for(var Pe,Oe=pe.key;ie(Oe);)if(++ae===re.length)return ve(Ne),!1;return!se(Pe=Oe)&&!ne(Pe)||(x._cmp(Oe,re[ae][1])===0||x._cmp(Oe,re[ae][0])===0||ve(function(){X===E?pe.continue(re[ae][0]):pe.continue(re[ae][1])}),!1)}),me},Tr.prototype.startsWithAnyOf=function(){var p=B.apply(le,arguments);return p.every(function(y){return typeof y=="string"})?p.length===0?Wi(this):this.inAnyRange(p.map(function(y){return[y,y+ci]})):un(this,"startsWithAnyOf() only works with strings")};var Wm=Tr;function Tr(){}function On(p){return ur(function(y){return Fa(y),p(y.target.error),!1})}function Fa(p){p.stopPropagation&&p.stopPropagation(),p.preventDefault&&p.preventDefault()}var vl="storagemutated",Yu="x-storagemutated-1",Ps=Ma(null,vl),O2=(Wn.prototype._lock=function(){return I(!$e.global),++this._reculock,this._reculock!==1||$e.global||($e.lockOwnerFor=this),this},Wn.prototype._unlock=function(){if(I(!$e.global),--this._reculock==0)for($e.global||($e.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var p=this._blockedFuncs.shift();try{li(p[1],p[0])}catch{}}return this},Wn.prototype._locked=function(){return this._reculock&&$e.lockOwnerFor!==this},Wn.prototype.create=function(p){var y=this;if(this.mode){var x=this.db.idbdb,S=this.db._state.dbOpenError;if(I(!this.idbtrans),!p&&!x)switch(S&&S.name){case"DatabaseClosedError":throw new Le.DatabaseClosed(S);case"MissingAPIError":throw new Le.MissingAPI(S.message,S);default:throw new Le.OpenFailed(S)}if(!this.active)throw new Le.TransactionInactive;I(this._completion._state===null),(p=this.idbtrans=p||(this.db.core||x).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=ur(function(E){Fa(E),y._reject(p.error)}),p.onabort=ur(function(E){Fa(E),y.active&&y._reject(new Le.Abort(p.error)),y.active=!1,y.on("abort").fire(E)}),p.oncomplete=ur(function(){y.active=!1,y._resolve(),"mutatedParts"in p&&Ps.storagemutated.fire(p.mutatedParts)})}return this},Wn.prototype._promise=function(p,y,x){var S,E=this;return p==="readwrite"&&this.mode!=="readwrite"?yr(new Le.ReadOnly("Transaction is readonly")):this.active?this._locked()?new ke(function(A,D){E._blockedFuncs.push([function(){E._promise(p,y,x).then(A,D)},$e])}):x?As(function(){var A=new ke(function(D,O){E._lock();var ee=y(D,O,E);ee&&ee.then&&ee.then(D,O)});return A.finally(function(){return E._unlock()}),A._lib=!0,A}):((S=new ke(function(A,D){var O=y(A,D,E);O&&O.then&&O.then(A,D)}))._lib=!0,S):yr(new Le.TransactionInactive)},Wn.prototype._root=function(){return this.parent?this.parent._root():this},Wn.prototype.waitFor=function(p){var y,x=this._root(),S=ke.resolve(p),E=(x._waitingFor?x._waitingFor=x._waitingFor.then(function(){return S}):(x._waitingFor=S,x._waitingQueue=[],y=x.idbtrans.objectStore(x.storeNames[0]),function A(){for(++x._spinCount;x._waitingQueue.length;)x._waitingQueue.shift()();x._waitingFor&&(y.get(-1/0).onsuccess=A)}()),x._waitingFor);return new ke(function(A,D){S.then(function(O){return x._waitingQueue.push(ur(A.bind(null,O)))},function(O){return x._waitingQueue.push(ur(D.bind(null,O)))}).finally(function(){x._waitingFor===E&&(x._waitingFor=null)})})},Wn.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Le.Abort))},Wn.prototype.table=function(p){var y=this._memoizedTables||(this._memoizedTables={});if(f(y,p))return y[p];var x=this.schema[p];if(x)return(x=new this.db.Table(p,x,this)).core=this.db.core.table(p),y[p]=x;throw new Le.NotFound("Table "+p+" not part of transaction")},Wn);function Wn(){}function Qu(p,y,x,S,E,A,D,O){return{name:p,keyPath:y,unique:x,multi:S,auto:E,compound:A,src:(x&&!D?"&":"")+(S?"*":"")+(E?"++":"")+Ym(y),type:O}}function Ym(p){return typeof p=="string"?p:p?"["+[].join.call(p,"+")+"]":""}function Xu(p,y,x){return{name:p,primKey:y,indexes:x,mappedClass:null,idxByName:(S=function(E){return[E.name,E]},x.reduce(function(E,A,D){return A=S(A,D),A&&(E[A[0]]=A[1]),E},{}))};var S}var Ua=function(p){try{return p.only([[]]),Ua=function(){return[[]]},[[]]}catch{return Ua=function(){return ci},ci}};function Ju(p){return p==null?function(){}:typeof p=="string"?(y=p).split(".").length===1?function(x){return x[y]}:function(x){return _(x,y)}:function(x){return _(x,p)};var y}function Qm(p){return[].slice.call(p)}var F2=0;function Va(p){return p==null?":id":typeof p=="string"?p:"[".concat(p.join("+"),"]")}function U2(p,y,D){function S(ie){if(ie.type===3)return null;if(ie.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var ae=ie.lower,se=ie.upper,ne=ie.lowerOpen,ie=ie.upperOpen;return ae===void 0?se===void 0?null:y.upperBound(se,!!ie):se===void 0?y.lowerBound(ae,!!ne):y.bound(ae,se,!!ne,!!ie)}function E(te){var ae,se,ne=te.name;return{name:ne,schema:te,mutate:function(ie){var me=ie.trans,pe=ie.type,ve=ie.keys,Ne=ie.values,Pe=ie.range;return new Promise(function(Oe,Be){Oe=ur(Oe);var Je=me.objectStore(ne),Me=Je.keyPath==null,Ze=pe==="put"||pe==="add";if(!Ze&&pe!=="delete"&&pe!=="deleteRange")throw new Error("Invalid operation type: "+pe);var Re,mt=(ve||Ne||{length:1}).length;if(ve&&Ne&&ve.length!==Ne.length)throw new Error("Given keys array must have same length as given values array.");if(mt===0)return Oe({numFailures:0,failures:{},results:[],lastResult:void 0});function gt(zr){++dn,Fa(zr)}var Tt=[],Mt=[],dn=0;if(pe==="deleteRange"){if(Pe.type===4)return Oe({numFailures:dn,failures:Mt,results:[],lastResult:void 0});Pe.type===3?Tt.push(Re=Je.clear()):Tt.push(Re=Je.delete(S(Pe)))}else{var Me=Ze?Me?[Ne,ve]:[Ne,null]:[ve,null],Ct=Me[0],Or=Me[1];if(Ze)for(var Fr=0;Fr<mt;++Fr)Tt.push(Re=Or&&Or[Fr]!==void 0?Je[pe](Ct[Fr],Or[Fr]):Je[pe](Ct[Fr])),Re.onerror=gt;else for(Fr=0;Fr<mt;++Fr)Tt.push(Re=Je[pe](Ct[Fr])),Re.onerror=gt}function Nl(zr){zr=zr.target.result,Tt.forEach(function(hi,gd){return hi.error!=null&&(Mt[gd]=hi.error)}),Oe({numFailures:dn,failures:Mt,results:pe==="delete"?ve:Tt.map(function(hi){return hi.result}),lastResult:zr})}Re.onerror=function(zr){gt(zr),Nl(zr)},Re.onsuccess=Nl})},getMany:function(ie){var me=ie.trans,pe=ie.keys;return new Promise(function(ve,Ne){ve=ur(ve);for(var Pe,Oe=me.objectStore(ne),Be=pe.length,Je=new Array(Be),Me=0,Ze=0,Re=function(Tt){Tt=Tt.target,Je[Tt._pos]=Tt.result,++Ze===Me&&ve(Je)},mt=On(Ne),gt=0;gt<Be;++gt)pe[gt]!=null&&((Pe=Oe.get(pe[gt]))._pos=gt,Pe.onsuccess=Re,Pe.onerror=mt,++Me);Me===0&&ve(Je)})},get:function(ie){var me=ie.trans,pe=ie.key;return new Promise(function(ve,Ne){ve=ur(ve);var Pe=me.objectStore(ne).get(pe);Pe.onsuccess=function(Oe){return ve(Oe.target.result)},Pe.onerror=On(Ne)})},query:(ae=ee,se=de,function(ie){return new Promise(function(me,pe){me=ur(me);var ve,Ne,Pe,Oe,mt=ie.trans,Be=ie.values,Je=ie.limit,Re=ie.query,Me=(Me=ie.direction)!=null?Me:"next",Ze=Je===1/0?void 0:Je,gt=Re.index,Re=Re.range,mt=mt.objectStore(ne),mt=gt.isPrimaryKey?mt:mt.index(gt.name),gt=S(Re);if(Je===0)return me({result:[]});se?(Re={query:gt,count:Ze,direction:Me},(ve=Be?mt.getAll(Re):mt.getAllKeys(Re)).onsuccess=function(Tt){return me({result:Tt.target.result})},ve.onerror=On(pe)):ae&&Me==="next"?((ve=Be?mt.getAll(gt,Ze):mt.getAllKeys(gt,Ze)).onsuccess=function(Tt){return me({result:Tt.target.result})},ve.onerror=On(pe)):(Ne=0,Pe=!Be&&"openKeyCursor"in mt?mt.openKeyCursor(gt,Me):mt.openCursor(gt,Me),Oe=[],Pe.onsuccess=function(){var Tt=Pe.result;return!Tt||(Oe.push(Be?Tt.value:Tt.primaryKey),++Ne===Je)?me({result:Oe}):void Tt.continue()},Pe.onerror=On(pe))})}),openCursor:function(ie){var me=ie.trans,pe=ie.values,ve=ie.query,Ne=ie.reverse,Pe=ie.unique;return new Promise(function(Oe,Be){Oe=ur(Oe);var Ze=ve.index,Je=ve.range,Me=me.objectStore(ne),Me=Ze.isPrimaryKey?Me:Me.index(Ze.name),Ze=Ne?Pe?"prevunique":"prev":Pe?"nextunique":"next",Re=!pe&&"openKeyCursor"in Me?Me.openKeyCursor(S(Je),Ze):Me.openCursor(S(Je),Ze);Re.onerror=On(Be),Re.onsuccess=ur(function(mt){var gt,Tt,Mt,dn,Ct=Re.result;Ct?(Ct.___id=++F2,Ct.done=!1,gt=Ct.continue.bind(Ct),Tt=(Tt=Ct.continuePrimaryKey)&&Tt.bind(Ct),Mt=Ct.advance.bind(Ct),dn=function(){throw new Error("Cursor not stopped")},Ct.trans=me,Ct.stop=Ct.continue=Ct.continuePrimaryKey=Ct.advance=function(){throw new Error("Cursor not started")},Ct.fail=ur(Be),Ct.next=function(){var Or=this,Fr=1;return this.start(function(){return Fr--?Or.continue():Or.stop()}).then(function(){return Or})},Ct.start=function(Or){function Fr(){if(Re.result)try{Or()}catch(zr){Ct.fail(zr)}else Ct.done=!0,Ct.start=function(){throw new Error("Cursor behind last entry")},Ct.stop()}var Nl=new Promise(function(zr,hi){zr=ur(zr),Re.onerror=On(hi),Ct.fail=hi,Ct.stop=function(gd){Ct.stop=Ct.continue=Ct.continuePrimaryKey=Ct.advance=dn,zr(gd)}});return Re.onsuccess=ur(function(zr){Re.onsuccess=Fr,Fr()}),Ct.continue=gt,Ct.continuePrimaryKey=Tt,Ct.advance=Mt,Fr(),Nl},Oe(Ct)):Oe(null)},Be)})},count:function(ie){var me=ie.query,pe=ie.trans,ve=me.index,Ne=me.range;return new Promise(function(Pe,Oe){var Be=pe.objectStore(ne),Be=ve.isPrimaryKey?Be:Be.index(ve.name),Je=S(Ne),Je=Je?Be.count(Je):Be.count();Je.onsuccess=ur(function(Me){return Pe(Me.target.result)}),Je.onerror=On(Oe)})}}}A=D,O=Qm((D=p).objectStoreNames),re=0<O.length?A.objectStore(O[0]):{};var A,D={schema:{name:D.name,tables:O.map(function(te){return A.objectStore(te)}).map(function(te){var ae=te.keyPath,se=te.autoIncrement,ie=o(ae),ne={},ie={name:te.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:ae==null,compound:ie,keyPath:ae,autoIncrement:se,unique:!0,extractKey:Ju(ae)},indexes:Qm(te.indexNames).map(function(me){return te.index(me)}).map(function(Ne){var Pe=Ne.name,pe=Ne.unique,ve=Ne.multiEntry,Ne=Ne.keyPath,Pe={name:Pe,compound:o(Ne),keyPath:Ne,unique:pe,multiEntry:ve,extractKey:Ju(Ne)};return ne[Va(Ne)]=Pe}),getIndexByKeyPath:function(me){return ne[Va(me)]}};return ne[":id"]=ie.primaryKey,ae!=null&&(ne[Va(ae)]=ie.primaryKey),ie})},hasGetAll:0<O.length&&"getAll"in re&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in re},O=D.schema,ee=D.hasGetAll,de=D.hasIdb3Features,re=O.tables.map(E),X={};return re.forEach(function(te){return X[te.name]=te}),{stack:"dbcore",transaction:p.transaction.bind(p),table:function(te){if(X[te])return X[te];throw new Error("Table '".concat(te,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Ua(y),schema:O}}function V2(p,y,x,S){return x=x.IDBKeyRange,y=U2(y,x,S),{dbcore:p.dbcore.reduce(function(E,A){return A=A.create,n(n({},E),A(E))},y)}}function xl(p,y){var x=y.db,x=V2(p._middlewares,x,p._deps,y);p.core=x.dbcore,p.tables.forEach(function(S){var E=S.name;p.core.schema.tables.some(function(A){return A.name===E})&&(S.core=p.core.table(E),p[E]instanceof p.Table)&&(p[E].core=S.core)})}function bl(p,y,x,S){x.forEach(function(E){var A=S[E];y.forEach(function(D){var O=function ee(de,re){return w(de,re)||(de=c(de))&&ee(de,re)}(D,E);(!O||"value"in O&&O.value===void 0)&&(D===p.Transaction.prototype||D instanceof p.Transaction?g(D,E,{get:function(){return this.table(E)},set:function(ee){m(this,E,{value:ee,writable:!0,configurable:!0,enumerable:!0})}}):D[E]=new p.Table(E,A))})})}function Zu(p,y){y.forEach(function(x){for(var S in x)x[S]instanceof p.Table&&delete x[S]})}function $2(p,y){return p._cfg.version-y._cfg.version}function z2(p,y,x,S){var E=p._dbSchema,A=(x.objectStoreNames.contains("$meta")&&!E.$meta&&(E.$meta=Xu("$meta",Jm("")[0],[]),p._storeNames.push("$meta")),p._createTransaction("readwrite",p._storeNames,E)),D=(A.create(x),A._completion.catch(S),A._reject.bind(A)),O=$e.transless||$e;As(function(){if($e.trans=A,$e.transless=O,y!==0)return xl(p,x),de=y,((ee=A).storeNames.includes("$meta")?ee.table("$meta").get("version").then(function(re){return re??de}):ke.resolve(de)).then(function(ie){var X=p,te=ie,ae=A,se=x,ne=[],ie=X._versions,me=X._dbSchema=Cl(0,X.idbdb,se);return(ie=ie.filter(function(pe){return pe._cfg.version>=te})).length===0?ke.resolve():(ie.forEach(function(pe){ne.push(function(){var ve,Ne,Pe,Oe=me,Be=pe._cfg.dbschema,Je=(Sl(X,Oe,se),Sl(X,Be,se),me=X._dbSchema=Be,ed(Oe,Be)),Me=(Je.add.forEach(function(Ze){td(se,Ze[0],Ze[1].primKey,Ze[1].indexes)}),Je.change.forEach(function(Ze){if(Ze.recreate)throw new Le.Upgrade("Not yet support for changing primary key");var Re=se.objectStore(Ze.name);Ze.add.forEach(function(mt){return wl(Re,mt)}),Ze.change.forEach(function(mt){Re.deleteIndex(mt.name),wl(Re,mt)}),Ze.del.forEach(function(mt){return Re.deleteIndex(mt)})}),pe._cfg.contentUpgrade);if(Me&&pe._cfg.version>te)return xl(X,se),ae._memoizedTables={},ve=V(Be),Je.del.forEach(function(Ze){ve[Ze]=Oe[Ze]}),Zu(X,[X.Transaction.prototype]),bl(X,[X.Transaction.prototype],a(ve),ve),ae.schema=ve,(Ne=Te(Me))&&Hi(),Be=ke.follow(function(){var Ze;(Pe=Me(ae))&&Ne&&(Ze=ks.bind(null,null),Pe.then(Ze,Ze))}),Pe&&typeof Pe.then=="function"?ke.resolve(Pe):Be.then(function(){return Pe})}),ne.push(function(ve){var Ne,Pe,Oe=pe._cfg.dbschema;Ne=Oe,Pe=ve,[].slice.call(Pe.db.objectStoreNames).forEach(function(Be){return Ne[Be]==null&&Pe.db.deleteObjectStore(Be)}),Zu(X,[X.Transaction.prototype]),bl(X,[X.Transaction.prototype],X._storeNames,X._dbSchema),ae.schema=X._dbSchema}),ne.push(function(ve){X.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(X.idbdb.version/10)===pe._cfg.version?(X.idbdb.deleteObjectStore("$meta"),delete X._dbSchema.$meta,X._storeNames=X._storeNames.filter(function(Ne){return Ne!=="$meta"})):ve.objectStore("$meta").put(pe._cfg.version,"version"))})}),function pe(){return ne.length?ke.resolve(ne.shift()(ae.idbtrans)).then(pe):ke.resolve()}().then(function(){Xm(me,se)}))}).catch(D);var ee,de;a(E).forEach(function(re){td(x,re,E[re].primKey,E[re].indexes)}),xl(p,x),ke.follow(function(){return p.on.populate.fire(A)}).catch(D)})}function K2(p,y){Xm(p._dbSchema,y),y.db.version%10!=0||y.objectStoreNames.contains("$meta")||y.db.createObjectStore("$meta").add(Math.ceil(y.db.version/10-1),"version");var x=Cl(0,p.idbdb,y);Sl(p,p._dbSchema,y);for(var S=0,E=ed(x,p._dbSchema).change;S<E.length;S++){var A=(D=>{if(D.change.length||D.recreate)return console.warn("Unable to patch indexes of table ".concat(D.name," because it has changes on the type of index or primary key.")),{value:void 0};var O=y.objectStore(D.name);D.add.forEach(function(ee){Ce&&console.debug("Dexie upgrade patch: Creating missing index ".concat(D.name,".").concat(ee.src)),wl(O,ee)})})(E[S]);if(typeof A=="object")return A.value}}function ed(p,y){var x,S={del:[],add:[],change:[]};for(x in p)y[x]||S.del.push(x);for(x in y){var E=p[x],A=y[x];if(E){var D={name:x,def:A,recreate:!1,del:[],add:[],change:[]};if(""+(E.primKey.keyPath||"")!=""+(A.primKey.keyPath||"")||E.primKey.auto!==A.primKey.auto)D.recreate=!0,S.change.push(D);else{var O=E.idxByName,ee=A.idxByName,de=void 0;for(de in O)ee[de]||D.del.push(de);for(de in ee){var re=O[de],X=ee[de];re?re.src!==X.src&&D.change.push(X):D.add.push(X)}(0<D.del.length||0<D.add.length||0<D.change.length)&&S.change.push(D)}}else S.add.push([x,A])}return S}function td(p,y,x,S){var E=p.db.createObjectStore(y,x.keyPath?{keyPath:x.keyPath,autoIncrement:x.auto}:{autoIncrement:x.auto});S.forEach(function(A){return wl(E,A)})}function Xm(p,y){a(p).forEach(function(x){y.db.objectStoreNames.contains(x)||(Ce&&console.debug("Dexie: Creating missing table",x),td(y,x,p[x].primKey,p[x].indexes))})}function wl(p,y){p.createIndex(y.name,y.keyPath,{unique:y.unique,multiEntry:y.multi})}function Cl(p,y,x){var S={};return C(y.objectStoreNames,0).forEach(function(E){for(var A=x.objectStore(E),D=Qu(Ym(de=A.keyPath),de||"",!0,!1,!!A.autoIncrement,de&&typeof de!="string",!0),O=[],ee=0;ee<A.indexNames.length;++ee){var re=A.index(A.indexNames[ee]),de=re.keyPath,re=Qu(re.name,de,!!re.unique,!!re.multiEntry,!1,de&&typeof de!="string",!1);O.push(re)}S[E]=Xu(E,D,O)}),S}function Sl(p,y,x){for(var S=x.db.objectStoreNames,E=0;E<S.length;++E){var A=S[E],D=x.objectStore(A);p._hasGetAll="getAll"in D;for(var O=0;O<D.indexNames.length;++O){var ee,de=D.indexNames[O],re=D.index(de).keyPath,re=typeof re=="string"?re:"["+C(re).join("+")+"]";y[A]&&(ee=y[A].idxByName[re])&&(ee.name=de,delete y[A].idxByName[re],y[A].idxByName[de]=ee)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&i.WorkerGlobalScope&&i instanceof i.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(p._hasGetAll=!1)}function Jm(p){return p.split(",").map(function(y,x){var E=y.split(":"),S=(S=E[1])==null?void 0:S.trim(),E=(y=E[0].trim()).replace(/([&*]|\+\+)/g,""),A=/^\[/.test(E)?E.match(/^\[(.*)\]$/)[1].split("+"):E;return Qu(E,A||null,/\&/.test(y),/\*/.test(y),/\+\+/.test(y),o(A),x===0,S)})}Yi.prototype._createTableSchema=Xu,Yi.prototype._parseIndexSyntax=Jm,Yi.prototype._parseStoresSpec=function(p,y){var x=this;a(p).forEach(function(S){if(p[S]!==null){var E=x._parseIndexSyntax(p[S]),A=E.shift();if(!A)throw new Le.Schema("Invalid schema for table "+S+": "+p[S]);if(A.unique=!0,A.multi)throw new Le.Schema("Primary key cannot be multiEntry*");E.forEach(function(D){if(D.auto)throw new Le.Schema("Only primary key can be marked as autoIncrement (++)");if(!D.keyPath)throw new Le.Schema("Index must have a name and cannot be an empty string")}),A=x._createTableSchema(S,A,E),y[S]=A}})},Yi.prototype.stores=function(x){var y=this.db,x=(this._cfg.storesSource=this._cfg.storesSource?l(this._cfg.storesSource,x):x,y._versions),S={},E={};return x.forEach(function(A){l(S,A._cfg.storesSource),E=A._cfg.dbschema={},A._parseStoresSpec(S,E)}),y._dbSchema=E,Zu(y,[y._allTables,y,y.Transaction.prototype]),bl(y,[y._allTables,y,y.Transaction.prototype,this._cfg.tables],a(E),E),y._storeNames=a(E),this},Yi.prototype.upgrade=function(p){return this._cfg.contentUpgrade=W(this._cfg.contentUpgrade||tt,p),this};var q2=Yi;function Yi(){}var $a=(()=>{var p,y,x;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(p=new Set,y=new FinalizationRegistry(function(S){p.delete(S)}),{toArray:function(){return Array.from(p).map(function(S){return S.deref()}).filter(function(S){return S!==void 0})},add:function(S){var E=new WeakRef(S._novip);p.add(E),y.register(S._novip,E,E),p.size>S._options.maxConnections&&(E=p.values().next().value,p.delete(E),y.unregister(E))},remove:function(S){if(S)for(var E=p.values(),A=E.next();!A.done;){var D=A.value;if(D.deref()===S._novip)return p.delete(D),void y.unregister(D);A=E.next()}}}):(x=[],{toArray:function(){return x},add:function(S){x.push(S._novip)},remove:function(S){S&&(S=x.indexOf(S._novip))!==-1&&x.splice(S,1)}})})();function rd(p,y){var x=p._dbNamesDB;return x||(x=p._dbNamesDB=new gs(fl,{addons:[],indexedDB:p,IDBKeyRange:y})).version(1).stores({dbnames:"name"}),x.table("dbnames")}function nd(p){return p&&typeof p.databases=="function"}function sd(p){return As(function(){return $e.letThrough=!0,p()})}function id(p){return!("from"in p)}var Mr=function(p,y){var x;if(!this)return x=new Mr,p&&"d"in p&&l(x,p),x;l(this,arguments.length?{d:1,from:p,to:1<arguments.length?y:p}:{d:0})};function za(p,y,x){var S=Ft(y,x);if(!isNaN(S)){if(0<S)throw RangeError();if(id(p))return l(p,{from:y,to:x,d:1});var S=p.l,E=p.r;if(Ft(x,p.from)<0)return S?za(S,y,x):p.l={from:y,to:x,d:1,l:null,r:null},eg(p);if(0<Ft(y,p.to))return E?za(E,y,x):p.r={from:y,to:x,d:1,l:null,r:null},eg(p);Ft(y,p.from)<0&&(p.from=y,p.l=null,p.d=E?E.d+1:1),0<Ft(x,p.to)&&(p.to=x,p.r=null,p.d=p.l?p.l.d+1:1),y=!p.r,S&&!p.l&&Ka(p,S),E&&y&&Ka(p,E)}}function Ka(p,y){id(y)||function x(S,E){var A=E.from,D=E.l,O=E.r;za(S,A,E.to),D&&x(S,D),O&&x(S,O)}(p,y)}function Zm(p,y){var x=El(y),S=x.next();if(!S.done)for(var E=S.value,A=El(p),D=A.next(E.from),O=D.value;!S.done&&!D.done;){if(Ft(O.from,E.to)<=0&&0<=Ft(O.to,E.from))return!0;Ft(E.from,O.from)<0?E=(S=x.next(O.from)).value:O=(D=A.next(E.from)).value}return!1}function El(p){var y=id(p)?null:{s:0,n:p};return{next:function(x){for(var S=0<arguments.length;y;)switch(y.s){case 0:if(y.s=1,S)for(;y.n.l&&Ft(x,y.n.from)<0;)y={up:y,n:y.n.l,s:1};else for(;y.n.l;)y={up:y,n:y.n.l,s:1};case 1:if(y.s=2,!S||Ft(x,y.n.to)<=0)return{value:y.n,done:!1};case 2:if(y.n.r){y.s=3,y={up:y,n:y.n.r,s:0};continue}case 3:y=y.up}return{done:!0}}}}function eg(p){var y,x,S,E=(((E=p.r)==null?void 0:E.d)||0)-(((E=p.l)==null?void 0:E.d)||0),E=1<E?"r":E<-1?"l":"";E&&(y=E=="r"?"l":"r",x=n({},p),S=p[E],p.from=S.from,p.to=S.to,p[E]=S[E],x[E]=S[y],(p[y]=x).d=tg(x)),p.d=tg(p)}function tg(x){var y=x.r,x=x.l;return(y?x?Math.max(y.d,x.d):y.d:x?x.d:0)+1}function Tl(p,y){return a(y).forEach(function(x){p[x]?Ka(p[x],y[x]):p[x]=function S(E){var A,D,O={};for(A in E)f(E,A)&&(D=E[A],O[A]=!D||typeof D!="object"||H.has(D.constructor)?D:S(D));return O}(y[x])}),p}function ad(p,y){return p.all||y.all||Object.keys(p).some(function(x){return y[x]&&Zm(y[x],p[x])})}h(Mr.prototype,((ue={add:function(p){return Ka(this,p),this},addKey:function(p){return za(this,p,p),this},addKeys:function(p){var y=this;return p.forEach(function(x){return za(y,x,x)}),this},hasKey:function(p){var y=El(this).next(p).value;return y&&Ft(y.from,p)<=0&&0<=Ft(y.to,p)}})[xe]=function(){return El(this)},ue));var di={},od={},ld=!1;function _l(p){Tl(od,p),ld||(ld=!0,setTimeout(function(){ld=!1,cd(od,!(od={}))},0))}function cd(p,y){y===void 0&&(y=!1);var x=new Set;if(p.all)for(var S=0,E=Object.values(di);S<E.length;S++)rg(O=E[S],p,x,y);else for(var A in p){var D,O,A=/^idb\:\/\/(.*)\/(.*)\//.exec(A);A&&(D=A[1],A=A[2],O=di["idb://".concat(D,"/").concat(A)])&&rg(O,p,x,y)}x.forEach(function(ee){return ee()})}function rg(p,y,x,S){for(var E=[],A=0,D=Object.entries(p.queries.query);A<D.length;A++){for(var O=D[A],ee=O[0],de=[],re=0,X=O[1];re<X.length;re++){var te=X[re];ad(y,te.obsSet)?te.subscribers.forEach(function(ie){return x.add(ie)}):S&&de.push(te)}S&&E.push([ee,de])}if(S)for(var ae=0,se=E;ae<se.length;ae++){var ne=se[ae],ee=ne[0],de=ne[1];p.queries.query[ee]=de}}function H2(p){var y=p._state,x=p._deps.indexedDB;if(y.isBeingOpened||p.idbdb)return y.dbReadyPromise.then(function(){return y.dbOpenError?yr(y.dbOpenError):p});y.isBeingOpened=!0,y.dbOpenError=null,y.openComplete=!1;var S=y.openCanceller,E=Math.round(10*p.verno),A=!1;function D(){if(y.openCanceller!==S)throw new Le.DatabaseClosed("db.open() was cancelled")}function O(){return new ke(function(te,ae){if(D(),!x)throw new Le.MissingAPI;var se=p.name,ne=y.autoSchema||!E?x.open(se):x.open(se,E);if(!ne)throw new Le.MissingAPI;ne.onerror=On(ae),ne.onblocked=ur(p._fireOnBlocked),ne.onupgradeneeded=ur(function(ie){var me;re=ne.transaction,y.autoSchema&&!p._options.allowEmptyDB?(ne.onerror=Fa,re.abort(),ne.result.close(),(me=x.deleteDatabase(se)).onsuccess=me.onerror=ur(function(){ae(new Le.NoSuchDatabase("Database ".concat(se," doesnt exist")))})):(re.onerror=On(ae),me=ie.oldVersion>Math.pow(2,62)?0:ie.oldVersion,X=me<1,p.idbdb=ne.result,A&&K2(p,re),z2(p,me/10,re,ae))},ae),ne.onsuccess=ur(function(){re=null;var ie,me,pe,ve,Ne,Pe,Oe=p.idbdb=ne.result,Be=C(Oe.objectStoreNames);if(0<Be.length)try{var Je=Oe.transaction((Ne=Be).length===1?Ne[0]:Ne,"readonly");if(y.autoSchema)Pe=Oe,ve=Je,(pe=p).verno=Pe.version/10,ve=pe._dbSchema=Cl(0,Pe,ve),pe._storeNames=C(Pe.objectStoreNames,0),bl(pe,[pe._allTables],a(ve),ve);else if(Sl(p,p._dbSchema,Je),me=Je,((me=ed(Cl(0,(ie=p).idbdb,me),ie._dbSchema)).add.length||me.change.some(function(Me){return Me.add.length||Me.change.length}))&&!A)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Oe.close(),E=Oe.version+1,A=!0,te(O());xl(p,Je)}catch{}$a.add(p),Oe.onversionchange=ur(function(Me){y.vcFired=!0,p.on("versionchange").fire(Me)}),Oe.onclose=ur(function(){p.close({disableAutoOpen:!1})}),X&&(Be=p._deps,Ne=se,nd(Pe=Be.indexedDB)||Ne===fl||rd(Pe,Be.IDBKeyRange).put({name:Ne}).catch(tt)),te()},ae)}).catch(function(te){switch(te?.name){case"UnknownError":if(0<y.PR1398_maxLoop)return y.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),O();break;case"VersionError":if(0<E)return E=0,O()}return ke.reject(te)})}var ee,de=y.dbReadyResolve,re=null,X=!1;return ke.race([S,(typeof navigator>"u"?ke.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(te){function ae(){return indexedDB.databases().finally(te)}ee=setInterval(ae,100),ae()}).finally(function(){return clearInterval(ee)}):Promise.resolve()).then(O)]).then(function(){return D(),y.onReadyBeingFired=[],ke.resolve(sd(function(){return p.on.ready.fire(p.vip)})).then(function te(){var ae;if(0<y.onReadyBeingFired.length)return ae=y.onReadyBeingFired.reduce(W,tt),y.onReadyBeingFired=[],ke.resolve(sd(function(){return ae(p.vip)})).then(te)})}).finally(function(){y.openCanceller===S&&(y.onReadyBeingFired=null,y.isBeingOpened=!1)}).catch(function(te){y.dbOpenError=te;try{re&&re.abort()}catch{}return S===y.openCanceller&&p._close(),yr(te)}).finally(function(){y.openComplete=!0,de()}).then(function(){var te;return X&&(te={},p.tables.forEach(function(ae){ae.schema.indexes.forEach(function(se){se.name&&(te["idb://".concat(p.name,"/").concat(ae.name,"/").concat(se.name)]=new Mr(-1/0,[[[]]]))}),te["idb://".concat(p.name,"/").concat(ae.name,"/")]=te["idb://".concat(p.name,"/").concat(ae.name,"/:dels")]=new Mr(-1/0,[[[]]])}),Ps(vl).fire(te),cd(te,!0)),p})}function ud(p){function y(A){return p.next(A)}var x=E(y),S=E(function(A){return p.throw(A)});function E(A){return function(O){var O=A(O),ee=O.value;return O.done?ee:ee&&typeof ee.then=="function"?ee.then(x,S):o(ee)?Promise.all(ee).then(x,S):x(ee)}}return E(y)()}function Il(p,y,x){for(var S=o(p)?p.slice():[p],E=0;E<x;++E)S.push(y);return S}var G2={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(p){return n(n({},p),{table:function(S){var x=p.table(S),S=x.schema,E={},A=[];function D(te,ae,se){var pe=Va(te),ne=E[pe]=E[pe]||[],ie=te==null?0:typeof te=="string"?1:te.length,me=0<ae,pe=n(n({},se),{name:me?"".concat(pe,"(virtual-from:").concat(se.name,")"):se.name,lowLevelIndex:se,isVirtual:me,keyTail:ae,keyLength:ie,extractKey:Ju(te),unique:!me&&se.unique});return ne.push(pe),pe.isPrimaryKey||A.push(pe),1<ie&&D(ie===2?te[0]:te.slice(0,ie-1),ae+1,se),ne.sort(function(ve,Ne){return ve.keyTail-Ne.keyTail}),pe}var O=D(S.primaryKey.keyPath,0,S.primaryKey);E[":id"]=[O];for(var ee=0,de=S.indexes;ee<de.length;ee++){var re=de[ee];D(re.keyPath,0,re)}function X(te){var ae,se=te.query.index;return se.isVirtual?n(n({},te),{query:{index:se.lowLevelIndex,range:(ae=te.query.range,se=se.keyTail,{type:ae.type===1?2:ae.type,lower:Il(ae.lower,ae.lowerOpen?p.MAX_KEY:p.MIN_KEY,se),lowerOpen:!0,upper:Il(ae.upper,ae.upperOpen?p.MIN_KEY:p.MAX_KEY,se),upperOpen:!0})}}):te}return n(n({},x),{schema:n(n({},S),{primaryKey:O,indexes:A,getIndexByKeyPath:function(te){return(te=E[Va(te)])&&te[0]}}),count:function(te){return x.count(X(te))},query:function(te){return x.query(X(te))},openCursor:function(te){var ae=te.query.index,se=ae.keyTail,ne=ae.keyLength;return ae.isVirtual?x.openCursor(X(te)).then(function(me){return me&&ie(me)}):x.openCursor(te);function ie(me){return Object.create(me,{continue:{value:function(pe){pe!=null?me.continue(Il(pe,te.reverse?p.MAX_KEY:p.MIN_KEY,se)):te.unique?me.continue(me.key.slice(0,ne).concat(te.reverse?p.MIN_KEY:p.MAX_KEY,se)):me.continue()}},continuePrimaryKey:{value:function(pe,ve){me.continuePrimaryKey(Il(pe,p.MAX_KEY,se),ve)}},primaryKey:{get:function(){return me.primaryKey}},key:{get:function(){var pe=me.key;return ne===1?pe[0]:pe.slice(0,ne)}},value:{get:function(){return me.value}}})}}})}})}};function dd(p,y,x,S){return x=x||{},S=S||"",a(p).forEach(function(E){var A,D,O;f(y,E)?(A=p[E],D=y[E],typeof A=="object"&&typeof D=="object"&&A&&D?(O=oe(A))!==oe(D)?x[S+E]=y[E]:O==="Object"?dd(A,D,x,S+E+"."):A!==D&&(x[S+E]=y[E]):A!==D&&(x[S+E]=y[E])):x[S+E]=void 0}),a(y).forEach(function(E){f(p,E)||(x[S+E]=y[E])}),x}function fd(p,y){return y.type==="delete"?y.keys:y.keys||y.values.map(p.extractKey)}var W2={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(p){return n(n({},p),{table:function(y){var x=p.table(y),S=x.schema.primaryKey;return n(n({},x),{mutate:function(E){var A=$e.trans,D=A.table(y).hook,O=D.deleting,ee=D.creating,de=D.updating;switch(E.type){case"add":if(ee.fire===tt)break;return A._promise("readwrite",function(){return re(E)},!0);case"put":if(ee.fire===tt&&de.fire===tt)break;return A._promise("readwrite",function(){return re(E)},!0);case"delete":if(O.fire===tt)break;return A._promise("readwrite",function(){return re(E)},!0);case"deleteRange":if(O.fire===tt)break;return A._promise("readwrite",function(){return function X(te,ae,se){return x.query({trans:te,values:!1,query:{index:S,range:ae},limit:se}).then(function(ne){var ie=ne.result;return re({type:"delete",keys:ie,trans:te}).then(function(me){return 0<me.numFailures?Promise.reject(me.failures[0]):ie.length<se?{failures:[],numFailures:0,lastResult:void 0}:X(te,n(n({},ae),{lower:ie[ie.length-1],lowerOpen:!0}),se)})})}(E.trans,E.range,1e4)},!0)}return x.mutate(E);function re(X){var te,ae,se,ne=$e.trans,ie=X.keys||fd(S,X);if(ie)return(X=X.type==="add"||X.type==="put"?n(n({},X),{keys:ie}):n({},X)).type!=="delete"&&(X.values=s([],X.values)),X.keys&&(X.keys=s([],X.keys)),te=x,se=ie,((ae=X).type==="add"?Promise.resolve([]):te.getMany({trans:ae.trans,keys:se,cache:"immutable"})).then(function(me){var pe=ie.map(function(ve,Ne){var Pe,Oe,Be,Je=me[Ne],Me={onerror:null,onsuccess:null};return X.type==="delete"?O.fire.call(Me,ve,Je,ne):X.type==="add"||Je===void 0?(Pe=ee.fire.call(Me,ve,X.values[Ne],ne),ve==null&&Pe!=null&&(X.keys[Ne]=ve=Pe,S.outbound||M(X.values[Ne],S.keyPath,ve))):(Pe=dd(Je,X.values[Ne]),(Oe=de.fire.call(Me,Pe,ve,Je,ne))&&(Be=X.values[Ne],Object.keys(Oe).forEach(function(Ze){f(Be,Ze)?Be[Ze]=Oe[Ze]:M(Be,Ze,Oe[Ze])}))),Me});return x.mutate(X).then(function(ve){for(var Ne=ve.failures,Pe=ve.results,Oe=ve.numFailures,ve=ve.lastResult,Be=0;Be<ie.length;++Be){var Je=(Pe||ie)[Be],Me=pe[Be];Je==null?Me.onerror&&Me.onerror(Ne[Be]):Me.onsuccess&&Me.onsuccess(X.type==="put"&&me[Be]?X.values[Be]:Je)}return{failures:Ne,results:Pe,numFailures:Oe,lastResult:ve}}).catch(function(ve){return pe.forEach(function(Ne){return Ne.onerror&&Ne.onerror(ve)}),Promise.reject(ve)})});throw new Error("Keys missing")}}})}})}};function ng(p,y,x){try{if(!y||y.keys.length<p.length)return null;for(var S=[],E=0,A=0;E<y.keys.length&&A<p.length;++E)Ft(y.keys[E],p[A])===0&&(S.push(x?Q(y.values[E]):y.values[E]),++A);return S.length===p.length?S:null}catch{return null}}var Y2={stack:"dbcore",level:-1,create:function(p){return{table:function(y){var x=p.table(y);return n(n({},x),{getMany:function(S){var E;return S.cache?(E=ng(S.keys,S.trans._cache,S.cache==="clone"))?ke.resolve(E):x.getMany(S).then(function(A){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?Q(A):A},A}):x.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),x.mutate(S)}})}}}};function sg(p,y){return p.trans.mode==="readonly"&&!!p.subscr&&!p.trans.explicit&&p.trans.db._options.cache!=="disabled"&&!y.schema.primaryKey.outbound}function ig(p,y){switch(p){case"query":return y.values&&!y.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var Q2={stack:"dbcore",level:0,name:"Observability",create:function(p){var y=p.schema.name,x=new Mr(p.MIN_KEY,p.MAX_KEY);return n(n({},p),{transaction:function(S,E,A){if($e.subscr&&E!=="readonly")throw new Le.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat($e.querier));return p.transaction(S,E,A)},table:function(S){function E(ie){var ne,ie=ie.query;return[ne=ie.index,new Mr((ne=(ie=ie.range).lower)!=null?ne:p.MIN_KEY,(ne=ie.upper)!=null?ne:p.MAX_KEY)]}var A=p.table(S),D=A.schema,O=D.primaryKey,ee=D.indexes,de=O.extractKey,re=O.outbound,X=O.autoIncrement&&ee.filter(function(se){return se.compound&&se.keyPath.includes(O.keyPath)}),te=n(n({},A),{mutate:function(se){function ne(Re){return Re="idb://".concat(y,"/").concat(S,"/").concat(Re),Ne[Re]||(Ne[Re]=new Mr)}var ie,me,pe,ve=se.trans,Ne=se.mutatedParts||(se.mutatedParts={}),Pe=ne(""),Oe=ne(":dels"),Be=se.type,Me=se.type==="deleteRange"?[se.range]:se.type==="delete"?[se.keys]:se.values.length<50?[fd(O,se).filter(function(Re){return Re}),se.values]:[],Je=Me[0],Me=Me[1],Ze=se.trans._cache;return o(Je)?(Pe.addKeys(Je),(Be=Be==="delete"||Je.length===Me.length?ng(Je,Ze):null)||Oe.addKeys(Je),(Be||Me)&&(ie=ne,me=Be,pe=Me,D.indexes.forEach(function(Re){var mt=ie(Re.name||"");function gt(Mt){return Mt!=null?Re.extractKey(Mt):null}function Tt(Mt){Re.multiEntry&&o(Mt)?Mt.forEach(function(dn){return mt.addKey(dn)}):mt.addKey(Mt)}(me||pe).forEach(function(Mt,Or){var Ct=me&&gt(me[Or]),Or=pe&&gt(pe[Or]);Ft(Ct,Or)!==0&&(Ct!=null&&Tt(Ct),Or!=null)&&Tt(Or)})}))):Je?(Me={from:(Ze=Je.lower)!=null?Ze:p.MIN_KEY,to:(Be=Je.upper)!=null?Be:p.MAX_KEY},Oe.add(Me),Pe.add(Me)):(Pe.add(x),Oe.add(x),D.indexes.forEach(function(Re){return ne(Re.name).add(x)})),A.mutate(se).then(function(Re){return!Je||se.type!=="add"&&se.type!=="put"||(Pe.addKeys(Re.results),X&&X.forEach(function(mt){for(var gt=se.values.map(function(Ct){return mt.extractKey(Ct)}),Tt=mt.keyPath.findIndex(function(Ct){return Ct===O.keyPath}),Mt=0,dn=Re.results.length;Mt<dn;++Mt)gt[Mt][Tt]=Re.results[Mt];ne(mt.name).addKeys(gt)})),ve.mutatedParts=Tl(ve.mutatedParts||{},Ne),Re})}}),ae={get:function(se){return[O,new Mr(se.key)]},getMany:function(se){return[O,new Mr().addKeys(se.keys)]},count:E,query:E,openCursor:E};return a(ae).forEach(function(se){te[se]=function(ne){var ie=$e.subscr,me=!!ie,pe=sg($e,A)&&ig(se,ne)?ne.obsSet={}:ie;if(me){var ve,ie=function(Me){return Me="idb://".concat(y,"/").concat(S,"/").concat(Me),pe[Me]||(pe[Me]=new Mr)},Ne=ie(""),Pe=ie(":dels"),me=ae[se](ne),Oe=me[0],me=me[1];if((se==="query"&&Oe.isPrimaryKey&&!ne.values?Pe:ie(Oe.name||"")).add(me),!Oe.isPrimaryKey){if(se!=="count")return ve=se==="query"&&re&&ne.values&&A.query(n(n({},ne),{values:!1})),A[se].apply(this,arguments).then(function(Me){if(se==="query"){if(re&&ne.values)return ve.then(function(gt){return gt=gt.result,Ne.addKeys(gt),Me});var Ze=ne.values?Me.result.map(de):Me.result;(ne.values?Ne:Pe).addKeys(Ze)}else{var Re,mt;if(se==="openCursor")return mt=ne.values,(Re=Me)&&Object.create(Re,{key:{get:function(){return Pe.addKey(Re.primaryKey),Re.key}},primaryKey:{get:function(){var gt=Re.primaryKey;return Pe.addKey(gt),gt}},value:{get:function(){return mt&&Ne.addKey(Re.primaryKey),Re.value}}})}return Me});Pe.add(x)}}return A[se].apply(this,arguments)}}),te}})}};function ag(p,y,x){var S;return x.numFailures===0?y:y.type==="deleteRange"||(S=y.keys?y.keys.length:"values"in y&&y.values?y.values.length:1,x.numFailures===S)?null:(S=n({},y),o(S.keys)&&(S.keys=S.keys.filter(function(E,A){return!(A in x.failures)})),"values"in S&&o(S.values)&&(S.values=S.values.filter(function(E,A){return!(A in x.failures)})),S)}function hd(p,y){return x=p,((S=y).lower===void 0||(S.lowerOpen?0<Ft(x,S.lower):0<=Ft(x,S.lower)))&&(x=p,(S=y).upper===void 0||(S.upperOpen?Ft(x,S.upper)<0:Ft(x,S.upper)<=0));var x,S}function og(p,y,x,S,E,A){var D,O,ee,de,re,X,te;return!x||x.length===0||(D=y.query.index,O=D.multiEntry,ee=y.query.range,de=S.schema.primaryKey.extractKey,re=D.extractKey,X=(D.lowLevelIndex||D).extractKey,(S=x.reduce(function(ae,se){var ne=ae,ie=[];if(se.type==="add"||se.type==="put")for(var me=new Mr,pe=se.values.length-1;0<=pe;--pe){var ve,Ne=se.values[pe],Pe=de(Ne);!me.hasKey(Pe)&&(ve=re(Ne),O&&o(ve)?ve.some(function(Ze){return hd(Ze,ee)}):hd(ve,ee))&&(me.addKey(Pe),ie.push(Ne))}switch(se.type){case"add":var Oe=new Mr().addKeys(y.values?ae.map(function(Re){return de(Re)}):ae),ne=ae.concat(y.values?ie.filter(function(Re){return Re=de(Re),!Oe.hasKey(Re)&&(Oe.addKey(Re),!0)}):ie.map(function(Re){return de(Re)}).filter(function(Re){return!Oe.hasKey(Re)&&(Oe.addKey(Re),!0)}));break;case"put":var Be=new Mr().addKeys(se.values.map(function(Re){return de(Re)}));ne=ae.filter(function(Re){return!Be.hasKey(y.values?de(Re):Re)}).concat(y.values?ie:ie.map(function(Re){return de(Re)}));break;case"delete":var Je=new Mr().addKeys(se.keys);ne=ae.filter(function(Re){return!Je.hasKey(y.values?de(Re):Re)});break;case"deleteRange":var Me=se.range;ne=ae.filter(function(Re){return!hd(de(Re),Me)})}return ne},p))===p)?p:(te=function(ae,se){return Ft(X(ae),X(se))||Ft(de(ae),de(se))},S.sort(y.direction==="prev"||y.direction==="prevunique"?function(ae,se){return te(se,ae)}:te),y.limit&&y.limit<1/0&&(S.length>y.limit?S.length=y.limit:p.length===y.limit&&S.length<y.limit&&(E.dirty=!0)),A?Object.freeze(S):S)}function lg(p,y){return Ft(p.lower,y.lower)===0&&Ft(p.upper,y.upper)===0&&!!p.lowerOpen==!!y.lowerOpen&&!!p.upperOpen==!!y.upperOpen}function X2(p,y){return((x,S,E,A)=>{if(x===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((x=Ft(x,S))===0){if(E&&A)return 0;if(E)return 1;if(A)return-1}return x})(p.lower,y.lower,p.lowerOpen,y.lowerOpen)<=0&&0<=((x,S,E,A)=>{if(x===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((x=Ft(x,S))===0){if(E&&A)return 0;if(E)return-1;if(A)return 1}return x})(p.upper,y.upper,p.upperOpen,y.upperOpen)}function J2(p,y,x,S){p.subscribers.add(x),S.addEventListener("abort",function(){var E,A;p.subscribers.delete(x),p.subscribers.size===0&&(E=p,A=y,setTimeout(function(){E.subscribers.size===0&&$(A,E)},3e3))})}var Z2={stack:"dbcore",level:0,name:"Cache",create:function(p){var y=p.schema.name;return n(n({},p),{transaction:function(x,S,E){var A,D,O=p.transaction(x,S,E);return S==="readwrite"&&(E=(A=new AbortController).signal,O.addEventListener("abort",(D=function(ee){return function(){if(A.abort(),S==="readwrite"){for(var de=new Set,re=0,X=x;re<X.length;re++){var te=X[re],ae=di["idb://".concat(y,"/").concat(te)];if(ae){var se=p.table(te),ne=ae.optimisticOps.filter(function(Re){return Re.trans===O});if(O._explicit&&ee&&O.mutatedParts)for(var ie=0,me=Object.values(ae.queries.query);ie<me.length;ie++)for(var pe=0,ve=(Oe=me[ie]).slice();pe<ve.length;pe++)ad((Be=ve[pe]).obsSet,O.mutatedParts)&&($(Oe,Be),Be.subscribers.forEach(function(Re){return de.add(Re)}));else if(0<ne.length){ae.optimisticOps=ae.optimisticOps.filter(function(Re){return Re.trans!==O});for(var Ne=0,Pe=Object.values(ae.queries.query);Ne<Pe.length;Ne++)for(var Oe,Be,Je,Me=0,Ze=(Oe=Pe[Ne]).slice();Me<Ze.length;Me++)(Be=Ze[Me]).res!=null&&O.mutatedParts&&(ee&&!Be.dirty?(Je=Object.isFrozen(Be.res),Je=og(Be.res,Be.req,ne,se,Be,Je),Be.dirty?($(Oe,Be),Be.subscribers.forEach(function(Re){return de.add(Re)})):Je!==Be.res&&(Be.res=Je,Be.promise=ke.resolve({result:Je}))):(Be.dirty&&$(Oe,Be),Be.subscribers.forEach(function(Re){return de.add(Re)})))}}}de.forEach(function(Re){return Re()})}}})(!1),{signal:E}),O.addEventListener("error",D(!1),{signal:E}),O.addEventListener("complete",D(!0),{signal:E})),O},table:function(x){var S=p.table(x),E=S.schema.primaryKey;return n(n({},S),{mutate:function(A){var D,O=$e.trans;return!E.outbound&&O.db._options.cache!=="disabled"&&!O.explicit&&O.idbtrans.mode==="readwrite"&&(D=di["idb://".concat(y,"/").concat(x)])?(O=S.mutate(A),A.type!=="add"&&A.type!=="put"||!(50<=A.values.length||fd(E,A).some(function(ee){return ee==null}))?(D.optimisticOps.push(A),A.mutatedParts&&_l(A.mutatedParts),O.then(function(ee){0<ee.numFailures&&($(D.optimisticOps,A),(ee=ag(0,A,ee))&&D.optimisticOps.push(ee),A.mutatedParts)&&_l(A.mutatedParts)}),O.catch(function(){$(D.optimisticOps,A),A.mutatedParts&&_l(A.mutatedParts)})):O.then(function(ee){var de=ag(0,n(n({},A),{values:A.values.map(function(re,X){var te;return ee.failures[X]?re:(M(te=(te=E.keyPath)!=null&&te.includes(".")?Q(re):n({},re),E.keyPath,ee.results[X]),te)})}),ee);D.optimisticOps.push(de),queueMicrotask(function(){return A.mutatedParts&&_l(A.mutatedParts)})}),O):S.mutate(A)},query:function(A){var D,O,ee,de,re,X,te;return sg($e,S)&&ig("query",A)?(D=((ee=$e.trans)==null?void 0:ee.db._options.cache)==="immutable",O=(ee=$e).requery,ee=ee.signal,X=((ae,se,ne,ie)=>{var me=di["idb://".concat(ae,"/").concat(se)];if(!me)return[];if(!(ae=me.queries[ne]))return[null,!1,me,null];var pe=ae[(ie.query?ie.query.index.name:null)||""];if(!pe)return[null,!1,me,null];switch(ne){case"query":var ve=(Ne=ie.direction)!=null?Ne:"next",Ne=pe.find(function(Pe){var Oe;return Pe.req.limit===ie.limit&&Pe.req.values===ie.values&&((Oe=Pe.req.direction)!=null?Oe:"next")===ve&&lg(Pe.req.query.range,ie.query.range)});return Ne?[Ne,!0,me,pe]:[pe.find(function(Pe){var Oe;return("limit"in Pe.req?Pe.req.limit:1/0)>=ie.limit&&((Oe=Pe.req.direction)!=null?Oe:"next")===ve&&(!ie.values||Pe.req.values)&&X2(Pe.req.query.range,ie.query.range)}),!1,me,pe];case"count":return Ne=pe.find(function(Pe){return lg(Pe.req.query.range,ie.query.range)}),[Ne,!!Ne,me,pe]}})(y,x,"query",A),te=X[0],de=X[2],re=X[3],te&&X[1]?te.obsSet=A.obsSet:(X=S.query(A).then(function(ae){var se=ae.result;if(te&&(te.res=se),D){for(var ne=0,ie=se.length;ne<ie;++ne)Object.freeze(se[ne]);Object.freeze(se)}return ae}).catch(function(ae){return re&&te&&$(re,te),Promise.reject(ae)}),te={obsSet:A.obsSet,promise:X,subscribers:new Set,type:"query",req:A,dirty:!1},re?re.push(te):(re=[te],(de=de||(di["idb://".concat(y,"/").concat(x)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[A.query.index.name||""]=re)),J2(te,re,O,ee),te.promise.then(function(ae){return ae=og(ae.result,A,de?.optimisticOps,S,te,D),{result:D?ae:Q(ae)}})):S.query(A)}})}})}};function Al(p,y){return new Proxy(p,{get:function(x,S,E){return S==="db"?y:Reflect.get(x,S,E)}})}vr.prototype.version=function(p){if(isNaN(p)||p<.1)throw new Le.Type("Given version is not a positive number");if(p=Math.round(10*p)/10,this.idbdb||this._state.isBeingOpened)throw new Le.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,p);var y=this._versions,x=y.filter(function(S){return S._cfg.version===p})[0];return x||(x=new this.Version(p),y.push(x),y.sort($2),x.stores({}),this._state.autoSchema=!1),x},vr.prototype._whenReady=function(p){var y=this;return this.idbdb&&(this._state.openComplete||$e.letThrough||this._vip)?p():new ke(function(x,S){if(y._state.openComplete)return S(new Le.DatabaseClosed(y._state.dbOpenError));if(!y._state.isBeingOpened){if(!y._state.autoOpen)return void S(new Le.DatabaseClosed);y.open().catch(tt)}y._state.dbReadyPromise.then(x,S)}).then(p)},vr.prototype.use=function(E){var y=E.stack,x=E.create,S=E.level,E=E.name,A=(E&&this.unuse({stack:y,name:E}),this._middlewares[y]||(this._middlewares[y]=[]));return A.push({stack:y,create:x,level:S??10,name:E}),A.sort(function(D,O){return D.level-O.level}),this},vr.prototype.unuse=function(p){var y=p.stack,x=p.name,S=p.create;return y&&this._middlewares[y]&&(this._middlewares[y]=this._middlewares[y].filter(function(E){return S?E.create!==S:!!x&&E.name!==x})),this},vr.prototype.open=function(){var p=this;return li(mr,function(){return H2(p)})},vr.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var p=this._state;if($a.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}p.isBeingOpened||(p.dbReadyPromise=new ke(function(y){p.dbReadyResolve=y}),p.openCanceller=new ke(function(y,x){p.cancelOpen=x}))},vr.prototype.close=function(y){var y=(y===void 0?{disableAutoOpen:!0}:y).disableAutoOpen,x=this._state;y?(x.isBeingOpened&&x.cancelOpen(new Le.DatabaseClosed),this._close(),x.autoOpen=!1,x.dbOpenError=new Le.DatabaseClosed):(this._close(),x.autoOpen=this._options.autoOpen||x.isBeingOpened,x.openComplete=!1,x.dbOpenError=null)},vr.prototype.delete=function(p){var y=this,x=(p===void 0&&(p={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),S=this._state;return new ke(function(E,A){function D(){y.close(p);var O=y._deps.indexedDB.deleteDatabase(y.name);O.onsuccess=ur(function(){var ee,de,re;ee=y._deps,de=y.name,nd(re=ee.indexedDB)||de===fl||rd(re,ee.IDBKeyRange).delete(de).catch(tt),E()}),O.onerror=On(A),O.onblocked=y._fireOnBlocked}if(x)throw new Le.InvalidArgument("Invalid closeOptions argument to db.delete()");S.isBeingOpened?S.dbReadyPromise.then(D):D()})},vr.prototype.backendDB=function(){return this.idbdb},vr.prototype.isOpen=function(){return this.idbdb!==null},vr.prototype.hasBeenClosed=function(){var p=this._state.dbOpenError;return p&&p.name==="DatabaseClosed"},vr.prototype.hasFailed=function(){return this._state.dbOpenError!==null},vr.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(vr.prototype,"tables",{get:function(){var p=this;return a(this._allTables).map(function(y){return p._allTables[y]})},enumerable:!1,configurable:!0}),vr.prototype.transaction=function(){var p=function(y,x,S){var E=arguments.length;if(E<2)throw new Le.InvalidArgument("Too few arguments");for(var A=new Array(E-1);--E;)A[E-1]=arguments[E];return S=A.pop(),[y,L(A),S]}.apply(this,arguments);return this._transaction.apply(this,p)},vr.prototype._transaction=function(p,y,x){var S,E,A=this,D=$e.trans,O=(D&&D.db===this&&p.indexOf("!")===-1||(D=null),p.indexOf("?")!==-1);p=p.replace("!","").replace("?","");try{if(E=y.map(function(de){if(de=de instanceof A.Table?de.name:de,typeof de!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return de}),p=="r"||p===qu)S=qu;else{if(p!="rw"&&p!=Hu)throw new Le.InvalidArgument("Invalid transaction mode: "+p);S=Hu}if(D){if(D.mode===qu&&S===Hu){if(!O)throw new Le.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");D=null}D&&E.forEach(function(de){if(D&&D.storeNames.indexOf(de)===-1){if(!O)throw new Le.SubTransaction("Table "+de+" not included in parent transaction.");D=null}}),O&&D&&!D.active&&(D=null)}}catch(de){return D?D._promise(null,function(re,X){X(de)}):yr(de)}var ee=function de(re,X,te,ae,se){return ke.resolve().then(function(){var pe=$e.transless||$e,ne=re._createTransaction(X,te,re._dbSchema,ae),pe=(ne.explicit=!0,{trans:ne,transless:pe});if(ae)ne.idbtrans=ae.idbtrans;else try{ne.create(),ne.idbtrans._explicit=!0,re._state.PR1398_maxLoop=3}catch(ve){return ve.name===ft.InvalidState&&re.isOpen()&&0<--re._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),re.close({disableAutoOpen:!1}),re.open().then(function(){return de(re,X,te,null,se)})):yr(ve)}var ie,me=Te(se),pe=(me&&Hi(),ke.follow(function(){var ve;(ie=se.call(ne,ne))&&(me?(ve=ks.bind(null,null),ie.then(ve,ve)):typeof ie.next=="function"&&typeof ie.throw=="function"&&(ie=ud(ie)))},pe));return(ie&&typeof ie.then=="function"?ke.resolve(ie).then(function(ve){return ne.active?ve:yr(new Le.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):pe.then(function(){return ie})).then(function(ve){return ae&&ne._resolve(),ne._completion.then(function(){return ve})}).catch(function(ve){return ne._reject(ve),yr(ve)})})}.bind(null,this,S,E,D,x);return D?D._promise(S,ee,"lock"):$e.trans?li($e.transless,function(){return A._whenReady(ee)}):this._whenReady(ee)},vr.prototype.table=function(p){if(f(this._allTables,p))return this._allTables[p];throw new Le.InvalidTable("Table ".concat(p," does not exist"))};var gs=vr;function vr(p,y){var x,S,E,A,D,O=this,ee=(this._middlewares={},this.verno=0,vr.dependencies),ee=(this._options=y=n({addons:vr.addons,autoOpen:!0,indexedDB:ee.indexedDB,IDBKeyRange:ee.IDBKeyRange,cache:"cloned",maxConnections:1e3},y),this._deps={indexedDB:y.indexedDB,IDBKeyRange:y.IDBKeyRange},y.addons),de=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:tt,dbReadyPromise:null,cancelOpen:tt,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:y.autoOpen}),re=(de.dbReadyPromise=new ke(function(X){de.dbReadyResolve=X}),de.openCanceller=new ke(function(X,te){de.cancelOpen=te}),this._state=de,this.name=p,this.on=Ma(this,"populate","blocked","versionchange","close",{ready:[W,tt]}),this.once=function(X,te){var ae=function(){for(var se=[],ne=0;ne<arguments.length;ne++)se[ne]=arguments[ne];O.on(X).unsubscribe(ae),te.apply(O,se)};return O.on(X,ae)},this.on.ready.subscribe=T(this.on.ready.subscribe,function(X){return function(te,ae){vr.vip(function(){var se,ne=O._state;ne.openComplete?(ne.dbOpenError||ke.resolve().then(te),ae&&X(te)):ne.onReadyBeingFired?(ne.onReadyBeingFired.push(te),ae&&X(te)):(X(te),se=O,ae||X(function ie(){se.on.ready.unsubscribe(te),se.on.ready.unsubscribe(ie)}))})}}),this.Collection=(x=this,Oa(D2.prototype,function(ie,ne){this.db=x;var ae=Mm,se=null;if(ne)try{ae=ne()}catch(pe){se=pe}var ne=ie._ctx,ie=ne.table,me=ie.hook.reading.fire;this._ctx={table:ie,index:ne.index,isPrimKey:!ne.index||ie.schema.primKey.keyPath&&ne.index===ie.schema.primKey.name,range:ae,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:se,or:ne.or,valueMapper:me!==ct?me:null}})),this.Table=(S=this,Oa(zm.prototype,function(X,te,ae){this.db=S,this._tx=ae,this.name=X,this.schema=te,this.hook=S._allTables[X]?S._allTables[X].hook:Ma(null,{creating:[Xr,tt],reading:[ht,ct],updating:[K,tt],deleting:[ps,tt]})})),this.Transaction=(E=this,Oa(O2.prototype,function(X,te,ae,se,ne){var ie=this;X!=="readonly"&&te.forEach(function(me){me=(me=ae[me])==null?void 0:me.yProps,me&&(te=te.concat(me.map(function(pe){return pe.updatesTable})))}),this.db=E,this.mode=X,this.storeNames=te,this.schema=ae,this.chromeTransactionDurability=se,this.idbtrans=null,this.on=Ma(this,"complete","error","abort"),this.parent=ne||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new ke(function(me,pe){ie._resolve=me,ie._reject=pe}),this._completion.then(function(){ie.active=!1,ie.on.complete.fire()},function(me){var pe=ie.active;return ie.active=!1,ie.on.error.fire(me),ie.parent?ie.parent._reject(me):pe&&ie.idbtrans&&ie.idbtrans.abort(),yr(me)})})),this.Version=(A=this,Oa(q2.prototype,function(X){this.db=A,this._cfg={version:X,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(D=this,Oa(Wm.prototype,function(X,te,ae){if(this.db=D,this._ctx={table:X,index:te===":id"?null:te,or:ae},this._cmp=this._ascending=Ft,this._descending=function(se,ne){return Ft(ne,se)},this._max=function(se,ne){return 0<Ft(se,ne)?se:ne},this._min=function(se,ne){return Ft(se,ne)<0?se:ne},this._IDBKeyRange=D._deps.IDBKeyRange,!this._IDBKeyRange)throw new Le.MissingAPI})),this.on("versionchange",function(X){0<X.newVersion?console.warn("Another connection wants to upgrade database '".concat(O.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(O.name,"'. Closing db now to resume the delete request.")),O.close({disableAutoOpen:!1})}),this.on("blocked",function(X){!X.newVersion||X.newVersion<X.oldVersion?console.warn("Dexie.delete('".concat(O.name,"') was blocked")):console.warn("Upgrade '".concat(O.name,"' blocked by other connection holding version ").concat(X.oldVersion/10))}),this._maxKey=Ua(y.IDBKeyRange),this._createTransaction=function(X,te,ae,se){return new O.Transaction(X,te,ae,O._options.chromeTransactionDurability,se)},this._fireOnBlocked=function(X){O.on("blocked").fire(X),$a.toArray().filter(function(te){return te.name===O.name&&te!==O&&!te._state.vcFired}).map(function(te){return te.on("versionchange").fire(X)})},this.use(Y2),this.use(Z2),this.use(Q2),this.use(G2),this.use(W2),new Proxy(this,{get:function(X,te,ae){var se;return te==="_vip"||(te==="table"?function(ne){return Al(O.table(ne),re)}:(se=Reflect.get(X,te,ae))instanceof zm?Al(se,re):te==="tables"?se.map(function(ne){return Al(ne,re)}):te==="_createTransaction"?function(){return Al(se.apply(this,arguments),re)}:se)}}));this.vip=re,ee.forEach(function(X){return X(O)})}var kl,Qi=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",eT=(pd.prototype.subscribe=function(p,y,x){return this._subscribe(p&&typeof p!="function"?p:{next:p,error:y,complete:x})},pd.prototype[Qi]=function(){return this},pd);function pd(p){this._subscribe=p}try{kl={indexedDB:i.indexedDB||i.mozIndexedDB||i.webkitIndexedDB||i.msIndexedDB,IDBKeyRange:i.IDBKeyRange||i.webkitIDBKeyRange}}catch{kl={indexedDB:null,IDBKeyRange:null}}function cg(p){var y,x=!1,S=new eT(function(E){var A=Te(p),D,O=!1,ee={},de={},re={get closed(){return O},unsubscribe:function(){O||(O=!0,D&&D.abort(),X&&Ps.storagemutated.unsubscribe(se))}},X=(E.start&&E.start(re),!1),te=function(){return Ku(ne)};function ae(){return ad(de,ee)}var se=function(ie){Tl(ee,ie),ae()&&te()},ne=function(){var ie,me,pe;!O&&kl.indexedDB&&(ee={},ie={},D&&D.abort(),D=new AbortController,pe=(ve=>{var Ne=Ki();try{A&&Hi();var Pe=As(p,ve);return Pe=A?Pe.finally(ks):Pe}finally{Ne&&qi()}})(me={subscr:ie,signal:D.signal,requery:te,querier:p,trans:null}),X||(Ps.storagemutated.subscribe(se),X=!0),Promise.resolve(pe).then(function(ve){x=!0,y=ve,O||me.signal.aborted||(ae()||(de=ie,ae())?te():(ee={},Ku(function(){return!O&&E.next&&E.next(ve)})))},function(ve){x=!1,["DatabaseClosedError","AbortError"].includes(ve?.name)||O||Ku(function(){O||E.error&&E.error(ve)})}))};return setTimeout(te,0),re});return S.hasValue=function(){return x},S.getValue=function(){return y},S}var fi=gs;function md(p){var y=js;try{js=!0,Ps.storagemutated.fire(p),cd(p,!0)}finally{js=y}}h(fi,n(n({},ye),{delete:function(p){return new fi(p,{addons:[]}).delete()},exists:function(p){return new fi(p,{addons:[]}).open().then(function(y){return y.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(p){try{return y=fi.dependencies,x=y.indexedDB,y=y.IDBKeyRange,(nd(x)?Promise.resolve(x.databases()).then(function(S){return S.map(function(E){return E.name}).filter(function(E){return E!==fl})}):rd(x,y).toCollection().primaryKeys()).then(p)}catch{return yr(new Le.MissingAPI)}var y,x},defineClass:function(){return function(p){l(this,p)}},ignoreTransaction:function(p){return $e.trans?li($e.transless||mr,p):p()},vip:sd,async:function(p){return function(){try{var y=ud(p.apply(this,arguments));return y&&typeof y.then=="function"?y:ke.resolve(y)}catch(x){return yr(x)}}},spawn:function(p,y,x){try{var S=ud(p.apply(x,y||[]));return S&&typeof S.then=="function"?S:ke.resolve(S)}catch(E){return yr(E)}},currentTransaction:{get:function(){return $e.trans||null}},waitFor:function(p,y){return p=ke.resolve(typeof p=="function"?fi.ignoreTransaction(p):p).timeout(y||6e4),$e.trans?$e.trans.waitFor(p):p},Promise:ke,debug:{get:function(){return Ce},set:function(p){Ee(p)}},derive:v,extend:l,props:h,override:T,Events:Ma,on:Ps,liveQuery:cg,extendObservabilitySet:Tl,getByKeyPath:_,setByKeyPath:M,delByKeyPath:function(p,y){typeof y=="string"?M(p,y,void 0):"length"in y&&[].map.call(y,function(x){M(p,x,void 0)})},shallowClone:V,deepClone:Q,getObjectDiff:dd,cmp:Ft,asap:k,minKey:-1/0,addons:[],connections:{get:$a.toArray}
38,errnames:ft,dependencies:kl,cache:di,semVer:"4.4.4",version:"4.4.4".split(".").map(function(p){return parseInt(p)}).reduce(function(p,y,x){return p+y/Math.pow(10,2*x)})})),fi.maxKey=Ua(fi.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Ps(vl,function(p){js||(p=new CustomEvent(Yu,{detail:p}),js=!0,dispatchEvent(p),js=!1)}),addEventListener(Yu,function(p){p=p.detail,js||md(p)}));var Xi,js=!1,ug=function(){};return typeof BroadcastChannel<"u"&&((ug=function(){(Xi=new BroadcastChannel(Yu)).onmessage=function(p){return p.data&&md(p.data)}})(),typeof Xi.unref=="function"&&Xi.unref(),Ps(vl,function(p){js||Xi.postMessage(p)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(p){if(!gs.disableBfCache&&p.persisted){Ce&&console.debug("Dexie: handling persisted pagehide"),Xi?.close();for(var y=0,x=$a.toArray();y<x.length;y++)x[y].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(p){!gs.disableBfCache&&p.persisted&&(Ce&&console.debug("Dexie: handling persisted pageshow"),ug(),md({all:new Mr(-1/0,[[]])}))})),ke.rejectionMapper=function(p,y){return!p||p instanceof Qe||p instanceof TypeError||p instanceof SyntaxError||!p.name||!Ut[p.name]?p:(y=new Ut[p.name](y||p.message,p),"stack"in p&&g(y,"stack",{get:function(){return this.inner.stack}}),y)},Ee(Ce),n(gs,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:gs,Entity:Om,PropModification:La,RangeSet:Mr,add:function(p){return new La({add:p})},cmp:Ft,default:gs,liveQuery:cg,mergeRanges:Ka,rangesOverlap:Zm,remove:function(p){return new La({remove:p})},replacePrefix:function(p,y){return new La({replacePrefix:[p,y]})}}),{default:gs}),gs})})(oE);var nU=oE.exports;const bh=Qc(nU),jy=Symbol.for("Dexie"),wh=globalThis[jy]||(globalThis[jy]=bh);if(bh.semVer!==wh.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${bh.semVer} and ${wh.semVer}`);var sU=Object.defineProperty,iU=(e,t,r)=>t in e?sU(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Gl=(e,t,r)=>iU(e,typeof t!="symbol"?t+"":t,r);class aU extends wh{constructor(){super("slinky_chat"),Gl(this,"threads"),Gl(this,"messages"),Gl(this,"toolEvents"),Gl(this,"paymentEvents"),this.version(1).stores({threads:"id, updatedAt, createdAt",messages:"id, threadId, createdAt, [threadId+createdAt]",toolEvents:"id, threadId, messageId, createdAt",paymentEvents:"id, threadId, messageId, createdAt"}),this.version(2).stores({threads:"id, updatedAt, createdAt, walletAddress, [walletAddress+updatedAt]",messages:"id, threadId, createdAt, [threadId+createdAt]",toolEvents:"id, threadId, messageId, createdAt",paymentEvents:"id, threadId, messageId, createdAt"})}}const Nt=new aU;function rl(e="id"){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}const By="slinky.chat.legacyClaimed.v1";function hm(e){return e&&e.trim().toLowerCase()||void 0}const Dy="slinky.chat.threads.v1",Ly="slinky.chat.thread.v1:",Xd="slinky.chat.migratedToDexie.v1";function pm(e){return{id:e.id,title:e.title,createdAt:e.createdAt,updatedAt:e.updatedAt,walletAddress:e.walletAddress}}function lE(e){return typeof e=="string"?{content:e,parts:[{type:"text",text:e}]}:{content:e.map(r=>r&&r.type==="text"?r.text:"").join(""),parts:e}}function oU(e){const t=e.parts??[{type:"text",text:e.content}];return{id:e.id,role:e.role,content:t}}async function lU(){if(!(typeof window>"u")&&localStorage.getItem(Xd)!=="1")try{const e=localStorage.getItem(Dy);if(!e){localStorage.setItem(Xd,"1");return}const t=JSON.parse(e);for(const r of t){await Nt.threads.get(r.id)||await Nt.threads.put({id:r.id,title:r.title||"New chat",createdAt:r.createdAt??Date.now(),updatedAt:r.updatedAt??Date.now()});const s=localStorage.getItem(Ly+r.id);if(!s)continue;const i=JSON.parse(s);let a=0;for(const o of i){const{content:l,parts:c}=lE(o.content),d=o.id||rl("m");await Nt.messages.get(d)||(await Nt.messages.put({id:d,threadId:r.id,role:o.role,content:l,parts:c,createdAt:(r.createdAt??Date.now())+a,updatedAt:(r.updatedAt??Date.now())+a,status:"complete"}),a+=1)}}localStorage.setItem(Xd,"1");try{localStorage.removeItem(Dy);for(const r of t)localStorage.removeItem(Ly+r.id)}catch{}}catch{}}async function My(e){const t=hm(e);if(!t)return[];const r=await Nt.threads.where("walletAddress").equals(t).toArray();return r.sort((n,s)=>s.updatedAt-n.updatedAt),r.map(pm)}
38async function Wl(e,t="New chat"){const r=hm(e);if(!r)return null;const n=Date.now(),s={id:pU(),title:t,createdAt:n,updatedAt:n,walletAddress:r};return await Nt.threads.put(s),pm(s)}async function cU(e){if(typeof window>"u"||localStorage.getItem(By)==="1")return;const t=hm(e);if(t)try{const n=(await Nt.threads.toArray()).filter(s=>!s.walletAddress);n.length&&await Nt.threads.bulkPut(n.map(s=>({...s,walletAddress:t}))),localStorage.setItem(By,"1")}catch{}}async function Oy(e,t){await Nt.threads.update(e,{...t,updatedAt:t.updatedAt??Date.now()})}async function uU(e){await Nt.transaction("rw",Nt.threads,Nt.messages,Nt.toolEvents,Nt.paymentEvents,async()=>{await Nt.messages.where("threadId").equals(e).delete(),await Nt.toolEvents.where("threadId").equals(e).delete(),await Nt.paymentEvents.where("threadId").equals(e).delete(),await Nt.threads.delete(e)})}async function dU(){await Nt.transaction("rw",Nt.threads,Nt.messages,Nt.toolEvents,Nt.paymentEvents,async()=>{await Nt.messages.clear(),await Nt.toolEvents.clear(),await Nt.paymentEvents.clear(),await Nt.threads.clear()})}async function fc(e){return(await Nt.messages.where("[threadId+createdAt]").between([e,-1/0],[e,1/0]).toArray()).map(oU)}async function fU(e,t){const r=Date.now();await Nt.transaction("rw",Nt.messages,Nt.threads,async()=>{await Nt.messages.where("threadId").equals(e).delete();const n=t.map((s,i)=>{const{content:a,parts:o}=lE(s.content);return{id:s.id||rl("m"),threadId:e,role:s.role,content:a,parts:o,createdAt:r+i,updatedAt:r+i,status:"complete"}});n.length&&await Nt.messages.bulkPut(n),await Nt.threads.update(e,{updatedAt:r})})}async function hU(e){const t=await Nt.threads.get(e),r=await fc(e);return{thread:t?pm(t):null,messages:r}}function pU(){return rl("t")}async function mU(e){const t=e.id??rl("tool");return await Nt.toolEvents.put({id:t,createdAt:e.createdAt??Date.now(),threadId:e.threadId,messageId:e.messageId,type:e.type,name:e.name,status:e.status}),t}async function gU(e,t){await Nt.toolEvents.update(e,t)}async function yU(e){const t=e.id??rl("pay");return await Nt.paymentEvents.put({id:t,createdAt:e.createdAt??Date.now(),threadId:e.threadId,messageId:e.messageId,provider:e.provider,amount:e.amount,currency:e.currency,status:e.status}),t}async function vU(e,t){await Nt.paymentEvents.update(e,t)}const xU="slinky.chat.activeThreadId",cE="chat:selectedModel",uE="chat:selectedTool",bU="slinky.chat.localOnly";function dE(e){if(!e)return null;const t=e.trim().toLowerCase();return t?`${xU}:${t}`:null}function wU(e){if(typeof window>"u")return null;const t=dE(e);return t?localStorage.getItem(t):null}function CU(e,t){if(typeof window>"u")return;const r=dE(e);r&&(t?localStorage.setItem(r,t):localStorage.removeItem(r))}function fE(){return typeof window>"u"?"default":localStorage.getItem(cE)||"default"}function SU(e){typeof window>"u"||localStorage.setItem(cE,e)}function hE(){return typeof window>"u"?"auto":localStorage.getItem(uE)||"auto"}function Ch(e){typeof window>"u"||localStorage.setItem(uE,e)}const EU="chat:pendingToolId";function Sh(e){return`${EU}:${e}`}function TU(e){return typeof window>"u"||!e?null:localStorage.getItem(Sh(e))}function zc(e,t){typeof window>"u"||!e||(t?localStorage.setItem(Sh(e),t):localStorage.removeItem(Sh(e)))}const _U="chat:pendingToolInputs";function Eh(e){return`${_U}:${e}`}function IU(e){if(typeof window>"u"||!e)return null;const t=localStorage.getItem(Eh(e));if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Kc(e,t){typeof window>"u"||!e||(t==null?localStorage.removeItem(Eh(e)):localStorage.setItem(Eh(e),JSON.stringify(t)))}function AU(){if(typeof window>"u")return!0;const e=localStorage.getItem(bU);return e===null?!0:e==="true"}function kU(e){const t=Date.now()-e;if(t<6e4)return"just now";const r=Math.floor(t/6e4);if(r<60)return`${r}m ago`;const n=Math.floor(r/60);if(n<24)return`${n}h ago`;const s=Math.floor(n/24);if(s<7)return`${s}d ago`;const i=Math.floor(s/7);if(i<5)return`${i}w ago`;const a=Math.floor(s/30);return a<12?`${a}mo ago`:`${Math.floor(s/365)}y ago`}function NU({threads:e,activeId:t,onSelect:r,onCreate:n,onDelete:s,onClearAll:i}){return u.jsxs("aside",{className:"flex h-full w-full flex-col border-r border-border/60 bg-background",children:[u.jsx("div",{className:"p-3",children:u.jsxs(yt,{onClick:n,className:"w-full justify-start gap-2 bg-black text-white hover:bg-[#98fe00] hover:text-black",children:[u.jsx(bx,{className:"h-4 w-4"}),"New chat"]})}),u.jsx("div",{className:"px-3 pb-2 text-[11px] font-semibold uppercase tracking-wide text-foreground
38/60",children:"Threads"}),u.jsxs("div",{className:"flex-1 overflow-y-auto px-2 pb-4",children:[e.length===0&&u.jsx("div",{className:"px-3 py-6 text-sm text-foreground/60",children:"No conversations yet."}),u.jsx("ul",{className:"space-y-1",children:e.map(a=>{const o=a.id===t;return u.jsxs("li",{className:"group relative",children:[u.jsxs("button",{onClick:()=>r(a.id),className:ze("flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors",o?"bg-[#98fe00] text-black":"text-foreground/80 hover:bg-[#98fe00]/10 hover:text-foreground"),children:[u.jsx($h,{className:ze("h-4 w-4 shrink-0",o?"text-black/70":"text-foreground/60")}),u.jsx("span",{className:"flex-1 truncate",children:a.title||"Untitled"}),u.jsx("span",{className:ze("shrink-0 text-[11px] tabular-nums transition-opacity group-hover:opacity-0",o?"text-black/60":"text-foreground/50"),children:kU(a.updatedAt)})]}),u.jsx("button",{onClick:l=>{l.stopPropagation(),s(a.id)},className:ze("absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 opacity-0 transition-opacity group-hover:opacity-100",o?"text-black/70 hover:bg-black/10 hover:text-black":"text-foreground/60 hover:bg-destructive/10 hover:text-destructive"),"aria-label":"Delete thread",children:u.jsx(a_,{className:"h-3.5 w-3.5"})})]},a.id)})})]}),i&&e.length>0&&u.jsx("div",{className:"border-t border-border/60 p-3",children:u.jsxs("button",{onClick:i,className:"inline-flex w-full items-center justify-center gap-2 rounded-md border border-border/70 px-3 py-2 text-xs text-foreground/70 hover:border-destructive/60 hover:text-destructive",children:[u.jsx(o_,{className:"h-3.5 w-3.5"}),"Destroy all chats"]})})]})}function RU(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const PU=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,jU=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,BU={};function Fy(e,t){return(BU.jsx?jU:PU).test(e)}const DU=/[ \t\n\f\r]/g;function LU(e){return typeof e=="object"?e.type==="text"?Uy(e.value):!1:Uy(e)}function Uy(e){return e.replace(DU,"")===""}class nl{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}nl.prototype.normal={};nl.prototype.property={};nl.prototype.space=void 0;function pE(e,t){const r={},n={};for(const s of e)Object.assign(r,s.property),Object.assign(n,s.normal);return new nl(r,n,t)}function Th(e){return e.toLowerCase()}class ln{constructor(t,r){this.attribute=r,this.property=t}}ln.prototype.attribute="";ln.prototype.booleanish=!1;ln.prototype.boolean=!1;ln.prototype.commaOrSpaceSeparated=!1;ln.prototype.commaSeparated=!1;ln.prototype.defined=!1;ln.prototype.mustUseProperty=!1;ln.prototype.number=!1;ln.prototype.overloadedBoolean=!1;ln.prototype.property="";ln.prototype.spaceSeparated=!1;ln.prototype.space=void 0;let MU=0;const xt=zi(),wr=zi(),_h=zi(),De=zi(),Jt=zi(),ki=zi(),fn=zi();function zi(){return 2**++MU}const Ih=Object.freeze(Object.defineProperty({__proto__:null,boolean:xt,booleanish:wr,commaOrSpaceSeparated:fn,commaSeparated:ki,number:De,overloadedBoolean:_h,spaceSeparated:Jt},Symbol.toStringTag,{value:"Module"})),Jd=Object.keys(Ih);class mm extends ln{constructor(t,r,n,s){let i=-1;if(super(t,r),Vy(this,"space",s),typeof n=="number")for(;++i<Jd.length;){const a=Jd[i];Vy(this,Jd[i],(n&Ih[a])===Ih[a])}}}mm.prototype.defined=!0;function Vy(e,t,r){r&&(e[t]=r)}function Ba(e){const t={},r={};for(const[n,s]of Object.entries(e.properties)){const i=new mm(n,e.transform(e.attributes||{},n),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),t[n]=i,r[Th(n)]=n,r[Th(i.attribute)]=n}return new nl(t,r,e.space)}const mE=Ba({properties:{ariaActiveDescendant:null,ariaAtomic:wr,ariaAutoComplete:null,ariaBusy:wr,ariaChecked:wr,ariaColCount:De,ariaColIndex:De,ariaColSpan:De,ariaControls:Jt,ariaCurrent:null,ariaDescribedBy:Jt,ariaDetails:null,ariaDisabled:wr,ariaDropEffect:Jt,ariaErrorMessage:null,ariaExpanded:wr,ariaFlowTo:Jt,ariaGrabbed:wr,ariaHasPopup:null,ariaHidden:wr,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Jt,ariaLevel:De,ariaLive:null,ariaModal:wr,ariaMultiLine:wr,ariaMultiSelectable:wr,ariaOrientation:null,ariaOwns:Jt,ariaPlaceholder:null,ariaPosInSet:De,ariaPressed:wr,ariaReadOnly:wr,ariaRelevant:null,ariaRequired:wr,ariaRoleDescription:Jt,ariaRowCount:De,ariaRowIndex:De,ariaRowSpan:De,ariaSelected:wr,ariaSetSize:De,ariaSort:null,ariaValueMax:De,ariaValueMin:De,ariaValueNow:De,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function gE(e,t){return t in e?e[t]:t}function yE(e,t){return gE(e,t.toLowerCase())}const OU=Ba({attributes:{acceptcharset:"accept-charset",classname:"
38class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ki,acceptCharset:Jt,accessKey:Jt,action:null,allow:null,allowFullScreen:xt,allowPaymentRequest:xt,allowUserMedia:xt,alpha:xt,alt:null,as:null,async:xt,autoCapitalize:null,autoComplete:Jt,autoFocus:xt,autoPlay:xt,blocking:Jt,capture:null,charSet:null,checked:xt,cite:null,className:Jt,closedBy:null,colorSpace:null,cols:De,colSpan:De,command:null,commandFor:null,content:null,contentEditable:wr,controls:xt,controlsList:Jt,coords:De|ki,crossOrigin:null,data:null,dateTime:null,decoding:null,default:xt,defer:xt,dir:null,dirName:null,disabled:xt,download:_h,draggable:wr,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:xt,formTarget:null,headers:Jt,height:De,hidden:_h,high:De,href:null,hrefLang:null,htmlFor:Jt,httpEquiv:Jt,id:null,imageSizes:null,imageSrcSet:null,inert:xt,inputMode:null,integrity:null,is:null,isMap:xt,itemId:null,itemProp:Jt,itemRef:Jt,itemScope:xt,itemType:Jt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:xt,low:De,manifest:null,max:null,maxLength:De,media:null,method:null,min:null,minLength:De,multiple:xt,muted:xt,name:null,nonce:null,noModule:xt,noValidate:xt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:xt,optimum:De,pattern:null,ping:Jt,placeholder:null,playsInline:xt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:xt,referrerPolicy:null,rel:Jt,required:xt,reversed:xt,rows:De,rowSpan:De,sandbox:Jt,scope:null,scoped:xt,seamless:xt,selected:xt,shadowRootClonable:xt,shadowRootCustomElementRegistry:xt,shadowRootDelegatesFocus:xt,shadowRootMode:null,shadowRootSerializable:xt,shape:null,size:De,sizes:null,slot:null,span:De,spellCheck:wr,src:null,srcDoc:null,srcLang:null,srcSet:null,start:De,step:null,style:null,tabIndex:De,target:null,title:null,translate:null,type:null,typeMustMatch:xt,useMap:null,value:wr,width:De,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Jt,axis:null,background:null,bgColor:null,border:De,borderColor:null,bottomMargin:De,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:xt,declare:xt,event:null,face:null,frame:null,frameBorder:null,hSpace:De,leftMargin:De,link:null,longDesc:null,lowSrc:null,marginHeight:De,marginWidth:De,noResize:xt,noHref:xt,noShade:xt,noWrap:xt,object:null,profile:null,prompt:null,rev:null,rightMargin:De,rules:null,scheme:null,scrolling:wr,standby:null,summary:null,text:null,topMargin:De,valueType:null,version:null,vAlign:null,vLink:null,vSpace:De,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:xt,disablePictureInPicture:xt,disableRemotePlayback:xt,exportParts:ki,part:Jt,prefix:null,property:null,results:De,security:null,unselectable:null},space:"html",transform:yE}),FU=Ba({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRen
38dering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",maskType:"mask-type",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav
38-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:fn,accentHeight:De,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:De,amplitude:De,arabicForm:null,ascent:De,attributeName:null,attributeType:null,azimuth:De,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:De,by:null,calcMode:null,capHeight:De,className:Jt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:De,diffuseConstant:De,direction:null,display:null,dur:null,divisor:De,dominantBaseline:null,download:xt,dx:null,dy:null,edgeMode:null,editable:null,elevation:De,enableBackground:null,end:null,event:null,exponent:De,externalResourcesRequired:null,fill:null,fillOpacity:De,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:ki,g2:ki,glyphName:ki,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:De,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:De,horizOriginX:De,horizOriginY:De,id:null,ideographic:De,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:De,k:De,k1:De,k2:De,k3:De,k4:De,kernelMatrix:fn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:De,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:De,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,on
vendor: 4,581 bytes, lines 38-39
38Zoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:De,overlineThickness:De,paintOrder:null,panose1:null,path:null,pathLength:De,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Jt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:De,pointsAtY:De,pointsAtZ:De,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:fn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:fn,rev:fn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:fn,requiredFeatures:fn,requiredFonts:fn,requiredFormats:fn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:De,specularExponent:De,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:De,strikethroughThickness:De,string:null,stroke:null,strokeDashArray:fn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:De,strokeOpacity:De,strokeWidth:null,style:null,surfaceScale:De,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:fn,tabIndex:De,tableValues:null,target:null,targetX:De,targetY:De,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:fn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:De,underlineThickness:De,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:De,values:null,vAlphabetic:De,vMathematical:De,vectorEffect:null,vHanging:De,vIdeographic:De,version:null,vertAdvY:De,vertOriginX:De,vertOriginY:De,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:De,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:gE}),vE=Ba({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),xE=Ba({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:yE}),bE=Ba({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),UU={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},VU=/[A-Z]/g,$y=/-[a-z]/g,$U=/^data[-\w.:]+$/i;function zU(e,t){const r=Th(t);let n=t,s=ln;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&$U.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace($y,qU);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!$y.test(i)){let a=i.replace(VU,KU);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}s=mm}return new s(n,t)}function KU(e){return"-"+e.toLowerCase()}function qU(e){return e.charAt(1).toUpperCase()}const HU=pE([mE,OU,vE,xE,bE],"html"),gm=pE([mE,FU,vE,xE,bE],"svg");function GU(e){return e.join(" ").trim()}var ym={},zy=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,WU=/\n/g,YU=/^\s*/,QU=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,XU=/^:\s*/,JU=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,ZU=/^[;\s]*/,eV=/^\s+|\s+$/g,tV=`
39`,Ky="/",qy="*",Ei="",rV="comment",nV="declaration";function sV(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var r=1,n=1;function s(g){var v=g.match(WU);v&&(r+=v.length);var w=g.lastIndexOf(tV);n=~w?g.length-w:n+g.length}function i(){var g={line:r,column:n};return function(v){return v.position=new a(g),c(),v}}function a(g){this.start=g,this.end={line:r,column:n},this.source=t.source}a.prototype.content=e;function o(g){var v=new Error(t.source+":"+r+":"+n+": "+g);if(v.reason=g,v.filename=t.source,v.line=r,v.column=n,v.source=e,!t.silent)throw v}function l(g){var v=g.exec(e);if(v){var w=v[0];return s(w),e=e.slice(w.length),v}}function c(){l(YU)}function d(g){var v;
vendor: 4,362 bytes, line 39
39for(g=g||[];v=f();)v!==!1&&g.push(v);return g}function f(){var g=i();if(!(Ky!=e.charAt(0)||qy!=e.charAt(1))){for(var v=2;Ei!=e.charAt(v)&&(qy!=e.charAt(v)||Ky!=e.charAt(v+1));)++v;if(v+=2,Ei===e.charAt(v-1))return o("End of comment missing");var w=e.slice(2,v-2);return n+=2,s(w),e=e.slice(v),n+=2,g({type:rV,comment:w})}}function h(){var g=i(),v=l(QU);if(v){if(f(),!l(XU))return o("property missing ':'");var w=l(JU),b=g({type:nV,property:Hy(v[0].replace(zy,Ei)),value:w?Hy(w[0].replace(zy,Ei)):Ei});return l(ZU),b}}function m(){var g=[];d(g);for(var v;v=h();)v!==!1&&(g.push(v),d(g));return g}return c(),m()}function Hy(e){return e?e.replace(eV,Ei):Ei}var iV=sV,aV=Ni&&Ni.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ym,"__esModule",{value:!0});ym.default=lV;const oV=aV(iV);function lV(e,t){let r=null;if(!e||typeof e!="string")return r;const n=(0,oV.default)(e),s=typeof t=="function";return n.forEach(i=>{if(i.type!=="declaration")return;const{property:a,value:o}=i;s?t(a,o,i):o&&(r=r||{},r[a]=o)}),r}var ju={};Object.defineProperty(ju,"__esModule",{value:!0});ju.camelCase=void 0;var cV=/^--[a-zA-Z0-9_-]+$/,uV=/-([a-z])/g,dV=/^[^-]+$/,fV=/^-(webkit|moz|ms|o|khtml)-/,hV=/^-(ms)-/,pV=function(e){return!e||dV.test(e)||cV.test(e)},mV=function(e,t){return t.toUpperCase()},Gy=function(e,t){return"".concat(t,"-")},gV=function(e,t){return t===void 0&&(t={}),pV(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(hV,Gy):e=e.replace(fV,Gy),e.replace(uV,mV))};ju.camelCase=gV;var yV=Ni&&Ni.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},vV=yV(ym),xV=ju;function Ah(e,t){var r={};return!e||typeof e!="string"||(0,vV.default)(e,function(n,s){n&&s&&(r[(0,xV.camelCase)(n,t)]=s)}),r}Ah.default=Ah;var bV=Ah;const wV=Qc(bV),wE=CE("end"),vm=CE("start");function CE(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function CV(e){const t=vm(e),r=wE(e);if(t&&r)return{start:t,end:r}}function xo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Wy(e.position):"start"in e||"end"in e?Wy(e):"line"in e||"column"in e?kh(e):""}function kh(e){return Yy(e&&e.line)+":"+Yy(e&&e.column)}function Wy(e){return kh(e&&e.start)+"-"+kh(e&&e.end)}function Yy(e){return e&&typeof e=="number"?e:1}class $r extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let s="",i={},a=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i={...r}),typeof t=="string"?s=t:!i.cause&&t&&(a=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?i.ruleId=n:(i.source=n.slice(0,l),i.ruleId=n.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=o?o.line:void 0,this.name=xo(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}$r.prototype.file="";$r.prototype.name="";$r.prototype.reason="";$r.prototype.message="";$r.prototype.stack="";$r.prototype.column=void 0;$r.prototype.line=void 0;$r.prototype.ancestors=void 0;$r.prototype.cause=void 0;$r.prototype.fatal=void 0;$r.prototype.place=void 0;$r.prototype.ruleId=void 0;$r.prototype.source=void 0;const xm={}.hasOwnProperty,SV=new Map,EV=/[A-Z]/g,TV=new Set(["table","tbody","thead","tfoot","tr"]),_V=new Set(["td","th"]),SE="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function IV(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=DV(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");
vendor: 9,199 bytes, line 39
39if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=BV(r,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?gm:HU,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=EE(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function EE(e,t,r){if(t.type==="element")return AV(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return kV(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return RV(e,t,r);if(t.type==="mdxjsEsm")return NV(e,t);if(t.type==="root")return PV(e,t,r);if(t.type==="text")return jV(e,t)}function AV(e,t,r){const n=e.schema;let s=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(s=gm,e.schema=s),e.ancestors.push(t);const i=_E(e,t.tagName,!1),a=LV(e,t);let o=wm(e,t);return TV.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!LU(l):!0})),TE(e,a,i,t),bm(a,o),e.ancestors.pop(),e.schema=n,e.create(t,i,a,r)}function kV(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}Do(e,t.position)}function NV(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Do(e,t.position)}function RV(e,t,r){const n=e.schema;let s=n;t.name==="svg"&&n.space==="html"&&(s=gm,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:_E(e,t.name,!0),a=MV(e,t),o=wm(e,t);return TE(e,a,i,t),bm(a,o),e.ancestors.pop(),e.schema=n,e.create(t,i,a,r)}function PV(e,t,r){const n={};return bm(n,wm(e,t)),e.create(t,e.Fragment,n,r)}function jV(e,t){return t.value}function TE(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function bm(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function BV(e,t,r){return n;function n(s,i,a,o){const c=Array.isArray(a.children)?r:t;return o?c(i,a,o):c(i,a)}}function DV(e,t){return r;function r(n,s,i,a){const o=Array.isArray(i.children),l=vm(n);return t(s,i,a,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function LV(e,t){const r={};let n,s;for(s in t.properties)if(s!=="children"&&xm.call(t.properties,s)){const i=OV(e,s,t.properties[s]);if(i){const[a,o]=i;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&_V.has(t.tagName)?n=o:r[a]=o}}if(n){const i=r.style||(r.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function MV(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];i.type;const a=i.expression;a.type;const o=a.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else Do(e,t.position);else{const s=n.name;let i;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const o=n.value.data.estree.body[0];o.type,i=e.evaluater.evaluateExpression(o.expression)}else Do(e,t.position);else i=n.value===null?!0:n.value;r[s]=i}return r}function wm(e,t){const r=[];let n=-1;const s=e.passKeys?new Map:SV;for(;++n<t.children.length;){const i=t.children[n];let a;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const c=s.get(l)||0;a=l+"-"+c,s.set(l,c+1)}}const o=EE(e,i,a);o!==void 0&&r.push(o)}return r}function OV(e,t,r){const n=zU(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?RU(r):GU(r)),n.property==="style"){let s=typeof r=="object"?r:FV(e,String(r));return e.stylePropertyNameCase==="css"&&(s=UV(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&n.space?UU[n.property]||n.property:n.attribute,r]}}function FV(e,t){try{return wV(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,s=new $r("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=SE+"#cannot-parse-style-attribute",s}}function _E(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const s=t.split(".");let i=-1,a;for(;++i<s.length;){const o=Fy(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}n=a}else n=Fy(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const s=n.value;return xm.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(n);Do(e)}function Do(e,t){const r=new $r("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=SE+"#cannot-handle-mdx-estrees-without-createevaluater",r}function UV(e){const t={};let r;for(r in e)xm.call(e,r)&&(t[VV(r)]=e[r]);return t}function VV(e){let t=e.replace(EV,$V);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function $V(e){return"-"+e.toLowerCase()}const Zd={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},zV={};function Cm(e,t){const r=zV,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,s=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return IE(e,n,s)}function IE(e,t,r){if(KV(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Qy(e.children,t,r)}return Array.isArray(e)?Qy(e,t,r):""}function Qy(e,t,r){const n=[];let s=-1;for(;++s<e.length;)n[s]=IE(e[s],t,r);return n.join("")}function KV(e){return!!(e&&typeof e=="object")}const Xy=document.createElement("i");function Sm(e){const t="&"+e+";";Xy.innerHTML=t;const r=Xy.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function yn(e,t,r,n){const s=e.length;let i=0,a;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,r=r>0?r:0,n.length<1e4)a=Array.from(n),a.unshift(t,r),e.splice(...a);else for(r&&e.splice(t,r);i<n.length;)a=n.slice(i,i+1e4),a.unshift(t,0),e.splice(...a),i+=1e4,t+=1e4}function wn(e,t){return e.length>0?(yn(e,e.length,0,t),e):t}const Jy={}.hasOwnProperty;function AE(e){const t={};let r=-1;for(;++r<e.length;)qV(t,e[r]);return t}function qV(e,t){let r;for(r in t){const s=(Jy.call(e,r)?e[r]:void 0)||(e[r]={}),i=t[r];let a;if(i)for(a in i){Jy.call(s,a)||(s[a]=[]);const o=i[a];HV(s[a],Array.isArray(o)?o:o?[o]:[])}}}function HV(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);yn(e,0,0,n)}function kE(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function Kn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Qr=oi(/[A-Za-z]/),Vr=oi(/[\dA-Za-z]/),GV=oi(/[#-'*+\--9=?A-Z^-~]/);function qc(e){return e!==null&&(e<32||e===127)}const Nh=oi(/\d/),WV=oi(/[\dA-Fa-f]/),YV=oi(/[!-/:-@[-`{-~]/);function lt(e){return e!==null&&e<-2}function er(e){return e!==null&&(e<0||e===32)}function Dt(e){return e===-2||e===-1||e===32}const Bu=oi(/\p{P}|\p{S}/u),Bi=oi(/\s/);function oi(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Da(e){const t=[];let r=-1,n=0,s=0;for(;++r<e.length;){const i=e.charCodeAt(r);let a="";if(i===37&&Vr(e.charCodeAt(r+1))&&Vr(e.charCodeAt(r+2)))s=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(a=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(r+1);i<56320&&o>56319&&o<57344?(a=String.fromCharCode(i,o),s=1):a="�"}else a=String.fromCharCode(i);a&&(t.push(e.slice(n,r),encodeURIComponent(a)),n=r+s+1,a=""),s&&(r+=s,s=0)}return t.join("")+e.slice(n)}function $t(e,t,r,n){const s=n?n-1:Number.POSITIVE_INFINITY;let i=0;return a;function a(l){return Dt(l)?(e.enter(r),o(l)):t(l)}function o(l){return Dt(l)&&i++<s?(e.consume(l),o):(e.exit(r),t(l))}}const QV={tokenize:XV};function XV(e){const t=e.attempt(this.parser.constructs.contentInitial,n,s);let r;return t;function n(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),$t(e,t,"linePrefix")}function s(o){return e.enter("paragraph"),i(o)}function i(o){const l=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,a(o)}function a(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return lt(o)?(e.consume(o),e.exit("chunkText"),i):(e.consume(o),a)}}const JV={tokenize:ZV},Zy={tokenize:e7};function ZV(e){const t=this,r=[];let n=0,s,i,a;return o;function o(T){if(n<r.length){const I=r[n];
vendor: 7,966 bytes, line 39
39return t.containerState=I[1],e.attempt(I[0].continuation,l,c)(T)}return c(T)}function l(T){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&C();const I=t.events.length;let k=I,_;for(;k--;)if(t.events[k][0]==="exit"&&t.events[k][1].type==="chunkFlow"){_=t.events[k][1].end;break}b(n);let M=I;for(;M<t.events.length;)t.events[M][1].end={..._},M++;return yn(t.events,k+1,0,t.events.slice(I)),t.events.length=M,c(T)}return o(T)}function c(T){if(n===r.length){if(!s)return h(T);if(s.currentConstruct&&s.currentConstruct.concrete)return g(T);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Zy,d,f)(T)}function d(T){return s&&C(),b(n),h(T)}function f(T){return t.parser.lazy[t.now().line]=n!==r.length,a=t.now().offset,g(T)}function h(T){return t.containerState={},e.attempt(Zy,m,g)(T)}function m(T){return n++,r.push([t.currentConstruct,t.containerState]),h(T)}function g(T){if(T===null){s&&C(),b(0),e.consume(T);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),v(T)}function v(T){if(T===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(T);return}return lt(T)?(e.consume(T),w(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(T),v)}function w(T,I){const k=t.sliceStream(T);if(I&&k.push(null),T.previous=i,i&&(i.next=T),i=T,s.defineSkip(T.start),s.write(k),t.parser.lazy[T.start.line]){let _=s.events.length;for(;_--;)if(s.events[_][1].start.offset<a&&(!s.events[_][1].end||s.events[_][1].end.offset>a))return;const M=t.events.length;let V=M,G,L;for(;V--;)if(t.events[V][0]==="exit"&&t.events[V][1].type==="chunkFlow"){if(G){L=t.events[V][1].end;break}G=!0}for(b(n),_=M;_<t.events.length;)t.events[_][1].end={...L},_++;yn(t.events,V+1,0,t.events.slice(M)),t.events.length=_}}function b(T){let I=r.length;for(;I-- >T;){const k=r[I];t.containerState=k[1],k[0].exit.call(t,e)}r.length=T}function C(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function e7(e,t,r){return $t(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ca(e){if(e===null||er(e)||Bi(e))return 1;if(Bu(e))return 2}function Du(e,t,r){const n=[];let s=-1;for(;++s<e.length;){const i=e[s].resolveAll;i&&!n.includes(i)&&(t=i(t,r),n.push(i))}return t}const Rh={name:"attention",resolveAll:t7,tokenize:r7};function t7(e,t){let r=-1,n,s,i,a,o,l,c,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;l=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const f={...e[n][1].end},h={...e[r][1].start};ev(f,-l),ev(h,l),a={type:l>1?"strongSequence":"emphasisSequence",start:f,end:{...e[n][1].end}},o={type:l>1?"strongSequence":"emphasisSequence",start:{...e[r][1].start},end:h},i={type:l>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[r][1].start}},s={type:l>1?"strong":"emphasis",start:{...a.start},end:{...o.end}},e[n][1].end={...a.start},e[r][1].start={...o.end},c=[],e[n][1].end.offset-e[n][1].start.offset&&(c=wn(c,[["enter",e[n][1],t],["exit",e[n][1],t]])),c=wn(c,[["enter",s,t],["enter",a,t],["exit",a,t],["enter",i,t]]),c=wn(c,Du(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),c=wn(c,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,c=wn(c,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,yn(e,n-1,r-n+3,c),r=n+c.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function r7(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,s=Ca(n);let i;return a;function a(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)return e.consume(l),o;const c=e.exit("attentionSequence"),d=Ca(l),f=!d||d===2&&s||r.includes(l),h=!s||s===2&&d||r.includes(n);return c._open=!!(i===42?f:f&&(s||!h)),c._close=!!(i===42?h:h&&(d||!f)),t(l)}}function ev(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const n7={name:"autolink",tokenize:s7};function s7(e,t,r){let n=0;return s;function s(m){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(m){return Qr(m)?(e.consume(m),a):m===64?r(m):c(m)}function a(m){return m===43||m===45||m===46||Vr(m)?(n=1,o(m)):c(m)}function o(m){return m===58?(e.consume(m),n=0,l):(m===43||m===45||m===46||Vr(m))&&n++<32?(e.consume(m),o):(n=0,c(m))}function l(m){return m===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.exit("autolink"),t):m===null||m===32||m===60||qc(m)?r(m):(e.consume(m),l)}function c(m){return m===64?(e.consume(m),d):GV(m)?(e.consume(m),c):r(m)}function d(m){return Vr(m)?f(m):r(m)}function f(m){return m===46?(e.consume(m),n=0,d):m===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.exit("autolink"),t):h(m)}function h(m){if((m===45||Vr(m))&&n++<63){const g=m===45?h:f;return e.consume(m),g}return r(m)}}const sl={partial:!0,tokenize:i7};function i7(e,t,r){return n;function n(i){return Dt(i)?$t(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||lt(i)?t(i):r(i)}}const NE={continuation:{tokenize:o7},exit:l7,name:"blockQuote",tokenize:a7};function a7(e,t,r){const n=this;return s;function s(a){if(a===62){const o=n.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),i}return r(a)}function i(a){return Dt(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function o7(e,t,r){const n=this;return s;function s(a){return Dt(a)?$t(e,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):i(a)}function i(a){return e.attempt(NE,t,r)(a)}}function l7(e){e.exit("blockQuote")}const RE={name:"characterEscape",tokenize:c7};function c7(e,t,r){return n;function n(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),s}function s(i){return YV(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(i)}}const PE={name:"characterReference",tokenize:u7};function u7(e,t,r){const n=this;let s=0,i,a;return o;function o(f){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),l}function l(f){return f===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(f),e.exit("characterReferenceMarkerNumeric"),c):(e.enter("characterReferenceValue"),i=31,a=Vr,d(f))}function c(f){return f===88||f===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(f),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,a=WV,d):(e.enter("characterReferenceValue"),i=7,a=Nh,d(f))}function d(f){if(f===59&&s){const h=e.exit("characterReferenceValue");return a===Vr&&!Sm(n.sliceSerialize(h))?r(f):(e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(f)&&s++<i?(e.consume(f),d):r(f)}}const tv={partial:!0,tokenize:f7},rv={concrete:!0,name:"codeFenced",tokenize:d7};function d7(e,t,r){const n=this,s={partial:!0,tokenize:k};let i=0,a=0,o;return l;function l(_){return c(_)}function c(_){const M=n.events[n.events.length-1];return i=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[1],!0).length:0,o=_,e.enter("co
39deFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(_)}function d(_){return _===o?(a++,e.consume(_),d):a<3?r(_):(e.exit("codeFencedFenceSequence"),Dt(_)?$t(e,f,"whitespace")(_):f(_))}function f(_){return _===null||lt(_)?(e.exit("codeFencedFence"),n.interrupt?t(_):e.check(tv,v,I)(_)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(_))}function h(_){return _===null||lt(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),f(_)):Dt(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),$t(e,m,"whitespace")(_)):_===96&&_===o?r(_):(e.consume(_),h)}function m(_){return _===null||lt(_)?f(_):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(_))}function g(_){return _===null||lt(_)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),f(_)):_===96&&_===o?r(_):(e.consume(_),g)}function v(_){return e.attempt(s,I,w)(_)}function w(_){return e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),b}function b(_){return i>0&&Dt(_)?$t(e,C,"linePrefix",i+1)(_):C(_)}function C(_){return _===null||lt(_)?e.check(tv,v,I)(_):(e.enter("codeFlowValue"),T(_))}function T(_){return _===null||lt(_)?(e.exit("codeFlowValue"),C(_)):(e.consume(_),T)}function I(_){return e.exit("codeFenced"),t(_)}function k(_,M,V){let G=0;return L;function L(oe){return _.enter("lineEnding"),_.consume(oe),_.exit("lineEnding"),H}function H(oe){return _.enter("codeFencedFence"),Dt(oe)?$t(_,F,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(oe):F(oe)}function F(oe){return oe===o?(_.enter("codeFencedFenceSequence"),Q(oe)):V(oe)}function Q(oe){return oe===o?(G++,_.consume(oe),Q):G>=a?(_.exit("codeFencedFenceSequence"),Dt(oe)?$t(_,J,"whitespace")(oe):J(oe)):V(oe)}function J(oe){return oe===null||lt(oe)?(_.exit("codeFencedFence"),M(oe)):V(oe)}}}function f7(e,t,r){const n=this;return s;function s(a){return a===null?r(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i)}function i(a){return n.parser.lazy[n.now().line]?r(a):t(a)}}const ef={name:"codeIndented",tokenize:p7},h7={partial:!0,tokenize:m7};function p7(e,t,r){const n=this;return s;function s(c){return e.enter("codeIndented"),$t(e,i,"linePrefix",5)(c)}function i(c){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?a(c):r(c)}function a(c){return c===null?l(c):lt(c)?e.attempt(h7,a,l)(c):(e.enter("codeFlowValue"),o(c))}function o(c){return c===null||lt(c)?(e.exit("codeFlowValue"),a(c)):(e.consume(c),o)}function l(c){return e.exit("codeIndented"),t(c)}}function m7(e,t,r){const n=this;return s;function s(a){return n.parser.lazy[n.now().line]?r(a):lt(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s):$t(e,i,"linePrefix",5)(a)}function i(a){const o=n.events[n.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):lt(a)?s(a):r(a)}}const g7={name:"codeText",previous:v7,resolve:y7,tokenize:x7};function y7(e){let t=e.length-4,r=3,n,s;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)s===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(s=n):(n===t||e[n][1].type==="lineEnding")&&(e[s][1].type="codeTextData",n!==s+2&&(e[s][1].end=e[n-1][1].end,e.splice(s+2,n-s-2),t-=n-s-2,n=s+2),s=void 0);return e}function v7(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function x7(e,t,r){let n=0,s,i;return a;function a(f){return e.enter("codeText"),e.enter("codeTextSequence"),o(f)}function o(f){return f===96?(e.consume(f),n++,o):(e.exit("codeTextSequence"),l(f))}function l(f){return f===null?r(f):f===32?(e.enter("space"),e.consume(f),e.exit("space"),l):f===96?(i=e.enter("codeTextSequence"),s=0,d(f)):lt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),l):(e.enter("codeTextData"),c(f))}function c(f){return f===null||f===32||f===96||lt(f)?(e.exit("codeTextData"),l(f)):(e.consume(f),c)}function d(f){return f===96?(e.consume(f),s++,d):s===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(f)):(i.type="codeTextData",c(f))}}class b7{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const s=r||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return n&&to(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),to(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),to(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);to(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);to(this.left,r.reverse())}}}function to(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function jE(e){const t={};let r=-1,n,s,i,a,o,l,c;const d=new b7(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,w7(d,r)),r=t[r],c=!0);else if(n[1]._container){for(i=r,s=void 0;i--;)if(a=d.get(i),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(s&&(d.get(s)[1].type="lineEndingBlank"),a[1].type="lineEnding",s=i);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;s&&(n[1].end={...d.get(s)[1].start},o=d.slice(s,r),o.unshift(n),d.splice(s,r-s+1,o))}}return yn(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!c}function w7(e,t){const r=e.get(t)[1],n=e.get(t)[2];let s=t-1;const i=[];let a=r._tokenizer;a||(a=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,l=[],c={};let d,f,h=-1,m=r,g=0,v=0;const w=[v];for(;m;){for(;e.get(++s)[1]!==m;);i.push(s),m._tokenizer||(d=n.sliceStream(m),m.next||d.push(null),f&&a.defineSki
vendor: 22,833 bytes, line 39
39p(m.start),m._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),m._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),f=m,m=m.next}for(m=r;++h<o.length;)o[h][0]==="exit"&&o[h-1][0]==="enter"&&o[h][1].type===o[h-1][1].type&&o[h][1].start.line!==o[h][1].end.line&&(v=h+1,w.push(v),m._tokenizer=void 0,m.previous=void 0,m=m.next);for(a.events=[],m?(m._tokenizer=void 0,m.previous=void 0):w.pop(),h=w.length;h--;){const b=o.slice(w[h],w[h+1]),C=i.pop();l.push([C,C+b.length-1]),e.splice(C,2,b)}for(l.reverse(),h=-1;++h<l.length;)c[g+l[h][0]]=g+l[h][1],g+=l[h][1]-l[h][0]-1;return c}const C7={resolve:E7,tokenize:T7},S7={partial:!0,tokenize:_7};function E7(e){return jE(e),e}function T7(e,t){let r;return n;function n(o){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),s(o)}function s(o){return o===null?i(o):lt(o)?e.check(S7,a,i)(o):(e.consume(o),s)}function i(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function a(o){return e.consume(o),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,s}}function _7(e,t,r){const n=this;return s;function s(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),$t(e,i,"linePrefix")}function i(a){if(a===null||lt(a))return r(a);const o=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):e.interrupt(n.parser.constructs.flow,r,t)(a)}}function BE(e,t,r,n,s,i,a,o,l){const c=l||Number.POSITIVE_INFINITY;let d=0;return f;function f(b){return b===60?(e.enter(n),e.enter(s),e.enter(i),e.consume(b),e.exit(i),h):b===null||b===32||b===41||qc(b)?r(b):(e.enter(n),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),v(b))}function h(b){return b===62?(e.enter(i),e.consume(b),e.exit(i),e.exit(s),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),m(b))}function m(b){return b===62?(e.exit("chunkString"),e.exit(o),h(b)):b===null||b===60||lt(b)?r(b):(e.consume(b),b===92?g:m)}function g(b){return b===60||b===62||b===92?(e.consume(b),m):m(b)}function v(b){return!d&&(b===null||b===41||er(b))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(n),t(b)):d<c&&b===40?(e.consume(b),d++,v):b===41?(e.consume(b),d--,v):b===null||b===32||b===40||qc(b)?r(b):(e.consume(b),b===92?w:v)}function w(b){return b===40||b===41||b===92?(e.consume(b),v):v(b)}}function DE(e,t,r,n,s,i){const a=this;let o=0,l;return c;function c(m){return e.enter(n),e.enter(s),e.consume(m),e.exit(s),e.enter(i),d}function d(m){return o>999||m===null||m===91||m===93&&!l||m===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?r(m):m===93?(e.exit(i),e.enter(s),e.consume(m),e.exit(s),e.exit(n),t):lt(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),f(m))}function f(m){return m===null||m===91||m===93||lt(m)||o++>999?(e.exit("chunkString"),d(m)):(e.consume(m),l||(l=!Dt(m)),m===92?h:f)}function h(m){return m===91||m===92||m===93?(e.consume(m),o++,f):f(m)}}function LE(e,t,r,n,s,i){let a;return o;function o(h){return h===34||h===39||h===40?(e.enter(n),e.enter(s),e.consume(h),e.exit(s),a=h===40?41:h,l):r(h)}function l(h){return h===a?(e.enter(s),e.consume(h),e.exit(s),e.exit(n),t):(e.enter(i),c(h))}function c(h){return h===a?(e.exit(i),l(a)):h===null?r(h):lt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),$t(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(h))}function d(h){return h===a||h===null||lt(h)?(e.exit("chunkString"),c(h)):(e.consume(h),h===92?f:d)}function f(h){return h===a||h===92?(e.consume(h),d):d(h)}}function bo(e,t){let r;return n;function n(s){return lt(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),r=!0,n):Dt(s)?$t(e,n,r?"linePrefix":"lineSuffix")(s):t(s)}}const I7={name:"definition",tokenize:k7},A7={partial:!0,tokenize:N7};function k7(e,t,r){const n=this;let s;return i;function i(m){return e.enter("definition"),a(m)}function a(m){return DE.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(m)}function o(m){return s=Kn(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),l):r(m)}function l(m){return er(m)?bo(e,c)(m):c(m)}function c(m){return BE(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(m)}function d(m){return e.attempt(A7,f,f)(m)}function f(m){return Dt(m)?$t(e,h,"whitespace")(m):h(m)}function h(m){return m===null||lt(m)?(e.exit("definition"),n.parser.defined.push(s),t(m)):r(m)}}function N7(e,t,r){return n;function n(o){return er(o)?bo(e,s)(o):r(o)}function s(o){return LE(e,i,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return Dt(o)?$t(e,a,"whitespace")(o):a(o)}function a(o){return o===null||lt(o)?t(o):r(o)}}const R7={name:"hardBreakEscape",tokenize:P7};function P7(e,t,r){return n;function n(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return lt(i)?(e.exit("hardBreakEscape"),t(i)):r(i)}}const j7={name:"headingAtx",resolve:B7,tokenize:D7};function B7(e,t){let r=e.length-2,n=3,s,i;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(s={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},i={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},yn(e,n,r-n+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function D7(e,t,r){let n=0;return s;function s(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&n++<6?(e.consume(d),a):d===null||er(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||lt(d)?(e.exit("atxHeading"),t(d)):Dt(d)?$t(e,o,"whitespace")(d):(e.enter("atxHeadingText"),c(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function c(d){return d===null||d===35||er(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),c)}}const L7=["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","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],nv=["pre","script","style","textarea"],M7={concrete:!0,name:"htmlFlow",resolveTo:U7,tokenize:V7},O7={partial:!0,tokenize:z7},F7={partial:!0,tokenize:$7};function U7(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function V7(e,t,r){const n=this;let s,i,a,o,l;return c;function c(U){return d(U)}function d(U){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(U),f}function f(U){return U===33?(e.consume(U),h):U===47?(e.consume(U),i=!0,v):U===63?(e.consume(U),s=3,n.interrupt?t:B):Qr(U)?(e.consume(U),a=String.fromCharCode(U),w):r(U)}function h(U){return U===45?(e.consume(U),s=2,m):U===91?(e.consume(U),s=5,o=0,g):Qr(U)?(e.consume(U),s=4,n.interrupt?t:B):r(U)}function m(U){return U===45?(e.consume(U),n.interrupt?t:B):r(U)}function g(U){const Qe="CDATA[";return U===Qe.charCodeAt(o++)?(e.consume(U),o===Qe.length?n.interrupt?t:F:g):r(U)}function v(U){return Qr(U)?(e.consume(U),a=String.fromCharCode(U),w):r(U)}function w(U){if(U===null||U===47||U===62||er(U)){const Qe=U===47,pt=a.toLowerCase();return!Qe&&!i&&nv.includes(pt)?(s=1,n.interrupt?t(U):F(U)):L7.includes(a.toLowerCase())?(s=6,Qe?(e.consume(U),b):n.interrupt?t(U):F(U)):(s=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(U):i?C(U):T(U))}return U===45||Vr(U)?(e.consume(U),a+=String.fromCharCode(U),w):r(U)}function b(U){return U===62?(e.consume(U),n.interrupt?t:F):r(U)}function C(U){return Dt(U)?(e.consume(U),C):L(U)}function T(U){return U===47?(e.consume(U),L):U===58||U===95||Qr(U)?(e.consume(U),I):Dt(U)?(e.consume(U),T):L(U)}function I(U){return U===45||U===46||U===58||U===95||Vr(U)?(e.consume(U),I):k(U)}function k(U){return U===61?(e.consume(U),_):Dt(U)?(e.consume(U),k):T(U)}function _(U){return U===null||U===60||U===61||U===62||U===96?r(U):U===34||U===39?(e.consume(U),l=U,M):Dt(U)?(e.consume(U),_):V(U)}function M(U){return U===l?(e.consume(U),l=null,G):U===null||lt(U)?r(U):(e.consume(U),M)}function V(U){return U===null||U===34||U===39||U===47||U===60||U===61||U===62||U===96||er(U)?k(U):(e.consume(U),V)}function G(U){return U===47||U===62||Dt(U)?T(U):r(U)}function L(U){return U===62?(e.consume(U),H):r(U)}function H(U){return U===null||lt(U)?F(U):Dt(U)?(e.consume(U),H):r(U)}function F(U){return U===45&&s===2?(e.consume(U),xe):U===60&&s===1?(e.consume(U),ge):U===62&&s===4?(e.consume(U),Te):U===63&&s===3?(e.consume(U),B):U===93&&s===5?(e.consume(U),le):lt(U)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(O7,ye,Q)(U)):U===null||lt(U)?(e.exit("htmlFlowData"),Q(U)):(e.consume(U),F)}function Q(U){return e.check(F7,J,ye)(U)}function J(U){return e.enter("lineEnding"),e.consume(U),e.exit("lineEnding"),oe}function oe(U){return U===null||lt(U)?Q(U):(e.enter("htmlFlowData"),F(U))}function xe(U){return U===45?(e.consume(U),B):F(U)}function ge(U){return U===47?(e.consume(U),a="",$):F(U)}function $(U){if(U===62){const Qe=a.toLowerCase();return nv.includes(Qe)?(e.consume(U),Te):F(U)}return Qr(U)&&a.length<8?(e.consume(U),a+=String.fromCharCode(U),$):F(U)}function le(U){return U===93?(e.consume(U),B):F(U)}function B(U){return U===62?(e.consume(U),Te):U===45&&s===2?(e.consume(U),B):F(U)}function Te(U){return U===null||lt(U)?(e.exit("htmlFlowData"),ye(U)):(e.consume(U),Te)}function ye(U){return e.exit("htmlFlow"),t(U)}}function $7(e,t,r){const n=this;return s;function s(a){return lt(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):r(a)}function i(a){return n.parser.lazy[n.now().line]?r(a):t(a)}}function z7(e,t,r){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(sl,t,r)}}const K7={name:"htmlText",tokenize:q7};function q7(e,t,r){const n=this;let s,i,a;return o;function o(B){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(B),l}function l(B){return B===33?(e.consume(B),c):B===47?(e.consume(B),k):B===63?(e.consume(B),T):Qr(B)?(e.consume(B),V):r(B)}function c(B){return B===45?(e.consume(B),d):B===91?(e.consume(B),i=0,g):Qr(B)?(e.consume(B),C):r(B)}function d(B){return B===45?(e.consume(B),m):r(B)}function f(B){return B===null?r(B):B===45?(e.consume(B),h):lt(B)?(a=f,ge(B)):(e.consume(B),f)}function h(B){return B===45?(e.consume(B),m):f(B)}function m(B){return B===62?xe(B):B===45?h(B):f(B)}function g(B){const Te="CDATA[";return B===Te.charCodeAt(i++)?(e.consume(B),i===Te.length?v:g):r(B)}function v(B){return B===null?r(B):B===93?(e.consume(B),w):lt(B)?(a=v,ge(B)):(e.consume(B),v)}function w(B){return B===93?(e.consume(B),b):v(B)}function b(B){return B===62?xe(B):B===93?(e.consume(B),b):v(B)}function C(B){return B===null||B===62?xe(B):lt(B)?(a=C,ge(B)):(e.consume(B),C)}function T(B){return B===null?r(B):B===63?(e.consume(B),I):lt(B)?(a=T,ge(B)):(e.consume(B),T)}function I(B){return B===62?xe(B):T(B)}function k(B){return Qr(B)?(e.consume(B),_):r(B)}function _(B){return B===45||Vr(B)?(e.consume(B),_):M(B)}function M(B){return lt(B)?(a=M,ge(B)):Dt(B)?(e.consume(B),M):xe(B)}function V(B){return B===45||Vr(B)?(e.consume(B),V):B===47||B===62||er(B)?G(B):r(B)}function G(B){return B===47?(e.consume(B),xe):B===58||B===95||Qr(B)?(e.consume(B),L):lt(B)?(a=G,ge(B)):Dt(B)?(e.consume(B),G):xe(B)}function L(B){return B===45||B===46||B===58||B===95||Vr(B)?(e.consume(B),L):H(B)}function H(B){return B===61?(e.consume(B),F):lt(B)?(a=H,ge(B)):Dt(B)?(e.consume(B),H):G(B)}function F(B){return B===null||B===60||B===61||B===62||B===96?r(B):B===34||B===39?(e.consume(B),s=B,Q):lt(B)?(a=F,ge(B)):Dt(B)?(e.consume(B),F):(e.consume(B),J)}function Q(B){return B===s?(e.consume(B),s=void 0,oe):B===null?r(B):lt(B)?(a=Q,ge(B)):(e.consume(B),Q)}function J(B){return B===null||B===34||B===39||B===60||B===61||B===96?r(B):B===47||B===62||er(B)?G(B):(e.consume(B),J)}function oe(B){return B===47||B===62||er(B)?G(B):r(B)}function xe(B){return B===62?(e.consume(B),e.exit("htmlTextData"),e.exit("htmlText"),t):r(B)}function ge(B){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),$}function $(B){return Dt(B)?$t(e,le,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):le(B)}function le(B){return e.enter("htmlTextData"),a(B)}}const Em={name:"labelEnd",resolveAll:Y7,resolveTo:Q7,tokenize:X7},H7={tokenize:J7},G7={tokenize:Z7},W7={tokenize:e9};function Y7(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const s=n.type==="labelImage"?4:2;n.type="data",t+=s}}return e.length!==r.length&&yn(e,0,e.length,r),e}function Q7(e,t){let r=e.length,n=0,s,i,a,o;for(;r--;)if(s=e[r][1],i){if(s.type==="link"||s.type==="labelLink"&&s._inactive)break;e[r][0]==="enter"&&s.type==="labelLink"&&(s._inactive=!0)}else if(a){if(e[r][0]==="enter"&&(s.type==="labelImage"||s.type==="labelLink")&&!s._balanced&&(i=r,s.type!=="labelLink")){n=2;break}}else s.type==="labelEnd"&&(a=r);const l={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},c={type:"label",start:{...e[i][1].start},end:{...e[a][1].end}},d={type:"labelText",start:{...e[i+n+2][1].end},end:{...e[a-2][1].start}};return o=[["enter",l,t],["enter",c,t]],o=wn(o,e.slice(i+1,i+n+3)),o=wn(o,[["enter",d,t]]),o=wn(o,Du(t.parser.constructs.insideSpan.null,e.slice(i+n+4,a-3),t)),o=wn(o,[["exit",d,t],e[a-2],e[a-1],["exit",c,t]]),o=wn(o,e.slice(a+1)),o=wn(o,[["exit",l,t]]),yn(e,i,e.length,o),e}function X7(e,t,r){const n=this;let s=n.events.length,i,a;for(;s--;)if((n.events[s][1].type==="labelImage"||n.events[s][1].type==="labelLink")&&!n.events[s][1]._balanced){i=n.events[s][1];break}return o;function o(h){return i?i._inactive?f(h):(a=n.parser.defined.includes(Kn(n.sliceSerialize({start:i.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),l):r(h)}function l(h){return h===40?e.attempt(H7,d,a?d:f)(h):h===91?e.attempt(G7,d,a?c:f)(h):a?d(h):f(h)}function c(h){return e.attempt(W7,d,f)(h)}function d(h){return t(h)}function f(h){return i._balanced=!0,r(h)}}function J7(e,t,r){return n;function n(f){return e.enter("resource"),e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),s}function s(f){return er(f)?bo(e,i)(f):i(f)}function i(f){return f===41?d(f):BE(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(f)}function a(f){return er(f)?bo(e,l)(f):d(f)}function o(f){return r(f)}function l(f){return f===34||f===39||f===40?LE(e,c,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(f):d(f)}function c(f){return er(f)?bo(e,d)(f):d(f)}function d(f){return f===41?(e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),e.exit("resource"),t):r(f)}}function Z7(e,t,r){const n=this;return s;function s(o){return DE.call(n,e,i,a,"reference","referenceMarker","referenceString")(o)}function i(o){return n.parser.defined.includes(Kn(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function a(o){return r(o)}}function e9(e,t,r){return n;function n(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),s}function s(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):r(i)}}const t9={name:"labelStartImage",resolveAll:Em.resolveAll,tokenize:r9};function r9(e,t,r){const n=this;return s;function s(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),a):r(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const n9={name:"labelStartLink",resolveAll:Em.resolveAll,tokenize:s9};function s9(e,t,r){const n=this;return s;function s(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),i}function i(a){return a===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(a):t(a)}}const tf={name:"lineEnding",tokenize:i9};function i9(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),$t(e,t,"linePrefix")}}const hc={name:"thematicBreak",tokenize:a9};function a9(e,t,r){let n=0,s;return i;function i(c){return e.enter("thematicBreak"),a(c)}function a(c){return s=c,o(c)}function o(c){return c===s?(e.enter("thematicBreakSequence"),l(c)):n>=3&&(c===null||lt(c))?(e.exit("thematicBreak"),t(c)):r(c)}function l(c){return c===s?(e.consume(c),n++,l):(e.exit("thematicBreakSequence"),Dt(c)?$t(e,o,"whitespace")(c):o(c))}}const en={continuation:{tokenize:u9},exit:f9,name:"list",tokenize:c9},o9={partial:!0,tokenize:h9},l9={partial:!0,tokenize:d9};function c9(e,t,r){const n=this,s=n.events[n.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,a=0;return o;function o(m){const g=n.containerState.type||(m===42||m===43||m===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!n.containerState.marker||m===n.containerState.marker:Nh(m)){if(n.containerState.type||(n.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),m===42||m===45?e.check(hc,r,c)(m):c(m);if(!n.interrupt||m===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(m)}return r(m)}function l(m){return Nh(m)&&++a<10?(e.consume(m),l):(!n.interrupt||a<2)&&(n.containerState.marker?m===n.containerState.marker:m===41||m===46)?(e.exit("listItemValue"),c(m)):r(m)}function c(m){return e.enter("listItemMarker"),e.consume(m),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||m,e.check(sl,n.interrupt?r:d,e.attempt(o9,h,f))}function d(m){return n.containerState.initialBlankLine=!0,i++,h(m)}function f(m){return Dt(m)?(e.enter("listItemPrefixWhitespace"),e.consume(m),e.exit("listItemPrefixWhitespace"),h):r(m)}function h(m){return n.containerState.size=i+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(m)}}function u9(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(sl,s,i);function s(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,$t(e,t,"listItemIndent",n.containerState.size+1)(o)}function i(o){return n.containerState.furtherBlankLines||!Dt(o)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,a(o)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(l9,t,a)(o))}function a(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,$t(e,e.attempt(en,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function d9(e,t,r){const n=this;return $t(e,s,"listItemIndent",n.containerState.size+1);function s(i){const a=n.events[n.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===n.containerState.size?t(i):r(i)}}function f9(e){e.exit(this.containerState.type)}function h9(e,t,r){const n=this;return $t(e,s,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const a=n.events[n.events.length-1];return!Dt(i)&&a&&a[1].type==="listItemPrefixWhitespace"?t(i):r(i)}}const sv={name:"setextUnderline",resolveTo:p9,tokenize:m9};function p9(e,t){let r=e.length,n,s,i;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(s=r)}else e[r][1].type==="content"&&e.splice(r,1),!i&&e[r][1].type==="definition"&&(i=r);const a={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",a,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end={...e[i][1].end}):e[n][1]=a,e.push(["exit",a,t]),e}function m9(e,t,r){const n=this;let s;return i;function i(c){let d=n.events.length,f;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){f=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||f)?(e.enter("setextHeadingLine"),s=c,a(c)):r(c)}function a(c){return e.enter("setextHeadingLineSequence"),o(c)}function o(c){return c===s?(e.consume(c),o):(e.exit("setextHeadingLineSequence"),Dt(c)?$t(e,l,"lineSuffix")(c):l(c))}function l(c){return c===null||lt(c)?(e.exit("setextHeadingLine"),t(c)):r(c)}}const g9={tokenize:y9};function y9(e){const t=this,r=e.attempt(sl,n,e.attempt(this.parser.constructs.flowInitial,s,$t(e,e.attempt(this.parser.constructs.flow,s,e.attempt(C7,s)),"linePrefix")));return r;function n(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const v9={resolveAll:OE()},x9=ME("string"),b9=ME("text");function ME(e){return{resolveAll:OE(e==="text"?w9:void 0),tokenize:t};function t(r){const n=this,s=this.parser.constructs[e],i=r.attempt(s,a,o);return a;function a(d){return c(d)?i(d):o(d)}function o(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),l}function l(d){return c(d)?(r.exit("data"),i(d)):(r.consume(d),l)}function c(d){if(d===null)return!0;const f=s[d];let h=-1;if(f)for(;++h<f.length;){const m=f[h];if(!m.previous||m.previous.call(n,n.previous))return!0}return!1}}}function OE(e){return t;function t(r,n){let s=-1,i;for(;++s<=r.length;)i===void 0?r[s]&&r[s][1].type==="data"&&(i=s,s++):(!r[s]||r[s][1].type!=="data")&&(s!==i+2&&(r[i][1].end=r[s-1][1].end,r.splice(i+2,s-i-2),s=i+2),i=void 0);return e?e(r,n):r}}function w9(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],s=t.sliceStream(n);let i=s.length,a=-1,o=0,l;for(;i--;){const c=s[i];if(typeof c=="string"){for(a=c.length;
vendor: 4,603 bytes, lines 39-41
39c.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(c===-2)l=!0,o++;else if(c!==-1){i++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const c={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?a:n.start._bufferIndex+a,_index:n.start._index+i,line:n.end.line,column:n.end.column-o,offset:n.end.offset-o},end:{...n.end}};n.end={...c.start},n.start.offset===n.end.offset?Object.assign(n,c):(e.splice(r,0,["enter",c,t],["exit",c,t]),r+=2)}r++}return e}const C9={42:en,43:en,45:en,48:en,49:en,50:en,51:en,52:en,53:en,54:en,55:en,56:en,57:en,62:NE},S9={91:I7},E9={[-2]:ef,[-1]:ef,32:ef},T9={35:j7,42:hc,45:[sv,hc],60:M7,61:sv,95:hc,96:rv,126:rv},_9={38:PE,92:RE},I9={[-5]:tf,[-4]:tf,[-3]:tf,33:t9,38:PE,42:Rh,60:[n7,K7],91:n9,92:[R7,RE],93:Em,95:Rh,96:g7},A9={null:[Rh,v9]},k9={null:[42,95]},N9={null:[]},R9=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:k9,contentInitial:S9,disable:N9,document:C9,flow:T9,flowInitial:E9,insideSpan:A9,string:_9,text:I9},Symbol.toStringTag,{value:"Module"}));function P9(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const s={},i=[];let a=[],o=[];const l={attempt:M(k),check:M(_),consume:C,enter:T,exit:I,interrupt:M(_,{interrupt:!0})},c={code:null,containerState:{},defineSkip:v,events:[],now:g,parser:e,previous:null,sliceSerialize:h,sliceStream:m,write:f};let d=t.tokenize.call(c,l);return t.resolveAll&&i.push(t),c;function f(H){return a=wn(a,H),w(),a[a.length-1]!==null?[]:(V(t,0),c.events=Du(i,c.events,c),c.events)}function h(H,F){return B9(m(H),F)}function m(H){return j9(a,H)}function g(){const{_bufferIndex:H,_index:F,line:Q,column:J,offset:oe}=n;return{_bufferIndex:H,_index:F,line:Q,column:J,offset:oe}}function v(H){s[H.line]=H.column,L()}function w(){let H;for(;n._index<a.length;){const F=a[n._index];if(typeof F=="string")for(H=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===H&&n._bufferIndex<F.length;)b(F.charCodeAt(n._bufferIndex));else b(F)}}function b(H){d=d(H)}function C(H){lt(H)?(n.line++,n.column=1,n.offset+=H===-3?2:1,L()):H!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===a[n._index].length&&(n._bufferIndex=-1,n._index++)),c.previous=H}function T(H,F){const Q=F||{};return Q.type=H,Q.start=g(),c.events.push(["enter",Q,c]),o.push(Q),Q}function I(H){const F=o.pop();return F.end=g(),c.events.push(["exit",F,c]),F}function k(H,F){V(H,F.from)}function _(H,F){F.restore()}function M(H,F){return Q;function Q(J,oe,xe){let ge,$,le,B;return Array.isArray(J)?ye(J):"tokenize"in J?ye([J]):Te(J);function Te(We){return dt;function dt(ft){const At=ft!==null&&We[ft],Le=ft!==null&&We.null,Ut=[...Array.isArray(At)?At:At?[At]:[],...Array.isArray(Le)?Le:Le?[Le]:[]];return ye(Ut)(ft)}}function ye(We){return ge=We,$=0,We.length===0?xe:U(We[$])}function U(We){return dt;function dt(ft){return B=G(),le=We,We.partial||(c.currentConstruct=We),We.name&&c.parser.constructs.disable.null.includes(We.name)?pt():We.tokenize.call(F?Object.assign(Object.create(c),F):c,l,Qe,pt)(ft)}}function Qe(We){return H(le,B),oe}function pt(We){return B.restore(),++$<ge.length?U(ge[$]):xe}}}function V(H,F){H.resolveAll&&!i.includes(H)&&i.push(H),H.resolve&&yn(c.events,F,c.events.length-F,H.resolve(c.events.slice(F),c)),H.resolveTo&&(c.events=H.resolveTo(c.events,c))}function G(){const H=g(),F=c.previous,Q=c.currentConstruct,J=c.events.length,oe=Array.from(o);return{from:J,restore:xe};function xe(){n=H,c.previous=F,c.currentConstruct=Q,c.events.length=J,o=oe,L()}}function L(){n.line in s&&n.column<2&&(n.column=s[n.line],n.offset+=s[n.line]-1)}}function j9(e,t){const r=t.start._index,n=t.start._bufferIndex,s=t.end._index,i=t.end._bufferIndex;let a;if(r===s)a=[e[r].slice(n,i)];else{if(a=e.slice(r,s),n>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(n):a.shift()}i>0&&a.push(e[s].slice(0,i))}return a}function B9(e,t){let r=-1;const n=[];let s;for(;++r<e.length;){const i=e[r];let a;if(typeof i=="string")a=i;else switch(i){case-5:{a="\r";break}case-4:{a=`
40`;break}case-3:{a=`\r
41`;break}case-2:{a=t?" ":"	";break}case-1:{if(!t&&s)continue;a=" ";break}default:a=String.fromCharCode(i)}s=i===-2,n.push(a)}return n.join("")}function D9(e){const n={constructs:AE([R9,...(e||{}).extensions||[]]),content:s(QV),defined:[],document:s(JV),flow:s(g9),lazy:{},string:s(x9),text:s(b9)};return n;function s(i){return a;function a(o){return P9(n,i,o)}}}function L9(e){for(;!jE(e););return e}const iv=/[\0\t\n\r]/g;function M9(){let e=1,t="",r=!0,n;return s;function s(i,a,o){const l=[];let c,d,f,h,m;
vendor: 9,622 bytes, line 41
41for(i=t+(typeof i=="string"?i.toString():new TextDecoder(a||void 0).decode(i)),f=0,t="",r&&(i.charCodeAt(0)===65279&&f++,r=void 0);f<i.length;){if(iv.lastIndex=f,c=iv.exec(i),h=c&&c.index!==void 0?c.index:i.length,m=i.charCodeAt(h),!c){t=i.slice(f);break}if(m===10&&f===h&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),f<h&&(l.push(i.slice(f,h)),e+=h-f),m){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}f=h+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const O9=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function F9(e){return e.replace(O9,U9)}function U9(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const s=r.charCodeAt(1),i=s===120||s===88;return kE(r.slice(i?2:1),i?16:10)}return Sm(r)||e}const FE={}.hasOwnProperty;function V9(e,t,r){return t&&typeof t=="object"&&(r=t,t=void 0),$9(r)(L9(D9(r).document().write(M9()(e,t,!0))))}function $9(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(fe),autolinkProtocol:G,autolinkEmail:G,atxHeading:i(kt),blockQuote:i(Le),characterEscape:G,characterReference:G,codeFenced:i(Ut),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:i(Ut,a),codeText:i(tt,a),codeTextData:G,data:G,codeFlowValue:G,definition:i(ct),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:i(ht),hardBreakEscape:i(Xr),hardBreakTrailing:i(Xr),htmlFlow:i(ps,a),htmlFlowData:G,htmlText:i(ps,a),htmlTextData:G,image:i(K),label:a,link:i(fe),listItem:i(Ce),listItemValue:h,listOrdered:i(W,f),listUnordered:i(W),paragraph:i(Ee),reference:U,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:i(kt),strong:i(be),thematicBreak:i(rt)},exit:{atxHeading:l(),atxHeadingSequence:k,autolink:l(),autolinkEmail:At,autolinkProtocol:ft,blockQuote:l(),characterEscapeValue:L,characterReferenceMarkerHexadecimal:pt,characterReferenceMarkerNumeric:pt,characterReferenceValue:We,characterReference:dt,codeFenced:l(w),codeFencedFence:v,codeFencedFenceInfo:m,codeFencedFenceMeta:g,codeFlowValue:L,codeIndented:l(b),codeText:l(oe),codeTextData:L,data:L,definition:l(),definitionDestinationString:I,definitionLabelString:C,definitionTitleString:T,emphasis:l(),hardBreakEscape:l(F),hardBreakTrailing:l(F),htmlFlow:l(Q),htmlFlowData:L,htmlText:l(J),htmlTextData:L,image:l(ge),label:le,labelText:$,lineEnding:H,link:l(xe),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:Qe,resourceDestinationString:B,resourceTitleString:Te,resource:ye,setextHeading:l(V),setextHeadingLineSequence:M,setextHeadingText:_,strong:l(),thematicBreak:l()}};UE(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(ue){let Se={type:"root",children:[]};const Ge={stack:[Se],tokenStack:[],config:t,enter:o,exit:c,buffer:a,resume:d,data:r},st=[];let Et=-1;for(;++Et<ue.length;)if(ue[Et][1].type==="listOrdered"||ue[Et][1].type==="listUnordered")if(ue[Et][0]==="enter")st.push(Et);else{const cr=st.pop();Et=s(ue,cr,Et)}for(Et=-1;++Et<ue.length;){const cr=t[ue[Et][0]];FE.call(cr,ue[Et][1].type)&&cr[ue[Et][1].type].call(Object.assign({sliceSerialize:ue[Et][2].sliceSerialize},Ge),ue[Et][1])}if(Ge.tokenStack.length>0){const cr=Ge.tokenStack[Ge.tokenStack.length-1];(cr[1]||av).call(Ge,void 0,cr[0])}for(Se.position={start:Fs(ue.length>0?ue[0][1].start:{line:1,column:1,offset:0}),end:Fs(ue.length>0?ue[ue.length-2][1].end:{line:1,column:1,offset:0})},Et=-1;++Et<t.transforms.length;)Se=t.transforms[Et](Se)||Se;return Se}function s(ue,Se,Ge){let st=Se-1,Et=-1,cr=!1,Xe,bt,sr,mr;for(;++st<=Ge;){const $e=ue[st];switch($e[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{$e[0]==="enter"?Et++:Et--,mr=void 0;break}case"lineEndingBlank":{$e[0]==="enter"&&(Xe&&!mr&&!Et&&!sr&&(sr=st),mr=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:mr=void 0}if(!Et&&$e[0]==="enter"&&$e[1].type==="listItemPrefix"||Et===-1&&$e[0]==="exit"&&($e[1].type==="listUnordered"||$e[1].type==="listOrdered")){if(Xe){let Jr=st;for(bt=void 0;Jr--;){const nt=ue[Jr];if(nt[1].type==="lineEnding"||nt[1].type==="lineEndingBlank"){if(nt[0]==="exit")continue;bt&&(ue[bt][1].type="lineEndingBlank",cr=!0),nt[1].type="lineEnding",bt=Jr}else if(!(nt[1].type==="linePrefix"||nt[1].type==="blockQuotePrefix"||nt[1].type==="blockQuotePrefixWhitespace"||nt[1].type==="blockQuoteMarker"||nt[1].type==="listItemIndent"))break}sr&&(!bt||sr<bt)&&(Xe._spread=!0),Xe.end=Object.assign({},bt?ue[bt][1].start:$e[1].end),ue.splice(bt||st,0,["exit",Xe,$e[2]]),st++,Ge++}if($e[1].type==="listItemPrefix"){const Jr={type:"listItem",_spread:!1,start:Object.assign({},$e[1].start),end:void 0};Xe=Jr,ue.splice(st,0,["enter",Jr,$e[2]]),st++,Ge++,sr=void 0,mr=!0}}}return ue[Se][1]._spread=cr,Ge}function i(ue,Se){return Ge;function Ge(st){o.call(this,ue(st),st),Se&&Se.call(this,st)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(ue,Se,Ge){this.stack[this.stack.length-1].children.push(ue),this.stack.push(ue),this.tokenStack.push([Se,Ge||void 0]),ue.position={start:Fs(Se.start),end:void 0}}function l(ue){return Se;function Se(Ge){ue&&ue.call(this,Ge),c.call(this,Ge)}}function c(ue,Se){const Ge=this.stack.pop(),st=this.tokenStack.pop();if(st)st[0].type!==ue.type&&(Se?Se.call(this,ue,st[0]):(st[1]||av).call(this,ue,st[0]));else throw new Error("Cannot close `"+ue.type+"` ("+xo({start:ue.start,end:ue.end})+"): it’s not open");Ge.position.end=Fs(ue.end)}function d(){return Cm(this.stack.pop())}function f(){this.data.expectingFirstListItemValue=!0}function h(ue){if(this.data.expectingFirstListItemValue){const Se=this.stack[this.stack.length-2];Se.start=Number.parseInt(this.sliceSerialize(ue),10),this.data.expectingFirstListItemValue=void 0}}function m(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.lang=ue}function g(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.meta=ue}function v(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.value=ue.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.value=ue.replace(/(\r?\n|\r)$/g,"")}function C(ue){const Se=this.resume(),Ge=this.stack[this.stack.length-1];Ge.label=Se,Ge.identifier=Kn(this.sliceSerialize(ue)).toLowerCase()}function T(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.title=ue}function I(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.url=ue}function k(ue){const Se=this.stack[this.stack.length-1];if(!Se.depth){const Ge=this.sliceSerialize(ue).length;Se.depth=Ge}}function _(){this.data.setextHeadingSlurpLineEnding=!0}function M(ue){const Se=this.stack[this.stack.length-1];Se.depth=this.sliceSerialize(ue).codePointAt(0)===61?1:2}function V(){this.data.setextHeadingSlurpLineEnding=void 0}function G(ue){const Ge=this.stack[this.stack.length-1].children;let st=Ge[Ge.length-1];(!st||st.type!=="text")&&(st=Ve(),st.position={start:Fs(ue.start),end:void 0},Ge.push(st)),this.stack.push(st)}function L(ue){const Se=this.stack.pop();Se.value+=this.sliceSerialize(ue),Se.position.end=Fs(ue.end)}function H(ue){const Se=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Ge=Se.children[Se.children.length-1];Ge.position.end=Fs(ue.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(Se.type)&&(G.call(this,ue),L.call(this,ue))}function F(){this.data.atHardBreak=!0}function Q(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.value=ue}function J(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.value=ue}function oe(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.value=ue}function xe(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const Se=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=Se,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function ge(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const Se=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=Se,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function $(ue){const Se=this.sliceSerialize(ue),Ge=this.stack[this.stack.length-2];Ge.label=F9(Se),Ge.identifier=Kn(Se).toLowerCase()}function le(){const ue=this.stack[this.stack.length-1],Se=this.resume(),Ge=this.stack[this.stack.length-1];if(this.data.inReference=!0,Ge.type==="link"){const st=ue.children;Ge.children=st}else Ge.alt=Se}function B(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.url=ue}function Te(){const ue=this.resume(),Se=this.stack[this.stack.length-1];Se.title=ue}function ye(){this.data.inReference=void 0}function U(){this.data.referenceType="collapsed"}function Qe(ue){const Se=this.resume(),Ge=this.stack[this.stack.length-1];Ge.label=Se,Ge.identifier=Kn(this.sliceSerialize(ue)).toLowerCase(),this.data.referenceType="full"}function pt(ue){this.data.characterReferenceType=ue.type}function We(ue){const Se=this.sliceSerialize(ue),Ge=this.data.characterReferenceType;let st;Ge?(st=kE(Se,Ge==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):st=Sm(Se);const Et=this.stack[this.stack.length-1];Et.value+=st}function dt(ue){const Se=this.stack.pop();
vendor: 14,098 bytes, lines 41-46
41Se.position.end=Fs(ue.end)}function ft(ue){L.call(this,ue);const Se=this.stack[this.stack.length-1];Se.url=this.sliceSerialize(ue)}function At(ue){L.call(this,ue);const Se=this.stack[this.stack.length-1];Se.url="mailto:"+this.sliceSerialize(ue)}function Le(){return{type:"blockquote",children:[]}}function Ut(){return{type:"code",lang:null,meta:null,value:""}}function tt(){return{type:"inlineCode",value:""}}function ct(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ht(){return{type:"emphasis",children:[]}}function kt(){return{type:"heading",depth:0,children:[]}}function Xr(){return{type:"break"}}function ps(){return{type:"html",value:""}}function K(){return{type:"image",title:null,url:"",alt:null}}function fe(){return{type:"link",title:null,url:"",children:[]}}function W(ue){return{type:"list",ordered:ue.type==="listOrdered",start:null,spread:ue._spread,children:[]}}function Ce(ue){return{type:"listItem",spread:ue._spread,checked:null,children:[]}}function Ee(){return{type:"paragraph",children:[]}}function be(){return{type:"strong",children:[]}}function Ve(){return{type:"text",value:""}}function rt(){return{type:"thematicBreak"}}}function Fs(e){return{line:e.line,column:e.column,offset:e.offset}}function UE(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?UE(e,n):z9(e,n)}}function z9(e,t){let r;for(r in t)if(FE.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function av(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+xo({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+xo({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+xo({start:t.start,end:t.end})+") is still open")}function K9(e){const t=this;t.parser=r;function r(n){return V9(n,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function q9(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function H9(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
42`}]}function G9(e,t){const r=t.value?t.value+`
43`:"",n={},s=t.lang?t.lang.split(/\s+/):[];s.length>0&&(n.className=["language-"+s[0]]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function W9(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Y9(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Q9(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),s=Da(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let a,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),a=e.footnoteOrder.length):a=i+1,o+=1,e.footnoteCounts.set(n,o);const l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+s,id:r+"fnref-"+s+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,l);const c={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,c),e.applyData(t,c)}function X9(e,t){const r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function J9(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function VE(e,t){const r=t.referenceType;let n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+n}];const s=e.all(t),i=s[0];i&&i.type==="text"?i.value="["+i.value:s.unshift({type:"text",value:"["});const a=s[s.length-1];return a&&a.type==="text"?a.value+=n:s.push({type:"text",value:n}),s}function Z9(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return VE(e,t);const s={src:Da(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(t,i),e.applyData(t,i)}function e$(e,t){const r={src:Da(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function t$(e,t){const r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);const n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function r$(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return VE(e,t);const s={href:Da(n.url||"")};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function n$(e,t){const r={href:Da(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function s$(e,t,r){const n=e.all(t),s=r?i$(r):$E(t),i={},a=[];if(typeof t.checked=="boolean"){const d=n[0];let f;d&&d.type==="element"&&d.tagName==="p"?f=d:(f={type:"element",tagName:"p",properties:{},children:[]},n.unshift(f)),f.children.length>0&&f.children.unshift({type:"text",value:" "}),f.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const d=n[o];(s||o!==0||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:`
44`}),d.type==="element"&&d.tagName==="p"&&!s?a.push(...d.children):a.push(d)}const l=n[n.length-1];l&&(s||l.type!=="element"||l.tagName!=="p")&&a.push({type:"text",value:`
45`});const c={type:"element",tagName:"li",properties:i,children:a};return e.patch(t,c),e.applyData(t,c)}function i$(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const r=e.children;let n=-1;for(;!t&&++n<r.length;)t=$E(r[n])}return t}function $E(e){const t=e.spread;return t??e.children.length>1}function a$(e,t){const r={},n=e.all(t);let s=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++s<n.length;){const a=n[s];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,i),e.applyData(t,i)}function o$(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function l$(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function c$(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function u$(e,t){const r=e.all(t),n=r.shift(),s=[];if(n){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],a),s.push(a)}if(r.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=vm(t.children[1]),l=wE(t.children[t.children.length-1]);o&&l&&(a.position={start:o,end:l}),s.push(a)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function d$(e,t,r){const n=r?r.children:void 0,i=(n?n.indexOf(t):1)===0?"th":"td",a=r&&r.type==="table"?r.align:void 0,o=a?a.length:t.children.length;let l=-1;const c=[];for(;++l<o;){const f=t.children[l],h={},m=a?a[l]:void 0;m&&(h.align=m);let g={type:"element",tagName:i,properties:h,children:[]};f&&(g.children=e.all(f),e.patch(f,g),g=e.applyData(f,g)),c.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(c,!0)};return e.patch(t,d),e.applyData(t,d)}function f$(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const ov=9,lv=32;function h$(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),s=0;const i=[];for(;n;)i.push(cv(t.slice(s,n.index),s>0,!0),n[0]),s=n.index+n[0].length,n=r.exec(t);return i.push(cv(t.slice(s),s>0,!1)),i.join("")}function cv(e,t,r){let n=0,s=e.length;if(t){let i=e.codePointAt(n);for(;i===ov||i===lv;)n++,i=e.codePointAt(n)}if(r){let i=e.codePointAt(s-1);for(;i===ov||i===lv;)s--,i=e.codePointAt(s-1)}return s>n?e.slice(n,s):""}function p$(e,t){const r={type:"text",value:h$(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function m$(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const g$={blockquote:q9,break:H9,code:G9,delete:W9,emphasis:Y9,footnoteReference:Q9,heading:X9,html:J9,imageReference:Z9,image:e$,inlineCode:t$,linkReference:r$,link:n$,listItem:s$,list:a$,paragraph:o$,root:l$,strong:c$,table:u$,tableCell:f$,tableRow:d$,text:p$,thematicBreak:m$,toml:Yl,yaml:Yl,definition:Yl,footnoteDefinition:Yl};function Yl(){}const zE=-1,Lu=0,wo=1,Hc=2,Tm=3,_m=4,Im=5,Am=6,KE=7,qE=8,y$=typeof self=="object"?self:globalThis,uv=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new y$[e](t)},v$=(e,t)=>{const r=(s,i)=>(e.set(i,s),s),n=s=>{if(e.has(s))return e.get(s);const[i,a]=t[s];switch(i){case Lu:case zE:return r(a,s);case wo:{const o=r([],s);for(const l of a)o.push(n(l));return o}case Hc:{const o=r({},s);for(const[l,c]of a)o[n(l)]=n(c);return o}case Tm:return r(new Date(a),s);case _m:{const{source:o,flags:l}=a;return r(new RegExp(o,l),s)}case Im:{const o=r(new Map,s);for(const[l,c]of a)o.set(n(l),n(c));return o}case Am:{const o=r(new Set,s);for(const l of a)o.add(n(l));return o}case KE:{const{name:o,message:l}=a;return r(uv(o,l),s)}case qE:return r(BigInt(a),s);case"BigInt":return r(Object(BigInt(a)),s);case"ArrayBuffer":return r(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:o}=new Uint8Array(a);return r(new DataView(o),a)}}return r(uv(i,a),s)};return n},dv=e=>v$(new Map,e)(0),xi="",{toString:x$}={},{keys:b$}=Object,ro=e=>{const t=typeof e;if(t!=="object"||!e)return[Lu,t];const r=x$.call(e).slice(8,-1);switch(r){case"Array":return[wo,xi];case"Object":return[Hc,xi];case"Date":return[Tm,xi];case"RegExp":return[_m,xi];case"Map":return[Im,xi];case"Set":return[Am,xi];case"DataView":return[wo,r]}return r.includes("Array")?[wo,r]:r.includes("Error")?[KE,r]:[Hc,r]},Ql=([e,t])=>e===Lu&&(t==="function"||t==="symbol"),w$=(e,t,r,n)=>{const s=(a,o)=>{const l=n.push(a)-1;return r.set(o,l),l},i=a=>{if(r.has(a))return r.get(a);let[o,l]=ro(a);switch(o){case Lu:{let d=a;switch(l){case"bigint":o=qE,d=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);d=null;break;case"undefined":return s([zE],a)}return s([o,d],a)}case wo:{if(l){let h=a;return l==="DataView"?h=new Uint8Array(a.buffer):l==="ArrayBuffer"&&(h=new Uint8Array(a)),s([l,[...h]],a)}const d=[],f=s([o,d],a);for(const h of a)d.push(i(h));return f}case Hc:{if(l)switch(l){case"BigInt":return s([l,a.toString()],a);case"Boolean":case"Number":case"String":return s([l,a.valueOf()],a)}if(t&&"toJSON"in a)return i(a.toJSON());const d=[],f=s([o,d],a);for(const h of b$(a))(e||!Ql(ro(a[h])))&&d.push([i(h),i(a[h])]);return f}case Tm:return s([o,isNaN(a.getTime())?xi:a.toISOString()],a);case _m:{const{source:d,flags:f}=a;return s([o,{source:d,flags:f}],a)}case Im:{const d=[],f=s([o,d],a);for(const[h,m]of a)(e||!(Ql(ro(h))||Ql(ro(m))))&&d.push([i(h),i(m)]);return f}case Am:{const d=[],f=s([o,d],a);for(const h of a)(e||!Ql(ro(h)))&&d.push(i(h));return f}}const{message:c}=a;return s([o,{name:l,message:c}],a)};return i},fv=(e,{json:t,lossy:r}={})=>{const n=[];return w$(!(t||r),!!t,new Map,n)(e),n},Gc=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?dv(fv(e,t)):structuredClone(e):(e,t)=>dv(fv(e,t));function C$(e,t){const r=[{type:"text",value:"↩"}];return t>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),r}function S$(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function E$(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||C$,n=e.options.footnoteBackLabel||S$,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const c=e.footnoteById.get(e.footnoteOrder[l]);if(!c)continue;const d=e.all(c),f=String(c.identifier).toUpperCase(),h=Da(f.toLowerCase());let m=0;const g=[],v=e.footnoteCounts.get(f);for(;v!==void 0&&++m<=v;){g.length>0&&g.push({type:"text",value:" "});let C=typeof r=="string"?r:r(l,m);typeof C=="string"&&(C={type:"text",value:C}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+h+(m>1?"-"+m:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,m),className:["data-footnote-backref"]},children:Array.isArray(C)?C:[C]})}const w=d[d.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const C=w.children[w.children.length-1];C&&C.type==="text"?C.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...g)}else d.push(...g);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+h},children:e.wrap(d,!0)};e.patch(c,b),o.push(b)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...Gc(a),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:`
46`},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)}
vendor: 17,925 bytes, lines 46-51
46,{type:"text",value:`
47`}]}}const Mu=function(e){if(e==null)return A$;if(typeof e=="function")return Ou(e);if(typeof e=="object")return Array.isArray(e)?T$(e):_$(e);if(typeof e=="string")return I$(e);throw new Error("Expected function, string, or object as test")};function T$(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=Mu(e[r]);return Ou(n);function n(...s){let i=-1;for(;++i<t.length;)if(t[i].apply(this,s))return!0;return!1}}function _$(e){const t=e;return Ou(r);function r(n){const s=n;let i;for(i in e)if(s[i]!==t[i])return!1;return!0}}function I$(e){return Ou(t);function t(r){return r&&r.type===e}}function Ou(e){return t;function t(r,n,s){return!!(k$(r)&&e.call(this,r,typeof n=="number"?n:void 0,s||void 0))}}function A$(){return!0}function k$(e){return e!==null&&typeof e=="object"&&"type"in e}const HE=[],N$=!0,Ph=!1,R$="skip";function GE(e,t,r,n){let s;typeof t=="function"&&typeof r!="function"?(n=r,r=t):s=t;const i=Mu(s),a=n?-1:1;o(e,void 0,[])();function o(l,c,d){const f=l&&typeof l=="object"?l:{};if(typeof f.type=="string"){const m=typeof f.tagName=="string"?f.tagName:typeof f.name=="string"?f.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(l.type+(m?"<"+m+">":""))+")"})}return h;function h(){let m=HE,g,v,w;if((!t||i(l,c,d[d.length-1]||void 0))&&(m=P$(r(l,d)),m[0]===Ph))return m;if("children"in l&&l.children){const b=l;if(b.children&&m[0]!==R$)for(v=(n?b.children.length:-1)+a,w=d.concat(b);v>-1&&v<b.children.length;){const C=b.children[v];if(g=o(C,v,w)(),g[0]===Ph)return g;v=typeof g[1]=="number"?g[1]:v+a}}return m}}}function P$(e){return Array.isArray(e)?e:typeof e=="number"?[N$,e]:e==null?HE:[e]}function km(e,t,r,n){let s,i,a;typeof t=="function"&&typeof r!="function"?(i=void 0,a=t,s=r):(i=t,a=r,s=n),GE(e,i,o,s);function o(l,c){const d=c[c.length-1],f=d?d.children.indexOf(l):void 0;return a(l,f,d)}}const jh={}.hasOwnProperty,j$={};function B$(e,t){const r=t||j$,n=new Map,s=new Map,i=new Map,a={...g$,...r.handlers},o={all:c,applyData:L$,definitionById:n,footnoteById:s,footnoteCounts:i,footnoteOrder:[],handlers:a,one:l,options:r,patch:D$,wrap:O$};return km(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const f=d.type==="definition"?n:s,h=String(d.identifier).toUpperCase();f.has(h)||f.set(h,d)}}),o;function l(d,f){const h=d.type,m=o.handlers[h];if(jh.call(o.handlers,h)&&m)return m(o,d,f);if(o.options.passThrough&&o.options.passThrough.includes(h)){if("children"in d){const{children:v,...w}=d,b=Gc(w);return b.children=o.all(d),b}return Gc(d)}return(o.options.unknownHandler||M$)(o,d,f)}function c(d){const f=[];if("children"in d){const h=d.children;let m=-1;for(;++m<h.length;){const g=o.one(h[m],d);if(g){if(m&&h[m-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=hv(g.value)),!Array.isArray(g)&&g.type==="element")){const v=g.children[0];v&&v.type==="text"&&(v.value=hv(v.value))}Array.isArray(g)?f.push(...g):f.push(g)}}}return f}}function D$(e,t){e.position&&(t.position=CV(e))}function L$(e,t){let r=t;if(e&&e.data){const n=e.data.hName,s=e.data.hChildren,i=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const a="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:a}}r.type==="element"&&i&&Object.assign(r.properties,Gc(i)),"children"in r&&r.children&&s!==null&&s!==void 0&&(r.children=s)}return r}function M$(e,t){const r=t.data||{},n="value"in t&&!(jh.call(r,"hProperties")||jh.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function O$(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
48`});++n<e.length;)n&&r.push({type:"text",value:`
49`}),r.push(e[n]);return t&&e.length>0&&r.push({type:"text",value:`
50`}),r}function hv(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function pv(e,t){const r=B$(e,t),n=r.one(e,void 0),s=E$(r),i=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return s&&i.children.push({type:"text",value:`
51`},s),i}function F$(e,t){return e&&"run"in e?async function(r,n){const s=pv(r,{file:n,...t});await e.run(s,n)}:function(r,n){return pv(r,{file:n,...e||t})}}function mv(e){if(e)throw e}var pc=Object.prototype.hasOwnProperty,WE=Object.prototype.toString,gv=Object.defineProperty,yv=Object.getOwnPropertyDescriptor,vv=function(t){return typeof Array.isArray=="function"?Array.isArray(t):WE.call(t)==="[object Array]"},xv=function(t){if(!t||WE.call(t)!=="[object Object]")return!1;var r=pc.call(t,"constructor"),n=t.constructor&&t.constructor.prototype&&pc.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!n)return!1;var s;for(s in t);return typeof s>"u"||pc.call(t,s)},bv=function(t,r){gv&&r.name==="__proto__"?gv(t,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):t[r.name]=r.newValue},wv=function(t,r){if(r==="__proto__")if(pc.call(t,r)){if(yv)return yv(t,r).value}else return;return t[r]},U$=function e(){var t,r,n,s,i,a,o=arguments[0],l=1,c=arguments.length,d=!1;for(typeof o=="boolean"&&(d=o,o=arguments[1]||{},l=2),(o==null||typeof o!="object"&&typeof o!="function")&&(o={});l<c;++l)if(t=arguments[l],t!=null)for(r in t)n=wv(o,r),s=wv(t,r),o!==s&&(d&&s&&(xv(s)||(i=vv(s)))?(i?(i=!1,a=n&&vv(n)?n:[]):a=n&&xv(n)?n:{},bv(o,{name:r,newValue:e(d,a,s)})):typeof s<"u"&&bv(o,{name:r,newValue:s}));return o};const rf=Qc(U$);function Bh(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function V$(){const e=[],t={run:r,use:n};return t;function r(...s){let i=-1;const a=s.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);o(null,...s);function o(l,...c){const d=e[++i];let f=-1;if(l){a(l);return}for(;++f<s.length;)(c[f]===null||c[f]===void 0)&&(c[f]=s[f]);s=c,d?$$(d,o)(...c):a(null,...c)}}function n(s){if(typeof s!="function")throw new TypeError("Expected `middelware` to be a function, not "+s);return e.push(s),t}}function $$(e,t){let r;return n;function n(...a){const o=e.length>a.length;let l;o&&a.push(s);try{l=e.apply(this,a)}catch(c){const d=c;if(o&&r)throw d;return s(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(i,s):l instanceof Error?s(l):i(l))}function s(a,...o){r||(r=!0,t(a,...o))}function i(a){s(null,a)}}const Qn={basename:z$,dirname:K$,extname:q$,join:H$,sep:"/"};function z$(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');il(e);let r=0,n=-1,s=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;s--;)if(e.codePointAt(s)===47){if(i){r=s+1;break}}else n<0&&(i=!0,n=s+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let a=-1,o=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){r=s+1;break}}else a<0&&(i=!0,a=s+1),o>-1&&(e.codePointAt(s)===t.codePointAt(o--)?o<0&&(n=s):(o=-1,n=a));return r===n?n=a:n<0&&(n=e.length),e.slice(r,n)}function K$(e){if(il(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function q$(e){il(e);let t=e.length,r=-1,n=0,s=-1,i=0,a;for(;t--;){const o=e.codePointAt(t);if(o===47){if(a){n=t+1;break}continue}r<0&&(a=!0,r=t+1),o===46?s<0?s=t:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||r<0||i===0||i===1&&s===r-1&&s===n+1?"":e.slice(s,r)}function H$(...e){let t=-1,r;for(;++t<e.length;)il(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":G$(r)}function G$(e){il(e);const t=e.codePointAt(0)===47;let r=W$(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function W$(e,t){let r="",n=0,s=-1,i=0,a=-1,o,l;for(;++a<=e.length;){if(a<e.length)o=e.codePointAt(a);else{if(o===47)break;o=47}if(o===47){if(!(s===a-1||i===1))if(s!==a-1&&i===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),s=a,i=0;continue}}else if(r.length>0){r="",n=0,s=a,i=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(s+1,a):r=e.slice(s+1,a),n=a-s-1;s=a,i=0}else o===46&&i>-1?i++:i=-1}return r}function il(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Y$={cwd:Q$};function Q$(){return"/"}function Dh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function X$(e){if(typeof e=="string")e=new URL(e);else if(!Dh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return J$(e)}function J$(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const s=new TypeError("File URL path must not include encoded / characters");throw s.code="ERR_INVALID_FILE_URL_PATH",s}}return decodeURIComponent(t)}const nf=["history","path","basename","stem","extname","dirname"];class YE{constructor(t){let r;t?Dh(t)?r={path:t}:typeof t=="string"||Z$(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":Y$.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<nf.length;){const i=nf[n];i in r&&r[i]!==void 0&&r[i]!==null&&(this[i]=i==="history"?[...r[i]]:r[i])}let s;for(s in r)nf.includes(s)||(this[s]=r[s])}get basename(){return typeof this.path=="string"?Qn.basename(this.path):void 0}set basename(t){af(t,"basename"),sf(t,"basename"),this.path=Qn.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Qn.dirname(this.path):void 0}set dirname(t){Cv(this.basename,"dirname"),this.path=Qn.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Qn.extname(this.path):void 0}set extname(t){if(sf(t,"extname"),Cv(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Qn.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Dh(t)&&(t=X$(t)),af(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Qn.basename(this.path,this.extname):void 0}set stem(t){af(t,"stem"),sf(t,"stem"),this.path=Qn.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const s=this.message(t,r,n);throw s.fatal=!0,s}info(t,r,n){const s=this.message(t,r,n);return s.fatal=void 0,s}message(t,r,n){const s=new $r(t,r,n);return this.path&&(s.name=this.path+":"+s.name,s.file=this.path),s.fatal=!1,this.messages.push(s),s}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function sf(e,t){if(e&&e.includes(Qn.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Qn.sep+"`")}function af(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Cv(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function Z$(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ez=function(e){const n=this.constructor.prototype,s=n[e],i=function(){return s.apply(i,arguments)};return Object.setPrototypeOf(i,n),i},tz={}.hasOwnProperty;class Nm extends ez{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=V$()}copy(){const t=new Nm;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(rf(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(cf("data",this.frozen),this.namespace[t]=r,this):tz.call(this.namespace,t)&&this.namespace[t]||void 0:t?(cf("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const s=r.call(t,...n);typeof s=="function"&&this.transformers.use(s)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=Xl(t),n=this.parser||this.Parser;return of("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),of("process",this.parser||this.Parser),lf("process",this.compiler||this.Compiler),r?s(void 0,r):new Promise(s);function s(i,a){const o=Xl(t),l=n.parse(o);n.run(l,o,function(d,f,h){if(d||!f||!h)return c(d);const m=f,g=n.stringify(m,h);sz(g)?h.value=g:h.result=g,c(d,h)});function c(d,f){d||!f?a(d):i?i(f):r(void 0,f)}}}processSync(t){let r=!1,n;return this.freeze(),of("processSync",this.parser||this.Parser),lf("processSync",this.compiler||this.Compiler),this.process(t,s),Ev("processSync","process",r),n;function s(i,a){r=!0,mv(i),n=a}}run(t,r,n){Sv(t),this.freeze();const s=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?i(void 0,n):new Promise(i);function i(a,o){const l=Xl(r);s.run(t,l,c);function c(d,f,h){const m=f||t;d?o(d):a?a(m):n(void 0,m,h)}}}runSync(t,r){let n=!1,s;return this.run(t,r,i),Ev("runSync","run",n),s;function i(a,o){mv(a),s=o,n=!0}}stringify(t,r){this.freeze();const n=Xl(r),s=this.compiler||this.Compiler;return lf("stringify",s),Sv(t),s(t,n)}use(t,...r){const n=this.attachers,s=this.namespace;if(cf("use",this.frozen),t!=null)if(typeof t=="function")l(t,r);else if(typeof t=="object")Array.isArray(t)?o(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(c){if(typeof c=="function")l(c,[]);else if(typeof c=="object")if(Array.isArray(c)){const[d,...f]=c;l(d,f)}else a(c);else throw new TypeError("Expected usable value, not `"+c+"`")}function a(c){if(!("plugins"in c)&&!("settings"in c))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(c.plugins),c.settings&&(s.settings=rf(!0,s.settings,c.settings))}function o(c){let d=-1;if(c!=null)if(Array.isArray(c))for(;++d<c.length;){const f=c[d];i(f)}else throw new TypeError("Expected a list of plugins, not `"+c+"`")}function l(c,d){let f=-1,h=-1;for(;++f<n.length;)if(n[f][0]===c){h=f;break}if(h===-1)n.push([c,...d]);else if(d.length>0){let[m,...g]=d;const v=n[h][1];Bh(v)&&Bh(m)&&(m=rf(!0,v,m)),n[h]=[c,m,...g]}}}}const rz=new Nm().freeze();function of(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function lf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function cf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Sv(e){if(!Bh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ev(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Xl(e){return nz(e)?e:new YE(e)}function nz(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function sz(e){return typeof e=="string"||iz(e)}function iz(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const az="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Tv=[],_v={allowDangerousHtml:!0},oz=/^(https?|ircs?|mailto|xmpp)$/i,lz=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function cz(e){const t=uz(e),r=dz(e);return fz(t.runSync(t.parse(r),r),e)}function uz(e){const t=e.rehypePlugins||Tv,r=e.remarkPlugins||Tv,n=e.remarkRehypeOptions?{...e.remarkRehypeOptions,..._v}:_v;return rz().use(K9).use(r).use(F$,n).use(t)}function dz(e){const t=e.children||"",r=new YE;return typeof t=="string"&&(r.value=t),r}function fz(e,t){const r=t.allowedElements,n=t.allowElement,s=t.components,i=t.disallowedElements,a=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||hz;for(const d of lz)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+az+d.id,void 0);return km(e,c),IV(e,{Fragment:u.Fragment,components:s,ignoreInvalidStyle:!0,jsx:u.jsx,jsxs:u.jsxs,passKeys:!0,passNode:!0});function c(d,f,h){if(d.type==="raw"&&h&&typeof f=="number")return a?h.children.splice(f,1):h.children[f]={type:"text",value:d.value},f;
vendor: 6,053 bytes, lines 51-52
51if(d.type==="element"){let m;for(m in Zd)if(Object.hasOwn(Zd,m)&&Object.hasOwn(d.properties,m)){const g=d.properties[m],v=Zd[m];(v===null||v.includes(d.tagName))&&(d.properties[m]=l(String(g||""),m,d))}}if(d.type==="element"){let m=r?!r.includes(d.tagName):i?i.includes(d.tagName):!1;if(!m&&n&&typeof f=="number"&&(m=!n(d,f,h)),m&&h&&typeof f=="number")return o&&d.children?h.children.splice(f,1,...d.children):h.children.splice(f,1),f}}}function hz(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),s=e.indexOf("/");return t===-1||s!==-1&&t>s||r!==-1&&t>r||n!==-1&&t>n||oz.test(e.slice(0,t))?e:""}function Iv(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,s=r.indexOf(t);for(;s!==-1;)n++,s=r.indexOf(t,s+t.length);return n}function pz(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function mz(e,t,r){const s=Mu((r||{}).ignore||[]),i=gz(t);let a=-1;for(;++a<i.length;)GE(e,"text",o);function o(c,d){let f=-1,h;for(;++f<d.length;){const m=d[f],g=h?h.children:void 0;if(s(m,g?g.indexOf(m):void 0,h))return;h=m}if(h)return l(c,d)}function l(c,d){const f=d[d.length-1],h=i[a][0],m=i[a][1];let g=0;const w=f.children.indexOf(c);let b=!1,C=[];h.lastIndex=0;let T=h.exec(c.value);for(;T;){const I=T.index,k={index:T.index,input:T.input,stack:[...d,c]};let _=m(...T,k);if(typeof _=="string"&&(_=_.length>0?{type:"text",value:_}:void 0),_===!1?h.lastIndex=I+1:(g!==I&&C.push({type:"text",value:c.value.slice(g,I)}),Array.isArray(_)?C.push(..._):_&&C.push(_),g=I+T[0].length,b=!0),!h.global)break;T=h.exec(c.value)}return b?(g<c.value.length&&C.push({type:"text",value:c.value.slice(g)}),f.children.splice(w,1,...C)):C=[c],w+C.length}}function gz(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const s=r[n];t.push([yz(s[0]),vz(s[1])])}return t}function yz(e){return typeof e=="string"?new RegExp(pz(e),"g"):e}function vz(e){return typeof e=="function"?e:function(){return e}}const uf="phrasing",df=["autolink","link","image","label"];function xz(){return{transforms:[_z],enter:{literalAutolink:wz,literalAutolinkEmail:ff,literalAutolinkHttp:ff,literalAutolinkWww:ff},exit:{literalAutolink:Tz,literalAutolinkEmail:Ez,literalAutolinkHttp:Cz,literalAutolinkWww:Sz}}}function bz(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:uf,notInConstruct:df},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:uf,notInConstruct:df},{character:":",before:"[ps]",after:"\\/",inConstruct:uf,notInConstruct:df}]}}function wz(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ff(e){this.config.enter.autolinkProtocol.call(this,e)}function Cz(e){this.config.exit.autolinkProtocol.call(this,e)}function Sz(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function Ez(e){this.config.exit.autolinkEmail.call(this,e)}function Tz(e){this.exit(e)}function _z(e){mz(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Iz],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Az]],{ignore:["link","linkReference"]})}function Iz(e,t,r,n,s){let i="";if(!QE(s)||(/^w/i.test(t)&&(r=t+r,t="",i="http://"),!kz(r)))return!1;const a=Nz(r+n);if(!a[0])return!1;const o={type:"link",title:null,url:i+t+a[0],children:[{type:"text",value:t+a[0]}]};return a[1]?[o,{type:"text",value:a[1]}]:o}function Az(e,t,r,n){return!QE(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function kz(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Nz(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const s=Iv(e,"(");let i=Iv(e,")");for(;n!==-1&&s>i;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),i++;return[e,r]}function QE(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||Bi(r)||Bu(r))&&(!t||r!==47)}XE.peek=Fz;function Rz(){this.buffer()}function Pz(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function jz(){this.buffer()}function Bz(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Dz(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Kn(this.sliceSerialize(e)).toLowerCase(),r.label=t}function Lz(e){this.exit(e)}function Mz(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Kn(this.sliceSerialize(e)).toLowerCase(),r.label=t}function Oz(e){this.exit(e)}function Fz(){return"["}function XE(e,t,r,n){const s=r.createTracker(n);let i=s.move("[^");const a=r.enter("footnoteReference"),o=r.enter("reference");return i+=s.move(r.safe(r.associationId(e),{after:"]",before:i})),o(),a(),i+=s.move("]"),i}function Uz(){return{enter:{gfmFootnoteCallString:Rz,gfmFootnoteCall:Pz,gfmFootnoteDefinitionLabelString:jz,gfmFootnoteDefinition:Bz},exit:{gfmFootnoteCallString:Dz,gfmFootnoteCall:Lz,gfmFootnoteDefinitionLabelString:Mz,gfmFootnoteDefinition:Oz}}}function Vz(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:XE},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,s,i,a){const o=i.createTracker(a);let l=o.move("[^");const c=i.enter("footnoteDefinition"),d=i.enter("label");return l+=o.move(i.safe(i.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
52`:" ")+i.indentLines(i.containerFlow(n,o.current()),t?JE:$z))),c(),l}}function $z(e,t,r){return t===0?e:JE(e,t,r)}function JE(e,t,r){return(r?"":"    ")+e}const zz=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];ZE.peek=Wz;
vendor: 13,652 bytes, lines 52-64
52function Kz(){return{canContainEols:["delete"],enter:{strikethrough:Hz},exit:{strikethrough:Gz}}}function qz(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:zz}],handlers:{delete:ZE}}}function Hz(e){this.enter({type:"delete",children:[]},e)}function Gz(e){this.exit(e)}function ZE(e,t,r,n){const s=r.createTracker(n),i=r.enter("strikethrough");let a=s.move("~~");return a+=r.containerPhrasing(e,{...s.current(),before:a,after:"~"}),a+=s.move("~~"),i(),a}function Wz(){return"~"}function Yz(e){return e.length}function Qz(e,t){const r=t||{},n=(r.align||[]).concat(),s=r.stringLength||Yz,i=[],a=[],o=[],l=[];let c=0,d=-1;for(;++d<e.length;){const v=[],w=[];let b=-1;for(e[d].length>c&&(c=e[d].length);++b<e[d].length;){const C=Xz(e[d][b]);if(r.alignDelimiters!==!1){const T=s(C);w[b]=T,(l[b]===void 0||T>l[b])&&(l[b]=T)}v.push(C)}a[d]=v,o[d]=w}let f=-1;if(typeof n=="object"&&"length"in n)for(;++f<c;)i[f]=Av(n[f]);else{const v=Av(n);for(;++f<c;)i[f]=v}f=-1;const h=[],m=[];for(;++f<c;){const v=i[f];let w="",b="";v===99?(w=":",b=":"):v===108?w=":":v===114&&(b=":");let C=r.alignDelimiters===!1?1:Math.max(1,l[f]-w.length-b.length);const T=w+"-".repeat(C)+b;r.alignDelimiters!==!1&&(C=w.length+C+b.length,C>l[f]&&(l[f]=C),m[f]=C),h[f]=T}a.splice(1,0,h),o.splice(1,0,m),d=-1;const g=[];for(;++d<a.length;){const v=a[d],w=o[d];f=-1;const b=[];for(;++f<c;){const C=v[f]||"";let T="",I="";if(r.alignDelimiters!==!1){const k=l[f]-(w[f]||0),_=i[f];_===114?T=" ".repeat(k):_===99?k%2?(T=" ".repeat(k/2+.5),I=" ".repeat(k/2-.5)):(T=" ".repeat(k/2),I=T):I=" ".repeat(k)}r.delimiterStart!==!1&&!f&&b.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&C==="")&&(r.delimiterStart!==!1||f)&&b.push(" "),r.alignDelimiters!==!1&&b.push(T),b.push(C),r.alignDelimiters!==!1&&b.push(I),r.padding!==!1&&b.push(" "),(r.delimiterEnd!==!1||f!==c-1)&&b.push("|")}g.push(r.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
53`)}function Xz(e){return e==null?"":String(e)}function Av(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function Jz(e,t,r,n){const s=r.enter("blockquote"),i=r.createTracker(n);i.move("> "),i.shift(2);const a=r.indentLines(r.containerFlow(e,i.current()),Zz);return s(),a}function Zz(e,t,r){return">"+(r?"":" ")+e}function eK(e,t){return kv(e,t.inConstruct,!0)&&!kv(e,t.notInConstruct,!1)}function kv(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function Nv(e,t,r,n){let s=-1;for(;++s<r.unsafe.length;)if(r.unsafe[s].character===`
54`&&eK(r.stack,r.unsafe[s]))return/[ \t]/.test(n.before)?"":" ";return`\\
55`}function tK(e,t){const r=String(e);let n=r.indexOf(t),s=n,i=0,a=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===s?++i>a&&(a=i):i=1,s=n+t.length,n=r.indexOf(t,s);return a}function rK(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function nK(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function sK(e,t,r,n){const s=nK(r),i=e.value||"",a=s==="`"?"GraveAccent":"Tilde";if(rK(e,r)){const f=r.enter("codeIndented"),h=r.indentLines(i,iK);return f(),h}const o=r.createTracker(n),l=s.repeat(Math.max(tK(i,s)+1,3)),c=r.enter("codeFenced");let d=o.move(l);if(e.lang){const f=r.enter(`codeFencedLang${a}`);d+=o.move(r.safe(e.lang,{before:d,after:" ",encode:["`"],...o.current()})),f()}if(e.lang&&e.meta){const f=r.enter(`codeFencedMeta${a}`);d+=o.move(" "),d+=o.move(r.safe(e.meta,{before:d,after:`
56`,encode:["`"],...o.current()})),f()}return d+=o.move(`
57`),i&&(d+=o.move(i+`
58`)),d+=o.move(l),c(),d}function iK(e,t,r){return(r?"":"    ")+e}function Rm(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function aK(e,t,r,n){const s=Rm(r),i=s==='"'?"Quote":"Apostrophe",a=r.enter("definition");let o=r.enter("label");const l=r.createTracker(n);let c=l.move("[");return c+=l.move(r.safe(r.associationId(e),{before:c,after:"]",...l.current()})),c+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),c+=l.move("<"),c+=l.move(r.safe(e.url,{before:c,after:">",...l.current()})),c+=l.move(">")):(o=r.enter("destinationRaw"),c+=l.move(r.safe(e.url,{before:c,after:e.title?" ":`
59`,...l.current()}))),o(),e.title&&(o=r.enter(`title${i}`),c+=l.move(" "+s),c+=l.move(r.safe(e.title,{before:c,after:s,...l.current()})),c+=l.move(s),o()),a(),c}function oK(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Lo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Wc(e,t,r){const n=Ca(e),s=Ca(t);return n===void 0?s===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}e2.peek=lK;function e2(e,t,r,n){const s=oK(r),i=r.enter("emphasis"),a=r.createTracker(n),o=a.move(s);let l=a.move(r.containerPhrasing(e,{after:s,before:o,...a.current()}));const c=l.charCodeAt(0),d=Wc(n.before.charCodeAt(n.before.length-1),c,s);d.inside&&(l=Lo(c)+l.slice(1));const f=l.charCodeAt(l.length-1),h=Wc(n.after.charCodeAt(0),f,s);h.inside&&(l=l.slice(0,-1)+Lo(f));const m=a.move(s);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},o+l+m}function lK(e,t,r){return r.options.emphasis||"*"}function cK(e,t){let r=!1;return km(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,Ph}),!!((!e.depth||e.depth<3)&&Cm(e)&&(t.options.setext||r))}function uK(e,t,r,n){const s=Math.max(Math.min(6,e.depth||1),1),i=r.createTracker(n);if(cK(e,r)){const d=r.enter("headingSetext"),f=r.enter("phrasing"),h=r.containerPhrasing(e,{...i.current(),before:`
60`,after:`
61`});return f(),d(),h+`
62`+(s===1?"=":"-").repeat(h.length-(Math.max(h.lastIndexOf("\r"),h.lastIndexOf(`
63`))+1))}const a="#".repeat(s),o=r.enter("headingAtx"),l=r.enter("phrasing");i.move(a+" ");let c=r.containerPhrasing(e,{before:"# ",after:`
64`,...i.current()});return/^[\t ]/.test(c)&&(c=Lo(c.charCodeAt(0))+c.slice(1)),c=c?a+" "+c:a,r.options.closeAtx&&(c+=" "+a),l(),o(),c}t2.peek=dK;function t2(e){return e.value||""}function dK(){return"<"}r2.peek=fK;function r2(e,t,r,n){const s=Rm(r),i=s==='"'?"Quote":"Apostrophe",a=r.enter("image");let o=r.enter("label");const l=r.createTracker(n);let c=l.move("![");return c+=l.move(r.safe(e.alt,{before:c,after:"]",...l.current()})),c+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),c+=l.move("<"),c+=l.move(r.safe(e.url,{before:c,after:">",...l.current()})),c+=l.move(">")):(o=r.enter("destinationRaw"),c+=l.move(r.safe(e.url,{before:c,after:e.title?" ":")",...l.current()}))),o(),e.title&&(o=r.enter(`title${i}`),c+=l.move(" "+s),c+=l.move(r.safe(e.title,{before:c,after:s,...l.current()})),c+=l.move(s),o()),c+=l.move(")"),a(),c}function fK(){return"!"}n2.peek=hK;function n2(e,t,r,n){const s=e.referenceType,i=r.enter("imageReference");let a=r.enter("label");const o=r.createTracker(n);let l=o.move("![");const c=r.safe(e.alt,{before:l,after:"]",...o.current()});l+=o.move(c+"]["),a();const d=r.stack;r.stack=[],a=r.enter("reference");const f=r.safe(r.associationId(e),{before:l,after:"]",...o.current()});return a(),r.stack=d,i(),s==="full"||!c||c!==f?l+=o.move(f+"]"):s==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function hK(){return"!"}s2.peek=pK;function s2(e,t,r){let n=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(n);)s+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++i<r.unsafe.length;){const a=r.unsafe[i],o=r.compilePattern(a);let l;if(a.atBreak)for(;l=o.exec(n);){let c=l.index;n.charCodeAt(c)===10&&n.charCodeAt(c-1)===13&&c--,n=n.slice(0,c)+" "+n.slice(l.index+1)}}return s+n+s}function pK(){return"`"}function i2(e,t){const r=Cm(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}a2.peek=mK;function a2(e,t,r,n){const s=Rm(r),i=s==='"'?"Quote":"Apostrophe",a=r.createTracker(n);let o,l;if(i2(e,r)){const d=r.stack;r.stack=[],o=r.enter("autolink");let f=a.move("<");return f+=a.move(r.containerPhrasing(e,{before:f,after:">",...a.current()})),f+=a.move(">"),o(),r.stack=d,f}o=r.enter("link"),l=r.enter("label");let c=a.move("[");return c+=a.move(r.containerPhrasing(e,{before:c,after:"](",...a.current()})),c+=a.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),c+=a.move("<"),c+=a.move(r.safe(e.url,{before:c,after:">",...a.current()})),c+=a.move(">")):(l=r.enter("destinationRaw"),c+=a.move(r.safe(e.url,{before:c,after:e.title?" ":")",...a.current()}))),l(),e.title&&(l=r.enter(`title${i}`),c+=a.move(" "+s),c+=a.move(r.safe(e.title,{before:c,after:s,...a.current()})),c+=a.move(s),l()),c+=a.move(")"),o(),c}function mK(e,t,r){return i2(e,r)?"<":"["}o2.peek=gK;function o2(e,t,r,n){const s=e.referenceType,i=r.enter("linkReference");let a=r.enter("label");const o=r.createTracker(n);let l=o.move("[");const c=r.containerPhrasing(e,{before:l,after:"]",...o.current()});l+=o.move(c+"]["),a();const d=r.stack;r.stack=[],a=r.enter("reference");const f=r.safe(r.associationId(e),{before:l,after:"]",...o.current()});return a(),r.stack=d,i(),s==="full"||!c||c!==f?l+=o.move(f+"]"):s==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function gK(){return"["}function Pm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function yK(e){const t=Pm(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function vK(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function l2(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function xK(e,t,r,n){const s=r.enter("list"),i=r.bulletCurrent;let a=e.ordered?vK(r):Pm(r);const o=e.ordered?a==="."?")":".":yK(r);let l=t&&r.bulletLastUsed?a===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&d&&(!d.children||!d.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(l=!0),l2(r)===a&&d){let f=-1;for(;++f<e.children.length;){const h=e.children[f];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(a=o),r.bulletCurrent=a;const c=r.containerFlow(e,n);return r.bulletLastUsed=a,r.bulletCurrent=i,s(),c}function bK(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function wK(e,t,r,n){const s=bK(r);let i=r.bulletCurrent||Pm(r);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let a=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(a=Math.ceil(a/4)*4);const o=r.createTracker(n);o.move(i+" ".repeat(a-i.length)),o.shift(a);const l=r.enter("listItem"),c=r.indentLines(r.containerFlow(e,o.current()),d);return l(),c;function d(f,h,m){return h?(m?"":" ".repeat(a))+f:(m?i:i+" ".repeat(a-i.length))+f}}function CK(e,t,r,n){const s=r.enter("paragraph"),i=r.enter("phrasing"),a=r.containerPhrasing(e,n);return i(),s(),a}const SK=Mu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function EK(e,t,r,n){return(e.children.some(function(a){return SK(a)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function TK(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}c2.peek=_K;function c2(e,t,r,n){const s=TK(r),i=r.enter("strong"),a=r.createTracker(n),o=a.move(s+s);let l=a.move(r.containerPhrasing(e,{after:s,before:o,...a.current()}));const c=l.charCodeAt(0),d=Wc(n.before.charCodeAt(n.before.length-1),c,s);d.inside&&(l=Lo(c)+l.slice(1));const f=l.charCodeAt(l.length-1),h=Wc(n.after.charCodeAt(0),f,s);h.inside&&(l=l.slice(0,-1)+Lo(f));const m=a.move(s+s);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},o+l+m}function _K(e,t,r){return r.options.strong||"*"}
vendor: 5,796 bytes, lines 64-66
64function IK(e,t,r,n){return r.safe(e.value,n)}function AK(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function kK(e,t,r){const n=(l2(r)+(r.options.ruleSpaces?" ":"")).repeat(AK(r));return r.options.ruleSpaces?n.slice(0,-1):n}const u2={blockquote:Jz,break:Nv,code:sK,definition:aK,emphasis:e2,hardBreak:Nv,heading:uK,html:t2,image:r2,imageReference:n2,inlineCode:s2,link:a2,linkReference:o2,list:xK,listItem:wK,paragraph:CK,root:EK,strong:c2,text:IK,thematicBreak:kK};function NK(){return{enter:{table:RK,tableData:Rv,tableHeader:Rv,tableRow:jK},exit:{codeText:BK,table:PK,tableData:hf,tableHeader:hf,tableRow:hf}}}function RK(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function PK(e){this.exit(e),this.data.inTable=void 0}function jK(e){this.enter({type:"tableRow",children:[]},e)}function hf(e){this.exit(e)}function Rv(e){this.enter({type:"tableCell",children:[]},e)}function BK(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,DK));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function DK(e,t){return t==="|"?t:e}function LK(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,s=t.stringLength,i=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
65`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[	 :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:h,table:a,tableCell:l,tableRow:o}};function a(m,g,v,w){return c(d(m,v,w),m.align)}function o(m,g,v,w){const b=f(m,v,w),C=c([b]);return C.slice(0,C.indexOf(`
66`))}function l(m,g,v,w){const b=v.enter("tableCell"),C=v.enter("phrasing"),T=v.containerPhrasing(m,{...w,before:i,after:i});return C(),b(),T}function c(m,g){return Qz(m,{align:g,alignDelimiters:n,padding:r,stringLength:s})}function d(m,g,v){const w=m.children;let b=-1;const C=[],T=g.enter("table");for(;++b<w.length;)C[b]=f(w[b],g,v);return T(),C}function f(m,g,v){const w=m.children;let b=-1;const C=[],T=g.enter("tableRow");for(;++b<w.length;)C[b]=l(w[b],m,g,v);return T(),C}function h(m,g,v){let w=u2.inlineCode(m,g,v);return v.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function MK(){return{exit:{taskListCheckValueChecked:Pv,taskListCheckValueUnchecked:Pv,paragraph:FK}}}function OK(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:UK}}}function Pv(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function FK(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const s=t.children;let i=-1,a;for(;++i<s.length;){const o=s[i];if(o.type==="paragraph"){a=o;break}}a===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function UK(e,t,r,n){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);i&&o.move(a);let l=u2.listItem(e,t,r,{...n,...o.current()});return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,c)),l;function c(d){return d+a}}function VK(){return[xz(),Uz(),Kz(),NK(),MK()]}function $K(e){return{extensions:[bz(),Vz(e),qz(),LK(e),OK()]}}const zK={tokenize:YK,partial:!0},d2={tokenize:QK,partial:!0},f2={tokenize:XK,partial:!0},h2={tokenize:JK,partial:!0},KK={tokenize:ZK,partial:!0},p2={name:"wwwAutolink",tokenize:GK,previous:g2},m2={name:"protocolAutolink",tokenize:WK,previous:y2},_s={name:"emailAutolink",tokenize:HK,previous:v2},hs={};function qK(){return{text:hs}}let yi=48;for(;yi<123;)hs[yi]=_s,yi++,yi===58?yi=65:yi===91&&(yi=97);hs[43]=_s;hs[45]=_s;hs[46]=_s;hs[95]=_s;hs[72]=[_s,m2];hs[104]=[_s,m2];hs[87]=[_s,p2];hs[119]=[_s,p2];function HK(e,t,r){const n=this;let s,i;return a;function a(f){return!Lh(f)||!v2.call(n,n.previous)||jm(n.events)?r(f):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(f))}function o(f){return Lh(f)?(e.consume(f),o):f===64?(e.consume(f),l):r(f)}function l(f){return f===46?e.check(KK,d,c)(f):f===45||f===95||Vr(f)?(i=!0,e.consume(f),l):d(f)}function c(f){return e.consume(f),s=!0,l}function d(f){return i&&s&&Qr(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(f)):r(f)}}function GK(e,t,r){const n=this;return s;function s(a){return a!==87&&a!==119||!g2.call(n,n.previous)||jm(n.events)?r(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(zK,e.attempt(d2,e.attempt(f2,i),r),r)(a))}function i(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function WK(e,t,r){const n=this;let s="",i=!1;return a;function a(f){return(f===72||f===104)&&y2.call(n,n.previous)&&!jm(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(f),e.consume(f),o):r(f)}function o(f){if(Qr(f)&&s.length<5)return s+=String.fromCodePoint(f),e.consume(f),o;if(f===58){const h=s.toLowerCase();if(h==="http"||h==="https")return e.consume(f),l}return r(f)}function l(f){return f===47?(e.consume(f),i?c:(i=!0,l)):r(f)}function c(f){return f===null||qc(f)||er(f)||Bi(f)||Bu(f)?r(f):e.attempt(d2,e.attempt(f2,d),r)(f)}function d(f){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(f)}}function YK(e,t,r){let n=0;return s;function s(a){return(a===87||a===119)&&n<3?(n++,e.consume(a),s):a===46&&n===3?(e.consume(a),i):r(a)}
vendor: 8,036 bytes, line 66
66function i(a){return a===null?r(a):t(a)}}function QK(e,t,r){let n,s,i;return a;function a(c){return c===46||c===95?e.check(h2,l,o)(c):c===null||er(c)||Bi(c)||c!==45&&Bu(c)?l(c):(i=!0,e.consume(c),a)}function o(c){return c===95?n=!0:(s=n,n=void 0),e.consume(c),a}function l(c){return s||n||!i?r(c):t(c)}}function XK(e,t){let r=0,n=0;return s;function s(a){return a===40?(r++,e.consume(a),s):a===41&&n<r?i(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(h2,t,i)(a):a===null||er(a)||Bi(a)?t(a):(e.consume(a),s)}function i(a){return a===41&&n++,e.consume(a),s}}function JK(e,t,r){return n;function n(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),n):o===38?(e.consume(o),i):o===93?(e.consume(o),s):o===60||o===null||er(o)||Bi(o)?t(o):r(o)}function s(o){return o===null||o===40||o===91||er(o)||Bi(o)?t(o):n(o)}function i(o){return Qr(o)?a(o):r(o)}function a(o){return o===59?(e.consume(o),n):Qr(o)?(e.consume(o),a):r(o)}}function ZK(e,t,r){return n;function n(i){return e.consume(i),s}function s(i){return Vr(i)?r(i):t(i)}}function g2(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||er(e)}function y2(e){return!Qr(e)}function v2(e){return!(e===47||Lh(e))}function Lh(e){return e===43||e===45||e===46||e===95||Vr(e)}function jm(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const eq={tokenize:lq,partial:!0};function tq(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:iq,continuation:{tokenize:aq},exit:oq}},text:{91:{name:"gfmFootnoteCall",tokenize:sq},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:rq,resolveTo:nq}}}}function rq(e,t,r){const n=this;let s=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let a;for(;s--;){const l=n.events[s][1];if(l.type==="labelImage"){a=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!a||!a._balanced)return r(l);const c=Kn(n.sliceSerialize({start:a.end,end:n.now()}));return c.codePointAt(0)!==94||!i.includes(c.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function nq(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",a,t],["exit",a,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function sq(e,t,r){const n=this,s=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=0,a;return o;function o(f){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),l}function l(f){return f!==94?r(f):(e.enter("gfmFootnoteCallMarker"),e.consume(f),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",c)}function c(f){if(i>999||f===93&&!a||f===null||f===91||er(f))return r(f);if(f===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return s.includes(Kn(n.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(f)}return er(f)||(a=!0),i++,e.consume(f),f===92?d:c}function d(f){return f===91||f===92||f===93?(e.consume(f),i++,c):c(f)}}function iq(e,t,r){const n=this,s=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,a=0,o;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(g)}function d(g){if(a>999||g===93&&!o||g===null||g===91||er(g))return r(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteDefinitionLabelString");return i=Kn(n.sliceSerialize(v)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return er(g)||(o=!0),a++,e.consume(g),g===92?f:d}function f(g){return g===91||g===92||g===93?(e.consume(g),a++,d):d(g)}function h(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),s.includes(i)||s.push(i),$t(e,m,"gfmFootnoteDefinitionWhitespace")):r(g)}function m(g){return t(g)}}function aq(e,t,r){return e.check(sl,t,e.attempt(eq,t,r))}function oq(e){e.exit("gfmFootnoteDefinition")}function lq(e,t,r){const n=this;return $t(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const a=n.events[n.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?t(i):r(i)}}function cq(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:s};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function s(a,o){let l=-1;for(;++l<a.length;)if(a[l][0]==="enter"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._close){let c=l;for(;c--;)if(a[c][0]==="exit"&&a[c][1].type==="strikethroughSequenceTemporary"&&a[c][1]._open&&a[l][1].end.offset-a[l][1].start.offset===a[c][1].end.offset-a[c][1].start.offset){a[l][1].type="strikethroughSequence",a[c][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},a[c][1].start),end:Object.assign({},a[l][1].end)},f={type:"strikethroughText",start:Object.assign({},a[c][1].end),end:Object.assign({},a[l][1].start)},h=[["enter",d,o],["enter",a[c][1],o],["exit",a[c][1],o],["enter",f,o]],m=o.parser.constructs.insideSpan.null;m&&yn(h,h.length,0,Du(m,a.slice(c+1,l),o)),yn(h,h.length,0,[["exit",f,o],["enter",a[l][1],o],["exit",a[l][1],o],["exit",d,o]]),yn(a,c-1,l-c+3,h),l=c+h.length-2;break}}for(l=-1;++l<a.length;)a[l][1].type==="strikethroughSequenceTemporary"&&(a[l][1].type="data");return a}function i(a,o,l){const c=this.previous,d=this.events;let f=0;return h;function h(g){return c===126&&d[d.length-1][1].type!=="characterEscape"?l(g):(a.enter("strikethroughSequenceTemporary"),m(g))}function m(g){const v=Ca(c);if(g===126)return f>1?l(g):(a.consume(g),f++,m);if(f<2&&!r)return l(g);const w=a.exit("strikethroughSequenceTemporary"),b=Ca(g);return w._open=!b||b===2&&!!v,w._close=!v||v===2&&!!b,o(g)}}}class uq{constructor(){this.map=[]}add(t,r,n){dq(this,t,r,n)}consume(t){if(this.map.sort(function(i,a){return i[0]-a[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let s=n.pop();for(;s;){for(const i of s)t.push(i);s=n.pop()}this.map.length=0}}function dq(e,t,r,n){let s=0;if(!(r===0&&n.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=r,e.map[s][2].push(...n);return}s+=1}e.map.push([t,r,n])}}function fq(e,t){let r=!1;const n=[];for(;t<e.length;){const s=e[t];if(r){if(s[0]==="enter")s[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left"
vendor: 4,353 bytes, line 66
66:"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=n.length-1;n[i]=n[i]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function hq(){return{flow:{null:{name:"table",tokenize:pq,resolveAll:mq}}}}function pq(e,t,r){const n=this;let s=0,i=0,a;return o;function o(L){let H=n.events.length-1;for(;H>-1;){const J=n.events[H][1].type;if(J==="lineEnding"||J==="linePrefix")H--;else break}const F=H>-1?n.events[H][1].type:null,Q=F==="tableHead"||F==="tableRow"?_:l;return Q===_&&n.parser.lazy[n.now().line]?r(L):Q(L)}function l(L){return e.enter("tableHead"),e.enter("tableRow"),c(L)}function c(L){return L===124||(a=!0,i+=1),d(L)}function d(L){return L===null?r(L):lt(L)?i>1?(i=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(L),e.exit("lineEnding"),m):r(L):Dt(L)?$t(e,d,"whitespace")(L):(i+=1,a&&(a=!1,s+=1),L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),a=!0,d):(e.enter("data"),f(L)))}function f(L){return L===null||L===124||er(L)?(e.exit("data"),d(L)):(e.consume(L),L===92?h:f)}function h(L){return L===92||L===124?(e.consume(L),f):f(L)}function m(L){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(L):(e.enter("tableDelimiterRow"),a=!1,Dt(L)?$t(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):g(L))}function g(L){return L===45||L===58?w(L):L===124?(a=!0,e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),v):k(L)}function v(L){return Dt(L)?$t(e,w,"whitespace")(L):w(L)}function w(L){return L===58?(i+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),b):L===45?(i+=1,b(L)):L===null||lt(L)?I(L):k(L)}function b(L){return L===45?(e.enter("tableDelimiterFiller"),C(L)):k(L)}function C(L){return L===45?(e.consume(L),C):L===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),T):(e.exit("tableDelimiterFiller"),T(L))}function T(L){return Dt(L)?$t(e,I,"whitespace")(L):I(L)}function I(L){return L===124?g(L):L===null||lt(L)?!a||s!==i?k(L):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(L)):k(L)}function k(L){return r(L)}function _(L){return e.enter("tableRow"),M(L)}function M(L){return L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),M):L===null||lt(L)?(e.exit("tableRow"),t(L)):Dt(L)?$t(e,M,"whitespace")(L):(e.enter("data"),V(L))}function V(L){return L===null||L===124||er(L)?(e.exit("data"),M(L)):(e.consume(L),L===92?G:V)}function G(L){return L===92||L===124?(e.consume(L),V):V(L)}}function mq(e,t){let r=-1,n=!0,s=0,i=[0,0,0,0],a=[0,0,0,0],o=!1,l=0,c,d,f;const h=new uq;for(;++r<e.length;){const m=e[r],g=m[1];m[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(jv(h,t,l,c,d),d=void 0,l=0),c={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(r,0,[["enter",c,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(n=!0,f=void 0,i=[0,0,0,0],a=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(r,0,[["enter",d,t]])),s=g.type==="tableDelimiterRow"?2:d?3:1):s&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,a[2]===0&&(i[1]!==0&&(a[0]=a[1],f=Jl(h,t,i,s,void 0,f),i=[0,0,0,0]),a[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(a[0]=a[1],f=Jl(h,t,i,s,void 0,f)),i=a,a=[i[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,i[1]!==0?(a[0]=a[1],f=Jl(h,t,i,s,r,f)):a[1]!==0&&(f=Jl(h,t,a,s,r,f)),s=0):s&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(a[3]=r)}for(l!==0&&jv(h,t,l,c,d),h.consume(t.events),r=-1;++r<t.events.length;){const m=t.events[r];m[0]==="enter"&&m[1].type==="table"&&(m[1]._align=fq(t.events,r))}return e}function Jl(e,t,r,n,s,i){const a=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(i.end=Object.assign({},aa(t.events,r[0])),e.add(r[0],0,[["exit",i,t]]));const l=aa(t.events,r[1]);if(i={type:a,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",i,t]]),r[2]!==0){const c=aa(t.events,r[2]),d=aa(t.events,r[3]),f={type:o,start:Object.assign({},c),end:Object.assign({},d)};
66if(e.add(r[2],0,[["enter",f,t]]),n!==2){const h=t.events[r[2]],m=t.events[r[3]];if(h[1].end=Object.assign({},m[1].end),h[1].type="chunkText",h[1].contentType="text",r[3]>r[2]+1){const g=r[2]+1,v=r[3]-r[2]-1;e.add(g,v,[])}}e.add(r[3]+1,0,[["exit",f,t]])}return s!==void 0&&(i.end=Object.assign({},aa(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function jv(e,t,r,n,s){const i=[],a=aa(t.events,r);s&&(s.end=Object.assign({},a),i.push(["exit",s,t])),n.end=Object.assign({},a),i.push(["exit",n,t]),e.add(r+1,0,i)}function aa(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const gq={name:"tasklistCheck",tokenize:vq};function yq(){return{text:{91:gq}}}function vq(e,t,r){const n=this;return s;function s(l){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),i)}function i(l){return er(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),a):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),a):r(l)}function a(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):r(l)}function o(l){return lt(l)?t(l):Dt(l)?e.check({tokenize:xq},t,r)(l):r(l)}}function xq(e,t,r){return $t(e,n,"whitespace");function n(s){return s===null?r(s):t(s)}}function bq(e){return AE([qK(),tq(),cq(e),hq(),yq()])}const wq={};function Cq(e){const t=this,r=e||wq,n=t.data(),s=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),a=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);s.push(bq(r)),i.push(VK()),a.push($K(r))}const Sq="https://x402.slinkylayer.ai";function Eq(e){if(/^https?:\/\//i.test(e))return e;const t=Sq.replace(/\/$/,""),r=e.startsWith("/")?e:`/${e}`;return`${t}${r}`}async function Tq({url:e,method:t="POST",query:r,body:n,headers:s}){const i=window.ethereum;if(!i)throw new Error("No wallet provider found. Please install/enable a wallet.");const[a]=await i.request({method:"eth_requestAccounts"});try{await i.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x2105"}]})}catch(C){if(C?.code===4902)await i.request({method:"wallet_addEthereumChain",params:[{chainId:"0x2105",chainName:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://mainnet.base.org"],blockExplorerUrls:["https://basescan.org"]}]});else throw C}const o=zv({account:a,chain:Kv,transport:qv(i)}),l={address:a,async signTypedData(C){const T={...C.types};return delete T.EIP712Domain,o.signTypedData({account:a,domain:C.domain,types:T,primaryType:C.primaryType,message:C.message})}},c=new iw;pw(c,{signer:l});const d=ow(qh.create(),c),f=new URL(Eq(e));if(r)for(const[C,T]of Object.entries(r))T==null||T===""||f.searchParams.append(C,String(T));const h={...s??{}};let m;t!=="GET"&&n&&(h["Content-Type"]="application/json",m=n);const g=await d.request({url:f.toString(),method:t,headers:h,data:m});let v,w;const b=g.headers?.["payment-response"];if(b)try{v=Pc(b),w=v?.transaction}catch{}return{data:g.data,paymentResponse:v,txHash:w}}const Bv=2e3,_q=60;function Iq(e){return!e||typeof e!="object"?null:e.job_id??e.run_id??e.data?.job_id??e.data?.run_id??null}function Aq(e){const t=e?.apiId,r=e?.resourceId;if(t!=null&&r)return{apiId:t,resourceId:r};const n=e?.endpoint;if(typeof n=="string"){const s=n.match(/\/proxy\/([^/?#]+)\/([^/?#]+)/);if(s)return{apiId:s[1],resourceId:s[2]}}return null}async function kq({apiId:e,resourceId:t,jobId:r,isCancelled:n}){for(let s=0;s<_q;s++){if(n?.())throw new Error("Polling cancelled");let i;try{i=await J1({apiId:e,resourceId:t,jobId:r})}catch{await new Promise(d=>setTimeout(d,Bv));continue}const a=i?.status??i?.state??i?.data?.status??i?.run?.status??i?.run?.state,o=a==="completed"||a==="success"||a==="succeeded"||a==="done"||a==="finished",l=a==="failed"||a==="error"||a==="cancelled",c=i?.output!==void 0||i?.data?.output!==void 0||i?.result!==void 0;if(o||!a&&c)return i;if(l){const d=i?.error??i?.message??"Job failed";throw new Error(String(d))}await new Promise(d=>setTimeout(d,Bv))}throw new Error("Job timed out after 2 minutes")}function x2({data:e}={}){const t=e?.name??"search_docs",r=e?.args??{query:"example",limit:5};return u.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-muted/30 p-3 text-xs",children:[u.jsxs("div",{className:"flex items-center gap-2 font-medium text-foreground",children:[u.jsx(Ax,{className:"h-3.5 w-3.5 text-[#98fe00]"}),"Tool call · ",u.jsx("span",{className:"text-muted-foreground",children:t}),e?.status&&u.jsx("span",{className:"rounded-full bg-background/70 px-2 py-0.5 text-[10px] uppercase text-muted-foreground",children:e.status}),u.jsx("span",{className:"ml-auto rounded-full bg-background/70 px-2 py-0.5 text-[10px] uppercase text-muted-foreground",children:e?"tool":"placeholder"})]}),u.jsx("pre",{className:"mt-2 overflow-x-auto rounded bg-background/60 p-2 text-[11px] text-muted-foreground",children:JSON.stringify(r,null,2)})]})}const Mh={requested_service:"google",language:"en",limit:5},Nq=new Set(["text","content","input","prompt","url","query","image","image_url","file","file_url","data"]);function Rq(e,t){const r=n=>n!=null&&!(typeof n=="string"&&n.trim()==="");return!!(r(e?.body?.[t])||r(e?.query?.[t])||t!=="body"&&t!=="query"&&r(e?.[t]))}function ta(e,t,r){return!!(t.required||Rq(r,e)||Nq.has(e))}function Pq(e,t){const r={},n=new Set([...Object.keys(e?.body??{}),...Object.keys(e?.query??{}),...Object.keys(e?.path??{})]),s=a=>
66{if(a)for(const[o,l]of Object.entries(a))l!=null&&(Array.isArray(l)?r[o]=JSON.stringify(l,null,2):r[o]=l)};if(s(t?.body),s(t?.query),t&&typeof t=="object")for(const[a,o]of Object.entries(t))a==="body"||a==="query"||n.has(a)&&o!=null&&(r[a]!=null&&r[a]!==""||(Array.isArray(o)?r[a]=JSON.stringify(o,null,2):r[a]=o));const i=a=>{if(a)for(const[o,l]of Object.entries(a))l?.defaultValue!==void 0&&(r[o]==null||r[o]==="")&&(r[o]=l.defaultValue)};i(e?.body),i(e?.query),i(e?.path);for(const[a,o]of Object.entries(Mh))n.has(a)&&(r[a]==null||r[a]==="")&&(r[a]=o);for(const a of n)a in r||(r[a]="");return r}function Dv(e){return e.default!=null?String(e.default):e.name in Mh?String(Mh[e.name]):""}function Lv({field:e,value:t,onChange:r,required:n}){const s=`paid-field-${e.name}`,i=e.type==="number"||e.type==="integer";return u.jsxs("div",{className:"space-y-1",children:[u.jsxs("label",{htmlFor:s,className:"flex items-center gap-1 text-[11px] font-medium text-foreground",children:[e.name,n&&u.jsx("span",{className:"text-[#98fe00]",children:"*"}),e.type&&u.jsx("span",{className:"ml-1 rounded bg-background/70 px-1 py-0.5 text-[9px] uppercase text-muted-foreground",children:e.type})]}),e.description&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80",children:e.description}),u.jsx("input",{id:s,type:i?"number":"text",value:t,onChange:a=>r(a.target.value),placeholder:e.placeholder??(e.name==="url"?"https://…":""),className:"w-full rounded border border-border/60 bg-background/80 px-2 py-1 text-xs outline-none focus:border-[#98fe00]/60 focus:ring-1 focus:ring-[#98fe00]/40"})]})}function ra({fieldKey:e,meta:t,value:r,isQuery:n,onChange:s,onNestedChange:i}){const a=t.example??t.value,o=Array.isArray(a),l=typeof a=="object"&&a!==null&&!o&&Object.keys(a).length>0,c=t.type===Number||t.type==="number"||t.type==="integer",d=n?" (query parameter)":"",f=t.placeholder??(e==="url"?"https://…":`Enter ${e}`),h=u.jsxs("label",{htmlFor:e,className:"flex items-center gap-1 text-[11px] font-medium text-foreground",children:[u.jsxs("span",{children:[e,d]}),t.required?u.jsx("span",{className:"text-[#98fe00]",children:"*"}):u.jsx("span",{className:"text-muted-foreground/70",children:"(optional)"})]}),m=a!=null&&typeof a!="object"?u.jsxs("p",{className:"text-[10px] text-muted-foreground/70",children:["Example: ",u.jsx("span",{className:"font-mono",children:String(a)})]}):null,g=t.help??t.more,v=u.jsx(u.Fragment,{children:g?u.jsx("p",{className:"text-[10px] text-muted-foreground/80",children:g}):m}),w="w-full rounded border border-border/60 bg-background/80 px-2 py-1 text-xs outline-none focus:border-[#98fe00]/60 focus:ring-1 focus:ring-[#98fe00]/40";if(l)return u.jsxs("div",{className:"space-y-1",children:[h,v,u.jsx("div",{className:"ml-2 space-y-2 rounded border border-border/60 bg-background/40 p-2",children:Object.entries(a).map(([C])=>u.jsxs("div",{className:"space-y-1",children:[u.jsx("label",{htmlFor:`${e}_${C}`,className:"text-[10px] text-muted-foreground",children:C}),u.jsx("input",{id:`${e}_${C}`,type:"text",value:r?.[C]??"",onChange:T=>i(e,C,T.target.value),placeholder:`Enter ${C}`,className:w})]},C))})]});if(o)return u.jsxs("div",{className:"space-y-1",children:[h,v,u.jsx("textarea",{id:e,value:r??"",onChange:C=>s(C.target.value),placeholder:t.placeholder??`Enter ${e} as JSON`,rows:5,className:`${w} font-mono`})]});const b=e==="content"||e==="text";return u.jsxs("div",{className:"space-y-1",children:[h,v,b?u.jsx("textarea",{id:e,value:r??"",onChange:C=>s(C.target.value),placeholder:f,rows:3,className:w}):u.jsx("input",{id:e,type:c?"number":"text",value:r??"",onChange:C=>s(c?Number(C.target.value):C.target.value),placeholder:f,className:w})]})}const b2="slinky.chat.card.v1:";function jq(e){if(typeof window>"u")return null;try{const t=localStorage.getItem(b2+e);return t?JSON.parse(t):null}catch{return null}}function Bq(e,t){if(!(typeof window>"u"))try{localStorage.setItem(b2+e,JSON.stringify(t))}catch{}}function Qs({children:e}){return u.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.08em] text-foreground",children:[u.jsx("span",{className:"h-3.5 w-[3px] rounded-full bg-[#98fe00]"}),e]})}function Dq(e){if(!e||typeof e!="object")return[];const t=[],r=new Set,n=(i,a)=>{a==null||a===""||r.has(i)||(r.add(i),t.push([i,a]))},s=i=>
66{if(!(!i||typeof i!="object"))for(const[a,o]of Object.entries(i))n(a,o)};s(e.body),s(e.query);for(const[i,a]of Object.entries(e))i==="body"||i==="query"||n(i,a);return t}function pf({fieldKey:e,meta:t,value:r,isQuery:n}){const s=`payload-field-${e}`,i=u.jsxs("label",{htmlFor:s,className:"flex items-center gap-1 text-[12px] font-medium text-foreground",children:[u.jsx("span",{children:e}),t.required?u.jsx("span",{className:"text-[#98fe00]",children:"*"}):u.jsx("span",{className:"text-muted-foreground/70",children:"(optional)"}),n&&u.jsx("span",{className:"ml-1 rounded bg-background/70 px-1 py-0.5 text-[9px] uppercase text-muted-foreground",children:"query"})]}),a=t.help??t.more,o=t.example??t.value,l=(()=>{if(r==null)return"";if(typeof r=="object")try{return JSON.stringify(r,null,2)}catch{return String(r)}return String(r)})(),c=typeof r=="object"||typeof l=="string"&&l.length>80||e==="content"||e==="text";return u.jsxs("div",{className:"space-y-1",children:[i,a&&u.jsx("p",{className:"text-[11px] leading-snug text-muted-foreground/80",children:a}),o!=null&&typeof o!="object"&&!a&&u.jsxs("p",{className:"text-[11px] text-muted-foreground/70",children:["Example: ",u.jsx("span",{className:"font-mono",children:String(o)})]}),c?u.jsx("textarea",{id:s,readOnly:!0,value:l,rows:Math.min(6,Math.max(2,Math.ceil(l.length/60))),className:"w-full rounded border border-border/60 bg-background/50 px-2 py-1.5 font-mono text-[11px] leading-snug text-foreground outline-none resize-none"}):u.jsx("input",{id:s,type:"text",readOnly:!0,value:l,className:"w-full rounded border border-border/60 bg-background/50 px-2 py-1.5 text-[12px] text-foreground outline-none"})]})}function Lq({requestExample:e,values:t}){const r=Object.entries(e?.body??{}),n=Object.entries(e?.query??{}),s=Object.entries(e?.path??{});return r.length+n.length+s.length===0?null:u.jsxs("div",{className:"space-y-4",children:[r.length>0&&u.jsxs("div",{className:"space-y-3",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Body"}),r.map(([i,a])=>u.jsx(pf,{fieldKey:i,meta:a,value:t[i]},`body-${i}`))]}),n.length>0&&u.jsxs("div",{className:"space-y-3",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Query"}),n.map(([i,a])=>u.jsx(pf,{fieldKey:i,meta:a,value:t[i],isQuery:!0},`query-${i}`))]}),s.length>0&&u.jsxs("div",{className:"space-y-3",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Path"}),s.map(([i,a])=>u.jsx(pf,{fieldKey:i,meta:a,value:t[i],isQuery:!0},`path-${i}`))]})]})}function Mq({text:e,label:t="Copy"}){const[r,n]=N.useState(!1);return u.jsx("button",{type:"button",onClick:async s=>{s.stopPropagation();try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),1500)}catch{}},className:"inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-white",title:r?"Copied":t,"aria-label":t,children:r?u.jsx(jr,{className:"h-3.5 w-3.5"}):u.jsx(zn,{className:"h-3.5 w-3.5"})})}function Oq({txHash:e,resultData:t}){const[r,n]=N.useState(!1),[s,i]=N.useState(!1),a=(()=>{if(t==null)return"";try{return typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return String(t)}})(),o=async()=>{if(e)try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},l=e?`${e.slice(0,10)}…${e.slice(-6)}`:"";return u.jsxs("div",{className:"mt-2 mb-2 rounded-xl border border-[#98fe00]/50 bg-white p-5 text-xs dark:bg-background",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(u_,{className:"h-4 w-4 text-[#98fe00]"}),u.jsx(Qs,{children:"ROUTE EXECUTED"}),u.jsx("span",{className:"ml-auto rounded-full bg-[#98fe00] px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-black",children:"Settled"})]}),u.jsxs("div",{className:"mt-5 space-y-2",children:[u.jsx(Qs,{children:"RECEIPT"}),u.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-[12px]",children:[u.jsxs("span",{className:"text-muted-foreground",children:["Paid via ",u.jsx("span",{className:"text-foreground",children:"x402"})]}),e&&u.jsxs(u.Fragment,{children:[u.jsxs("span",{className:"text-muted-foreground",children:["tx ",u.jsx("span",{className:"font-mono text-foreground",children:l})]}),u.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[u.jsx("button",{type:"button",onClick:o,className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground",title:s?"Copied":"Copy tx hash","aria-label":"Copy tx hash",children:s?u.jsx(jr,{className:"h-3.5 w-3.5"}):u.jsx(zn,{className:"h-3.5 w-3.5"})}),u.jsx("a",{href:`https://basescan.org/tx/${e}`,target:"_blank",rel:"noreferrer",className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground",title:"View on BaseScan",children:u.jsx(kx,{className:"h-3.5 w-3.5"})})]})]})]})]}),u.jsxs("div",{className:"mt-5 space-y-2",children:[u.jsx(Qs,{children:"EVIDENCE"}),u.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border/60 bg-transparent px-3 py-2 text-[12px]",children:[u.jsxs("button",{type:"button",onClick:()=>n(c=>!c),className:"flex flex-1 items-center gap-2 text-left",children:[u.jsx(ru,{className:ze("h-3.5 w-3.5 text-muted-foreground transition-transform",r&&"rotate-90")}),u.jsx("span",{className:"font-semibold text-foreground",children:"Evidence packet (JSON)"})]}),u.jsxs("div",{className:"flex items-center gap-1",children:[u.jsx("button",{type:"button",onClick:()=>n(c=>!c),className:"text-[11px] font-medium text-muted-foreground hover:text-foreground",children:r?"Collapse":"Expand"}),u.jsx(Mq,{text:a,label:"Copy evidence packet"})]})]}),r&&u.jsx("pre",{className:"max-h-80 overflow-auto rounded-md border border-border/60 bg-transparent p-3 font-mono text-[11px] leading-snug text-foreground",children:a||"(no data)"})]})]})}function Fq({data:e,onApprove:t,onReject:r,onCompleted:n,threadId:s,messageId:i}={}){const a=e?.endpoint??"/tools/example/run",o=e?.requestExample,l=!!(o&&(o.body||o.query||o.path)),c=e?.method??(l?o?.body?"POST":"GET":"POST"),d=e?.estimatedCost??e?.price??e?.perCallPrice,f=d==null||d===""?"—":d,h=e?.currency??"USDC",m=e?.requiredFields??[],g=e?.optionalFields??[],v=N.useMemo(()=>i&&e?.endpoint?`${i}::${e.endpoint}`:i||`anon::${e?.endpoint??"unknown"}`,[i,e?.endpoint]),w=N.useMemo(()=>jq(v),[v]),C=N.useRef(w?.invocationId??(typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`inv_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`)).current,T=N.useMemo(()=>
66{if(w?.values)return w.values;if(l)return Pq(o,e?.inputPreview);const W={};for(const Ce of m)W[Ce.name]=Dv(Ce);for(const Ce of g)W[Ce.name]=Dv(Ce);return W},[e]),[I,k]=N.useState(T),[_,M]=N.useState(!1),[V,G]=N.useState(!1),[L,H]=N.useState(!1),[F,Q]=N.useState(!1),[J,oe]=N.useState(w?.state??"pending"),[xe,ge]=N.useState(w?.resultData??null),[$,le]=N.useState(w?.errorMsg??null),[B,Te]=N.useState(w?.txHash??null),ye=J==="paying"||J==="running"||J==="polling",U=J==="completed"||J==="failed"||J==="rejected";N.useEffect(()=>{Bq(v,{state:J,values:I,resultData:xe,errorMsg:$,txHash:B,invocationId:C})},[v,J,I,xe,$,B,C]);const Qe=W=>W==null?!0:typeof W=="string"?W.trim()==="":Array.isArray(W)?W.length===0:typeof W=="object"?Object.keys(W).length===0:!1,pt=l?[...Object.entries(o?.body??{}),...Object.entries(o?.query??{}),...Object.entries(o?.path??{})].filter(([W,Ce])=>Ce.required&&!Ce.useDefault&&Qe(I[W])).map(([W])=>W):m.filter(W=>Qe(I[W.name])).map(W=>W.name),We=pt.length===0,dt=(W,Ce)=>k(Ee=>({...Ee,[W]:Ce})),ft=(W,Ce,Ee)=>k(be=>({...be,[W]:{...be[W]||{},[Ce]:Ee}})),At=()=>{const W={},Ce={};if(o?.query)for(const Ee of Object.keys(o.query)){const be=I[Ee];be==null||be===""||(W[Ee]=typeof be=="string"?be:String(be))}if(o?.path)for(const Ee of Object.keys(o.path)){const be=I[Ee];be==null||be===""||(W[Ee]=typeof be=="string"?be:String(be))}if(o?.body)for(const Ee of Object.keys(o.body)){const be=I[Ee];if(typeof be=="string")try{Ce[Ee]=JSON.parse(be)}catch{Ce[Ee]=be}else Ce[Ee]=be}return{query:W,body:Ce}},Le=()=>{const W=new Map;for(const Ee of m)W.set(Ee.name,Ee);for(const Ee of g)W.set(Ee.name,Ee);const Ce={};for(const[Ee,be]of Object.entries(I)){const Ve=W.get(Ee),rt=g.some(Se=>Se.name===Ee),ue=typeof be=="string"?be.trim():be;if(!(rt&&(ue===""||ue==null)))if(Ve?.type==="number"||Ve?.type==="integer"){const Se=Number(ue);Ce[Ee]=Number.isFinite(Se)?Se:ue}else Ce[Ee]=ue}return Ce},Ut=async()=>{if(s)try{await yU({id:`pay_${C}`,threadId:s,messageId:i,provider:"x402",amount:Number.isFinite(Number(f))?Number(f):0,currency:String(h),status:"pending"}),await mU({id:`tool_${C}`,threadId:s,messageId:i,type:"paid-approval",name:String(e?.name??e?.endpoint??"paid-api"),status:"pending"})}catch{}},tt=async W=>{if(s)try{W.payment&&await vU(`pay_${C}`,{status:W.payment}),W.tool&&await gU(`tool_${C}`,{status:W.tool})}catch{}},ct=async()=>{if(M(!0),!We||ye||U)return;if(!e?.endpoint){oe("failed"),le("Missing endpoint on approval payload.");return}le(null),ge(null),Te(null),oe("paying"),await Ut(),await tt({payment:"approved",tool:"pending"});const W=String(c).toUpperCase()==="GET"?"GET":"POST";let Ce,Ee;const be=window.setTimeout(()=>{oe(Ve=>Ve==="paying"?"running":Ve),tt({tool:"running"})},900);try{if(l){const Ge=At();Ce=Object.keys(Ge.query).length?Ge.query:void 0,Ee=o?.body?Ge.body:void 0}else{const Ge=Le();W==="GET"?Ce=Ge:Ee=Ge}const Ve=await Tq({url:e.endpoint,method:W,query:Ce,body:Ee,headers:{"X-Tool-Invocation-Id":C}});window.clearTimeout(be);const rt=Iq(Ve.data),ue=rt?Aq(e):null;let Se=Ve.data;if(rt&&ue){oe("polling"),await tt({payment:"complete",tool:"running"});try{Se=await kq({apiId:ue.apiId,resourceId:ue.resourceId,jobId:rt})}catch(Ge){const st=Ge?.response?.data?.message||Ge?.message||"Job polling failed";le(String(st)),oe("failed"),await tt({tool:"error"}),n?.({status:"error",endpoint:e.endpoint,method:W,request:{query:Ce,body:Ee},error:String(st),txHash:Ve.txHash??null,completedAt:Date.now(),invocationId:C});return}}ge(Se),Te(Ve.txHash??null),oe("completed"),await tt({payment:"complete",tool:"complete"}),t?.(I),n?.({status:"success",endpoint:e.endpoint,method:W,request:{query:Ce,body:Ee},data:Se,txHash:Ve.txHash??null,completedAt:Date.now(),invocationId:C})}catch(Ve){window.clearTimeout(be);const rt=Ve?.response?.data?.message||Ve?.shortMessage||Ve?.message||"Payment or request failed";le(String(rt)),oe("failed"),await tt({payment:"error",tool:"error"}),n?.({status:"error",endpoint:e.endpoint,method:W,request:{query:Ce,body:Ee},error:String(rt),completedAt:Date.now(),invocationId:C})}},ht=e?.name??e?.tool??"Scoped tool",kt=e?.resource??e?.resourceId??a.match(/\/proxy\/[^/]+\/([^/?#]+)/)?.[1]??"",Xr=J==="completed"?"PAID":J==="failed"?"FAILED":J==="rejected"?"REJECTED":J==="paying"||J==="running"||J==="polling"?"EXECUTING":"PENDING APPROVAL",ps=J==="completed"?"bg-[#98fe00] text-black":J==="failed"?"bg-red-500/20 text-red-500 border border-red-500/40":J==="rejected"?"bg-muted text-muted-foreground border border-border/60":J==="paying"||J==="running"||J==="polling"?"bg-[#98fe00]/20 text-[#98fe00] border border-[#98fe00]/40":"bg-[#98fe00] text-black";if(J==="completed")return u.jsx(Oq,{txHash:B,resultData:xe});const K=Dq(e?.inputPreview),fe=!We||F;return u.jsxs("div",{className:"mt-2 mb-2 rounded-xl border border-[#98fe00]/50 bg-white p-5 text-xs shadow-sm dark:bg-background",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(Qs,{children:"SCOPED TOOL REQUEST"}),u.jsx("span",{className:`ml-auto rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider ${ps}`,children:Xr})]}),u.jsxs("div",{className:"mt-3",children:[u.jsxs("div",{className:"text-[15px] font-semibold text-foreground",children:[ht,kt&&u.jsxs("span",{className:"text-muted-foreground",children:[" — ",kt]})]}),e?.description&&u.jsx("p",{className:"mt-1 text-[12px] leading-relaxed text-muted-foreground",children:e.description}),u.jsx("p",{className:"mt-2 text-[12px] text-muted-foreground",children:"Route ready. Review the scoped request before execution."})]}),u.jsxs("div",{className:"mt-4 grid grid-cols-1 divide-y divide-border/60 rounded-lg border border-border/60 bg-transparent md:grid-cols-3 md:divide-x md:divide-y-0",children:[u.jsxs("div",{className:"p-4 space-y-2",children:[u.jsx(Qs,{children:"SCOPE"}),K.length>0?u.jsx("div",{className:"grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1 text-[12px]",children:K.map(([W,Ce])=>u.jsxs(N.Fragment,{children:[u.jsx("div",{className:"font-mono text-muted-foreground",children:W}),u.jsx("div",{className:"break-words text-foreground",children:typeof Ce=="object"?JSON.stringify(Ce):String(Ce)})]},W))}):u.jsx("p",{className:"text-[12px] text-muted-foreground",children:"No values extracted. Fill the required fields below."})]}),u.jsxs("div",{className:"p-4 space-y-2",children:[u.jsx(Qs,{children:"PRIVACY"}),u.jsxs("div",{className:"flex items-start gap-2 text-[12px] text-muted-foreground",children:[u.jsx(mc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-[#98fe00]"}),u.jsxs("span",{children:[u.jsx("span",{className:"block font-medium text-foreground",children:"Scoped request only"}),"Only the extracted intent is sent to the tool."]})]}),u.jsxs("div",{className:"flex items-start gap-2 text-[12px] text-muted-foreground",children:[u.jsx(Kh,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-[#98fe00]"}),u.jsx("span",{children:"Your full conversation stays private."})]})]}),u.jsxs("div",{className:"p-4 space-y-1",children:[u.jsx(Qs,{children:"SETTLEMENT"}),u.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Estimated cost"}),u.jsxs("div",{className:"font-mono text-xl font-semibold text-foreground",children:[typeof f=="number"?`$${f}
66`:f," ",u.jsx("span",{className:"text-sm text-muted-foreground",children:h})]}),u.jsx("div",{className:"pt-1 font-mono text-[11px] text-muted-foreground",children:"via x402"})]})]}),u.jsxs("div",{className:"mt-3",children:[u.jsxs("button",{type:"button",onClick:()=>H(W=>!W),className:"inline-flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground hover:text-foreground",children:[u.jsx(l_,{className:"h-3.5 w-3.5"}),L?"Hide full payload":"View full payload",u.jsx(ru,{className:ze("h-3 w-3 transition-transform",L&&"rotate-90")})]}),L&&u.jsx("div",{className:"mt-2 w-full rounded-md border border-border/60 bg-white p-4 dark:bg-background",children:l?u.jsx(Lq,{requestExample:o,values:I}):u.jsx("pre",{className:"max-h-72 overflow-auto font-mono text-[10px] leading-snug text-foreground",children:JSON.stringify({endpoint:a,method:c,values:I,inputPreview:e?.inputPreview},null,2)})})]}),!U&&We&&K.length>0&&u.jsx("button",{type:"button",onClick:()=>Q(W=>!W),className:"mt-3 text-[11px] font-medium text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",children:F?"Hide fields":"Edit values"}),U||!fe?null:l?(()=>{const W=([,Xe])=>!Xe.useDefault,Ce=Object.entries(o?.body??{}).filter(W),Ee=Object.entries(o?.query??{}).filter(W),be=Object.entries(o?.path??{}).filter(W),Ve=e?.inputPreview,rt=Ce.filter(([Xe,bt])=>ta(Xe,bt,Ve)),ue=Ce.filter(([Xe,bt])=>!ta(Xe,bt,Ve)),Se=Ee.filter(([Xe,bt])=>ta(Xe,bt,Ve)),Ge=Ee.filter(([Xe,bt])=>!ta(Xe,bt,Ve)),st=be.filter(([Xe,bt])=>ta(Xe,bt,Ve)),Et=be.filter(([Xe,bt])=>!ta(Xe,bt,Ve)),cr=ue.length+Ge.length+Et.length>0;return u.jsxs("div",{className:"mt-3 space-y-3",children:[rt.length>0&&u.jsx("div",{className:"space-y-2",children:rt.map(([Xe,bt])=>u.jsx(ra,{fieldKey:Xe,meta:bt,value:I[Xe],onChange:sr=>dt(Xe,sr),onNestedChange:ft},`body-${Xe}`))}),Se.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Query"}),Se.map(([Xe,bt])=>u.jsx(ra,{fieldKey:Xe,meta:bt,value:I[Xe],isQuery:!0,onChange:sr=>dt(Xe,sr),onNestedChange:ft},`query-${Xe}`))]}),st.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Path"}),st.map(([Xe,bt])=>u.jsx(ra,{fieldKey:Xe,meta:bt,value:I[Xe],isQuery:!0,onChange:sr=>dt(Xe,sr),onNestedChange:ft},`path-${Xe}`))]}),cr&&u.jsxs("div",{children:[u.jsx("button",{type:"button",onClick:()=>G(Xe=>!Xe),className:"text-[10px] font-medium text-muted-foreground underline-offset-2 hover:underline",children:V?"Hide optional fields":"Show optional fields"}),V&&u.jsxs("div",{className:"mt-2 space-y-3",children:[ue.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Optional body"}),ue.map(([Xe,bt])=>u.jsx(ra,{fieldKey:Xe,meta:bt,value:I[Xe],onChange:sr=>dt(Xe,sr),onNestedChange:ft},`body-${Xe}`))]}),Ge.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Optional query"}),Ge.map(([Xe,bt])=>u.jsx(ra,{fieldKey:Xe,meta:bt,value:I[Xe],isQuery:!0,onChange:sr=>dt(Xe,sr),onNestedChange:ft},`query-${Xe}`))]}),Et.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Optional path"}),Et.map(([Xe,bt])=>u.jsx(ra,{fieldKey:Xe,meta:bt,value:I[Xe],isQuery:!0,onChange:sr=>dt(Xe,sr),onNestedChange:ft},`path-${Xe}`))]})]})]})]})})():u.jsxs(u.Fragment,{children:[m.length>0&&u.jsxs("div",{className:"mt-3 space-y-2",children:[u.jsx("div",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:"Required"}),m.map(W=>u.jsx(Lv,{field:W,required:!0,value:I[W.name]??"",onChange:Ce=>dt(W.name,Ce)},W.name))]}),g.length>0&&u.jsxs("div",{className:"mt-3",children:[u.jsx("button",{type:"button",onClick:()=>G(W=>!W),className:"text-[10px] font-medium text-muted-foreground underline-offset-2 hover:underline",children:V?"Hide optional fields":"Show optional fields"}),V&&u.jsx("div",{className:"mt-2 space-y-2",children:g.map(W=>u.jsx(Lv,{field:W,value:I[W.name]??"",onChange:Ce=>dt(W.name,Ce)}
66,W.name))})]})]}),_&&!We&&!U&&u.jsxs("p",{className:"mt-2 text-[11px] text-red-500",children:["Missing required fields: ",pt.join(", ")]}),J==="failed"&&$&&u.jsxs("div",{className:"mt-3 flex items-start gap-1 rounded border border-red-500/40 bg-red-500/10 p-2 text-[11px] text-red-600",children:[u.jsx(_x,{className:"mt-0.5 h-3 w-3 shrink-0"}),u.jsxs("span",{className:"break-all",children:["Route failed — ",$]})]}),J==="rejected"&&u.jsxs("div",{className:"mt-3 flex items-center gap-1 rounded border border-border/60 bg-muted/40 p-2 text-[11px] text-muted-foreground",children:[u.jsx(c_,{className:"h-3 w-3"}),"Route rejected — no payment was made."]}),!U&&u.jsx("div",{className:"mt-3 flex items-center gap-2",children:u.jsx(yt,{size:"sm",onClick:ct,disabled:!We||ye,className:"group h-10 flex-1 justify-center bg-[#98fe00] px-4 text-black hover:bg-[#98fe00]/90 disabled:opacity-50",children:J==="paying"?u.jsxs("span",{className:"inline-flex items-center gap-2",children:[u.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Settling route…"]}):J==="running"?u.jsxs("span",{className:"inline-flex items-center gap-2",children:[u.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Executing…"]}):J==="polling"?u.jsxs("span",{className:"inline-flex items-center gap-2",children:[u.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Waiting for job…"]}):u.jsxs("span",{className:"inline-flex items-center gap-2 font-normal",children:[u.jsx(mc,{className:"h-4 w-4"}),"Approve route & execute"]})})}),J==="failed"&&u.jsx("div",{className:"mt-3",children:u.jsx(yt,{size:"sm",onClick:()=>{oe("pending"),le(null)},className:"h-7 bg-black text-white hover:bg-[#98fe00] hover:text-black",children:"Retry"})})]})}function Uq({data:e}={}){const t=e?.address,r=e?.connected??!!t;return u.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-muted/30 p-3 text-xs",children:[u.jsxs("div",{className:"flex items-center gap-2 font-medium text-foreground",children:[u.jsx(Ts,{className:"h-3.5 w-3.5 text-[#98fe00]"}),"Wallet status",u.jsx("span",{className:"ml-auto rounded-full bg-background/70 px-2 py-0.5 text-[10px] uppercase text-muted-foreground",children:r?"connected":"disconnected"})]}),u.jsxs("div",{className:"mt-2 space-y-1 text-muted-foreground",children:[t&&u.jsxs("div",{children:["Address: ",u.jsx("span",{className:"font-mono",children:t})]}),e?.network&&u.jsxs("div",{children:["Network: ",e.network]}),e?.balance&&u.jsxs("div",{children:["Balance: ",e.balance]})]})]})}const mf=[{label:"Default",value:"default"}];function Vq(){return"https://x402.slinkylayer.ai/api/v1/chat".replace(/\/chat\/?$/,"").replace(/\/$/,"")}async function $q(e){const t=Vq();if(!t)return{models:mf,defaultModel:"default"};try{const r=localStorage.getItem("web3_jwt"),n=await fetch(`${t}/chat/models`,{headers:{Accept:"application/json","ngrok-skip-browser-warning":"true",...r?{Authorization:`Bearer ${r}`}:{}},signal:e});if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.json(),i=Array.isArray(s?.models)&&s.models.length>0?s.models:mf,a=typeof s?.defaultModel=="string"?s.defaultModel:"default";return{models:i,defaultModel:a}}catch{return{models:mf,defaultModel:"default"}}}let gf=null,no=null;function zq(e){const t=Array.isArray(e?.apis)?e.apis:[],r=[];for(const n of t){const s=String(n?.id??""),i=String(n?.name??s),a=Array.isArray(n?.resources)?n.resources:[];for(const o of a){const l=String(o?.id??"");if(!s||!l)continue;const c=Array.isArray(n?.categories)&&n.categories[0]||o?.category||"Other";r.push({id:`${s}:${l}`,apiId:s,apiName:i,resourceId:l,resourceKey:String(o?.resourceKey??l),label:`${i} — ${o?.description||o?.resourceKey||l}`,description:o?.description??n?.description,category:String(c),method:String(o?.method??n?.method??"POST").toUpperCase(),endpoint:`/proxy/${s}/${l}`,perCallPrice:typeof o?.perCallPrice=="number"?o.perCallPrice:void 0,requestExample:o?.requestExample})}}return r}async function Kq(e){return gf||no||(no=(async()=>{try{const t=await X1(),r=Array.isArray(t)?{apis:t}:t,n=zq(r);return gf=n,n}catch{return[]}finally{no=null}})(),no)}const w2="slinky.chat.raw.v1:",C2="slinky:rawResultAttached";function qq(e,t){if(!(typeof window>"u"||!e))try{localStorage.setItem(w2+e,JSON.stringify(t)),window.dispatchEvent(new CustomEvent(C2,{detail:{messageId:e}}))}catch{}}function yf(e){if(typeof window>"u"||!e)return null;try{const t=localStorage.getItem(w2+e);return t?JSON.parse(t):null}catch{return null}}const Mv=C2,Hq=N.memo(function({text:t}){return u.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert prose-pre:my-2 prose-p:my-2 prose-p:leading-normal prose-headings:my-3",children:u.jsx(cz,{remarkPlugins:[Cq],children:t})})}),Gq=e=>u.jsx(Hq,{text:e.text}),Wq=e=>u.jsx("span",{children:e.text}),Yq=e=>u.jsx(x2,{}),Qq=()=>{const e=wa(s=>s.metadata?.custom?.hidden===!0),t=wa(s=>s.createdAt);if(e)return null;const n=(t?new Date(t):new Date).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return u.jsx(jo.Root,{className:"flex justify-end px-4 py-3",children:u.jsxs("div",{className:"flex max-w-[85%] flex-col items-end",children:[u.jsxs("div",{className:"flex items-start gap-3",children:[u.jsx("div",{className:"rounded-2xl rounded-tr-sm bg-[#f1f3f5] px-4 py-2 text-sm text-[#111827]",children:u.jsx(jo.Content,{components:{Text:Wq}})}),u.jsx("div",{className:"mt-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-border bg-background text-foreground
66/70",children:u.jsx(So,{className:"h-4 w-4",strokeWidth:1.75})})]}),u.jsxs("div",{className:"mr-12 mt-1 flex items-center gap-1 text-[11px] text-muted-foreground",children:[u.jsx("span",{children:n}),u.jsx(jr,{className:"h-3 w-3",strokeWidth:2.5})]})]})})};function Xq(){const e=wa(t=>t.isLast);return u.jsxs(Wd.Root,{hideWhenRunning:!0,className:"mt-1 flex items-center gap-1 text-muted-foreground",children:[u.jsx(Wd.Copy,{asChild:!0,children:u.jsx("button",{className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-white",title:"Copy","aria-label":"Copy",children:u.jsx(zn,{className:"h-3.5 w-3.5"})})}),e&&u.jsx(Wd.Reload,{asChild:!0,children:u.jsx("button",{className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-white",title:"Regenerate","aria-label":"Regenerate",children:u.jsx(gc,{className:"h-3.5 w-3.5"})})})]})}function Jq(){return wa(t=>t.isLast)?u.jsx(Ii.If,{running:!0,children:u.jsx(jo.If,{hasContent:!1,children:u.jsx(sH,{})})}):null}const Fu=N.createContext(null);function Zq({data:e}){const t=N.useContext(Fu),r=wa(i=>i.id),n=hS();N.useEffect(()=>{zc(t,null),Kc(t,null)},[t]);const s=async i=>{if(!t)return;KF(t,i);const a=i.status==="success"?i.data:void 0;try{const o=new Set((n.getState?.().messages??[]).map(l=>l.id));if(n.startRun({parentId:r}),a!=null){let l=!1;const c=()=>{if(l)return;const f=n.getState?.();if(!f||f.isRunning)return;const m=[...f.messages??[]].reverse().find(g=>g.role==="assistant"&&!o.has(g.id));m&&(l=!0,qq(m.id,a),d?.())},d=n.subscribe?.(c);setTimeout(c,0)}}catch{}};return u.jsx(Fq,{data:e,threadId:t??void 0,messageId:r,onCompleted:s,onReject:()=>{}})}function eH({data:e}){const t=N.useContext(Fu),r=e?.toolId??(e?.apiId&&e?.resourceId?`${e.apiId}:${e.resourceId}`:void 0),n=e?.inputPreview;return N.useEffect(()=>{r&&zc(t,r),n!==void 0&&Kc(t,n??null)},[t,r,n]),null}function tH(){const e=wa(n=>n.id),[t,r]=N.useState(()=>e?yf(e):null);return N.useEffect(()=>{if(!e)return;r(yf(e));const n=s=>{s.detail?.messageId===e&&r(yf(e))};return window.addEventListener(Mv,n),()=>window.removeEventListener(Mv,n)},[e]),t}function rH(){const e=tH(),[t,r]=N.useState(!1),[n,s]=N.useState(!1);if(e==null)return null;let i;try{i=typeof e=="string"?e:JSON.stringify(e,null,2)}catch{i=String(e)}const a=async o=>{o.stopPropagation();try{await navigator.clipboard.writeText(i),s(!0),setTimeout(()=>s(!1),1500)}catch{}};return u.jsxs("div",{className:"mt-3 rounded-lg border border-[#98fe00]/30 bg-[#98fe00]/5",children:[u.jsxs("div",{className:"flex w-full items-center gap-2 px-3 py-2",children:[u.jsxs("button",{type:"button",onClick:()=>r(o=>!o),className:"flex flex-1 items-center gap-2 text-left","aria-expanded":t,children:[u.jsx(ri,{className:ze("h-3.5 w-3.5 text-muted-foreground transition-transform",t?"":"-rotate-90")}),u.jsx(Qs,{children:"EVIDENCE PACKET"})]}),u.jsx("span",{className:"rounded-full border border-[#98fe00]/40 bg-[#98fe00]/10 px-2 py-0.5 text-[9px] font-medium text-foreground",children:"json"}),u.jsx("button",{type:"button",onClick:a,className:"inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-white",title:n?"Copied":"Copy evidence packet","aria-label":"Copy evidence packet",children:n?u.jsx(jr,{className:"h-3.5 w-3.5"}):u.jsx(zn,{className:"h-3.5 w-3.5"})})]}),t&&u.jsx("pre",{className:"max-h-80 overflow-auto border-t border-border/60 bg-background/60 p-3 font-mono text-[11px] leading-snug text-foreground",children:i})]})}const nH=()=>u.jsxs(jo.Root,{className:"flex px-4 py-3",children:[u.jsx("div",{className:"mr-3 mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-[#98fe00]/20 text-foreground",children:u.jsx(nu,{className:"h-3.5 w-3.5"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx(jo.Content,{components:{Text:Gq,tools:{Fallback:Yq},data:{by_name:{"paid-approval":e=>u.jsx(Zq,{data:e.data}),"tool-input-needed":e=>u.jsx(eH,{data:e.data}),"tool-call":e=>u.jsx(x2,{data:e.data}),"wallet-status":e=>u.jsx(Uq,{data:e.data})},Fallback:e=>u.jsxs("div",{className:"mt-2 rounded border border-border/60 bg-muted/30 p-2 text-[11px] text-muted-foreground",children:[u.jsxs("div",{className:"font-medium text-foreground",children:["data-",e.name]}),u.jsx("pre",{className:"mt-1 overflow-x-auto",children:JSON.stringify(e.data,null,2)})]})}}}),u.jsx(rH,{}),u.jsx(Jq,{}),u.jsx(Xq,{})]})]});function sH(){return u.jsxs("div",{className:"flex items-center gap-1 py-1 text-muted-foreground",children:[u.jsx("span",{className:"h-1.5 w-1.5 animate-bounce rounded-full bg-current [animation-delay:-0.3s]"}),u.jsx("span",{className:"h-1.5 w-1.5 animate-bounce rounded-full bg-current [animation-delay:-0.15s]"}),u.jsx("span",{className:"h-1.5 w-1.5 animate-bounce rounded-full bg-current"})]})}function vf({icon:e,label:t}){return u.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-border/70 bg-background px-3 py-1.5 text-xs text-muted-foreground",children:[u.jsx(e,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:t})]})}function iH(){return u.jsxs("div",{className:"mx-auto flex max-w-2xl flex-col items-center justify-center px-6 py-16 text-center",children:[u.jsxs("div",{className:"relative mb-5",children:[u.jsx(Tf,{className:"absolute -left-6 -top-1 h-4 w-4 text-[#98fe00]"}),u.jsx(Tf,{className:"absolute -right-5 top-2 h-3 w-3 text-[#98fe00]"}),u.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-full bg-[#98fe00]/20",children:u.jsx(nu,{className:"h-7 w-7"})})]}),u.jsx("h2",{className:"text-2xl font-semibold",children:"Welcome to SlinkyLayer"}),u.jsx("p",{className:"mt-2 text-sm text-foreground",children:"Ask freely. Build privately. Pay only when you use it."}),u.jsx("p",{className:"mt-3 max-w-md text-sm text-muted-foreground",children:"Your conversations stay private. Chat with AI or build AI apps without accounts, API Keys or identity-based billing right away."}),u.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-2",children:[u.jsx(vf,{icon:mc,label:"Pay-Per-Call Compute"}),u.jsx(vf,{icon:d_,label:"Incognito Access"}),u.jsx(vf,{icon:Kh,label:"Zero Data Retention"})]})]})}function aH(){return u.jsxs("div",{className:"flex items-center gap-2 border-b border-border/60 bg-background px-4 py-2 text-xs text-muted-foreground",children:[u.jsx(Kh,{className:"h-3.5 w-3.5 shrink-0"}),u.jsxs("span",{children:["Anonymized by Slinky. Zero data retention for this chat. No AI training."," ",u.jsx("span",{className:"cursor-pointer underline hover:text-foreground",children:"Learn more"})]})]})}function oH(){const[e,t]=N.useState([{label:"Default",value:"default"}]),[r,n]=N.useState(()=>fE()),[s,i]=N.useState([]),[a,o]=N.useState(()=>hE()),l=hS(),c=N.useContext(Fu),[d,f]=N.useState(!1);N.useEffect(()=>{const C=()=>f(!0),T=()=>f(!1);return window.addEventListener(ji,C),window.addEventListener(xh,T),()=>{window.removeEventListener(ji,C),window.removeEventListener(xh,T)}},[]),N.useEffect(()=>{const C=new AbortController;return $q(C.signal).then(({models:T})=>{t(T)}),Kq(C.signal).then(T=>{i(T)}),()=>C.abort()},[]);const h=C=>{n(C),SU(C)},m=C=>{if(o(C),Ch(C),C==="auto"||C==="none"||!C.includes(":")){c&&(zc(c,null),Kc(c,null));return}c&&(zc(c,C),Kc(c,null),HF(c,C));try{l.append({role:"user",content:[{type:"text",text:""}],metadata:{custom:{hidden:!0,toolSetup:!0,toolId:C}}})}catch{}},g=e.find(C=>C.value===r)?.label??"Default",v=(()=>
66{if(a==="auto")return"Auto";if(a==="none")return"No tools";const C=s.find(I=>I.id===a);return C?C.apiName.length>24?C.apiName.slice(0,24)+"…":C.apiName:"Auto"})(),w=s.reduce((C,T)=>{const I=T.category||"Other";return(C[I]||(C[I]=[])).push(T),C},{}),b=Object.keys(w).sort();return d?u.jsx("div",{className:"border-t border-border/60 bg-background/80 p-3",children:u.jsx("div",{className:"rounded-xl border border-border/70 bg-background p-4 shadow-[0_1px_2px_rgba(16,24,40,0.04)]",children:u.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[u.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted/30",children:u.jsx(mc,{className:"h-4 w-4 text-muted-foreground"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[#98fe00]"}),u.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-foreground",children:"Bandwidth depleted"})]}),u.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:"Chat resumes when daily bandwidth refreshes at 00:00 UTC — or claim an eligible reward to top up now."})]}),u.jsx(yt,{asChild:!0,size:"sm",className:"h-8 shrink-0 bg-black text-white hover:bg-[#98fe00] hover:text-black",children:u.jsx(oo,{to:"/account",children:"Check Credits"})})]})})}):u.jsx(ql.Root,{className:"border-t border-border/60 bg-background/80 p-3",children:u.jsxs("div",{className:"rounded-xl border border-border/70 bg-background p-2 shadow-sm",children:[u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx(ql.Input,{asChild:!0,submitOnEnter:!0,autoFocus:!0,placeholder:"Message the assistant…",children:u.jsx("textarea",{rows:1,className:ze("max-h-40 min-h-[40px] flex-1 resize-none rounded-md bg-transparent px-2 py-2 text-sm outline-none")})}),u.jsx("button",{type:"button",title:"Attachments (coming soon)",className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground","aria-label":"Attach",children:u.jsx(f_,{className:"h-4 w-4"})}
66),u.jsx(Ii.If,{running:!1,children:u.jsx(ql.Send,{asChild:!0,children:u.jsx(yt,{size:"icon",className:"h-9 w-9 shrink-0 rounded-md bg-black text-white hover:bg-[#98fe00] hover:text-black","aria-label":"Send",children:u.jsx(wx,{className:"h-4 w-4"})})})}),u.jsx(Ii.If,{running:!0,children:u.jsx(ql.Cancel,{asChild:!0,children:u.jsxs(yt,{size:"icon",className:"relative h-9 w-9 shrink-0 rounded-md bg-black text-white hover:bg-[#98fe00] hover:text-black","aria-label":"Stop",title:"Stop generating",children:[u.jsx("span",{className:"pointer-events-none absolute inset-0 rounded-md ring-2 ring-[#98fe00]/40 animate-pulse"}),u.jsx(h_,{className:"h-2.5 w-2.5",fill:"currentColor"})]})})})]}),u.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 px-1",children:[u.jsxs(Pf,{children:[u.jsx(jf,{asChild:!0,children:u.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background px-3 py-1 text-xs text-foreground hover:bg-accent hover:text-accent-foreground",children:[u.jsx(Cx,{className:"h-3.5 w-3.5"}),"Model: ",g,u.jsx(ri,{className:"h-3 w-3 opacity-60"})]})}),u.jsx(yc,{align:"start",className:"z-[100] min-w-[200px] bg-background shadow-lg",children:e.map(C=>u.jsxs(zs,{onSelect:()=>h(C.value),className:"flex items-center justify-between gap-2 text-xs",children:[C.label,r===C.value&&u.jsx(jr,{className:"h-3.5 w-3.5"})]},C.value))})]}),u.jsxs(Pf,{children:[u.jsx(jf,{asChild:!0,children:u.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background px-3 py-1 text-xs text-foreground hover:bg-accent hover:text-accent-foreground",children:[u.jsx(Ax,{className:"h-3.5 w-3.5"}),"Tools: ",v,u.jsx(ri,{className:"h-3 w-3 opacity-60"})]})}),u.jsxs(yc,{align:"start",className:"z-[100] max-h-[60vh] min-w-[280px] overflow-y-auto bg-background shadow-lg",children:[u.jsxs(zs,{onSelect:()=>m("auto"),className:"flex items-center justify-between gap-2 text-xs",children:["Auto",a==="auto"&&u.jsx(jr,{className:"h-3.5 w-3.5"})]}),u.jsxs(zs,{onSelect:()=>m("none"),className:"flex items-center justify-between gap-2 text-xs",children:["No tools",a==="none"&&u.jsx(jr,{className:"h-3.5 w-3.5"})]}),b.length>0&&u.jsx(vb,{}),b.map(C=>u.jsxs("div",{children:[u.jsx("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:C}),w[C].map(T=>u.jsxs(zs,{onSelect:()=>m(T.id),className:"flex items-start justify-between gap-2 text-xs",children:[u.jsxs("span",{className:"flex min-w-0 flex-col",children:[u.jsx("span",{className:"truncate font-medium",children:T.apiName}),T.description&&u.jsx("span",{className:"truncate text-[10px] text-muted-foreground",children:T.description})]}),a===T.id&&u.jsx(jr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"})]},T.id))]},C))]})]})]})]})})}function lH({threadId:e}={}){return u.jsx(Fu.Provider,{value:e??null,children:u.jsxs(Ii.Root,{className:"flex h-full min-h-0 flex-col",children:[u.jsx(aH,{}),u.jsxs(Ii.Viewport,{className:"flex-1 overflow-y-auto",children:[u.jsx(Ii.Empty,{children:u.jsx(iH,{})}),u.jsx(Ii.Messages,{components:{UserMessage:Qq,AssistantMessage:nH}})]}),u.jsx(oH,{})]})})}function cH({walletAddress:e}){const t=!!e;return u.jsxs("div",{className:ze("flex items-center gap-2 rounded-full border px-3 py-1 text-xs",t?"border-[#98fe00]/40 bg-[#98fe00]/10 text-foreground":"border-border/60 bg-muted/10 text-muted-foreground"),title:"Wallet / payment status (placeholder)",children:[u.jsx("span",{className:ze("h-1.5 w-1.5 rounded-full",t?"bg-[#98fe00]":"bg-muted-foreground/50")}),u.jsx(Ts,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"font-medium",children:t?`${e.slice(0,6)}…${e.slice(-4)}`:"Wallet not connected"}),u.jsx("span",{className:"text-muted-foreground/70",children:"·"})]})}new Date(Date.now()+1e3*60*60*9).toISOString();new Date(Date.now()-1e3*60*60*26).toISOString(),new Date(Date.now()-1e3*60*60*30).toISOString(),new Date(Date.now()-1e3*60*60*72).toISOString();const uH={NFT_NOT_OWNED:"This NFT is not held by your connected wallet.",NFT_ALREADY_CLAIMED:"This NFT reward has already been claimed.",CAMPAIGN_NOT_CLAIMABLE:"This campaign is no longer claimable."};function Uu(){return"https://x402.slinkylayer.ai"}function Vu(){const e=localStorage.getItem("web3_jwt");return{"Content-Type":"application/json","ngrok-skip-browser-warning":"1",...e?{Authorization:`Bearer ${e}`}:{}}}async function S2(){const e=await fetch(`${Uu()}/api/v1/bandwidth`,{method:"GET",headers:Vu()});if(!e.ok){const t=await e.text().catch(()=>"Unknown error");throw new Error(`Failed to load bandwidth: ${e.status} ${t}`)}return e.json()}function dH(e){const t=String(e?.source||""),r=String(e?.type||"");if(t==="DAILY_WALLET"){if(r==="CREDIT")return"Daily credits added";if(r==="DEBIT")return"Daily credits used";if(r==="EXPIRED")return"Daily credits expired"}if(t==="TOKEN_HOLDING"){if(r==="CREDIT")return"Token holding credits added";if(r==="DEBIT")return"Token holding credits used";if(r==="EXPIRED")return"Token holding credits expired"}if(t==="NFT_CAMPAIGN"){if(r==="CREDIT")return"NFT reward claimed";if(r==="DEBIT")return"NFT reward credits used";if(r==="EXPIRED")return"NFT reward credits expired"}return"Bandwidth activity"}async function E2(){const e=await fetch(`${Uu()}/api/v1/bandwidth/history`,{method:"GET",headers:Vu()});if(!e.ok)throw new Error(`Failed to load bandwidth history: ${e.status}`);const t=await e.json().catch(()=>null);return Array.isArray(t)?t:t?.history||[]}async function fH(){const e=await fetch(`${Uu()}/api/v1/bandwidth/campaigns`,{method:"GET",headers:Vu()});if(!e.ok)throw new Error(`Failed to load campaigns: ${e.status}`);const t=await e.json().catch(()=>null);return Array.isArray(t)?t:t?.campaigns||[]}async function hH(e,t){const r=await fetch(`${Uu()}/api/v1/bandwidth/campaigns/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Vu(),body:JSON.stringify({tokenId:t})});if(!r.ok){const n=await r.json().catch(()=>null),s=n?.code||n?.error||n?.message,i=new Error(uH[s]||"Could not claim this reward. Please try again.");throw i.code=s,i}}function T2(e,t){return!e||!t?"":`${Number(e)}
66:${String(t).toLowerCase()}`}function pH(e){const t=new Set;for(const r of e||[]){if(r?.source!=="NFT_CAMPAIGN"||r?.type!=="CREDIT")continue;const n=r.metadata||{},s=T2(n.chainId??n.chain_id,n.contractAddress??n.contract_address);s&&t.add(s);const i=n.campaignId??n.campaign_id;i&&t.add(String(i))}return t}function mH(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function xn(e){const t=typeof e=="string"?Number(e):e;return Number.isFinite(t)?t.toLocaleString(void 0,{maximumFractionDigits:0}):"0"}function gH(e){if(!e)return"—";const t=new Date(e).getTime()-Date.now();if(t<=0)return"now";const r=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return r>0?`${r}h ${n}m`:`${n}m`}function yH(e){const t=Date.now()-new Date(e).getTime(),r=Math.floor(t/6e4);if(r<1)return"Just now";if(r<60)return`${r}m ago`;const n=Math.floor(r/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`}function vH(e){const t=!!e,[r,n]=N.useState(null),[s,i]=N.useState(t),[a,o]=N.useState(!1),l=N.useCallback(async()=>{if(t){i(!0);try{const c=await S2();n(c.balance??0),o(!1)}catch{o(!0)}finally{i(!1)}}},[t]);return N.useEffect(()=>{if(!t){n(null),i(!1);return}l()},[t,l]),N.useEffect(()=>{if(!t)return;const c=()=>{l()};return window.addEventListener(Bo,c),window.addEventListener(ji,c),()=>{window.removeEventListener(Bo,c),window.removeEventListener(ji,c)}},[t,l]),{balance:r,loading:s,available:t&&!a}}const xH=({walletAddress:e,className:t})=>{const{balance:r,loading:n,available:s}=vH(e);if(!s)return null;const i=!n&&(r??0)<=0,a=n||r===null?"—":xn(r);return u.jsxs(oo,{to:"/account",title:"View your credits",className:ze("inline-flex h-8 items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors",i?"border-border/70 bg-muted/30 text-foreground hover:bg-[#98fe00]/12":"border-border/70 bg-background text-foreground hover:bg-[#98fe00]/12",t),children:[i?u.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[#98fe00]"}):u.jsx(Ix,{className:"h-3.5 w-3.5 shrink-0 text-[#4ba300]"}),u.jsx("span",{className:"tabular-nums",children:a}),u.jsx("span",{className:"hidden sm:inline text-muted-foreground",children:"credits"})]})};function bH({threadId:e,initialMessages:t,onMessagesChange:r}){const n=N.useMemo(()=>rU({threadId:e,getMetadata:()=>{const a=hE(),o=TU(e),l=IU(e),c={selectedModel:fE(),localOnly:AU()};return a&&a!=="auto"&&a!=="none"&&a.includes(":")?(c.selectedToolMode="specific",c.selectedToolId=a):a==="none"?c.selectedToolMode="none":o?(c.selectedToolMode="specific",c.selectedToolId=o):c.selectedToolMode="auto",o&&(c.pendingToolId=o),l&&(c.pendingToolInputs=l),c}}),[e]),s=V8(n,{initialMessages:t}),i=N.useRef(r);return i.current=r,N.useEffect(()=>s.thread.subscribe(()=>{const o=s.thread.getState();i.current(o.messages)}),[s]),u.jsx(Y8,{runtime:s,children:u.jsx(lH,{threadId:e})})}function Ov({walletAddress:e}){const t=e?e.toLowerCase():void 0,[r,n]=N.useState(!1),[s,i]=N.useState([]),[a,o]=N.useState(null),[l,c]=N.useState([]),d=N.useCallback(b=>{o(b),CU(t,b)},[t]);N.useEffect(()=>{let b=!1;return(async()=>{if(n(!1),Ch("auto"),!t){if(b)return;i([]),o(null),c([]),n(!0);return}await lU(),await cU(t);let C=await My(t);if(C.length===0){const _=await Wl(t);_&&(C=[_])}if(b)return;const T=wU(t),I=T&&C.find(_=>_.id===T)||C[0],k=I?await fc(I.id):[];b||(i(C),d(I?I.id:null),c(k),n(!0))})(),()=>{b=!0}},[t,d]);const f=N.useCallback(async b=>{if(b===a)return;const C=await fc(b);d(b),c(C)},[a,d]),h=N.useCallback(async()=>{if(!t)return;const b=await Wl(t);b&&(Ch("auto"),i(C=>[b,...C]),d(b.id),c([]))},[d,t]),m=N.useCallback(async b=>{if(!t)return;await uU(b);let C=await My(t);if(C.length===0){const T=await Wl(t);T&&(C=[T])}if(i(C),a===b){const T=C[0],I=T?await fc(T.id):[];d(T?T.id:null),c(I)}},[a,d,t]),g=N.useCallback(async()=>{if(!t||typeof window<"u"&&!window.confirm("Delete all chats? This cannot be undone."))return;await dU();const b=await Wl(t);i(b?[b]:[]),d(b?b.id:null),c([])},[d,t]),v=N.useCallback(async()=>{if(!a)return;const b=await hU(a),C=new Blob([JSON.stringify(b,null,2)],{type:"application/json"}),T=URL.createObjectURL(C),I=document.createElement("a");I.href=T;const k=(b.thread?.title||"chat").replace(/[^a-z0-9-_]+/gi,"_").slice(0,40);I.download=`${k}_${a}.json`,document.body.appendChild(I),I.click(),I.remove(),URL.revokeObjectURL(T)}
66,[a]),w=N.useCallback(async b=>{a&&(await fU(a,b),i(C=>{const T=C.findIndex(V=>V.id===a);if(T===-1)return C;const I=C[T];let k=I.title;if(k==="New chat"||!k){const V=b.find(G=>G.role==="user");if(V){const G=Array.isArray(V.content)?V.content.map(L=>L.type==="text"?L.text:"").join(" "):String(V.content??"");G&&(k=G.length>40?G.slice(0,40)+"…":G)}}const _={...I,title:k,updatedAt:Date.now()};_.title!==I.title?Oy(a,{title:_.title,updatedAt:_.updatedAt}):Oy(a,{updatedAt:_.updatedAt});const M=[...C];return M[T]=_,M.sort((V,G)=>G.updatedAt-V.updatedAt),M}))},[a]);return u.jsxs("div",{className:"mx-auto flex h-[calc(100vh-8rem)] w-full max-w-6xl overflow-hidden rounded-xl border border-border/60 bg-background shadow-sm",children:[u.jsx("div",{className:"hidden w-64 shrink-0 md:block",children:u.jsx(NU,{threads:s,activeId:a,onSelect:f,onCreate:h,onDelete:m,onClearAll:g})}),u.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[u.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/60 px-4 py-2",children:[u.jsx("div",{className:"min-w-0",children:u.jsx("div",{className:"truncate text-sm font-semibold",children:s.find(b=>b.id===a)?.title??"Chat"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs(yt,{variant:"outline",size:"sm",onClick:v,disabled:!a,className:"h-8 gap-1",children:[u.jsx(p_,{className:"h-3.5 w-3.5"}),"Export"]}),u.jsxs(yt,{variant:"outline",size:"sm",onClick:()=>a&&m(a),disabled:!a,className:"h-8 gap-1",children:[u.jsx(m_,{className:"h-3.5 w-3.5"}),"Delete"]}),u.jsx(xH,{walletAddress:e}),u.jsx(cH,{walletAddress:e})]})]}),u.jsxs("div",{className:"min-h-0 flex-1",children:[r&&!t&&u.jsx("div",{className:"flex h-full items-center justify-center p-8",children:u.jsxs("div",{className:"max-w-sm rounded-xl border border-border/60 bg-muted/10 p-8 text-center",children:[u.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-[#98fe00]/15",children:u.jsx(Ts,{className:"h-6 w-6 text-foreground"})}),u.jsx("div",{className:"mb-2 text-base font-semibold",children:"Connect your wallet to start chatting"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect a wallet to view your conversations or start a new one."})]})}),r&&t&&a&&u.jsx(bH,{threadId:a,initialMessages:l,onMessagesChange:w},a)]})]})]})}const _2={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_API_SOCKET_URL:"https://dev-api2.slinkylayer.ai",VITE_API_URL:"https://x402.slinkylayer.ai",VITE_APP_ENV:"dev",VITE_BANDWIDTH_ENABLED:"true",VITE_CHAT_API_URL:"https://x402.slinkylayer.ai/api/v1/chat",VITE_MAX_MODELS:"3",VITE_PUBLIC_ONCHAINKIT_API_KEY:"goKJeXpK8NvjpkC9JfxPJtzkllfCUPLD",VITE_PUBLIC_PRODUCT_ID:"ffc8da99-0736-4769-a348-349679bdc7b3",VITE_RPC_137:"https://polygon-mainnet.g.alchemy.com/v2/alch_uoKWuHZmAVIQ0qof_Ulbl",VITE_RPC_56:"https://bnb-mainnet.g.alchemy.com/v2/alch_uoKWuHZmAVIQ0qof_Ulbl",VITE_RPC_8453:"https://base-mainnet.g.alchemy.com/v2/alch_uoKWuHZmAVIQ0qof_Ulbl",VITE_SLINKY_CHAIN_ID:"8453",VITE_SLINKY_TOKEN_ADDRESS:"0xBB3D6C47379Abb4713Acffffa27483B726ee67dB",VITE_SLINKY_TOKEN_DECIMALS:"18",VITE_SLINKY_TOKEN_SYMBOL:"SLINKY",VITE_SUPABASE_PUBLISHABLE_KEY:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJjemdmdWdpcGJqcnJ4c21zYXFhIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQyODYwNTcsImV4cCI6MjA1OTg2MjA1N30.pELZO0foUj96Cto3cD3JontGcDZAxKibIpvqM7LyE6A",VITE_SUPABASE_URL:"https://rczgfugipbjrrxsmsaqa.supabase.co"},wH={1:"https://eth.llamarpc.com",56:"https://bsc-dataseed.binance.org",137:"https://polygon-rpc.com",8453:"https://mainnet.base.org",42161:"https://arb1.arbitrum.io/rpc",10:"https://mainnet.optimism.io"};function I2(e){if(!e)return;const r=_2[`VITE_RPC_${e}`];return r&&r.trim()?r.trim():wH[e]}const CH={1:"https://etherscan.io",56:"https://bscscan.com",137:"https://polygonscan.com",8453:"https://basescan.org",42161:"https://arbiscan.io",10:"https://optimistic.etherscan.io"};function SH(e,t){if(!e||!t)return;const n=_2[`VITE_EXPLORER_${e}`],s=n&&n.trim()||CH[e];if(s)return`${s.replace(/\/$/,"")}/address/${t}`}const EH=["function balanceOf(address) view returns (uint256)","function decimals() view returns (uint8)","function symbol() view returns (string)"];function TH(e,t){const r=t?.enabled&&t?.tokenAddress||"",n=t?.chainId,s=t?.symbol||"TOKEN",i=!!r,[a,o]=N.useState({configured:i,loading:!1,symbol:s}),l=N.useCallback(async()=>
66{if(!i||!e){o({configured:i,loading:!1,error:void 0,balance:0,symbol:s});return}const c=n?I2(n):void 0,d=window.ethereum;if(!c&&!d){o({configured:i,loading:!1,error:void 0,balance:0,symbol:s});return}o({configured:i,loading:!0,error:void 0,balance:0,symbol:s});try{const f=c?new Hv(c):new Yc(d),h=new Gv(r,EH,f),[m,g,v]=await Promise.all([h.balanceOf(e),h.decimals().catch(()=>18),h.symbol().catch(()=>s)]);o({configured:!0,loading:!1,balance:Number(oT(m,Number(g))),symbol:String(v||s)})}catch{o({configured:i,loading:!1,error:void 0,balance:0,symbol:s})}},[i,e,r,n,s]);return N.useEffect(()=>{l()},[l]),{...a,refresh:l}}const _H=["function balanceOf(address) view returns (uint256)","function tokenOfOwnerByIndex(address,uint256) view returns (uint256)"];function IH(e,t,r){const[n,s]=N.useState({status:"idle"});return N.useEffect(()=>{let i=!1;const a=I2(t);if(!e||!r||!a){s({status:"unknown"});return}return s({status:"checking"}),(async()=>{try{const o=new Hv(a),l=new Gv(r,_H,o),c=await l.balanceOf(e);if(i)return;if(!c||c.isZero?.()||Number(c.toString())===0){s({status:"none",owns:!1});return}try{const d=await l.tokenOfOwnerByIndex(e,0);if(i)return;s({status:"found",owns:!0,tokenId:d.toString()})}catch{i||s({status:"unknown",owns:!0})}}catch{i||s({status:"unknown"})}})(),()=>{i=!0}},[e,t,r]),n}function Fv(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function AH({children:e}){return u.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.08em] text-foreground",children:[u.jsx("span",{className:"h-3.5 w-[3px] rounded-full bg-[#98fe00]"}),e]})}function xf({children:e,tone:t="neutral"}){const r={neutral:"border-border/60 bg-white text-foreground",reward:"border-[#98fe00] bg-[#98fe00]/15 text-[#3c6a00]",muted:"border-border/40 bg-muted/30 text-muted-foreground"};return u.jsx("span",{className:ze("inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium",r[t]),children:e})}function kH({status:e}){const r={claimable:{label:"Claimable",className:"border-[#98fe00]/60 bg-[#98fe00]/15 text-[#3c6a00]"},not_eligible:{label:"Not eligible",className:"border-amber-200 bg-amber-50 text-amber-600"},claimed:{label:"Claimed",className:"border-[#98fe00]/60 bg-[#98fe00]/15 text-[#3c6a00]"},expired:{label:"Expired",className:"border-border/50 bg-muted/30 text-muted-foreground"},checking:{label:"Checking…",className:"border-border/50 bg-muted/30 text-muted-foreground"}}[e];return u.jsx("span",{className:ze("shrink-0 inline-flex items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.06em]",r.className),children:r.label})}function NH({campaign:e,walletAddress:t,claimedKeys:r,onClaimed:n,reload:s}){const i=e,a=String(i.id),o=i.rewardPoints??i.rewardAmount??i.reward??i.amount??0,l=i.claimableUntil??i.claimBy??i.claim_by??i.expires_at,c=i.pointsValidityDays??i.creditsValidDays??i.credits_valid_days??i.validityDays,d=Number(i.chainId??i.chain_id)||void 0,f=i.contractAddress??i.contract_address,h=SH(d,f),m=IH(t,d,f),[g,v]=N.useState(!1),[w,b]=N.useState(""),[C,T]=N.useState(!1),[I,k]=N.useState(""),[_,M]=N.useState(!1),V=r.has(T2(d,f))||r.has(a),G=_||!!(i.claimed??i.isClaimed??i.claimedAt??i.claimed_at)||V,L=m.status==="found"?m.tokenId:void 0,H=w.trim(),F=H||L,Q=l?new Date(l).getTime()<Date.now():!1,J=G?"claimed":Q?"expired":m.status==="checking"?"checking":m.status==="found"?"claimable":m.status==="none"?"not_eligible":"claimable",oe=async()=>{if(!F){k("Enter the NFT token ID you hold.");return}T(!0),k("");try{await hH(a,F),M(!0),await n(),await s()}catch(xe){xe?.code==="NFT_ALREADY_CLAIMED"?M(!0):k(xe?.message||"Claim failed.")}finally{T(!1)}};return u.jsxs("div",{className:"rounded-lg border border-border/60 bg-white/70 p-3.5",children:[u.jsxs("div",{className:"flex items-start justify-between gap-3",children:[u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:"truncate text-sm font-semibold text-foreground",children:i.name||i.title||"Campaign"}),(i.description||f)&&u.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[i.description&&u.jsx("span",{className:"truncate",children:i.description}),i.description&&f&&u.jsx("span",{className:"text-border",children:"·"}),f&&(h?u.jsxs("a",{href:h,target:"_blank",rel:"noopener noreferrer",title:f,className:"inline-flex shrink-0 items-center gap-0.5 font-mono text-[11px] text-muted-foreground transition-colors hover:text-foreground hover:underline",children:[Fv(f),u.jsx(kx,{className:"h-2.5 w-2.5"})]}):u.jsx("span",{title:f,className:"shrink-0 font-mono text-[11px] text-muted-foreground",children:Fv(f)}))]})]}),u.jsx(kH,{status:J})]}),u.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-1.5",children:[u.jsxs(xf,{tone:"reward",children:["+",xn(o)," credits"]}),u.jsxs(xf,{tone:"neutral",children:["Claim by ",mH(l)]}),u.jsx(xf,{tone:"neutral",children:c?`Valid ${c} days`:"—"})]}),G?u.jsxs("div",{className:"mt-3 rounded-lg border border-[#98fe00]/50 bg-[#98fe00]/10 px-3 py-2.5 text-sm",children:[u.jsxs("div",{className:"flex items-center gap-2 font-semibold text-[#3c6a00]",children:[u.jsx(jr,{className:"h-4 w-4"}),"Claimed · +",xn(o)," credits"]}),c?u.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:["Credits valid for ",c," days from claim date."]}):null]}):Q?u.jsx("div",{className:"mt-3 border-t border-border/40 pt-2.5 text-xs text-muted-foreground",children:"This campaign has expired and can no longer be claimed."}):m.status==="checking"?u.jsx("div",{className:"mt-3 border-t border-border/40 pt-2.5",children:u.jsxs("div",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[u.jsx(ls,{className:"h-3 w-3 animate-spin"}),"Checking wallet for eligible NFT…"]})}):L?u.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 border-t border-border/40 pt-2.5",children:[u.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-[#98fe00]/40 bg-[#98fe00]/10 px-2.5 py-1 text-xs font-medium text-[#3c6a00]",children:["NFT #",L," detected"]}),u.jsx(yt,{onClick:oe,disabled:C,className:"h-9 bg-black text-white hover:bg-[#98fe00] hover:text-black",children:C?u.jsxs(u.Fragment,{children:[u.jsx(ls,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Claiming"]}):"Claim"}),I&&u.jsx("p",{className:"w-full text-xs text-destructive",children:I})]}):u.jsxs("div",{className:"mt-3 border-t border-border/40 pt-2.5",children:[m.status==="none"&&u.jsx("p",{className:"text-xs text-amber-600",children:"Couldn’t detect an eligible NFT."}),g?u.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[u.jsx(rn,{value:w,onChange:xe=>b(xe.target.value),placeholder:"NFT token ID (e.g. 123)",className:"h-9 w-full sm:w-[220px]",disabled:C}),u.jsx(yt,{onClick:oe,disabled:C||!H,className:"h-9 bg-black text-white hover:bg-[#98fe00] hover:text-black",children:C?u.jsxs(u.Fragment,{children:[u.jsx(ls,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Claiming"]}):"Claim"})]}):u.jsx("button",{type:"button",onClick:()=>v(!0),className:"text-xs font-medium text-muted-foreground underline-offset-2 hover:underline",children:"Enter token ID manually"}),I&&u.jsx("p",{className:"mt-2 text-xs text-destructive",children:I})]})]})}const RH=({walletAddress:e,onClaimed:t,className:r})=>{const[n,s]=N.useState([]),[i,a]=N.useState(new Set),[o,l]=N.useState(vh),c=N.useCallback(async()=>
66{l(!0);const[d,f]=await Promise.allSettled([fH(),E2()]);s(d.status==="fulfilled"?d.value:[]),a(f.status==="fulfilled"?pH(f.value):new Set),l(!1)},[]);return N.useEffect(()=>{e&&c()},[e,c]),u.jsxs("div",{className:ze("rounded-xl border border-border/60 bg-white p-5 shadow-[0_1px_2px_rgba(16,24,40,0.04)]",r),children:[u.jsxs("div",{className:"flex items-start justify-between",children:[u.jsx(AH,{children:"REWARD CAMPAIGNS"}),u.jsx(Nx,{className:"h-4 w-4 text-muted-foreground"})]}),o?u.jsx("div",{className:"mt-5 text-sm text-muted-foreground",children:"Loading campaigns…"}):n.length===0?u.jsx("div",{className:"mt-5 text-sm text-muted-foreground",children:"No reward campaigns available"}):u.jsx("div",{className:"mt-3 flex flex-col gap-2.5",children:n.map(d=>u.jsx(NH,{campaign:d,walletAddress:e,claimedKeys:i,onClaimed:t,reload:c},String(d.id)))})]})};function bf({children:e}){return u.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.08em] text-foreground",children:[u.jsx("span",{className:"h-3.5 w-[3px] rounded-full bg-[#98fe00]"}),e]})}function wf({className:e,children:t}){return u.jsx("div",{className:ze("rounded-xl border border-border/70 bg-white p-6 shadow-[0_1px_2px_rgba(16,24,40,0.04)]",e),children:t})}const PH=({walletAddress:e,currentNetwork:t})=>{const[r,n]=N.useState(!1),[s,i]=N.useState(null),[a,o]=N.useState(vh),[l,c]=N.useState([]),[d,f]=N.useState(vh),[h,m]=N.useState(!1),g=TH(e,s?.tokenHolding),v=N.useCallback(async()=>{o(!0);try{i(await S2())}catch{i({balance:0,grants:[],tokenHolding:null})}finally{o(!1)}},[]),w=N.useCallback(async()=>{f(!0),m(!1);try{c(await E2())}catch{c([]),m(!0)}finally{f(!1)}},[]);N.useEffect(()=>{e&&Promise.all([v(),w()])},[e,v,w]),N.useEffect(()=>{if(!e)return;const F=()=>{Promise.all([v(),w()])};return window.addEventListener(Bo,F),window.addEventListener(ji,F),()=>{window.removeEventListener(Bo,F),window.removeEventListener(ji,F)}},[e,v,w]);const b=N.useCallback(async()=>{await Promise.all([v(),w()])},[v,w]),{balance:C,totalGranted:T,used:I,usagePercent:k,dailyCredits:_,bonus:M,resetsAt:V,resetsAtIsFallback:G,tokenGrant:L}=N.useMemo(()=>{const F=()=>{const ye=new Date;return new Date(Date.UTC(ye.getUTCFullYear(),ye.getUTCMonth(),ye.getUTCDate()+1,0,0,0)).toISOString()};if(!s)return{balance:0,totalGranted:0,used:0,usagePercent:0,dailyCredits:0,bonus:0,resetsAt:F(),resetsAtIsFallback:!0,tokenGrant:void 0};const Q=s.grants||[],J=Q.reduce((ye,U)=>ye+Number(U.amount),0),oe=s.balance??0,xe=Math.max(0,J-oe),ge=J>0?xe/J*100:0,$=Q.filter(ye=>ye.source_type==="DAILY_WALLET"||ye.source_type==="TOKEN_HOLDING").reduce((ye,U)=>ye+Number(U.amount),0),le=Math.max(0,J-$),B=Q.find(ye=>ye.source_type==="TOKEN_HOLDING"),Te=Q.find(ye=>ye.source_type==="DAILY_WALLET")||B;return{balance:oe,totalGranted:J,used:xe,usagePercent:ge,dailyCredits:$,bonus:le,resetsAt:Te?.expires_at||F(),resetsAtIsFallback:!Te?.expires_at,tokenGrant:B}},[s]),H=()=>{e&&(navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),1500))};return e?u.jsxs("div",{className:"mx-auto max-w-5xl space-y-6",children:[u.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-end md:justify-between",children:[u.jsx("div",{children:u.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"My Account"})}),u.jsxs("div",{className:"flex items-center gap-2 rounded-full border border-border/70 bg-white px-3 py-1.5 shadow-[0_1px_2px_rgba(16,24,40,0.04)]",children:[u.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[#98fe00]"}),u.jsx(Ts,{className:"h-3.5 w-3.5 text-muted-foreground"}),u.jsxs("span",{className:"font-mono text-xs text-foreground",children:[e.slice(0,6),"…",e.slice(-4)]}),t&&u.jsx(cs,{variant:"outline",className:"border-border/70 bg-transparent text-[10px] uppercase tracking-wider text-foreground",children:t}),u.jsx("button",{onClick:H,className:"text-muted-foreground transition-colors hover:text-foreground","aria-label":"Copy wallet address",children:r?u.jsx(jr,{className:"h-3.5 w-3.5"}):u.jsx(zn,{className:"h-3.5 w-3.5"})})]})]}),u.jsxs(wf,{children:[u.jsxs("div",{className:"flex items-start justify-between",children:[u.jsx(bf,{children:"BANDWIDTH"}),u.jsx(g_,{className:"h-4 w-4 text-muted-foreground"})]}),u.jsxs("div",{className:"mt-5 flex items-end gap-2",children:[u.jsx("span",{className:"text-4xl font-semibold leading-none",children:a?"—":xn(C)}),u.jsx("span",{className:"pb-1 text-xs uppercase tracking-wider text-muted-foreground",children:"credits available"})]}
66),u.jsx(ip,{value:a?0:Math.min(100,Math.max(0,k)),className:"mt-4 h-2"}),u.jsxs("div",{className:"mt-2 flex items-center justify-between text-[11px] text-muted-foreground",children:[u.jsx("span",{children:a?"—":`${xn(C)} of ${xn(T)} total`}),u.jsx("span",{children:a?"—":`${G?"Next refresh in":"Resets in"} ${gH(V)}`})]}),u.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3 md:grid-cols-3",children:[{label:"Daily credits",value:xn(_)},{label:"Bonus",value:`+${xn(M)}`},{label:"Usage",value:`${Math.round(k)}%`}].map(F=>u.jsxs("div",{className:"rounded-lg border border-border/60 px-3 py-2.5",children:[u.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:F.label}),u.jsx("div",{className:"mt-1 text-sm font-semibold",children:a?"—":F.value})]},F.label))})]}),u.jsxs(wf,{children:[u.jsxs("div",{className:"flex items-start justify-between",children:[u.jsx(bf,{children:"TOKEN HOLDINGS"}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(pg,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("button",{onClick:g.refresh,className:"text-muted-foreground transition-colors hover:text-foreground","aria-label":"Refresh token balance",children:u.jsx(gc,{className:ze("h-3.5 w-3.5",g.loading&&"animate-spin")})})]})]}),u.jsx("div",{className:"mt-4",children:u.jsx(Df,{variant:"panel",token:{address:s?.tokenHolding?.tokenAddress,symbol:s?.tokenHolding?.symbol,chainId:s?.tokenHolding?.chainId}})}),(()=>{const F=L?.metadata||{},Q=Number(F.tokenBalance??NaN),J=Number.isFinite(Q)?Q:Number.isFinite(Number(g.balance))?Number(g.balance):0,oe=Number(F.pointsPerToken??NaN),xe=F.tokenSymbol||g.symbol||"TOKEN",ge=Number.isFinite(oe);return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"mt-5 flex items-end gap-2",children:u.jsx("span",{className:"text-4xl font-semibold leading-none",children:xe})}),u.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[xn(J)," ",xe," held"]}),u.jsxs("div",{className:"mt-6 grid grid-cols-2 gap-3",children:[u.jsxs("div",{className:"rounded-lg border border-border/60 px-3 py-2.5",children:[u.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Rate"}),u.jsx("div",{className:"mt-1 text-sm font-semibold",children:ge?`1 ${xe} = ${xn(oe)} credit${oe===1?"":"s"}`:"—"})]}),u.jsxs("div",{className:"rounded-lg border border-border/60 px-3 py-2.5",children:[u.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Today's bandwidth"}),u.jsxs("div",{className:"mt-1 text-sm font-semibold",children:["+",xn(Number(L?.amount)||0)]})]})]})]})})()]}),u.jsx(RH,{walletAddress:e,onClaimed:b}),u.jsxs(wf,{children:[u.jsxs("div",{className:"flex items-start justify-between",children:[u.jsx(bf,{children:"RECENT ACTIVITY"}),u.jsx("button",{onClick:()=>void w(),className:"text-muted-foreground transition-colors hover:text-foreground","aria-label":"Refresh activity",children:u.jsx(gc,{className:ze("h-3.5 w-3.5",d&&"animate-spin")})})]}),d?u.jsx("div",{className:"mt-4 space-y-3",children:[0,1,2].map(F=>u.jsxs("div",{className:"flex items-center justify-between py-1",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"h-7 w-7 animate-pulse rounded-full bg-muted"}),u.jsxs("div",{className:"space-y-1.5",children:[u.jsx("div",{className:"h-3 w-32 animate-pulse rounded bg-muted"}),u.jsx("div",{className:"h-2.5 w-16 animate-pulse rounded bg-muted"})]})]}),u.jsx("div",{className:"h-3 w-10 animate-pulse rounded bg-muted"})]},F))}):h?u.jsxs("div",{className:"mt-5 flex items-center gap-3 text-sm text-muted-foreground",children:["Could not load activity.",u.jsx("button",{onClick:()=>void w(),className:"text-xs font-semibold uppercase tracking-wider text-foreground underline",children:"Retry"})]}):l.length===0?u.jsx("div",{className:"mt-5 text-sm text-muted-foreground",children:"No bandwidth activity yet"}):u.jsx("div",{className:"mt-4 divide-y divide-border/60",children:l.map((F,Q)=>{const J=F.type==="CREDIT",oe=String(F.source||"");return u.jsxs("div",{className:"flex items-center justify-between py-3",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-full border border-border/60",children:oe==="NFT_CAMPAIGN"?u.jsx(Nx,{className:"h-3.5 w-3.5 text-muted-foreground"}):J?u.jsx(pg,{className:"h-3.5 w-3.5 text-muted-foreground"}):u.jsx(y_,{className:"h-3.5 w-3.5 text-muted-foreground"})}),u.jsxs("div",{children:[u.jsx("div",{className:"text-sm",children:dH(F)}),u.jsx("div",{className:"text-[11px] text-muted-foreground",children:yH(F.created_at)})]})]}),u.jsxs("span",{className:ze("text-sm font-semibold",J?"text-foreground":"text-muted-foreground"),children:[J?"+":"-",xn(F.amount)]})]},`${oe}-${F.created_at}-${Q}`)})})]})]}):u.jsxs("div",{className:"mx-auto max-w-md py-20 text-center",children:[u.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full border border-border/70",children:u.jsx(Ts,{className:"h-5 w-5 text-muted-foreground"})}),u.jsx("h1",{className:"text-xl font-semibold",children:"Connect your wallet"}),u.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Your bandwidth and token holdings are tied to your wallet."})]})},jH=({isOpen:e,onRetry:t})=>{const[r,n]=N.useState(!1),s=async()=>{n(!0),t?await t():window.location.reload()};return u.jsx(zo,{open:e,onOpenChange:()=>{},children:u.jsxs(_a,{className:"sm:max-w-md",children:[u.jsxs(Ko,{children:[u.jsx("div",{className:"flex justify-center mb-4",children:u.jsx("div",{className:"w-16 h-16 rounded-full bg-[#98fe00]/10 flex items-center justify-center",children:u.jsx(v_,{className:"h-8 w-8 text-[#98fe00]"})})}),u.jsx(qo,{className:"text-center text-xl",children:"We're Working On It"}),u.jsx(au,{className:"text-center pt-2",children:"Our service is temporarily unavailable. We're aware of the issue and working to restore it as quickly as possible."})]}),u.jsxs("div",{className:"space-y-3 py-4",children:[u.jsx("div",{className:"text-center text-sm text-muted-foreground",children:"Please check back in a few moments"}),u.jsxs(yt,{onClick:s,disabled:r,className:"w-full bg-[#98fe00]/10 text-[black] border border-[#98fe00]/30 hover:bg-[#98fe00]/20 transition-all duration-300 disabled:opacity-50",children:[u.jsx(gc,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Retrying...":"Try Again"]}),u.jsx("div",{className:"text-center text-xs text-gray-500 pt-2",children:"If this persists, please contact support"})]})]})})},A2="current_user",Cf=new Map;function Oh(e){return(e||"").toLowerCase()}function k2(e){const t=localStorage.getItem(A2);if(!t)return null;
66try{const r=JSON.parse(t),n=Oh(r.walletAddress||r.wallet_address||r.address);return e&&n&&n!==Oh(e)?null:r}catch{return null}}const BH=e=>new Promise(t=>setTimeout(t,e));function DH(e){const t=e?.response?.status;return t?t>=500:!0}async function Sf(e,t={}){if(!e)return null;const r=Oh(e);if(!t.force){const i=k2(e);if(i)return i}const n=Cf.get(r);if(n)return n;const s=(async()=>{try{let i=null;try{i=await f0(e)}catch(a){if(!DH(a))throw a;await BH(1200),i=await f0(e)}return i&&localStorage.setItem(A2,JSON.stringify({walletAddress:e,...i})),i}finally{Cf.delete(r)}})();return Cf.set(r,s),s}const LH=new lT,MH=()=>{const[e,t]=N.useState(""),[r,n]=N.useState("evm"),[s,i]=N.useState(null),[a,o]=N.useState(!0),[l,c]=N.useState("solana"),[d,f]=N.useState(!1),[h,m]=N.useState(!1),{toast:g}=jn();N.useEffect(()=>{(async()=>{try{const{data:{session:I}}=await En.auth.getSession();i(I);const k=Eo(),_=localStorage.getItem("web3_jwt");if(k&&_){t(k.address),n(k.type);try{const V=await HA();V&&V.address!==k.address&&(t(V.address),n(V.type))}catch{}const M=Eo()?.address||k.address;k2(M)||Sf(M).catch(V=>{})}}catch{}finally{o(!1)}})();const{data:{subscription:T}}=En.auth.onAuthStateChange((I,k)=>{i(k),I==="SIGNED_OUT"&&(t(""),co())});return()=>{T.unsubscribe()}},[]),N.useEffect(()=>{const C=k=>{r==="evm"&&(k.length===0?(t(""),co(),g({title:"Wallet Disconnected",description:"Your EVM wallet has been disconnected"})):k[0])},T=()=>{m(!0)},I=()=>{m(!1)};return window.addEventListener("service-down",T),window.addEventListener("service-up",I),window.ethereum&&r==="evm"&&window.ethereum.on("accountsChanged",C),()=>{window.ethereum&&window.ethereum.removeListener("accountsChanged",C),window.removeEventListener("service-down",T),window.removeEventListener("service-up",I)}},[e,r,g]);const v=C=>{t(C.address),n(C.type),f(!1),Sf(C.address,{force:!0}).catch(T=>{g({title:"Could not finish setting up your account",description:"Your wallet is connected, but registration failed. Tap to retry.",variant:"destructive",action:u.jsx(cb,{altText:"Retry registration",onClick:()=>{Sf(C.address,{force:!0}).catch(I=>{})},children:"Retry"})})})},w=()=>{f(!0)},b=async()=>{t(""),n("evm"),co(),s&&(await En.auth.signOut(),i(null)),g({title:"Wallet Disconnected",description:"Successfully disconnected wallet"})};return a?u.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:"Loading..."}):u.jsx(S_,{children:u.jsx(w_,{client:LH,children:u.jsx(BI,{attribute:"class",defaultTheme:"light",storageKey:"theme",disableTransitionOnChange:!1,children:u.jsxs(dA,{children:[u.jsxs("div",{className:"min-h-screen bg-background pb-20 md:pb-0",children:[u.jsx("header",{className:"sticky top-0 z-50 border-b border-border/50 bg-background/95 backdrop-blur-md supp
66orts-[backdrop-filter]:bg-background/80 shadow-sm",style:{borderBottomWidth:"1px"},children:u.jsx("div",{className:"container mx-auto px-6",children:u.jsxs("div",{className:"flex h-14 items-center justify-between",children:[u.jsx("div",{className:"flex items-center",children:u.jsx("a",{href:"/",className:"flex items-center",children:u.jsx("img",{src:"/uploads/slinky-logo.png",alt:"SlinkyLayer Logo",className:"h-[80px] object-contain"})})}),u.jsx(RA,{walletAddress:e,currentNetwork:l,onDisconnect:b}),!e&&u.jsxs(yt,{variant:"outline",onClick:w,className:"border-border hover:bg-accent hover:text-accent-foreground transition-all duration-200",title:"Connect Wallet",children:[u.jsx(Ts,{className:"h-4 w-4"}),u.jsx("span",{className:"ml-2",children:"Connect Wallet"})]})]})})}),u.jsx("main",{className:"container mx-auto px-6 py-8",children:u.jsxs(E_,{children:[u.jsx(Bs,{path:"/",element:u.jsx(pi,{walletAddress:e,onConnect:v,children:u.jsx(Ov,{walletAddress:e})})}),u.jsx(Bs,{path:"/apis",element:u.jsx(T_,{to:"/tools",replace:!0})}),u.jsx(Bs,{path:"/tools",element:u.jsx(pi,{walletAddress:e,onConnect:v,children:u.jsx(g5,{})})}),u.jsx(Bs,{path:"/dashboard",element:u.jsx(pi,{walletAddress:e,onConnect:v,children:u.jsx(fN,{walletAddress:e})})}),u.jsx(Bs,{path:"/chat",element:u.jsx(pi,{walletAddress:e,onConnect:v,children:u.jsx(Ov,{walletAddress:e})})}),u.jsx(Bs,{path:"/tools/:apiId",element:u.jsx(pi,{walletAddress:e,onConnect:v,children:u.jsx(cP,{})})}),u.jsx(Bs,{path:"/account",element:u.jsx(pi,{walletAddress:e,onConnect:v,children:u.jsx(PH,{walletAddress:e})})}),u.jsx(Bs,{path:"/profile",element:u.jsx(pi,{walletAddress:e,onConnect:v,children:u.jsx(vN,{walletAddress:e,walletType:r})})})]})}),u.jsx(PA,{}),u.jsx("div",{className:"md:hidden fixed bottom-0 left-0 right-0 z-40 bg-accent/20 backdrop-blur-sm border-t border-border px-0 pr-0",children:u.jsx(jA,{})})]}),u.jsx(Jh,{isOpen:d,onClose:()=>f(!1),onWalletConnected:v}),u.jsx(jH,{isOpen:h,onRetry:()=>{window.location.reload()}}),u.jsx(NI,{}),u.jsx(uA,{})]})})})})};_f.createRoot(document.getElementById("root")).render(u.jsx(_e.StrictMode,{children:u.jsx(MH,{})}));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.