@augmentd-labs/canvas-web 2.26.12 → 2.26.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{EditorOverlay-V80099Ju.js → EditorOverlay-B384ALjA.js} +1 -1
- package/dist/assets/{MarkdownEditor-CB8zhARt.js → MarkdownEditor-CkobBLtI.js} +2 -2
- package/dist/assets/{NextShell-DopBDMF8.js → NextShell-Byg6OtC2.js} +1 -1
- package/dist/assets/{SketchEditor-DHl4hUwl.js → SketchEditor-C9_lu3Ot.js} +5 -5
- package/dist/assets/{TextDocumentEditor-tZq2zx1j.js → TextDocumentEditor-DBVWuJaR.js} +1 -1
- package/dist/assets/{alert-dialog-BDwriJIW.js → alert-dialog-BC58hyW-.js} +1 -1
- package/dist/assets/{blobs-BK6-mKQR.js → blobs-CtDkR2hC.js} +1 -1
- package/dist/assets/document-list-BmUv3zzK.js +19 -0
- package/dist/assets/index-BhcdilCi.css +2 -0
- package/dist/assets/index-DVsVQDNU.js +59 -0
- package/dist/assets/{subtree-transfer-dialog-Ca1CCxIf.js → subtree-transfer-dialog-DRz8kLqY.js} +1 -1
- package/dist/assets/{text-documents-CmVlLSiW.js → text-documents-BvR9-zf4.js} +3 -3
- package/dist/assets/ui-BqHBdBU4.js +41 -0
- package/dist/assets/{useAddTarget-DJfPFrxr.js → useAddTarget-CgZfKokT.js} +1 -1
- package/dist/assets/{workspace-20BTA60d.js → workspace-BSXnX2Me.js} +1 -1
- package/dist/index.html +9 -9
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/document-list-DFyWTgB-.js +0 -19
- package/dist/assets/index-DqL81tH2.js +0 -40
- package/dist/assets/index-VRpQX_cE.css +0 -2
- package/dist/assets/ui-zR-lMEcp.js +0 -41
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/NextShell-Byg6OtC2.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BQnKd3jw.js","assets/workspace-BSXnX2Me.js","assets/react-BzqgEMSQ.js","assets/alert-dialog-BC58hyW-.js","assets/ui-BqHBdBU4.js","assets/utils-BxVxyehK.js","assets/utils-2pl1SbIp.js","assets/NextShell-BT6-_CFY.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{a,i as o,l as s,n as c,r as l,t as u,u as d}from"./code-editor-BQnKd3jw.js";import{_t as f,gt as p,vt as m,yt as h}from"./react-BzqgEMSQ.js";import{t as g}from"./preload-helper-Czpn1I53.js";import{$ as _,$n as v,$t as y,A as b,An as x,At as S,B as C,Bn as w,Bt as T,C as E,Cn as D,Ct as O,D as k,Dn as A,Dt as j,E as M,En as N,Et as P,F as ee,Fn as F,Ft as I,G as te,Gn as L,Gt as R,H as ne,Hn as re,Ht as ie,I as ae,In as z,It as oe,J as se,Jn as B,Jt as ce,K as V,Kn as le,Kt as ue,L as de,Ln as fe,Lt as pe,M as me,Mn as he,Mt as ge,N as _e,Nn as ve,Nt as ye,O as be,On as xe,Ot as H,P as Se,Pn as Ce,Pt as U,Q as W,Qn as we,Qt as Te,R as Ee,Rn as De,Rt as Oe,S as ke,Sn as Ae,St as je,T as Me,Tn as Ne,Tt as Pe,U as Fe,Un as Ie,Ut as Le,V as Re,Vn as ze,Vt as Be,W as Ve,Wn as He,Wt as Ue,Xn as We,Xt as Ge,Y as Ke,Yn as G,Yt as qe,Z as Je,Zn as Ye,Zt as Xe,_ as Ze,_n as Qe,_t as $e,a as et,an as tt,ar as nt,at as rt,b as it,bn as at,bt as ot,c as st,cr as ct,ct as lt,d as ut,dn as dt,dr as ft,dt as pt,en as mt,er as ht,et as gt,f as _t,fn as vt,fr as yt,ft as bt,g as xt,gn as St,gt as Ct,h as wt,hn as Tt,ht as Et,i as Dt,in as Ot,ir as kt,it as At,j as jt,jn as Mt,jt as Nt,k as Pt,kn as Ft,kt as It,l as Lt,lr as Rt,lt as zt,m as Bt,mn as Vt,mt as Ht,n as Ut,nn as Wt,nr as Gt,nt as Kt,o as qt,on as Jt,or as Yt,ot as Xt,p as Zt,pn as Qt,pr as $t,pt as en,q as tn,qn as nn,qt as rn,r as an,rn as on,rr as sn,rt as cn,s as ln,sr as un,st as dn,t as fn,tn as pn,tr as mn,tt as hn,u as gn,un as _n,ur as vn,ut as yn,v as bn,vn as xn,vt as Sn,w as Cn,wn,wt as Tn,x as En,xn as Dn,xt as On,y as kn,yn as An,yt as jn,z as Mn,zn as Nn,zt as Pn}from"./document-list-BmUv3zzK.js";import{$ as Fn,$n as In,$r as Ln,$t as Rn,An as zn,Ar as Bn,At as Vn,B as Hn,Bn as Un,Br as Wn,Bt as Gn,C as Kn,Cn as qn,Cr as Jn,Ct as Yn,Dn as Xn,Dr as Zn,En as Qn,F as $n,Fr as er,Ft as tr,G as nr,Gn as rr,Gr as ir,H as ar,Hn as or,Hr as sr,Ht as cr,I as lr,It as ur,J as dr,Jn as fr,Jr as pr,Jt as mr,K as hr,Kn as gr,Kr as _r,L as vr,Lr as yr,Mt as br,Nn as xr,Nr as Sr,Nt as Cr,On as wr,Or as Tr,Ot as Er,P as Dr,Pn as Or,Pr as kr,Pt as Ar,Q as jr,Qn as Mr,Qr as Nr,R as Pr,Rn as Fr,Rr as Ir,Rt as Lr,S as Rr,Sn as zr,St as Br,Tt as Vr,U as Hr,Ur,Ut as Wr,V as Gr,Vn as Kr,Vr as qr,Vt as Jr,W as Yr,Wn as Xr,Wt as Zr,X as Qr,Xn as $r,Xt as ei,Y as ti,Yn as ni,Yr as ri,Yt as ii,Z as ai,Zn as oi,Zr as si,Zt as ci,_ as li,_i as ui,_n as di,_r as fi,_t as pi,an as mi,ar as hi,at as gi,b as _i,bn as vi,br as yi,bt as bi,ci as xi,cn as Si,ct as Ci,d as wi,dn as Ti,dr as Ei,dt as Di,ei as Oi,en as ki,er as Ai,et as ji,f as Mi,fi as Ni,fr as Pi,ft as Fi,g as Ii,gi as Li,gn as Ri,gr as zi,gt as Bi,h as Vi,hi as Hi,hn as Ui,ht as Wi,in as Gi,ir as Ki,it as qi,jn as Ji,jr as Yi,jt as Xi,kn as Zi,kr as Qi,kt as $i,ln as ea,lt as ta,m as na,mi as ra,mr as ia,mt as aa,ni as oa,nn as sa,oi as ca,on as la,or as ua,p as da,pi as fa,pn as pa,pr as ma,pt as ha,q as ga,qn as _a,qt as va,ri as ya,rn as ba,rr as xa,rt as Sa,si as Ca,sn as wa,st as Ta,tn as Ea,tt as Da,u as Oa,ui as ka,un as Aa,ur as ja,ut as Ma,v as Na,vn as Pa,vr as Fa,vt as Ia,w as La,wn as Ra,wr as za,wt as Ba,x as Va,xn as Ha,xt as Ua,y as Wa,yn as Ga,yr as Ka,yt as qa,z as Ja,zn as Ya,zr as Xa,zt as Za}from"./ui-BqHBdBU4.js";import{i as Qa,n as $a,r as eo}from"./utils-BxVxyehK.js";import{n as to,t as K}from"./utils-2pl1SbIp.js";import{_ as no,a as ro,b as q,c as io,d as ao,f as oo,g as so,h as co,i as lo,l as uo,m as fo,n as po,o as mo,p as ho,r as go,s as _o,t as vo,u as J,v as yo,x as Y,y as bo}from"./alert-dialog-BC58hyW-.js";import{t as xo}from"./socket-hM4c-ZSl.js";import{a as So,c as Co,l as wo,n as To,o as Eo,r as Do,s as Oo}from"./blobs-CtDkR2hC.js";import{$ as ko,$t as Ao,A as jo,At as Mo,B as No,C as Po,Cn as Fo,Ct as Io,D as Lo,Dn as Ro,Dt as zo,E as Bo,En as Vo,Fn as Ho,Ft as Uo,Gt as Wo,H as Go,Ht as Ko,I as qo,It as Jo,J as Yo,Jt as Xo,K as Zo,Kn as Qo,Kt as $o,L as es,Ln as ts,M as ns,Mn as rs,Nn as is,Nt as as,O as os,On as ss,Ot as cs,Pn as ls,Pt as us,Q as ds,Qt as fs,R as ps,Rn as ms,S as hs,Sn as gs,St as _s,T as vs,Tn as ys,Tt as bs,U as xs,Ut as Ss,V as Cs,Vt as ws,W as Ts,Wn as Es,Wt as Ds,Yt as Os,Zt as ks,_ as As,_n as js,_t as Ms,a as Ns,an as Ps,at as Fs,b as Is,bn as Ls,bt as Rs,cn as zs,ct as Bs,dn as Vs,dt as Hs,en as Us,et as Ws,f as Gs,fn as Ks,ft as qs,gn as Js,gt as Ys,ht as Xs,i as Zs,it as Qs,j as $s,jt as ec,k as tc,kn as nc,kt as rc,ln as ic,lt as ac,m as oc,mt as sc,n as cc,nn as lc,nt as uc,o as dc,on as fc,ot as pc,p as mc,pn as hc,pt as gc,q as _c,qt as vc,r as yc,rn as bc,rt as xc,s as Sc,sn as Cc,st as wc,t as Tc,tt as Ec,u as Dc,un as Oc,ut as kc,v as Ac,vn as jc,vt as Mc,w as Nc,wn as Pc,wt as Fc,x as Ic,xn as Lc,xt as Rc,y as zc,yt as Bc,z as Vc,zn as Hc,zt as Uc}from"./workspace-BSXnX2Me.js";import{_ as Wc,c as Gc,f as Kc,g as qc,h as Jc,l as Yc,m as Xc,o as Zc,p as Qc,s as $c,u as el,y as tl}from"./text-documents-BvR9-zf4.js";import{B as nl,D as rl,F as il,I as al,L as ol,N as sl,O as cl,P as ll,R as ul,T as dl,_ as fl,a as pl,b as ml,c as hl,d as gl,f as _l,g as vl,h as yl,i as bl,j as xl,m as Sl,n as Cl,o as wl,p as Tl,r as El,s as Dl,t as Ol,u as kl,w as Al,y as jl,z as Ml}from"./useAddTarget-CgZfKokT.js";import{n as Nl,t as Pl}from"./map-BxCwdK0d.js";import{t as Fl}from"./sha256-65KIjGvZ.js";import{n as Il,t as Ll}from"./use-theme-Bd8sb5Ox.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var X=n(d(),1),Rl=m(),Z=s(),zl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));zl.displayName=`Card`;var Bl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Bl.displayName=`CardHeader`;var Vl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Vl.displayName=`CardTitle`;var Hl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));Hl.displayName=`CardDescription`;var Ul=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));Ul.displayName=`CardContent`;var Wl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Wl.displayName=`CardFooter`;var Gl=`2.26.14`,Kl=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function ql(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Kl(e);else{if(document.getElementById(`particles-js-script`))return;let t=document.createElement(`script`);t.id=`particles-js-script`,t.src=`/js/particles.min.js`,t.onload=()=>{console.log(`particles.js loaded`),Kl(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Jl=`session.open`,Yl=`session.set`,Xl=`session.ids`,Zl=`session.materialize`,Ql=`session.close`,$l=`session.delta`;function eu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await J.get(`/ping`,{skipAuth:!0});e&&(n?.version?t(n.version):a(`Invalid server response`))}catch(t){e&&(console.error(`Failed to fetch server version:`,t),a(`Unable to connect to server`))}finally{e&&r(!1)}}n();let i=setInterval(n,3e4);return()=>{e=!1,clearInterval(i)}},[]),{serverVersion:e,isLoading:n,error:i}}var tu=`https://github.com/canvas-ui/canvas-server`,nu=null;function ru(){return nu||=J.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||tu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),nu=null,{sourceUrl:tu,version:null,commit:null,license:null})),nu}function iu(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return ru().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function au({className:e=``}){let t=iu();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function ou({children:e}){ql(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=eu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(zl,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(we,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Gl,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,Z.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,Z.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(au,{className:`mt-4 text-center`})]})]})})]})})}async function su(e,t,n=`auto`){try{let r=await J.post(no.login,{email:e,password:t,strategy:n},{skipAuth:!0});console.log(`Login response:`,r);let i=r;if(`token`in i)return console.log(`Setting auth token (direct):`,i.token.substring(0,10)+`...`),J.setAuthToken(i.token),B.connect(i.token),r;if(i&&`payload`in i&&i.payload&&i.payload.token)return console.log(`Setting auth token (nested):`,i.payload.token.substring(0,10)+`...`),J.setAuthToken(i.payload.token),B.connect(i.payload.token),r;throw console.error(`Invalid login response structure:`,r),Error(`Invalid login response: missing token`)}catch(e){throw console.error(`Login error:`,e),J.clearAuthToken(),e}}async function cu(e,t,n){try{return await J.post(no.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function lu(e){return e instanceof Error&&/^Network error/i.test(e.message)}function uu(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return eo(e).exp*1e3>Date.now()}catch{return!1}}function du(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=eo(e);return t.exp*1e3<Date.now()?(J.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),J.clearAuthToken(),null}}async function fu(){try{if(!J.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await J.get(no.me);return console.log(`Current user response:`,e),e&&e?(B.isConnected()||B.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),lu(e))throw e;return e instanceof Error&&(e.message.includes(`USER_NOT_FOUND_IN_DATABASE`)||e.message.includes(`Your session is invalid`)||e.message.includes(`Authentication required`)||e.message.includes(`user account no longer exists`))?(console.warn(`Authentication error detected, clearing token:`,e.message),J.clearAuthToken(),B.disconnect(),null):null}}function pu(){return J.isAuthenticated()}function mu(){let e=new URL(`${yo}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function hu(e){let t=await J.post(`${yo}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);J.setAuthToken(t.token),B.connect(t.token)}async function gu(){try{let e=await J.get(no.authConfig,{skipAuth:!0});return e||e}catch(e){return console.error(`Failed to get auth config:`,e),{strategies:{local:{enabled:!0},imap:{enabled:!1,domains:[]}}}}}async function _u(e){try{await J.post(no.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var vu=e=>e?.strategies?.local?.enabled!==!1,yu=e=>e?.allowUserRegistrations!==!1;function bu(){let e=ft(),[t,n]=X.useState(!1),[r,i]=X.useState(``),[a,o]=X.useState(``),[s,c]=X.useState(!1),[l,u]=X.useState({}),[d,p]=X.useState(null),[m,h]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{uu()&&e(`/workspaces`),fetch(`${yo}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),gu().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let g=()=>{let e={};return m.email?/\S+@\S+\.\S+/.test(m.email)||(e.email=`Email is invalid`):e.email=`Email is required`,m.password||(e.password=`Password is required`),u(e),Object.keys(e).length===0},_=e=>{let{name:t,value:n}=e.target;h(e=>({...e,[t]:n}))};async function v(t){if(t.preventDefault(),g()){c(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await su(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),u({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}u({password:t})}finally{c(!1)}}}return t?(0,Z.jsx)(ou,{children:(0,Z.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(J.setAuthToken(r.trim()),!await fu())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){J.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,Z.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,Z.jsx)(G,{htmlFor:`local-token`,children:`Local access token`}),(0,Z.jsx)(q,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(Y,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,Z.jsx)(ou,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:v,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:m.strategy,onChange:_,disabled:s,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),l.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,disabled:s,onClick:()=>mu(),children:[(0,Z.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),vu(d)&&yu(d)&&(0,Z.jsx)(Y,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function xu(){let e=ft(),{showToast:t}=wo(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await gu(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=X.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,Z.jsxs)(ou,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(Y,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(we,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(ou,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await cu(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(Y,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(we,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,Z.jsx)(we,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(we,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function Su(){let e=ft(),[t]=$t(),[n,r]=X.useState(t.get(`error`)),i=X.useRef(!1);return X.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,hu(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,Z.jsx)(ou,{children:(0,Z.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Cu({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!pu()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await fu();e?(console.log(`User authenticated:`,e.email),n(`authenticated`)):(console.log(`User not authenticated or token expired`),n(`unauthenticated`))}catch(e){if(console.error(`Authentication check failed:`,e),lu(e)){if(uu()){n(`authenticated`);return}J.clearAuthToken(),n(`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),J.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(nn,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(ht,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function wu({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{(async()=>{try{await J.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),J.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Z.jsx)(ht,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var Tu=i(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n[`fast-equals`]={}))})(e,(function(e){function t(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function n(e){return function(t,n,r,i){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r,i);var a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);var s=e(t,n,r,i);return i.delete(t),i.delete(n),s}}function r(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function i(e){return e.constructor===Object||e.constructor==null}function a(e){return typeof e.then==`function`}function o(e,t){return e===t||e!==e&&t!==t}var s=Object.prototype.toString;function c(e){var t=e.areArraysEqual,n=e.areDatesEqual,r=e.areMapsEqual,c=e.areObjectsEqual,l=e.areRegExpsEqual,u=e.areSetsEqual,d=e.createIsNestedEqual,f=d(p);function p(e,d,p){if(e===d)return!0;if(!e||!d||typeof e!=`object`||typeof d!=`object`)return e!==e&&d!==d;if(i(e)&&i(d))return c(e,d,f,p);var m=Array.isArray(e),h=Array.isArray(d);if(m||h)return m===h&&t(e,d,f,p);var g=s.call(e);return g===s.call(d)?g===`[object Date]`?n(e,d,f,p):g===`[object RegExp]`?l(e,d,f,p):g===`[object Map]`?r(e,d,f,p):g===`[object Set]`?u(e,d,f,p):g===`[object Object]`||g===`[object Arguments]`?a(e)||a(d)?!1:c(e,d,f,p):g===`[object Boolean]`||g===`[object Number]`||g===`[object String]`?o(e.valueOf(),d.valueOf()):!1:!1}return p}function l(e,t,n,r){var i=e.length;if(t.length!==i)return!1;for(;i-->0;)if(!n(e[i],t[i],i,i,e,t,r))return!1;return!0}var u=n(l);function d(e,t){return o(e.valueOf(),t.valueOf())}function f(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={},o=0;return e.forEach(function(s,c){if(i){var l=!1,u=0;t.forEach(function(i,d){!l&&!a[u]&&(l=n(c,d,o,u,e,t,r)&&n(s,i,c,d,e,t,r))&&(a[u]=!0),u++}),o++,i=l}}),i}var p=n(f),m=`_owner`,h=Object.prototype.hasOwnProperty;function g(e,t,n,r){var i=Object.keys(e),a=i.length;if(Object.keys(t).length!==a)return!1;for(var o;a-->0;){if(o=i[a],o===m){var s=!!e.$$typeof,c=!!t.$$typeof;if((s||c)&&s!==c)return!1}if(!h.call(t,o)||!n(e[o],t[o],o,o,e,t,r))return!1}return!0}var _=n(g);function v(e,t){return e.source===t.source&&e.flags===t.flags}function y(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={};return e.forEach(function(o,s){if(i){var c=!1,l=0;t.forEach(function(i,u){!c&&!a[l]&&(c=n(o,i,s,u,e,t,r))&&(a[l]=!0),l++}),i=c}}),i}var b=n(y),x=Object.freeze({areArraysEqual:l,areDatesEqual:d,areMapsEqual:f,areObjectsEqual:g,areRegExpsEqual:v,areSetsEqual:y,createIsNestedEqual:t}),S=Object.freeze({areArraysEqual:u,areDatesEqual:d,areMapsEqual:p,areObjectsEqual:_,areRegExpsEqual:v,areSetsEqual:b,createIsNestedEqual:t}),C=c(x);function w(e,t){return C(e,t,void 0)}var T=c(r(x,{createIsNestedEqual:function(){return o}}));function E(e,t){return T(e,t,void 0)}var D=c(S);function O(e,t){return D(e,t,new WeakMap)}var k=c(r(S,{createIsNestedEqual:function(){return o}}));function A(e,t){return k(e,t,new WeakMap)}function j(e){return c(r(x,e(x)))}function M(e){var t=c(r(S,e(S)));return(function(e,n,r){return r===void 0&&(r=new WeakMap),t(e,n,r)})}e.circularDeepEqual=O,e.circularShallowEqual=A,e.createCustomCircularEqual=M,e.createCustomEqual=j,e.deepEqual=w,e.sameValueZeroEqual=o,e.shallowEqual=E,Object.defineProperty(e,"__esModule",{value:!0})}))})),Eu=i(((e,t)=>{t.exports=function(e,t,n){return e===t||e.className===t.className&&n(e.style,t.style)&&e.width===t.width&&e.autoSize===t.autoSize&&e.cols===t.cols&&e.draggableCancel===t.draggableCancel&&e.draggableHandle===t.draggableHandle&&n(e.verticalCompact,t.verticalCompact)&&n(e.compactType,t.compactType)&&n(e.layout,t.layout)&&n(e.margin,t.margin)&&n(e.containerPadding,t.containerPadding)&&e.rowHeight===t.rowHeight&&e.maxRows===t.maxRows&&e.isBounded===t.isBounded&&e.isDraggable===t.isDraggable&&e.isResizable===t.isResizable&&e.allowOverlap===t.allowOverlap&&e.preventCollision===t.preventCollision&&e.useCSSTransforms===t.useCSSTransforms&&e.transformScale===t.transformScale&&e.isDroppable===t.isDroppable&&n(e.resizeHandles,t.resizeHandles)&&n(e.resizeHandle,t.resizeHandle)&&e.onLayoutChange===t.onLayoutChange&&e.onDragStart===t.onDragStart&&e.onDrag===t.onDrag&&e.onDragStop===t.onDragStop&&e.onResizeStart===t.onResizeStart&&e.onResize===t.onResize&&e.onResizeStop===t.onResizeStop&&e.onDrop===t.onDrop&&n(e.droppingItem,t.droppingItem)&&n(e.innerRef,t.innerRef)}})),Du=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=se,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=L,e.setTopLeft=ne,e.setTransform=R,e.sortLayoutItems=re,e.sortLayoutItemsByColRow=ae,e.sortLayoutItemsByRowCol=ie,e.synchronizeLayoutWithChildren=z,e.validateLayout=oe,e.withLayoutItem=p;var t=Tu(),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:t+``}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){let t=0,n;for(let r=0,i=e.length;r<i;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function u(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=m(e[n]);return t}function f(e,t){let n=Array(e.length);for(let r=0,i=e.length;r<i;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function p(e,t,n){let r=C(e,t);return r?(r=n(m(r)),e=f(e,r),[e,r]):[e,null]}function m(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function h(e,r){return(0,t.deepEqual)(n.default.Children.map(e,e=>e?.key),n.default.Children.map(r,e=>e?.key))&&(0,t.deepEqual)(n.default.Children.map(e,e=>e?.props[`data-grid`]),n.default.Children.map(r,e=>e?.props[`data-grid`]))}e.fastRGLPropsEqual=Eu();function g(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function _(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function v(e,t,n,r){let i=E(e),a=l(i),o=re(e,t),s=Array(e.length);for(let c=0,l=o.length;c<l;c++){let l=m(o[c]);l.static||(l=x(i,l,t,n,o,r,a),a=Math.max(a,l.y+l.h),i.push(l)),s[e.indexOf(o[c])]=l,l.moved=!1}return s}var y={x:`w`,y:`h`};function b(e,t,n,r){let i=y[r];t[r]+=1;let a=e.map(e=>e.i).indexOf(t.i);for(let o=a+1;o<e.length;o++){let a=e[o];if(!a.static){if(a.y>t.y+t.h)break;_(t,a)&&b(e,a,n+t[i],r)}}t[r]=n}function x(e,t,n,r,i,a,o){let s=n===`vertical`,c=n===`horizontal`;if(s)for(t.y=Math.min(typeof o==`number`?o:l(e),t.y);t.y>0&&!w(e,t);)t.y--;else if(c)for(;t.x>0&&!w(e,t);)t.x--;let u;for(;(u=w(e,t))&&!(n===null&&a);)if(c?b(i,t,u.x+u.w,`x`):b(i,t,u.y+u.h,`y`),c&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!w(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function S(e,t){let n=E(e);for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i.x+i.w>t.cols&&(i.x=t.cols-i.w),i.x<0&&(i.x=0,i.w=t.cols),!i.static)n.push(i);else for(;w(n,i);)i.y++}return e}function C(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function w(e,t){for(let n=0,r=e.length;n<r;n++)if(_(e[n],t))return e[n]}function T(e,t){return e.filter(e=>_(e,t))}function E(e){return e.filter(e=>e.static)}function D(e,t,n,r,i,a,o,s,c){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;let l=t.x,d=t.y;typeof n==`number`&&(t.x=n),typeof r==`number`&&(t.y=r),t.moved=!0;let f=re(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},te={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function L(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function R(e){let{top:t,left:n,width:r,height:i}=e,a=`translate(${n}px,${t}px)`;return{transform:a,WebkitTransform:a,MozTransform:a,msTransform:a,OTransform:a,width:`${r}px`,height:`${i}px`,position:`absolute`}}function ne(e){let{top:t,left:n,width:r,height:i}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${i}px`,position:`absolute`}}function re(e,t){return t===`horizontal`?ae(e):t===`vertical`?ie(e):e}function ie(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ae(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function z(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function oe(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function se(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Ou=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calcGridColWidth=t,e.calcGridItemPosition=r,e.calcGridItemWHPx=n,e.calcWH=a,e.calcXY=i,e.clamp=o;function t(e){let{margin:t,containerPadding:n,containerWidth:r,cols:i}=e;return(r-t[0]*(i-1)-n[0]*2)/i}function n(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function r(e,r,i,a,o,s){let{margin:c,containerPadding:l,rowHeight:u}=e,d=t(e),f={};return s&&s.resizing?(f.width=Math.round(s.resizing.width),f.height=Math.round(s.resizing.height)):(f.width=n(a,d,c[0]),f.height=n(o,u,c[1])),s&&s.dragging?(f.top=Math.round(s.dragging.top),f.left=Math.round(s.dragging.left)):s&&s.resizing&&typeof s.resizing.top==`number`&&typeof s.resizing.left==`number`?(f.top=Math.round(s.resizing.top),f.left=Math.round(s.resizing.left)):(f.top=Math.round((u+c[1])*i+l[1]),f.left=Math.round((d+c[0])*r+l[0])),f}function i(e,n,r,i,a){let{margin:s,containerPadding:c,cols:l,rowHeight:u,maxRows:d}=e,f=t(e),p=Math.round((r-c[0])/(f+s[0])),m=Math.round((n-c[1])/(u+s[1]));return p=o(p,0,l-i),m=o(m,0,d-a),{x:p,y:m}}function a(e,n,r,i,a,s){let{margin:c,maxRows:l,cols:u,rowHeight:d}=e,f=t(e),p=Math.round((n+c[0])/(f+c[0])),m=Math.round((r+c[1])/(d+c[1])),h=o(p,0,u-i),g=o(m,0,l-a);return[`sw`,`w`,`nw`].indexOf(s)!==-1&&(h=o(p,0,u)),[`nw`,`n`,`ne`].indexOf(s)!==-1&&(g=o(m,0,l)),{w:h,h:g}}function o(e,t,n){return Math.max(Math.min(e,n),t)}})),ku=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),Au=i(((e,t)=>{var n=ku();function r(){}function i(){}i.resetWarningCache=r,t.exports=function(){function e(e,t,r,i,a,o){if(o!==n){var s=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name=`Invariant Violation`,s}}e.isRequired=e;function t(){return e}var a={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:i,resetWarningCache:r};return a.PropTypes=a,a}})),ju=i(((e,t)=>{t.exports=Au()()})),Mu=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},u=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{DraggableCore:()=>Se,default:()=>Ce}),t.exports=f(p);var m=u(d()),g=u(ju()),_=u(h()),v=$a();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function te(e,t,n){let r=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect();return{x:(e.clientX+t.scrollLeft-r.left)/n,y:(e.clientY+t.scrollTop-r.top)/n}}function L(e,t){let n=ne(e,t,`px`);return{[E(`transform`,O)]:n}}function R(e,t){return ne(e,t,``)}function ne({x:e,y:t},n,r){let i=`translate(${e}${r},${t}${r})`;return n&&(i=`translate(${`${typeof n.x==`string`?n.x:n.x+r}`}, ${`${typeof n.y==`string`?n.y:n.y+r}`})`+i),i}function re(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function ie(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ae(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function z(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ae();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
3
|
+
`,n.innerHTML+=`.react-draggable-transparent-selection *::selection {all: inherit;}
|
|
4
|
+
`,e.getElementsByTagName(`head`)[0].appendChild(n)}e.body&&B(e.body,`react-draggable-transparent-selection`)}function oe(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{se(e)}):se(e)}function se(e){if(e)try{e.body&&ce(e.body,`react-draggable-transparent-selection`);let t=e.selection;if(t)t.empty();else{let t=(e.defaultView||window).getSelection();t&&t.type!==`Caret`&&t.removeAllRanges()}}catch{}}function B(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function ce(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function V(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:he(r);let i=ge(e);if(typeof r==`string`){let{ownerDocument:e}=i,t=e.defaultView;if(!t)throw Error(`Cannot resolve the owner window of the draggable node.`);let n;if(n=r===`parent`?i.parentNode:i.getRootNode().querySelector(r),!(n instanceof t.HTMLElement))throw Error(`Bounds selector "`+r+`" could not find an element.`);let a=n,o=t.getComputedStyle(i),s=t.getComputedStyle(a);r={left:-i.offsetLeft+S(s.paddingLeft)+S(o.marginLeft),top:-i.offsetTop+S(s.paddingTop)+S(o.marginTop),right:I(a)-ee(i)-i.offsetLeft+S(s.paddingRight)-S(o.marginRight),bottom:F(a)-P(i)-i.offsetTop+S(s.paddingBottom)-S(o.marginBottom)}}return x(r.right)&&(t=Math.min(t,r.right)),x(r.bottom)&&(n=Math.min(n,r.bottom)),x(r.left)&&(t=Math.max(t,r.left)),x(r.top)&&(n=Math.max(n,r.top)),[t,n]}function le(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function ue(e){return e.props.axis===`both`||e.props.axis===`x`}function de(e){return e.props.axis===`both`||e.props.axis===`y`}function fe(e,t,n){let r=typeof t==`number`?re(e,t):null;if(typeof t==`number`&&!r)return null;let i=ge(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return te(r||e,a,n.props.scale)}function pe(e,t,n){let r=!x(e.lastX),i=ge(e);return r?{node:i,deltaX:0,deltaY:0,lastX:t,lastY:n,x:t,y:n}:{node:i,deltaX:t-e.lastX,deltaY:n-e.lastY,lastX:e.lastX,lastY:e.lastY,x:t,y:n}}function me(e,t){let n=e.props.scale;return{node:t.node,x:e.state.x+t.deltaX/n,y:e.state.y+t.deltaY/n,deltaX:t.deltaX/n,deltaY:t.deltaY/n,lastX:e.state.x,lastY:e.state.y}}function he(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function ge(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var _e=u(d()),ve=u(ju()),ye=u(h()),be=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},xe={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},H=xe.mouse,Se=class extends _e.Component{constructor(){super(...arguments),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,this.touchIdentifier=null,this.mounted=!1,this.handleDragStart=e=>{if(this.props.onMouseDown(e),!this.props.allowAnyClick&&(typeof e.button==`number`&&e.button!==0||e.ctrlKey))return!1;let t=this.findDOMNode();if(!t||!t.ownerDocument||!t.ownerDocument.body)throw Error(`<DraggableCore> not mounted on DragStart!`);let{ownerDocument:n}=t;if(this.props.disabled||!(e.target instanceof n.defaultView.Node)||this.props.handle&&!j(e.target,this.props.handle,t)||this.props.cancel&&j(e.target,this.props.cancel,t))return;e.type===`touchstart`&&!this.props.allowMobileScroll&&e.preventDefault();let r=ie(e);this.touchIdentifier=r;let i=fe(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=pe(this,a,o);be(`DraggableCore: handleDragStart: %j`,s),be(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&z(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,H.move,this.handleDrag),M(n,H.stop,this.handleDragStop))},this.handleDrag=e=>{let t=fe(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX,t=r-this.lastY;if([e,t]=le(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(be(`DraggableCore: handleDrag: %j`,i),this.props.onDrag(e,i)===!1||this.mounted===!1){try{this.handleDragStop(new MouseEvent(`mouseup`))}catch{let e=document.createEvent(`MouseEvents`);e.initMouseEvent(`mouseup`,!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),this.handleDragStop(e)}return}this.lastX=n,this.lastY=r},this.handleDragStop=e=>{if(!this.dragging)return;let t=fe(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX||0,t=r-this.lastY||0;[e,t]=le(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&oe(a.ownerDocument),be(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(be(`DraggableCore: Removing handlers`),N(a.ownerDocument,H.move,this.handleDrag),N(a.ownerDocument,H.stop,this.handleDragStop))},this.onMouseDown=e=>(H=xe.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(H=xe.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(H=xe.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(H=xe.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,xe.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,xe.mouse.move,this.handleDrag),N(t,xe.touch.move,this.handleDrag),N(t,xe.mouse.stop,this.handleDragStop),N(t,xe.touch.stop,this.handleDragStop),N(e,xe.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&oe(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=ye.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(be(`react-draggable: ReactDOM.findDOMNode is not available in React 19+. You must provide a nodeRef prop. See: https://github.com/react-grid-layout/react-draggable#noderef`),null)}render(){return _e.cloneElement(_e.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};Se.displayName=`DraggableCore`,Se.propTypes={allowAnyClick:ve.default.bool,allowMobileScroll:ve.default.bool,children:ve.default.node.isRequired,disabled:ve.default.bool,enableUserSelectHack:ve.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:ve.default.arrayOf(ve.default.number),handle:ve.default.string,cancel:ve.default.string,nodeRef:ve.default.object,nonce:ve.default.string,onStart:ve.default.func,onDrag:ve.default.func,onStop:ve.default.func,onMouseDown:ve.default.func,scale:ve.default.number,className:C,style:C,transform:C},Se.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var Ce=class extends m.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(be(`Draggable: onDragStart: %j`,t),this.props.onStart(e,me(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;be(`Draggable: onDrag: %j`,t);let n=me(this,t),r={x:n.x,y:n.y,slackX:0,slackY:0};if(this.props.bounds){let{x:e,y:t}=r;r.x+=this.state.slackX,r.y+=this.state.slackY;let[i,a]=V(this,r.x,r.y);r.x=i,r.y=a,r.slackX=this.state.slackX+(e-r.x),r.slackY=this.state.slackY+(t-r.y),n.x=r.x,n.y=r.y,n.deltaX=r.x-this.state.x,n.deltaY=r.y-this.state.y}if(this.props.onDrag(e,n)===!1)return!1;this.setState(r)},this.onDragStop=(e,t)=>{if(!this.state.dragging||this.props.onStop(e,me(this,t))===!1)return!1;be(`Draggable: onDragStop: %j`,t);let n={dragging:!1,slackX:0,slackY:0};if(this.props.position){let{x:e,y:t}=this.props.position;n.x=e,n.y=t}this.setState(n)},this.state={dragging:!1,dragged:!1,x:e.position?e.position.x:e.defaultPosition.x,y:e.position?e.position.y:e.defaultPosition.y,prevPropsPosition:{...e.position},slackX:0,slackY:0,isElementSVG:!1},e.position&&!(e.onDrag||e.onStop)&&console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.")}static getDerivedStateFromProps({position:e},{prevPropsPosition:t}){return e&&(!t||e.x!==t.x||e.y!==t.y)?(be(`Draggable: getDerivedStateFromProps %j`,{position:e,prevPropsPosition:t}),{x:e.x,y:e.y,prevPropsPosition:{...e}}):null}componentDidMount(){window.SVGElement!==void 0&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.state.dragging&&this.setState({dragging:!1})}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=_.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):null}render(){let{axis:e,bounds:t,children:n,defaultPosition:r,defaultClassName:i,defaultClassNameDragging:a,defaultClassNameDragged:o,position:s,positionOffset:c,scale:l,...u}=this.props,d={},f=null,p=!s||this.state.dragging,h=s||r,g={x:ue(this)&&p?this.state.x:h.x,y:de(this)&&p?this.state.y:h.y};this.state.isElementSVG?f=R(g,c):d=L(g,c);let _=m.Children.only(n),y=(0,v.clsx)(_.props.className||``,i,{[a]:this.state.dragging,[o]:this.state.dragged});return m.createElement(Se,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},m.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};Ce.displayName=`Draggable`,Ce.propTypes={...Se.propTypes,axis:g.default.oneOf([`both`,`x`,`y`,`none`]),bounds:g.default.oneOfType([g.default.shape({left:g.default.number,right:g.default.number,top:g.default.number,bottom:g.default.number}),g.default.string,g.default.oneOf([!1])]),defaultClassName:g.default.string,defaultClassNameDragging:g.default.string,defaultClassNameDragged:g.default.string,defaultPosition:g.default.shape({x:g.default.number,y:g.default.number}),positionOffset:g.default.shape({x:g.default.oneOfType([g.default.number,g.default.string]),y:g.default.oneOfType([g.default.number,g.default.string])}),position:g.default.shape({x:g.default.number,y:g.default.number}),className:C,style:C,transform:C},Ce.defaultProps={...Se.defaultProps,axis:`both`,bounds:!1,defaultClassName:`react-draggable`,defaultClassNameDragging:`react-draggable-dragging`,defaultClassNameDragged:`react-draggable-dragged`,defaultPosition:{x:0,y:0},scale:1},0&&(t.exports={DraggableCore:Se})})),Nu=i(((e,t)=>{var n=Mu(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),Pu=i((e=>{e.__esModule=!0,e.cloneElement=c;var t=n(d());function n(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return(t=o(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=s(e,`string`);return typeof t==`symbol`?t:t+``}function s(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function c(e,n){return n.style&&e.props.style&&(n.style=i(i({},e.props.style),n.style)),n.className&&e.props.className&&(n.className=e.props.className+` `+n.className),t.default.cloneElement(e,n)}})),Fu=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(ju());Nu();function n(e){return e&&e.__esModule?e:{default:e}}e.resizableProps={axis:t.default.oneOf([`both`,`x`,`y`,`none`]),className:t.default.string,children:t.default.element.isRequired,draggableOpts:t.default.shape({allowAnyClick:t.default.bool,cancel:t.default.string,children:t.default.node,disabled:t.default.bool,enableUserSelectHack:t.default.bool,offsetParent:typeof Element<`u`?t.default.instanceOf(Element):t.default.any,grid:t.default.arrayOf(t.default.number),handle:t.default.string,nodeRef:t.default.object,onStart:t.default.func,onDrag:t.default.func,onStop:t.default.func,onMouseDown:t.default.func,scale:t.default.number}),height:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`y`?t.default.number.isRequired(...e):t.default.number(...e)},handle:t.default.oneOfType([t.default.node,t.default.func]),handleSize:t.default.arrayOf(t.default.number),lockAspectRatio:t.default.bool,maxConstraints:t.default.arrayOf(t.default.number),minConstraints:t.default.arrayOf(t.default.number),onResizeStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,resizeHandles:t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),transformScale:t.default.number,width:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`x`?t.default.number.isRequired(...e):t.default.number(...e)}}})),Iu=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=Nu(),r=Pu(),i=Fu(),a=[`children`,`className`,`draggableOpts`,`width`,`height`,`handle`,`handleSize`,`lockAspectRatio`,`axis`,`minConstraints`,`maxConstraints`,`onResize`,`onResizeStop`,`onResizeStart`,`resizeHandles`,`transformScale`];function o(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(o=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s.apply(null,arguments)}function c(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var h=class extends t.Component{constructor(){super(...arguments),this.handleRefs={},this.lastHandleRect=null,this.slack=null,this.lastSize=null}componentWillUnmount(){this.resetData()}resetData(){this.lastHandleRect=this.slack=this.lastSize=null}runConstraints(e,t){let n=this.props,r=n.minConstraints,i=n.maxConstraints,a=n.lockAspectRatio;if(!r&&!i&&!a)return[e,t];if(a){let n=this.props.width/this.props.height,r=e-this.props.width,i=t-this.props.height;Math.abs(r)>Math.abs(i*n)?t=e/n:e=t*n}let o=e,s=t,c=this.slack||[0,0],l=c[0],u=c[1];return e+=l,t+=u,r&&(e=Math.max(r[0],e),t=Math.max(r[1],t)),i&&(e=Math.min(i[0],e),t=Math.min(i[1],t)),this.slack=[l+(o-e),u+(s-t)],[e,t]}resizeHandler(e,t){return(n,r)=>{let i=r.node,a=r.deltaX,o=r.deltaY;e===`onResizeStart`&&this.resetData();let s=(this.props.axis===`both`||this.props.axis===`x`)&&t!==`n`&&t!==`s`,c=(this.props.axis===`both`||this.props.axis===`y`)&&t!==`e`&&t!==`w`;if(!s&&!c)return;let l=t[0],u=t[t.length-1],d=i.getBoundingClientRect();if(this.lastHandleRect!=null){if(u===`w`){let e=d.left-this.lastHandleRect.left;a+=e}if(l===`n`){let e=d.top-this.lastHandleRect.top;o+=e}}this.lastHandleRect=d,u===`w`&&(a=-a),l===`n`&&(o=-o);let f=this.lastSize?.width??this.props.width,p=this.lastSize?.height??this.props.height,m=f+(s?a/this.props.transformScale:0),h=p+(c?o/this.props.transformScale:0);var g=this.runConstraints(m,h);if(m=g[0],h=g[1],e===`onResizeStop`&&this.lastSize){var _=this.lastSize;m=_.width,h=_.height}let v=m!==f||h!==p;e!==`onResizeStop`&&(this.lastSize={width:m,height:h});let y=typeof this.props[e]==`function`?this.props[e]:null;y&&!(e===`onResize`&&!v)&&(n.persist==null||n.persist(),y(n,{node:i,size:{width:m,height:h},handle:t})),e===`onResizeStop`&&this.resetData()}}renderResizeHandle(e,n){let r=this.props.handle;if(!r)return t.createElement(`span`,{className:`react-resizable-handle react-resizable-handle-`+e,ref:n});if(typeof r==`function`)return r(e,n);let i=typeof r.type==`string`,a=u({ref:n},i?{}:{handleAxis:e});return t.cloneElement(r,a)}render(){let e=this.props,i=e.children,o=e.className,l=e.draggableOpts;e.width,e.height,e.handle,e.handleSize,e.lockAspectRatio,e.axis,e.minConstraints,e.maxConstraints,e.onResize,e.onResizeStop,e.onResizeStart;let d=e.resizeHandles;e.transformScale;let f=c(e,a);return(0,r.cloneElement)(i,u(u({},f),{},{className:(o?o+` `:``)+`react-resizable`,children:[...t.Children.toArray(i.props.children),...d.map(e=>{let r=this.handleRefs[e]??(this.handleRefs[e]=t.createRef());return t.createElement(n.DraggableCore,s({},l,{nodeRef:r,key:`resizableHandle-`+e,onStop:this.resizeHandler(`onResizeStop`,e),onStart:this.resizeHandler(`onResizeStart`,e),onDrag:this.resizeHandler(`onResize`,e)}),this.renderResizeHandle(e,r))})]}))}};e.default=h,h.propTypes=i.resizableProps,h.defaultProps={axis:`both`,handleSize:[20,20],lockAspectRatio:!1,minConstraints:[20,20],maxConstraints:[1/0,1/0],resizeHandles:[`se`],transformScale:1}})),Lu=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(ju()),r=o(Iu()),i=Fu(),a=[`handle`,`handleSize`,`onResize`,`onResizeStart`,`onResizeStop`,`draggableOpts`,`minConstraints`,`maxConstraints`,`lockAspectRatio`,`axis`,`width`,`height`,`resizeHandles`,`style`,`transformScale`];function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(s=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(null,arguments)}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function h(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var g=class extends t.Component{constructor(){super(...arguments),this.state={width:this.props.width,height:this.props.height,propsWidth:this.props.width,propsHeight:this.props.height},this.onResize=(e,t)=>{let n=t.size;this.props.onResize?(e.persist==null||e.persist(),this.setState(n,()=>this.props.onResize&&this.props.onResize(e,t))):this.setState(n)}}static getDerivedStateFromProps(e,t){return t.propsWidth!==e.width||t.propsHeight!==e.height?{width:e.width,height:e.height,propsWidth:e.width,propsHeight:e.height}:null}render(){let e=this.props,n=e.handle,i=e.handleSize;e.onResize;let o=e.onResizeStart,s=e.onResizeStop,l=e.draggableOpts,d=e.minConstraints,f=e.maxConstraints,p=e.lockAspectRatio,m=e.axis;e.width,e.height;let g=e.resizeHandles,_=e.style,v=e.transformScale,y=h(e,a);return t.createElement(r.default,{axis:m,draggableOpts:l,handle:n,handleSize:i,height:this.state.height,lockAspectRatio:p,maxConstraints:f,minConstraints:d,onResizeStart:o,onResize:this.onResize,onResizeStop:s,resizeHandles:g,transformScale:v,width:this.state.width},t.createElement(`div`,c({},y,{style:u(u({},_),{},{width:this.state.width+`px`,height:this.state.height+`px`})})))}};e.default=g,g.propTypes=u(u({},i.resizableProps),{},{children:n.default.element})})),Ru=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=Iu().default,t.exports.ResizableBox=Lu().default})),zu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(ju()),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}var i=e.resizeHandleAxesType=t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),a=e.resizeHandleType=t.default.oneOfType([t.default.node,t.default.func]);e.default={className:t.default.string,style:t.default.object,width:t.default.number,autoSize:t.default.bool,cols:t.default.number,draggableCancel:t.default.string,draggableHandle:t.default.string,verticalCompact:function(e){e.verticalCompact},compactType:t.default.oneOf([`vertical`,`horizontal`]),layout:function(e){var t=e.layout;t!==void 0&&Du().validateLayout(t,`layout`)},margin:t.default.arrayOf(t.default.number),containerPadding:t.default.arrayOf(t.default.number),rowHeight:t.default.number,maxRows:t.default.number,isBounded:t.default.bool,isDraggable:t.default.bool,isResizable:t.default.bool,allowOverlap:t.default.bool,preventCollision:t.default.bool,useCSSTransforms:t.default.bool,transformScale:t.default.number,isDroppable:t.default.bool,resizeHandles:i,resizeHandle:a,onLayoutChange:t.default.func,onDragStart:t.default.func,onDrag:t.default.func,onDragStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,onResizeStop:t.default.func,onDrop:t.default.func,droppingItem:t.default.shape({i:t.default.string.isRequired,w:t.default.number.isRequired,h:t.default.number.isRequired}),children:function(e,t){let r=e[t],i={};n.default.Children.forEach(r,function(e){if(e?.key!=null){if(i[e.key])throw Error(`Duplicate child key "`+e.key+`" found! This will cause problems in ReactGridLayout.`);i[e.key]=!0}})},innerRef:t.default.any}})),Bu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=u(d()),n=h(),r=u(ju()),i=Nu(),a=Ru(),o=Du(),s=Ou(),c=zu(),l=u($a());function u(e){return e&&e.__esModule?e:{default:e}}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?f(Object(n),!0).forEach(function(t){m(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function m(e,t,n){return(t=g(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e){var t=_(e,`string`);return typeof t==`symbol`?t:t+``}function _(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var v=class extends t.default.Component{constructor(){super(...arguments),m(this,`state`,{resizing:null,dragging:null,className:``}),m(this,`elementRef`,t.default.createRef()),m(this,`onDragStart`,(e,t)=>{let{node:n}=t,{onDragStart:r,transformScale:i}=this.props;if(!r)return;let a={top:0,left:0},{offsetParent:o}=n;if(!o)return;let c=o.getBoundingClientRect(),l=n.getBoundingClientRect(),u=l.left/i,d=c.left/i,f=l.top/i,p=c.top/i;a.left=u-d+o.scrollLeft,a.top=f-p+o.scrollTop,this.setState({dragging:a});let{x:m,y:h}=(0,s.calcXY)(this.getPositionParams(),a.top,a.left,this.props.w,this.props.h);return r.call(this,this.props.i,m,h,{e,node:n,newPosition:a})}),m(this,`onDrag`,(e,t,r)=>{let{node:i,deltaX:a,deltaY:o}=t,{onDrag:c}=this.props;if(!c)return;if(!this.state.dragging)throw Error(`onDrag called before onDragStart.`);let l=this.state.dragging.top+o,u=this.state.dragging.left+a,{isBounded:d,i:f,w:p,h:m,containerWidth:h}=this.props,g=this.getPositionParams();if(d){let{offsetParent:e}=i;if(e){let{margin:t,rowHeight:n}=this.props,r=e.clientHeight-(0,s.calcGridItemWHPx)(m,n,t[1]);l=(0,s.clamp)(l,0,r);let i=(0,s.calcGridColWidth)(g),a=h-(0,s.calcGridItemWHPx)(p,i,t[0]);u=(0,s.clamp)(u,0,a)}}let _={top:l,left:u};r?this.setState({dragging:_}):(0,n.flushSync)(()=>{this.setState({dragging:_})});let{x:v,y}=(0,s.calcXY)(g,l,u,p,m);return c.call(this,f,v,y,{e,node:i,newPosition:_})}),m(this,`onDragStop`,(e,t)=>{let{node:n}=t,{onDragStop:r}=this.props;if(!r)return;if(!this.state.dragging)throw Error(`onDragEnd called before onDragStart.`);let{w:i,h:a,i:o}=this.props,{left:c,top:l}=this.state.dragging,u={top:l,left:c};this.setState({dragging:null});let{x:d,y:f}=(0,s.calcXY)(this.getPositionParams(),l,c,i,a);return r.call(this,o,d,f,{e,node:n,newPosition:u})}),m(this,`onResizeStop`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStop`)),m(this,`onResizeStart`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStart`)),m(this,`onResize`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResize`))}shouldComponentUpdate(e,t){if(this.props.children!==e.children||this.props.droppingPosition!==e.droppingPosition)return!0;let n=(0,s.calcGridItemPosition)(this.getPositionParams(this.props),this.props.x,this.props.y,this.props.w,this.props.h,this.state),r=(0,s.calcGridItemPosition)(this.getPositionParams(e),e.x,e.y,e.w,e.h,t);return!(0,o.fastPositionEqual)(n,r)||this.props.useCSSTransforms!==e.useCSSTransforms}componentDidMount(){this.moveDroppingItem({})}componentDidUpdate(e){this.moveDroppingItem(e)}moveDroppingItem(e){let{droppingPosition:t}=this.props;if(!t)return;let n=this.elementRef.current;if(!n)return;let r=e.droppingPosition||{left:0,top:0},{dragging:i}=this.state,a=i&&t.left!==r.left||t.top!==r.top;if(!i)this.onDragStart(t.e,{node:n,deltaX:t.left,deltaY:t.top});else if(a){let e=t.left-i.left,r=t.top-i.top;this.onDrag(t.e,{node:n,deltaX:e,deltaY:r},!0)}}getPositionParams(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.props;return{cols:e.cols,containerPadding:e.containerPadding,containerWidth:e.containerWidth,margin:e.margin,maxRows:e.maxRows,rowHeight:e.rowHeight}}createStyle(e){let{usePercentages:t,containerWidth:n,useCSSTransforms:r}=this.props,i;return r?i=(0,o.setTransform)(e):(i=(0,o.setTopLeft)(e),t&&(i.left=(0,o.perc)(e.left/n),i.width=(0,o.perc)(e.width/n))),i}mixinDraggable(e,n){return t.default.createElement(i.DraggableCore,{disabled:!n,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,handle:this.props.handle,cancel:`.react-resizable-handle`+(this.props.cancel?`,`+this.props.cancel:``),scale:this.props.transformScale,nodeRef:this.elementRef},e)}curryResizeHandler(e,t){return(n,r)=>t(n,r,e)}mixinResizable(e,n,r){let{cols:i,minW:o,minH:c,maxW:l,maxH:u,transformScale:d,resizeHandles:f,resizeHandle:p}=this.props,m=this.getPositionParams(),h=(0,s.calcGridItemPosition)(m,0,0,i,0).width,g=(0,s.calcGridItemPosition)(m,0,0,o,c),_=(0,s.calcGridItemPosition)(m,0,0,l,u),v=[g.width,g.height],y=[Math.min(_.width,h),Math.min(_.height,1/0)];return t.default.createElement(a.Resizable,{draggableOpts:{disabled:!r},className:r?void 0:`react-resizable-hide`,width:n.width,height:n.height,minConstraints:v,maxConstraints:y,onResizeStop:this.curryResizeHandler(n,this.onResizeStop),onResizeStart:this.curryResizeHandler(n,this.onResizeStart),onResize:this.curryResizeHandler(n,this.onResize),transformScale:d,resizeHandles:f,handle:p},e)}onResizeHandler(e,t,r,i){let{node:a,size:c,handle:l}=t,u=this.props[i];if(!u)return;let{x:d,y:f,i:p,maxH:m,minH:h,containerWidth:g}=this.props,{minW:_,maxW:v}=this.props,y=c;a&&(y=(0,o.resizeItemInDirection)(l,r,c,g),(0,n.flushSync)(()=>{this.setState({resizing:i===`onResizeStop`?null:y})}));let{w:b,h:x}=(0,s.calcWH)(this.getPositionParams(),y.width,y.height,d,f,l);b=(0,s.clamp)(b,Math.max(_,1),v),x=(0,s.clamp)(x,h,m),u.call(this,p,b,x,{e,node:a,size:y,handle:l})}render(){let{x:e,y:n,w:r,h:i,isDraggable:a,isResizable:o,droppingPosition:c,useCSSTransforms:u}=this.props,d=(0,s.calcGridItemPosition)(this.getPositionParams(),e,n,r,i,this.state),f=t.default.Children.only(this.props.children),m=t.default.cloneElement(f,{ref:this.elementRef,className:(0,l.default)(`react-grid-item`,f.props.className,this.props.className,{static:this.props.static,resizing:!!this.state.resizing,"react-draggable":a,"react-draggable-dragging":!!this.state.dragging,dropping:!!c,cssTransforms:u}),style:p(p(p({},this.props.style),f.props.style),this.createStyle(d))});return m=this.mixinResizable(m,d,o),m=this.mixinDraggable(m,a),m}};e.default=v,m(v,`propTypes`,{children:r.default.element,cols:r.default.number.isRequired,containerWidth:r.default.number.isRequired,rowHeight:r.default.number.isRequired,margin:r.default.array.isRequired,maxRows:r.default.number.isRequired,containerPadding:r.default.array.isRequired,x:r.default.number.isRequired,y:r.default.number.isRequired,w:r.default.number.isRequired,h:r.default.number.isRequired,minW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minWidth not Number`);if(n>e.w||n>e.maxW)return Error(`minWidth larger than item width/maxWidth`)},maxW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxWidth not Number`);if(n<e.w||n<e.minW)return Error(`maxWidth smaller than item width/minWidth`)},minH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minHeight not Number`);if(n>e.h||n>e.maxH)return Error(`minHeight larger than item height/maxHeight`)},maxH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxHeight not Number`);if(n<e.h||n<e.minH)return Error(`maxHeight smaller than item height/minHeight`)},i:r.default.string.isRequired,resizeHandles:c.resizeHandleAxesType,resizeHandle:c.resizeHandleType,onDragStop:r.default.func,onDragStart:r.default.func,onDrag:r.default.func,onResizeStop:r.default.func,onResizeStart:r.default.func,onResize:r.default.func,isDraggable:r.default.bool.isRequired,isResizable:r.default.bool.isRequired,isBounded:r.default.bool.isRequired,static:r.default.bool,useCSSTransforms:r.default.bool.isRequired,transformScale:r.default.number,className:r.default.string,handle:r.default.string,cancel:r.default.string,droppingPosition:r.default.shape({e:r.default.object.isRequired,left:r.default.number.isRequired,top:r.default.number.isRequired})}),m(v,`defaultProps`,{className:``,cancel:``,handle:``,minH:1,minW:1,maxH:1/0,maxW:1/0,transformScale:1})})),Vu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=Tu(),r=c($a()),i=Du(),a=Ou(),o=c(Bu()),s=c(zu());function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){p(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`,_=!1;try{_=/firefox/i.test(navigator.userAgent)}catch{}var v=class extends t.Component{constructor(){super(...arguments),p(this,`state`,{activeDrag:null,layout:(0,i.synchronizeLayoutWithChildren)(this.props.layout,this.props.children,this.props.cols,(0,i.compactType)(this.props),this.props.allowOverlap),mounted:!1,oldDragItem:null,oldLayout:null,oldResizeItem:null,resizing:!1,droppingDOMNode:null,children:[]}),p(this,`dragEnterCounter`,0),p(this,`onDragStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);if(!c)return;let l={w:c.w,h:c.h,x:c.x,y:c.y,placeholder:!0,i:e};return this.setState({oldDragItem:(0,i.cloneLayoutItem)(c),oldLayout:s,activeDrag:l}),this.props.onDragStart(s,c,c,null,a,o)}),p(this,`onDrag`,(e,t,n,r)=>{let{e:a,node:o}=r,{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,allowOverlap:u,preventCollision:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;let p={w:f.w,h:f.h,x:f.x,y:f.y,placeholder:!0,i:e};c=(0,i.moveElement)(c,f,t,n,!0,d,(0,i.compactType)(this.props),l,u),this.props.onDrag(c,s,f,p,a,o),this.setState({layout:u?c:(0,i.compact)(c,(0,i.compactType)(this.props),l),activeDrag:p})}),p(this,`onDragStop`,(e,t,n,r)=>{let{e:a,node:o}=r;if(!this.state.activeDrag)return;let{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,preventCollision:u,allowOverlap:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;c=(0,i.moveElement)(c,f,t,n,!0,u,(0,i.compactType)(this.props),l,d);let p=d?c:(0,i.compact)(c,(0,i.compactType)(this.props),l);this.props.onDragStop(p,s,f,null,a,o);let{oldLayout:m}=this.state;this.setState({activeDrag:null,layout:p,oldDragItem:null,oldLayout:null}),this.onLayoutMaybeChanged(p,m)}),p(this,`onResizeStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);c&&(this.setState({oldResizeItem:(0,i.cloneLayoutItem)(c),oldLayout:this.state.layout,resizing:!0}),this.props.onResizeStart(s,c,c,null,a,o))}),p(this,`onResize`,(e,t,n,r)=>{let{e:a,node:o,size:s,handle:c}=r,{oldResizeItem:l}=this.state,{layout:u}=this.state,{cols:d,preventCollision:p,allowOverlap:m}=this.props,h=!1,g,_,v,[y,b]=(0,i.withLayoutItem)(u,e,e=>{let r;return _=e.x,v=e.y,[`sw`,`w`,`nw`,`n`,`ne`].indexOf(c)!==-1&&([`sw`,`nw`,`w`].indexOf(c)!==-1&&(_=e.x+(e.w-t),t=e.x!==_&&_<0?e.w:t,_=_<0?0:_),[`ne`,`n`,`nw`].indexOf(c)!==-1&&(v=e.y+(e.h-n),n=e.y!==v&&v<0?e.h:n,v=v<0?0:v),h=!0),p&&!m&&(r=(0,i.getAllCollisions)(u,f(f({},e),{},{w:t,h:n,x:_,y:v})).filter(t=>t.i!==e.i).length>0,r&&(v=e.y,n=e.h,_=e.x,t=e.w,h=!1)),e.w=t,e.h=n,e});if(!b)return;g=y,h&&(g=(0,i.moveElement)(y,b,_,v,!0,this.props.preventCollision,(0,i.compactType)(this.props),d,m));let x={w:b.w,h:b.h,x:b.x,y:b.y,static:!0,i:e};this.props.onResize(g,l,b,x,a,o),this.setState({layout:m?g:(0,i.compact)(g,(0,i.compactType)(this.props),d),activeDrag:x})}),p(this,`onResizeStop`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s,oldResizeItem:c}=this.state,{cols:l,allowOverlap:u}=this.props,d=(0,i.getLayoutItem)(s,e),f=u?s:(0,i.compact)(s,(0,i.compactType)(this.props),l);this.props.onResizeStop(f,c,d,null,a,o);let{oldLayout:p}=this.state;this.setState({activeDrag:null,layout:f,oldResizeItem:null,oldLayout:null,resizing:!1}),this.onLayoutMaybeChanged(f,p)}),p(this,`onDragOver`,e=>{var n;if(e.preventDefault(),e.stopPropagation(),_&&!((n=e.nativeEvent.target)!=null&&n.classList.contains(g)))return!1;let{droppingItem:r,onDropDragOver:i,margin:o,cols:s,rowHeight:c,maxRows:l,width:u,containerPadding:d,transformScale:p}=this.props,m=i?.(e);if(m===!1)return this.state.droppingDOMNode&&this.removeDroppingPlaceholder(),!1;let h=f(f({},r),m),{layout:v}=this.state,y=e.currentTarget.getBoundingClientRect(),b=e.clientX-y.left,x=e.clientY-y.top,S={left:b/p,top:x/p,e};if(!this.state.droppingDOMNode){let e={cols:s,margin:o,maxRows:l,rowHeight:c,containerWidth:u,containerPadding:d||o},n=(0,a.calcXY)(e,x,b,h.w,h.h);this.setState({droppingDOMNode:t.createElement(`div`,{key:h.i}),droppingPosition:S,layout:[...v,f(f({},h),{},{x:n.x,y:n.y,static:!1,isDraggable:!0})]})}else if(this.state.droppingPosition){let{left:e,top:t}=this.state.droppingPosition;(e!=b||t!=x)&&this.setState({droppingPosition:S})}}),p(this,`removeDroppingPlaceholder`,()=>{let{droppingItem:e,cols:t}=this.props,{layout:n}=this.state,r=(0,i.compact)(n.filter(t=>t.i!==e.i),(0,i.compactType)(this.props),t,this.props.allowOverlap);this.setState({layout:r,droppingDOMNode:null,activeDrag:null,droppingPosition:void 0})}),p(this,`onDragLeave`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter--,this.dragEnterCounter===0&&this.removeDroppingPlaceholder()}),p(this,`onDragEnter`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter++}),p(this,`onDrop`,e=>{e.preventDefault(),e.stopPropagation();let{droppingItem:t}=this.props,{layout:n}=this.state,r=n.find(e=>e.i===t.i);this.dragEnterCounter=0,this.removeDroppingPlaceholder(),this.props.onDrop(n,r,e)})}componentDidMount(){this.setState({mounted:!0}),this.onLayoutMaybeChanged(this.state.layout,this.props.layout)}static getDerivedStateFromProps(e,t){let r;return t.activeDrag?null:(!(0,n.deepEqual)(e.layout,t.propsLayout)||e.compactType!==t.compactType?r=e.layout:(0,i.childrenEqual)(e.children,t.children)||(r=t.layout),r?{layout:(0,i.synchronizeLayoutWithChildren)(r,e.children,e.cols,(0,i.compactType)(e),e.allowOverlap),compactType:e.compactType,children:e.children,propsLayout:e.layout}:null)}shouldComponentUpdate(e,t){return this.props.children!==e.children||!(0,i.fastRGLPropsEqual)(this.props,e,n.deepEqual)||this.state.activeDrag!==t.activeDrag||this.state.mounted!==t.mounted||this.state.droppingPosition!==t.droppingPosition}componentDidUpdate(e,t){if(!this.state.activeDrag){let e=this.state.layout,n=t.layout;this.onLayoutMaybeChanged(e,n)}}containerHeight(){if(!this.props.autoSize)return;let e=(0,i.bottom)(this.state.layout),t=this.props.containerPadding?this.props.containerPadding[1]:this.props.margin[1];return e*this.props.rowHeight+(e-1)*this.props.margin[1]+t*2+`px`}onLayoutMaybeChanged(e,t){t||=this.state.layout,(0,n.deepEqual)(t,e)||this.props.onLayoutChange(e)}placeholder(){let{activeDrag:e}=this.state;if(!e)return null;let{width:n,cols:r,margin:i,containerPadding:a,rowHeight:s,maxRows:c,useCSSTransforms:l,transformScale:u}=this.props;return t.createElement(o.default,{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,className:`react-grid-placeholder ${this.state.resizing?`placeholder-resizing`:``}`,containerWidth:n,cols:r,margin:i,containerPadding:a||i,maxRows:c,rowHeight:s,isDraggable:!1,isResizable:!1,isBounded:!1,useCSSTransforms:l,transformScale:u},t.createElement(`div`,null))}processGridItem(e,n){if(!e||!e.key)return;let r=(0,i.getLayoutItem)(this.state.layout,String(e.key));if(!r)return null;let{width:a,cols:s,margin:c,containerPadding:l,rowHeight:u,maxRows:d,isDraggable:f,isResizable:p,isBounded:m,useCSSTransforms:h,transformScale:g,draggableCancel:_,draggableHandle:v,resizeHandles:y,resizeHandle:b}=this.props,{mounted:x,droppingPosition:S}=this.state,C=typeof r.isDraggable==`boolean`?r.isDraggable:!r.static&&f,w=typeof r.isResizable==`boolean`?r.isResizable:!r.static&&p,T=r.resizeHandles||y,E=C&&m&&r.isBounded!==!1;return t.createElement(o.default,{containerWidth:a,cols:s,margin:c,containerPadding:l||c,maxRows:d,rowHeight:u,cancel:_,handle:v,onDragStop:this.onDragStop,onDragStart:this.onDragStart,onDrag:this.onDrag,onResizeStart:this.onResizeStart,onResize:this.onResize,onResizeStop:this.onResizeStop,isDraggable:C,isResizable:w,isBounded:E,useCSSTransforms:h&&x,usePercentages:!x,transformScale:g,w:r.w,h:r.h,x:r.x,y:r.y,i:r.i,minH:r.minH,minW:r.minW,maxH:r.maxH,maxW:r.maxW,static:r.static,droppingPosition:n?S:void 0,resizeHandles:T,resizeHandle:b},e)}render(){let{className:e,style:n,isDroppable:a,innerRef:o}=this.props,s=(0,r.default)(g,e),c=f({height:this.containerHeight()},n);return t.createElement(`div`,{ref:o,className:s,style:c,onDrop:a?this.onDrop:i.noop,onDragLeave:a?this.onDragLeave:i.noop,onDragEnter:a?this.onDragEnter:i.noop,onDragOver:a?this.onDragOver:i.noop},t.Children.map(this.props.children,e=>this.processGridItem(e)),a&&this.state.droppingDOMNode&&this.processGridItem(this.state.droppingDOMNode,!0),this.placeholder())}};e.default=v,p(v,`displayName`,`ReactGridLayout`),p(v,`propTypes`,s.default),p(v,`defaultProps`,{autoSize:!0,cols:12,className:``,style:{},draggableHandle:``,draggableCancel:``,containerPadding:null,rowHeight:150,maxRows:1/0,layout:[],margin:[10,10],isBounded:!1,isDraggable:!0,isResizable:!0,allowOverlap:!1,isDroppable:!1,useCSSTransforms:!0,transformScale:1,verticalCompact:!0,compactType:`vertical`,preventCollision:!1,droppingItem:{i:`__dropping-elem__`,h:1,w:1},resizeHandles:[`se`],onLayoutChange:i.noop,onDragStart:i.noop,onDrag:i.noop,onDragStop:i.noop,onResizeStart:i.noop,onResize:i.noop,onResizeStop:i.noop,onDrop:i.noop,onDropDragOver:i.noop})})),Hu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=Du();function n(e,t){let n=a(e),r=n[0];for(let i=1,a=n.length;i<a;i++){let a=n[i];t>e[a]&&(r=a)}return r}function r(e,t){if(!t[e])throw Error("ResponsiveReactGridLayout: `cols` entry for breakpoint "+e+` is missing!`);return t[e]}function i(e,n,r,i,o,s){if(e[r])return(0,t.cloneLayout)(e[r]);let c=e[i],l=a(n),u=l.slice(l.indexOf(r));for(let t=0,n=u.length;t<n;t++){let n=u[t];if(e[n]){c=e[n];break}}return c=(0,t.cloneLayout)(c||[]),(0,t.compact)((0,t.correctBounds)(c,{cols:o}),s,o)}function a(e){return Object.keys(e).sort(function(t,n){return e[t]-e[n]})}})),Uu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(ju()),r=Tu(),i=Du(),a=Hu(),o=c(Vu()),s=[`breakpoint`,`breakpoints`,`cols`,`layouts`,`margin`,`containerPadding`,`onBreakpointChange`,`onLayoutChange`,`onWidthChange`];function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u.apply(null,arguments)}function f(e,t){if(e==null)return{};var n,r,i=p(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function p(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?m(Object(n),!0).forEach(function(t){g(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function g(e,t,n){return(t=_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _(e){var t=v(e,`string`);return typeof t==`symbol`?t:t+``}function v(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var y=e=>Object.prototype.toString.call(e);function b(e,t){return e==null?null:Array.isArray(e)?e:e[t]}var x=class extends t.Component{constructor(){super(...arguments),g(this,`state`,this.generateInitialState()),g(this,`onLayoutChange`,e=>{this.props.onLayoutChange(e,h(h({},this.props.layouts),{},{[this.state.breakpoint]:e}))})}generateInitialState(){let{width:e,breakpoints:t,layouts:n,cols:r}=this.props,i=(0,a.getBreakpointFromWidth)(t,e),o=(0,a.getColsFromBreakpoint)(i,r),s=this.props.verticalCompact===!1?null:this.props.compactType;return{layout:(0,a.findOrGenerateResponsiveLayout)(n,t,i,i,o,s),breakpoint:i,cols:o}}static getDerivedStateFromProps(e,t){if(!(0,r.deepEqual)(e.layouts,t.layouts)){let{breakpoint:n,cols:r}=t;return{layout:(0,a.findOrGenerateResponsiveLayout)(e.layouts,e.breakpoints,n,n,r,e.compactType),layouts:e.layouts}}return null}componentDidUpdate(e){(this.props.width!=e.width||this.props.breakpoint!==e.breakpoint||!(0,r.deepEqual)(this.props.breakpoints,e.breakpoints)||!(0,r.deepEqual)(this.props.cols,e.cols))&&this.onWidthChange(e)}onWidthChange(e){let{breakpoints:t,cols:n,layouts:r,compactType:o}=this.props,s=this.props.breakpoint||(0,a.getBreakpointFromWidth)(this.props.breakpoints,this.props.width),c=this.state.breakpoint,l=(0,a.getColsFromBreakpoint)(s,n),u=h({},r);if(c!==s||e.breakpoints!==t||e.cols!==n){c in u||(u[c]=(0,i.cloneLayout)(this.state.layout));let e=(0,a.findOrGenerateResponsiveLayout)(u,t,s,c,l,o);e=(0,i.synchronizeLayoutWithChildren)(e,this.props.children,l,o,this.props.allowOverlap),u[s]=e,this.props.onBreakpointChange(s,l),this.props.onLayoutChange(e,u),this.setState({breakpoint:s,layout:e,cols:l})}let d=b(this.props.margin,s),f=b(this.props.containerPadding,s);this.props.onWidthChange(this.props.width,d,l,f)}render(){let e=this.props,{breakpoint:n,breakpoints:r,cols:i,layouts:a,margin:c,containerPadding:l,onBreakpointChange:d,onLayoutChange:p,onWidthChange:m}=e,h=f(e,s);return t.createElement(o.default,u({},h,{margin:b(c,this.state.breakpoint),containerPadding:b(l,this.state.breakpoint),onLayoutChange:this.onLayoutChange,layout:this.state.layout,cols:this.state.cols}))}};e.default=x,g(x,`propTypes`,{breakpoint:n.default.string,breakpoints:n.default.object,allowOverlap:n.default.bool,cols:n.default.object,margin:n.default.oneOfType([n.default.array,n.default.object]),containerPadding:n.default.oneOfType([n.default.array,n.default.object]),layouts(e,t){if(y(e[t])!==`[object Object]`)throw Error(`Layout property must be an object. Received: `+y(e[t]));Object.keys(e[t]).forEach(t=>{if(!(t in e.breakpoints))throw Error(`Each key in layouts must align with a key in breakpoints.`);(0,i.validateLayout)(e.layouts[t],`layouts.`+t)})},width:n.default.number.isRequired,onBreakpointChange:n.default.func,onLayoutChange:n.default.func,onWidthChange:n.default.func}),g(x,`defaultProps`,{breakpoints:{lg:1200,md:996,sm:768,xs:480,xxs:0},cols:{lg:12,md:10,sm:6,xs:4,xxs:2},containerPadding:{lg:null,md:null,sm:null,xs:null,xxs:null},layouts:{},margin:[10,10],allowOverlap:!1,onBreakpointChange:i.noop,onLayoutChange:i.noop,onWidthChange:i.noop})})),Wu=r({default:()=>yd});function Gu(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){id(a)}function s(){var e=Date.now();if(n){if(e-i<ad)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function Ku(e){return parseFloat(e)||0}function qu(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+Ku(r)},0)}function Ju(e){for(var t=[`top`,`right`,`bottom`,`left`],n={},r=0,i=t;r<i.length;r++){var a=i[r],o=e[`padding-`+a];n[a]=Ku(o)}return n}function Yu(e){var t=e.getBBox();return ed(0,0,t.width,t.height)}function Xu(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return fd;var r=dd(e).getComputedStyle(e),i=Ju(r),a=i.left+i.right,o=i.top+i.bottom,s=Ku(r.width),c=Ku(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=qu(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=qu(r,`top`,`bottom`)+o)),!Zu(e)){var l=Math.round(s+a)-t,u=Math.round(c+o)-n;Math.abs(l)!==1&&(s-=l),Math.abs(u)!==1&&(c-=u)}return ed(i.left,i.top,s,c)}function Zu(e){return e===dd(e).document.documentElement}function Qu(e){return nd?pd(e)?Yu(e):Xu(e):fd}function $u(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return ud(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function ed(e,t,n,r){return{x:e,y:t,width:n,height:r}}var td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd=t((()=>{td=(function(){if(typeof Map<`u`)return Map;function e(e,t){var n=-1;return e.some(function(e,r){return e[0]===t&&(n=r,!0)}),n}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(t){var n=e(this.__entries__,t),r=this.__entries__[n];return r&&r[1]},t.prototype.set=function(t,n){var r=e(this.__entries__,t);~r?this.__entries__[r][1]=n:this.__entries__.push([t,n])},t.prototype.delete=function(t){var n=this.__entries__,r=e(n,t);~r&&n.splice(r,1)},t.prototype.has=function(t){return!!~e(this.__entries__,t)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(e,t){t===void 0&&(t=null);for(var n=0,r=this.__entries__;n<r.length;n++){var i=r[n];e.call(t,i[1],i[0])}},t}()})(),nd=typeof window<`u`&&typeof document<`u`&&window.document===document,rd=(function(){return typeof global<`u`&&global.Math===Math?global:typeof self<`u`&&self.Math===Math?self:typeof window<`u`&&window.Math===Math?window:Function(`return this`)()})(),id=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(rd):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),ad=2,od=20,sd=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],cd=typeof MutationObserver<`u`,ld=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=Gu(this.refresh.bind(this),od)}return e.prototype.addObserver=function(e){~this.observers_.indexOf(e)||this.observers_.push(e),this.connected_||this.connect_()},e.prototype.removeObserver=function(e){var t=this.observers_,n=t.indexOf(e);~n&&t.splice(n,1),!t.length&&this.connected_&&this.disconnect_()},e.prototype.refresh=function(){this.updateObservers_()&&this.refresh()},e.prototype.updateObservers_=function(){var e=this.observers_.filter(function(e){return e.gatherActive(),e.hasActive()});return e.forEach(function(e){return e.broadcastActive()}),e.length>0},e.prototype.connect_=function(){!nd||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),cd?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener(`DOMSubtreeModified`,this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!nd||!this.connected_||(document.removeEventListener(`transitionend`,this.onTransitionEnd_),window.removeEventListener(`resize`,this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener(`DOMSubtreeModified`,this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(e){var t=e.propertyName,n=t===void 0?``:t;sd.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),ud=(function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];Object.defineProperty(e,i,{value:t[i],enumerable:!1,writable:!1,configurable:!0})}return e}),dd=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||rd}),fd=ed(0,0,0,0),pd=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof dd(e).SVGGraphicsElement}:function(e){return e instanceof dd(e).SVGElement&&typeof e.getBBox==`function`}})(),md=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=ed(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=Qu(this.target);return this.contentRect_=e,e.width!==this.broadcastWidth||e.height!==this.broadcastHeight},e.prototype.broadcastRect=function(){var e=this.contentRect_;return this.broadcastWidth=e.width,this.broadcastHeight=e.height,e},e}(),hd=function(){function e(e,t){var n=$u(t);ud(this,{target:e,contentRect:n})}return e}(),gd=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new td,typeof e!=`function`)throw TypeError(`The callback provided as parameter 1 is not a function.`);this.callback_=e,this.controller_=t,this.callbackCtx_=n}return e.prototype.observe=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof dd(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new md(e)),this.controller_.addObserver(this),this.controller_.refresh())}},e.prototype.unobserve=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof dd(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)&&(t.delete(e),t.size||this.controller_.removeObserver(this))}},e.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},e.prototype.gatherActive=function(){var e=this;this.clearActive(),this.observations_.forEach(function(t){t.isActive()&&e.activeObservations_.push(t)})},e.prototype.broadcastActive=function(){if(this.hasActive()){var e=this.callbackCtx_,t=this.activeObservations_.map(function(e){return new hd(e.target,e.broadcastRect())});this.callback_.call(e,t,e),this.clearActive()}},e.prototype.clearActive=function(){this.activeObservations_.splice(0)},e.prototype.hasActive=function(){return this.activeObservations_.length>0},e}(),_d=typeof WeakMap<`u`?new WeakMap:new td,vd=function(){function e(t){if(!(this instanceof e))throw TypeError(`Cannot call a class as a function.`);if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);var n=new gd(t,ld.getInstance(),this);_d.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){vd.prototype[e]=function(){var t;return(t=_d.get(this))[e].apply(t,arguments)}}),yd=(function(){return rd.ResizeObserver===void 0?vd:rd.ResizeObserver})()})),xd=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(ju()),i=s((bd(),e(Wu))),a=s($a()),o=[`measureBeforeMount`];function s(e){return e&&e.__esModule?e:{default:e}}function c(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(c=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(null,arguments)}function u(e,t){if(e==null)return{};var n,r,i=f(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function f(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`;function _(e){var t;return t=class extends n.Component{constructor(){super(...arguments),p(this,`state`,{width:1280}),p(this,`elementRef`,n.createRef()),p(this,`mounted`,!1),p(this,`resizeObserver`,void 0)}componentDidMount(){this.mounted=!0,this.resizeObserver=new i.default(e=>{if(this.elementRef.current instanceof HTMLElement){let t=e[0].contentRect.width;this.setState({width:t})}});let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.observe(e)}componentWillUnmount(){this.mounted=!1;let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.unobserve(e),this.resizeObserver.disconnect()}render(){let t=this.props,{measureBeforeMount:r}=t,i=u(t,o);return r&&!this.mounted?n.createElement(`div`,{className:(0,a.default)(this.props.className,g),style:this.props.style,ref:this.elementRef}):n.createElement(e,l({innerRef:this.elementRef},i,this.state))}},p(t,`defaultProps`,{measureBeforeMount:!1}),p(t,`propTypes`,{measureBeforeMount:r.default.bool}),t}})),Sd=n(i(((e,t)=>{t.exports=Vu().default,t.exports.utils=Du(),t.exports.calculateUtils=Ou(),t.exports.Responsive=Uu().default,t.exports.Responsive.utils=Hu(),t.exports.WidthProvider=xd().default}))(),1),Cd=new Map;function wd(e){Cd.set(e.type,e)}function Td(e){return Cd.get(e)}function Ed(){return[...Cd.values()]}function Dd(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,X.useState)(e.canvasQueries??[]),a=(0,X.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,X.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,X.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,X.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,X.useCallback)(()=>o([]),[o])}}function Od({config:e,canvas:t}){let n=typeof e.pageSize==`number`?e.pageSize:50,r=e.viewMode===`card`||e.viewMode===`tile`||e.viewMode===`table`?e.viewMode:`table`,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(1),[u,d]=(0,X.useState)(!0),f=t.canvasSort??xt,{queries:p,runSearch:m,removeQuery:h}=Dd(t,()=>l(1));(0,X.useEffect)(()=>{let e=!1;return(async()=>{d(!0);try{let r=await t.fetchDocuments({limit:n,page:c,sortBy:f.sortBy,order:f.order,queries:p.length?p:void 0});if(e)return;a(r.payload||[]),s(r.totalCount||r.count||0)}catch{e||(a([]),s(0))}finally{e||d(!1)}})(),()=>{e=!0}},[t,n,c,f.sortBy,f.order,p]);let g=(0,X.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(wt,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsx)(fn,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,serverSort:f,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}wd({type:`documents-table`,name:`Documents`,icon:Fn,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:Od});function kd({config:e,setConfig:t,canvas:n}){let[r,i]=(0,X.useState)(()=>new Date),a=e.format!==`24`;return(0,X.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,Z.jsx)(`div`,{className:`text-3xl font-semibold tabular-nums`,children:r.toLocaleTimeString(void 0,{hour12:a,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t({...e,format:a?`24`:`12`}),className:`mt-1 px-2 py-0.5 text-[10px] border rounded-md text-muted-foreground hover:bg-accent`,children:a?`12h`:`24h`})]})}wd({type:`clock`,name:`Clock`,icon:Zn,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:kd});var Ad=450,jd=10;function Md(e,t){let{open:n}=I(),r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.useRef)(!1),o=()=>{e&&n(e,t)},s=()=>{r.current&&=(clearTimeout(r.current),null)};return{activationProps:{role:`button`,tabIndex:0,onClick:()=>{if(a.current){a.current=!1;return}o()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},onContextMenu:e=>{e.preventDefault(),o()},onPointerDown:e=>{e.pointerType===`touch`&&(i.current={x:e.clientX,y:e.clientY},a.current=!1,s(),r.current=setTimeout(()=>{a.current=!0,o()},Ad))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>jd&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function Nd({doc:e,workspaceId:t}){let n=Ho(e),{activationProps:r}=Md(e,t);return(0,Z.jsxs)(`li`,{...r,title:`Open details`,className:`canvas-no-drag cursor-pointer py-1.5 min-w-0 rounded px-1 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function Pd({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!1;return(async()=>{o(!0);try{let r=await t.fetchDocuments({limit:n});if(e)return;i(r.payload||[]),c(null)}catch(t){if(e)return;c(t instanceof Error?t.message:`Failed to load documents`),i([])}finally{e||o(!1)}})(),()=>{e=!0}},[t,n]),a?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,Z.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,Z.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,Z.jsx)(Nd,{doc:e,workspaceId:t.workspaceId},e.id))})}wd({type:`recent-documents`,name:`Recent documents`,icon:hi,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:Pd});function Fd({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,Z.jsx)(`textarea`,{value:r,readOnly:n.readOnly,onChange:n=>t({...e,text:n.target.value}),placeholder:n.readOnly?``:`Jot something down…`,className:`canvas-no-drag w-full h-full resize-none bg-transparent text-sm leading-6 outline-none`})}wd({type:`note`,name:`Note`,icon:Da,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:Fd});var Id=`data/schema/file`,Ld=`data/schema/drawing`;function Rd(e){return(e.schema===Id||e.schema===Ld)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function zd(e){return e.schema===Id&&String(e.metadata?.contentType||``).startsWith(`video/`)}var Bd=`data/mime/image`;function Vd(e,t,n=!1){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(1),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=Dd(e,()=>c(1)),y=e.canvasSort??xt;(0,X.useEffect)(()=>{let r=!1,a=async()=>{u(!0),f(null);try{let a=await e.fetchDocuments({limit:t,page:s,queries:h.length?h:void 0,sortBy:y.sortBy,order:y.order,...n?{anyOf:[Bd,`data/mime/video`]}:{allOf:[Bd]}});if(r)return;i((a.payload||[]).filter(e=>Rd(e)||n&&zd(e))),o(a.totalCount||a.count||0)}catch(e){if(r)return;i([]),o(0),f(e instanceof Error?e.message:`Failed to load images`)}finally{r||u(!1)}};return a(),window.addEventListener(`workspace:documents:refresh`,a),()=>{r=!0,window.removeEventListener(`workspace:documents:refresh`,a)}},[e,t,s,h,y.sortBy,y.order,n]);let b=(0,X.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,X.useCallback)(()=>{m(``),v()},[v]),S=(0,X.useCallback)(e=>{_(e)},[_]),C=(0,X.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,X.useMemo)(()=>Math.max(1,Math.ceil(a/t)),[a,t]),input:p,setInput:m,submit:b,clearSearch:x,removeQuery:S,activeQueries:h,sort:y,setSort:C}}var Hd=n(h(),1);function Ud({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=z(e,t.id,512,{blobFallback:!zd(t),version:t.checksumArray?.[0]??null}),c=ts(t)||`image-${t.id}`,l=ls(t),u=l!==``&&i!==`off`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-(--card-radius) border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!zd(t)&&(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,Z.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-normal group-hover:scale-105`}),zd(t)&&(0,Z.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,Z.jsx)(Ar,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute inset-x-0 bottom-0 px-1.5 pb-1 pt-4 text-left text-[11px] leading-snug text-white bg-gradient-to-t from-black/75 via-black/45 to-transparent ${i===`reveal`?`caption-reveal`:``}`,children:(0,Z.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute right-1 top-1 rounded-full bg-black/55 p-1 text-white transition-opacity ${i===`reveal`?`hidden [@media(hover:hover)]:block [@media(hover:hover)]:group-hover:opacity-0`:``}`,title:`Has a comment`,children:(0,Z.jsx)(Rn,{className:`h-3 w-3`})})]})}function Wd({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Xc(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!zd(a)}),l=ts(a)||`image-${a.id}`,u=ls(a),[d,f]=(0,X.useState)(!1);return Ae(r),(0,X.useEffect)(()=>{let e=e=>{e.target?.closest(`video`)||(e.key===`ArrowLeft`&&n>0&&i(n-1),e.key===`ArrowRight`&&n<t.length-1&&i(n+1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,t.length,i]),(0,Hd.createPortal)((0,Z.jsxs)(`div`,{"data-scheme":`dark`,className:`fixed inset-0 z-fullscreen flex flex-col bg-scrim p-0 sm:p-4`,onClick:r,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:r,className:`canvas-no-drag absolute right-2 top-2 z-10 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20 touch-target sm:right-4 sm:top-4`,title:`Close`,children:(0,Z.jsx)(vr,{className:`h-5 w-5`})}),n>0&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n-1)},className:`canvas-no-drag absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Previous`,children:(0,Z.jsx)(Wn,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n+1)},className:`canvas-no-drag absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Next`,children:(0,Z.jsx)(Xa,{className:`h-6 w-6 touch-target`})}),(0,Z.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,Z.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),zd(a)&&(0,Z.jsx)(Kd,{workspaceId:e,doc:a},a.id),o&&(0,Z.jsx)(fe,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,Z.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,Z.jsx)(`span`,{className:`mx-auto mb-1 block max-w-2xl whitespace-pre-wrap text-sm text-foreground`,children:u}),l,` · `,n+1,`/`,t.length,!d&&!zd(a)&&(0,Z.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function Gd({workspaceId:e,state:t,comments:n,onToggleComments:r}){let{input:i,setInput:a,submit:o,clearSearch:s,removeQuery:c,activeQueries:l,sort:u,setSort:d,page:f,setPage:p,totalPages:m,totalCount:h,isLoading:g}=t,_=l.length>0;return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b px-1 pb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,Z.jsx)(qa,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()},placeholder:_?`Refine: add another query (Enter)…`:`Search media (Enter)…`,className:`h-7 w-full rounded-md border bg-background pl-7 pr-7 text-xs`}),_&&(0,Z.jsx)(`button`,{type:`button`,onClick:s,title:`Clear search`,className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}),_&&(0,Z.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(t),title:`Remove "${e}"`,className:`rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,Z.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-pressed":n!==`off`,title:n===`off`?`Show comments on tiles`:`Hide comments on tiles`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border touch-target ${n===`off`?`text-muted-foreground hover:bg-accent`:`border-primary/30 bg-primary/15 text-primary hover:bg-primary/25`}`,children:(0,Z.jsx)(Rn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(wt,{workspaceId:e,value:u,onChange:d}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,Z.jsx)(nn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,Z.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.max(1,f-1)),disabled:f<=1,title:`Previous page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.min(m,f+1)),disabled:f>=m,title:`Next page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(Xa,{className:`h-3.5 w-3.5`})})]})]})]})}function Kd({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=Jc(e,t.id);return(0,Z.jsxs)(Z.Fragment,{children:[r&&(0,Z.jsx)(`span`,{children:`Loading video…`}),i&&(0,Z.jsx)(`span`,{role:`alert`,children:i}),n&&(0,Z.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function qd({config:e,setConfig:t,canvas:n}){let r=Vd(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=tl()==null&&(n.interactive??!n.readOnly),[a,o]=(0,X.useState)(new Set),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),p=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[m,h]=(0,X.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Gd,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:_?`Loading media…`:y.length?`No images or videos match your search.`:`No images or videos in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(min(120px,100%),1fr))] gap-2 sm:grid-cols-[repeat(auto-fill,minmax(min(200px,100%),1fr))] sm:gap-3`,children:g.map((e,t)=>(0,Z.jsxs)(`div`,{className:`relative`,onContextMenu:t=>{i&&(t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,ids:a.has(e.id)?[...a]:[e.id]}))},children:[(0,Z.jsx)(Ud,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select document ${e.id}`,checked:a.has(e.id),onChange:()=>p(e.id),className:`canvas-no-drag absolute left-2 top-2 h-4 w-4 accent-primary`})]},e.id))})}),d&&(0,Z.jsx)(xn,{anchor:d,onClose:()=>f(null),label:`${d.ids.length} image${d.ids.length===1?``:`s`}`,items:[{id:`bulk-edit`,label:`Bulk edit… (${d.ids.length})`,icon:Lr,run:()=>u(d.ids)}]}),l&&(0,Z.jsx)(Ee,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,Z.jsx)(Wd,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}wd({type:`gallery`,name:`Gallery`,icon:Zi,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:qd});var Jd=150;function Yd(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function Xd(e){let t=e.metadata??{},n=e.data??{};return{w:Yd(t.width)||Yd(t.imageWidth)||Yd(n.width)||Yd(n.imageWidth),h:Yd(t.height)||Yd(t.imageHeight)||Yd(n.height)||Yd(n.imageHeight)}}function Zd(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=Xd(e),i=n&&r?n/r:0;return i>=1.5?{cols:2,rows:1}:i>0&&i<=.66?{cols:1,rows:2}:!i&&t%7==3?{cols:2,rows:1}:{cols:1,rows:1}}function Qd({config:e,setConfig:t,canvas:n}){let r=Vd(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,X.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Gd,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:s?`Loading images…`:l.length?`No images match your search.`:`No images in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${Jd}px, 1fr))`,gridAutoRows:`${Jd}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=Zd(e,t);return(0,Z.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,Z.jsx)(Ud,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,Z.jsx)(Wd,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}wd({type:`mosaic`,name:`Mosaic`,icon:Pa,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Qd});var $d=`data/schema/task`;function ef({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=A(e),[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=nc(e),l=i.status===`completed`,u=i.status??`pending`,d=Ne(i),{activationProps:f,stopRowActivation:p}=Md(e,t),m=async()=>{if(!(n||a)){o(!0);try{await N(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,Z.jsxs)(`div`,{...f,title:`Open details`,className:`canvas-no-drag flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-2.5 py-2 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${s?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{p(e),m()},disabled:n||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`canvas-no-drag mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${n?`cursor-default opacity-70`:``}`,children:a?(0,Z.jsx)(Ti,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,Z.jsx)(sr,{className:`h-3 w-3`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${D[u]}`,children:xe[u]}),i.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(_r,{className:`h-3 w-3`}),wn(i.dueDate)]}),typeof i.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,Z.jsx)(Ai,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function tf({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,X.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,X.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[$d],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===Qo))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,X.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,X.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>A(e).status!==`completed`):i,v=i.filter(e=>{let t=A(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,Z.jsx)(ef,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}wd({type:`todos`,name:`Todos`,icon:pa,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:tf});function nf(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var rf=`context`;function af(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:rf,path:`/`};if(n[2]===`trees`&&n[3]){let e=t(n[3]);if(n[4]!==`path`)return{treeName:e,path:`/`};let r=n.slice(5).map(t).join(`/`);return{treeName:e,path:r?`/${r}`:`/`}}if(n[2]===`path`){let e=n.slice(3).map(t).join(`/`);return{treeName:rf,path:e?`/${e}`:`/`}}return{treeName:rf,path:`/`}}function of(e,t,n){let r=n&&n!==rf?`/trees/${encodeURIComponent(n)}`:``,i=nf(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function sf({canvas:e}){return tl()!=null||!pu()?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,Z.jsx)(cf,{workspaceId:e.workspaceId},e.workspaceId)}function cf({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(`Workspace`),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([Ws(e),rc(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),c(null)}catch{if(t||a!==r)return;n([]),c(`Workspace pins are unavailable. Check your workspace access or try again.`)}finally{!t&&a===r&&o(!1)}},s=()=>{document.visibilityState===`visible`&&a()};a(),window.addEventListener(`focus`,s),document.addEventListener(`visibilitychange`,s);let l=B.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),l?.(),window.clearInterval(u)}},[e,l]),(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,Z.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>u(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,Z.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=Jt(t.color),i=(0,Z.jsxs)(Z.Fragment,{children:[n?(0,Z.jsx)(dr,{className:`h-5 w-5 shrink-0 text-warning`}):(0,Z.jsx)(f,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,Z.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,Z.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-(--card-radius) border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,Z.jsx)(`li`,{children:n?(0,Z.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,Z.jsx)(we,{to:of(e,t.path,t.tree),title:`Open ${t.tree}:${t.path}`,className:`${a} transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,style:o,children:i})},t.id)})}):(0,Z.jsx)(`p`,{className:`p-2 text-sm text-muted-foreground`,children:a?`Loading pins…`:`No workspace pins yet. Pin a folder from the workspace tree menu.`})})]})}wd({type:`workspace-pins`,name:`Workspace pins`,icon:tr,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:sf});function lf({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,X.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,Z.jsxs)(`div`,{className:c?u?`absolute inset-0 z-40 flex flex-col bg-background`:`fixed inset-0 z-50 flex flex-col bg-background`:`flex flex-col h-full rounded-(--card-radius) border bg-background overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`canvas-drag-handle flex items-center gap-2 px-2 py-1 border-b bg-muted/30 select-none ${o?``:`cursor-move`}`,children:[t&&(0,Z.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(uf,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:ga}),(0,Z.jsx)(uf,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:hr})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-accent touch-target`,title:c?`Restore`:`Full screen`,children:c?(0,Z.jsx)(ei,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(ba,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 touch-target`,title:`Remove widget`,children:(0,Z.jsx)(vr,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,Hd.createPortal)(d,u??document.body):d}function uf({on:e,onClick:t,label:n,icon:r}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-pressed":e,title:e?`${n} (on)`:n,className:`canvas-no-drag shrink-0 p-0.5 rounded touch-target ${e?`bg-primary/15 text-primary hover:bg-primary/25`:`text-muted-foreground hover:text-foreground hover:bg-accent`}`,children:(0,Z.jsx)(r,{className:`w-3.5 h-3.5`})})}var df=(0,Sd.WidthProvider)(Sd.default),ff=12,pf=80,mf=40,hf=[12,12],gf=[8,8],_f={w:!1,h:!1};function vf(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function yf(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function bf(e){let t=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t;return{...e,x:t(e.x,0),y:t(e.y,0),w:t(e.w,1),h:t(e.h,1)}}function xf(e,t,n=0){let r=n>0?n:vf(e);return e.map(e=>{let n=t[e.i]??_f;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?ff:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var Sf=4;function Cf(e,t,n=hf[1]){return Math.max(1,Math.ceil((e-n-Sf)/(t+n)))}var wf=45,Tf=640;function Ef(e,t,n=0,r){let i=[...xf(e,t,n)].sort((e,t)=>e.y-t.y||e.x-t.x),a=0;return i.map(e=>{let t=r?.(e.i)??0,n=Math.max(e.h,e.minH??1,t),i={...e,x:0,w:ff,y:a,h:n};return a+=n,i})}var Df=e=>e&&e.trim()?[e]:[];function Of(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(bf):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=ff,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function kf({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,metadata:a,isLocked:o=!1,readOnly:s=!1,interactive:c=!0,fetchDocuments:l,onSaved:u}){let d=!s,f=(0,X.useMemo)(()=>Of(a),[a]),[p,m]=(0,X.useState)(f.layout),[h,g]=(0,X.useState)(f.widgets),[_,v]=(0,X.useState)(f.fills),y=(0,X.useRef)(f.fills),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(!1),[A,j]=(0,X.useState)(0),M=(0,X.useRef)(0),N=(0,X.useCallback)(e=>{y.current=e,v(e)},[]),[P,ee]=(0,X.useState)(()=>Cn(i?.sort)),F=(0,X.useRef)(!1),[I,te]=(0,X.useState)(()=>Df(i?.query)),L=(0,X.useRef)(!1),R=(0,X.useRef)(null),ne=(0,X.useRef)(f),re=(0,X.useCallback)(e=>{let t=Td(h[e]?.type??``)?.mobileHeight;if(!(!t||A<=0))return Math.max(1,Math.round(A*t))},[h,A]),ie=(0,X.useMemo)(()=>O?Ef(p,_,A,re):xf(p,_,A),[p,_,O,A,re]),ae=O?mf:pf,z=(0,X.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,X.useEffect)(()=>{let e=Of(a);m(e.layout),g(e.widgets),N(e.fills),ne.current=e,ee(Cn(i?.sort)),F.current=!1,te(Df(i?.query)),L.current=!1,C(!1)},[n,r]),(0,X.useEffect)(()=>{if(!s)return;let e=Of(a);m(e.layout),g(e.widgets),N(e.fills),ne.current=e},[s,z,a,N]),(0,X.useEffect)(()=>{let e=R.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<Tf;k(n),M.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?gf:hf;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&j(Cf(t,n?mf:pf,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let oe=(0,X.useCallback)(e=>{ee(e),F.current=!0,C(!0)},[]),se=(0,X.useCallback)(e=>{te(e),L.current=!0,C(!0)},[]),B=(0,X.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:P,setCanvasSort:d?oe:void 0,canvasQueries:I,setCanvasQueries:d?se:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await Yo(e,n,t,{anyOf:r.anyOf,limit:0,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!i.length))return{payload:[],count:0,totalCount:0};let a=await Yo(e,n,t,{...r,anyOf:void 0,ids:i});return{payload:a.payload||[],count:a.count??void 0,totalCount:a.totalCount??void 0}})}),[e,t,n,r,i,d,c,l,P,oe,I,se]),ce=(0,X.useCallback)((e,t,n)=>{ne.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),V=(0,X.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:ne.current.widgets,layout:ne.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};ne.current={...r,fills:y.current};let o=F.current||L.current?{...i||{},...F.current?{sort:P.sortBy?P:null}:{},...L.current?{query:I.join(` `).trim()||null}:{}}:void 0;await zs(e,n,t,{...a||{},ui:r},o),F.current=!1,L.current=!1,C(!1),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t}})),u?.()}catch(e){let t=e instanceof Error?e.message:`Save failed`;D(t),console.error(`Failed to save canvas layout:`,e)}finally{T(!1)}}},[d,w,e,n,t,a,u,i,P,I]),le=(0,X.useCallback)(e=>{!d||O||m(t=>{let n=e.map(e=>{let n=t.find(t=>t.i===e.i),r=y.current[e.i];return n?{...e,x:r?.w?n.x:e.x,w:r?.w?n.w:e.w,y:r?.h?n.y:e.y,h:r?.h?n.h:e.h}:e});return ce(n,h),n})},[d,O,ce,h]),ue=(0,X.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??_f,i=hf[1]+(n.y+n.h)*(pf+hf[1]),a={w:n.x+n.w>=ff,h:M.current>0&&i>=M.current-wf};if(a.w||=r.w&&n.w===t.w,a.h||=r.h&&n.h===t.h,a.w===r.w&&a.h===r.h)return;let o={...y.current,[n.i]:a};N(o),ce(ne.current.layout,h,o)},[d,N,ce,h]),de=(0,X.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??_f,r={...y.current,[e]:{...n,[t]:!n[t]}};N(r),ce(p,h,r)},[d,N,ce,p,h]),fe=(0,X.useCallback)(e=>{let t=Td(e);if(!t)return;let n=crypto.randomUUID(),{w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}=t.defaultSize,l=[...p,{i:n,x:0,y:yf(ie),w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}],u={...h,[n]:{type:e,config:{...t.defaultConfig||{}}}},d={...y.current,[n]:{w:r>=ff,h:!1}};m(l),g(u),N(d),x(!1),ce(l,u,d)},[p,ie,h,N,ce]),pe=(0,X.useCallback)(e=>{let t=p.filter(t=>t.i!==e),n={...h};delete n[e];let r={...y.current};delete r[e],m(t),g(n),N(r),ce(t,n,r)},[p,h,N,ce]),me=(0,X.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return ce(p,r),r})},[p,ce]),he=Object.keys(h);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>x(e=>!e),className:`flex items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:[(0,Z.jsx)(br,{className:`w-3.5 h-3.5`}),`Add`,(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,Z.jsx)(`div`,{className:`absolute left-0 top-full mt-1 z-20 w-48 rounded-md border bg-popover shadow-elevation-2 py-1`,children:Ed().map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>fe(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,Z.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:V,disabled:!S||w,className:K(`flex shrink-0 items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs rounded-md transition-colors disabled:opacity-50`,S?`bg-primary text-primary-foreground hover:bg-primary`:`border hover:bg-accent`),children:[(0,Z.jsx)(Yn,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[he.length,` widget`,he.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,Z.jsx)(`div`,{ref:R,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:he.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,Z.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,Z.jsx)(df,{className:`layout`,layout:ie,cols:ff,rowHeight:ae,margin:O?gf:hf,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:le,onResizeStop:ue,compactType:`vertical`,children:he.map(e=>{let t=h[e],n=Td(t.type),r=_[e]??_f,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,Z.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,Z.jsx)(lf,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>pe(e),fill:_[e]??_f,onToggleFill:d?t=>de(e,t):void 0,children:(0,Z.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>me(e,t),canvas:B})}):(0,Z.jsx)(lf,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>pe(e),children:(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var Af=`data/schema/file`;function jf(e){return String(e.locations?.[0]?.url||``).trim()}function Mf(e){let t=jf(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function Nf(e){return e.schema===Af&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Pf(e){let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Ff(e){if(e.schema!==Af)return Ho(e);let t=Mf(e),n=String(e.metadata?.contentType||``).trim(),r=Pf(e.metadata?.size);return{...Ho(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:jf(e),schemaLabel:`file`}}function If(e){return/^https?:\/\/[^\s]+$/i.test(e)}function Lf(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return If(t)?t:null}return t.isExternal&&If(t.subtitle)?t.subtitle:If(t.title)?t.title:null}function Rf(e,t,n=!1){return Wc(e,t,{download:n})}function zf(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>If(e)?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`underline decoration-muted-foreground underline-offset-2 hover:text-primary`,children:e},`${e}-${t}`):e)}function Bf(e){return e?new Date(e).toLocaleString():``}function Vf(){let{code:e=``}=yt(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),d=(0,X.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=Ff(t);return[t.schema,n.title,n.preview,n.subtitle,Mf(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,X.useCallback)(async()=>{if(e){i(!0);try{let t=await J.get(`${yo}/pub/c/${encodeURIComponent(e)}`,{skipAuth:!0});n(t),o(null)}catch(e){n(null),o(e instanceof Error?e.message:`Failed to load public canvas`)}finally{i(!1)}}},[e]);(0,X.useEffect)(()=>{p()},[p]),(0,X.useEffect)(()=>{if(!e)return;let t=xo(`${bo}/pub`,{transports:[`websocket`],auth:{code:e},reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1500});return t.on(`connect`,()=>c(!0)),t.on(`disconnect`,()=>c(!1)),t.on(`connect_error`,()=>c(!1)),t.on(`canvas:changed`,()=>p()),()=>{t?.disconnect(),t=null}},[e,p]);let m=(0,X.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,X.useCallback)(()=>{u(``)},[]),g=(0,X.useCallback)(async e=>({payload:rs(e?.sortBy)?is(d,e.sortBy,e?.order):d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Z.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Z.jsxs)(zl,{className:`max-w-md bg-card`,children:[(0,Z.jsx)(Bl,{children:(0,Z.jsx)(Vl,{children:`Canvas unavailable`})}),(0,Z.jsx)(Ul,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Z.jsx)(au,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,Z.jsx)(qc.Provider,{value:e,children:(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Z.jsxs)(zl,{className:`bg-card shadow-elevation-3`,children:[(0,Z.jsx)(Bl,{className:`border-b p-3 sm:p-6`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Z.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-accent text-primary sm:mt-1 sm:h-12 sm:w-12 sm:rounded-2xl`,style:t.canvas.color?{borderLeft:`4px solid ${t.canvas.color}`}:void 0,children:(0,Z.jsx)(Pa,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground md:hidden`,children:[s?(0,Z.jsx)(Ja,{className:`h-3 w-3 text-success`}):(0,Z.jsx)(Hn,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Z.jsx)(Vl,{className:`mt-0.5 truncate text-2xl sm:mt-1 sm:text-3xl md:text-5xl`,children:t.canvas.label||t.canvas.name||`Canvas`}),t.canvas.description&&(0,Z.jsx)(`p`,{className:`mt-1.5 max-w-3xl text-sm text-muted-foreground sm:mt-3 sm:text-base`,children:t.canvas.description})]})]}),(0,Z.jsxs)(`div`,{className:`hidden shrink-0 items-center gap-2 rounded-full border px-3 py-1 text-xs text-muted-foreground md:flex`,children:[s?(0,Z.jsx)(Ja,{className:`h-3.5 w-3.5 text-success`}):(0,Z.jsx)(Hn,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Z.jsxs)(Ul,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Z.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,Z.jsxs)(`span`,{className:`truncate`,children:[`· `,Bf(t.stats.refreshedAt)]})]}),(0,Z.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Z.jsx)(Hf,{label:`Path`,value:t.share.path,mono:!0}),(0,Z.jsx)(Hf,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Z.jsx)(Hf,{label:`Shown`,value:String(f.length)}),(0,Z.jsx)(Hf,{label:`Refreshed`,value:Bf(t.stats.refreshedAt)})]}),v&&(0,Z.jsx)(`section`,{id:`content-area`,className:`flex w-full flex-col overflow-hidden rounded-2xl border h-viewport-card min-h-[420px] md:h-viewport-pane`,children:(0,Z.jsx)(kf,{workspaceId:t.workspace.name,treeName:t.share.treeName,path:t.share.path,layerId:t.canvas.id,querySpec:t.canvas.querySpec,metadata:t.canvas.metadata,readOnly:!0,interactive:!1,fetchDocuments:g},JSON.stringify(_))}),!v&&(0,Z.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 border-b px-4 py-3 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Z.jsx)(qa,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`search`,value:l,onChange:e=>u(e.target.value),placeholder:`Search loaded documents...`,className:`w-full rounded-md border py-1.5 pl-9 pr-8 text-sm md:w-72`}),l&&(0,Z.jsx)(`button`,{type:`button`,onClick:h,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:p,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,Z.jsx)(Er,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,Z.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,Z.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,Z.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:l.trim()?`No loaded documents match your search.`:`No documents yet.`}):f.map(t=>{let n=Ff(t),r=Lf(t,n),i=t.schema===Af,a=i?Rf(e,t.id):null,o=a||r;return(0,Z.jsxs)(`article`,{className:`p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Z.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Z.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Z.jsxs)(`a`,{href:Rf(e,t.id,!0),download:n.title,className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(zi,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Z.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:Bf(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Z.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:zf(n.preview)}),Nf(t)&&(0,Z.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Z.jsx)(`img`,{src:a||void 0,alt:n.title,loading:`lazy`,className:`max-h-64 max-w-full rounded border bg-muted object-contain transition-opacity hover:opacity-90`})})]},t.id)})})]})]})]}),(0,Z.jsx)(au,{className:`mt-6 text-center`})]})})})}function Hf({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var Uf=`false`,Wf=`false`,Gf=Uf===`true`,Kf=Wf===`true`;function qf(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,Gf||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await g(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!Kf){if(Gf)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}}c.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}var Jf=new Set,Yf=!1,Xf=qf({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){Yf=!0,Jf.forEach(e=>e())}});function Zf(e){return Jf.add(e),Yf&&e(),()=>{Jf.delete(e)}}function Qf(){Xf(!0)}function $f(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>Zf(()=>t(!0)),[]),!e||n?null:(0,Z.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>Qf(),className:`flex items-center gap-1 rounded-full bg-foreground px-3 py-1 text-xs font-medium text-background hover:bg-foreground/90`,children:[(0,Z.jsx)(Er,{className:`h-3 w-3`}),` Reload`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(!0),"aria-label":`Not now`,className:`rounded-full p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})})}var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,np=(e,t)=>{for(var n in t)ep(e,n,{get:t[n],enumerable:!0})},rp=(e,t,n,r)=>{for(var i=r>1?void 0:r?tp(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&ep(t,n,i),i},ip=(e,t)=>(n,r)=>t(n,r,e),ap=`Terminal input`,op={get:()=>ap,set:e=>ap=e},sp=`Too much output to announce, navigate to rows manually to read`,cp={get:()=>sp,set:e=>sp=e};function lp(e){return e.replace(/\r?\n/g,`\r`)}function up(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function dp(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function fp(e,t,n,r){e.stopPropagation(),e.clipboardData&&pp(e.clipboardData.getData(`text/plain`),t,n,r)}function pp(e,t,n,r){e=lp(e),e=up(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function mp(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function hp(e,t,n,r,i){mp(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function gp(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function _p(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var vp=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},yp=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},bp=``,xp=` `,Sp=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Cp}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Cp=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},wp=class e extends Sp{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Cp,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?gp(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Tp=`di$target`,Ep=`di$dependencies`,Dp=new Map;function Op(e){return e[Ep]||[]}function kp(e){if(Dp.has(e))return Dp.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Ap(t,e,r)};return t._id=e,Dp.set(e,t),t}function Ap(e,t,n){t[Tp]===t?t[Ep].push({id:e,index:n}):(t[Ep]=[{id:e,index:n}],t[Tp]=t)}var jp=kp(`BufferService`),Mp=kp(`CoreMouseService`),Np=kp(`CoreService`),Pp=kp(`CharsetService`),Fp=kp(`InstantiationService`),Ip=kp(`LogService`),Lp=kp(`OptionsService`),Rp=kp(`OscLinkService`),zp=kp(`UnicodeService`),Bp=kp(`DecorationService`),Vp=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new wp,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(!(c===-1&&!n.hasContent(t))){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):Hp(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};Vp=rp([ip(0,jp),ip(1,Lp),ip(2,Rp)],Vp);function Hp(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
5
|
+
|
|
6
|
+
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var Up=kp(`CharSizeService`),Wp=kp(`CoreBrowserService`),Gp=kp(`MouseService`),Kp=kp(`RenderService`),qp=kp(`SelectionService`),Jp=kp(`CharacterJoinerService`),Yp=kp(`ThemeService`),Xp=kp(`LinkProviderService`),Zp=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?rm.isErrorNoTelemetry(e)?new rm(e.message+`
|
|
7
|
+
|
|
8
|
+
`+e.stack):Error(e.message+`
|
|
9
|
+
|
|
10
|
+
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function Qp(e){em(e)||Zp.onUnexpectedError(e)}var $p=`Canceled`;function em(e){return e instanceof tm||e instanceof Error&&e.name===$p&&e.message===$p}var tm=class extends Error{constructor(){super($p),this.name=this.message}};function nm(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var rm=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},im=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function am(e,t=0){return e[e.length-(1+t)]}var om;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(om||={});var sm=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||om.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};sm.empty=new sm(e=>{});function cm(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var lm;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(lm||={});var um=null;function dm(e){return um?.trackDisposable(e),e}function fm(e){um?.markAsDisposed(e)}function pm(e,t){um?.setParent(e,t)}function mm(e){return um?.markAsSingleton(e),e}function hm(e){if(lm.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function gm(...e){return _m(()=>hm(e))}function _m(e){let t=dm({dispose:cm(()=>{fm(t),e()})});return t}var vm=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,dm(this)}dispose(){this._isDisposed||(fm(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{hm(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return pm(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),pm(e,null))}};vm.DISABLE_DISPOSED_WARNING=!1;var ym=vm,bm=class{constructor(){this._store=new ym,dm(this),pm(this._store,this)}dispose(){fm(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};bm.None=Object.freeze({dispose(){}});var xm=class{constructor(){this._isDisposed=!1,dm(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&pm(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,fm(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&pm(e,null),e}},Sm=typeof window==`object`?window:globalThis,Cm=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Cm.Undefined=new Cm(void 0);var wm=Cm,Tm=class{constructor(){this._first=wm.Undefined,this._last=wm.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===wm.Undefined}clear(){let e=this._first;for(;e!==wm.Undefined;){let t=e.next;e.prev=wm.Undefined,e.next=wm.Undefined,e=t}this._first=wm.Undefined,this._last=wm.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new wm(e);if(this._first===wm.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==wm.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==wm.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==wm.Undefined&&e.next!==wm.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===wm.Undefined&&e.next===wm.Undefined?(this._first=wm.Undefined,this._last=wm.Undefined):e.next===wm.Undefined?(this._last=this._last.prev,this._last.next=wm.Undefined):e.prev===wm.Undefined&&(this._first=this._first.next,this._first.prev=wm.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==wm.Undefined;)yield e.element,e=e.next}},Em=globalThis.performance&&typeof globalThis.performance.now==`function`,Dm=class e{static create(t){return new e(t)}constructor(e){this._now=Em&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Om;(e=>{e.None=()=>bm.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(gm(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new Q({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new Q({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new Q({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Q({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Q({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new Q;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new Q(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof ym?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(Om||={});var km=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Dm,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};km.all=new Set,km._idPool=0;var Am=km,jm=-1,Mm=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Fm(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Mm._idPool=1;var Nm=Mm,Pm=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
|
|
11
|
+
`).slice(2).join(`
|
|
12
|
+
`))}},Fm=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Im=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},Lm=0,Rm=class{constructor(e){this.value=e,this.id=Lm++}},zm=2,Bm,Q=class{constructor(e){this._size=0,this._options=e,this._leakageMon=jm>0||this._options?.leakWarningThreshold?new Nm(e?.onListenerError??Qp,this._options?.leakWarningThreshold??jm):void 0,this._perfMon=this._options?._profName?new Am(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Im(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||Qp)(n),bm.None}if(this._disposed)return bm.None;t&&(e=e.bind(t));let r=new Rm(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Pm.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Rm?(this._deliveryQueue??=new Vm,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=_m(()=>{Bm?.unregister(a),i?.(),this._removeListener(r)});if(n instanceof ym?n.add(a):Array.isArray(n)&&n.push(a),Bm){let e=Error().stack.split(`
|
|
13
|
+
`).slice(2,3).join(`
|
|
14
|
+
`).trim(),t=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(e);Bm.register(a,t?.[2]??e,a)}return a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*zm<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||Qp;if(!n){e.value(t);return}try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof Rm)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},Vm=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Hm=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Q,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Q,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};Hm.INSTANCE=new Hm;var Um=Hm;function Wm(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}Um.INSTANCE.onDidChangeZoomLevel;function Gm(e){return Um.INSTANCE.getZoomFactor(e)}Um.INSTANCE.onDidChangeFullscreen;var Km=typeof navigator==`object`?navigator.userAgent:``,qm=Km.indexOf(`Firefox`)>=0,Jm=Km.indexOf(`AppleWebKit`)>=0,Ym=Km.indexOf(`Chrome`)>=0,Xm=!Ym&&Km.indexOf(`Safari`)>=0;Km.indexOf(`Electron/`),Km.indexOf(`Android`);var Zm=!1;if(typeof Sm.matchMedia==`function`){let e=Sm.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=Sm.matchMedia(`(display-mode: fullscreen)`);Zm=e.matches,Wm(Sm,e,({matches:e})=>{Zm&&t.matches||(Zm=e)})}function Qm(){return Zm}var $m=`en`,eh=!1,th=!1,nh=!1,rh=!1,ih=!1,ah=$m,oh,sh=globalThis,ch;typeof sh.vscode<`u`&&typeof sh.vscode.process<`u`?ch=sh.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(ch=process);var lh=typeof ch?.versions?.electron==`string`&&ch?.type===`renderer`;if(typeof ch==`object`){eh=ch.platform===`win32`,th=ch.platform===`darwin`,nh=ch.platform===`linux`,nh&&ch.env.SNAP&&ch.env.SNAP_REVISION,ch.env.CI||ch.env.BUILD_ARTIFACTSTAGINGDIRECTORY,ah=$m;let e=ch.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,ah=t.resolvedLanguage||$m,t.languagePack?.translationsConfigFile}catch{}rh=!0}else typeof navigator==`object`&&!lh?(oh=navigator.userAgent,eh=oh.indexOf(`Windows`)>=0,th=oh.indexOf(`Macintosh`)>=0,(oh.indexOf(`Macintosh`)>=0||oh.indexOf(`iPad`)>=0||oh.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,nh=oh.indexOf(`Linux`)>=0,oh?.indexOf(`Mobi`),ih=!0,ah=globalThis._VSCODE_NLS_LANGUAGE||$m,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var uh=eh,dh=th,fh=nh,ph=rh;ih&&typeof sh.importScripts==`function`&&sh.origin;var mh=oh,hh=ah,gh;(e=>{function t(){return hh}e.value=t;function n(){return hh.length===2?hh===`en`:hh.length>=3&&hh[0]===`e`&&hh[1]===`n`&&hh[2]===`-`}e.isDefaultVariant=n;function r(){return hh===`en`}e.isDefault=r})(gh||={});var _h=typeof sh.postMessage==`function`&&!sh.importScripts;(()=>{if(_h){let e=[];sh.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),sh.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var vh=!!(mh&&mh.indexOf(`Chrome`)>=0);mh&&mh.indexOf(`Firefox`),!vh&&mh&&mh.indexOf(`Safari`),mh&&mh.indexOf(`Edg/`),mh&&mh.indexOf(`Android`);var yh=typeof navigator==`object`?navigator:{};ph||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||yh&&yh.clipboard&&yh.clipboard.writeText,ph||yh&&yh.clipboard&&yh.clipboard.readText,ph||Qm()||yh.keyboard,`ontouchstart`in Sm||yh.maxTouchPoints,Sm.PointerEvent&&(`ontouchstart`in Sm||navigator.maxTouchPoints);var bh=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},xh=new bh,Sh=new bh,Ch=new bh,wh=Array(230),Th;(e=>{function t(e){return xh.keyCodeToStr(e)}e.toString=t;function n(e){return xh.strToKeyCode(e)}e.fromString=n;function r(e){return Sh.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Ch.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Sh.strToKeyCode(e)||Ch.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return xh.keyCodeToStr(e)}e.toElectronAccelerator=o})(Th||={});var Eh=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Dh([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Dh=class{constructor(e){if(e.length===0)throw nm(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function Oh(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Th.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(qm)switch(t){case 59:return 85;case 60:if(fh)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(dh)return 57;break}else if(Jm&&(dh&&t===93||!dh&&t===92))return 57;return wh[t]||0}var kh=dh?256:2048,Ah=512,jh=1024,Mh=dh?2048:256,Nh=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=Oh(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=kh),this.altKey&&(t|=Ah),this.shiftKey&&(t|=jh),this.metaKey&&(t|=Mh),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new Eh(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Ph=new WeakMap;function Fh(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var Ih=class{static getSameOriginWindowChain(e){let t=Ph.get(e);if(!t){t=[],Ph.set(e,t);let n=e,r;do r=Fh(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},Lh=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=Ih.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Rh=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(Ym){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?qm&&!dh?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=Xm&&uh?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?qm&&!dh?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},zh=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Bh;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Vh?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Om.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:zh})})(Bh||={});var Vh=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?zh:(this._emitter||=new Q,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},Hh=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new im(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new im(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Uh=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new im(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=_m(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var Wh;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(Wh||={});var Gh=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Q,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await Om.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};Gh.EMPTY=Gh.fromArray([]);function Kh(e){return qh(e,0)}function qh(e,t){switch(typeof e){case`object`:return e===null?Jh(349,t):Array.isArray(e)?Zh(e,t):Qh(e,t);case`string`:return Xh(e,t);case`boolean`:return Yh(e,t);case`number`:return Jh(e,t);case`undefined`:return Jh(937,t);default:return Jh(617,t)}}function Jh(e,t){return(t<<5)-t+e|0}function Yh(e,t){return Jh(e?433:863,t)}function Xh(e,t){t=Jh(149417,t);for(let n=0,r=e.length;n<r;n++)t=Jh(e.charCodeAt(n),t);return t}function Zh(e,t){return t=Jh(104579,t),e.reduce((e,t)=>qh(t,e),t)}function Qh(e,t){return t=Jh(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=Xh(n,t),qh(e[n],t)),t)}var{registerWindow:$h,getWindow:eg,getDocument:tg,getWindows:ng,getWindowsCount:rg,getWindowId:ig,getWindowById:ag,hasWindow:og,onDidRegisterWindow:sg,onWillUnregisterWindow:cg,onDidUnregisterWindow:lg}=function(){let e=new Map,t={window:Sm,disposables:new ym};e.set(Sm.vscodeWindowId,t);let n=new Q,r=new Q,i=new Q;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return bm.None;let a=new ym,o={window:t,disposables:a.add(new ym)};return e.set(t.vscodeWindowId,o),a.add(_m(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(dg(t,bg.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:Sm},getDocument(e){return eg(e).document}}}(),ug=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function dg(e,t,n,r){return new ug(e,t,n,r)}function fg(e,t){return function(n){return t(new Lh(e,n))}}function pg(e){return function(t){return e(new Nh(t))}}var mg=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=fg(eg(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=pg(n)),dg(e,t,i,r)},hg,gg=class extends Uh{constructor(e){super(),this.defaultTarget=e&&eg(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},_g=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){Qp(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(_g.sort),a.shift().execute();r.set(i,!1)};hg=(t,r,a=0)=>{let o=ig(t),s=new _g(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var vg=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};vg.None=new vg(0,0);function yg(e){let t=e.getBoundingClientRect(),n=eg(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=Kh(n),a=r.get(i);if(a)a.users+=1;else{let o=new Q,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(_m(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var bg={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:Jm?`webkitAnimationStart`:`animationstart`,ANIMATION_END:Jm?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:Jm?`webkitAnimationIteration`:`animationiteration`},xg=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=Sg(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Sg(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Sg(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Sg(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Sg(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Sg(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Sg(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Sg(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Sg(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Sg(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Sg(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Sg(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Sg(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Sg(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Sg(e){return typeof e==`number`?`${e}px`:e}function Cg(e){return new xg(e)}var wg=class{constructor(){this._hooks=new ym,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(_m(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=eg(e)}this._hooks.add(dg(a,bg.POINTER_MOVE,e=>{if(e.buttons!==n){this.stopMonitoring(!0);return}e.preventDefault(),this._pointerMoveCallback(e)})),this._hooks.add(dg(a,bg.POINTER_UP,e=>this.stopMonitoring(!0)))}};function Tg(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Eg;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Eg||={});var Dg=class e extends bm{constructor(){super(),this.dispatched=!1,this.targets=new Tm,this.ignoreTargets=new Tm,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Om.runAndSubscribe(sg,({window:e,disposables:t})=>{t.add(dg(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(dg(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(dg(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:Sm,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=mm(new e),_m(e.INSTANCE.targets.push(t))):bm.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=mm(new e),_m(e.INSTANCE.ignoreTargets.push(t))):bm.None}static isTouchDevice(){return`ontouchstart`in Sm||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(Eg.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-am(s.rollingPageX))<30&&Math.abs(s.initialPageY-am(s.rollingPageY))<30){let e=this.newGestureEvent(Eg.Tap,s.initialTarget);e.pageX=am(s.rollingPageX),e.pageY=am(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-am(s.rollingPageX))<30&&Math.abs(s.initialPageY-am(s.rollingPageY))<30){let e=this.newGestureEvent(Eg.Contextmenu,s.initialTarget);e.pageX=am(s.rollingPageX),e.pageY=am(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=am(s.rollingPageX),n=am(s.rollingPageY),i=am(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Eg.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Eg.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Eg.Change||t.type===Eg.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=hg(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Eg.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(Eg.Change,i.initialTarget);a.translationX=r.pageX-am(i.rollingPageX),a.translationY=r.pageY-am(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Dg.SCROLL_FRICTION=-.005,Dg.HOLD_DELAY=700,Dg.CLEAR_TAP_COUNT_TIME=400,rp([Tg],Dg,`isTouchDevice`,1);var Og=Dg,kg=class extends bm{onclick(e,t){this._register(dg(e,bg.CLICK,n=>t(new Lh(eg(e),n))))}onmousedown(e,t){this._register(dg(e,bg.MOUSE_DOWN,n=>t(new Lh(eg(e),n))))}onmouseover(e,t){this._register(dg(e,bg.MOUSE_OVER,n=>t(new Lh(eg(e),n))))}onmouseleave(e,t){this._register(dg(e,bg.MOUSE_LEAVE,n=>t(new Lh(eg(e),n))))}onkeydown(e,t){this._register(dg(e,bg.KEY_DOWN,e=>t(new Nh(e))))}onkeyup(e,t){this._register(dg(e,bg.KEY_UP,e=>t(new Nh(e))))}oninput(e,t){this._register(dg(e,bg.INPUT,t))}onblur(e,t){this._register(dg(e,bg.BLUR,t))}onfocus(e,t){this._register(dg(e,bg.FOCUS,t))}onchange(e,t){this._register(dg(e,bg.CHANGE,t))}ignoreGesture(e){return Og.ignoreTarget(e)}},Ag=11,jg=class extends kg{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Ag+`px`,this.domNode.style.height=Ag+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new wg),this._register(mg(this.bgDomNode,bg.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(mg(this.domNode,bg.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new gg),this._pointerdownScheduleRepeatTimer=this._register(new Hh)}_arrowPointerDown(e){!e.target||!(e.target instanceof Element)||(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,eg(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Mg=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Ng=class extends bm{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Mg(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Lg(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Lg.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Pg=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Fg(e,t){let n=t-e;return function(t){return e+n*zg(t)}}function Ig(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Lg=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),Ig(Fg(e,r),Fg(i,t),.33)}return Fg(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new Pg(this.scrollLeft(t),this.scrollTop(t),!1):new Pg(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function Rg(e){return e**3}function zg(e){return 1-Rg(1-e)}var Bg=class extends bm{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Hh)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},Vg=140,Hg=class extends kg{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Bg(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new wg),this._shouldRender=!0,this.domNode=Cg(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(dg(this.domNode.domNode,bg.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new jg(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Cg(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(dg(this.slider.domNode,bg.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=yg(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(uh&&a>Vg){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Ug=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},Wg=class extends Hg{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Ug(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Gg=class extends Hg{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Ug(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Kg=500,qg=50,Jg=!0,Yg=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},Xg=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(!0);return t<=.5}acceptStandardWheelEvent(e){if(Ym){let t=Gm(eg(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new Yg(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};Xg.INSTANCE=new Xg;var Zg=Xg,Qg=class extends kg{constructor(e,t,n){super(),this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Q),this.onWillScroll=this._onWillScroll.event,this._options=e_(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Gg(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new Wg(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Cg(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Cg(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Cg(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new Hh),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=hm(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,dh&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Rh(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=hm(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(dg(this._listenOnDomNode,bg.MOUSE_WHEEL,e=>{this._onMouseWheel(new Rh(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=Zg.INSTANCE;Jg&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!dh&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=qg*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=qg*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(Jg&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Kg)}},$g=class extends Qg{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function e_(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,dh&&(t.className+=` mac`),t}var t_=class extends bm{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Ng({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>hg(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new $g(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Om.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(_m(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(_m(()=>this._styleElement.remove())),this._register(Om.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
|
|
15
|
+
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};t_=rp([ip(2,jp),ip(3,Wp),ip(4,Mp),ip(5,Yp),ip(6,Lp),ip(7,Kp)],t_);var n_=class extends bm{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(_m(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};n_=rp([ip(1,jp),ip(2,Wp),ip(3,Bp),ip(4,Kp)],n_);var r_=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},i_={full:0,left:0,center:0,right:0},a_={full:0,left:0,center:0,right:0},o_={full:0,left:0,center:0,right:0},s_=class extends bm{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new r_,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(_m(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);a_.full=this._canvas.width,a_.left=e,a_.center=t,a_.right=e,this._refreshDrawHeightConstants(),o_.full=1,o_.left=1,o_.center=1+a_.left,o_.right=1+a_.left+a_.center}_refreshDrawHeightConstants(){i_.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);i_.left=t,i_.center=t,i_.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*i_.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*i_.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*i_.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*i_.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(o_[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-i_[e.position||`full`]/2),a_[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+i_[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};s_=rp([ip(2,jp),ip(3,Bp),ip(4,Kp),ip(5,Lp),ip(6,Yp),ip(7,Wp)],s_);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
16
|
+
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var c_;(e=>(e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``))(c_||={});var l_;(e=>e.ST=`${$.ESC}\\`)(l_||={});var u_=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};u_=rp([ip(2,jp),ip(3,Lp),ip(4,Np),ip(5,Kp)],u_);var d_=0,f_=0,p_=0,m_=0,h_={css:`#00000000`,rgba:0},g_;(e=>{function t(e,t,n,r){return r===void 0?`#${x_(e)}${x_(t)}${x_(n)}`:`#${x_(e)}${x_(t)}${x_(n)}${x_(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(g_||={});var __;(e=>{function t(e,t){if(m_=(t.rgba&255)/255,m_===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return d_=a+Math.round((n-a)*m_),f_=o+Math.round((r-o)*m_),p_=s+Math.round((i-s)*m_),{css:g_.toCss(d_,f_,p_),rgba:g_.toRgba(d_,f_,p_)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=b_.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return g_.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[d_,f_,p_]=b_.toChannels(t),{css:g_.toCss(d_,f_,p_),rgba:t}}e.opaque=i;function a(e,t){return m_=Math.round(t*255),[d_,f_,p_]=b_.toChannels(e.rgba),{css:g_.toCss(d_,f_,p_,m_),rgba:g_.toRgba(d_,f_,p_,m_)}}e.opacity=a;function o(e,t){return m_=e.rgba&255,a(e,m_*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(__||={});var v_;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return d_=parseInt(e.slice(1,2).repeat(2),16),f_=parseInt(e.slice(2,3).repeat(2),16),p_=parseInt(e.slice(3,4).repeat(2),16),g_.toColor(d_,f_,p_);case 5:return d_=parseInt(e.slice(1,2).repeat(2),16),f_=parseInt(e.slice(2,3).repeat(2),16),p_=parseInt(e.slice(3,4).repeat(2),16),m_=parseInt(e.slice(4,5).repeat(2),16),g_.toColor(d_,f_,p_,m_);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return d_=parseInt(r[1]),f_=parseInt(r[2]),p_=parseInt(r[3]),m_=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),g_.toColor(d_,f_,p_,m_);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[d_,f_,p_,m_]=t.getImageData(0,0,1,1).data,m_!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:g_.toRgba(d_,f_,p_,m_),css:e}}e.toColor=r})(v_||={});var y_;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(y_||={});var b_;(e=>{function t(e,t){if(m_=(t&255)/255,m_===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return d_=a+Math.round((n-a)*m_),f_=o+Math.round((r-o)*m_),p_=s+Math.round((i-s)*m_),g_.toRgba(d_,f_,p_)}e.blend=t;function n(e,t,n){let a=y_.relativeLuminance(e>>8),o=y_.relativeLuminance(t>>8);if(S_(a,o)<n){if(o<a){let o=r(e,t,n),s=S_(a,y_.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>S_(a,y_.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=S_(a,y_.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>S_(a,y_.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=S_(y_.relativeLuminance2(o,s,c),y_.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=S_(y_.relativeLuminance2(o,s,c),y_.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=S_(y_.relativeLuminance2(o,s,c),y_.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=S_(y_.relativeLuminance2(o,s,c),y_.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(b_||={});function x_(e){let t=e.toString(16);return t.length<2?`0`+t:t}function S_(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var C_=class extends Sp{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},w_=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new wp}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||xp.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)w_._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||xp.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};w_=rp([ip(0,jp)],w_);function T_(e){return 57508<=e&&e<=57558}function E_(e){return 9472<=e&&e<=9631}function D_(e){return T_(e)||E_(e)}function O_(){return{css:{canvas:k_(),cell:k_()},device:{canvas:k_(),cell:k_(),char:{width:0,height:0,left:0,top:0}}}}function k_(){return{width:0,height:0}}var A_=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new wp,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let A=!1,j=k>=E,M=k,N=this._workCell;if(f.length>0&&k===f[0][0]&&j){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)j&&=i===this._isCellInSelection(v,t);j&&=!n||a<r[0]||a>=r[1],j?(A=!0,N=new C_(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),M=r[1]-1,m=N.getWidth()):E=r[1]}let P=this._isCellInSelection(k,t),ee=n&&k===a,F=O&&k>=l&&k<=u,I=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{I=!0});let te=N.getChars()||xp;if(te===` `&&(N.isUnderline()||N.isOverline())&&(te=`\xA0`),T=m*s-c.get(te,N.isBold(),N.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(P&&w||!P&&!w&&N.bg===y)&&(P&&w&&p.selectionForeground||N.fg===b)&&N.extended.ext===x&&F===S&&T===C&&!ee&&!A&&!I&&j){N.isInvisible()?_+=xp:_+=te,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=N.bg,b=N.fg,x=N.extended.ext,S=F,C=T,w=P,A&&a>=k&&a<=M&&(a=k),!this._coreService.isCursorHidden&&ee&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`);break;default:break}}if(N.isBold()&&D.push(`xterm-bold`),N.isItalic()&&D.push(`xterm-italic`),N.isDim()&&D.push(`xterm-dim`),_=N.isInvisible()?xp:N.getChars()||xp,N.isUnderline()&&(D.push(`xterm-underline-${N.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!N.isUnderlineColorDefault())){if(N.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${Sp.toColorRGB(N.getUnderlineColor()).join(`,`)})`;else{let e=N.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&N.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}N.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),N.isStrikethrough()&&D.push(`xterm-strikethrough`),F&&(h.style.textDecoration=`underline`);let L=N.getFgColor(),R=N.getFgColorMode(),ne=N.getBgColor(),re=N.getBgColorMode(),ie=!!N.isInverse();if(ie){let e=L;L=ne,ne=e;let t=R;R=re,re=t}let ae,z,oe=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&oe||(e.backgroundColorRGB&&(re=50331648,ne=e.backgroundColorRGB.rgba>>8&16777215,ae=e.backgroundColorRGB),e.foregroundColorRGB&&(R=50331648,L=e.foregroundColorRGB.rgba>>8&16777215,z=e.foregroundColorRGB),oe=e.options.layer===`top`)}),!oe&&P&&(ae=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,ne=ae.rgba>>8&16777215,re=50331648,oe=!0,p.selectionForeground&&(R=50331648,L=p.selectionForeground.rgba>>8&16777215,z=p.selectionForeground)),oe&&D.push(`xterm-decoration-top`);let se;switch(re){case 16777216:case 33554432:se=p.ansi[ne],D.push(`xterm-bg-${ne}`);break;case 50331648:se=g_.toColor(ne>>16,ne>>8&255,ne&255),this._addStyle(h,`background-color:#${j_((ne>>>0).toString(16),`0`,6)}`);break;default:ie?(se=p.foreground,D.push(`xterm-bg-257`)):se=p.background}switch(ae||N.isDim()&&(ae=__.multiplyOpacity(se,.5)),R){case 16777216:case 33554432:N.isBold()&&L<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(L+=8),this._applyMinimumContrast(h,se,p.ansi[L],N,ae,void 0)||D.push(`xterm-fg-${L}`);break;case 50331648:let e=g_.toColor(L>>16&255,L>>8&255,L&255);this._applyMinimumContrast(h,se,e,N,ae,z)||this._addStyle(h,`color:#${j_(L.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,se,p.foreground,N,ae,z)||ie&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!ee&&!A&&!I&&j?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=M}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||D_(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=__.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};A_=rp([ip(1,Jp),ip(2,Lp),ip(3,Wp),ip(4,Np),ip(5,Bp),ip(6,Yp)],A_);function j_(e,t,n){for(;e.length<n;)e=t+e;return e}var M_=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},N_=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function P_(){return new N_}var F_=`xterm-dom-renderer-owner-`,I_=`xterm-rows`,L_=`xterm-fg-`,R_=`xterm-bg-`,z_=`xterm-focus`,B_=`xterm-selection`,V_=1,H_=class extends bm{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=V_++,this._rowElements=[],this._selectionRenderModel=P_(),this.onRequestRedraw=this._register(new Q).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(I_),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(B_),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=O_(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(A_,document),this._element.classList.add(F_+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(_m(()=>{this._element.classList.remove(F_+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new M_(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${I_} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${I_} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${I_} .xterm-dim { color: ${__.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${I_}.${z_} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${I_}.${z_} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${I_}.${z_} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${I_} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${I_} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${I_} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${I_} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${I_} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${B_} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${B_} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${B_} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${L_}${n} { color: ${r.css}; }${this._terminalSelector} .${L_}${n}.xterm-dim { color: ${__.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${R_}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${L_}257 { color: ${__.opaque(e.background).css}; }${this._terminalSelector} .${L_}257.xterm-dim { color: ${__.multiplyOpacity(__.opaque(e.background),.5).css}; }${this._terminalSelector} .${R_}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(z_),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(z_),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${F_}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};H_=rp([ip(7,Fp),ip(8,Up),ip(9,Lp),ip(10,jp),ip(11,Np),ip(12,Wp),ip(13,Yp)],H_);var U_=class extends bm{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Q),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new K_(this._optionsService))}catch{this._measureStrategy=this._register(new G_(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};U_=rp([ip(2,Lp)],U_);var W_=class extends bm{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},G_=class extends W_{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},K_=class extends W_{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},q_=class extends bm{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new J_(this._window)),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Q),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Om.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(dg(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(dg(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},J_=class extends bm{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new xm),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(_m(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=dg(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Y_=class extends bm{constructor(){super(),this.linkProviders=[],this._register(_m(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function X_(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function Z_(e,t,n,r,i,a,o,s,c){if(!a)return;let l=X_(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var Q_=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return Z_(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=X_(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};Q_=rp([ip(0,Kp),ip(1,Up)],Q_);var $_=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},ev={};np(ev,{getSafariVersion:()=>sv,isChromeOS:()=>pv,isFirefox:()=>iv,isIpad:()=>lv,isIphone:()=>uv,isLegacyEdge:()=>av,isLinux:()=>fv,isMac:()=>cv,isNode:()=>tv,isSafari:()=>ov,isWindows:()=>dv});var tv=typeof process<`u`&&`title`in process,nv=tv?`node`:navigator.userAgent,rv=tv?`node`:navigator.platform,iv=nv.includes(`Firefox`),av=nv.includes(`Edge`),ov=/^((?!chrome|android).)*safari/i.test(nv);function sv(){if(!ov)return 0;let e=nv.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var cv=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(rv),lv=rv===`iPad`,uv=rv===`iPhone`,dv=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(rv),fv=rv.indexOf(`Linux`)>=0,pv=/\bCrOS\b/.test(nv),mv=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},hv=class extends mv{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},gv=class extends mv{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},_v=!tv&&`requestIdleCallback`in window?gv:hv,vv=class{constructor(){this._queue=new _v}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},yv=class extends bm{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new xm),this._pausedResizeTask=new vv,this._observerDisposable=this._register(new xm),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Q),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Q),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Q),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new $_((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new bv(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(_m(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=_m(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};yv=rp([ip(2,Lp),ip(3,Up),ip(4,Np),ip(5,Bp),ip(6,jp),ip(7,Wp),ip(8,Yp)],yv);var bv=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function xv(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return wv(i,a,e,t,n,r)+Tv(a,t,n,r)+Ev(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,Nv(Math.abs(i-e),Mv(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return Nv(Cv(a>t?e:i,n)+(s-1)*n.cols+1+Sv(a>t?i:e,n),Mv(o,r))}function Sv(e,t){return e-1}function Cv(e,t){return t.cols-e}function wv(e,t,n,r,i,a){return Tv(t,r,i,a).length===0?``:Nv(jv(e,t,e,t-Ov(t,i),!1,i).length,Mv(`D`,a))}function Tv(e,t,n,r){let i=e-Ov(e,n),a=t-Ov(t,n);return Nv(Math.abs(i-a)-Dv(e,t,n),Mv(Av(e,t),r))}function Ev(e,t,n,r,i,a){let o;o=Tv(t,r,i,a).length>0?r-Ov(r,i):t;let s=r,c=kv(e,t,n,r,i,a);return Nv(jv(e,o,n,s,c===`C`,i).length,Mv(c,a))}function Dv(e,t,n){let r=0,i=e-Ov(e,n),a=t-Ov(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Av(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function Ov(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function kv(e,t,n,r,i,a){let o;return o=Tv(n,r,i,a).length>0?r-Ov(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Av(e,t){return e>t?`A`:`B`}function jv(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Mv(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function Nv(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var Pv=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Fv(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var Iv=50,Lv=15,Rv=50,zv=500,Bv=RegExp(`\xA0`,`g`),Vv=class extends bm{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new wp,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Q),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Q),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new Pv(this._bufferService),this._activeSelectionMode=0,this._register(_m(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(Bv,` `)).join(dv?`\r
|
|
17
|
+
`:`
|
|
18
|
+
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),fv&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=Fv(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=X_(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Iv),Iv),t/=Iv,t/Math.abs(t)+Math.round(t*(Lv-1)))}shouldForceSelection(e){return cv?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Rv)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(cv&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<zv&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=xv(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!n){this._oldHasSelection&&this._fireOnSelectionChange(e,t,n);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(!(!t&&o.slice(s,c).trim()===``)){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Fv(n,this._bufferService.cols)}};Vv=rp([ip(3,jp),ip(4,Np),ip(5,Gp),ip(6,Lp),ip(7,Kp),ip(8,Wp)],Vv);var Hv=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Uv=class{constructor(){this._color=new Hv,this._css=new Hv}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Wv=Object.freeze((()=>{let e=[v_.toColor(`#2e3436`),v_.toColor(`#cc0000`),v_.toColor(`#4e9a06`),v_.toColor(`#c4a000`),v_.toColor(`#3465a4`),v_.toColor(`#75507b`),v_.toColor(`#06989a`),v_.toColor(`#d3d7cf`),v_.toColor(`#555753`),v_.toColor(`#ef2929`),v_.toColor(`#8ae234`),v_.toColor(`#fce94f`),v_.toColor(`#729fcf`),v_.toColor(`#ad7fa8`),v_.toColor(`#34e2e2`),v_.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:g_.toCss(r,i,a),rgba:g_.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:g_.toCss(n,n,n),rgba:g_.toRgba(n,n,n)})}return e})()),Gv=v_.toColor(`#ffffff`),Kv=v_.toColor(`#000000`),qv=v_.toColor(`#ffffff`),Jv=Kv,Yv={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},Xv=Gv,Zv=class extends bm{constructor(e){super(),this._optionsService=e,this._contrastCache=new Uv,this._halfContrastCache=new Uv,this._onChangeColors=this._register(new Q),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Gv,background:Kv,cursor:qv,cursorAccent:Jv,selectionForeground:void 0,selectionBackgroundTransparent:Yv,selectionBackgroundOpaque:__.blend(Kv,Yv),selectionInactiveBackgroundTransparent:Yv,selectionInactiveBackgroundOpaque:__.blend(Kv,Yv),scrollbarSliderBackground:__.opacity(Gv,.2),scrollbarSliderHoverBackground:__.opacity(Gv,.4),scrollbarSliderActiveBackground:__.opacity(Gv,.5),overviewRulerBorder:Gv,ansi:Wv.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Qv(e.foreground,Gv),t.background=Qv(e.background,Kv),t.cursor=__.blend(t.background,Qv(e.cursor,qv)),t.cursorAccent=__.blend(t.background,Qv(e.cursorAccent,Jv)),t.selectionBackgroundTransparent=Qv(e.selectionBackground,Yv),t.selectionBackgroundOpaque=__.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Qv(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=__.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Qv(e.selectionForeground,h_):void 0,t.selectionForeground===h_&&(t.selectionForeground=void 0),__.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=__.opacity(t.selectionBackgroundTransparent,.3)),__.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=__.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Qv(e.scrollbarSliderBackground,__.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Qv(e.scrollbarSliderHoverBackground,__.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Qv(e.scrollbarSliderActiveBackground,__.opacity(t.foreground,.5)),t.overviewRulerBorder=Qv(e.overviewRulerBorder,Xv),t.ansi=Wv.slice(),t.ansi[0]=Qv(e.black,Wv[0]),t.ansi[1]=Qv(e.red,Wv[1]),t.ansi[2]=Qv(e.green,Wv[2]),t.ansi[3]=Qv(e.yellow,Wv[3]),t.ansi[4]=Qv(e.blue,Wv[4]),t.ansi[5]=Qv(e.magenta,Wv[5]),t.ansi[6]=Qv(e.cyan,Wv[6]),t.ansi[7]=Qv(e.white,Wv[7]),t.ansi[8]=Qv(e.brightBlack,Wv[8]),t.ansi[9]=Qv(e.brightRed,Wv[9]),t.ansi[10]=Qv(e.brightGreen,Wv[10]),t.ansi[11]=Qv(e.brightYellow,Wv[11]),t.ansi[12]=Qv(e.brightBlue,Wv[12]),t.ansi[13]=Qv(e.brightMagenta,Wv[13]),t.ansi[14]=Qv(e.brightCyan,Wv[14]),t.ansi[15]=Qv(e.brightWhite,Wv[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=Qv(e.extendedAnsi[r],Wv[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};Zv=rp([ip(0,Lp)],Zv);function Qv(e,t){if(e!==void 0)try{return v_.toColor(e)}catch{}return t}var $v=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},ey=class{constructor(){this._services=new $v,this._services.set(Fp,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Op(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},ty={trace:0,debug:1,info:2,warn:3,error:4,off:5},ny=`xterm.js: `,ry=class extends bm{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),iy=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=ty[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:ny)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};ry=rp([ip(0,Lp)],ry);var iy,ay=class extends bm{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Q),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Q),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Q),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},oy=3,sy=Object.freeze(new Sp),cy=0,ly=2,uy=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*oy);let r=t||wp.fromCharData([0,bp,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*oy+0],n=t&2097151;return[this._data[e*oy+1],t&2097152?this._combined[e]:n?gp(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*oy+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*oy+0]=e|2097152|t[2]<<22):this._data[e*oy+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*oy+0]>>22}hasWidth(e){return this._data[e*oy+0]&12582912}getFg(e){return this._data[e*oy+1]}getBg(e){return this._data[e*oy+2]}hasContent(e){return this._data[e*oy+0]&4194303}getCodePoint(e){let t=this._data[e*oy+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*oy+0]&2097152}getString(e){let t=this._data[e*oy+0];return t&2097152?this._combined[e]:t&2097151?gp(t&2097151):``}isProtected(e){return this._data[e*oy+2]&536870912}loadCell(e,t){return cy=e*oy,t.content=this._data[cy+0],t.fg=this._data[cy+1],t.bg=this._data[cy+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*oy+0]=t.content,this._data[e*oy+1]=t.fg,this._data[e*oy+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*oy+0]=t|n<<22,this._data[e*oy+1]=r.fg,this._data[e*oy+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*oy+0];r&2097152?this._combined[e]+=gp(t):r&2097151?(this._combined[e]=gp(r&2097151)+gp(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*oy+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new wp;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new wp;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r){for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;return}for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*ly<this._data.buffer.byteLength;let n=e*oy;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*ly<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*ly<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t){for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);return}this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*oy+0]&4194303)return e+(this._data[e*oy+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*oy+0]&4194303||this._data[e*oy+2]&50331648)return e+(this._data[e*oy+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<oy;e++)this._data[(n+i)*oy+e]=a[(t+i)*oy+e];a[(t+i)*oy+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<oy;e++)this._data[(n+i)*oy+e]=a[(t+i)*oy+e];a[(t+i)*oy+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*oy+0],n=e&2097151,a=e&2097152?this._combined[t]:n?gp(n):xp;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function dy(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=hy(u,d,t),p=1,m=0;for(;p<u.length;){let e=hy(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function fy(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function py(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function my(e,t,n){let r=[],i=e.map((n,r)=>hy(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=hy(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function hy(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var gy=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Q),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),hm(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};gy._nextId=1;var _y=gy,vy={},yy=vy.B;vy[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},vy.A={"#":`£`},vy.B=void 0,vy[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},vy.C=vy[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},vy.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},vy.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},vy.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},vy.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},vy.E=vy[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},vy.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},vy.H=vy[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},vy[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var by=4294967295,xy=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=sy.clone(),this.savedCharset=yy,this.markers=[],this._nullCell=wp.fromCharData([0,bp,1,0]),this._whitespaceCell=wp.fromCharData([0,xp,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new _v,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new ay(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Cp),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Cp),this._whitespaceCell}getBlankLine(e,t){return new uy(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>by?by:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=sy);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new ay(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(sy),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new uy(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new uy(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=dy(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(sy),n);if(r.length>0){let n=fy(this.lines,r);py(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(sy),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new uy(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(sy),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=my(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(sy,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=hy(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new _y(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Sy=class extends bm{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Q),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new xy(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new xy(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Cy=2,wy=1,Ty=class extends bm{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Cy),this.rows=Math.max(e.rawOptions.rows||0,wy),this.buffers=this._register(new Sy(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Ty=rp([ip(0,Lp)],Ty);var Ey={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:cv,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Dy=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Oy=class extends bm{constructor(e){super(),this._onOptionChange=this._register(new Q),this.onOptionChange=this._onOptionChange.event;let t={...Ey};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(_m(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Ey))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Ey))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Ey[e],!ky(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Ey[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Dy.includes(t)?t:Ey[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function ky(e){return e===`block`||e===`underline`||e===`bar`}function Ay(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Ay(e[r],t-1);return n}var jy=Object.freeze({insertMode:!1}),My=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Ny=class extends bm{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Q),this.onData=this._onData.event,this._onUserInput=this._register(new Q),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Q),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Ay(jy),this.decPrivateModes=Ay(My)}reset(){this.modes=Ay(jy),this.decPrivateModes=Ay(My)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Ny=rp([ip(0,jp),ip(1,Ip),ip(2,Lp)],Ny);var Py={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function Fy(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Iy=String.fromCharCode,Ly={DEFAULT:e=>{let t=[Fy(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Iy(t[0])}${Iy(t[1])}${Iy(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Fy(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Fy(e,!0)};${e.x};${e.y}${t}`}},Ry=class extends bm{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Q),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Py))this.addProtocol(e,Py[e]);for(let e of Object.keys(Ly))this.addEncoding(e,Ly[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};Ry=rp([ip(0,jp),ip(1,Np),ip(2,Lp)],Ry);var zy=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],By=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Vy;function Hy(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var Uy=class{constructor(){if(this.version=`6`,!Vy){Vy=new Uint8Array(65536),Vy.fill(1),Vy[0]=0,Vy.fill(0,1,32),Vy.fill(0,127,160),Vy.fill(2,4352,4448),Vy[9001]=2,Vy[9002]=2,Vy.fill(2,11904,42192),Vy[12351]=1,Vy.fill(2,44032,55204),Vy.fill(2,63744,64256),Vy.fill(2,65040,65050),Vy.fill(2,65072,65136),Vy.fill(2,65280,65377),Vy.fill(2,65504,65511);for(let e=0;e<zy.length;++e)Vy.fill(0,zy[e][0],zy[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Vy[e]:Hy(e,By)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=Wy.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Wy.createPropertyValue(0,n,r)}},Wy=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Q,this.onChange=this._onChange.event;let e=new Uy;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},Gy=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Ky(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var qy=2147483647,Jy=256,Yy=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>Jy)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>qy?qy:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>qy?qy:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,qy):e}},Xy=[],Zy=class{constructor(){this._state=0,this._active=Xy,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Xy}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Xy,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Xy,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,_p(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=Xy,this._id=-1,this._state=0}}},Qy=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=_p(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},$y=[],eb=class{constructor(){this._handlers=Object.create(null),this._active=$y,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=$y}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=$y,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||$y,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,_p(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=$y,this._ident=0}},tb=new Yy;tb.addParam(0);var nb=class{constructor(e){this._handler=e,this._data=``,this._params=tb,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():tb,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=_p(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=tb,this._data=``,this._hitLimit=!1,e));return this._params=tb,this._data=``,this._hitLimit=!1,t}},rb=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},ib=160,ab=function(){let e=new rb(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(ib,0,2,0),e.add(ib,8,5,8),e.add(ib,6,0,6),e.add(ib,11,0,11),e.add(ib,13,13,13),e}(),ob=class extends bm{constructor(e=ab){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Yy,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(_m(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Zy),this._dcsParser=this._register(new eb),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:ib)],i>>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r<ib){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<ib){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<ib){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<ib){this._printHandler(e,n,i),n=i-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<ib){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<ib){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},sb=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,cb=/^[\da-f]+$/;function lb(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=sb.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),cb.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function ub(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function db(e,t=16){let[n,r,i]=e;return`rgb:${ub(n,t)}/${ub(r,t)}/${ub(i,t)}`}var fb={"(":0,")":1,"*":2,"+":3,"-":1,".":2},pb=131072,mb=10;function hb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var gb=5e3,_b=0,vb=class extends bm{constructor(e,t,n,r,i,a,o,s,c=new ob){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new vp,this._utf8Decoder=new yp,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=sy.clone(),this._eraseAttrDataInternal=sy.clone(),this._onRequestBell=this._register(new Q),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Q),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Q),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Q),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Q),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Q),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Q),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Q),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Q),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Q),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Q),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Q),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new yb(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(c_.IND,()=>this.index()),this._parser.setExecuteHandler(c_.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(c_.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Qy(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new Qy(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new Qy(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new Qy(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new Qy(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new Qy(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new Qy(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new Qy(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new Qy(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new Qy(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new Qy(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new Qy(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in vy)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new nb((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),gb))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${gb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>pb&&(a=this._parseStack.position+pb)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<pb&&(this._parseBuffer=new Uint32Array(Math.min(e.length,pb))),o||this._dirtyRowTracker.clearRange(),e.length>pb)for(let t=a;t<e.length;t+=pb){let a=t+pb<e.length?t+pb:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=Wy.extractWidth(t);let n=Wy.extractShouldJoin(t),m=n?Wy.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(gp(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof uy&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!hb(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new nb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Qy(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(sy));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=Wy.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,yy),this._charsetService.setgCharset(1,yy),this._charsetService.setgCharset(2,yy),this._charsetService.setgCharset(3,yy);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Sp.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=sy.fg,e.bg=sy.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=sy.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=sy.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=sy.fg&16777215,r.bg&=-67108864,r.bg|=sy.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=sy.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!hb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>mb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>mb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(bb(n)){if(r===`?`)t.push({type:0,index:n});else{let e=lb(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=lb(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);bb(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,yy),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(fb[e[0]],vy[e[1]]||yy),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=sy.clone(),this._eraseAttrDataInternal=sy.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new wp;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},yb=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(_b=e,e=t,t=_b),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yb=rp([ip(0,jp)],yb);function bb(e){return 0<=e&&e<256}var xb=5e7,Sb=12,Cb=50,wb=class extends bm{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>xb)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=Sb?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=Sb)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Cb&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Tb=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Tb=rp([ip(0,jp)],Tb);var Eb=!1,Db=class extends bm{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new xm),this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onData=this._register(new Q),this.onData=this._onData.event,this._onLineFeed=this._register(new Q),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Q),this._instantiationService=new ey,this.optionsService=this._register(new Oy(e)),this._instantiationService.setService(Lp,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Ty)),this._instantiationService.setService(jp,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(ry)),this._instantiationService.setService(Ip,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Ny)),this._instantiationService.setService(Np,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Ry)),this._instantiationService.setService(Mp,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Wy)),this._instantiationService.setService(zp,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Gy),this._instantiationService.setService(Pp,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Tb),this._instantiationService.setService(Rp,this._oscLinkService),this._inputHandler=this._register(new vb(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Om.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Om.forward(this._bufferService.onResize,this._onResize)),this._register(Om.forward(this.coreService.onData,this._onData)),this._register(Om.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new wb((e,t)=>this._inputHandler.parse(e,t))),this._register(Om.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Q),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Eb&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Eb=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Cy),t=Math.max(t,wy),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Ky.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(Ky(this._bufferService),!1))),this._windowsWrappingHeuristics.value=_m(()=>{for(let t of e)t.dispose()})}}},Ob={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function kb(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=Ob[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var Ab=0,jb=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new _v,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new _v,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Ab=this._search(t),Ab===-1)||this._getKey(this._array[Ab])!==t)return!1;do if(this._array[Ab]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Ab),!0;while(++Ab<this._array.length&&this._getKey(this._array[Ab])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Ab=this._search(e),!(Ab<0||Ab>=this._array.length)&&this._getKey(this._array[Ab])===e))do yield this._array[Ab];while(++Ab<this._array.length&&this._getKey(this._array[Ab])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Ab=this._search(e),!(Ab<0||Ab>=this._array.length)&&this._getKey(this._array[Ab])===e))do t(this._array[Ab]);while(++Ab<this._array.length&&this._getKey(this._array[Ab])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Mb=0,Nb=0,Pb=class extends bm{constructor(){super(),this._decorations=new jb(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Q),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Q),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(_m(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Fb(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{Mb=t.options.x??0,Nb=Mb+(t.options.width??1),e>=Mb&&e<Nb&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},Fb=class extends ym{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Q),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Q),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?v_.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?v_.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Ib=1e3,Lb=class{constructor(e,t=Ib){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Rb=20,zb=class extends bm{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Lb(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
19
|
+
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(dg(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(_m(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Rb+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
|
|
20
|
+
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Rb+1&&(this._liveRegion.textContent+=cp.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(!(!a||!o)){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};zb=rp([ip(1,Fp),ip(2,Wp),ip(3,Kp)],zb);var Bb=class extends bm{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Q),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Q),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(_m(()=>{hm(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(dg(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(dg(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(dg(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(dg(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Vb(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,hm(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Bb=rp([ip(1,Gp),ip(2,Kp),ip(3,jp),ip(4,Xp)],Bb);function Vb(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var Hb=class extends Db{constructor(e={}){super(e),this._linkifier=this._register(new xm),this.browser=ev,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new xm),this._onCursorMove=this._register(new Q),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Q),this.onKey=this._onKey.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Q),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Q),this.onBell=this._onBell.event,this._onFocus=this._register(new Q),this._onBlur=this._register(new Q),this._onA11yCharEmitter=this._register(new Q),this._onA11yTabEmitter=this._register(new Q),this._onWillOpen=this._register(new Q),this._setup(),this._decorationService=this._instantiationService.createInstance(Pb),this._instantiationService.setService(Bp,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Y_),this._instantiationService.setService(Xp,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Vp)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Om.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Om.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Om.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Om.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(_m(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=__.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${db(r)}${l_.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=g_.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=g_.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(zb,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(dg(this.element,`copy`,e=>{this.hasSelection()&&dp(e,this._selectionService)}));let e=e=>fp(e,this.textarea,this.coreService,this.optionsService);this._register(dg(this.textarea,`paste`,e)),this._register(dg(this.element,`paste`,e)),iv?this._register(dg(this.element,`mousedown`,e=>{e.button===2&&hp(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(dg(this.element,`contextmenu`,e=>{hp(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),fv&&this._register(dg(this.element,`auxclick`,e=>{e.button===1&&mp(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(dg(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(dg(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(dg(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(dg(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(dg(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(dg(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(dg(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(dg(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,op.get()),pv||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(q_,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(Wp,this._coreBrowserService),this._register(dg(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(dg(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(U_,this._document,this._helperContainer),this._instantiationService.setService(Up,this._charSizeService),this._themeService=this._instantiationService.createInstance(Zv),this._instantiationService.setService(Yp,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(w_),this._instantiationService.setService(Jp,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(yv,this.rows,this.screenElement)),this._instantiationService.setService(Kp,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(u_,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Q_),this._instantiationService.setService(Gp,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Bb,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(t_,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Vv,this.element,this.screenElement,r)),this._instantiationService.setService(qp,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Om.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(n_,this.screenElement)),this._register(dg(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(zb,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(s_,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(s_,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(H_,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(dg(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(e)))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(dg(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){pp(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=kb(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Ub(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(sy));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function Ub(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Wb=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},Gb=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new wp)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Kb=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new Gb(t)}getNullCell(){return new wp}},qb=class extends bm{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Q),this.onBufferChange=this._onBufferChange.event,this._normal=new Kb(this._core.buffers.normal,`normal`),this._alternate=new Kb(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},Jb=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},Yb=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},Xb=[`cols`,`rows`],Zb=0,Qb=class extends bm{constructor(e){super(),this._core=this._register(new Hb(e)),this._addonManager=this._register(new Wb),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(Xb.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new Jb(this._core),this._parser}get unicode(){return this._checkProposedApi(),new Yb(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new qb(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
21
|
+
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return op.get()},set promptLabel(e){op.set(e)},get tooMuchOutput(){return cp.get()},set tooMuchOutput(e){cp.set(e)}}}_verifyIntegers(...e){for(Zb of e)if(Zb===1/0||isNaN(Zb)||Zb%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(Zb of e)if(Zb&&(Zb===1/0||isNaN(Zb)||Zb%1!=0||Zb<0))throw Error(`This API only accepts positive integers`)}},$b=2,ex=1,tx=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max($b,Math.floor(u/e.css.cell.width)),rows:Math.max(ex,Math.floor(l/e.css.cell.height))}}},nx=(0,X.createContext)(void 0);function rx(){let e=(0,X.useContext)(nx),t=ul()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,X.useMemo)(()=>e===void 0?n?r===`context`&&i?{mode:`context`,contextId:i}:a&&o?{mode:`workspace`,workspaceName:a,path:o,treeName:s||`context`,treeType:s===`directory`||s===`backends`?`directory`:`context`}:null:null:e,[e,n,r,i,a,o,s])}var ix=(0,X.createContext)(null),ax=()=>(0,X.useContext)(ix);function ox({session:e,transport:t,report:n}){let r=(0,X.useRef)(null),i=(0,X.useRef)(n);return i.current=n,(0,X.useEffect)(()=>{if(!r.current)return;let n=new Qb({cursorBlink:!0,scrollback:1e4,fontSize:14,fontFamily:`monospace`,theme:{background:`#111418`,foreground:`#e4e8ee`},allowProposedApi:!1}),a=new tx;n.loadAddon(a),n.open(r.current);let o=!1,s=0,c,l=e=>{o||i.current(e)},u=()=>{!r.current||r.current.clientWidth===0||r.current.clientHeight===0||(a.fit(),t.resize(e.id,n.cols,n.rows).catch(l))},d=new ResizeObserver(u);d.observe(r.current),u();let f=n.onData(n=>{t.write(e.id,n).catch(l)}),p=n.onBinary(n=>{t.write(e.id,Uint8Array.from(n,e=>e.charCodeAt(0))).catch(l)});n.attachCustomKeyEventHandler(e=>e.type===`keydown`&&e.ctrlKey&&e.shiftKey&&e.code===`KeyC`?(navigator.clipboard.writeText(n.getSelection()).catch(l),!1):!(e.ctrlKey&&!e.shiftKey&&[`KeyT`,`KeyN`,`KeyW`,`Tab`,`PageUp`,`PageDown`].includes(e.code)));let m=async()=>{try{let r;do{if(r=await t.read(e.id,s),o)return;s<r.start&&n.reset(),s=r.offset,r.data.length&&await new Promise(e=>n.write(Uint8Array.from(r.data),e))}while(r.data.length===65536&&!o);if(!r.running){n.write(`\r
|
|
22
|
+
\x1B[90m[Process exited]\x1B[0m\r
|
|
23
|
+
`);return}c=setTimeout(()=>{m()},50)}catch(e){l(e)}};return m(),n.focus(),()=>{o=!0,clearTimeout(c),d.disconnect(),f.dispose(),p.dispose(),n.dispose()}},[e.id,t]),(0,Z.jsx)(`div`,{ref:r,className:`min-h-0 flex-1 overflow-hidden p-2`,style:{background:`#111418`},"aria-label":`Terminal screen`})}function sx(){let e=rx(),t=ax(),n=e?.mode===`workspace`?JSON.stringify([`workspace`,e.workspaceName,e.treeName,e.treeType,`/`+e.path.split(`/`).filter(Boolean).join(`/`)]):e?.mode===`context`?JSON.stringify([`context`,e.contextId]):``;return t?n?(0,Z.jsx)(cx,{scope:n,transport:t},n):(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:`Choose a context to open its terminals.`}):(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:`Local terminals are available in Canvas Desktop.`})}function cx({scope:e,transport:t}){let[n,r]=(0,X.useState)([]),i=`terminal:selected:${e}`,[a,o]=(0,X.useState)(()=>localStorage.getItem(i)||``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!0),h=e=>u(String(e));(0,X.useEffect)(()=>{let n=!1,i=async()=>{try{let i=await t.list(e);n||(r(i),m(!1))}catch(e){n||(h(e),m(!1))}};i();let a=setInterval(()=>{i()},1e3);return()=>{n=!0,clearInterval(a)}},[e,t]);let g=n.find(e=>e.id===a)||n[0],_=e=>{o(e),localStorage.setItem(i,e)},v=async()=>{f(!0),u(``);try{let n=await t.create(e,s||void 0);r(e=>[...e,n]),_(n.id)}catch(e){h(e)}finally{f(!1)}},y=async e=>{try{await t.close(e),r(t=>t.filter(t=>t.id!==e))}catch(e){h(e)}};return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,"aria-label":`Terminal app`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b p-1`,role:`tablist`,"aria-label":`Terminal sessions`,onDoubleClick:e=>{e.target===e.currentTarget&&v()},children:[n.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center rounded border`,children:[(0,Z.jsxs)(`button`,{role:`tab`,"aria-selected":g?.id===e.id,className:`px-3 py-1 text-xs`,title:`Started in ${e.cwd}`,onClick:()=>_(e.id),children:[`Terminal `,t+1,e.running?``:` · exited`]}),(0,Z.jsx)(`button`,{className:`p-1`,"aria-label":`Close terminal ${t+1}`,title:`End this shell session`,onClick:()=>void y(e.id),children:(0,Z.jsx)(vr,{size:13})})]},e.id)),(0,Z.jsx)(`button`,{className:`p-2`,disabled:d,"aria-label":`New terminal session`,onClick:()=>void v(),children:(0,Z.jsx)(br,{size:16})})]}),l&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-between p-2 text-xs text-destructive`,role:`alert`,children:[l,(0,Z.jsx)(`button`,{"aria-label":`Dismiss terminal error`,onClick:()=>u(``),children:(0,Z.jsx)(vr,{size:14})})]}),g?(0,Z.jsx)(ox,{session:g,transport:t,report:h},g.id):(0,Z.jsxs)(`form`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-4`,onSubmit:e=>{e.preventDefault(),v()},children:[(0,Z.jsx)(`p`,{className:`text-sm`,children:p?`Loading sessions…`:`No terminals in this context yet.`}),(0,Z.jsx)(`input`,{"aria-label":`Starting directory`,className:`w-full max-w-sm rounded border p-2 text-sm`,placeholder:`Starting directory (default: home)`,value:s,onChange:e=>c(e.target.value)}),(0,Z.jsx)(`button`,{className:`rounded border px-4 py-2 text-sm`,disabled:d||p,children:`Open terminal`})]})]})}var lx={title:``,content:``,comment:``,tags:[]};function ux(e,t,n=`add`){let r=Ce(),i=el(`new:${n}:${e?.mode===`workspace`?`${e.workspaceName}:${e.treeName}:${e.path}`:e?.contextId??`home`}`),a=e=>async(n,i,a)=>{let o=typeof i.workspace==`string`?i.workspace:(await pl(e)).workspaceName,s=await r.capture(),c={schema:`data/schema/note`,schemaVersion:`2.0`,comment:n.comment,data:{title:n.title.trim(),content:n.content},metadata:{features:Qc(n.tags),...s?{geo:s}:{}}},l=typeof i.id==`number`?i.id:void 0;if(l==null){let t=await wl(e,[c],{refresh:!1});if(!t.length)throw Error(`The server did not return the saved note`);l=t[0],a({id:l,workspace:o})}else await ys(o,{...c,id:l});await t?.([l]),El(e)},o=Yc(i,lx,{retainAfterSave:!0,valid:e=>!!e.content.trim(),save:e?a(e):void 0});async function s(e){await o.saveWith(a(e));let t=o.getSnapshot().meta.id;if(typeof t!=`number`)throw Error(`Write a note before saving`);return[t]}return{...o.value,status:o.status,error:o.error,storageError:o.storageError,setTitle:e=>o.update({title:e}),setContent:e=>o.update({content:e}),setComment:e=>o.update({comment:e}),setTags:e=>o.update({tags:e}),saving:o.status===`saving`,canSave:!!o.value.content.trim()&&o.status!==`saving`,save:s,finish:o.clear,retry:o.flush,geotag:r}}function dx({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,X.useRef)(null),o=(0,X.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,X.useEffect)(()=>{o()},[e,o]),(0,Z.jsx)(`textarea`,{ref:e=>{a.current=e,i?.(e)},value:e,onChange:e=>t(e.target.value),onBlur:n,placeholder:r,rows:1,spellCheck:!1,className:`w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-sm leading-relaxed text-foreground outline-none placeholder:text-muted-foreground/60`})}function fx({onLinkTo:e,onDelete:t}){return(0,Z.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:e,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Link to…`,title:`Link to…`,children:(0,Z.jsx)(Ri,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-destructive`,"aria-label":`Delete`,title:`Delete (moves to trash)`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]})}function px({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Oo(),[a,o]=(0,X.useState)(!1);return(0,Z.jsx)(Le,{onClose:n,children:(0,Z.jsx)(y,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await Ko(a.workspaceName,n,[e],a.treeName,a.treeType);r(`Linked to ${t.length} path${t.length>1?`s`:``}`),n()}catch(e){i(e instanceof Error?e.message:`Failed to link document`),o(!1)}}},documentCount:1,saving:a,sizeClassName:ie,tabs:t?[`context`,`directory`,`relations`]:[`context`,`directory`],relationWorkspaceName:t,relationExcludeIds:new Set([e]),onConfirmRelation:async({predicate:a,direction:s,targetIds:c})=>{if(!(!t||!c.length)){o(!0);try{await Ac(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Te(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var mx=1200;function hx(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})+` `+t.toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function gx(e,t){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=(0,X.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([Sl(n,[t]),Tl(n)]).then(([e,t])=>{r(Array.isArray(e)?e:[]);let n=t.workspaceName||t.workspaceId;l(n?{workspaceName:n,path:t.path||`/`,treeName:t.treeId||`context`,treeType:`context`}:null)}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))}let{workspaceName:n,path:i,treeName:o,treeType:c}=e;return Fs(n,i,[t],{treeName:o,treeType:c,limit:50}).then(e=>{r(e.payload||[]),l({workspaceName:n,path:i,treeName:o,treeType:c})}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))},[e,t]),d=(0,X.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,X.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,X.useEffect)(()=>{u()},[u]),(0,X.useEffect)(()=>{let e=()=>d();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[d]),{docs:n,setDocs:r,loading:i,error:o,scope:c,reload:d,removeDoc:(0,X.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await Bo(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}function _x({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let s=Gc(e,t||``,!!t),{title:c,content:l,setTitle:u,setContent:d}=s,f=()=>{s.save().catch(()=>{})};return(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[hx(e.createdAt),` · #`,e.id]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[(0,Z.jsx)($c,{...s,onRetry:s.save}),(0,Z.jsx)(fx,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsx)(`input`,{value:c,onChange:e=>u(e.target.value),onBlur:f,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(dx,{value:l,onChange:d,onBlur:f,innerRef:t=>r(e.id,t)})]})}function vx({target:e,onCreated:t,onCancel:n}){let r=ux(e,void 0,`applet`),{title:i,content:a,setTitle:o,setContent:s,saving:c}=r,[l,u]=(0,X.useState)(null),d=async()=>{try{await r.save(e),r.finish(),t()}catch(e){u(e instanceof Error?e.message:`Failed to save note`)}};return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Close note`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:i,onChange:e=>o(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(dx,{value:a,onChange:s,placeholder:`Write your note…`}),(0,Z.jsx)($c,{...r,onRetry:r.retry}),l&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:d,disabled:!a.trim()||c,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:c?`Saving…`:`Done`})})]})}function yx({autoAdd:e=!1}){let t=rx(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=gx(t,Es),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(`desc`),[m,h]=(0,X.useState)(e),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(new Map),y=(0,X.useRef)(new Map),b=(0,X.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,X.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,X.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await s(e.id)}catch{}},[s]),C=(0,X.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return f===`asc`?n:-n}),e},[n,f]),w=(0,X.useMemo)(()=>{let e=c.trim().toLowerCase();if(!e)return[];let t=[];for(let n of C){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[c,C]),T=w.length?w[Math.min(u,w.length-1)]:null;(0,X.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,X.useCallback)(e=>{if(!w.length)return;let t=e?(u+1)%w.length:u;e&&d(t);let n=w[t],r=y.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+c.trim().length)),v.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[w,u,c]);return t?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(qa,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),d(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),E(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),c.trim()&&(0,Z.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:w.length?`${Math.min(u+1,w.length)}/${w.length}`:`0/0`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:f===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:f===`desc`?(0,Z.jsx)(Ni,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(ca,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>h(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,Z.jsx)(br,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,Z.jsx)(vx,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)},JSON.stringify(t)),r&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Ti,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,Z.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),C.map(e=>(0,Z.jsx)(_x,{doc:e,updateWorkspace:a?.workspaceName??null,registerEl:b,registerBody:x,highlighted:T?.docId===e.id,onLinkTo:()=>_(e.id),onDelete:()=>S(e)},e.id))]}),g!==null&&(0,Z.jsx)(px,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:Ol(t)})}var bx=`2.1`,xx=new Set([`completed`,`cancelled`]);function Sx({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,X.useState)(String(e.data?.title??``)),[u,d]=(0,X.useState)(String(e.data?.description??``)),[f,p]=(0,X.useState)(e.data?.status||`pending`),[m,h]=(0,X.useState)(x(e.data?.dueDate)),[g,_]=(0,X.useState)(`idle`),{replicating:v,label:y}=nc(e),b=(0,X.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),S=(0,X.useRef)(null),C=(0,X.useRef)(0),w=(0,X.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++C.current;_(`saving`);try{let i=Mt(n.due),a={...e.data||{},title:n.title.trim(),...n.description.trim()?{description:n.description.trim()}:{description:void 0},status:n.status,completed:n.status===`completed`};return i?a.dueDate=i:delete a.dueDate,await ys(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:a,metadata:e.metadata}),r!==C.current||(b.current={title:n.title,description:n.description},_(`saved`),setTimeout(()=>_(e=>e===`saved`?`idle`:e),1500),!0)}catch{return r===C.current&&_(`error`),!1}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),T=(0,X.useCallback)((e,t)=>{(e!==b.current.title||t!==b.current.description)&&(_(`dirty`),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>w({title:e,description:t,status:f,due:m}),mx))},[w,f,m]),E=(0,X.useCallback)(()=>{S.current&&=(clearTimeout(S.current),null),w({title:c,description:u,status:f,due:m})},[w,c,u,f,m]);(0,X.useEffect)(()=>()=>{S.current&&clearTimeout(S.current)},[]);let D=(0,X.useCallback)(async()=>{let t=f,n=f===`completed`?`pending`:`completed`;p(n),await w({title:c,description:u,status:n,due:m})?s(e.id,n):p(t)},[f,w,c,u,m,e.id,s]),O=(0,X.useCallback)(e=>{h(e),S.current&&=(clearTimeout(S.current),null),w({title:c,description:u,status:f,due:e})},[w,c,u,f]),k=xx.has(f);return(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0`,children:[hx(e.createdAt),` · #`,e.id,f!==`pending`&&(0,Z.jsxs)(`span`,{children:[` · `,xe[f]??f]})]}),(0,Z.jsx)(Pn,{value:m,onChange:O,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,Z.jsx)(Ti,{className:`inline h-3 w-3 animate-spin`}),v&&(0,Z.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,Z.jsx)(sr,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(fx,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:D,className:`mt-0.5 shrink-0 text-muted-foreground transition-colors hover:text-foreground`,"aria-label":k?`Mark as pending`:`Mark as completed`,title:k?`Mark as pending`:`Mark as completed`,children:k?(0,Z.jsx)(Sr,{className:`h-4 w-4 text-success`}):(0,Z.jsx)(Qi,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),T(e.target.value,u)},onBlur:E,placeholder:`Untitled`,spellCheck:!1,className:K(`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold outline-none placeholder:text-muted-foreground/50`,k?`text-muted-foreground line-through`:`text-foreground`)}),(0,Z.jsx)(dx,{value:u,onChange:e=>{d(e),T(c,e)},onBlur:E,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function Cx({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(he()),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`What needs doing?`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(dx,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(Pn,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await wl(e,[{schema:Qo,schemaVersion:bx,data:Ft({title:r,description:a,status:`pending`,priority:``,due:s}),metadata:{features:[]}}]),t()}catch(e){f(e instanceof Error?e.message:`Failed to create todo`),u(!1)}}},disabled:!r.trim()||l,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:l?`Saving…`:`Save todo`})})]})}function wx({autoAdd:e=!1}){let t=rx(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=gx(t,Qo),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(0),[p,m]=(0,X.useState)(`desc`),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(e),[y,b]=(0,X.useState)(null),x=(0,X.useRef)(new Map),S=(0,X.useRef)(new Map),C=(0,X.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,X.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,X.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete todo ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await c(e.id)}catch{}},[c]),E=(0,X.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,X.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!xx.has(String(e.data?.status??`pending`)));return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return p===`asc`?n:-n}),e},[n,p,h]),O=(0,X.useMemo)(()=>n.filter(e=>xx.has(String(e.data?.status??`pending`))).length,[n]),k=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();if(!e)return[];let t=[];for(let n of D){let r=String(n.data?.description??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[l,D]),A=k.length?k[Math.min(d,k.length-1)]:null;(0,X.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,X.useCallback)(e=>{if(!k.length)return;let t=e?(d+1)%k.length:d;e&&f(t);let n=k[t],r=S.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+l.trim().length)),x.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[k,d,l]);return t?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(qa,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:l,onChange:e=>{u(e.target.value),f(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),j(!0))},placeholder:`Search todos…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),l.trim()&&(0,Z.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:k.length?`${Math.min(d+1,k.length)}/${k.length}`:`0/0`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:K(`rounded-md border p-1.5 transition-colors`,h?`border-foreground text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:h?`Hide done items`:`Show done items${O?` (${O})`:``}`,"aria-label":h?`Hide done items`:`Show done items`,children:h?(0,Z.jsx)(ja,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Ei,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:p===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:p===`desc`?(0,Z.jsx)(Ni,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(ca,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a todo`,children:[(0,Z.jsx)(br,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,Z.jsx)(Cx,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Ti,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,Z.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:O?`Nothing pending - ${O} done item${O>1?`s`:``} hidden.`:`No todos here yet - add the first one.`}),D.map(e=>(0,Z.jsx)(Sx,{doc:e,updateWorkspace:o?.workspaceName??null,registerEl:C,registerBody:w,highlighted:A?.docId===e.id,onLinkTo:()=>b(e.id),onDelete:()=>T(e),onStatusSaved:E},e.id))]}),y!==null&&(0,Z.jsx)(px,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:Ol(t)})}var Tx=(0,X.createContext)(null);function Ex(){let e=(0,X.useContext)(Tx);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function Dx(e=!0){let{registerViewer:t}=Ex();(0,X.useEffect)(()=>{if(e)return t()},[e,t])}var Ox=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],kx=`canvas.lens.camera`,Ax={min:1,max:4,step:.1,hardware:!1};function jx(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(kx)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:Ox.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function Mx(e,t){let n=Ox.find(t=>t.id===e.resolution)??Ox[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function Nx(e={}){let t=(0,X.useRef)(null),n=(0,X.useRef)(e.onEnded);(0,X.useEffect)(()=>{n.current=e.onEnded});let r=(0,X.useRef)(null),i=(0,X.useRef)(null),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(jx),p=(0,X.useRef)(d),[m,h]=(0,X.useState)([]),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(1),w=(0,X.useRef)(1),[T,E]=(0,X.useState)(!1),D=(0,X.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,X.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,X.useCallback)(async()=>{try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`&&e.deviceId);h(e.map((e,t)=>({deviceId:e.deviceId,label:e.label||`Camera ${t+1}`})))}catch{}},[]),j=(0,X.useCallback)(()=>{D.current&&window.clearTimeout(D.current),r.current?.getTracks().forEach(e=>e.stop()),r.current=null,t.current&&(t.current.srcObject=null),c(null),o(!1),_(!1),y(null),x(null),C(1),w.current=1,E(!1)},[]),M=(0,X.useCallback)(async(e,i)=>{r.current=e,e.getVideoTracks().forEach(e=>{e.onended=()=>{j(),n.current?.()}}),t.current&&(t.current.srcObject=e,await t.current.play().catch(()=>{}));let a=e.getVideoTracks()[0],s=a?.getSettings();if(x(s?.width&&s?.height?{width:s.width,height:s.height}:null),_(i),E(!1),i&&a){let e=a.getCapabilities?.()??{};y(e),e.focusMode?.includes(`continuous`)&&await k({focusMode:`continuous`});let t=a.getSettings().zoom;C(e.zoom?t??e.zoom.min:1),w.current=1,A()}c(e),o(!0)},[j,k,A]),N=(0,X.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:Mx(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:Mx(e,!1),audio:!1});throw t}},[]),P=(0,X.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Camera needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getUserMedia)return u(`Camera API not available in this browser.`),!1;try{let e=await N(p.current);return await M(e,!0),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Camera permission denied.`:t===`NotFoundError`?`No camera found.`:`Camera failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M,N]),ee=(0,X.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Screen capture needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getDisplayMedia)return u(`Screen capture API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1280},height:{ideal:720}},audio:!1});return await M(e,!1),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Screen capture cancelled.`:`Screen capture failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M]),F=(0,X.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(kx,JSON.stringify(t))}catch{}!r.current||!g||(r.current.getTracks().forEach(e=>{e.onended=null,e.stop()}),r.current=null,P().then(e=>{e||(j(),n.current?.())}))},[g,P,j]),I=(0,X.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),te=(0,X.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),L=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),R=(0,X.useCallback)(e=>{let t=v?.focusMode??[];if(!t.length)return;D.current&&window.clearTimeout(D.current);let n=navigator.mediaDevices.getSupportedConstraints(),r=e&&n.pointsOfInterest?{pointsOfInterest:[e]}:{};t.includes(`single-shot`)?(k({...r,focusMode:`single-shot`}),t.includes(`continuous`)&&(D.current=window.setTimeout(()=>void k({...r,focusMode:`continuous`}),1500))):k({...r,focusMode:`continuous`})},[v,k]),ne=(0,X.useCallback)((e=640,n=.72)=>{let r=t.current;if(!r||r.readyState<2||!r.videoWidth)return null;let a=Math.max(1,w.current),o=r.videoWidth/a,s=r.videoHeight/a,c=(r.videoWidth-o)/2,l=(r.videoHeight-s)/2,u=Math.min(1,e/Math.max(o,s)),d=Math.round(o*u),f=Math.round(s*u);i.current||=document.createElement(`canvas`);let p=i.current;p.width=d,p.height=f;let m=p.getContext(`2d`);return m?(m.drawImage(r,c,l,o,s,0,0,d,f),p.toDataURL(`image/jpeg`,n)):null},[]);return(0,X.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:P,startScreen:ee,stop:j,captureFrame:ne,camera:(0,X.useMemo)(()=>g?{devices:m,prefs:d,setPrefs:F,size:b,zoomRange:v?.zoom?{min:v.zoom.min,max:v.zoom.max,step:v.zoom.step||.1,hardware:!0}:Ax,zoom:S,setZoom:I,torchSupported:!!v?.torch,torch:T,setTorch:te,focusSupported:L,focusAt:R}:null,[g,m,d,F,b,v,S,I,T,te,L,R])}}async function Px(e,t,n={}){let r={limit:n.limit??12,scope:n.contextPath?`path`:`workspace`};t&&(r.image=t),n.similarTo&&(r.similarTo=n.similarTo);let i=n.q?.trim();i&&(r.q=i),n.maxDistance!=null&&Number.isFinite(n.maxDistance)&&(r.maxDistance=n.maxDistance),n.minDistance!=null&&Number.isFinite(n.minDistance)&&(r.minDistance=n.minDistance),n.debug&&(r.debug=!0),n.idsOnly&&(r.idsOnly=!0),n.contextPath&&(r.context=n.contextPath),n.treeId&&(r.treeNameOrTreeId=n.treeId),n.features&&Object.assign(r,n.features),n.filters&&(r.filters=n.filters),n.applyCanvasQuerySpec!==void 0&&(r.applyCanvasQuerySpec=n.applyCanvasQuerySpec);let a=await J.postEnvelope(`${no.workspaces}/${encodeURIComponent(e)}/documents/search/image`,r,n.signal?{signal:n.signal}:void 0),o=a.payload??[],s=n.idsOnly===!0;return{documents:s?[]:o,ids:s?o:o.map(e=>e.id),count:a.count??o.length,totalCount:a.totalCount??o.length,distances:a.debug?.distances??a.debug?.imageDistances??null}}var Fx=[{label:`0.5 fps`,ms:2e3},{label:`1 fps`,ms:1e3},{label:`2 fps`,ms:500},{label:`5 fps`,ms:200},{label:`10 fps`,ms:100},{label:`15 fps`,ms:67},{label:`30 fps`,ms:33}],Ix=1e3,Lx=32,Rx=12,zx=`canvas.lens.fit`;function Bx({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=Ex(),a=(0,X.useRef)(null),[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,X.useEffect)(()=>{if(!o)return;let e=window.setTimeout(()=>s(null),900);return()=>window.clearTimeout(e)},[o]);let c=r&&!r.zoomRange.hardware?r.zoom:1;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`video`,{ref:a,muted:!0,playsInline:!0,onClick:t?e=>{let t=a.current;if(!t||!r?.focusSupported||!t.videoWidth)return;let n=t.getBoundingClientRect(),o=(e.clientX-n.left)/n.width,l=(e.clientY-n.top)/n.height,u=.5+(o-.5)/c,d=.5+(l-.5)/c,f=i===`contain`?Math.min(n.width/t.videoWidth,n.height/t.videoHeight):Math.max(n.width/t.videoWidth,n.height/t.videoHeight),p=t.videoWidth*f/n.width,m=t.videoHeight*f/n.height,h=.5+(u-.5)/p,g=.5+(d-.5)/m;h<0||h>1||g<0||g>1||(r.focusAt({x:h,y:g}),s({x:o,y:l,key:Date.now()}))}:void 0,style:c===1?void 0:{transform:`scale(${c})`},className:K(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute h-10 w-10 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white/90 animate-fade-in`,style:{left:`${o.x*100}%`,top:`${o.y*100}%`}},o.key)]})}function Vx({children:e}){let t=ul(),n=(0,X.useRef)(t);(0,X.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,X.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=Nx({onEnded:()=>a.current()}),[m,h]=(0,X.useState)(null),g=(0,X.useRef)(m);(0,X.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(Ix),[C,w]=(0,X.useState)(``),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)([]),[ee,F]=(0,X.useState)(null),[I,te]=(0,X.useState)(null),L=I&&I.frame===ee?I:null,R=(0,X.useRef)(null),[ne,re]=(0,X.useState)(0),[ie,ae]=(0,X.useState)(``),[z,oe]=(0,X.useState)(()=>{try{return localStorage.getItem(zx)===`cover`?`cover`:`contain`}catch{return`contain`}}),se=(0,X.useCallback)(e=>{oe(e);try{localStorage.setItem(zx,e)}catch{}},[]),B=(0,X.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:Ix,snapshot:!1}),ce=(0,X.useRef)([]),V=(0,X.useRef)(new Map),le=(0,X.useRef)(null),ue=(0,X.useRef)(null),de=(0,X.useRef)(null),fe=(0,X.useRef)(0),pe=(0,X.useRef)(``),me=(0,X.useRef)(!1),he=(0,X.useRef)(async()=>{}),ge=(0,X.useRef)(()=>{});(0,X.useEffect)(()=>{B.current.text=T,B.current.maxDistance=C===``?NaN:Number(C),B.current.rateMs=x,B.current.paused=y},[T,C,x,y]);let _e=(0,X.useCallback)(()=>(re(e=>e+1),()=>re(e=>Math.max(0,e-1))),[]),ve=(0,X.useCallback)(e=>{ce.current=[...ce.current.slice(-2),e];let t=ce.current,r=[...new Set(t.flat())],i=t.length<2?e:r.filter(e=>t.filter(t=>t.includes(e)).length>=2);M(i.length);let a=le.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(le.current=i,n.current?.setLensIds(i))},[]),ye=(0,X.useCallback)((e,t)=>{for(let n of e)V.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);ce.current=[...ce.current.slice(-2),n];let r=ce.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...V.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>V.current.get(e)).filter(e=>!!e);M(s.length),P(s)},[]),be=(0,X.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;de.current?.abort();let a=new AbortController;de.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await Px(t.workspaceRef,e,{q:i&&t.text||void 0,maxDistance:Number.isFinite(t.maxDistance)?t.maxDistance:void 0,contextPath:s?o.activeContextPath:i?t.contextPath:null,treeId:s?o.activeTreeName:null,features:s?o.filters.features:void 0,filters:s?[...it(o.filters.timeline),...En(o.filters.geo),...ke(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?Rx:Lx,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||B.current!==t||!t.running?!1:(fe.current=0,A(Math.round(performance.now()-r)),O(null),i?ye(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):ve(c.ids),!0)}catch(e){return a.signal.aborted||B.current!==t||!t.running?!1:(fe.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[ye,ve]),xe=(0,X.useCallback)(async()=>{let e=B.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await be(t,e)}if(B.current.running){let e=Math.max(fe.current?Math.min(3e4,1e3*2**Math.min(fe.current-1,5)):0,B.current.rateMs-(performance.now()-t));ue.current=window.setTimeout(()=>void he.current(),e)}},[p,be]);(0,X.useEffect)(()=>{he.current=xe},[xe]);let H=(0,X.useCallback)(()=>{let e=B.current.consumer===`filter`;B.current.running=!1,fe.current=0,B.current.consumer=null,ue.current&&window.clearTimeout(ue.current),de.current?.abort(),f(),ce.current=[],V.current.clear(),le.current=null,h(null),v(null),b(!1),ae(``),P([]),F(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,X.useEffect)(()=>{a.current=H},[H]);let Se=(0,X.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||me.current||(B.current.running&&H(),e===`photo`&&!r.image))return!1;me.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return me.current=!1,i?(ce.current=[],V.current.clear(),le.current=null,P([]),M(null),O(null),ae(r.workspaceRef),B.current={...B.current,running:!0,paused:!1,consumer:t,workspaceRef:r.workspaceRef,contextPath:r.contextPath??null,snapshot:e===`photo`},F(e===`photo`?r.image:null),h(e),v(t),b(!1),t===`filter`&&n.current?.setLensIds([]),e===`photo`?ge.current(r.image):xe(),!0):!1},[u,d,H,xe]),Ce=JSON.stringify(t?{contextId:t.state.activeContextId,path:t.state.activeContextPath,tree:t.state.activeTreeName,features:t.state.filters.features,timeline:t.state.filters.timeline,geo:t.state.filters.geo,gps:t.state.filters.lens.gps}:null);(0,X.useEffect)(()=>{pe.current!==Ce&&(pe.current=Ce,B.current.consumer===`filter`&&(de.current?.abort(),ce.current=[],le.current=null,n.current?.setLensIds([])))},[Ce]);let U=(0,X.useCallback)(e=>{B.current.contextPath=e},[]),W=(0,X.useCallback)(e=>{B.current.paused=e,b(e)},[]),we=JSON.stringify([T,C,Ce]),Te=(0,X.useRef)(we);(0,X.useEffect)(()=>{Te.current=we});let Ee=(0,X.useCallback)(e=>{let t=B.current;!t.running||!t.workspaceRef||(R.current={frame:e,key:Te.current},ce.current=[],V.current.clear(),le.current=null,M(null),be(e,t))},[be]);(0,X.useEffect)(()=>{ge.current=Ee},[Ee]);let De=(0,X.useCallback)(()=>{let e=B.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,F(t),Ee(t))},[p,Ee]),Oe=(0,X.useCallback)(()=>{if(B.current.running&&g.current===`photo`){H();return}B.current.snapshot=!1,de.current?.abort(),ce.current=[],V.current.clear(),F(null)},[H]),Ae=(0,X.useCallback)(async(e,t,n)=>{let r=B.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,F(e),Ee(e),!0):Se(`photo`,t,{...n,image:e})},[Se,Ee]);(0,X.useEffect)(()=>{if(!ee)return;let e=!0,t=new Image;return t.onload=()=>{e&&te({frame:ee,width:t.naturalWidth,height:t.naturalHeight})},t.src=ee,()=>{e=!1}},[ee]),(0,X.useEffect)(()=>{if(!ee)return;let e=R.current;if(e&&e.frame===ee&&e.key===we)return;let t=window.setTimeout(()=>Ee(ee),350);return()=>window.clearTimeout(t)},[ee,we,Ee]),(0,X.useEffect)(()=>{!i||!B.current.running||r&&r===B.current.workspaceRef||H()},[i,r,H]);let je=(0,X.useCallback)(()=>{let e=n.current;if(e){if(B.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,X.useEffect)(()=>H,[H]);let Me=(0,X.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:z,setFit:se,workspaceRef:ie,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:Se,setContextPath:U,stop:H,setPaused:W,snapshot:ee,takeSnapshot:De,clearSnapshot:Oe,snapshotSize:L,searchPhoto:Ae,reopen:je,hasViewer:ne>0,registerViewer:_e}),[m,y,_,s,c,z,se,ie,x,C,T,l,D,k,j,N,Se,U,H,W,ee,De,Oe,L,Ae,je,ne,_e]);return(0,Z.jsxs)(Tx.Provider,{value:Me,children:[e,(0,Z.jsx)(`video`,{ref:o,muted:!0,playsInline:!0,"aria-hidden":!0,className:`pointer-events-none fixed bottom-0 left-0 h-px w-px opacity-0`})]})}var Hx=`h-7 min-w-0 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,Ux=`flex h-7 items-center gap-1 rounded-md border border-border px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,Wx=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function Gx({className:e}){let{camera:t,fit:n,setFit:r}=Ex();if(!t)return null;let{devices:i,prefs:a,setPrefs:o,size:s,zoomRange:c,zoom:l,setZoom:u}=t,d=c.max>c.min;return(0,Z.jsxs)(`div`,{className:K(`flex flex-col gap-2`,e),children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,Z.jsxs)(`select`,{className:K(Hx,`max-w-[12rem] flex-1`),value:a.deviceId??``,onChange:e=>o({deviceId:e.target.value||null}),title:`Camera / lens. On phones with several rear cameras, pick the main or wide one if the picture is too zoomed in.`,"aria-label":`Camera`,children:[(0,Z.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,Z.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,Z.jsx)(`select`,{className:Hx,value:a.resolution,onChange:e=>o({resolution:e.target.value}),title:s?`Requested resolution — camera is delivering ${s.width}×${s.height}`:`Requested resolution`,"aria-label":`Resolution`,children:Ox.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:Ux,title:n===`contain`?`Showing the whole frame — switch to fill the preview`:`Filling the preview (edges cropped) — switch to the whole frame`,"aria-label":n===`contain`?`Fill preview`:`Fit whole frame`,children:n===`contain`?(0,Z.jsx)(ma,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(ta,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:Ux,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,Z.jsx)(Ka,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:K(Ux,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,Z.jsx)(Mr,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(In,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,title:c.hardware?`Optical/sensor zoom`:`Digital zoom — crops the searched frame too`,children:[(0,Z.jsx)($n,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.jsx)(`input`,{type:`range`,min:c.min,max:c.max,step:c.step,value:l,onChange:e=>u(Number(e.target.value)),onDoubleClick:()=>u(c.min),className:`h-1 min-w-0 flex-1 accent-foreground`,"aria-label":`Zoom`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:Wx(l)})]})]})}function Kx(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=Ex();return e?n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:K(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,Z.jsx)(`span`,{className:`pointer-events-none absolute left-2 top-2 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-white`,children:t===`photo`?`Photo`:`Snapshot`}),(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`absolute bottom-2 left-1/2 flex h-9 -translate-x-1/2 items-center gap-1.5 rounded-full bg-black/60 px-3 text-xs font-medium text-white backdrop-blur transition-colors hover:bg-black/75`,title:t===`photo`?`Close the photo and clear its matches`:`Discard the snapshot and go back to the live feed`,children:t===`photo`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`}),` Close`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Vr,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Take a snapshot and search it`,title:`Snapshot: freeze this frame and search for similar items`,className:`absolute bottom-2 left-1/2 flex h-12 w-12 -translate-x-1/2 items-center justify-center rounded-full border-4 border-white/90 bg-white/25 text-white shadow-lg backdrop-blur transition-transform hover:bg-white/40 active:scale-90`,children:(0,Z.jsx)(Li,{className:`h-5 w-5`})}):null}async function qx(e,t=1280,n=.85){let r,i=null;try{r=await createImageBitmap(e,{imageOrientation:`from-image`})}catch{i=URL.createObjectURL(e);let t=new Image;t.src=i,await t.decode(),r=t}try{let e=r.width,i=r.height,a=Math.min(1,t/Math.max(e,i)),o=document.createElement(`canvas`);o.width=Math.round(e*a),o.height=Math.round(i*a);let s=o.getContext(`2d`);if(!s)throw Error(`canvas unavailable`);return s.drawImage(r,0,0,o.width,o.height),o.toDataURL(`image/jpeg`,n)}finally{`close`in r&&r.close(),i&&URL.revokeObjectURL(i)}}function Jx({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=Ex(),o=(0,X.useRef)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await qx(r);await a(i,e,{workspaceRef:t,contextPath:n})}catch{u(`Could not read that image.`)}finally{c(!1),o.current&&(o.current.value=``)}}};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>o.current?.click(),disabled:r||s||!t,className:i,title:l??`Search with a photo from the camera app or gallery`,children:[(0,Z.jsx)(Ji,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,Z.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,Z.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var Yx=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,Xx=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Zx({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=ms(t),{blobUrl:a}=z(e,t.id,256,{enabled:i}),o=Ho(t);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-(--card-radius) border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,Z.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,Z.jsx)(Wt,{document:t,size:10})}),(0,Z.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,Z.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function Qx(){let e=rx(),t=I(),n=Ex(),{rateMs:r,setRateMs:i,text:a,setText:o,maxDistance:s,setMaxDistance:c,latencyMs:l,error:u}=n,d=e?.mode===`workspace`?e.workspaceName:``,f=e?.mode===`workspace`&&e.path!==`/`?e.path:null,p=n.running&&n.consumer===`applet`,m=n.running&&n.consumer!==`applet`,h=p?n.hits:[];Dx(p);let g=p?n.snapshotSize??n.camera?.size:null,_=!!g&&g.height>g.width,v=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:y}=n;return(0,X.useEffect)(()=>{p&&y(f)},[p,f,y]),e?.mode===`workspace`?(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:Yx,value:r,onChange:e=>i(Number(e.target.value)),title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:Fx.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(Xx,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,Z.jsx)(`input`,{className:K(Xx,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:s,onChange:e=>c(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),p?(0,Z.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,Z.jsx)(Yi,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(`camera`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(Ur,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(`screen`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(mr,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(Jx,{consumer:`applet`,workspaceRef:d,contextPath:f,disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:K(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,_?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[p&&(0,Z.jsx)(Bx,{className:`h-full w-full`,interactive:!0}),p&&(0,Z.jsx)(Kx,{}),!p&&(0,Z.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,Z.jsx)(oi,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),p&&(0,Z.jsx)(Gx,{className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,Z.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,Z.jsxs)(Z.Fragment,{children:[n.snapshot?`snapshot`:`live`,` · `,l==null?`searching…`:`${l} ms/frame`,` · `,h.length,` match`,h.length===1?``:`es`,f?` · scoped to ${f}`:``]}):m?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),h.length===0?(0,Z.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:p?n.snapshot?`Nothing similar in the snapshot`:`Nothing matching in view`:`Matches appear here`}):(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,Z.jsx)(Zx,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}var $x=`data/schema/`,eS={"data/schema/file":{label:`Files`,icon:Ki},"data/schema/note":{label:`Notes`,icon:Da},"data/schema/task":{label:`Todos`,icon:pa},"data/schema/tab":{label:`Tabs`,icon:Kr},"data/schema/message/email":{label:`Emails`,icon:la},"data/schema/link":{label:`Links`,icon:Ui},"data/schema/identity":{label:`Identities`,icon:Hr},"data/schema/drawing":{label:`Sketches`,icon:pr}};function tS(e){return eS[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:jr}}function nS(e){return eS[e]?.icon??jr}function rS(e){return{...e,lens:Ze.lens}}function iS(e,t,n=!1){let r=n?e=>e:rS;return JSON.stringify(r(e))!==JSON.stringify(r(t??Ze))}var aS={savedGeoSelection:null,liveEnabled:!1,liveError:null,t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,addModal:!1,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null,activeContextPath:null,activeContextType:null,activeWorkspaceName:null,activeTreeName:null,activeCanvasId:null,activeContextId:null,activeAccentColor:null,filters:Ze,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function oS(e,t){switch(t.type){case`SET_VIEW`:return{...e,t1Open:t.view!==null,t1View:t.view};case`TOGGLE_VIEW`:return e.t1View===t.view?{...e,t1Open:!1,t1View:null}:{...e,t1Open:!0,t1View:t.view};case`CLOSE_T1`:return{...e,t1Open:!1,t1View:null,t2Open:!1,t2AgentId:null};case`OPEN_T2_AGENT`:return{...e,t2Open:!0,t2AgentId:t.agentId};case`CLOSE_T2`:return{...e,t2Open:!1,t2AgentId:null};case`OPEN_ADD`:return{...e,addOpen:!0,addModal:t.modal??(e.addOpen&&e.addModal),addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addModal:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,addModal:!1,addKind:null,addRelateTo:null,editDocument:t.document,editWorkspaceId:t.workspaceId};case`SET_TOOLS_TAB`:return{...e,toolsTab:t.tab};case`SET_APPS_APPLET`:return{...e,appsAppletId:t.appletId};case`SET_ACCENT_COLOR`:return e.activeAccentColor===t.color?e:{...e,activeAccentColor:t.color};case`SET_GEO_SELECTION`:return{...e,geoSelection:t.selection,isDirty:e.activeContextType===`context`?iS(e.filters,e.savedFilters,!0)||JSON.stringify(t.selection)!==JSON.stringify(e.savedGeoSelection):e.isDirty};case`SET_SAVED_GEO_SELECTION`:return{...e,savedGeoSelection:t.selection,isDirty:e.activeContextType===`context`?iS(e.filters,e.savedFilters,!0)||JSON.stringify(e.geoSelection)!==JSON.stringify(t.selection):e.isDirty};case`SET_MAP_DOCUMENTS`:return e.mapDocuments===t.documents&&e.mapWorkspaceId===t.workspaceId?e:{...e,mapDocuments:t.documents,mapWorkspaceId:t.workspaceId};case`SET_NAVIGATION`:{let n=e.activeContextType===t.contextType&&e.activeContextId===t.contextId&&e.activeCanvasId===t.canvasId;return{...e,activeWorkspaceName:t.workspaceName,activeTreeName:t.treeName,activeCanvasId:t.canvasId,activeContextId:t.contextId,activeContextType:t.contextType,activeContextPath:t.contextPath,geoSelection:null,...n?{}:{filters:Ze,savedFilters:null,savedSearchQuery:null,isDirty:!1,savedGeoSelection:null,liveEnabled:!1,liveError:null}}}case`SET_CONTEXT_SCOPE`:return e.activeContextType!==`context`||e.activeWorkspaceName===t.workspaceName&&e.activeContextPath===t.contextPath&&e.activeTreeName===t.treeId?e:{...e,activeWorkspaceName:t.workspaceName,activeContextPath:t.contextPath,activeTreeName:t.treeId};case`SET_LIVE`:return{...e,liveEnabled:t.enabled,liveError:null};case`SET_LIVE_ERROR`:return{...e,liveError:t.error};case`SET_FILTERS`:return{...e,filters:t.filters,isDirty:e.activeContextType===null?!1:iS(t.filters,e.savedFilters,e.activeContextType===`context`)||e.activeContextType===`context`&&JSON.stringify(e.geoSelection)!==JSON.stringify(e.savedGeoSelection)};case`SET_SAVED_FILTERS`:{let n=t.hydrating===!0&&e.isDirty,r=n?e.filters:t.savedFilters??Ze;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?iS(r,t.savedFilters,e.activeContextType===`context`):!1}}case`SET_SAVING`:return{...e,isSaving:t.isSaving};case`SET_BITMAPS`:return{...e,availableBitmaps:t.keys,bitmapsLoading:!1};case`SET_BITMAPS_LOADING`:return{...e,bitmapsLoading:t.loading};case`SET_TIMELINES`:return{...e,availableTimelines:t.names,timelineScales:t.scales??e.timelineScales,timelinesLoading:!1};case`SET_TIMELINES_LOADING`:return{...e,timelinesLoading:t.loading};default:return e}}var sS=`toolbox:session:filters`;function cS(){try{let e=localStorage.getItem(sS);if(!e)return null;let t=JSON.parse(e);return{...Ze,...t,features:{...Ze.features,...t.features??{}},timeline:{...Ze.timeline,...t.timeline??{}},geo:{...Ze.geo,...t.geo??{}},lens:Ze.lens,sort:Cn(t.sort)}}catch{return null}}function lS(e){try{localStorage.setItem(sS,JSON.stringify(rS(e)))}catch{}}function uS(e,t=!1){if(!e?.toolbox)return null;try{let n=e.toolbox;return{features:{allOf:n.features?.allOf??[],anyOf:n.features?.anyOf??[],noneOf:n.features?.noneOf??[]},timeline:{quickFilter:n.timeline?.quickFilter??null,customRanges:n.timeline?.customRanges??(n.timeline?.customRange?[n.timeline.customRange]:[]),indexCreated:n.timeline?.indexCreated??!0,indexUpdated:n.timeline?.indexUpdated??!0,indexDeleted:n.timeline?.indexDeleted??!1,contentEvents:n.timeline?.contentEvents??!1,selectedTimelines:n.timeline?.selectedTimelines??[]},geo:{bbox:n.geo?.bbox??null,includeUnlocated:n.geo?.includeUnlocated??!1},lens:t?{...Ze.lens,...n.lens??{}}:Ze.lens,sort:Cn(n.sort)}}catch{return null}}function dS(e,t){let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)break;return n}function fS({children:e,target:t}){let[n,r]=(0,X.useReducer)(oS,aS),i=vn(),a=ft(),o=new URLSearchParams(i.search).get(`ownerId`)||void 0,s=(0,X.useRef)(null),c=(0,X.useRef)(n);(0,X.useEffect)(()=>{c.current=n}),(0,X.useEffect)(()=>{let e=!1,n=i.pathname.split(`/`).filter(Boolean),a=t===void 0?n[0]===`workspaces`&&decodeURIComponent(n[1]||``)||null:t?.mode===`workspace`?t.workspaceName:null,o=t===void 0?n[0]===`contexts`&&decodeURIComponent(n[1]||``)||null:t?.mode===`context`?t.contextId:null,{path:s,treeName:l}=t?.mode===`workspace`?t:a?af(i.pathname):{path:`/`,treeName:``},u=t=>{if(e)return;let n=t?`canvas`:o?`context`:null,i=c.current;i.activeContextType!==null&&n===null&&lS(i.filters),r({type:`SET_NAVIGATION`,workspaceName:a,treeName:a?l:null,canvasId:t,contextId:o,contextType:n,contextPath:a?s:null})};return a&&s!==`/`?(_c(a,l).then(t=>{if(e)return;let n=dS(t,s);u(n?.type===`canvas`?n.id:null)}).catch(()=>u(null)),()=>{e=!0}):(u(null),()=>{e=!0})},[i.pathname,t]),(0,X.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_BITMAPS_LOADING`,loading:!0}),Fc(e).then(e=>{r({type:`SET_BITMAPS`,keys:e})}))},[n.activeWorkspaceName]),(0,X.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),as(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[n.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeCanvasId:t,activeWorkspaceName:i,activeTreeName:a,activeContextPath:o}=n;if(e!==`context`){if(e===`canvas`&&t&&i&&o)_c(i,a||`context`).then(e=>{let t=dS(e,o),n=uS(t?.metadata);r({type:`SET_SAVED_FILTERS`,savedFilters:n,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{r({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=cS();r({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[n.activeCanvasId,n.activeContextPath,n.activeContextType,n.activeTreeName,n.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeContextId:t}=n;if(e!==`context`||!t)return;let l=!1;s.current=null;let u=0,d=e=>{let t=new URLSearchParams(window.location.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let n=t.toString();a(`${i.pathname}${n?`?${n}`:``}${window.location.hash}`,{replace:!0})},f=(e,t,n,i=null,a=n?[n]:[])=>{let o=e?.filters??t??Ze,c=e?.geoSelection??i;s.current=JSON.stringify({filters:o,geoSelection:c,queries:e?.queries??a}),r({type:`SET_SAVED_FILTERS`,savedFilters:t,savedSearchQuery:n}),r({type:`SET_FILTERS`,filters:o}),r({type:`SET_GEO_SELECTION`,selection:c}),r({type:`SET_SAVED_GEO_SELECTION`,selection:i}),r({type:`SET_LIVE`,enabled:e!==null}),d(e?.queries??a)},p=e=>{let n=++u;return Tl(t,o).then(t=>{if(l||n!==u)return;let i=t.metadata,a=uS(i,!0),o=typeof i?.toolboxSearchQuery==`string`?i.toolboxSearchQuery:null;if(r({type:`SET_CONTEXT_SCOPE`,workspaceName:t.workspaceName||t.workspaceId||null,contextPath:t.path||`/`,treeId:t.treeId||null}),t.liveQuery)f(t.liveQuery,a,o,i?.toolboxGeoSelection??null,t.queryOptions?.queries);else if(e){r({type:`SET_LIVE`,enabled:!1});let e=c.current.isDirty?c.current.filters:a??Ze,n=i?.toolboxGeoSelection??null;s.current=JSON.stringify({filters:e,geoSelection:n,queries:[]}),r({type:`SET_SAVED_FILTERS`,savedFilters:a,savedSearchQuery:o,hydrating:!0}),r({type:`SET_GEO_SELECTION`,selection:n}),r({type:`SET_SAVED_GEO_SELECTION`,selection:n});let l=new URLSearchParams(window.location.search),u=t.queryOptions?.queries?.length?t.queryOptions.queries:o?[o]:[];!l.has(`q`)&&!l.has(`search`)&&u.length&&d(u)}}).catch(e=>{l||n!==u||r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not load context`})})};p(!0);let m=()=>{p(!1)},h=B.on(`context.url.set`,e=>{e?.id===t&&m()}),g=B.on(`context.updated`,e=>{let n=e;if((n.contextId||n.id)!==t)return;if(!n.metadata){p(!0);return}++u;let r=uS(n.metadata,!0);f(n.liveQuery??null,r,typeof n.metadata.toolboxSearchQuery==`string`?n.metadata.toolboxSearchQuery:null,n.metadata.toolboxGeoSelection??null,n.queryOptions?.queries)}),_=B.on(`connect`,()=>{p(!0)}),v=B.on(`disconnect`,()=>{c.current.liveEnabled&&r({type:`SET_LIVE_ERROR`,error:`Disconnected — Live updates will resume when connected.`})});return window.addEventListener(`contexts:refresh`,m),()=>{l=!0,s.current=null,h(),g(),_(),v(),window.removeEventListener(`contexts:refresh`,m)}},[n.activeContextId,n.activeContextType,o]);let l=(0,X.useMemo)(()=>{let e=new URLSearchParams(i.search),t=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),n=(e.get(`search`)||``).trim();return t.length?t:n?[n]:[]},[i.search]),u=(0,X.useRef)(l);(0,X.useEffect)(()=>{u.current=l},[l]);let d=(0,X.useRef)(!1),f=(0,X.useRef)(null),[p,m]=(0,X.useState)(0);(0,X.useEffect)(()=>()=>{f.current!==null&&window.clearTimeout(f.current),f.current=null},[n.activeContextType,n.activeContextId,n.liveEnabled,o]),(0,X.useEffect)(()=>{n.activeContextType!==`context`||!n.activeContextId||o||!n.liveEnabled||s.current===null||d.current||f.current!==null||!B.isConnected()||JSON.stringify({filters:n.filters,geoSelection:n.geoSelection,queries:l})!==s.current&&(f.current=window.setTimeout(()=>{f.current=null;let e=c.current;if(e.activeContextId!==n.activeContextId||!e.liveEnabled)return;let t=u.current,i=JSON.stringify({filters:e.filters,geoSelection:e.geoSelection,queries:t});if(i===s.current)return;let a=s.current;d.current=!0;let o={filters:e.filters,geoSelection:e.geoSelection,queries:t,binding:kn(e.filters,e.geoSelection,t)};B.request(`context.filters.set`,{contextId:e.activeContextId,liveQuery:o}).then(()=>{c.current.activeContextId===e.activeContextId&&s.current===a&&(s.current=i,r({type:`SET_LIVE_ERROR`,error:null}))}).catch(t=>{c.current.activeContextId===e.activeContextId&&r({type:`SET_LIVE_ERROR`,error:t instanceof Error?t.message:`Live update failed`})}).finally(()=>{d.current=!1,m(e=>e+1)})},n.liveError?1500:100))},[n.activeContextType,n.activeContextId,n.liveEnabled,n.filters,n.geoSelection,l,o,p,n.liveError]);let h=(0,X.useCallback)(async e=>{let t=c.current;if(t.activeContextType!==`context`||!t.activeContextId||o)return;let n=l,i=e?{filters:t.filters,geoSelection:t.geoSelection,queries:n,binding:kn(t.filters,t.geoSelection,n)}:null;try{await B.request(`context.filters.set`,{contextId:t.activeContextId,liveQuery:i}),s.current=JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:n}),r({type:`SET_LIVE`,enabled:e})}catch(e){r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not change Live mode`})}},[o,l]);(0,X.useEffect)(()=>{n.activeContextType===null&&lS(n.filters)},[n.filters,n.activeContextType]);let g=(0,X.useCallback)(e=>r({type:`SET_VIEW`,view:e}),[]),_=(0,X.useCallback)(e=>r({type:`TOGGLE_VIEW`,view:e}),[]),v=(0,X.useCallback)(()=>r({type:`CLOSE_T1`}),[]),y=(0,X.useCallback)(e=>r({type:`OPEN_T2_AGENT`,agentId:e}),[]),b=(0,X.useCallback)(()=>r({type:`CLOSE_T2`}),[]),x=(0,X.useCallback)(e=>r({type:`OPEN_ADD`,kind:e}),[]),S=(0,X.useCallback)(e=>r({type:`OPEN_ADD`,kind:null,modal:e?.modal,relateTo:e?.fresh?null:void 0}),[]),C=(0,X.useCallback)((e,t=!1)=>r({type:`OPEN_ADD`,kind:null,relateTo:e,modal:t}),[]),w=(0,X.useCallback)(()=>r({type:`CLOSE_ADD`}),[]),T=(0,X.useCallback)((e,t)=>r({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),E=(0,X.useCallback)(e=>r({type:`SET_TOOLS_TAB`,tab:e}),[]),D=(0,X.useCallback)(e=>r({type:`SET_APPS_APPLET`,appletId:e}),[]),O=(0,X.useCallback)(e=>r({type:`SET_ACCENT_COLOR`,color:e}),[]),k=(0,X.useCallback)(e=>{r({type:`SET_FILTERS`,filters:e})},[]),A=(0,X.useCallback)((e,t)=>{let{filters:n}=c.current,i=e.startsWith($x),a=i?n.features.allOf.filter(t=>t!==e):t?[...new Set([...n.features.allOf,e])]:n.features.allOf.filter(t=>t!==e),o=i&&t?[...new Set([...n.features.anyOf,e])]:n.features.anyOf.filter(t=>t!==e),s=n.features.noneOf.filter(t=>t!==e);r({type:`SET_FILTERS`,filters:{...n,features:{allOf:a,anyOf:o,noneOf:s}}})},[]),j=(0,X.useCallback)((e,t)=>{let{filters:n}=c.current,i=n.features.allOf.filter(t=>t!==e),a=n.features.anyOf.filter(t=>t!==e),o=n.features.noneOf.filter(t=>t!==e);t===`allOf`?i.push(e):t===`anyOf`?a.push(e):t===`noneOf`&&o.push(e),r({type:`SET_FILTERS`,filters:{...n,features:{allOf:i,anyOf:a,noneOf:o}}})},[]),M=(0,X.useCallback)(()=>{let{filters:e}=c.current;r({type:`SET_GEO_SELECTION`,selection:null}),r({type:`SET_FILTERS`,filters:{...Ze,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}});let t=new URLSearchParams(i.search);t.delete(`q`),t.delete(`search`),t.set(`q`,``),a({pathname:i.pathname,search:t.toString(),hash:i.hash},{replace:!0})},[i.pathname,i.search,i.hash,a]),N=(0,X.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),P=(0,X.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),ee=(0,X.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),F=(0,X.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),I=(0,X.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),te=(0,X.useCallback)(e=>{r({type:`SET_GEO_SELECTION`,selection:e})},[]),L=(0,X.useCallback)((e,t=null)=>{r({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),R=(0,X.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:n,activeTreeName:a,activeContextPath:s,filters:u,geoSelection:d,isSaving:f}=c.current;if(!f){r({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&n&&s){let e=a||`context`,t=dS(await _c(n,e),s),r=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await Ro(n,s,{metadata:{...t?.metadata||{},toolbox:rS(u)},querySpec:{features:u.features,filters:[...it(u.timeline),...En(u.geo)],query:r.trim()||void 0,sort:u.sort?.sortBy?u.sort:null}},e),Ms(n,e)}else if(e===`context`&&t){let e=(await Tl(t,o)).metadata||{},n=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await dl(t,{metadata:{...e,toolbox:u,toolboxGeoSelection:d,toolboxSearchQuery:n.trim()||void 0},...kn(u,d,l)},o)}let c=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;r({type:`SET_SAVED_FILTERS`,savedFilters:u,savedSearchQuery:c.trim()||null,hydrating:!0}),e===`context`&&r({type:`SET_SAVED_GEO_SELECTION`,selection:d})}finally{r({type:`SET_SAVING`,isSaving:!1})}}},[i.search,o,l]),ne=(0,X.useCallback)(e=>{let t=c.current.availableBitmaps.filter(t=>t!==e);r({type:`SET_BITMAPS`,keys:t});let n=c.current.filters,i={...n,features:{allOf:n.features.allOf.filter(t=>t!==e),anyOf:n.features.anyOf.filter(t=>t!==e),noneOf:n.features.noneOf.filter(t=>t!==e)}};JSON.stringify(i.features)!==JSON.stringify(n.features)&&r({type:`SET_FILTERS`,filters:i})},[]),re=(0,X.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Nc(t,e),ne(e)},[ne]),ie=(0,X.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await vs(t,e);return ne(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[ne]),ae=(0,X.useCallback)(()=>{let e=c.current.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),as(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[]),z=(0,X.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await hs(t,e),ae()},[ae]),oe=(0,X.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await os(t,e);let n=c.current.availableTimelines.filter(t=>t!==e);r({type:`SET_TIMELINES`,names:n});let i=c.current.filters,a=i.timeline.selectedTimelines.filter(t=>t!==e);a.length!==i.timeline.selectedTimelines.length&&r({type:`SET_FILTERS`,filters:{...i,timeline:{...i.timeline,selectedTimelines:a}}})},[]),{features:se,timeline:ce,geo:V,lens:le}=n.filters,ue=se.allOf.length>0||se.anyOf.length>0||se.noneOf.length>0||ce.quickFilter!==null||(ce.customRanges?.length??0)>0||(ce.selectedTimelines?.length??0)>0||V.bbox!==null||le.gps!==null||le.ids!==null||n.geoSelection!==null;return(0,Z.jsx)(al.Provider,{value:{state:n,setView:g,toggleView:_,closeT1:v,openAgentT2:y,closeT2:b,openAdd:x,openAddPicker:S,openAddRelated:C,closeAdd:w,openEdit:T,setToolsTab:E,openApplet:D,setAccentColor:O,setFilters:k,setFeatureToggle:A,setFeatureMode:j,clearFilters:M,hasActiveFilters:ue,setTimelineFilter:P,setGeoBBox:ee,setLensGps:F,setLensIds:I,setGeoSelection:te,setMapDocuments:L,setSort:N,setLiveEnabled:h,saveFilters:R,deleteBitmap:re,deleteDataset:ie,createTimeline:z,deleteTimeline:oe,refreshTimelines:ae},children:e})}function pS(e){let t=new URLSearchParams(e),n=t.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(t.get(`search`)||``).trim();return t.has(`q`)?n:r?[r]:[]}function mS(){let{state:e,setFilters:t}=ol();return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:e.filters.geo.includeUnlocated??!1,onChange:n=>t({...e.filters,geo:{...e.filters.geo,includeUnlocated:n.target.checked}})}),`Include documents without a location`]})}var hS=p(),gS=n(Nl(),1);Pl();var _S=`#8b5cf6`,vS=`#94a3b8`,yS={color:_S,weight:2,fillColor:_S,fillOpacity:.12},bS={color:_S,weight:2,dashArray:`5,5`,fillColor:_S,fillOpacity:.06},xS=e=>Math.round(e*1e6)/1e6;function SS(e){let t=e<10?32:e<100?38:44,n=`<div style="display:flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:9999px;background:${_S};color:#fff;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4);font:600 12px system-ui,sans-serif;cursor:pointer">${e}</div>`;return gS.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var CS=e=>e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e]),wS=new Map;function TS(e){let t=wS.get(e);return t??(t=(0,hS.renderToStaticMarkup)((0,X.createElement)(nS(e),{width:13,height:13,strokeWidth:2.5})),wS.set(e,t)),t}var ES=new Map;function DS(e,t){let n=`${e}|${+!!t}`,r=ES.get(n);if(!r){let i=`<div style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:9999px;background:${t?_S:vS};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${TS(e)}</div>`;r=gS.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),ES.set(n,r)}return r}function OS(){let{state:e,setGeoSelection:t,setGeoBBox:n}=ol(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=I(),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(null),p=(0,X.useRef)([]),m=(0,X.useRef)(!1),[h,g]=(0,X.useState)(`idle`),[_,v]=(0,X.useState)(0),y=(0,X.useRef)(h),b=(0,X.useMemo)(()=>r.reduce((e,t)=>e+ +!!j(t),0),[r]),x=(0,X.useMemo)(()=>i?r.reduce((e,t)=>{let n=j(t);return e+(n&&P(n.lat,n.lon,i)?1:0)},0):0,[r,i]),S=(0,X.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&gS.default.polyline(t,bS).addTo(e),t.forEach(t=>gS.default.circleMarker(t,{radius:4,color:_S,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),C=(0,X.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),w=(0,X.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:xS(e.lat),lon:xS(e.lng)}))}),C(),g(`idle`)},[t,C]),T=(0,X.useCallback)(()=>{C(),g(`idle`),t(null),n(null)},[C,t,n]);(0,X.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=gS.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});gS.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=gS.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>SS(e.getChildCount())}).addTo(t),f.current=gS.default.layerGroup().addTo(t),l.current=t;let r=t.getContainer(),i=null,a=null,o=()=>{a&&=(a.remove(),null)},s=e=>{if(y.current===`rect`){e.preventDefault(),i=t.mouseEventToLatLng(e),o();try{r.setPointerCapture(e.pointerId)}catch{}}},m=e=>{if(y.current!==`rect`||!i)return;e.preventDefault();let n=gS.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=gS.default.rectangle(n,bS).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=gS.default.latLngBounds(i,t.mouseEventToLatLng(e));i=null,o();try{r.releasePointerCapture(e.pointerId)}catch{}let s=a.getSouthWest(),c=a.getNorthEast();s.lat!==c.lat&&s.lng!==c.lng&&n({minLat:xS(s.lat),minLon:xS(s.lng),maxLat:xS(c.lat),maxLon:xS(c.lng)}),g(`idle`)};r.addEventListener(`pointerdown`,s),r.addEventListener(`pointermove`,m),r.addEventListener(`pointerup`,h),r.addEventListener(`pointercancel`,h);let _=e=>{y.current===`polygon`&&(p.current=[...p.current,e.latlng],v(p.current.length),S())};t.on(`click`,_);let b=new ResizeObserver(()=>t.invalidateSize());b.observe(e);let x=window.setTimeout(()=>t.invalidateSize(),120);return()=>{r.removeEventListener(`pointerdown`,s),r.removeEventListener(`pointermove`,m),r.removeEventListener(`pointerup`,h),r.removeEventListener(`pointercancel`,h),t.off(`click`,_),b.disconnect(),window.clearTimeout(x),t.remove(),l.current=null,u.current=null,f.current=null,d.current=null}},[t,n,S]),(0,X.useEffect)(()=>{y.current=h;let e=l.current;if(!e)return;let t=e.getContainer();h!==`polygon`&&p.current.length&&C(),h===`rect`?(e.dragging.disable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=`none`):h===`polygon`?(e.dragging.enable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=``):(e.dragging.enable(),e.doubleClickZoom.enable(),t.style.cursor=``,t.style.touchAction=``)},[h,C]),(0,X.useEffect)(()=>{let e=l.current,t=c.current;if(!e||!t)return;let n=new ResizeObserver(()=>e.invalidateSize());return n.observe(t),()=>n.disconnect()},[]),(0,X.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=j(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||P(t.lat,t.lon,i),c=gS.default.marker([t.lat,t.lon],{icon:DS(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(CS(Ho(e).title),{direction:`top`,offset:[0,-14]}),c.on(`click`,()=>{y.current===`idle`&&s(e,a??``)}),o.push(c)}t.addLayers(o),!m.current&&n.length&&!i&&(m.current=!0,e.fitBounds(gS.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,X.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=gS.default.layerGroup();o&&gS.default.rectangle(gS.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),yS).addTo(t),i?.kind===`polygon`&&gS.default.polygon(i.points.map(e=>[e.lat,e.lon]),yS).addTo(t),t.addTo(e),d.current=t},[o,i]);let E=h===`rect`?`Drag a box on the map…`:h===`polygon`?`Tap to add points${_?` · ${_}`:``}`:o||i?`Area selected`:`Pan & pick an area`,D=`flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:K(D,h===`rect`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Drag a rectangle to select an area`,children:[(0,Z.jsx)(Sa,{className:`h-3.5 w-3.5`}),`Box`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:K(D,h===`polygon`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Tap points to enclose an area`,children:[(0,Z.jsx)(Or,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:w,disabled:_<3,className:K(D,`border-primary bg-primary text-primary-foreground hover:bg-primary disabled:opacity-40 disabled:hover:bg-primary`),title:`Close the polygon and filter`,children:[(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:C,className:K(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:T,disabled:!o&&!i&&h===`idle`,className:K(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent`),title:`Clear the area selection`,children:[(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,Z.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:E})]}),(0,Z.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,Z.jsx)(`div`,{ref:c,className:`absolute inset-0`}),b===0&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border px-3 py-2 shrink-0 text-[11px] text-muted-foreground`,children:[(0,Z.jsx)(mi,{className:`h-3 w-3`}),b,` of `,r.length,` located`,i&&(0,Z.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,x,` in area`]})]})]})}var kS=[{label:`25 m`,m:25},{label:`100 m`,m:100},{label:`500 m`,m:500},{label:`2 km`,m:2e3},{label:`10 km`,m:1e4}],AS=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,jS=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,MS=e=>Math.round(e*1e4)/1e4;function NS(){let{state:e,setLensGps:t,setLensIds:n}=ol(),r=e.filters.lens,i=e.activeWorkspaceName,a=r.gps?.radiusM??100,[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(r.gps?.radiusM??100),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(0),[m,h]=(0,X.useState)(`prompt`),g=(0,X.useRef)(null),_=(0,X.useRef)(c);(0,X.useEffect)(()=>{_.current=c},[c]);let v=`geolocation`in navigator&&window.isSecureContext;(0,X.useEffect)(()=>{if(!navigator.permissions?.query)return;let e=null;return navigator.permissions.query({name:`geolocation`}).then(t=>{e=t,h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`),t.onchange=()=>h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`)}).catch(()=>{}),()=>{e&&(e.onchange=null)}},[]),(0,X.useEffect)(()=>{if(!o||!v)return;let e=navigator.geolocation.watchPosition(e=>{let n=MS(e.coords.latitude),r=MS(e.coords.longitude);t({lat:n,lon:r,radiusM:_.current})},e=>d(e.code===e.PERMISSION_DENIED?`Location permission denied.`:e.message),{enableHighAccuracy:!0,maximumAge:15e3,timeout:2e4});return g.current=e,()=>{navigator.geolocation.clearWatch(e),g.current=null}},[o,v,f,t]);let y=e=>{s(e),d(null),e||t(null)},b=()=>{d(null),s(!0),p(e=>e+1)},x=e=>{l(e),r.gps&&t({...r.gps,radiusM:e})},S=Ex(),{rateMs:C,setRateMs:w,maxDistance:T,setMaxDistance:E,error:D}=S,O=S.running&&S.consumer===`filter`,k=S.running&&S.consumer!==`filter`;Dx(O);let A=t=>{i&&S.start(t,`filter`,{workspaceRef:i,contextPath:e.activeContextPath})},j=O,M=S.snapshotSize??S.camera?.size,N=!!M&&M.height>M.width;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[e.activeContextType===`context`&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Point the camera at an object to find visually related content in this context. `,e.liveEnabled?`Bound devices follow your matches as you move.`:`Enable Live to show the matches on your other devices.`]}),(0,Z.jsx)(mS,{}),(0,Z.jsxs)(`section`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,disabled:!v,onChange:e=>y(e.target.checked)}),(0,Z.jsx)(Aa,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{children:`Track this device’s GPS`})]}),(0,Z.jsx)(`select`,{className:AS,value:c,onChange:e=>x(Number(e.target.value)),disabled:!o,children:kS.map(e=>(0,Z.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?m===`denied`?(0,Z.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):u?(0,Z.jsxs)(`span`,{className:`text-destructive`,children:[u,` `,(0,Z.jsx)(`button`,{type:`button`,onClick:b,className:`underline hover:text-foreground`,children:`Request again`})]}):r.gps?`Showing documents within ${a>=1e3?`${a/1e3} km`:`${a} m`} of ${r.gps.lat}, ${r.gps.lon}.`:o?`Waiting for a position fix…`:`Resurface documents geotagged near your current position.`:`Needs a secure context (https or localhost) with location access.`})]}),(0,Z.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,Z.jsxs)(`button`,{type:`button`,onClick:S.stop,className:`flex h-7 items-center gap-1 rounded-md bg-destructive px-2.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,children:[(0,Z.jsx)(Yi,{className:`h-3.5 w-3.5`}),` `,S.source===`photo`?`Close photo`:`Stop ${S.source===`camera`?`camera`:`recording`}`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>A(`camera`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(Ur,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>A(`screen`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(mr,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(Jx,{consumer:`filter`,workspaceRef:i??``,contextPath:e.activeContextPath,disabled:k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`}),(0,Z.jsx)(`select`,{className:AS,value:C,onChange:e=>w(Number(e.target.value)),disabled:!i,title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:Fx.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(jS,`w-24`),placeholder:`max dist`,inputMode:`decimal`,value:T,onChange:e=>E(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K (loose but tunable).`})]}),(0,Z.jsxs)(`div`,{className:K(`relative overflow-hidden rounded-lg border border-border bg-black/80`,j?N?`aspect-[3/4] max-h-[60vh]`:`aspect-video`:`hidden`),children:[(0,Z.jsx)(Bx,{className:`h-full w-full`,interactive:!0}),(0,Z.jsx)(Kx,{})]}),j&&(0,Z.jsx)(Gx,{}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?(0,Z.jsx)(`span`,{className:`text-destructive`,children:D}):j?S.snapshot?`Snapshot: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. The photo is not stored. Tap Live to resume the feed.`:`Live: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. Tap the shutter to search one still frame. Frames are ephemeral, never stored. Closing the toolbox keeps it running.`:k?`The Lens applet is using the camera. Stop it there first.`:r.ids===null?i?`Point a camera (or share a screen). The view narrows to what the feed matches.`:`Open a workspace to refine with a live feed.`:`The current view holds ${r.ids.length} camera match${r.ids.length===1?``:`es`}. Save to keep this view, or clear matches to remove the camera filter.`}),!j&&r.ids!==null&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(null),className:`min-h-10 rounded-md border border-border px-3 text-xs hover:bg-muted`,children:`Clear matches`})]})]})}var PS={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function FS(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t%360+360)%360}function IS(e){return PS[e]??`oklch(var(--data-l) var(--data-c) ${FS(e)})`}var LS=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],RS=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],zS=[`Yesterday`,`Today`,`Tomorrow`],BS=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],VS=10,HS=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function US(e,t){let n=new Date;switch(e){case`millennium`:{let e=Math.floor(n.getFullYear()/1e3)*1e3;return new Date(e-t*1e3,0,1)}case`century`:{let e=Math.floor(n.getFullYear()/100)*100;return new Date(e-t*100,0,1)}case`decade`:{let e=Math.floor(n.getFullYear()/10)*10;return new Date(e-t*10,0,1)}case`year`:return new Date(n.getFullYear()-t,0,1);case`month`:return new Date(n.getFullYear(),n.getMonth()-t,1);case`week`:{let e=(n.getDay()+6)%7,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()-e);return r.setDate(r.getDate()-t*7),r}}}function WS(e,t){let n=new Date(t);switch(e){case`millennium`:n.setFullYear(n.getFullYear()+1e3);break;case`century`:n.setFullYear(n.getFullYear()+100);break;case`decade`:n.setFullYear(n.getFullYear()+10);break;case`year`:n.setFullYear(n.getFullYear()+1);break;case`month`:n.setMonth(n.getMonth()+1);break;case`week`:n.setDate(n.getDate()+7)}return n}function GS(e,t,n){if(n===0)return`Now`;switch(e){case`millennium`:case`century`:case`decade`:{let e=t.getFullYear();return e<=0?`${1-e} BCE`:`${e}`}case`year`:return`${t.getFullYear()}`;case`month`:return`${HS[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${HS[t.getMonth()]} – ${e.getDate()} ${HS[e.getMonth()]}`}}}function KS(e,t){return Array.from({length:t},(t,n)=>{let r=US(e,n),i=WS(e,r);return{offset:n,label:GS(e,r,n),start:r,end:i,isNow:n===0}})}var qS={yesterday:5,today:5,tomorrow:5,lastWeek:5,thisWeek:5,nextWeek:5,lastMonth:4,thisMonth:4,nextMonth:4,lastYear:3,thisYear:3,nextYear:3,lastDecade:2,thisDecade:2,nextDecade:2,lastCentury:1,thisCentury:1,nextCentury:1,lastMillennium:0,thisMillennium:0,nextMillennium:0};function JS(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function YS(e,t){let n=eC(e);return n?(n.setDate(n.getDate()+t),JS(n)):e}function XS(e){let t=[...e].sort((e,t)=>e.start.localeCompare(t.start)),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=YS(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function ZS(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return XS([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=YS(t,-1)&&r.push({start:n.start,end:YS(t,-1)}),YS(t,1)<=n.end&&r.push({start:YS(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function QS(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:JS(t.start),end:JS(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function $S({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=ol(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,X.useState)(3),[d,f]=(0,X.useState)(VS),[p,m]=(0,X.useState)(new Set),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(e);e!==_&&(v(e),e&&qS[e]!==void 0&&u(qS[e]),m(new Set));let[y,b]=(0,X.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=BS[l],S=KS(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,X.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{Go(a,{names:r,buckets:KS(x.unit,d).map(e=>QS(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:En(c.geo),applyCanvasSpec:!1}).then(t=>{e||g(t)}).catch(()=>{e||g([])})},250);return()=>{e=!0,clearTimeout(t)}},[a,o,s,x.unit,d,w,C]);let T=a&&r.length>0?h:[],E=Math.max(1,...T.map(e=>e.total)),D=e=>{u(t=>Math.max(0,Math.min(5,t+e))),f(VS),m(new Set)},O=(0,X.useCallback)((e,t)=>{m(r=>{let i;if(t&&r.size>0){let t=Math.min(e,...r),n=Math.max(e,...r);i=new Set(r);for(let e=t;e<=n;e++)i.add(e)}else i=new Set(r),i.has(e)?i.delete(e):i.add(e);let a=[...i].sort((e,t)=>e-t),o=[];for(let e of a){let t=o[o.length-1];t&&e===t[1]+1?t[1]=e:o.push([e,e])}return n(o.map(([e,t])=>{let n=S.find(e=>e.offset===t).start,r=new Date(S.find(t=>t.offset===e).end);return r.setDate(r.getDate()-1),{start:JS(n),end:JS(r)}})),i})},[S,n]);return(0,Z.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>D(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom in (finer periods)`,children:(0,Z.jsx)($n,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>D(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom out (coarser periods)`,children:(0,Z.jsx)(Dr,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-1.5 space-y-1 touch-target`,children:[S.map(e=>{let t=p.has(e.offset),n=T[e.offset],r=n?.total??0,i=r>0?Math.log1p(r)/Math.log1p(E):0,a=n&&r>0?`: ${r} doc${r===1?``:`s`} (${Object.entries(n.counts).map(([e,t])=>`${e}: ${t}`).join(`, `)})`:``;return(0,Z.jsxs)(`button`,{type:`button`,onClick:t=>O(e.offset,t.shiftKey),title:`${e.isNow?`Now`:e.label}${a}. Click to tag, shift-click to fill range`,className:K(`w-full flex items-center gap-2 rounded-2xl px-3 py-1.5 text-xs font-medium transition-colors select-none text-left`,t?`bg-primary text-primary-foreground`:e.isNow?`bg-primary/10 text-primary hover:bg-primary/20`:`bg-card text-foreground hover:bg-muted shadow-elevation-1`),children:[e.isNow&&(0,Z.jsx)(Zn,{className:`w-3 h-3 shrink-0`}),(0,Z.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,Z.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,Z.jsx)(`span`,{className:K(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,Z.jsx)(`span`,{className:`mt-1 flex h-[3px] overflow-hidden rounded-full`,style:{width:`${Math.max(8,i*100)}%`},children:Object.entries(n.counts).map(([e,t])=>(0,Z.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:IS(e)}},e))})]})]},e.offset)}),d<200&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+VS),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function eC(e){let t=/^(-?\d{1,6})-(\d{2})-(\d{2})$/.exec(e);return t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):null}function tC({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,X.useState)(()=>{let t=e[0]?.start&&eC(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=e=>a(t=>{let n=new Date(t.y,t.m+e,1);return{y:n.getFullYear(),m:n.getMonth()}}),d=(e,r)=>{if(r){n(e),s(null),l(null);return}if(!o){s(e);return}let[i,a]=o<=e?[o,e]:[e,o];t(i,a),s(null),l(null)},f=new Date(i.y,i.m,1),p=new Date(f);p.setDate(p.getDate()-(f.getDay()+6)%7);let m=Array.from({length:42},(e,t)=>{let n=new Date(p);return n.setDate(n.getDate()+t),n}),[h,g]=o?c&&c!==o?o<=c?[o,c]:[c,o]:[o,o]:[null,null],_=t=>e.some(e=>t>=e.start&&t<=e.end),v=t=>e.some(e=>t===e.start||t===e.end),y=JS(r);return(0,Z.jsxs)(`div`,{className:`select-none`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(-12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous year`,children:(0,Z.jsx)(Ir,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous month`,children:(0,Z.jsx)(Wn,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>a({y:r.getFullYear(),m:r.getMonth()}),className:`text-xs font-semibold text-foreground hover:text-primary transition-colors`,title:`Jump to current month`,children:[HS[i.m],` `,i.y]}),(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next month`,children:(0,Z.jsx)(Xa,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next year`,children:(0,Z.jsx)(yr,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=JS(e),n=e.getMonth()===i.m,r=h!==null&&g!==null&&t>=h&&t<=g,a=t===h||t===g,s=!o&&_(t),c=a||s&&v(t);return(0,Z.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:K(`h-6 text-[11px] tabular-nums transition-colors`,c?`bg-primary text-primary-foreground rounded-md`:r||s?`bg-primary/15 text-foreground`:n?`text-foreground hover:bg-muted rounded-md`:`text-muted-foreground/40 hover:bg-muted rounded-md`,t===y&&!c&&`font-bold text-primary`),children:e.getDate()},t)})}),(0,Z.jsx)(`p`,{className:`mt-1.5 text-[10px] text-muted-foreground/70`,children:o?`From ${o}: pick the end date`:`Click start + end. Ctrl+click adds/removes single days.`})]})}function nC({label:e,checked:t,onChange:n,color:r}){return(0,Z.jsxs)(`div`,{role:`switch`,"aria-checked":t,tabIndex:0,onClick:()=>n(!t),onKeyDown:e=>(e.key===` `||e.key===`Enter`)&&n(!t),className:`flex items-center justify-between gap-3 cursor-pointer select-none outline-none focus-visible:ring-2 focus-visible:ring-ring rounded`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,Z.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,Z.jsx)(`div`,{className:K(`relative w-10 h-5 rounded-full transition-colors shrink-0`,!t&&`bg-accent dark:bg-muted-foreground`),style:t?{backgroundColor:r}:void 0,children:(0,Z.jsx)(`div`,{className:K(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function rC(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=ol(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(`quick`),[_,v]=(0,X.useState)(!1),{showToast:y}=wo(),b=new Set(a.selectedTimelines??[]),x=(0,X.useMemo)(()=>{let e=[];return a.indexCreated&&e.push(`crud:created`),a.indexUpdated&&e.push(`crud:updated`),a.indexDeleted&&e.push(`crud:deleted`),a.contentEvents&&e.push(`content`),e.push(...a.selectedTimelines??[]),e.length>0?e:[`crud:created`]},[a.indexCreated,a.indexUpdated,a.indexDeleted,a.contentEvents,a.selectedTimelines]),S=e=>{let n=new Set(b);n.has(e)?n.delete(e):n.add(e),t({selectedTimelines:[...n]})},C=async()=>{let e=l.trim();if(e){f(!0);try{await n(e),u(``),y({title:`Timeline created`,description:e})}catch(e){y({title:`Failed to create timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{f(!1)}}},w=async e=>{if(window.confirm(`Delete timeline "${e}"?\n\nThis removes all interval data for this timeline.`)){m(e);try{await r(e),y({title:`Timeline deleted`,description:e})}catch(e){y({title:`Failed to delete timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{m(null)}}},T=o.filter(e=>!e.startsWith(`crud:`)&&e!==`content`),D=E(a),O=D.length>0,k=(0,X.useCallback)(e=>{t({customRanges:e,customRange:null,...e.length>0?{quickFilter:null}:{}})},[t]),A=e=>{t({quickFilter:a.quickFilter===e?null:e,customRanges:[],customRange:null})},j=e=>{t({customRanges:D.filter((t,n)=>n!==e),customRange:null})},M=(e,t)=>(0,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!O;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>A(e),className:K(`text-xs px-1.5 py-1 rounded-md transition-colors truncate`,r?`bg-primary text-primary-foreground font-medium`:`bg-muted/50 text-foreground hover:bg-muted`),title:e,children:t?zS[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,Z.jsx)($S,{quickFilterKey:a.quickFilter,activeRangeCount:D.length,onSelectRanges:k,histogramNames:x}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,Z.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:K(`px-2 py-0.5 transition-colors`,h===`quick`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Quick filters`,children:(0,Z.jsx)(lr,{className:`w-3 h-3`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:K(`px-2 py-0.5 transition-colors`,h===`calendar`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Calendar range picker`,children:(0,Z.jsx)(ir,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,Z.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),LS.map((e,t)=>M(e,t===0)),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),className:`flex items-center gap-1 text-[11px] text-muted-foreground/70 hover:text-muted-foreground pt-1 transition-colors`,children:[(0,Z.jsx)(qr,{className:K(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&RS.map(e=>M(e,!1))]}):(0,Z.jsx)(tC,{ranges:D,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:ZS(D,e),customRange:null,quickFilter:null})}),O&&(0,Z.jsx)(`div`,{className:`mt-2 space-y-1`,children:D.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-md bg-primary/10 border border-primary/30 px-2.5 py-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>j(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,Z.jsx)(vr,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(nC,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:IS(`crud:created`)}),(0,Z.jsx)(nC,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:IS(`crud:updated`)}),(0,Z.jsx)(nC,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:IS(`crud:deleted`)}),(0,Z.jsx)(nC,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:IS(`content`)})]}),(0,Z.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,Z.jsx)(Er,{className:`w-3 h-3`})})]}),c?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Ti,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):T.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,Z.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:T.map(e=>{let t=b.has(e),n=IS(e);return(0,Z.jsxs)(`div`,{className:K(`flex items-center gap-2.5 group rounded-md px-2 py-1.5 cursor-pointer transition-colors`,t?`bg-muted/60`:`hover:bg-muted/30`),onClick:()=>S(e),children:[(0,Z.jsx)(`div`,{className:K(`shrink-0 w-4 h-4 rounded border-2 flex items-center justify-center transition-colors`,!t&&`border-muted-foreground/40 bg-transparent group-hover:border-muted-foreground/70`),style:t?{backgroundColor:n,borderColor:n}:void 0,children:t&&(0,Z.jsx)(`svg`,{className:K(`w-2.5 h-2.5`,tt(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,Z.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,Z.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,Z.jsx)(`span`,{className:`shrink-0 text-[10px] px-1 py-0.5 rounded bg-muted text-muted-foreground select-none`,title:`Observed granularity for "${e}" — each entry is indexed at its own precision (a bare year at year cells, a full date at day cells)`,children:(s[e]??[]).join(`·`)}),(0,Z.jsx)(`button`,{type:`button`,disabled:p===e,onClick:t=>{t.stopPropagation(),w(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:`Delete timeline "${e}"`,children:p===e?(0,Z.jsx)(Ti,{className:`w-3 h-3 animate-spin`}):(0,Z.jsx)(Qr,{className:`w-3 h-3`})})]},e)})}),(0,Z.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,Z.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&C(),placeholder:`New timeline (e.g. wikipedia, trips)…`,title:`A timeline is a named time axis. Entries index at their own precision — a bare year at year granularity, a full date at day granularity — nothing to configure.`,className:`flex-1 px-2 py-1 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`}),(0,Z.jsx)(`button`,{type:`button`,onClick:C,disabled:d||!l.trim(),className:`shrink-0 p-1.5 rounded-md bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 touch-target`,title:`Create timeline`,children:d?(0,Z.jsx)(Ti,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(br,{className:`w-3.5 h-3.5`})})]})]})]})]})}var iC={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},aC=`data/dataset/default`;function oC(e){let t=new Map;for(let n of e){let e=n.startsWith(`data/backend/`)?`data/backend`:n.startsWith(`data/mime/`)?`data/mime`:n.startsWith(`data/dataset/`)?`data/dataset`:n.split(`/`)[0];t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}var sC=[`off`,`anyOf`,`allOf`,`noneOf`];function cC(e){return sC[(sC.indexOf(e)+1)%sC.length]}var lC=[{m:`anyOf`,label:`any`,on:`bg-info text-info-foreground`},{m:`allOf`,label:`all`,on:`bg-success text-success-foreground`},{m:`noneOf`,label:`not`,on:`bg-destructive text-destructive-foreground`}];function uC({mode:e,onSet:t}){return(0,Z.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:lC.map(n=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:K(`px-2 py-0.5 text-[11px] font-medium transition-colors`,e===n.m?n.on:`bg-transparent text-muted-foreground hover:bg-muted hover:text-foreground`),title:`${n.label}: ${n.m}`,children:n.label},n.m))})}function dC({keys:e,modeOf:t,onCycle:n}){return e.length?(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=tS(e),a=t(e),o=lC.find(e=>e.m===a);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:K(`relative flex flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border p-3 min-h-[4.5rem] transition-colors select-none`,a===`off`?`border-border bg-muted/40 text-foreground hover:bg-muted`:a===`anyOf`?`border-info bg-info/10 text-foreground`:a===`allOf`?`border-success bg-success/10 text-foreground`:`border-destructive bg-destructive/10 text-foreground`),children:[o&&(0,Z.jsx)(`span`,{className:K(`absolute right-1.5 top-1.5 rounded px-1 py-0.5 text-[9px] font-semibold leading-none`,o.on),children:o.label}),(0,Z.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function fC(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=ol(),{availableBitmaps:o,bitmapsLoading:s,filters:c}=e,l=new Set(c.features.allOf),u=new Set(c.features.anyOf),d=new Set(c.features.noneOf),f=e=>l.has(e)?`allOf`:u.has(e)?`anyOf`:d.has(e)?`noneOf`:`off`,[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(null),{showToast:_}=wo(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==aC){let t=e.slice(13);if(!window.confirm(`Drop dataset "${t}"?\n\nALL documents stamped with this dataset will be PERMANENTLY DELETED. Documents in other datasets (or the default dataset) are unaffected. Re-ingesting recreates the dataset from scratch.`))return;g(e);try{let n=await a(e);_({title:`Dataset dropped`,description:`"${t}": ${n} document(s) deleted`})}catch(e){_({title:`Dataset drop failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}return}if(!e.startsWith(`data/`)&&window.confirm(`Delete bitmap "${e}"?\n\nThis removes the bitmap from the database. Documents are unaffected, but any features/filters relying on this bitmap will lose their grouping.`)){g(e);try{await i(e),_({title:`Bitmap deleted`,description:e})}catch(e){_({title:`Delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}}};if(s)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Ti,{className:`w-4 h-4 animate-spin text-muted-foreground`})});let y=[...c.features.allOf,...c.features.anyOf,...c.features.noneOf],b=[...new Set([...o,...y])];if(!b.length)return(0,Z.jsx)(`div`,{className:`p-4 text-xs text-muted-foreground text-center py-10`,children:`No feature bitmaps found`});let x=p.trim().toLowerCase(),S=x?b.filter(e=>e.toLowerCase().includes(x)):b,C=S.filter(e=>e.startsWith($x)).sort((e,t)=>{let n=Object.keys(eS),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=oC(S.filter(e=>!e.startsWith($x))),T=w.get(`data/dataset`);return T&&!T.includes(aC)&&(!x||aC.includes(x))&&T.unshift(aC),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(qa,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,Z.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:`Search features…`,className:`w-full pl-7 pr-3 py-1.5 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:n,disabled:!r,className:`flex items-center gap-1.5 w-full justify-center px-2.5 py-1.5 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,Z.jsx)(vr,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsx)(dC,{keys:C,modeOf:f,onCycle:e=>t(e,cC(f(e)))}),w.size===0&&C.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:iC[e]??e}),(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===aC,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,Z.jsxs)(`div`,{onClick:()=>t(e,cC(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,cC(o)))},className:K(`flex items-center gap-2 group rounded-md pl-2 pr-1.5 py-1 border-l-2 transition-colors cursor-pointer select-none`,n%2==0?`bg-muted/50`:`bg-transparent`,`hover:bg-muted`,o===`off`?`border-l-transparent`:o===`anyOf`?`border-l-blue-500 !bg-info/10`:o===`allOf`?`border-l-emerald-500 !bg-success/10`:`border-l-rose-500 !bg-destructive/10`),children:[(0,Z.jsxs)(`span`,{className:`flex-1 min-w-0 text-xs font-mono text-foreground truncate`,title:i?`Virtual dataset: documents not stamped with any dataset. Included by default; "not" hides them, "all" shows only them.`:e,children:[e,i&&(0,Z.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,Z.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(uC,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,Z.jsx)(`button`,{type:`button`,disabled:h===e,onClick:t=>{t.stopPropagation(),v(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:a?`Drop dataset "${e.slice(13)}" (DELETES its documents)`:`Delete bitmap "${e}" from database`,"aria-label":a?`Drop dataset ${e}`:`Delete bitmap ${e}`,children:h===e?(0,Z.jsx)(Ti,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(Qr,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function pC(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i,setLiveEnabled:a}=ol(),{toolsTab:o,isDirty:s,isSaving:c,activeContextType:l,savedSearchQuery:u}=e,d=vn(),f=(new URLSearchParams(d.search).has(`q`)||new URLSearchParams(d.search).has(`search`)?pS(d.search):u?[u]:[])[0]||``,p=l!==null&&f.trim()!==(u||``),m=e.filters.sort??Ze.sort,h=m.sortBy!==Ze.sort.sortBy||m.order!==Ze.sort.order,g=i||!!f.trim()||h,_=(0,Z.jsxs)(Z.Fragment,{children:[g&&(0,Z.jsxs)(`button`,{type:`button`,onClick:r,title:`Clear all active filters`,className:`flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(vr,{className:`h-3 w-3`}),`Clear`]}),l!==null&&g&&(s||p)&&(0,Z.jsxs)(`button`,{type:`button`,onClick:n,disabled:c,className:`flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary disabled:opacity-60`,children:[c?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Yn,{className:`h-3 w-3`}),`Save filters`]})]});return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex border-b border-border shrink-0`,children:[{id:`features`,label:`Features`},{id:`timeline`,label:`Timeline`},{id:`map`,label:`Map`},{id:`lens`,label:`Lens`}].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:K(`flex-1 py-2.5 text-xs transition-colors`,o===e.id?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),l===`context`&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-1 border-b border-border px-3 py-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-h-8 flex-wrap items-center justify-between gap-x-3 gap-y-1`,children:[(0,Z.jsxs)(`label`,{className:`flex min-h-8 cursor-pointer items-center gap-2 text-sm font-medium`,title:`Live view updates every device bound to this context. Save filters to keep the current view.`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 accent-current`,checked:e.liveEnabled,disabled:new URLSearchParams(d.search).has(`ownerId`),onChange:e=>{a(e.target.checked)}}),`Live view`]}),(0,Z.jsx)(`div`,{className:`ml-auto flex items-center gap-2`,children:_})]}),e.liveError&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-destructive`,children:e.liveError})]}),l!==`context`&&g&&(0,Z.jsx)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:_}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[o===`features`&&(0,Z.jsx)(fC,{}),o===`timeline`&&(0,Z.jsx)(rC,{}),o===`map`&&(0,Z.jsx)(OS,{}),o===`lens`&&(0,Z.jsx)(NS,{})]})]})}function mC(){let e=rx(),t=ul()?.state,n=!!t&&(e?.mode===`context`?t.activeContextType===`context`&&t.activeContextId===e.contextId:e?.mode===`workspace`?t.activeContextType!==`context`&&t.activeWorkspaceName===e.workspaceName&&t.activeTreeName===e.treeName&&t.activeContextPath===e.path:!t.activeWorkspaceName&&!t.activeContextId),r=!n&&e?.mode===`context`?e.contextId:null;return(0,X.useEffect)(()=>{if(!r)return;let e=`context:${r}`,t=()=>B.emit(`subscribe`,{channel:e}),n=B.on(`connect`,t);return t(),()=>{n(),B.emit(`unsubscribe`,{channel:e})}},[r]),n?(0,Z.jsx)(pC,{}):(0,Z.jsx)(fS,{target:e,children:(0,Z.jsx)(Vx,{children:(0,Z.jsx)(pC,{})})})}function hC({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=z(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-(--card-radius) border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,Z.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,Z.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,Z.jsx)(pr,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,Z.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,Z.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:hx(e.updatedAt||e.createdAt)})]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Delete ${o}`,className:`absolute right-1.5 top-1.5 rounded-md bg-background/80 p-1 opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]})}function gC({autoAdd:e}){let t=rx(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=gx(t,Hc),[c,l]=(0,X.useState)(e?`new`:null),{showErrorToast:u}=Oo();return t?(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,Z.jsx)(br,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,Z.jsx)(hC,{doc:e,scope:a,onOpen:()=>l(e),onRemove:()=>{confirm(`Delete "${String(e.data?.title??`Sketch`)}"?`)&&s(e.id).catch(e=>u(e instanceof Error?e.message:`Failed to delete sketch`))}},`${e.id}:${e.checksumArray?.[0]??``}`))}),c&&a&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(H,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var _C=[{id:`terminal`,category:`utilities`,label:`Terminal`,icon:qi,modes:[`context`],description:`Shell sessions for this context`,Component:sx},{id:`filters`,category:`utilities`,label:`Filters`,icon:Ci,modes:[`context`,`global`],description:`Search and filter a workspace or a live context`,Component:mC},{id:`notes`,category:`productivity`,label:`Notes`,icon:Da,modes:[`context`],description:`All notes in the current context, editable in place`,Component:yx},{id:`todo`,category:`productivity`,label:`Todos`,icon:pa,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:wx},{id:`sketch`,category:`creative`,label:`Sketch`,icon:pr,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:gC},{id:`lens`,category:`media`,label:`Lens`,icon:Br,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:Qx}];function vC(e){return _C.filter(t=>t.modes.includes(e))}function yC({target:e,children:t}){return(0,Z.jsx)(nx.Provider,{value:e,children:t})}var bC=`universe`;function xC(){let{appletId:e}=yt(),[t,n]=$t(),r=_C.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||bC,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,X.useMemo)(()=>i?{mode:`context`,contextId:i}:{mode:`workspace`,workspaceName:a,path:o,treeName:s,treeType:s===`directory`?`directory`:`context`},[i,a,o,s]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)([]);(0,X.useEffect)(()=>{Uo().then(d).catch(()=>d([])),ml().then(p).catch(()=>p([]))},[]);let[m,h]=(0,X.useState)(o),[g,_]=(0,X.useState)(o);g!==o&&(_(o),h(o));let v=e=>{let r=new URLSearchParams(t);r.delete(`add`);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r,{replace:!0})};if(!r)return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col items-center justify-center gap-3 surface-desk`,children:[(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:_C.map(e=>(0,Z.jsx)(we,{to:`/apps/${e.id}`,className:`rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted`,children:e.label},e.id))})]});let y=i?`context`:`path`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col surface-desk p-shell gap-shell`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 rounded-xl border bg-card px-3 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,Z.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:K(`px-2.5 py-1 text-xs capitalize transition-colors`,y===e?`bg-foreground text-background`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:e},e))}),y===`path`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:a,onChange:e=>v({workspace:e.target.value,path:`/`}),className:`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Workspace`,children:[!u.some(e=>e.name===a)&&(0,Z.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,Z.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,Z.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),onBlur:()=>{let e=m.trim()||`/`;e!==o&&v({path:e})},onKeyDown:e=>{e.key===`Enter`&&e.target.blur()},spellCheck:!1,placeholder:`/`,className:`h-7 w-40 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,"aria-label":`Path`})]}):(0,Z.jsxs)(`select`,{value:i??``,onChange:e=>v({context:e.target.value}),className:`h-7 max-w-56 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Context`,children:[!i&&(0,Z.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,Z.jsx)(`div`,{className:`grow`})]}),(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-elevation-2`,children:y===`context`&&!i?(0,Z.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:[`Pick a context above to bind `,r.label,` to it.`]}):(0,Z.jsx)(yC,{target:l,children:(0,Z.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})}var SC=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:Wr,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:zr,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:Ya,label:`Offline & cache`,description:`Manage cached content and storage on this device.`}]},{id:`account`,label:`Your account`,description:`Manage your access and the defaults your workspaces inherit.`,items:[{path:`/api-tokens`,icon:qn,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:mr,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:Ta,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:aa,label:`Shared with you`,description:`Find content other people have shared with your account.`}]},{id:`server`,label:`Server administration`,description:`Administrator controls for everyone using this Canvas server.`,items:[{path:`/admin/users`,icon:ar,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:Ma,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/auth`,icon:Ra,label:`Authentication`,description:`Configure sign-in backends: local passwords, LDAP and IMAP.`},{path:`/admin/embedding`,icon:Ta,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:bi,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:vi,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:$r,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:ri,label:`All agents`,description:`Inspect and manage agents across the server.`}]},{id:`information`,label:`Information`,description:`Information about your Canvas installation.`,items:[{path:`/about`,icon:Xn,label:`About Canvas`,description:`View versions and information about this installation.`}]}],CC=[`/settings`,...SC.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function wC(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var TC=[{id:`classic`,name:`Classic`,description:`Menu panel on the left, one content sheet.`},{id:`strip`,name:`Canvas strip (beta)`,description:`Experimental. Menus and canvases side by side in a strip you walk with the arrow keys or a swipe. Shift+click opens a second canvas to the right; pins open their own row.`}],EC=`canvas:layout`;function DC(){try{return localStorage.getItem(EC)===`strip`?`strip`:`classic`}catch{return`classic`}}var OC=DC(),kC=new Set;function AC(){for(let e of kC)e()}function jC(){return OC}function MC(e){try{e===`strip`?localStorage.setItem(EC,e):localStorage.removeItem(EC)}catch{}OC=e,AC()}function NC(e){kC.add(e);let t=t=>{(t.key===EC||t.key===null)&&(OC=DC(),e())};return window.addEventListener(`storage`,t),()=>{kC.delete(e),window.removeEventListener(`storage`,t)}}function PC(){return(0,X.useSyncExternalStore)(NC,jC,()=>`classic`)}var FC=[{id:`shift`,name:`Shift + arrows`,description:`Shift with an arrow key moves between columns and rows.`},{id:`alt`,name:`Alt + arrows`,description:`Alt with an arrow key. Some browsers use Alt+Left/Right for history.`},{id:`ctrl`,name:`Ctrl + arrows`,description:`Ctrl (Cmd on macOS) with an arrow key.`},{id:`none`,name:`Bare arrows`,description:`Plain arrow keys, except while typing in a field.`}],IC=`canvas:layout-nav`;function LC(){try{let e=localStorage.getItem(IC);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var RC=LC(),zC=new Set;function BC(){return RC}function VC(e){try{e===`shift`?localStorage.removeItem(IC):localStorage.setItem(IC,e)}catch{}RC=e;for(let e of zC)e()}function HC(e){zC.add(e);let t=t=>{(t.key===IC||t.key===null)&&(RC=LC(),e())};return window.addEventListener(`storage`,t),()=>{zC.delete(e),window.removeEventListener(`storage`,t)}}function UC(){return(0,X.useSyncExternalStore)(HC,BC,()=>`shift`)}function WC(e,t){let n=e.ctrlKey||e.metaKey;switch(t){case`shift`:return e.shiftKey&&!e.altKey&&!n;case`alt`:return e.altKey&&!e.shiftKey&&!n;case`ctrl`:return n&&!e.shiftKey&&!e.altKey;case`none`:return!e.shiftKey&&!e.altKey&&!n}}function GC(){return window.matchMedia(`(max-width: 767px)`).matches&&jC()!==`strip`}var KC=(0,X.createContext)(null);function qC(){let e=(0,X.useContext)(KC);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function JC(e){let t=e.split(`/`).filter(Boolean),n=t[0]||``,r=t[1]||null,i=t[2]||null;return n===`contexts`?{section:`contexts`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`workspaces`?{section:`workspaces`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`agents`?{section:`agents`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`apps`?{section:`apps`,entityId:null,m2View:null}:n===`admin`||CC.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function YC(e,t){let n=vn(),r=ft(),i=(0,X.useRef)(!1),a=(0,X.useRef)(e);return(0,X.useEffect)(()=>{a.current=e},[e]),(0,X.useLayoutEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=JC(n.pathname);if(e===null&&n.pathname!==`/`&&jC()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=GC(),c=s?n.state?.canvasMenu:void 0;t(c?{type:`RESTORE_MENU`,menu:c}:{type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,n.state,t]),{navigateToEntity:(0,X.useCallback)(e=>{i.current=!0,r(e)},[r])}}function XC(){let{goBack:e}=qC();return(0,Z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Back to previous view`,title:`Back to previous view`,className:`-ml-2 mr-1 flex h-11 w-11 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent md:hidden`,children:(0,Z.jsx)(ka,{className:`h-5 w-5`})})}var ZC=[{id:`productivity`,label:`Productivity`},{id:`creative`,label:`Creative`},{id:`media`,label:`Media & capture`},{id:`utilities`,label:`Utilities`}];function QC(e,t){let n=t.trim().toLocaleLowerCase();return ZC.map(t=>({...t,apps:e.filter(e=>e.category===t.id&&`${e.name} ${e.description} ${e.kind} ${t.label}`.toLocaleLowerCase().includes(n)).sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))})).filter(e=>e.apps.length)}function $C(e){let t=new URL(e);if(![`http:`,`https:`].includes(t.protocol)||t.username||t.password)throw Error(`Enter an HTTP or HTTPS URL without embedded credentials.`);return t.href}function ew({apps:e,query:t,activeId:n,onLaunch:r,onRemove:i}){let a=QC(e,t);return(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto p-2`,children:[a.map(e=>(0,Z.jsxs)(`section`,{"aria-label":e.label,children:[(0,Z.jsx)(`h3`,{className:`px-2 py-2 text-xs font-semibold text-muted-foreground`,children:e.label}),e.apps.map(e=>{let t=e.kind===`web`?Kr:e.kind===`desktop`?mr:vi;return(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e),"aria-current":n===e.id?`page`:void 0,className:`flex min-w-0 flex-1 items-start gap-2 rounded-md p-2 text-left hover:bg-accent/50 ${n===e.id?`bg-accent`:``}`,children:[(0,Z.jsx)(t,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block truncate text-sm font-medium`,children:e.name}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.description}),(0,Z.jsx)(`span`,{className:`mt-1 block text-[10px] text-muted-foreground`,children:e.kind===`canvas`?`Canvas`:e.kind===`web`?`Web app · opens in browser`:`Desktop app`})]})]}),e.kind===`web`&&i&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i(e),"aria-label":`Remove ${e.name}`,className:`rounded p-2 text-muted-foreground hover:bg-accent`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]},e.id)})]},e.id)),!a.length&&(0,Z.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching apps.`})]})}var tw=`canvas:webApps`;function nw(){try{let e=JSON.parse(localStorage.getItem(tw)||`[]`);return Array.isArray(e)?e.filter(e=>{if(!e||typeof e.id!=`string`||typeof e.name!=`string`||typeof e.description!=`string`||e.kind!==`web`||!ZC.some(t=>t.id===e.category))return!1;try{return typeof e.target==`string`&&!!$C(e.target)}catch{return!1}}):[]}catch{return[]}}function rw(){let{navigateFromMenu:e}=qC(),t=vn(),n=rx(),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(nw),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``);(0,X.useEffect)(()=>{let e=()=>o(nw());return window.addEventListener(`storage`,e),window.addEventListener(`canvas:apps-changed`,e),()=>{window.removeEventListener(`storage`,e),window.removeEventListener(`canvas:apps-changed`,e)}},[]);let d=e=>{try{return localStorage.setItem(tw,JSON.stringify(e)),o(e),window.dispatchEvent(new Event(`canvas:apps-changed`)),!0}catch{return u(`Unable to save web apps on this device.`),!1}},f=[..._C.map(e=>({id:`canvas:${e.id}`,name:e.label,description:e.description,category:e.category,kind:`canvas`,target:`/apps/${e.id}`})),...a];return(0,Z.jsxs)(`nav`,{"aria-label":`Apps`,className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(XC,{}),(0,Z.jsx)(`h2`,{className:`flex-1 text-sm font-semibold`,children:`Apps`}),(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Add web app`,title:`Add web app`,onClick:()=>{c(!s),u(``)},className:`rounded p-1 hover:bg-accent`,children:(0,Z.jsx)(br,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`input`,{type:`search`,"aria-label":`Search apps`,placeholder:`Find an app…`,value:r,onChange:e=>i(e.target.value),className:`w-full rounded-md border bg-background px-2 py-1.5 text-sm`}),s&&(0,Z.jsxs)(`form`,{className:`space-y-2`,onSubmit:e=>{e.preventDefault();let t=new FormData(e.currentTarget);try{let e=String(t.get(`name`)||``).trim();if(!e)throw Error(`Enter an app name.`);let n={id:`web:${crypto.randomUUID()}`,name:e,description:``,category:t.get(`category`),kind:`web`,target:$C(String(t.get(`url`)||``))};d([...nw(),n])&&(c(!1),u(``))}catch(e){u(e instanceof Error?e.message:`Unable to add app.`)}},children:[(0,Z.jsx)(`input`,{name:`name`,required:!0,"aria-label":`App name`,placeholder:`App name`,className:`w-full rounded border bg-background p-1 text-sm`}),(0,Z.jsx)(`input`,{name:`url`,type:`url`,required:!0,"aria-label":`App URL`,placeholder:`https://…`,className:`w-full rounded border bg-background p-1 text-sm`}),(0,Z.jsx)(`select`,{name:`category`,"aria-label":`App category`,className:`w-full rounded border bg-background p-1 text-sm`,children:ZC.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Saved on this device. Opens in your browser.`}),(0,Z.jsx)(`button`,{type:`submit`,className:`rounded border px-2 py-1 text-sm hover:bg-accent`,children:`Add app`})]}),l&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:l})]}),(0,Z.jsx)(ew,{apps:f,query:r,activeId:f.find(e=>e.kind===`canvas`&&e.target===t.pathname)?.id,onLaunch:r=>{if(r.kind===`web`){window.open($C(r.target),`_blank`,`noopener,noreferrer`);return}let i=new URLSearchParams;if(t.pathname.startsWith(`/apps/`)){let e=new URLSearchParams(t.search);for(let t of[`context`,`workspace`,`path`,`tree`])e.has(t)&&i.set(t,e.get(t))}else n?.mode===`context`?i.set(`context`,n.contextId):n?.mode===`workspace`&&(i.set(`workspace`,n.workspaceName),i.set(`path`,n.path),i.set(`tree`,n.treeName));e(`${r.target}${i.size?`?${i}`:``}`)},onRemove:e=>{d(nw().filter(t=>t.id!==e.id))}})]})}var iw;function aw(){let[e,t]=(0,X.useState)({local:!1});return(0,X.useEffect)(()=>{iw??=fetch(`${yo}/runtime/capabilities`).then(async e=>e.ok?(await e.json()).payload:{local:!1}).catch(()=>({local:!1}));let e=!0;return iw.then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function ow(e){return e.isShared||e.type===`shared`?e.id:e.name}function sw({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=ft();return(0,Z.jsxs)(`div`,{className:K(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i?i():s(r),"aria-label":`Back`,title:`Back`,className:`mt-1 shrink-0 text-muted-foreground transition-colors hover:text-foreground touch-target`,children:(0,Z.jsx)(ka,{className:`h-5 w-5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h1`,{className:K(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,Z.jsx)(`p`,{className:K(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>s(`/`),"aria-label":`Close`,title:`Close`,className:`order-2 flex h-9 w-9 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})}),n&&(0,Z.jsx)(`div`,{className:`order-3 flex w-full items-center gap-2 max-sm:flex-wrap sm:order-1 sm:w-auto`,children:n})]})}function cw({className:e}){let t=ft();return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:K(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,e),children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})}function lw({onBack:e,title:t=`Back`,className:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:K(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,n),children:(0,Z.jsx)(ka,{className:`h-4 w-4`})})}var uw=180;function dw({x:e,y:t,current:n,onChange:r,onClose:i}){Ae(i);let[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)([]),[l,u]=(0,X.useState)({q:``,list:[]}),[d,p]=(0,X.useState)(!0),m=(0,X.useRef)(null),h=(0,X.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&i(),h.current={name:e,t}};(0,X.useEffect)(()=>{m.current?.focus()},[]),(0,X.useEffect)(()=>{let e=!0;return Vt().then(t=>{e&&(c(t),p(!1))}),()=>{e=!1}},[]),(0,X.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{Qe(e).then(t=>{u({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=l.q===_,y=_!==``&&!v,b=(0,X.useMemo)(()=>(_?v?l.list:[]:s).slice(0,uw),[_,v,l.list,s]),x=(0,X.useRef)(null),[S,C]=(0,X.useState)({x:e,y:t});return(0,X.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,Hd.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,Z.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,Z.jsx)(vr,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[dt.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:K(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,Z.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:K(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,Z.jsx)(vr,{className:`w-3 h-3`})}),(0,Z.jsx)(`label`,{title:`Custom color`,className:K(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!dt.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!dt.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,Z.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,Z.jsx)(`input`,{ref:m,value:a,onChange:e=>o(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),d||y?(0,Z.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Ti,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,Z.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(vr,{className:`w-4 h-4`})}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(f,{icon:e,width:18,height:18,color:n.color})},e))]}),!d&&!y&&b.length===0&&(0,Z.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function fw(e,t,n){let r=(0,X.useRef)(n);(0,X.useEffect)(()=>{r.current=n}),(0,X.useEffect)(()=>{if(!e)return;e.emit(`subscribe`,{channel:t});let n=Object.keys(r.current).map(t=>{let n=(...e)=>{r.current[t]?.(...e)};return e.on(t,n),[t,n]});return()=>{e.emit(`unsubscribe`,{channel:t});for(let[t,r]of n)e.off(t,r)}},[e,t])}function pw({title:e,onClose:t,children:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-(--card-radius) border bg-card p-4 shadow-elevation-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),n]})}function mw({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,X.useState)(!1),l=e.status===`active`,u=e.type===`universe`||e.name===`universe`,d=e.status===`error`,f=e.status===`not_found`,p=e.isShared===!0||e.type===`shared`,m=e.ownerEmail||e.owner,h=typeof e.sharedVia==`object`&&e.sharedVia?e.sharedVia:null,g=h?.permissions||[],_=g.includes(`admin`)?`admin`:g.includes(`write`)?`read/write`:`read-only`,v=h?.type===`group`?`via group ${h.principal}`:h?.type===`user`?`shared with you`:``,y=e.origin===`remote`,b=e.status===`offline`,x=Jt(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsxs)(zl,{className:`relative ${S}`,style:C,children:[(0,Z.jsx)(Bl,{children:(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(Vl,{className:`truncate`,children:e.label||e.name}),(0,Z.jsx)(Hl,{children:p?`Shared from ${m}`:e.description||``})]}),(0,Z.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>n(ow(e)),title:`Stop Workspace`,disabled:d||f,children:(0,Z.jsx)(Sa,{className:`h-4 w-4`})}):(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>t(ow(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,Z.jsx)(Ar,{className:`h-4 w-4`})}),l&&(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>r(ow(e)),title:`Enter Workspace`,disabled:d||f,children:(0,Z.jsx)(fi,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:se(e)?`Workspace settings`:`Workspace settings require admin access`,"aria-label":`Workspace settings`,disabled:f||!se(e),children:(0,Z.jsx)(Wi,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,Z.jsx)(gi,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,Z.jsxs)(vo,{open:s,onOpenChange:c,children:[(0,Z.jsx)(uo,{asChild:!0,children:(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,title:y?`Remove remote workspace reference`:`Delete Workspace`,disabled:l&&!y,className:`text-destructive hover:text-destructive hover:bg-destructive/10`,children:(0,Z.jsx)(Qr,{className:`h-4 w-4`})})}),(0,Z.jsxs)(lo,{children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsx)(io,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,Z.jsx)(ro,{children:y?(0,Z.jsxs)(Z.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),`The workspace itself stays untouched on `,e.remote?.url||e.host,`; only the stored share token and the local cache entry are dropped.`]}):(0,Z.jsxs)(Z.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,Z.jsx)(Ul,{children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`h-3 w-3 rounded-full ${(()=>{switch(e.status){case`active`:return`bg-success`;case`inactive`:case`available`:return`bg-muted-foreground`;case`error`:case`offline`:return`bg-destructive`;case`not_found`:return`bg-muted-foreground`;default:return`bg-accent`}})()}`}),(0,Z.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:(()=>{switch(e.status){case`active`:return`Active`;case`inactive`:return`Inactive`;case`error`:return`Error`;case`not_found`:return`Not Found`;case`available`:return`Available`;case`removed`:return`Removed`;case`destroyed`:return`Destroyed`;case`offline`:return`Offline`;default:return e.status}})()}),u&&(0,Z.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,Z.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:e.remote?.url?`${e.remote.url} (${(e.remote.permissions||[]).join(`, `)||`no permissions`})`:void 0,children:[`Remote · `,e.host]}),p&&(0,Z.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:[v,`${_} access`].filter(Boolean).join(` · `),children:[`Shared · `,_]})]})})]})})}function hw(){let[e,t]=$t(),n=e.get(`create`)===`1`,[r,i]=(0,X.useState)(n),[a,o]=(0,X.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,X.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var gw=`canvas:lastPath`,_w=200;function vw(){try{let e=localStorage.getItem(gw);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function yw(e){try{localStorage.setItem(gw,JSON.stringify(e))}catch{}}function bw(e,t,n){if(!e)return;let r=vw(),i=r[e];if(i&&i.tree===t&&i.path===n)return;delete r[e],r[e]={tree:t,path:n};let a=Object.keys(r);if(a.length>_w)for(let e of a.slice(0,a.length-_w))delete r[e];yw(r)}function xw(e){let t=vw()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function Sw(e){let t=xw(e);return t?of(e,t.path,t.tree):`/workspaces/${e}`}function Cw(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=xo(no.ws,{auth:{token:e},transports:[`websocket`],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3});return n.on(`connect`,()=>{console.log(`WebSocket connected`)}),n.on(`connect_error`,e=>{console.error(`WebSocket connection error:`,e)}),n.on(`error`,e=>{console.error(`WebSocket error:`,e)}),t(n),()=>{n.close()}},[]),e}var ww=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function Tw(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await Ys(e,`/${n}`,!0,a);let t=St(`/${n}`);t&&await Ro(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return Ms(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function Ew(){let[e,t]=(0,X.useState)(new Set),[n,r]=(0,X.useState)(`context`);return{selected:e,setSelected:t,tree:n,setTree:r,toggle:e=>{t(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}}}function Dw({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,Z.jsx)(`div`,{className:`mt-3 grid gap-1.5 ${o?`grid-cols-1`:`grid-cols-2 sm:grid-cols-3 md:grid-cols-4`}`,children:ww.map(n=>{let r=_n[n.toLowerCase()];return(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded border px-2 py-1.5 text-sm hover:bg-accent/50`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,Z.jsx)(f,{icon:r.icon,width:16,height:16,color:r.color}),(0,Z.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var Ow=[{value:`full`,icon:rr,title:`Standard`,blurb:`Everything in one folder: your files in home/, alongside db/, data/, git/.`,tree:[`workspace.json`,`home/ ← your files`,`db/ data/ cache/ Git/`]},{value:`home`,icon:Fr,title:`Roaming home`,blurb:`The workspace folder IS your drive. Mount it over WebDAV and it looks like a plain home directory. Canvas keeps its files in a hidden .workspace/.`,tree:[`your files, at the top level`,`.workspace/ ← hidden, ignored`]}];function kw({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,Z.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:Ow.map(i=>{let a=e===i.value,o=i.icon;return(0,Z.jsxs)(`button`,{id:`${r}-${i.value}`,type:`button`,role:`radio`,"aria-checked":a,disabled:n,onClick:()=>t(i.value),className:`flex w-full gap-2 rounded-md border p-2.5 text-left transition-colors disabled:opacity-50 ${a?`border-primary bg-accent/40`:`hover:bg-accent/20`}`,children:[(0,Z.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,Z.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,Z.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function Aw(){let[e,t]=(0,X.useState)(`full`),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let e=!0;return J.get(`/ping`,{skipAuth:!0}).then(r=>{let i=r?.defaults?.workspaceLayout;e&&!n&&(i===`home`||i===`full`)&&t(i)}).catch(()=>{}),()=>{e=!1}},[]),[e,e=>{r(!0),t(e)}]}function jw({disabled:e}){let[t,n]=(0,X.useState)(0),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(``),d=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let e=!0;return d.current?.id!==t&&(d.current={id:t,promise:ic()}),d.current.promise.then(t=>{if(!e)return;let n=[...t.discovered,...t.adopted];o(e=>[...new Map([...e,...n].map(e=>[e.id,e])).values()]),c(t)}).catch(t=>{e&&u(t instanceof Error?t.message:`Workspace scan failed`)}).finally(()=>{e&&i(!1)}),()=>{e=!1}},[t]),(0,Z.jsxs)(`section`,{className:`space-y-2 rounded-md border p-3`,"aria-label":`Find workspace folders`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:`Workspaces folder`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copied a workspace folder here? Scan to add it to your workspaces.`})]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:e||r,onClick:()=>{i(!0),u(``),n(e=>e+1)},children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${r?`animate-spin`:``}`}),r?`Scanning…`:`Rescan`]})]}),r&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Looking for workspace folders…`}),!r&&!l&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:a.length?`Found ${a.length} ${a.length===1?`workspace`:`workspaces`}. Added to your workspace list.`:`No new workspace folders found.`}),a.length>0&&(0,Z.jsx)(`ul`,{className:`space-y-2`,children:a.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(we,{className:`text-sm font-medium underline underline-offset-2`,to:`/workspaces/${encodeURIComponent(e.name)}`,children:e.label||e.name}),(0,Z.jsx)(`p`,{className:`break-all text-xs text-muted-foreground`,children:e.dir})]},e.id))}),l&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:l}),!!s?.skipped.length&&(0,Z.jsxs)(`details`,{className:`text-sm text-muted-foreground`,children:[(0,Z.jsxs)(`summary`,{children:[s.skipped.length,` `,s.skipped.length===1?`folder could`:`folders could`,` not be added`]}),(0,Z.jsx)(`ul`,{className:`mt-1 space-y-1`,children:s.skipped.map(e=>(0,Z.jsxs)(`li`,{className:`break-all`,children:[e.dir,`: `,e.reason]},e.dir))})]})]})}function Mw({name:e,label:t,setName:n,setLabel:r,disabled:i=!1}){return(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace name`,(0,Z.jsx)(q,{required:!0,pattern:`[a-zA-Z0-9]([a-zA-Z0-9_]|-)*`,placeholder:`my-workspace`,value:e,onChange:e=>n(e.target.value),disabled:i}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Used in addresses. Archive imports also use it as the folder name.`})]}),(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Display label`,(0,Z.jsx)(q,{required:!0,placeholder:`My Workspace`,value:t,onChange:e=>r(e.target.value),disabled:i})]})]})}function Nw({onImported:e,disabled:t=!1}){let[n,r]=(0,X.useState)(`upload`),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(``),[v,y]=(0,X.useState)(null),b=t||f,x=async t=>{t.preventDefault(),p(!0),_(``),y(null),h(`Starting…`);let r={name:c.trim(),label:u.trim()},a=e=>h(cc[e.phase]||e.phase);try{let t=n===`upload`?await gc(i,e=>h(e<1?`Uploading… ${Math.round(e*100)}%`:`Extracting…`),a,r):await sc(o.trim(),r,a);y(t),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e?.(t)}catch(e){_(e instanceof Error?e.message:`Workspace import failed`)}finally{p(!1)}};return(0,Z.jsxs)(`form`,{className:`space-y-3`,onSubmit:e=>void x(e),children:[(0,Z.jsx)(jw,{disabled:b}),(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Import from`,(0,Z.jsxs)(`select`,{value:n,disabled:b,onChange:e=>r(e.target.value),className:`rounded-md border bg-background p-2`,children:[(0,Z.jsx)(`option`,{value:`upload`,children:`Upload an archive`}),(0,Z.jsx)(`option`,{value:`path`,children:`Path on this server`})]})]}),n===`upload`?(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace archive`,(0,Z.jsx)(q,{required:!0,type:`file`,accept:`.tar.gz,.tgz,.tar.bz2,.tbz2,.tbz`,disabled:b,onChange:e=>a(e.target.files?.[0]||null)})]}):(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Server path`,(0,Z.jsx)(q,{required:!0,placeholder:`/tmp/workspace.tar.gz`,value:o,disabled:b,onChange:e=>s(e.target.value)}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`An archive or workspace folder on the server. Archives are extracted into your Workspaces directory.`})]}),(0,Z.jsx)(Mw,{name:c,label:u,setName:l,setLabel:d,disabled:b}),(0,Z.jsxs)(Y,{type:`submit`,disabled:b||!c.trim()||!u.trim()||(n===`upload`?!i:!o.trim()),children:[f?(0,Z.jsx)(Er,{className:`mr-2 h-4 w-4 animate-spin`}):(0,Z.jsx)(Yr,{className:`mr-2 h-4 w-4`}),f?`Importing…`:`Import workspace`]}),f&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:m}),g&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),v&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Imported `,v.label||v.name,`.`]})]})}function Pw(e){return[...e].sort((e,t)=>{let n=typeof e.order==`number`&&Number.isFinite(e.order)?e.order:2**53-1,r=typeof t.order==`number`&&Number.isFinite(t.order)?t.order:2**53-1;if(n!==r)return n-r;let i=e.createdAt??``,a=t.createdAt??``;return i===a?(e.name??``).localeCompare(t.name??``):i<a?-1:1})}function Fw(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function Iw(e,t){return{failed:(await Promise.allSettled(e.map((e,n)=>e.order===n?Promise.resolve():t(e,n)))).filter(e=>e.status===`rejected`).length}}function Lw(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function Rw(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(on()),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(``),[_,v]=Aw(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),T=aw(),[E,D]=hw(),O=Ew(),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(!1),[N,P]=(0,X.useState)(!1),[ee,F]=(0,X.useState)(!1),[I,te]=(0,X.useState)(null),{showToast:L}=wo(),R=ft(),ne=De(),{openM2Drawer:re}=qC(),ie=Cw();fw(ie,`workspace`,{"workspace:status:changed":e=>t(t=>t.map(t=>t.id===e.workspaceId?{...t,status:e.status}:t)),"workspace:created":e=>t(t=>[...t,e.workspace]),"workspace:deleted":e=>t(t=>t.filter(t=>t.id!==e.workspaceId)),"workspaces.scanned":({report:e})=>{!e.discovered.length&&!e.adopted.length&&!e.updated.length&&!e.missing.length||Uo().then(e=>t(Pw(e))).catch(()=>{})}}),(0,X.useEffect)(()=>{let e=async()=>{try{r(!0);let e=await Uo();t(Pw(e)),a(null)}catch(e){console.error(`Workspace fetch error:`,e);let t=`Failed to fetch workspaces`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch workspaces`}a(t),L({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}};e();let n=()=>{e()};return window.addEventListener(`workspaces:refresh`,n),()=>{window.removeEventListener(`workspaces:refresh`,n)}},[ie,L]);let ae=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await Is({name:o,description:c||void 0,color:u,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),O.selected.size>0){try{await Ks(e.name);let{ok:t,failed:n}=await Tw(e.name,Array.from(O.selected),O.tree);n&&L({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),L({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}O.setSelected(new Set)}s(``),l(``),d(on()),m(null),g(``),L({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),D(!1)}catch(e){console.error(`Workspace creation error:`,e);let t=`Failed to create workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create workspace`}L({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},z=async e=>{if(e.preventDefault(),I)try{let e={label:I.label,description:I.description,color:I.color,icon:I.icon??null};await Pc(I.name,e),t(t=>t.map(t=>t.id===I.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),L({title:`Success`,description:`Workspace '${I.label}' details updated.`}),te(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;L({title:`Error`,description:t,variant:`destructive`})}},oe=e=>{te(e)},se=async e=>{try{await fs(e.name),t(t=>t.filter(t=>t.id!==e.id)),L({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;L({title:`Error`,description:t,variant:`destructive`})}},B=async e=>{try{let n=await Ks(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),L({title:`Success`,description:`Workspace '${n.label||n.name}' started.`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){console.error(`Workspace start error:`,e);let t=`Failed to start workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start workspace`}L({title:`Error`,description:t,variant:`destructive`})}},ce=async e=>{try{let n=await hc(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),L({title:`Success`,description:`Workspace '${n.label||n.name}' stopped.`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){console.error(`Workspace stop error:`,e);let t=`Failed to stop workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop workspace`}L({title:`Error`,description:t,variant:`destructive`})}},V=e=>{R(Sw(e))},{rowProps:le,handleProps:ue,draggingIndex:de,insertLineClass:fe}=Lw((n,r)=>{let i=Fw(e,n,r);t(i),Iw(i,(e,t)=>Pc(ow(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&L({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>A(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>P(e=>!e),children:`Import workspace`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>M(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>F(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!T.local&&!E&&(0,Z.jsxs)(Y,{onClick:()=>D(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,Z.jsx)(br,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),!T.local&&E&&(0,Z.jsx)(pw,{title:`Create New Workspace`,onClose:()=>D(!1),children:(0,Z.jsxs)(`form`,{onSubmit:ae,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,Z.jsx)(q,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,disabled:C,onClick:e=>b({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(f,{icon:p||`ph:stack-fill`,width:22,height:22,color:Jt(u)})}),(0,Z.jsx)(q,{id:`workspace-color`,type:`color`,value:u,onChange:e=>d(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>d(on()),disabled:C,children:`Randomize`})]}),y&&(0,Z.jsx)(dw,{x:y.x,y:y.y,current:{icon:p??void 0,color:u},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&d(e.color)},onClose:()=>b(null)}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,Z.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`How the workspace directory is laid out on disk. Fixed once created.`}),(0,Z.jsx)(kw,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`Ticked folders are created right after the workspace, with matching icons and colors.`}),(0,Z.jsx)(Dw,{selected:O.selected,onToggle:O.toggle,tree:O.tree,onTreeChange:O.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:C||!o.trim(),children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),k&&(0,Z.jsx)(Bw,{}),ee&&(0,Z.jsx)(Vw,{onClose:()=>F(!1),onChanged:async()=>{try{t(Pw(await Uo()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),N&&(0,Z.jsx)(pw,{title:`Import workspace`,onClose:()=>P(!1),children:(0,Z.jsx)(Nw,{onImported:()=>P(!1)})}),j&&(0,Z.jsx)(zw,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),M(!1)},onClose:()=>M(!1)}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,Z.jsx)(`div`,{className:`grid gap-4`,children:e.map((t,n)=>{let r={...t,createdAt:t.createdAt,updatedAt:t.updatedAt,color:t.color===null?void 0:t.color},i=Jt(t.color);return(0,Z.jsxs)(`div`,{...le(n),className:`flex items-stretch rounded-lg ${fe(n,e.length)||``} ${de===n?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,...ue(n),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:`hidden w-5 shrink-0 cursor-grab items-center justify-center rounded-l-lg active:cursor-grabbing md:flex ${i?``:`bg-muted`}`,style:i?{backgroundColor:i}:void 0,children:(0,Z.jsx)(Un,{className:`h-4 w-4 ${tt(i)}`})}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(mw,{workspace:r,onStart:B,onStop:ce,onEnter:V,onEdit:oe,onSettings:e=>{ne?re(`workspaces`,`settings`,ow(e)):R(`/workspaces/${ow(e)}/settings/general`)},onDestroy:se})})]},t.id)})})]}),I&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,I.label]}),(0,Z.jsxs)(`form`,{onSubmit:z,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-label`,value:I.label,onChange:e=>te(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`edit-description`,value:I.description||``,onChange:e=>te(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>S({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(f,{icon:I.icon||`ph:stack-fill`,width:22,height:22,color:Jt(I.color)})}),(0,Z.jsx)(q,{id:`edit-workspace-color`,type:`color`,value:I.color||`#FFFFFF`,onChange:e=>te(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>te(e=>e?{...e,color:on()}:null),children:`Randomize Color`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:!I.label?.trim(),children:`Save Changes`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>te(null),children:`Cancel`})]})]}),x&&(0,Z.jsx)(dw,{x:x.x,y:x.y,current:{icon:I.icon??void 0,color:I.color??void 0},onChange:e=>{te(t=>{if(!t)return null;let n={...t};return`icon`in e&&(n.icon=e.icon??null),`color`in e&&e.color&&(n.color=e.color),n})},onClose:()=>S(null)})]})]})}function zw({onImported:e,onClose:t}){let{showToast:n}=wo(),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(``);return(0,Z.jsx)(pw,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,Z.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault();let i;try{i=new URL(r.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}if(!a.trim().startsWith(`canvas-`)){n({title:`Error`,description:`Invalid access token (expected canvas-...)`,variant:`destructive`});return}f(!0),m(`Starting…`);try{let t=await Xs(i,a.trim(),e=>{m(cc[e.phase]||e.phase)},{name:s.trim(),label:l.trim()});n({title:`Success`,description:`Workspace '${t.label||t.name}' imported from ${i}.`}),e(t)}catch(e){let t=e,r=t?.message||t?.payload?.message||`Failed to import remote workspace`;n({title:`Error`,description:r,variant:`destructive`})}finally{f(!1),m(``)}},className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:d}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:d}),(0,Z.jsx)(Y,{type:`submit`,disabled:d||!r.trim()||!a.trim()||!s.trim()||!l.trim(),children:d?`Importing…`:`Import Workspace`})]}),(0,Z.jsx)(Mw,{name:s,label:l,setName:c,setLabel:u,disabled:d}),d&&p&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,Z.jsx)(`strong`,{children:`copy`}),` of the workspace from the remote canvas-server into this one, where it then lives independently. The remote workspace is stopped while it is packed, and large workspaces can take several minutes — progress is shown above.`]})]})})}function Bw(){let{showToast:e}=wo(),[t,n]=(0,X.useState)(``),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,Z.jsx)(q,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,Z.jsx)(Y,{onClick:async()=>{if(!s(t.trim())){e({title:`Error`,description:`Invalid URL`,variant:`destructive`});return}if(!r.trim().startsWith(`canvas-`)){e({title:`Error`,description:`Invalid access token`,variant:`destructive`});return}o(!0);try{sessionStorage.setItem(`sharedToken:last`,r.trim());let e=new URLSearchParams({url:t.trim()}).toString();window.location.href=`/shared?${e}`}catch(t){e({title:`Error`,description:t instanceof Error?t.message:`Failed to open shared resource`,variant:`destructive`})}finally{o(!1)}},disabled:a||!t.trim()||!r.trim(),children:`Open`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`We use your provided URL and token to fetch via the remote's public API.`})]})}function Vw({onClose:e,onChanged:t}){let{showToast:n}=wo(),r=ft(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)([]),f=(0,X.useCallback)(async()=>{try{d(await _s())}catch{d([])}},[]);(0,X.useEffect)(()=>{f()},[f]);let p=async e=>{e.preventDefault();let r;try{r=new URL(i.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}l(!0);try{let e=await dc(r,o.trim());n({title:`Remote workspace added`,description:`'${e.label}' is available as ${e.address}.`}),a(``),s(``),await f(),t?.()}catch(e){let t=e;n({title:`Error`,description:t?.message||t?.payload?.message||`Failed to add remote workspace`,variant:`destructive`})}finally{l(!1)}},m=async e=>{try{await ks(e.id),await f(),t?.()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to remove remote workspace`,variant:`destructive`})}};return(0,Z.jsxs)(pw,{title:`Open a remote Workspace`,onClose:e,children:[(0,Z.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,Z.jsx)(Y,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,Z.jsx)(`code`,{className:`font-mono text-xs`,children:`name@host`}),` — nothing is copied. Every call you make to it is forwarded to the remote with the share token (its permissions apply); document content and thumbnails are cached locally so they stay readable when the remote is offline. Use “Import remote…” if you want an independent local copy instead.`]})]}),u.length>0&&(0,Z.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,Z.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`remote`})]}),(0,Z.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}function Hw({workspaceId:e,treeName:t=`context`,path:n=`/`,children:r,className:i,headerOnly:a=!1,readOnly:o=!1}){let[s,c]=(0,X.useState)(null),l=ft(),u=Ut({workspaceId:e,treeName:t}),d=[...!o&&t!==`backends`?[{label:`New folder…`,run:async()=>{let e=prompt(`New folder name:`)?.trim();if(e){if(/[\\/]/.test(e)||e===`.`||e===`..`)throw Error(`Enter a folder name without slashes`);await u.onInsertPath(`${n===`/`?``:n}/${e}`)}}},{label:`New canvas…`,run:async()=>{l(`${of(e,n,t)}?createCanvas=1`)}}]:[],...!o&&u.onImportDocuments?[{label:`Import documents…`,run:()=>u.onImportDocuments(n)}]:[],{label:`Export documents…`,run:()=>u.onExportDocuments(n)}];return(0,Z.jsxs)(`div`,{className:i,onContextMenu:e=>{e.defaultPrevented||a&&!e.target.closest(`.canvas-navigation`)||(e.preventDefault(),c({x:e.clientX,y:e.clientY}))},children:[r,s&&(0,Z.jsx)(Dn,{...s,onClose:()=>c(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:d.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:`block w-full rounded-sm px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{c(null),e.run().catch(e=>alert(e instanceof Error?e.message:String(e)))},children:e.label},e.label))})]})}var Uw={membership:`keep`,propagation:`never`,targets:[],acceptPropagatedDeletions:!1},Ww=e=>`/workspaces/${encodeURIComponent(e)}/trash/operations`,Gw=(e,t)=>J.get(`${Ww(e)}?${new URLSearchParams(Object.entries(t).map(([e,t])=>[e,String(t)]))}`),Kw=(e,t,n,r={})=>J.post(`${Ww(e)}/${n}`,{ids:t,...r}),qw=(e,t,n,r)=>J.patch(`/workspaces/${encodeURIComponent(e)}/backends/imap/${encodeURIComponent(t)}/containers/${encodeURIComponent(n)}`,{removalPolicy:r});function Jw(e){let t=_t(`backends`,e.path)?.backend;return(0,Z.jsx)(Yw,{...e},JSON.stringify([e.workspace,t]))}function Yw({workspace:e,path:t,onNavigate:n}){let r=_t(`backends`,t),i=r.backend,a=r.prefix,[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=(0,X.useRef)(!1),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(0),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)(null),x=(0,X.useCallback)(()=>g(e=>e+1),[]),[S,C]=(0,X.useState)(t);S!==t&&(C(t),v(new Set),b(null),m(null),f(null));let w=o?.revision!==h,T=w?[]:o.items,E=w?[]:o.backends,D=o?.days;(0,X.useEffect)(()=>{let t=!1;return(i?Lt(e,i).then(e=>({...e,backends:[]})):Rc(e).then(e=>({items:[],days:null,backends:e.filter(e=>e.driver===`file`&&e.enabled!==!1)}))).then(e=>{t||s({...e,revision:h,error:null})}).catch(e=>{t||s({revision:h,items:[],backends:[],days:null,error:e instanceof Error?e.message:String(e)})}),()=>{t=!0}},[e,i,h]),(0,X.useEffect)(()=>{let t=null,n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==`backends`||(t||=setTimeout(()=>{t=null,x()},500))};return window.addEventListener(`workspace:trash:refresh`,n),window.addEventListener(`workspace:tree:refresh`,n),()=>{window.removeEventListener(`workspace:trash:refresh`,n),window.removeEventListener(`workspace:tree:refresh`,n),t&&clearTimeout(t)}},[e,x]);let O=Bt(T,a),k=async(t,n)=>{if(!(!i||u.current||w||!n.length)&&!(t===`discard`&&!qt(i,n))){u.current=!0,l(t),f(null),m(null),b(null);try{let r=await(t===`restore`?gn:ln)(e,i,[...n].sort((e,t)=>t.deletedAt-e.deletedAt).map(e=>e.id)),a=r.filter(e=>!e.ok);m(`${r.length-a.length} item(s) ${t===`restore`?`restored to their original paths`:`permanently deleted`}.`),a.length&&f(`${a.length} item(s) remain in Trash. ${a.slice(0,3).map(e=>`${e.key||`Item`}: ${e.reason===`precondition-failed`||e.reason===`target-exists`?`original path is occupied`:e.message||e.reason}`).join(`; `)}`),v(new Set)}catch(e){f(e instanceof Error?e.message:String(e))}finally{u.current=!1,l(null),x()}}},A=(e,t,n)=>b({x:e,y:t,row:n});return(0,Z.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col bg-background`,"aria-label":`Backend Trash`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 border-b px-4 py-3`,children:[(0,Z.jsx)(Qr,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(pn,{items:mt(t,e).map((e,t)=>t===2&&i?{...e,label:i}:e),onNavigate:n,className:`basis-48`}),(0,Z.jsxs)(`div`,{className:`ml-auto flex max-w-full flex-wrap items-center gap-2`,children:[_.size>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`restore`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,Z.jsx)(Vr,{className:`h-3.5 w-3.5`}),`Restore selected`]}),(0,Z.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`}),`Delete selected`]})]}),i&&O.length>0&&(0,Z.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.flatMap(e=>e.items)),children:[(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`}),a?`Empty this folder`:`Empty Trash`]}),(0,Z.jsx)(`button`,{title:`Refresh Trash`,"aria-label":`Refresh Trash`,className:`rounded p-2 hover:bg-accent`,disabled:!!c||w,onClick:x,children:(0,Z.jsx)(Er,{className:`h-4 w-4 ${w?`animate-spin`:``}`})})]})]}),(0,Z.jsxs)(`div`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`Restore files and folders to their original paths. Existing files are kept.`,D?` Deleted items are kept for ${D} days.`:``]}),p&&(0,Z.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:p}),(d||o?.error)&&(0,Z.jsx)(`p`,{role:`alert`,className:`px-4 py-2 text-sm text-destructive`,children:d||o?.error}),c&&(0,Z.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:c===`restore`?`Restoring…`:`Deleting permanently…`}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:w?(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Loading Trash…`}):i?O.length===0?(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`This Trash folder is empty.`}):(0,Z.jsxs)(`table`,{className:`w-full text-left text-sm`,children:[(0,Z.jsx)(`thead`,{className:`border-b text-xs text-muted-foreground`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`w-8 p-2`,children:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all visible items`,checked:O.length>0&&O.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(O.map(e=>e.id)):new Set)})}),(0,Z.jsx)(`th`,{className:`p-2`,children:`Name`}),(0,Z.jsx)(`th`,{className:`p-2 max-sm:hidden`,children:`Original path`}),(0,Z.jsx)(`th`,{className:`p-2 max-md:hidden`,children:`Deleted`}),(0,Z.jsx)(`th`,{className:`p-2`,children:(0,Z.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,Z.jsx)(`tbody`,{children:O.map(e=>(0,Z.jsxs)(`tr`,{className:`border-b border-border/50 hover:bg-accent/50`,onContextMenu:t=>{t.preventDefault(),A(t.clientX,t.clientY,e)},onDoubleClick:()=>e.navigable&&n(Zt(i,e.key)),children:[(0,Z.jsx)(`td`,{className:`p-2`,children:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.name}`,checked:_.has(e.id),disabled:!!c,onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,Z.jsx)(`td`,{className:`p-2`,children:(0,Z.jsxs)(`button`,{className:`flex items-center gap-2 text-left`,onClick:()=>e.navigable&&n(Zt(i,e.key)),children:[e.directory?(0,Z.jsx)(Xr,{className:`h-4 w-4 shrink-0`}):(0,Z.jsx)(xa,{className:`h-4 w-4 shrink-0`}),(0,Z.jsxs)(`span`,{children:[e.name,e.navigable&&(0,Z.jsxs)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.items.length,` items`]})]})]})}),(0,Z.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-sm:hidden`,children:e.key}),(0,Z.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-md:hidden`,children:new Date(e.items.reduce((e,t)=>Math.max(e,t.deletedAt),0)).toLocaleString()}),(0,Z.jsx)(`td`,{className:`p-2 text-right`,children:(0,Z.jsx)(`button`,{title:`Actions for ${e.name}`,"aria-label":`Actions for ${e.name}`,disabled:!!c,className:`rounded p-2 hover:bg-accent`,onClick:t=>A(t.clientX,t.clientY,e),children:(0,Z.jsx)(ia,{className:`h-4 w-4`})})})]},e.id))})]}):(0,Z.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[E.map(e=>(0,Z.jsxs)(`button`,{onClick:()=>n(Zt(e.address)),className:`flex items-center gap-3 rounded-lg border p-4 text-left hover:bg-accent`,children:[(0,Z.jsx)(Qr,{className:`h-6 w-6 text-muted-foreground`}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:e.label||e.address}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.address})]})]},e.address)),!E.length&&(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`No file backends are available.`})]})}),y&&(0,Z.jsxs)(Dn,{x:y.x,y:y.y,onClose:()=>b(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[y.row.navigable&&(0,Z.jsxs)(`button`,{className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent`,onClick:()=>{n(Zt(i,y.row.key)),b(null)},children:[(0,Z.jsx)(Xr,{className:`h-4 w-4`}),`Open folder`]}),(0,Z.jsxs)(`button`,{disabled:!!c,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent disabled:opacity-50`,onClick:()=>void k(`restore`,y.row.items),children:[(0,Z.jsx)(Vr,{className:`h-4 w-4`}),`Restore `,y.row.directory?`folder`:`file`]}),(0,Z.jsxs)(`button`,{disabled:!!c||w,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-destructive hover:bg-destructive/10 disabled:opacity-50`,onClick:()=>void k(`discard`,y.row.items),children:[(0,Z.jsx)(Qr,{className:`h-4 w-4`}),`Delete permanently`]})]})]})}function Xw({value:e,backends:t,source:n,onSave:r,destination:i=!0}){let[a,o]=(0,X.useState)({...Uw,...e}),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),d=`rounded border bg-background px-2 py-1.5 text-xs w-full`,f=async()=>{c(!0),u(``);try{await r(a),u(`Removal policy saved.`)}catch(e){u(e instanceof Error?e.message:`Could not save policy`)}finally{c(!1)}};return(0,Z.jsxs)(`details`,{className:`border-t pt-3 text-xs`,children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:`Source removals and Trash`}),(0,Z.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`A completed scan removes missing locations from the backend tree. Items with no remaining locations go to Trash until you purge them.`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`space-y-1 block`,children:[`When an item disappears from this source`,(0,Z.jsxs)(`select`,{className:d,value:a.membership,disabled:s,onChange:e=>o({...a,membership:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`keep`,children:`Keep in managed trees`}),(0,Z.jsx)(`option`,{value:`review`,children:`Review removal in Trash`}),(0,Z.jsx)(`option`,{value:`trash`,children:`Move to Trash automatically`})]})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 block`,children:[`Remove tracked copies from other backends`,(0,Z.jsxs)(`select`,{className:d,value:a.propagation,disabled:s,onChange:e=>o({...a,propagation:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`never`,children:`Never`}),(0,Z.jsx)(`option`,{value:`review`,children:`Review in Trash`}),(0,Z.jsx)(`option`,{value:`automatic`,children:`Automatically, retaining recovery copies`})]})]})]}),a.propagation!==`never`&&(0,Z.jsxs)(`fieldset`,{className:`space-y-2`,children:[(0,Z.jsx)(`legend`,{className:`mb-1 font-medium`,children:`Destinations`}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:a.targets===`all`,disabled:s,onChange:e=>o({...a,targets:e.target.checked?`all`:[]})}),`All eligible backends`]}),a.targets!==`all`&&t.filter(e=>e.address!==n&&e.kind===`storage`).map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:s||e.config?.propagatedRemovalSupported!==!0,checked:a.targets.includes(e.address),onChange:t=>o({...a,targets:t.target.checked?[...a.targets,e.address]:a.targets.filter(t=>t!==e.address)})}),String(e.config?.label||e.address),e.config?.propagatedRemovalSupported===!0?!e.config?.removalPolicy?.acceptPropagatedDeletions&&` · protected`:` · recovery removal unavailable`]},e.address)),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Only tracked, Canvas-owned copies are eligible. Protected destinations refuse propagated deletion. Recovery removal currently supports filesystem and workspace blob storage; remote destinations remain protected.`})]}),i&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:s,checked:a.acceptPropagatedDeletions,onChange:e=>o({...a,acceptPropagatedDeletions:e.target.checked})}),`Accept propagated deletions on this backend`]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>void f(),children:s?`Saving…`:`Save removal policy`}),(0,Z.jsx)(`span`,{role:`status`,children:l})]})]})]})}function Zw({workspaceName:e,canWrite:t}){let{showToast:n}=wo(),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)([]),[l,u]=(0,X.useState)(!1),d=(0,X.useCallback)(async()=>{o(!0);try{i(await Io(e))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to load the trash`,variant:`destructive`})}finally{o(!1)}},[e]);(0,X.useEffect)(()=>{d()},[d]);let f=(0,X.useCallback)(e=>s.includes(e),[s]),p=async(e,t)=>{c(t=>[...t,...e]);try{await t()}finally{c(t=>t.filter(t=>!e.includes(t)))}},m=t=>p([t.id],async()=>{try{let r=await Ps(e,[t.id]);r.failed?.length?n({title:`Not restored`,description:r.failed[0]?.error||`No restore target recorded`,variant:`destructive`}):(n({title:`Restored`,description:`Document put back where it was.`}),i(e=>e.filter(e=>e.id!==t.id)))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to restore`,variant:`destructive`})}}),h=t=>p([t.id],async()=>{try{let r=await es(e,[t.id]);if(r.failed?.length)throw Error(`The item could not be purged. Refresh and retry.`);n({title:`Cleared from Trash`,description:r.preserved?.length?`Existing backend copies remain indexed.`:`Document permanently deleted.`}),i(e=>e.filter(e=>e.id!==t.id))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to delete`,variant:`destructive`})}}),g=async()=>{if(!l){u(!0);return}u(!1);try{let t=await es(e);n({title:`Trash emptied`,description:`${t.destroyed?.length??0} document(s) purged. ${t.preserved?.length??0} item(s) cleared with backend copies preserved.`}),await d()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to empty the trash`,variant:`destructive`})}},_=(0,X.useMemo)(()=>r.map(e=>{let t=Ho(e),n=(e.trashed?.placements??[]).flatMap(e=>e.paths.map(t=>`${e.tree}:${t}`));return{document:e,title:t.title,origin:n,trashedAt:e.trashed?.trashedAt||null}}),[r]);return(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-medium`,children:`Managed-tree items`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 max-w-2xl`,children:`Restore managed-tree placements or permanently purge these items. Pending removals require separate approval. Backend copies are managed below.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 max-sm:flex-wrap`,children:[(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>d(),disabled:a,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${a?`animate-spin`:``}`}),`Refresh`]}),(0,Z.jsxs)(Y,{variant:l?`destructive`:`outline`,size:`sm`,onClick:g,onBlur:()=>u(!1),disabled:!t||r.length===0,children:[(0,Z.jsx)(Qr,{className:`mr-2 h-3.5 w-3.5`}),l?`Click again to delete everything`:`Empty trash`]})]})]}),a&&r.length===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading…`}),!a&&r.length===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The trash is empty.`}),_.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md divide-y`,children:_.map(({document:e,title:n,origin:r,trashedAt:i})=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm`,children:n}),(0,Z.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[r.length>0?`from ${r.join(`, `)}`:`no recorded origin`,i?` · ${new Date(i).toLocaleString()}`:``]})]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>m(e),disabled:!t||f(e.id)||r.length===0,title:r.length===0?`Nothing recorded to restore to`:`Put it back where it was`,children:[(0,Z.jsx)(Vr,{className:`mr-2 h-3.5 w-3.5`}),`Restore placements`]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>h(e),disabled:!t||f(e.id),title:`Delete permanently`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]},e.id))})]})}function Qw({workspaceName:e}){return(0,Z.jsx)($w,{workspaceName:e},e)}function $w({workspaceName:e}){let[t,n]=(0,X.useState)(`pending`),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(0),[l,u]=(0,X.useState)(0),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)({}),[x,S]=(0,X.useState)(`/Trash`),[C,w]=(0,X.useState)([]),[T,E]=(0,X.useState)({write:!1,admin:!1});(0,X.useEffect)(()=>{let t=!0;return Ws(e).then(e=>{let n=e.remote?.permissions||e.access?.permissions||(typeof e.sharedVia==`object`?e.sharedVia?.permissions:[])||[],r=se(e);t&&E({admin:r,write:r||n.includes(`write`)})}).catch(()=>{}),()=>{t=!1}},[e]);let[D,O]=(0,X.useState)(null);(0,X.useEffect)(()=>{let t=!0;return Rc(e).then(e=>{t&&w(e)}).catch(()=>{}),()=>{t=!1}},[e]),(0,X.useEffect)(()=>{let n=!1,i=()=>Gw(e,{view:t,search:r,...a?{backend:a}:{},offset:s}).then(e=>{n||(f(e),m(``))}).catch(e=>{n||m(e instanceof Error?e.message:`Could not load Trash`)});i();let o=setInterval(()=>{h||i()},5e3);return()=>{n=!0,clearInterval(o)}},[e,t,r,a,s,l,h]);let k=d?.operations||[],A=()=>{v(new Set),u(e=>e+1)},j=()=>{Ms(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e}}))},M=async(t,n=[..._])=>{if(!(!n.length||h)&&!(t===`purge`&&!window.confirm(`Permanently delete retained recovery copies for ${n.length} operation(s)?`))){g(!0),m(``);try{let r=(t===`approve`?(await Promise.all(n.map(n=>Kw(e,[n],t,y[n])))).flatMap(e=>e.results):(await Kw(e,n,t)).results).filter(e=>!e.ok||e.operation?.state===`failed`);r.length&&m(r.map(e=>e.error||e.operation?.error||`A destination could not be changed. Expand the item for details.`).join(` `)),j(),A()}catch(e){m(e instanceof Error?e.message:`Trash action failed`)}finally{g(!1)}}},N=e=>{n(e),c(0),f(null),v(new Set),b({})};return(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:`Workspace Trash`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Review source removals, recover items, and see what automatic policies changed.`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,role:`tablist`,"aria-label":`Trash views`,children:[[[`pending`,`Pending removal`],[`trashed`,`In Trash`],[`activity`,`Activity`]].map(([e,n])=>(0,Z.jsx)(Y,{role:`tab`,"aria-selected":t===e,size:`sm`,variant:t===e?`default`:`outline`,onClick:()=>N(e),children:n},e)),(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,className:`ml-auto`,onClick:A,disabled:h,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),t===`trashed`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Zw,{workspaceName:e,canWrite:T.write},l),(0,Z.jsxs)(`details`,{className:`rounded border p-3`,children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:`Browse backend recovery copies`}),(0,Z.jsx)(`div`,{className:`mt-3 min-h-48`,children:(0,Z.jsx)(Jw,{workspace:e,path:x,onNavigate:S})})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(q,{"aria-label":`Filter Trash items`,placeholder:`Filter by item or path…`,className:`max-w-xs`,value:r,onChange:e=>{i(e.target.value),f(null),c(0),v(new Set)}}),(0,Z.jsx)(q,{"aria-label":`Filter by backend`,placeholder:`Backend name…`,className:`max-w-56`,value:a,onChange:e=>{o(e.target.value),f(null),c(0),v(new Set)}}),_.size>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsxs)(`span`,{children:[_.size,` selected`]}),t===`pending`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{size:`sm`,disabled:h,onClick:()=>void M(`approve`),children:`Approve selected`}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`keep`),children:`Keep selected`}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`retry`),children:`Retry`})]}),t===`trashed`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`restore`),children:`Restore copies`}),(0,Z.jsx)(Y,{size:`sm`,variant:`destructive`,disabled:h,onClick:()=>void M(`purge`),children:`Purge copies`})]})]})]}),D&&(0,Z.jsxs)(`div`,{className:`rounded border p-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Removal policy · `,D.source.account||D.source.backend,D.source.folder?` / ${D.source.folder}`:``]}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>O(null),children:`Close`})]}),(0,Z.jsx)(Xw,{source:D.source.backend,backends:C,destination:!1,value:{...Uw,...C.find(e=>e.address===D.source.backend)?.config?.removalPolicy,membership:y[D.id]?.membership??D.membership!==`keep`?`review`:`keep`,propagation:D.targets.length?`review`:`never`,targets:[...new Set(D.targets.filter(e=>!y[D.id]||y[D.id].targets.includes(JSON.stringify([e.backend,e.key]))).map(e=>e.backend))]},onSave:async t=>{D.source.driver===`imap`?await qw(e,D.source.account,D.source.folder,t):await Fo(e,D.source.driver,D.source.backend,{removalPolicy:t}),w(await Rc(e))}},D.id)]}),p&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p}),(0,Z.jsxs)(`div`,{className:`overflow-x-auto rounded border`,children:[(0,Z.jsxs)(`table`,{className:`w-full text-left text-xs`,children:[(0,Z.jsx)(`thead`,{className:`bg-muted`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`p-3 w-8`,children:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select visible operations`,disabled:!T.write||h||!k.length||t===`activity`,checked:k.length>0&&k.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(k.map(e=>e.id)):new Set)})}),(0,Z.jsx)(`th`,{className:`p-3`,children:`Item and affected copies`}),(0,Z.jsx)(`th`,{className:`p-3`,children:`Source`}),(0,Z.jsx)(`th`,{className:`p-3`,children:`Status`}),(0,Z.jsx)(`th`,{className:`p-3`,children:`Detected`})]})}),(0,Z.jsx)(`tbody`,{children:k.map(e=>{let n=y[e.id]||{targets:e.targets.filter(e=>e.state!==`kept`).map(e=>JSON.stringify([e.backend,e.key])),membership:e.membership!==`keep`};return(0,Z.jsxs)(`tr`,{className:`border-t align-top`,children:[(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.title}`,disabled:!T.write||h||t===`activity`,checked:_.has(e.id),onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,Z.jsx)(`td`,{className:`p-3 min-w-64`,children:(0,Z.jsxs)(`details`,{children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:e.title}),(0,Z.jsxs)(`div`,{className:`mt-2 space-y-2 text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:e.orphan?`No remaining byte locations. Restore placements only unless recovery bytes are available.`:`${e.remainingLocations.length} remaining location(s) when detected.`}),e.placements.map(e=>(0,Z.jsxs)(`p`,{children:[e.tree,`: `,e.paths.join(`, `)]},e.tree)),e.membership!==`keep`&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:n.membership,disabled:h||t!==`pending`||e.membershipApplied,onChange:t=>b({...y,[e.id]:{...n,membership:t.target.checked}})}),e.membershipApplied?`Managed placements moved to Trash`:`Move managed placements to Trash`]}),e.targets.map(r=>{let i=JSON.stringify([r.backend,r.key]);return(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:h||t!==`pending`||!!r.trashId,checked:n.targets.includes(i),onChange:t=>b({...y,[e.id]:{...n,targets:t.target.checked?[...n.targets,i]:n.targets.filter(e=>e!==i)}})}),(0,Z.jsxs)(`span`,{className:`break-all`,children:[r.backend,`:`,r.key,` · `,r.state,r.error&&(0,Z.jsx)(`span`,{className:`block text-destructive`,children:r.error})]})]},i)}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,disabled:!T.admin,onClick:()=>O(e),children:`Use these choices as a source policy`}),e.remainingLocations.map(e=>(0,Z.jsx)(`p`,{className:`break-all`,children:e.url},e.url))]})]})}),(0,Z.jsxs)(`td`,{className:`p-3 break-all`,children:[e.source.account||e.source.backend,e.source.folder&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:e.source.folder})]}),(0,Z.jsxs)(`td`,{className:`p-3`,children:[e.state,e.error&&(0,Z.jsx)(`p`,{className:`mt-1 max-w-xs text-destructive`,children:e.error})]}),(0,Z.jsx)(`td`,{className:`p-3 whitespace-nowrap text-muted-foreground`,children:new Date(e.createdAt).toLocaleString()})]},e.id)})})]}),!k.length&&(0,Z.jsx)(`p`,{className:`p-5 text-center text-sm text-muted-foreground`,children:d?`No matching operations.`:`Loading…`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[d?.total??0,` operation(s)`]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,disabled:!s||h,onClick:()=>{c(Math.max(0,s-200)),v(new Set)},children:`Previous`}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,disabled:s+k.length>=(d?.total??0)||h,onClick:()=>{c(s+200),v(new Set)},children:`Next`})]})]})]})}function eT({workspaceName:e,children:t}){let n=e,[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(0),[d,f]=(0,X.useState)(null);if((0,X.useEffect)(()=>{let t=!1,r=0,a,s=!1,c=async()=>{if(s||t)return;s=!0;let c=++r;try{let s=a?await Bs(e):await Ws(e);!t&&c===r&&(`id`in s&&(a=s.id,f({identity:n,allowed:se(s)})),i({identity:n,state:oo()||s.status===`active`?`active`:s.status===`inactive`?`stopped`:`unavailable`}),o(``))}catch(e){if(!t&&c===r){let t=e instanceof Error?e.message:`Unable to check workspace status`,r=ao(t);i(e=>r&&e?.identity===n&&e.state===`active`?e:{identity:n,state:r?`offline`:`unavailable`}),o(t)}}finally{s=!1}},l=t=>{let s=t.detail?.refs;!s?.includes(e)&&!(a&&s?.includes(a))||(r++,i({identity:n,state:`stopped`}),o(``))},u=t=>{let s=t.workspaceId||t.id;!s||s!==e&&s!==a||!t.status||(r++,i({identity:n,state:t.status===`active`?`active`:t.status===`inactive`?`stopped`:`unavailable`}),o(``))};c(),window.addEventListener(`workspaces:refresh`,c),window.addEventListener(`workspace:stopped`,l),window.addEventListener(`focus`,c);let d=B.on(`connect`,c);B.on(`workspace:status:changed`,u),B.on(`workspace.status.changed`,u);let p=ho(e=>{e||c()});return()=>{t=!0,d?.(),p(),B.off(`workspace:status:changed`,u),B.off(`workspace.status.changed`,u),window.removeEventListener(`workspaces:refresh`,c),window.removeEventListener(`workspace:stopped`,l),window.removeEventListener(`focus`,c)}},[e,n,l]),r?.identity!==n)return(0,Z.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`});if(r.state===`active`)return t;let p=r.state===`stopped`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:p?`Workspace stopped`:r.state===`offline`?`Server unreachable`:`Workspace unavailable`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p?`Start this workspace to view its content.`:r.state===`offline`?`Reconnect to load this workspace. Previously loaded content stays available offline.`:`Unable to check this workspace. Try again or check its settings.`}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(Y,{disabled:s,onClick:async()=>{c(!0),o(``);try{p&&await Ks(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?p?`Starting…`:`Checking…`:p?`Start workspace`:`Retry`}),d?.identity===n&&d.allowed&&(0,Z.jsx)(we,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]})}function tT({workspaceId:e,workspaceName:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,X.useEffect)(()=>{let t=!1,n=!1,i=!1,a=0,o=new Map,s=new Map,c=(e,t)=>{let n=e.filter(e=>e.address!==t.backend);if(!t.resyncing)return n;let r=e.find(e=>e.address===t.backend)||s.get(t.backend);return[...n,{address:t.backend,config:r?.config,resyncStartedAt:r?.resyncStartedAt||new Date().toISOString(),progress:t.progress??r?.progress}]},l=async()=>{if(n){i=!0;return}n=!0;let u=a;try{let n=await Rc(e);if(!t){s=new Map(n.map(e=>[e.address,e]));let e=n.filter(e=>e.resyncing);for(let t of o.values())t.version>u&&(e=c(e,t.event));r(e)}}catch{}finally{n=!1,i&&!t&&(i=!1,l())}},u=t=>{t.workspaceId!==e||!t.backend||typeof t.resyncing!=`boolean`||(o.set(t.backend,{version:++a,event:t}),r(e=>c(e,t)))},d=t=>{t.workspaceId===e&&l()};l();let f=B.on(`connect`,l);return B.on(`backend.resync.changed`,u),B.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),B.off(`backend.resync.changed`,u),B.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,Z.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,Z.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Ti,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,Z.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,Z.jsx)(vr,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:i}),(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,Z.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}var nT=`references`;function rT(e){return e?e.documents.map(e=>({predicate:nT,direction:`out`,targetId:e.id,document:e})):[]}function iT(e,t){let[n,r]=(0,X.useState)(()=>rT(t)),[i,a]=(0,X.useState)([...yc]),o=e?.mode===`context`?e.contextId:null,[s,c]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!o)return;let e=!1;return pl({mode:`context`,contextId:o}).then(t=>{e||c({contextId:o,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[o]);let l=e?.mode===`workspace`?e.workspaceName:o&&s?.contextId===o?s.workspaceName:t?.workspaceName??null;return(0,X.useEffect)(()=>{let e=!1;if(l)return ko(l).then(t=>{e||a(t)}),()=>{e=!0}},[l]),{rows:n,predicates:i,workspaceName:l,add:(0,X.useCallback)(async(e,t,i)=>{let a=i.filter(r=>!n.some(n=>n.targetId===r&&n.predicate===e&&n.direction===t));if(a.length===0)return;let o=await Promise.all(a.map(e=>l?xc(l,e).catch(()=>null):Promise.resolve(null)));r(n=>[...n,...a.map((n,r)=>({predicate:e,direction:t,targetId:n,document:o[r]??null}))])},[n,l]),update:(0,X.useCallback)((e,t)=>{r(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),remove:(0,X.useCallback)(e=>{r(t=>t.filter((t,n)=>n!==e))},[]),write:(0,X.useCallback)(async e=>{if(n.length===0||e.length===0||!l)return 0;let t=new Map;for(let e of n){let n=`${e.direction}:${e.predicate}`,r=t.get(n)??{predicate:e.predicate,direction:e.direction,targets:[]};r.targets.push(e.targetId),t.set(n,r)}let r=0;for(let n of e)for(let e of t.values())try{await Ac(l,n,e.predicate,e.targets,e.direction)}catch(t){r+=1,console.error(`Failed to relate document`,n,e.predicate,t)}return r<e.length*t.size&&Te(),r},[n,l]),hasRows:n.length>0}}function aT({f:e,idPrefix:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(!1),o=!e.workspaceName;return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(G,{children:`Related documents`}),(0,Z.jsxs)(Y,{type:`button`,variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs`,disabled:o,onClick:()=>r(!0),title:o?`No workspace to relate within`:`Pick documents the new one relates to`,children:[(0,Z.jsx)(br,{className:`mr-1 h-3 w-3`}),` Add`]})]}),e.rows.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None. Relations are written right after the document is created.`}):(0,Z.jsx)(`ul`,{className:`space-y-1`,children:e.rows.map((n,r)=>{let i=n.document?Ho(n.document).title:`Document ${n.targetId}`,a=`${t}-relation-${r}`;return(0,Z.jsxs)(`li`,{className:`flex items-center gap-1.5 rounded-md border border-input px-2 py-1.5 text-sm`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>e.update(r,{direction:n.direction===`out`?`in`:`out`}),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground`,title:n.direction===`out`?`The new document ${n.predicate} this one (click to flip)`:`This document ${n.predicate} the new one (click to flip)`,"aria-label":`Flip relation direction`,children:n.direction===`out`?(0,Z.jsx)(xi,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(ka,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`label`,{htmlFor:a,className:`sr-only`,children:`Predicate`}),(0,Z.jsx)(`select`,{id:a,value:n.predicate,onChange:t=>e.update(r,{predicate:t.target.value}),className:`w-[9.5rem] shrink-0 rounded-md border border-input bg-background px-1.5 py-1 font-mono text-[11px] focus:outline-none focus:ring-2 focus:ring-ring`,children:(e.predicates.includes(n.predicate)?e.predicates:[n.predicate,...e.predicates]).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))}),n.document?(0,Z.jsx)(Wt,{document:n.document,size:3.5}):null,(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 truncate`,!n.document&&`italic text-muted-foreground`),title:i,children:i}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>e.remove(r),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,title:`Remove`,"aria-label":`Remove relation`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]},`${n.direction}:${n.predicate}:${n.targetId}`)})}),n&&e.workspaceName&&(0,Z.jsx)(Le,{onClose:()=>{i||r(!1)},children:(0,Z.jsx)(y,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,confirmLabel:`Add`,tabs:[`relations`],fixedWorkspaceName:e.workspaceName,documentCount:1,saving:i,relationPredicates:e.predicates.length?e.predicates:[`references`],relationExcludeIds:new Set(e.rows.map(e=>e.targetId)),onClose:()=>r(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:t,direction:n,targetIds:i})=>{a(!0);try{await e.add(t,n,i),r(!1)}finally{a(!1)}}})})]})}function oT(e){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return ec(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var sT=`data/schema/file`,cT=`3.0`;function lT(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:oT(e),geotag:Ce()}}function uT(e,t,n={}){let r=Qc(n.tags??[]),i=n.comment?.trim();return{schema:sT,schemaVersion:cT,data:{},checksumArray:[`sha256/${e.checksum}`],locations:[{url:e.url,metadata:{filename:t.name}}],...i?{comment:i}:{},metadata:{contentType:t.type,size:e.size,...r.length?{features:r}:{},...n.geo?{geo:n.geo}:{}}}}function dT(e){if(e.manual){let t=`${e.manual.lat.toFixed(5)}, ${e.manual.lon.toFixed(5)}`;return e.manualLabel?`${e.manualLabel} · ${t}`:`Custom pin · ${t}`}if(!e.supported)return`Needs a secure (https) connection, or pick a point on the map`;if(e.permission===`denied`)return`Blocked. Allow location for this site, or pick a point on the map`;if(e.error)return e.error;if(e.busy)return`Getting your location…`;if(e.enabled&&e.fix){let{lat:t,lon:n,accuracy:r}=e.fix;return`${t.toFixed(5)}, ${n.toFixed(5)}${r==null?``:` · ±${r} m`}`}return e.enabled?`Location will be attached when you save`:`Attach where you are, or pick any point on the map`}function fT({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,X.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{role:`switch`,"aria-checked":e.enabled,"aria-disabled":i,"aria-label":`Geotag this document`,"aria-describedby":`${t}-hint`,tabIndex:i?-1:0,onClick:()=>!i&&e.setEnabled(!e.enabled),onKeyDown:t=>{i||(t.key===` `||t.key===`Enter`)&&(t.preventDefault(),e.setEnabled(!e.enabled))},className:K(`flex flex-1 items-center justify-between gap-3 select-none outline-none rounded focus-visible:ring-2 focus-visible:ring-ring`,i?`cursor-not-allowed opacity-50`:`cursor-pointer`),children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,Z.jsx)(Ti,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,Z.jsx)(mi,{className:K(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,Z.jsx)(`div`,{className:K(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,Z.jsx)(`div`,{className:K(`absolute top-[2px] h-4 w-4 rounded-full bg-background shadow-elevation-1 transition-transform`,e.enabled?`translate-x-[22px]`:`translate-x-[2px]`)})})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(!0),title:`Pick a point on the map`,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(Gi,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>e.setManual(null),"aria-label":`Remove custom pin`,title:`Remove custom pin`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`p`,{id:`${t}-hint`,className:K(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:dT(e)}),n&&(0,Z.jsx)(T,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}var pT=`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function mT({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`${t}-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`${t}-comment`,value:e.comment,onChange:t=>e.setComment(t.target.value),rows:3,placeholder:`Optional; searchable, and the only text a photo has`,className:pT}),n&&e.tags.length+e.comment.trim().length>0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,Z.jsx)(fT,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var hT=3;function gT(e){return`${e.name}:${e.size}:${e.lastModified}`}function _T(e=[]){let[t,n]=(0,X.useState)(()=>e.map(e=>({id:gT(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(t),o=(0,X.useRef)(null),s=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,X.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,X.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,X.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(gT(e))).map(e=>({id:gT(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,X.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,X.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,X.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,X.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await pl(e),d=r===`backends`?await bl(n,u):null,f=JSON.stringify([n,r,u]);o.current!==null&&o.current!==f&&c(a.current.map(({id:e,file:t})=>({id:e,file:t,status:`queued`,progress:0}))),o.current=f;let p=new AbortController;s.current=p,i(!0);let m=a.current.filter(e=>e.status!==`done`);for(let e of m)l(e.id,{status:`queued`,progress:0,error:void 0});try{if(d){let e=0;await Promise.all(Array.from({length:Math.min(hT,m.length)},async()=>{for(;e<m.length&&!p.signal.aborted;){let t=m[e++];try{l(t.id,{status:`uploading`,progress:0,resumed:!1});let e=await Do(n,{...d,key:Ml(d.key,t.file.name)},t.file,{signal:p.signal,onProgress:(e,n)=>l(t.id,{progress:n?e/n:0})});l(t.id,{status:`done`,progress:1,docId:e.docId??void 0})}catch(e){l(t.id,{status:`error`,error:e instanceof Error?e.message:`Upload failed`})}}}))}else{let r=new Map;for(let e of m){if(p.signal.aborted)throw new DOMException(`cancelled`,`AbortError`);if(!(e.file.size>=8388608)){l(e.id,{status:`hashing`});try{let t=await Fl(e.file,t=>l(e.id,{progress:t}));r.set(e.id,t),l(e.id,{status:`checking`,progress:0})}catch(t){l(e.id,{status:`error`,error:t instanceof Error?t.message:`Failed to read file`})}}}let i={};if(r.size)try{i=await To(n,[...new Set(r.values())])}catch{i={}}let a=m.filter(e=>r.has(e.id)||e.file.size>=8388608),o=0;await Promise.all(Array.from({length:Math.min(hT,a.length)},async()=>{for(;o<a.length;){if(p.signal.aborted)return;let s=a[o++],c=r.get(s.id);try{let r=c?i[c]??null:null;r?l(s.id,{status:`linking`,progress:1,resumed:!0}):(l(s.id,{status:`uploading`,progress:0}),r=await So(n,s.file,{sha256:c,signal:p.signal,onProgress:(e,t)=>l(s.id,{progress:t?e/t:0})}),l(s.id,{status:`linking`,progress:1}));let a=await wl(e,[t(r,s.file)],{refresh:!1});l(s.id,{status:`done`,docId:a[0]})}catch(e){let t=e instanceof DOMException&&e.name===`AbortError`;l(s.id,{status:`error`,error:t?`Cancelled`:e instanceof Error?e.message:`Upload failed`})}}}))}}finally{if(p.signal.aborted)for(let e of a.current)e.status!==`done`&&e.status!==`error`&&l(e.id,{status:`error`,error:`Cancelled`});i(!1),s.current===p&&(s.current=null),a.current.some(e=>e.status===`done`)&&El(e)}let h=a.current;return{done:h.filter(e=>e.status===`done`).length,resumed:h.filter(e=>e.status===`done`&&e.resumed).length,failed:h.filter(e=>e.status===`error`).length,total:h.length,docIds:h.flatMap(e=>e.status===`done`&&e.docId!=null?[e.docId]:[])}},[l,c]),cancel:p}}function vT(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function yT(e){switch(e.status){case`hashing`:return`hashing`;case`checking`:return`checking`;case`uploading`:return`${Math.round(e.progress*100)}%`;case`linking`:return`saving`;case`done`:return e.resumed?`already uploaded`:`done`;case`error`:return e.error||`failed`;default:return vT(e.file.size)}}function bT({item:e}){switch(e.status){case`done`:return(0,Z.jsx)(sr,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,Z.jsx)(er,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,Z.jsx)(xa,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function xT({item:e}){if(e.status===`queued`)return null;let t=e.status===`done`||e.status===`error`||e.status===`linking`?1:e.status===`checking`?0:e.progress;return(0,Z.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:K(`h-full rounded-full transition-[width] duration-normal`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function ST({items:e,running:t,onRemove:n}){let r=e.filter(e=>e.status===`done`).length,i=e.filter(e=>e.status===`error`).length;return(0,Z.jsx)(Z.Fragment,{children:e.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(G,{children:[e.length,` file(s)`,r>0&&(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,Z.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(bT,{item:e}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,Z.jsx)(`span`,{className:K(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:yT(e)}),!t&&e.status!==`done`&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(xT,{item:e})]},e.id))})]})})}function CT({items:e,running:t,onCancel:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,Z.jsx)(ST,{items:e,running:!0,onRemove:()=>{}}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function wT({capture:e=!1,target:t,initialFiles:n=[],onClose:r,onBusyChange:i}={}){let{closeAdd:a,state:o}=ol(),s=Dl(),c=t===void 0?s:t,l=r??a,u=c?.mode===`workspace`&&c.treeName===`backends`,d=iT(c,t===void 0?o.addRelateTo:null),{showSuccessToast:f,showErrorToast:p}=Oo(),m=(0,X.useRef)(null),[h,g]=(0,X.useState)(!1),_=_T(n),{items:v,running:y}=_,b=(0,X.useRef)(!1),x=(0,X.useRef)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(c?.mode!==`context`)return;let e=!1;return pl(c).then(t=>{e||T({contextId:c.contextId,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[c]);let E=lT(c?.mode===`workspace`?c.workspaceName:c&&w?.contextId===c.contextId?w.workspaceName:null),D=e=>{e&&_.addFiles(Array.from(e))},O=e=>{e.preventDefault(),g(!1),D(e.dataTransfer.files)},k=v.filter(e=>e.status===`error`).length,A=v.filter(e=>e.status===`done`).length,j=v.length-A,M=!!c&&!S&&j>0;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),g(!0)},onDragLeave:()=>g(!1),onDrop:O,onClick:()=>m.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,h?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(Yr,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:e?`Take a photo or video`:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`click to open the camera`:`or click to browse`}),(0,Z.jsx)(`input`,{ref:m,type:`file`,multiple:!0,accept:e?`image/*,video/*`:void 0,capture:e?`environment`:void 0,className:`hidden`,onChange:e=>{D(e.target.files),e.target.value=``}})]}),(0,Z.jsx)(ST,{items:v,running:y,onRemove:_.removeItem}),!u&&(0,Z.jsx)(mT,{fields:E,idPrefix:`file`,multiple:v.length>1}),(0,Z.jsx)(aT,{f:d,idPrefix:`file`}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[Ol(c),u?`. Existing files are never overwritten.`:``]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>{S?(x.current=!0,_.cancel()):l()},children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{if(!(!M||!c||b.current)){b.current=!0,x.current=!1,C(!0),i?.(!0);try{let e=u?null:await E.geotag.capture();if(x.current)return;let t=await _.start(c,(t,n)=>uT(t,n,{tags:E.tags,comment:E.comment,geo:e})),n=await d.write(t.docIds);if(t.failed===0){let e=t.resumed?` (${t.resumed} already uploaded)`:``,r=n?`; some relations failed`:``;f(`${t.done} file(s) uploaded${e}${r}`),l()}else p(`${t.failed} of ${t.total} file(s) failed — retry keeps what already made it`)}catch(e){p(e instanceof Error?e.message:`Failed to upload files`)}finally{b.current=!1,C(!1),i?.(!1)}}},disabled:!M,children:S?`Uploading…`:k>0?(0,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(Vr,{className:`h-3.5 w-3.5`}),`Retry failed (`,k,`)`]}):`Add files`})]})]})}function TT({target:e,children:t}){let[n,r]=(0,X.useState)([]),i=(0,X.useRef)(!1),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),{showErrorToast:d}=Oo();return(0,Z.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0 bg-background ${a?`ring-2 ring-inset ring-primary`:``}`,onDragOverCapture:t=>{s||!e||!Array.from(t.dataTransfer.types).includes(`Files`)||(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=i.current?`none`:`copy`,o(!i.current))},onDragLeaveCapture:e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)},onDropCapture:t=>{if(s||!e||!Array.from(t.dataTransfer.types).includes(`Files`))return;if(t.preventDefault(),t.stopPropagation(),o(!1),i.current){d(`Wait for the current upload to finish`);return}let n=Array.from(t.dataTransfer.files);if(!n.length){d(`Drop files rather than folders`);return}r(n),u(e),c(!0)},children:[t,a&&(0,Z.jsxs)(`div`,{className:`pointer-events-none absolute inset-0 z-30 flex items-center justify-center bg-background/80 text-sm font-medium`,children:[`Drop files to upload to `,e?.mode===`workspace`?e.path:`this context`]}),s&&(0,Z.jsxs)(tn,{label:`Import files`,onClose:()=>{i.current||c(!1)},children:[(0,Z.jsx)(`h2`,{className:`border-b px-4 py-3 text-sm font-medium`,children:`Import files`}),(0,Z.jsx)(wT,{target:l,initialFiles:n,onClose:()=>c(!1),onBusyChange:e=>{i.current=e}})]})]})}function ET({navigationTabs:e,navigationActions:t,onBack:n,accentColor:r,frameContent:i=!0,urlType:a,urlDisplay:o,contextPath:s,treeName:c,workspaceId:l,workspaceLabel:u,workspaceIcon:d,documentSchema:f,documents:p,isLoading:m,totalCount:h,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:M,disablePurgeDocuments:N,canvasInfo:P,isCanvasPinned:ee,onTogglePinCanvas:F,onSaveAsCanvas:I,onShareCanvas:te,onUnshareCanvas:L,onDeleteCanvas:R,isSharingCanvas:ne,isDeletingCanvas:re,isCanvasShared:ie,isCanvasLocked:ae,backendSearchQueries:z,onBackendSearch:oe,onRemoveBackendQuery:se,serverSort:B,onServerSortChange:ce,scope:V,onScopeChange:le,canSaveChanges:ue,isSavingChanges:de,onSaveChanges:fe,onBrowseWorkspaces:pe,onBrowseTree:me,onNavigatePath:he,linkTree:ge,children:_e,contentBanner:ve,folders:be,onOpenFolder:xe}){let H=a===`canvas`,{state:Se,toggleView:Ce,hasActiveFilters:U,openAddPicker:W}=ol(),we=ye(),[Te,Ee]=(0,X.useState)(``),De=JSON.stringify([l,c,s,f]),[Oe,ke]=(0,X.useState)(De);Oe!==De&&(ke(De),Ee(``));let Ae=(0,Z.jsxs)(Z.Fragment,{children:[t,I&&(0,Z.jsx)(`button`,{type:`button`,onClick:I,title:`Save as canvas`,"aria-label":`Save as canvas`,className:`flex h-control-sm w-control-sm shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent touch-target`,children:(0,Z.jsx)(Oi,{className:`h-4 w-4`})})]});return(0,Z.jsxs)(TT,{target:k&&l?{mode:`workspace`,workspaceName:l,path:s,treeName:c||`context`,treeType:c===`directory`?`directory`:`context`}:null,children:[e&&(0,Z.jsx)(Ge,{accentColor:r,children:e}),(0,Z.jsxs)(`div`,{className:`canvas-surface-body${i?` is-framed`:``}`,children:[(0,Z.jsx)(qe,{workspaceIcon:d,workspace:u||l||o.split(`://`)[0]||`Workspace`,tree:c?`${c}${a.endsWith(`-layer`)?`:layer`:``}`:a.replace(`-layer`,``),path:s,accentColor:r,onBack:we.location?we.location.section===`view`?we.close:()=>we.update?.({section:`view`}):n,section:we.location?`document/${we.location.documentId}/${we.location.section}`:void 0,onSection:we.location?()=>we.update?.({section:`view`}):void 0,onBrowseWorkspaces:pe,onBrowseTree:me,onNavigatePath:he,onFilter:()=>Ce(`tools`),filtersActive:U,filtersOpen:Se.t1Open&&Se.t1View===`tools`,onAdd:e=>W({modal:e.shiftKey,fresh:!0}),search:oe||!_e?{queries:z||[],onSearch:oe??Ee,localOnly:!oe,onRemoveQuery:se,scope:V,onScopeChange:le}:void 0,onDraftChange:_e?void 0:Ee}),H&&P?(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[P.color&&(0,Z.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:P.color}}),(0,Z.jsx)(Pa,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:P.label||o.split(`://`)[1]||`Canvas`}),P.description&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:P.description})]}),ue&&fe&&(0,Z.jsxs)(`button`,{type:`button`,onClick:fe,disabled:de,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:`Save filters`,children:[(0,Z.jsx)(Yn,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:de?`Saving...`:`Save filters`})]}),F&&(0,Z.jsxs)(`button`,{type:`button`,onClick:F,"aria-pressed":!!ee,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground`,title:ee?`Unpin from home`:`Pin to home`,children:[ee?(0,Z.jsx)(ur,{className:`w-3 h-3`}):(0,Z.jsx)(tr,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:ee?`Unpin`:`Pin`})]}),te&&(0,Z.jsxs)(`button`,{type:`button`,onClick:te,disabled:ne||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:ie?`Copy public link`:`Share canvas`,children:[(0,Z.jsx)(aa,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:ne?`Sharing...`:ie?`Copy link`:`Share`})]}),ie&&L&&(0,Z.jsxs)(`button`,{type:`button`,onClick:L,disabled:ne||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,Z.jsx)(nr,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),R&&(0,Z.jsxs)(`button`,{type:`button`,onClick:R,disabled:re||ae&&!ie,title:ae&&!ie?`Unlock this canvas before deleting it`:`Delete canvas`,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,Z.jsx)(Qr,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:re?`Deleting…`:`Delete`})]})]})}):null,_e&&(I||t)&&(0,Z.jsx)(`div`,{className:`flex items-center gap-2 border-b px-3 py-1`,children:Ae}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[ve,_e||(0,Z.jsx)(fn,{readingPane:!0,externalSearchQuery:Te,toolbarActions:Ae,documents:f?p.filter(e=>e.schema===f):p,isLoading:m,folders:f?void 0:be,onOpenFolder:xe,contextPath:s,treeName:c,workspaceId:l,totalCount:h,viewMode:f?`card`:`table`,allowViewToggle:!0,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:f?void 0:M,disablePurgeDocuments:N,backendSearchQueries:z,onBackendSearch:oe,serverSort:B,onServerSortChange:ce,onRemoveBackendQuery:se,scope:V,onScopeChange:le,canSaveChanges:!H&&ue,isSavingChanges:de,onSaveChanges:fe,linkTree:ge},f??`documents`)]})]})]})}var DT=[{id:`todos`,label:`Todo list`},{id:`todo-app`,label:`Todo App`},{id:`notes`,label:`Notes list`},{id:`notes-app`,label:`Notes App`},{id:`sketch`,label:`Sketch`},{id:`terminal`,label:`Terminal`}];function OT(e){return e?.kind===`app`&&e.app===`notes`?`data/schema/note`:void 0}var kT={id:`default`,name:`All`,kind:`documents`};function AT(){return[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}]}function jT(e){let t=e?.views;if(!Array.isArray(t))return[kT];let n=t.filter(e=>{let t=e;return!t||typeof t.id!=`string`||typeof t.name!=`string`?!1:t.kind===`documents`||t.kind===`columns`||t.kind===`app`&&(DT.some(e=>e.id===t.app)||t.app===`filters`||t.app===`lens`)});return n.length>0?n:[kT]}var MT={todos:pa,"todo-app":pa,notes:Da,"notes-app":Da,filters:Ci,sketch:qi,Brush:pr,terminal:qi,lens:Br};function NT({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=v.current;if(!e)return;let t=t=>{if(t.ctrlKey||e.scrollWidth<=e.clientWidth)return;let n=Math.abs(t.deltaX)>Math.abs(t.deltaY)?t.deltaX:t.deltaY,r=t.deltaMode===1?16:t.deltaMode===2?e.clientWidth:1;t.preventDefault(),e.scrollLeft+=n*r};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[]),(0,X.useEffect)(()=>{v.current?.querySelector(`[aria-pressed="true"], input`)?.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,c]);let y=()=>{h(null),_(null)},b=()=>{if(m&&g&&m!==g.id){let t=e.find(e=>e.id===m),n=e.filter(e=>e.id!==m),i=n.findIndex(e=>e.id===g.id);t&&i>=0&&(n.splice(g.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!c)return;let t=u.trim();t&&r(e.map(e=>e.id===c?{...e,name:t}:e)),l(null)},S=(t,n)=>{p(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?DT.find(e=>e.id===n)?.label??`App`:`List`,o=t===`columns`?{id:i,name:a,kind:t,columns:AT()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),l(i),d(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[kT],n===t?i[0]?.id??kT.id:void 0)};return(0,Z.jsxs)(`div`,{className:K(`relative flex h-full min-w-0 items-end`,a),children:[(0,Z.jsx)(`div`,{ref:v,className:`flex min-w-0 items-end gap-0.5 overflow-x-auto overscroll-x-contain pt-1 [scrollbar-width:none]`,children:e.map(r=>{let a=r.id===t,f=r.kind===`columns`?za:r.kind===`app`&&r.app?MT[r.app]:di;return c===r.id?(0,Z.jsx)(`input`,{autoFocus:!0,"aria-label":`Tab name`,value:u,onChange:e=>d(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&l(null)},className:K(`relative h-[2.3rem] w-28 shrink-0 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs outline-none ring-0`,a?K(`z-[2] bg-background font-medium`,o?Ot(o):`text-foreground`):`bg-muted text-muted-foreground`),style:{backgroundColor:a?o:void 0}},r.id):(0,Z.jsxs)(`button`,{type:`button`,"aria-pressed":a,onClick:()=>n(r.id),onDoubleClick:()=>{i||(l(r.id),d(r.name))},title:i?r.name:`${r.name}: double-click to rename, drag to reorder`,draggable:!i,onDragStart:e=>{e.dataTransfer.setData(`text/plain`,r.name),e.dataTransfer.effectAllowed=`move`,h(r.id)},onDragOver:e=>{if(!m||m===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;_(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:K(`group relative flex h-[2.3rem] shrink-0 items-center gap-1.5 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs transition-colors`,a?K(`z-[2] bg-background font-medium`,o?Ot(o):`text-foreground`):`bg-muted text-muted-foreground hover:bg-accent hover:text-foreground`,m===r.id&&`opacity-50`),style:{backgroundColor:a?o:void 0,boxShadow:g?.id===r.id?`inset ${g.before?`2px`:`-2px`} 0 0 var(--primary)`:void 0},children:[(0,Z.jsx)(f,{className:`h-3 w-3 shrink-0`}),(0,Z.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,Z.jsx)(cr,{className:`h-3 w-3 shrink-0 opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-60`,"aria-label":`Open to the side`,onClick:e=>{e.stopPropagation(),s(r.id)}}),!i&&e.length>1&&(0,Z.jsx)(vr,{className:K(`h-3 w-3 shrink-0 transition-opacity hover:text-destructive`,a?`opacity-60 hover:opacity-100`:`opacity-0 group-hover:opacity-100`),onClick:e=>{e.stopPropagation(),C(r.id)}})]},r.id)})}),!i&&(f?(0,Z.jsxs)(`span`,{className:`absolute left-0 top-full z-30 flex w-full min-w-64 flex-wrap items-center gap-2 rounded-b-xl border bg-card p-2 shadow-lg`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(di,{className:`h-3 w-3`}),` List`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(za,{className:`h-3 w-3`}),` Board`]}),DT.map(e=>{let t=MT[e.id];return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(t,{className:`h-3 w-3`}),` `,e.label]},e.id)}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]}):(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(!0),title:`Add view`,"aria-label":`Add view`,className:`relative ml-1 flex h-[2.3rem] w-10 shrink-0 items-center justify-center rounded-md pb-1 text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,Z.jsx)(br,{className:`h-3.5 w-3.5`})}))]})}function PT(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null);(0,X.useEffect)(()=>{let o=!1;return Yo(e,n,t,{limit:200,allOf:[r],...i?{sortBy:i,order:`asc`}:{}}).then(e=>{o||l({key:a,docs:e.payload||[]})}).catch(()=>{o||l({key:a,docs:[]})}),()=>{o=!0}},[a,o]);let u=c?.key===a?c.docs:[],d=c?.key!==a;return(0,X.useEffect)(()=>{let e=()=>s(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]),{docs:u,isLoading:d,refresh:(0,X.useCallback)(()=>s(e=>e+1),[])}}function FT({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=PT(e,t,n,Qo,`tasks`),[o,s]=(0,X.useState)(!1),c=o?r.filter(e=>e.data?.status!==`completed`):r,l=r.filter(e=>{let t=e.data?.status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,Z.jsx)(ef,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function IT({app:e,contextId:t,...n}){let r=t&&e!==`lens`?{mode:`context`,contextId:t}:{mode:`workspace`,workspaceName:n.workspaceId,treeName:n.treeName,path:n.path,treeType:n.treeName===`directory`||n.treeName===`backends`?`directory`:`context`},i=e===`todo-app`?`todo`:e===`notes-app`?`notes`:e,a=_C.find(e=>e.id===i);return(0,Z.jsx)(yC,{target:r,children:e===`todos`?(0,Z.jsx)(FT,{...n}):a?(0,Z.jsx)(a.Component,{}):null})}var LT=[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}];function RT(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function zT({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)({}),p=(0,X.useRef)(null),[m,h]=(0,X.useState)(!1),g=(0,X.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,X.useEffect)(()=>{let e=p.current;if(!e)return;let t=new ResizeObserver(()=>g());return t.observe(e),()=>t.disconnect()},[g]);let _=(e,t)=>{e.preventDefault();let i=e.currentTarget.parentElement;if(!i)return;let a=e.clientX,o=i.getBoundingClientRect().width,s=o,c=e=>{s=Math.min(900,Math.max(220,o+e.clientX-a)),f(e=>({...e,[t]:s}))},l=()=>{window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),r(n.map(e=>e.id===t?{...e,width:Math.round(s)}:e))};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l)},v=e=>{f(t=>{let n={...t};return delete n[e],n}),r(n.map(t=>t.id===e?{...t,width:void 0}:t))},y=e=>{let t=l[e];if(t===void 0)return;let i=n.find(t=>t.id===e);i&&(i.filter||``)!==t&&r(n.map(n=>n.id===e?{...n,filter:t||void 0}:n))},b=LT.filter(e=>!n.some(t=>t.id===e.id));return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.jsx)(`div`,{ref:p,onScroll:g,className:`flex h-full snap-x snap-mandatory gap-3 overflow-x-auto overscroll-x-contain p-2`,"data-testid":`schema-columns-board`,children:n.map(t=>{let a=(l[t.id]??t.filter??``).toLowerCase(),s=e.filter(e=>RT(e,t.schemas)).filter(e=>{if(!a)return!0;let t=Ho(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,Z.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-(--card-radius) border bg-muted/20 ${c?`sm:basis-[var(--col-w)]`:`sm:basis-[48%] lg:basis-[32%] xl:basis-[24%]`}`,style:c?{"--col-w":`${c}px`}:void 0,children:[!i&&(0,Z.jsx)(`div`,{onPointerDown:e=>_(e,t.id),onDoubleClick:()=>v(t.id),title:`Drag to resize; double-click to reset`,className:`absolute right-0 inset-y-0 z-10 w-2 cursor-col-resize touch-none rounded-r-lg transition-colors hover:bg-primary/25 active:bg-primary/40 max-sm:hidden`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,Z.jsx)(`span`,{className:`flex-1`}),!i&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(n.filter(e=>e.id!==t.id)),title:`Remove column`,className:`rounded-sm p-0.5 text-muted-foreground hover:text-destructive`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`div`,{className:`px-3 pb-2`,children:(0,Z.jsx)(`input`,{value:l[t.id]??t.filter??``,onChange:e=>u(n=>({...n,[t.id]:e.target.value})),onBlur:()=>y(t.id),onKeyDown:e=>{e.key===`Enter`&&y(t.id)},placeholder:`Filter…`,readOnly:i,className:`h-7 w-full rounded-md border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})}),(0,Z.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=Ho(e);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>o(e),className:`w-full min-w-0 rounded-md border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(Wt,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,Z.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,Z.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground/70`,children:new Date(e.updatedAt||e.createdAt).toLocaleDateString()})]},e.id)}),s.length===0&&(0,Z.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground/60`,children:`Empty`})]})]},t.id)})}),(!i&&b.length>0||m)&&(0,Z.jsxs)(`div`,{className:`pointer-events-none absolute inset-y-0 right-0 z-20 flex w-7 flex-col items-end bg-gradient-to-l from-background via-background/60 to-transparent py-2`,children:[!i&&b.length>0&&(0,Z.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(e=>!e),title:`Add column`,"aria-label":`Add column`,className:`flex h-7 w-6 items-center justify-center rounded-l-md border border-r-0 bg-background text-muted-foreground shadow-elevation-1 hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(br,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{c(!1),r([...n,{...e}])},className:`w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:e.label},e.id)),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`mt-1 w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/60 hover:bg-accent/50`,children:`Cancel`})]})]}),m&&(0,Z.jsx)(Xa,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,Z.jsx)(Me,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var BT=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function VT(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function HT(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>HT(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:VT(e)}];let r=BT(e);if(!r)return[];let i=r.tree??r.treeId,a=typeof i==`string`?n.get(i)??null:null;return[].concat(r.paths??r.path??`/`).filter(e=>typeof e==`string`).map(e=>({tree:a,kind:t,path:VT(e)}))}function UT(e){let t=[],n=e=>{let n=Number(e);Number.isSafeInteger(n)&&n>0&&t.push(n)};return Array.isArray(e.ids)&&e.ids.forEach(n),Array.isArray(e.documentIds)&&e.documentIds.forEach(n),e.id!=null&&n(e.id),e.documentId!=null&&n(e.documentId),t}function WT(e){let t=new Map;for(let n of e)t.set(n.id,n.name),t.set(n.name,n.name);return t}function GT(e,t,n=new Map){let r=BT(t);if(!r)return{targets:[],ids:[],unknown:!0};if(e.startsWith(`tree.`)){let e=typeof r.treeName==`string`?r.treeName:null,t=r.treeType===`directory`||r.treeType===`context`?r.treeType:null,n=r.contextSpec??r.path;return typeof n==`string`?{targets:[{tree:e,kind:t,path:VT(n)}],ids:UT(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...HT(r.context,`context`,n),...HT(r.directory,`directory`,n)],a=BT(r.changed);a&&i.push(...HT(a.context,`context`,n),...HT(a.directory,`directory`,n));let o=UT(r);if(i.length)return{targets:i,ids:o,unknown:!1};let s=r.reason===`content`||r.reason===`relations`;return e.startsWith(`document.updated`)&&s&&o.length?{targets:[],ids:o,unknown:!1}:{targets:[],ids:o,unknown:!0}}function KT(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function qT(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>VT(e).split(`/`).filter(Boolean).map(e=>e.normalize(`NFKC`).trim().replace(/\s+/g,` `).replace(/[^\p{L}\p{N}\p{M} .+_@-]/gu,`_`).replace(/_+/g,`_`).toLowerCase()||`_`),r=new Set(n(e.path)),i=n(t.path);return r.size===0||i.length===0||i.some(e=>r.has(e))}return KT(e.path,t.path)}function JT(e){return GT(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function YT(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>qT(e,t))))return!0;if(e.ids.length&&n){let t=n instanceof Set?n:new Set(n);if(e.ids.some(e=>t.has(e)))return!0}return!1}var XT=(0,X.createContext)(null);function ZT(){let e=(0,X.useContext)(XT);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function QT(e,t,n={}){return B.request(Jl,{workspace:e,specs:t,opts:n})}function $T(e,t,n){return B.request(Yl,{sessionId:e,label:t,spec:n})}function eE(e){return B.request(Xl,{sessionId:e})}function tE(e,t={}){return B.request(Zl,{sessionId:e,...t})}function nE(e){return B.request(Ql,{sessionId:e})}function rE(e){return B.on($l,e)}var iE=100;function aE({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),f=(0,X.useRef)([]),p=(0,X.useRef)(new Map),m=(0,X.useRef)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(null),_=(0,X.useRef)({}),v=(0,X.useRef)(null),y=(0,X.useMemo)(()=>JSON.stringify(t),[t]),b=(0,X.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,X.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,X.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=iE){let i=e.slice(r,r+iE),a=await Fs(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,X.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),x(),r.length===0)return;let a=await S(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}x()},[S,x]),w=(0,X.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await C(a,[],t)},[C]);(0,X.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await QT(e,JSON.parse(y),JSON.parse(b));if(t){nE(r.sessionId).catch(()=>{});return}n=r.sessionId,m.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await w(r.ids,r.count)}catch(e){if(t)return;d(e instanceof Error?e.message:`Failed to open query session`),l(null),m.current=null}};i();let o=B.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&nE(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,X.useEffect)(()=>{if(!c)return;let e=rE(e=>{if(e.sessionId===c){if(g.current!==null){v.current?.(g.current,_.current);return}e.ids===void 0?C(e.added??[],e.removed??[],e.count):w(e.ids,e.count)}});return()=>{e?.()}},[c,C,w]);let T=(0,X.useCallback)(async()=>{let e=m.current;if(e)try{let t=await eE(e);await w(t.ids,t.count)}catch{}},[w]),E=(0,X.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await $T(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await w(r.ids,r.count)},[w]),D=(0,X.useCallback)(async(e,t={})=>{let n=m.current;if(!n)throw Error(`No open query session`);if(g.current=e,_.current=t,e===null){await T();return}let r=await tE(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),x()},[x,T]);(0,X.useEffect)(()=>{v.current=D},[D]);let O=(0,X.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await tE(r,{match:t,limit:n.limit??100,...n.mode?{mode:n.mode}:{}});for(let e of i.documents)p.current.set(e.id,e);let a=await $T(r,e,{ids:i.ids});return await w(a.ids,a.count),i.ids},[w]);return{documents:i,count:o,ready:c!==null,error:u,setCue:E,resync:T,rank:D,rankAndPin:O}}var oE=`canvas:query-debug`,sE=`canvas:query-debug-changed`;function cE(){try{return localStorage.getItem(oE)===`1`}catch{return!1}}function lE(e){try{e?localStorage.setItem(oE,`1`):localStorage.removeItem(oE)}catch{}window.dispatchEvent(new CustomEvent(sE,{detail:e}))}function uE(){let[e,t]=(0,X.useState)(cE);return(0,X.useEffect)(()=>{let e=()=>t(cE());return window.addEventListener(sE,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(sE,e),window.removeEventListener(`storage`,e)}},[]),e}function dE({data:e,className:t}){let[n,r]=(0,X.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,X.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,Z.jsxs)(`div`,{className:K(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let s=a>0?i[a].distance:null;return(0,Z.jsxs)(`div`,{className:K(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,Z.jsx)(qr,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Xa,{className:`h-3.5 w-3.5`}),`Query debug`,(0,Z.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,Z.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,s===null?(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,Z.jsxs)(Z.Fragment,{children:[` A jump at `,(0,Z.jsx)(`span`,{className:`font-mono`,children:s.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,Z.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,Z.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,Z.jsx)(`tbody`,{children:i.map((e,t)=>(0,Z.jsxs)(`tr`,{className:K(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,Z.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,Z.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,Z.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,Z.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}function fE(e,t){if(!e)return[];let n=t.split(`/`).filter(Boolean),r=e;for(let e of n)if(r=r?.children?.find(t=>t.name===e)??null,!r)return[];let i=n.length?`/${n.join(`/`)}`:``,a=(r.children??[]).filter(e=>e.type!==`canvas`).map(e=>({name:e.name,path:`${i}/${e.name}`,label:e.label,color:e.color,childCount:e.children?.length??0})).sort((e,t)=>(e.label||e.name).localeCompare(t.label||t.name,void 0,{numeric:!0,sensitivity:`base`}));return n.length>0&&a.unshift({name:`..`,path:n.length>1?`/${n.slice(0,-1).join(`/`)}`:`/`,isParent:!0}),a}var pE=new Map;function mE(e,t,n){return`${e}\0${t}\0${n}`}function hE(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${mE(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function gE(e,t,n){let r=mE(e,t,n);for(let e of pE.keys())e.startsWith(r)&&pE.delete(e)}function _E(e,t){let n=`${e}\0`;for(let[e,r]of pE){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);YT(t,{tree:i,kind:Ls(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&pE.delete(e)}}function vE(e,t){_E(t?.workspaceName??e,JT(t))}function yE(){let{workspaceName:e}=yt();return e?(0,Z.jsx)(eT,{workspaceName:e,children:(0,Z.jsx)(bE,{})}):null}function bE(){let{workspaceName:e,treeName:t}=yt(),n=vn(),r=ft(),{showToast:i,showProgress:a}=wo(),o=new URLSearchParams(n.search),s=(()=>{let e=o.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(o.get(`search`)||``).trim();return t?[t]:[]})(),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(0),v=uE(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(v);x!==v&&(S(v),v||b(null));let[C,w]=(0,X.useState)(`path`),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(``),[N,P]=(0,X.useState)(!1),[ee,F]=(0,X.useState)(!1),[I,te]=(0,X.useState)(!1),[L,R]=(0,X.useState)(null),[ne,re]=(0,X.useState)(1),[ie,ae]=(0,X.useState)(50),[z,oe]=(0,X.useState)(s),[se,ce]=(0,X.useState)(null),{state:V,saveFilters:ue,setSort:de,setAccentColor:fe,setMapDocuments:pe}=ol(),me=V.filters.features.allOf,he=V.filters.features.anyOf,ge=V.filters.features.noneOf,_e=it(V.filters.timeline),ve=En(V.filters.geo),ye=ke(V.filters.lens,V.filters.geo.includeUnlocated),be=V.filters.lens.ids,xe=[..._e,...ve,...ye],H=V.filters.sort??bn,Se=JSON.stringify({a:me,b:he,c:ge,d:xe,i:be,s:H}),Ce=JSON.stringify({a:me,b:he,c:ge,d:xe,s:H}),U=af(n.pathname).path,W=t??`context`,we=W===`backends`,[Te,Ee]=(0,X.useState)([]);(0,X.useEffect)(()=>{!we||!e||Rc(e).then(Ee).catch(()=>Ee([]))},[we,e]);let De=we?Sc(U,Te):null,[Oe,Ae]=(0,X.useState)(!1),je=`${W}\0${U}`,[Me,Ne]=(0,X.useState)(je);Me!==je&&(Ne(je),Ae(!1));let Fe=o.get(`layer`)===`1`,Ie=o.get(`layerId`)||null,[Le,Re]=(0,X.useState)(null),[ze,Be]=(0,X.useState)(null),Ve=(0,X.useRef)(null);(0,X.useEffect)(()=>{Ve.current=ze},[ze]);let[He,Ue]=(0,X.useState)(`left`),[We,Ge]=(0,X.useState)([]),{openM1Drawer:Ke,openM2Drawer:G,goBack:Je}=qC(),[Ye,Xe]=(0,X.useState)([]),Ze=(0,X.useMemo)(()=>{if(!Le||U===`/`||Fe)return null;let e=U.split(`/`).filter(Boolean),t=Le;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Le,U,Fe]),Qe=Ze?.type===`canvas`?`canvas`:null,$e=(0,X.useRef)(null);(0,X.useEffect)(()=>{!e||!Le||Fe||$e.current===`${e}/${W}`&&(U!==`/`&&!Ze||bw(e,W,U))},[e,Le,Fe,U,Ze,W]);let et=(0,X.useMemo)(()=>Fe||C===`workspace`||z.length>0||Ls(W)!==`directory`?[]:fE(Le,U),[Le,U,W,Fe,C,z]),tt=Fe?null:U===`/`?Le:Ze,nt=le(),rt=`${W}\0${U}`,[at,ot]=(0,X.useState)(null),st=at?.key===rt?at.views:jT(tt?.metadata),ct=nt?.pinned&&nt.view?[nt.view,...st.filter(e=>e.id!==nt.view.id)]:st,lt=nt?.pinned&&nt.view?nt.view.id:at?.key===rt?at.activeId:ct[0]?.id??kT.id,ut=ct.find(e=>e.id===lt)??ct[0]??kT;(0,X.useEffect)(()=>{nt?.selectView(ut)},[ut,nt]);let dt=we?void 0:nt?.schema??OT(ut),pt=dt?[...me,dt]:me,mt=e=>{let t=ct.find(t=>t.id===e);t&&nt?.selectView(t),re(1),Ge([]),ot({key:rt,views:ct,activeId:e})},ht=(t,n)=>{n&&n!==lt&&(re(1),Ge([]));let r=t.find(e=>e.id===(n??lt));r&&nt?.selectView(r),ot({key:rt,views:t,activeId:n??lt}),Ro(e,U,{metadata:{...tt?.metadata??{},views:t}},W).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},gt=Qe===`canvas`&&typeof Ze?.querySpec?.query==`string`?Ze.querySpec.query:``,vt=Qe===`canvas`?{label:Ze?.label,description:Ze?.description,color:Ze?.color}:null,{isPinned:bt,pin:xt,unpin:St,pins:Ct}=ZT(),wt=c?.name,Tt=(0,X.useMemo)(()=>wt&&Qe===`canvas`&&!Fe?{workspaceName:wt,treeName:W,path:U}:null,[wt,Qe,Fe,W,U]),Et=Tt?bt(Tt):!1,Ot=Ze?.id,kt=Ze?.label,At=(0,X.useCallback)(async()=>{if(Tt)try{let e=Ct.find(e=>e.workspaceName===Tt.workspaceName&&e.treeName===Tt.treeName&&e.path===Tt.path);e?await St(e.id):await xt({...Tt,layerId:Ot,label:kt})}catch(e){console.error(`Failed to update home pins:`,e)}},[Tt,Ct,xt,St,Ot,kt]),jt=e?`${e}://${U===`/`?``:U.replace(/^\//,``)}`:``,Mt=Jt(c?.color)||null;(0,X.useEffect)(()=>(fe(Mt),()=>fe(null)),[Mt,fe]);let Nt=(0,X.useCallback)(async t=>{let n=be;if(t?.anyOf?.length&&he.length&&(n=((await Yo(e,U,W,{limit:0,anyOf:he,ids:be,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await Yo(e,U,W,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...me,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:he,noneOf:ge,filters:xe,ids:n,queries:[...z,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,U,W,Se,z]);(0,X.useEffect)(()=>{e&&(async()=>{d(!0);try{let t=await J.get(`${no.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,l(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;i({title:`Error`,description:n,variant:`destructive`}),l(null)}finally{d(!1)}})()},[e,i]),(0,X.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&l(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let Pt=(be?.length??0)>0&&!Fe&&!(Oe&&De)&&z.length<=1,{documents:Ft,count:It,ready:Lt,setCue:Rt,resync:zt,rank:Bt}=aE({workspaceRef:e,specs:(0,X.useMemo)(()=>{let e={features:{allOf:pt,anyOf:he,noneOf:ge},filters:xe};return C!==`workspace`&&(Ls(W)===`directory`?e.directory={tree:W,path:U}:e.context=U),[{label:`scope`,spec:e}]},[Ce,U,W,C,dt]),opts:(0,X.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:Pt}),Vt=Pt&&Lt,Ht=(0,X.useRef)(!1);(0,X.useEffect)(()=>{Ht.current=Vt},[Vt]);let Ut=z.length===1?z[0].trim():``;(0,X.useEffect)(()=>{Lt&&Bt(Ut?{text:Ut}:null,{limit:ie,offset:(ne-1)*ie}).catch(()=>{})},[Lt,Ut,ie,ne,Bt]);let Wt=(be??[]).join(`,`);(0,X.useEffect)(()=>{Lt&&Rt(`lens`,{ids:be??[]}).catch(()=>{})},[Lt,Wt,Rt,be]);let Gt=Vt?Ft:f,Kt=Vt?It:g,qt=(0,X.useRef)(new Set);(0,X.useEffect)(()=>{qt.current=new Set(Gt.map(e=>Number(e.id)))},[Gt]);let Yt=V.geoSelection;(0,X.useEffect)(()=>{pe(Gt,c?.name??null)},[Gt,c?.name,pe]),(0,X.useEffect)(()=>()=>pe([]),[pe]);let Xt=(0,X.useMemo)(()=>Yt?Gt.filter(e=>Pe(e,Yt,V.filters.geo.includeUnlocated)):Gt,[Gt,Yt,V.filters.geo.includeUnlocated]),Zt=Gs(U,pt,{treeName:W,treeType:Ls(W),scope:C,queries:z,anyOf:he,noneOf:ge,filters:xe,ids:be,layerId:Fe&&Ie?Ie:void 0}),Qt=JSON.stringify([e,Zt]),[$t,en]=(0,X.useState)(``),[tn,nn]=(0,X.useState)(!1),rn=(0,X.useRef)(!1),on=m||tn||$t!==Qt||Vt||!!Yt,sn=(0,X.useRef)(0),cn=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{sn.current++,cn.current=null},[]);let ln=(0,X.useRef)(``),un=(0,X.useCallback)(async t=>{if(!e)return;if(_t(W,U)){sn.current++,cn.current=null,ln.current=``,p([]),_(0),h(!1);return}if(Ht.current)return;let n=`${Oe&&De?`${C}:unfiled`:C}:${dt??``}`,r=(be?.length??0)>0,a=hE(e,W,U,ne,ie,z.join(`␟`),Ce,Fe&&Ie?Ie:``,n),o=r&&a===ln.current;ln.current=a;let s=hE(e,W,U,ne,ie,z.join(`␟`),Se,Fe&&Ie?Ie:``,n),c=`${s}\0${v}`;if(t?.silent&&cn.current?.key===c){cn.current.refreshPending=!0;return}let l=++sn.current,u=t?.silent||r||v?void 0:pE.get(s);u&&(p(u.documents),_(u.totalCount),en(Qt),h(!1)),(t?.silent??(o||!!u))||h(!0);let d={key:c,refreshPending:!1};cn.current=d;try{let t;t=Oe&&De?await Bc(e,De.driver,De.address,{linked:!1,limit:ie,offset:(ne-1)*ie}):Fe&&Ie&&C!==`workspace`?await pc(e,W,Ie,{limit:ie,page:ne,queries:z,allOf:pt,anyOf:he,noneOf:ge,filters:xe,ids:be,sortBy:H.sortBy||void 0,order:H.order}):await Fs(e,U,pt,{limit:ie,page:ne,treeName:W,treeType:W===`directory`||W===`backends`?`directory`:`context`,queries:z,anyOf:he,noneOf:ge,filters:xe,ids:be,sortBy:H.sortBy||void 0,order:H.order,scope:C,debug:v&&z.length>0,debugLimit:200});let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&pE.set(s,{documents:n,totalCount:i}),l!==sn.current)return;let a=t.debug,c=a?.imageDistances??a?.distances??null;b(c?{query:z[z.length-1]??``,distances:c}:null),p(o?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),_(i),en(Qt)}catch(e){if(l!==sn.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),p([]),_(0)}finally{cn.current===d&&(cn.current=null),l===sn.current&&h(!1),l===sn.current&&d.refreshPending&&un({silent:!0})}},[e,U,W,Ie,Fe,ne,ie,c?.status,z,Se,C,Oe,v,dt]);(0,X.useEffect)(()=>{un()},[un]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Be({treeName:n.treeName||`context`,path:nf(n.path||`/`)}),Ue(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,W,U]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&vE(e,n),YT(JT(n),{tree:W,kind:Ls(W),path:U,wholeWorkspace:C===`workspace`}))){if(e&&gE(e,W,U),Ht.current){zt();return}un({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[un,e,U,W,C,zt]);let dn=c?.name,fn=c?.id;(0,X.useEffect)(()=>{if(!e||!dn&&!fn)return;let t=[dn,fn].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>B.emit(`subscribe`,{channel:e}));n();let r=B.on(`connect`,n),i=new Map,a=!1,o=()=>{us(e).then(e=>{a||(i=WT(e))}).catch(()=>{})};o();let s=null,c=0,l=!1,u=null,d=()=>{if(s=null,c=Date.now(),u){let{treeName:t,path:n}=u;u=null,window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}if(l){if(l=!1,Ht.current){zt();return}un({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=GT(t,n,i);_E(e,r);let a={tree:W,kind:Ls(W),path:U,wholeWorkspace:C===`workspace`},f=Ve.current;f&&YT(r,{tree:f.treeName,kind:Ls(f.treeName),path:f.path})&&(u=f),YT(r,a,qt.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.inserted.batch`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>B.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>B.off(e,t))}},[e,fn,dn,W,U,C,un,zt]);let pn=`${U}\0${W}\0${Ie??``}\0${C}`,[mn,hn]=(0,X.useState)(pn);mn!==pn&&(hn(pn),re(1),ce(null));let gn=`${U}\0${W}\0${Ie??``}`,[_n,yn]=(0,X.useState)(gn);_n!==gn&&(yn(gn),w(`path`));let xn=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;M(n),A({parentPath:e,captureView:t})},Sn=o.get(`createCanvas`)===`1`,[Cn,wn]=(0,X.useState)(!1);Cn!==Sn&&(wn(Sn),Sn&&xn(U,!1)),(0,X.useEffect)(()=>{if(!Sn)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[Sn,U]);let Tn=(0,X.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let i=t.toString();r(`${n.pathname}${i?`?${i}`:``}${n.hash}`)},[n.pathname,n.search,n.hash,r]),Dn=JSON.stringify([o.has(`q`),...s]),[On,kn]=(0,X.useState)(Dn);On!==Dn&&(kn(Dn),oe(s),re(1));let An=`${Dn}\0${Qe??``}\0${gt}\0${U}\0${se??``}`,[jn,Mn]=(0,X.useState)(An);jn!==An&&(Mn(An),o.has(`q`)||s.length>0||Qe!==`canvas`||se===U||(oe(gt?[gt]:[]),re(1)));let Nn=(0,X.useCallback)(e=>{let t=e.trim();t&&(ce(null),oe(e=>{if(e.includes(t))return e;let n=[...e,t];return Tn(n),re(1),n}))},[Tn,ce,oe,re]),Pn=(0,X.useCallback)(e=>{oe(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&ce(U),Tn(n),re(1),n})},[Tn,U,ce,oe,re]),Fn=z.join(` `).trim(),In=!!V.activeContextType&&(V.isDirty||Fn!==(Qe===`canvas`?gt:V.savedSearchQuery||``));!e&&Le!==null&&Re(null),(0,X.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&Ms(e,W),_c(e,W).then(i=>{!t&&a===n&&(r=!0,$e.current=`${e}/${W}`,Re(i))}).catch(()=>{!t&&a===n&&!r&&Re(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==W||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=Dt(e,fn);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,W,fn]),!(e&&Qe===`canvas`&&!Fe)&&L!==null&&R(null),(0,X.useEffect)(()=>{let t=!1;if(!(!e||Qe!==`canvas`||Fe))return ds(e,U,W).then(e=>{t||R(e)}).catch(()=>{t||R(null)}),()=>{t=!0}},[e,U,W,Qe,Fe]);let Ln=async()=>{if(c){E(!0);try{let t=await Ks(e||c.id);l(t),i({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;i({title:`Error`,description:t,variant:`destructive`})}finally{E(!1)}}},Rn=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`Document from "${U}"`});try{await Ao(e||c.id,[t],U,[],W,Kn,{trashIfOrphaned:!0}),gE(e||c.id,W,U),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document removed from workspace path.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},zn=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`Document from "${U}"`});try{await Bo(e||c.id,[t],U,[],W,Kn),gE(e||c.id,W,U),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Bn=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`${t.length} document(s) from "${U}"`});try{await Ao(e||c.id,t,U,[],W,Kn,{trashIfOrphaned:!0}),gE(e||c.id,W,U),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Vn=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`${t.length} document(s)`});try{await Bo(e||c.id,t,U,[],W,Kn),gE(e||c.id,W,U),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Hn=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await tc(e||c.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},Un=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await tc(e||c.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);p(e=>e.filter(e=>!i.has(e.id))),_(e=>Math.max(0,e-i.size));let a=[r.successful?.length?`${r.successful.length} destroyed`:null,r.failed?.length?`${r.failed.length} failed`:null].filter(Boolean).join(`, `);r.failed?.length?n.fail({title:`Destroy incomplete`,description:a,variant:`destructive`}):n.done({title:`Destroyed`,description:a||`No documents destroyed`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},Wn=e=>{O({documentIds:e,operation:`copy`,sourcePath:U,sourceTreeName:W}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Gn=e=>{O({documentIds:e,operation:`cut`,sourcePath:U,sourceTreeName:W}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Kn=Ls(W),qn=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??W,o=r.targetTreeType??Kn,s=r.move??D?.operation===`cut`,c=a({title:s?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let a=await Ko(e,t,n,i,o);if(a){gE(e,i,t);let a=r.sourceTreeName||D?.sourceTreeName,o=r.sourcePath||D?.sourcePath;if((r.move??D?.operation===`cut`)&&o&&a){let t=Ls(a);await Ao(e,n,o,[],a,t),gE(e,a,o),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:o,treeName:a}}))}c.done({title:`Success`,description:`${n.length} document(s) ${s?`moved`:`pasted`} to "${t}"`}),O(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await un(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else c.done();return a}catch(e){return c.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Jn=async(t,n)=>{if(!e)return!1;try{let r=(await qs(e,n,t,W,Kn)).length>0;return r&&(an(e,W,n),i({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},Yn=async()=>{if(!c||Kt===0||on||rn.current||window.prompt(`Type PURGE to permanently delete all ${Kt} matching documents across all pages.`)!==`PURGE`)return;rn.current=!0,nn(!0);let t=a({title:`Purging…`,description:`${Kt} matching document(s)`});try{let n=await Ds(e||c.id,Zt,Kt);n.deleted===n.requested?t.done({title:`Success`,description:`${n.deleted} document(s) purged.`}):t.fail({title:`Purge incomplete`,description:`${n.deleted} of ${n.requested} document(s) purged. Refresh and review the remaining results before retrying.`})}catch(e){t.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}finally{gE(e||c.id,W,U),await un({silent:!0}),rn.current=!1,nn(!1)}},Xn=()=>xn(U,!0),Zn=async()=>{if(!(!e||!k||!j.trim())){P(!0);try{let t=j.trim(),n=k.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`,a={...V.filters,features:{...V.filters.features,allOf:pt}};await Ic(e,i,W,k.captureView?{metadata:{toolbox:a},querySpec:{features:a.features,filters:[...it(V.filters.timeline),...En(V.filters.geo)],query:Fn||void 0,sort:V.filters.sort?.sortBy?V.filters.sort:null}}:{}),A(null),Ms(e,W);try{let t=await _c(e,W,{force:!0});Re(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(of(e,i,W))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{P(!1)}}},Qn=async()=>{if(!(!e||Qe!==`canvas`)){F(!0);try{let t=L||await zc(e,U,W);R(t);let n=`${window.location.origin}${t.url}`;await navigator.clipboard?.writeText(n),i({title:`Public canvas link copied`,description:n})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to share canvas`,variant:`destructive`})}finally{F(!1)}}},$n=async()=>{if(L){F(!0);try{await Po(L.code),R(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:W}})),i({title:`Canvas unshared`,description:`The public link no longer works.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to unshare canvas`,variant:`destructive`})}finally{F(!1)}}},er=async()=>{if(!e||Qe!==`canvas`||U===`/`)return;let t=vt?.label||U.split(`/`).pop()||`canvas`,n=L?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){te(!0);try{if(L)await Po(L.code),R(null);else if(Ze?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await Us(e,U,!1,W);let n=U.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:W}})),r(of(e,a,W)),i({title:`Canvas deleted`,description:`"${t}" was removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete canvas`,variant:`destructive`})}finally{te(!1)}}},tr=(0,X.useCallback)(async t=>{if(!e||!ze)return;let n={treeName:W,path:U},r=He===`left`?n:ze,o=He===`left`?ze:n,s=He===`left`?We:Ye;if(s.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let c=Ls(o.treeName),l=a({title:t?`Moving…`:`Copying…`,description:`${s.length} document(s) → "${o.path}"`});try{if(!await Ko(e,o.path,s,o.treeName,c)){l.done();return}if(gE(e,o.treeName,o.path),t){let t=Ls(r.treeName);await Ao(e,s,r.path,[],r.treeName,t),gE(e,r.treeName,r.path)}[r,o].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),l.done({title:t?`Moved`:`Copied`,description:`${s.length} document(s) → "${o.path}"`})}catch(e){l.fail({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,ze,He,W,U,We,Ye,i,a]);if((0,X.useEffect)(()=>{if(!ze)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),tr(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[ze,tr]),u)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!c)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let nr=Qe===`canvas`&&!Fe&&!!Ze,rr=!nr&&!we&&tt?(0,Z.jsx)(NT,{views:ct,activeId:lt,onSelect:mt,onSave:ht,accentColor:Jt(c.color),onOpenToSide:e=>{Be({treeName:W,path:U,viewId:e}),Ue(`right`)}}):void 0,ir=De||c.status!==`active`?(0,Z.jsxs)(Z.Fragment,{children:[De&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{Ae(!Oe),re(1)},"aria-pressed":Oe,className:K(`min-h-10 rounded-md border px-2 text-xs`,Oe&&`bg-warning/15 text-warning`),children:`Unfiled only`}),c.status!==`active`&&(0,Z.jsx)(`button`,{type:`button`,onClick:Ln,disabled:T,className:`min-h-10 rounded-md border px-2 text-xs`,children:T?`Starting…`:`Start`})]}):void 0,ar=_t(W,U)?U===`/Trash`?(0,Z.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,Z.jsx)(Qw,{workspaceName:e||c.id})}):(0,Z.jsx)(Jw,{workspace:e||c.id,path:U,onNavigate:t=>r(of(e,t,`backends`))},e):(0,Z.jsx)(ET,{navigationTabs:rr,navigationActions:ir,onBack:Je,accentColor:Jt(c.color),urlType:Fe?Ls(W)===`directory`?`${W}-layer`:`context-layer`:Qe===`canvas`?`canvas`:Ls(W)===`directory`?W:`context`,urlDisplay:jt,contextPath:U,treeName:W,workspaceId:e||c.id,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,documentSchema:dt,documents:Xt,isLoading:m,totalCount:Kt,currentPage:ne,pageSize:ie,onPageChange:re,onPageSizeChange:e=>{ae(e),re(1)},onRemoveDocument:U===`/`?void 0:Rn,onDeleteDocument:zn,onDestroyDocument:Hn,onRemoveDocuments:U===`/`?void 0:Bn,onDeleteDocuments:Vn,onDestroyDocuments:Un,onCopyDocuments:Wn,onCutDocuments:Gn,onPasteDocuments:we?void 0:qn,onImportDocuments:we?void 0:Jn,onSelectionChange:Ge,onBrowseTree:()=>G(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>Ke(`workspaces`),onNavigatePath:t=>r(of(e,t,W)),folders:et,onOpenFolder:t=>r(of(e,nf(t),W)),scope:C,onScopeChange:w,pastedDocumentIds:D?.documentIds,linkTree:Le,onPurgeDocuments:we?void 0:Yn,disablePurgeDocuments:on,canvasInfo:vt??void 0,isCanvasPinned:Et,onTogglePinCanvas:Tt?At:void 0,onSaveAsCanvas:Le&&Qe!==`canvas`&&!Fe&&!we?Xn:void 0,onShareCanvas:Qe===`canvas`&&!Fe?Qn:void 0,onUnshareCanvas:L?$n:void 0,onDeleteCanvas:Qe===`canvas`&&!Fe?er:void 0,isSharingCanvas:ee,isDeletingCanvas:I,isCanvasShared:!!L,isCanvasLocked:!!Ze?.locked,backendSearchQueries:z,onBackendSearch:Nn,serverSort:V.filters.sort,onServerSortChange:de,onRemoveBackendQuery:Pn,canSaveChanges:In,isSavingChanges:V.isSaving,onSaveChanges:ue,contentBanner:v&&y?(0,Z.jsx)(dE,{data:y,className:`mb-3`}):null,children:nr&&Ze?(0,Z.jsx)(kf,{workspaceId:e||c.id,treeName:W,path:U,layerId:Ze.id,querySpec:Ze.querySpec,metadata:Ze.metadata,isLocked:!!Ze.locked,fetchDocuments:V.isDirty?Nt:void 0}):!we&&ut.kind===`columns`?(0,Z.jsx)(zT,{documents:Xt,workspaceId:e||c.id,columns:ut.columns??[],onColumnsChange:e=>ht(ct.map(t=>t.id===ut.id?{...t,columns:e}:t))}):!we&&ut.kind===`app`&&ut.app&&ut.app!==`notes`?(0,Z.jsx)(IT,{app:ut.app,workspaceId:e||c.id,treeName:W,path:U}):null});return(0,Z.jsxs)(Hw,{workspaceId:e||c.id,treeName:W,path:U,headerOnly:!0,className:`relative flex flex-col h-full min-h-0`,children:[(0,Z.jsx)(tT,{workspaceId:c.id,workspaceName:c.label||c.name},c.id),_t(W,U)&&(0,Z.jsx)(qe,{workspace:c.label||c.name,workspaceIcon:c.icon,tree:W,path:U,onBack:Je,onBrowseTree:()=>G(`workspaces`,`detail`,e||c.id),onBrowseWorkspaces:()=>Ke(`workspaces`),onNavigatePath:t=>r(of(e,t,W)),accentColor:Jt(c.color)}),k&&(0,Z.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,Z.jsx)(pw,{title:`New canvas`,onClose:()=>A(null),children:(0,Z.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Zn()},className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,Z.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:j,onChange:e=>M(e.target.value),onKeyDown:e=>{e.key===`Escape`&&A(null)},autoFocus:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,Z.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:k.parentPath===`/`?`/`:k.parentPath})]})]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:k.captureView,onChange:e=>A({...k,captureView:e.target.checked})}),(0,Z.jsxs)(`span`,{children:[`Capture the current view`,(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:!j.trim()||N,children:N?`Creating…`:`Create canvas`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})})}),(0,Z.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,Z.jsx)(`div`,{"data-canvas-pane":!0,className:K(`flex-1 min-w-0 bg-background overflow-hidden`,ze&&(He===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||Ue(`left`)},children:ar}),ze&&e&&(0,Z.jsx)(SE,{workspaceName:e,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,pane:ze,isFocused:He===`right`,clipboard:D,setClipboard:O,onFocus:()=>Ue(`right`),onSelectionChange:Xe,onNavigate:e=>Be(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Be(null),Ue(`left`),Xe([])}})]})]})}function xE(e,t){if(!e||t===`/`)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)return null;return n}function SE({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:u}){let{openM1Drawer:d,openM2Drawer:f}=qC(),{showToast:p,showProgress:m}=wo(),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)([]),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(0),[C,w]=(0,X.useState)(1),[T,E]=(0,X.useState)(50),D=Ls(r.treeName),O=xE(h,r.path),k=O?.type===`canvas`,A=(0,X.useMemo)(()=>D===`directory`?fE(h,r.path):[],[h,r.path,D]),j=r.viewId?jT(O?.metadata).find(e=>e.id===r.viewId)??null:null,M=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,N=OT(j),P=(0,X.useCallback)(async()=>{if(_t(r.treeName,r.path)){v([]),S(0),b(!1);return}let t=hE(e,r.treeName,r.path,C,T,``,N??``),n=pE.get(t);if(n){v(n.documents),S(n.totalCount);return}b(!0);try{let n=await Fs(e,r.path,N?[N]:[],{limit:T,page:C,treeName:r.treeName,treeType:D}),i=n.payload||[],a=n.totalCount||n.count||0;v(i),S(a),pE.set(t,{documents:i,totalCount:a})}catch(e){p({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),v([]),S(0)}finally{b(!1)}},[e,r.path,r.treeName,D,T,C,p,N]);(0,X.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&Ms(e,r.treeName),_c(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,g(e))}).catch(()=>{!t&&o===n&&!i&&g(null)})};a(!1);let o=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==r.treeName||a(!n?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{t=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,r.treeName]),(0,X.useEffect)(()=>{P()},[P]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(vE(e,n),YT(JT(n),{tree:r.treeName,kind:Ls(r.treeName),path:r.path})&&(gE(e,r.treeName,r.path),P()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[P,e,r.treeName,r.path]);let ee=(0,X.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??D,l=i.move??a?.operation===`cut`,u=m({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await Ko(e,t,n,s,c);if(r){gE(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=Ls(c);await Ao(e,n,r,[],c,t),gE(e,c,r),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:r,treeName:c}}))}u.done({title:`Success`,description:`${n.length} document(s) ${l?`moved`:`pasted`} to "${t}"`}),o(null),await P(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:s}}))}else u.done();return r}catch(e){return u.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,r.treeName,D,P,m,a,o]),F=(0,X.useCallback)(()=>{gE(e,r.treeName,r.path),P()},[e,r.treeName,r.path,P]),I=(0,X.useCallback)(async t=>{let n=m({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await Ao(e,t,r.path,[],r.treeName,D),F(),n.done({title:`Removed`,description:`${t.length} document(s) removed from "${r.path}"`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,F,m]),te=(0,X.useCallback)(async t=>{let n=m({title:`Deleting…`,description:`${t.length} document(s)`});try{await Bo(e,t,r.path,[],r.treeName,D),F(),n.done({title:`Deleted`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,F,m]),L=(0,X.useCallback)(async t=>{let n=m({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await tc(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}F();let i=`${r.successful?.length??0} document(s) destroyed${r.failed?.length?` · ${r.failed.length} failed`:``}.`;r.failed?.length?n.fail({title:`Destroy incomplete`,description:i,variant:`destructive`}):n.done({title:`Destroyed`,description:i})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,F,m]);return(0,Z.jsxs)(`div`,{className:K(`relative flex-1 min-w-0 rounded-(--sheet-radius) border bg-background overflow-hidden`,i?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||s()},children:[u&&(0,Z.jsx)(`button`,{type:`button`,onClick:u,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),_t(r.treeName,r.path)?r.path===`/Trash`?(0,Z.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,Z.jsx)(Qw,{workspaceName:e})}):(0,Z.jsx)(Jw,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,Z.jsx)(ET,{frameContent:!1,onBrowseWorkspaces:()=>d(`workspaces`),onBrowseTree:()=>f(`workspaces`,`detail`,e),urlType:k?`canvas`:D===`directory`?r.treeName:`context`,urlDisplay:M,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:N,documents:_,isLoading:y,totalCount:x,currentPage:C,pageSize:T,onPageChange:w,onPageSizeChange:e=>{E(e),w(1)},onRemoveDocument:r.path===`/`?void 0:e=>I([e]),onRemoveDocuments:r.path===`/`?void 0:I,onDeleteDocument:e=>te([e]),onDeleteDocuments:te,onDestroyDocument:e=>L([e]),onDestroyDocuments:L,onCopyDocuments:e=>{o({documentIds:e,operation:`copy`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{o({documentIds:e,operation:`cut`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:r.treeName===`backends`?void 0:ee,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:h,folders:A,onOpenFolder:l,onNavigatePath:l,canvasInfo:k?{label:O?.label,description:O?.description,color:O?.color}:void 0,children:j?.kind===`columns`?(0,Z.jsx)(zT,{documents:_,workspaceId:e,columns:j.columns??[],onColumnsChange:()=>{},readOnly:!0}):j?.kind===`app`&&j.app&&j.app!==`notes`?(0,Z.jsx)(IT,{app:j.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}function CE(e){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{if(!e)return;let t=!1,r=()=>{Ws(e).then(r=>{t||n({ref:e,workspace:r})}).catch(()=>{})};return r(),window.addEventListener(`workspaces:refresh`,r),()=>{t=!0,window.removeEventListener(`workspaces:refresh`,r)}},[e]),t?.ref===e?t?.workspace:void 0}function wE(){let{workspaceName:e}=yt();return e?(0,Z.jsx)(eT,{workspaceName:e,children:(0,Z.jsx)(TE,{})}):(0,Z.jsx)(`p`,{role:`alert`,className:`p-6`,children:`Workspace not specified.`})}function TE(){let{workspaceName:e=``,documentId:t=``,algo:n=``,checksum:r=``}=yt(),i=ft(),a=vn(),{goBack:o,openM1Drawer:s,openM2Drawer:c}=qC(),l=CE(e),u=!!n&&!!r,d=u?`${n}/${r}`:t,f=JSON.stringify([e,t,n,r]),p=Number(t),m=/^\d+$/.test(t)&&Number.isSafeInteger(p)&&p>0,h=u||m,[g,_]=(0,X.useState)(0),[v,y]=(0,X.useState)(null),b=v?.identity===f?v:null,x=h&&(!b||b.revision!==g);(0,X.useEffect)(()=>{let t=!1;if(h)return(u?Qs(e,n,r):xc(e,p)).then(e=>{t||y({identity:f,revision:g,document:e||null,missing:!e,error:``})}).catch(e=>{t||y({identity:f,revision:g,document:null,missing:e?.statusCode===404,error:e instanceof Error?e.message:`Unable to retrieve this document.`})}),()=>{t=!0}},[e,p,f,g,h,u,n,r]);let S={workspace:l?.label||e,workspaceIcon:l?.icon,path:`/`,tree:`context`,document:b?.document?Ho(b.document).title:`Document ${d}`,onBack:o,onBrowseWorkspaces:()=>s(`workspaces`),onBrowseTree:()=>c(`workspaces`,`detail`,e),onNavigatePath:t=>i(of(e,t,`context`))},C=a.hash.slice(1),w=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`].includes(C)?C:`view`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[!b?.document&&(0,Z.jsx)(qe,{...S}),b?.document?(0,Z.jsx)(Tn,{document:b.document,workspaceId:e,onChanged:()=>_(e=>e+1),navigation:S,initialTab:w,onTabChange:e=>i(`${a.pathname}${a.search}#${e}`,{replace:!0}),tabActions:(0,Z.jsx)(Y,{variant:`ghost`,disabled:x,onClick:()=>_(e=>e+1),children:`Refresh`})},f):x?(0,Z.jsx)(`p`,{role:`status`,className:`p-6 text-sm text-muted-foreground`,children:`Loading document…`}):(0,Z.jsxs)(`div`,{role:`alert`,className:`space-y-2 p-6 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:b?.missing?`Document ${d} not found`:`Unable to load document`}),h&&(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>_(e=>e+1),children:`Retry`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:h?b?.missing?`This record is no longer available in this workspace. Subtree exports skip missing records and report their IDs.`:b?.error:`Document ID must be a positive integer.`})]})]})}function EE(e){let t=new URLSearchParams;return e?.mode===`context`&&t.set(`context`,e.contextId),e?.mode===`workspace`&&(t.set(`workspace`,e.workspaceName),t.set(`path`,e.path),t.set(`tree`,e.treeName)),t}var DE={id:`sketch`,label:`Sketch`,icon:pr,schemas:[Hc],canCreate:!0,canEdit:e=>e.schema===Hc,createUrl(e){let t=EE(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=EE(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},OE=[{kind:`message`,label:`New Message`,icon:ki},{kind:`note`,label:`Note`,icon:Da},{kind:`link`,label:`Link`,icon:Ui},{kind:`todo`,label:`Todo`,icon:pa},{kind:`identity`,label:`Identity`,icon:Hr},{kind:`sketch`,label:`Sketch`,icon:pr},{kind:`plaintext`,label:`Plaintext file`,icon:Ki},{kind:`file`,label:`File`,icon:Yr},{kind:`photo`,label:`Photo/Video`,icon:Ur},{kind:`existing`,label:`Existing document`,icon:ua},{kind:`folder`,label:`Folder`,icon:ni}];function kE(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?OE:OE.filter(e=>e.kind!==`photo`)}function AE({onSelect:e,variant:t=`list`,omit:n}){let r=kE().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,Z.jsx)(Z.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex items-center gap-2 rounded-full bg-card px-3 py-1.5 text-sm font-medium shadow-elevation-3 transition-transform hover:scale-105`,children:[n,(0,Z.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,Z.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}function jE({onClose:e,initialData:t,draftId:n}){let r=ux(void 0,void 0,`home-card:${n}`);return(0,X.useEffect)(()=>{t?.title&&r.setTitle(t.title),t?.content&&r.setContent(t.content)},[]),(0,Z.jsx)(Xe,{title:`New Note`,icon:Da,onClose:e,onSave:async e=>{let t=await r.save({mode:`workspace`,...e});return r.finish(),t},canSave:r.canSave,saving:r.saving,successMessage:`Note created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`qa-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-note-title`,value:r.title,onChange:e=>r.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(G,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(Zc,{kind:`markdown`,value:r.content,onChange:r.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:r.tags,onChange:r.setTags})]}),(0,Z.jsx)($c,{...r,onRetry:r.retry}),(0,Z.jsx)(fT,{geotag:r.geotag,idPrefix:`qa-note-geotag`})]})})}var ME=`data/schema/tab`,NE=`2.0`;function PE(e){try{return new URL(e),!0}catch{return!1}}function FE(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),c=Ce(),l=e.trim(),u=PE(l),d=l.length>0&&!u,f=u&&!o;async function p(e){if(!u)throw Error(`Enter a valid URL`);s(!0);try{let t=await c.capture(),r=i.map(e=>e.trim()).filter(Boolean),a={schema:ME,schemaVersion:NE,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:Qc(i),...t?{geo:t}:{}}};return await wl(e,[a])}finally{s(!1)}}return{url:e,setUrl:t,title:n,setTitle:r,tags:i,setTags:a,saving:o,canSave:f,urlValid:u,showUrlError:d,save:p,geotag:c}}function IE({onClose:e,initialData:t}){let n=FE();return(0,X.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,Z.jsx)(Xe,{title:`New Link`,icon:Ui,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`qa-link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`qa-link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(fT,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function LE({onClose:e,initialData:t}){let n=ve();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,Z.jsx)(Xe,{title:`New Todo`,icon:pa,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(Oe,{...n,idPrefix:`qa-todo`}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`qa-todo-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(fT,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function RE({onClose:e,initialData:t}){let n=pe();return(0,X.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,Z.jsx)(Xe,{title:`New Identity`,icon:Hr,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(oe,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`qa-identity-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]})]})})}var zE={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,heic:`image/heic`,heif:`image/heif`,bmp:`image/bmp`,tif:`image/tiff`,tiff:`image/tiff`,svg:`image/svg+xml`,mp4:`video/mp4`,mov:`video/quicktime`,webm:`video/webm`,"3gp":`video/3gpp`};function BE(e){return/^(image|video)\//.test(e.type)}async function VE(e){let t=await Promise.all(e.map(async e=>{let t=new Uint8Array(await e.slice(0,64).arrayBuffer()),n=(e,n)=>String.fromCharCode(...t.slice(e,e+n)),r=``;if(t[0]===255&&t[1]===216&&t[2]===255)r=`image/jpeg`;else if(n(0,8)===`PNG\r
|
|
24
|
+
|
|
25
|
+
`)r=`image/png`;else if([`GIF87a`,`GIF89a`].includes(n(0,6)))r=`image/gif`;else if(n(0,4)===`RIFF`&&n(8,4)===`WEBP`)r=`image/webp`;else if(n(0,5)===`%PDF-`)r=`application/pdf`;else if(n(0,4)===`PK`)r=`application/zip`;else if(n(4,4)===`ftyp`){let e=[n(8,4)],i=new DataView(t.buffer).getUint32(0);for(let r=16;r+4<=Math.min(t.length,i);r+=4)e.push(n(r,4));e.some(e=>[`avif`,`avis`].includes(e))?r=`image/avif`:e.some(e=>[`heic`,`heix`,`hevc`,`hevx`].includes(e))?r=`image/heic`:e.some(e=>[`mif1`,`msf1`].includes(e))?r=`image/heif`:e.includes(`qt `)?r=`video/quicktime`:e.some(e=>[`isom`,`iso2`,`mp41`,`mp42`,`avc1`,`M4V `].includes(e))&&(r=`video/mp4`)}let i=e.type.toLowerCase().split(`;`)[0].trim(),a=!i||[`application/octet-stream`,`binary/octet-stream`,`*/*`].includes(i),o=e.name.split(`.`).pop()?.toLowerCase()??``,s=r||a&&zE[o]||i;return s===e.type?e:new File([e],e.name,{type:s,lastModified:e.lastModified})}));return{kind:t.length>0&&t.every(BE)?`photo`:`file`,files:t}}function HE({file:e}){let t=(0,X.useRef)(null),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let n=t.current;if(!n)return;let r=URL.createObjectURL(e);return n.src=r,()=>{n.removeAttribute(`src`),URL.revokeObjectURL(r)}},[e]),(0,Z.jsx)(`div`,{className:`flex min-h-24 items-center justify-center overflow-hidden rounded-md border border-input bg-muted/30`,children:n?(0,Z.jsxs)(`p`,{className:`p-4 text-center text-sm text-muted-foreground`,children:[`Preview unavailable for `,e.name,`. You can still save the original.`]}):e.type.startsWith(`video/`)?(0,Z.jsx)(`video`,{ref:t,controls:!0,preload:`metadata`,"aria-label":e.name,onError:()=>r(!0),className:`max-h-64 max-w-full`}):(0,Z.jsx)(`img`,{ref:t,alt:e.name,onError:()=>r(!0),className:`max-h-64 max-w-full object-contain`})})}function UE({onClose:e,initialData:t}){let n=(0,X.useRef)(null),r=_T(t?.files),i=r.items.map(e=>e.file),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(!1),{state:l}=ol(),u=lT(l.activeWorkspaceName),d=e=>{e&&(s||r.addFiles(Array.from(e)))},f=e=>{e.preventDefault(),o(!1),d(e.dataTransfer.files)},p=i.length>0;return(0,Z.jsx)(Xe,{title:`Upload File`,icon:Yr,onClose:e,onSave:async e=>{c(!0);try{let t={mode:`workspace`,...e},n=await u.geotag.capture(),i=await r.start(t,(e,t)=>uT(e,t,{tags:u.tags,comment:u.comment,geo:n}));if(i.failed)throw Error(`${i.failed} file(s) failed or cancelled. Retry keeps completed uploads.`);return i.docIds}finally{c(!1)}},navigateAfterSave:!0,canSave:p,saving:s,saveProgress:(0,Z.jsx)(CT,{items:r.items,running:r.running,onCancel:r.cancel}),successMessage:`File(s) uploaded`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:f,onClick:()=>n.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,a?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(Yr,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`or click to browse`}),(0,Z.jsx)(`input`,{ref:n,type:`file`,multiple:!0,disabled:s,className:`hidden`,onChange:e=>{d(e.target.files),e.target.value=``}})]}),r.items.filter(e=>BE(e.file)).map(e=>(0,Z.jsx)(HE,{file:e.file},e.id)),(0,Z.jsx)(ST,{items:r.items,running:s,onRemove:r.removeItem}),(0,Z.jsx)(mT,{fields:u,idPrefix:`qa-file`,multiple:i.length>1})]})})}function WE({onClose:e,initialData:t}){let n=_T(t?.files),r=(0,X.useRef)(null),i=n.items.length>0,[a,o]=(0,X.useState)(!1),{state:s}=ol(),c=lT(s.activeWorkspaceName),l=e=>{!a&&e&&n.addFiles([e])};return(0,Z.jsx)(Xe,{title:`Photo/Video`,icon:Ur,onClose:e,onSave:async e=>{if(!i)return[];o(!0);try{let t=await c.geotag.capture(),r={mode:`workspace`,...e},i=await n.start(r,(e,n)=>uT(e,n,{tags:c.tags,comment:c.comment,geo:t}));if(i.failed)throw Error(`Upload failed or cancelled. You can retry.`);return i.docIds}finally{o(!1)}},navigateAfterSave:!0,canSave:i,saving:a,saveProgress:(0,Z.jsx)(CT,{items:n.items,running:n.running,onCancel:n.cancel}),successMessage:`Upload saved`,children:(0,Z.jsxs)(`div`,{className:K(`flex h-full flex-col gap-4 p-4`,!i&&`items-center justify-center`),children:[i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex min-h-0 w-full flex-1 flex-col gap-3 overflow-y-auto`,children:n.items.map(({id:e,file:t,status:r})=>(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(HE,{file:t}),(0,Z.jsxs)(`div`,{className:`flex w-full items-center gap-2 rounded border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(xa,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:t.name}),(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[(t.size/1024/1024).toFixed(1),` MB`]}),(0,Z.jsx)(`button`,{type:`button`,disabled:a||r===`done`,onClick:()=>n.removeItem(e),"aria-label":`Remove ${t.name}`,className:`text-muted-foreground hover:text-foreground disabled:opacity-40`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})]},e))}),(0,Z.jsx)(`div`,{className:`w-full shrink-0 space-y-4`,children:(0,Z.jsx)(mT,{fields:c,idPrefix:`qa-photo`,multiple:n.items.length>1})})]}):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r.current?.click(),className:`flex flex-col items-center gap-2 rounded-md border border-dashed border-input px-6 py-10 text-center transition-colors hover:bg-muted/40`,children:[(0,Z.jsx)(Ur,{className:`h-8 w-8 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm`,children:`Open camera`})]}),(0,Z.jsx)(`input`,{ref:r,type:`file`,accept:`image/*,video/*`,capture:`environment`,className:`hidden`,disabled:a,onChange:e=>{l(e.target.files?.[0]??null),e.target.value=``}})]})})}var GE=`shrink-0 h-viewport-card w-[min(380px,90vw)] max-md:fixed max-md:inset-2 max-md:z-40 max-md:h-auto max-md:w-auto max-md:shadow-elevation-5`;function KE({onClose:e}){let{showSuccessToast:t,showErrorToast:n}=Oo(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(!1);return r?(0,Z.jsx)(y,{sizeClassName:GE,documentCount:r.length,saving:a,onClose:e,onConfirm:async(i,a)=>{o(!0);try{await Promise.all(i.map(e=>Ko(a.workspaceName,e,r,a.treeName,a.treeType))),t(`${r.length} document${r.length===1?``:`s`} linked`),e()}catch(e){n(e instanceof Error?e.message:`Failed to link documents`)}finally{o(!1)}}}):(0,Z.jsx)(ae,{sizeClassName:GE,onConfirm:e=>{e.length&&i(e)},onClose:e})}function qE(){let e=el(`new:home-card:`);try{return Object.keys(localStorage).filter(t=>t.startsWith(e)&&t.endsWith(`:home`)).filter(e=>{let t=JSON.parse(localStorage.getItem(e)||`null`)?.value;return t&&(t.title||t.content||t.comment||t.tags?.length)}).map(t=>t.slice(e.length,-5))}catch{return[]}}var JE=0;function YE(){return JE+=1,`card-${JE}`}function XE({initialKind:e,initialData:t,onInitialCardClose:n,onCardsOpenChange:r}){let[i,a]=(0,X.useState)(!1),o=De(),s=ul(),c=!!(s?.state.t1Open||s?.state.addOpen),[l,u]=(0,X.useState)(()=>e?[{id:`initial`,kind:e,initialData:t,noteDraftId:crypto.randomUUID()}]:qE().map(e=>({id:e,kind:`note`,noteDraftId:e}))),d=l.length>0,f=(0,X.useRef)(r);(0,X.useEffect)(()=>{f.current=r},[r]),(0,X.useEffect)(()=>{f.current?.(d)},[d]),c&&i&&a(!1);let p=ft(),m=e=>{if(e===`sketch`){a(!1),p(DE.createUrl(null));return}let t=e===`note`?qE().find(e=>!l.some(t=>t.noteDraftId===e))||crypto.randomUUID():void 0;u(n=>[...n,{id:YE(),kind:e,noteDraftId:t}]),a(!1)},h=e=>{u(t=>t.filter(t=>t.id!==e)),e===`initial`&&n?.()},g=(0,Z.jsxs)(`div`,{className:K(`pointer-events-none fixed right-6 z-40 flex flex-col items-end gap-2`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`,l.length>0&&`max-md:hidden`,c&&`hidden`),children:[(0,Z.jsx)(`div`,{className:K(`flex flex-col items-end gap-2 transition-all duration-fast`,i?`pointer-events-auto opacity-100`:`pointer-events-none translate-y-2 opacity-0`),children:(0,Z.jsx)(AE,{variant:`stack`,omit:[`plaintext`,`folder`,`message`],onSelect:m})}),(0,Z.jsx)(`div`,{className:`pointer-events-none flex w-16 justify-center`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-label":i?`Close quick add`:`Quick add`,className:`pointer-events-auto flex h-11 w-11 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-elevation-3 transition-transform hover:scale-105`,children:i?(0,Z.jsx)(vr,{className:`h-5 w-5`}):(0,Z.jsx)(br,{className:`h-5 w-5`})})})]});return(0,Z.jsxs)(`div`,{className:`relative flex h-full w-full flex-col`,children:[l.length>0&&(0,Z.jsx)(`div`,{className:`pointer-events-auto flex flex-1 items-center gap-4 overflow-x-auto p-6 md:pr-28`,children:l.map(e=>{let t=()=>h(e.id);switch(e.kind){case`note`:return(0,Z.jsx)(jE,{draftId:e.noteDraftId,onClose:t,initialData:e.initialData},e.id);case`link`:return(0,Z.jsx)(IE,{onClose:t,initialData:e.initialData},e.id);case`todo`:return(0,Z.jsx)(LE,{onClose:t,initialData:e.initialData},e.id);case`identity`:return(0,Z.jsx)(RE,{onClose:t,initialData:e.initialData},e.id);case`file`:return(0,Z.jsx)(UE,{onClose:t,initialData:e.initialData},e.id);case`photo`:return(0,Z.jsx)(WE,{onClose:t,initialData:e.initialData},e.id);case`existing`:return(0,Z.jsx)(KE,{onClose:t},e.id);case`sketch`:return null;case`folder`:case`message`:return null}})}),o?(0,Hd.createPortal)(g,document.body):g]})}function ZE(e){let t=`${e.workspaceName}\0${e.treeName}\0${e.path}`,[n,r]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let n=!1;return ac(e.workspaceName,e.treeName).then(i=>{n||r({key:t,node:xs(i,e.path)})}).catch(()=>{n||r({key:t,node:null})}),()=>{n=!0}},[t,e.workspaceName,e.treeName,e.path]),!n||n.key!==t?{state:`loading`}:n.node?{state:`ready`,node:n.node}:{state:`missing`}}function QE(e){let t=`/workspaces/${encodeURIComponent(e.workspaceName)}`,n=e.path.replace(/^\//,``);return e.treeName===`context`?`${t}/path/${n}`:`${t}/trees/${encodeURIComponent(e.treeName)}/path/${n}`}var $E=`application/x-canvas-pin`;function eD({pin:e,onUnpin:t,onMinimize:n,onDropPin:r}){let i=ZE(e),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=!!r&&!a,u=e=>{let t=e.currentTarget.getBoundingClientRect();return e.clientX>t.left+t.width/2?`after`:`before`},d=l?{onDragOver:e=>{e.dataTransfer.types.includes(`application/x-canvas-pin`)&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,c(u(e)))},onDragLeave:()=>c(null),onDrop:t=>{let n=t.dataTransfer.getData($E);c(null),!(!n||n===e.id)&&(t.preventDefault(),r?.(n,u(t)===`after`))}}:{},f=i.state===`ready`?i.node:null,p=f?.label||e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`,m=f?.color;return(0,X.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]),(0,Z.jsxs)(`section`,{...d,className:a?`fixed inset-0 z-picker flex flex-col bg-background`:`flex flex-col rounded-(--card-radius) border bg-background overflow-hidden min-h-0 min-w-0 ${s?`ring-2 ring-primary/60`:``}`,children:[(0,Z.jsxs)(`header`,{draggable:l,onDragStart:l?t=>{t.dataTransfer.setData($E,e.id),t.dataTransfer.effectAllowed=`move`}:void 0,className:`flex items-center gap-2 px-3 py-2 border-b bg-muted/20 shrink-0 min-w-0 ${l?`cursor-grab active:cursor-grabbing`:``}`,children:[l&&(0,Z.jsx)(Un,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-hidden":!0}),m&&(0,Z.jsx)(`div`,{className:`w-1 h-5 rounded-full shrink-0`,style:{backgroundColor:m}}),(0,Z.jsx)(Pa,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:p}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono`,children:[e.workspaceName,`://`,e.path.replace(/^\//,``)]})]}),n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,title:`Minimize to tab bar`,"aria-label":`Minimize to tab bar`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(ii,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-pressed":a,title:a?`Restore tile (Esc)`:`Fill view area`,"aria-label":a?`Restore tile`:`Fill view area`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:a?(0,Z.jsx)(ei,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(ba,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(we,{to:QE(e),title:`Open in workspace`,"aria-label":`Open in workspace`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(Pi,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,title:`Unpin from home`,"aria-label":`Unpin from home`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Z.jsx)(ur,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0`,children:[i.state===`loading`&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}),i.state===`missing`&&(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 px-4 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This canvas is no longer available.`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`It may have been renamed, moved or deleted.`}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`mt-1 px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:`Remove pin`})]}),i.state===`ready`&&(0,Z.jsx)(kf,{workspaceId:e.workspaceName,treeName:e.treeName,path:e.path,layerId:i.node.id,querySpec:i.node.querySpec,metadata:i.node.metadata,readOnly:!0})]})]})}function tD(e,t,n){let r=Promise.resolve();return i=>{let a=r.then(async()=>{let r=await e(),a=i(r.home?.pinnedCanvases??[]);n(await t({...r,home:{...r.home,pinnedCanvases:a}}))});return r=a.catch(()=>{}),a}}function nD(e,t){return e.minimized===!0||t.has(e.id)}function rD(e){return e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`}function iD({pins:e,onRestore:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(e.length);return i!==e.length&&(a(e.length),e.length===0&&r(!1)),e.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute bottom-0 left-0 right-0 z-40 max-md:hidden`,children:(0,Z.jsx)(`div`,{className:`pointer-events-auto flex items-end gap-1 overflow-x-auto px-3 pr-28 pb-safe-bottom`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),title:`Restore ${rD(e)}`,className:`flex max-w-[180px] shrink-0 items-center gap-1.5 rounded-t-lg border border-b-0 bg-background px-3 py-1.5 text-xs shadow-elevation-1 hover:bg-accent`,children:[(0,Z.jsx)(Pa,{className:`h-3.5 w-3.5 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:rD(e)})]},e.id))})}),n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-drawer md:hidden`,onClick:()=>r(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed bottom-rail-stack left-2 z-rail w-60 max-w-[calc(100vw-1rem)] rounded-xl border bg-card p-1.5 shadow-elevation-5 animate-fade-in md:hidden touch-target`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm hover:bg-accent`,children:[(0,Z.jsx)(Pa,{className:`h-4 w-4 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:rD(e)})]},e.id))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),"aria-label":n?`Close minimized canvases`:`Minimized canvases (${e.length})`,className:`fixed bottom-rail-inset left-16 z-nav flex h-12 w-12 items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[(0,Z.jsx)(Pa,{className:`h-5 w-5`}),(0,Z.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold`,children:e.length})]})]})}function aD(){let{pins:e,unpin:t,movePin:n,setMinimized:r,isLoading:i}=ZT(),{showErrorToast:a}=Oo(),[o,s]=(0,X.useState)(new Set),c=(0,X.useRef)(e);(0,X.useEffect)(()=>{c.current=e},[e]);let l=e=>{r(e,!0).catch(()=>a(`Could not save minimized state`))},u=t=>{s(e=>{let n=new Set(e);return n.delete(t),n}),e.find(e=>e.id===t)?.minimized&&r(t,!1).catch(()=>a(`Could not save restored state`))},d=(0,X.useCallback)(e=>{s(e?new Set(c.current.filter(e=>!e.minimized).map(e=>e.id)):new Set)},[]),f=e.filter(e=>!nD(e,o)),p=e.filter(e=>nD(e,o)),m=(t,r,i)=>{let a=e.findIndex(e=>e.id===r.id);if(a===-1)return;let o=i?e[a+1]?.id??null:r.id;n(t,o)};return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto`,children:i?(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsx)(`div`,{className:`grid gap-4 p-4 h-full grid-cols-[repeat(auto-fit,minmax(min(640px,100%),1fr))] auto-rows-fr ${p.length>0?`md:pb-12`:``}`,children:f.map(e=>(0,Z.jsx)(eD,{pin:e,onUnpin:()=>{t(e.id)},onMinimize:()=>l(e.id),onDropPin:(t,n)=>m(t,e,n)},e.id))})}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,children:(0,Z.jsx)(XE,{onCardsOpenChange:d})}),(0,Z.jsx)(iD,{pins:p,onRestore:u})]})}function oD(){return(0,Z.jsx)(`div`,{className:`h-full w-full`,"aria-hidden":!0})}var sD=`share-target-inbox`,cD={"too-large":`Android shares are limited to 100 MiB in total for temporary device storage. Nothing was uploaded. Use Add File to upload larger files directly.`,"stash-failed":`Canvas couldn't hold on to the shared file — device storage may be full. Try again, or upload it from the app.`,"empty-share":`Canvas received no files or text from the sharing app. Try again, or use Add File to select the photo directly.`,"empty-file":`The sharing app delivered an empty file. Try again, or use Add File to select the original directly.`,expired:`Nothing shared, or the share expired.`};async function lD(e){let t=await caches.open(sD),n=null,r=Date.now()+3e5;for(;Date.now()<r;){let r=await t.match(`/share-target-inbox/${e}/meta`);if(!r)return null;if(n=await r.json(),n?.status===`error`)throw Error(n.error||`stash-failed`);if(n?.status!==`receiving`)break;await new Promise(e=>setTimeout(e,300))}if(!n||n.status===`receiving`)throw Error(`stash-failed`);let i=[];for(let r=0;r<n.fileNames.length;r++){let a=await t.match(`/share-target-inbox/${e}/file-${r}`);if(!a)throw Error(`stash-failed`);let o=await a.blob();i.push(new File([o],n.fileNames[r],{type:o.type}))}let a=i.length?await VE(i):null;if(await Promise.all(n.fileNames.map((n,r)=>t.delete(`/share-target-inbox/${e}/file-${r}`))),await t.delete(`/share-target-inbox/${e}/meta`),a)return{kind:a.kind,data:{files:a.files}};if(![n.title,n.text,n.url].some(e=>e.trim()))throw Error(`empty-share`);let o=n.text.trim(),s=n.url||(fD(o)?o:``);return s?{kind:`link`,data:{url:s,title:n.title}}:{kind:`note`,data:{title:n.title,content:n.text}}}var uD=new Map;function dD(e){let t=uD.get(e);return t||(t=lD(e),uD.set(e,t),t.finally(()=>setTimeout(()=>uD.delete(e),6e4)).catch(()=>{})),t}function fD(e){if(!e||/\s/.test(e))return!1;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function pD(){let[e]=$t(),t=ft(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null);(0,X.useEffect)(()=>{let t=!1;async function n(){let n=e.get(`error`);if(n){a(n);return}let i=e.get(`token`),o=i?await dD(i):null;t||(o?r(o):a(`expired`))}return n().catch(e=>{t||a(e instanceof Error?e.message:`stash-failed`)}),()=>{t=!0}},[e]);let o=()=>t(`/home`,{replace:!0});return i?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 px-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:cD[i]??cD.expired}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/apps/add/file`,{replace:!0}),className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Add File`}),(0,Z.jsx)(`button`,{type:`button`,onClick:o,className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Go to Canvas`})]}):n?(0,Z.jsx)(XE,{initialKind:n.kind,initialData:n.data,onInitialCardClose:o}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Receiving shared content on this device… No upload has started.`})}function mD(e,t=`An error occurred`){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let n=e;return n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||t}return t}function hD(e,t,n=`An error occurred`){return console.error(t,e),mD(e,n)}function gD(){let e=ft(),[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(`context`),[h,g]=(0,X.useState)(`/`),[_,v]=(0,X.useState)(``),[y,x]=(0,X.useState)(null),[S,w]=(0,X.useState)(`/`),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(!1),[k,A]=hw(),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)(null),{showToast:F}=wo();(0,X.useEffect)(()=>{B.isConnected()||(console.log(`Socket not connected, attempting to connect...`),B.reconnect())},[]);let I=(0,X.useCallback)(async()=>{try{o(!0);let[e,t]=await Promise.all([ml(),Uo()]),r=e?.filter(e=>e&&typeof e==`object`&&e.id&&e.userId)||[];n(r);let a=t||[];if(i(a),a.length>0){let e=a.some(e=>e.id===T);(!T||!e)&&E(a[0].id)}else E(``);c(null)}catch(e){console.error(`Data fetch error:`,e),n([]),i([]);let t=`Failed to fetch data`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch data`}c(t),F({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[T,F]);(0,X.useEffect)(()=>{I()},[I]),(0,X.useEffect)(()=>{let e=()=>B.emit(`subscribe`,{channel:`context`}),t=()=>B.emit(`unsubscribe`,{channel:`context`}),r=B.on(`connect`,e);console.log(`Subscribing to context events`),e();let i=e=>{let t=e;if(console.log(`Received context created:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:created event:`,t);return}n(e=>e.some(e=>e&&e.id===t.id&&e.userId===t.userId)?(console.log(`Context ${t.id} already exists, skipping duplicate add`),e):[...e,t])},a=e=>{let t=e;if(console.log(`Received context update:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:updated event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},o=e=>{let t=e;console.log(`Received context deletion:`,t);let r=t?.contextId??t?.id;if(!r){console.error(`Invalid context deletion data received:`,t);return}n(e=>e.filter(e=>e&&e.id!==r))},s=e=>{let t=e;if(console.log(`Received context URL change:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:url:changed event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},c=[[`context:created`,i],[`context.created`,i],[`context:updated`,a],[`context.updated`,a],[`context:deleted`,o],[`context.deleted`,o],[`context:url:changed`,s],[`context.url.set`,s],[`context:url:set`,s]];return c.forEach(([e,t])=>B.on(e,t)),()=>{console.log(`Unsubscribing from context events`),t(),r?.(),c.forEach(([e,t])=>B.off(e,t))}},[]);let te=async t=>{if(t.preventDefault(),!h.trim()||!T||!l.trim()){F({title:`Missing Fields`,description:`Context ID, Context URL and Workspace are required.`,variant:`destructive`});return}O(!0);try{let t={id:l,name:d.trim()||void 0,url:h,description:_.trim()||void 0,metadata:{ui:{color:y}},workspaceId:T,baseUrl:S||void 0,treeType:p},n=await kl(t);u(``),f(``),g(`/`),v(``),x(null),w(`/`),await I(),F({title:`Success`,description:`Context created successfully`}),A(!1),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e(`/contexts/${n.id}`)}catch(e){let t=hD(e,`Context creation error:`,`Failed to create context`);F({title:`Error`,description:t,variant:`destructive`})}finally{O(!1)}},L=async e=>{let n=t.find(t=>t.id===e);if(n&&n.url&&(n.url.endsWith(`/default`)||n.url.includes(`://default`))){F({title:`Error`,description:`Cannot delete the default context`,variant:`destructive`});return}P(e)},R=async()=>{if(N)try{await gl(N),n(e=>e.filter(e=>!il(e,{id:N}))),F({title:`Success`,description:`Context deleted successfully`})}catch(e){console.error(`Context deletion error:`,e);let t=`Failed to delete context`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to delete context`}F({title:`Error`,description:t,variant:`destructive`})}finally{P(null)}},ne=t=>{let n=t.isShared||t.type===`shared`;e(n?`/contexts/${t.id}?ownerId=${encodeURIComponent(t.userId)}`:`/contexts/${t.id}`)},re=e=>{M(e)},ie=async e=>{if(e.preventDefault(),j)try{n(e=>e.map(e=>e.id===j.id&&e.userId===j.userId?j:e)),F({title:`Success`,description:`Context updated successfully (mock update)`}),M(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update context`;F({title:`Error`,description:t,variant:`destructive`})}},ae=(0,X.useMemo)(()=>({type:e=>e.isShared||e.type===`shared`?`shared`:`owned`,id:e=>e.id??``,owner:e=>e.isShared||e.type===`shared`?e.ownerEmail||e.userId||``:`you`,url:e=>e.url??``,workspaceId:e=>e.workspaceId??``,baseUrl:e=>e.baseUrl??``,path:e=>e.path??``,locked:e=>+!!e.locked,created:e=>Date.parse(e.createdAt)||0,updated:e=>Date.parse(e.updatedAt)||0}),[]),{sorted:z,sort:oe,toggleSort:se}=be(t.filter(e=>e!=null),ae);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`Contexts`,description:`Create and manage contexts in your workspaces. View contexts shared with you.`,actions:!k&&(0,Z.jsxs)(Y,{onClick:()=>A(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create context`,title:`Create context`,children:[(0,Z.jsx)(br,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Context`})]})}),k&&(0,Z.jsx)(pw,{title:`Create New Context`,onClose:()=>A(!1),children:(0,Z.jsxs)(`form`,{onSubmit:te,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`workspace`,className:`block text-sm font-medium mb-1`,children:`Workspace`}),(0,Z.jsxs)(`select`,{id:`workspace`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:T,onChange:e=>E(e.target.value),disabled:D||r.length===0,children:[r.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),r.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label||e.name},`${e.owner}-${e.id}`))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`newContextId`,className:`block text-sm font-medium mb-1`,children:`Context ID`}),(0,Z.jsx)(q,{id:`newContextId`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g., my-new-context`,disabled:D})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(C,{id:`url`,value:h,onChange:g,placeholder:`e.g., /project/path/resource`,disabled:D,pickerTitle:`Context URL path…`,onPickTarget:(e,t)=>{g(e),m(t.treeType);let n=r.find(e=>e.name===t.workspaceName||e.id===t.workspaceName);n&&E(n.id)}})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`block text-sm font-medium mb-1`,children:`Base URL (Optional)`}),(0,Z.jsx)(C,{id:`baseUrl`,value:S,onChange:w,format:`path`,placeholder:`e.g., /base/path`,disabled:D,pickerTitle:`Base path…`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`description`,className:`block text-sm font-medium mb-1`,children:`Description (Optional)`}),(0,Z.jsx)(q,{id:`description`,value:_,onChange:e=>v(e.target.value),placeholder:`Description`,disabled:D})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`contextColor`,className:`block text-sm font-medium mb-1`,children:`Color (Optional)`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{id:`contextColor`,type:`color`,value:y||`#808080`,onChange:e=>x(e.target.value),className:`h-10 w-16 p-1`,disabled:D}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:D||y===null,onClick:()=>x(null),children:`Use inherited color`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:y===null?`Uses the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`contextName`,className:`block text-sm font-medium mb-1`,children:`Name (Optional)`}),(0,Z.jsx)(q,{id:`contextName`,value:d,onChange:e=>f(e.target.value),placeholder:`My Context`,disabled:D})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`treeType`,className:`block text-sm font-medium mb-1`,children:`Tree`}),(0,Z.jsxs)(`select`,{id:`treeType`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:p,onChange:e=>m(e.target.value),disabled:D,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context tree`}),(0,Z.jsx)(`option`,{value:`directory`,children:`Directory tree`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Which workspace tree this context navigates.`})]})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:D||!h.trim()||!T||!l.trim(),children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Context`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Contexts & Shared Contexts`}),a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading contexts...`}),s&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:s})}),!a&&!s&&t.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No contexts found. Create one above.`}),t.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,Z.jsxs)(b,{children:[(0,Z.jsx)(Se,{children:(0,Z.jsxs)(ee,{children:[(0,Z.jsx)(Pt,{label:`Type`,sortKey:`type`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`ID`,sortKey:`id`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Owner`,sortKey:`owner`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Context URL`,sortKey:`url`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Workspace ID`,sortKey:`workspaceId`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Base URL`,sortKey:`baseUrl`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Path`,sortKey:`path`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Locked`,sortKey:`locked`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Created`,sortKey:`created`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Updated`,sortKey:`updated`,sort:oe,onSort:se}),(0,Z.jsx)(_e,{className:`text-right`,children:`Actions`})]})}),(0,Z.jsx)(jt,{children:z.map(e=>{if(!e)return console.warn(`Found null/undefined context in contexts array, skipping`),null;let t=e.createdAt?new Date(e.createdAt).toLocaleDateString():`-`,n=e.updatedAt?new Date(e.updatedAt).toLocaleDateString():`-`,r=e.isShared||e.type===`shared`,i=r?e.ownerEmail||e.userId||`-`:`You`,a=r&&e.sharedVia?typeof e.sharedVia==`string`?e.sharedVia:e.sharedVia.accessLevel||`-`:`-`;return(0,Z.jsxs)(ee,{children:[(0,Z.jsx)(me,{children:r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 text-info`,title:`Shared with you (${a})`,children:[(0,Z.jsx)(aa,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`Shared`})]}):(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Owned`})}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.id||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,title:r?`Owned by: ${i}`:`You are the owner`,children:i}),(0,Z.jsx)(me,{className:`font-mono text-sm max-w-xs truncate`,title:e.url||`-`,children:e.url||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.workspaceId||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.baseUrl||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.path||`-`}),(0,Z.jsx)(me,{children:e.locked?`Yes`:`No`}),(0,Z.jsx)(me,{children:t}),(0,Z.jsx)(me,{children:n}),(0,Z.jsx)(me,{className:`text-right`,children:(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[!r&&(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>re(e),title:`Edit Context`,children:(0,Z.jsx)(gi,{className:`h-4 w-4`})}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>ne(e),title:r?`Open Shared Context`:`Open Context Details`,children:(0,Z.jsx)(fi,{className:`h-4 w-4`})}),!r&&(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>L(e.id),disabled:!!(e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))),className:`text-destructive hover:bg-destructive/10 hover:text-destructive disabled:opacity-50 disabled:cursor-not-allowed`,title:e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))?`Cannot delete default context`:`Delete Context`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})]})})]},`${e.userId}-${e.id}`)})})]})})]}),j&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Edit Context`}),(0,Z.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-id`,className:`block text-sm font-medium mb-1`,children:`Context ID (read-only)`}),(0,Z.jsx)(q,{id:`edit-context-id`,value:j.id,disabled:!0,className:`bg-muted`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(C,{id:`edit-context-url`,value:j.url,onChange:e=>M(t=>t?{...t,url:e}:null),placeholder:`workspace://path or /path`,pickerTitle:`Context URL path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Use format: workspace://path or /path for current workspace`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-base-url`,className:`block text-sm font-medium mb-1`,children:`Base URL (optional)`}),(0,Z.jsx)(C,{id:`edit-base-url`,value:j.baseUrl||``,onChange:e=>M(t=>t?{...t,baseUrl:e||null}:null),format:`path`,placeholder:`/base/path`,pickerTitle:`Base path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Restricts context navigation to this base path`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,children:`Save Changes`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>M(null),children:`Cancel`})]})]})]}),(0,Z.jsx)(vo,{open:N!==null,onOpenChange:e=>!e&&P(null),children:(0,Z.jsxs)(lo,{children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsx)(io,{children:`Delete Context`}),(0,Z.jsx)(ro,{children:`Are you sure you want to delete this context? This action cannot be undone.`})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{onClick:R,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:`Delete`})]})]})})]})}function _D(e,t){if(!e||!t)return`/`;let n=`${t}://`;if(!e.startsWith(n))return`/`;let r=e.slice(n.length).replace(/^\/+/,``).replace(/\/+$/,``);return r?`/${r}`:`/`}function vD(){let{contextId:e}=yt(),t=vn(),n=ft(),r=new URLSearchParams(t.search).get(`ownerId`)||void 0,i=(0,X.useMemo)(()=>{let e=new URLSearchParams(t.search),n=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(e.get(`search`)||``).trim();return n.length?n:r?[r]:[]},[t.search]),{showToast:a,showProgress:o}=wo(),{state:s,saveFilters:c,setSort:l,setAccentColor:u,setMapDocuments:d}=ol(),{openM1Drawer:f,openM2Drawer:p,goBack:m}=qC(),h=s.filters.features.allOf,g=s.filters.features.anyOf,_=s.filters.features.noneOf,v=[...it(s.filters.timeline),...En(s.filters.geo),...ke(s.filters.lens,s.filters.geo.includeUnlocated)],y=JSON.stringify({a:h,b:g,c:_,d:v,ids:s.filters.lens.ids,sort:s.filters.sort,geoSelection:s.geoSelection,includeUnlocated:s.filters.geo.includeUnlocated}),b=(0,X.useMemo)(()=>JSON.parse(y),[y]),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!0),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)([]),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(0),[N,P]=(0,X.useState)([]),[ee,F]=(0,X.useState)(1),[I,te]=(0,X.useState)(50),[L,R]=(0,X.useState)(i),[ne,re]=(0,X.useState)(!1),[ie,ae]=(0,X.useState)(null),[z,oe]=(0,X.useState)(!1),se=(0,X.useRef)(!1),ce=ie?.id===x?.id&&ie?.url===x?.url?ie?.path:null,V=new URLSearchParams(t.search).get(`layer`),le=!!r,ue=CE(le?void 0:x?.workspaceName||x?.workspaceId),de=x?_D(x.url,x.workspaceName):`/`,fe=V?`context-layer`:`context`,pe=!s.liveEnabled&&typeof x?.metadata?.toolboxSearchQuery==`string`?x.metadata.toolboxSearchQuery:``,me=le?null:x?.workspaceName??null,[he,ge]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!me)return;let e=!1;return _c(me,Tc).then(t=>{e||ge({key:me,tree:t})}).catch(()=>{e||ge({key:me,tree:null})}),()=>{e=!0}},[me]);let _e=me&&he?.key===me?he.tree:null,ve=!V&&!le&&_e?de===`/`?_e:xs(_e,de):null,ye=`${x?.workspaceName??``}\0${de}`,[be,xe]=(0,X.useState)(null),H=be?.key===ye?be.views:jT(ve?.metadata),Se=be?.key===ye?be.activeId:H[0]?.id??kT.id,Ce=H.find(e=>e.id===Se)??H[0]??kT,U=OT(Ce),W=e=>{F(1),xe({key:ye,views:H,activeId:e})},we=(e,t)=>{t&&t!==Se&&F(1),xe({key:ye,views:e,activeId:t??Se}),x?.workspaceName&&Ro(x.workspaceName,de,{metadata:{...ve?.metadata??{},views:e}},Tc).catch(()=>{a({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},Te=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>Te.current?.abort(),[]);let Ee=(0,X.useCallback)(async()=>{if(!e)return;Te.current?.abort();let t=new AbortController;Te.current=t,A(!0);try{let n=await Sl(e,U?[...b.a,U]:b.a,b.d,{...b.sort,geoSelection:b.geoSelection,includeUnlocated:b.includeUnlocated,ids:b.ids,signal:t.signal,limit:I,page:ee,queries:L.length?L:void 0,anyOf:b.b,noneOf:b.c,applyContextSpec:!1},r);if(t.signal.aborted)return;O(n),M(n.totalCount||n.count||n.length)}catch(e){if(t.signal.aborted)return;a({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch documents`,variant:`destructive`}),O([]),M(0)}finally{t.signal.aborted||A(!1)}},[e,ee,I,r,L,b,a,U]),De=(0,X.useCallback)(async()=>{if(e){w(!0);try{let t=le?await Tl(e,r):await Tl(e);if(!t)throw Error(`No context data received.`);let n=t.workspace,i=t.workspaceId||(typeof n==`string`?n:n?.id)||``,a=t.workspaceName||(typeof n==`string`?n:n?.name)||``;S({id:t.id,userId:t.userId,url:t.url,baseUrl:t.baseUrl||null,path:t.path||null,pathArray:t.pathArray||[],workspaceId:i,workspaceName:a,acl:t.acl||{},createdAt:t.createdAt,updatedAt:t.updatedAt,locked:t.locked||!1,serverContextArray:t.serverContextArray||[],clientContextArray:t.clientContextArray||[],contextBitmapArray:t.contextBitmapArray||[],featureBitmapArray:t.featureBitmapArray||[],filterArray:t.filterArray||[],pendingUrl:t.pendingUrl||null,description:t.description||null,metadata:t.metadata||{},name:t.name??null,color:t.color??null,icon:t.icon??null}),E(null)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch context ${e}`;E(n),S(null),a({title:`Error`,description:n,variant:`destructive`})}w(!1)}},[e,r,le,a]);(0,X.useEffect)(()=>{De()},[De]);let Oe=Jt(x?.color)||null;(0,X.useEffect)(()=>(u(Oe),()=>u(null)),[Oe,u]);let Ae=s.geoSelection,je=x?.workspaceName||x?.workspaceId||null;(0,X.useEffect)(()=>{d(D,je)},[D,je,d]),(0,X.useEffect)(()=>()=>d([]),[d]);let Me=(0,X.useMemo)(()=>Ae?D.filter(e=>Pe(e,Ae,s.filters.geo.includeUnlocated)):D,[D,Ae,s.filters.geo.includeUnlocated]),Ne=x?.id,Fe=x?.url;(0,X.useEffect)(()=>{Ne&&Ee()},[Ne,Fe,Ee]),(0,X.useEffect)(()=>{let e=()=>Ee();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[Ee]);let[Ie,Le]=(0,X.useState)(y);Ie!==y&&(Le(y),F(1));let[Re,ze]=(0,X.useState)(e);Re!==e&&(ze(e),F(1),re(!1));let[Be,Ve]=(0,X.useState)(i);Be!==i&&(Ve(i),R(i),F(1));let[He,Ue]=(0,X.useState)({urlSearchQueries:i,ignoreSavedSearch:ne,savedContextSearchQuery:pe});(He.urlSearchQueries!==i||He.ignoreSavedSearch!==ne||He.savedContextSearchQuery!==pe)&&(Ue({urlSearchQueries:i,ignoreSavedSearch:ne,savedContextSearchQuery:pe}),!new URLSearchParams(t.search).has(`q`)&&!i.length&&!ne&&(R(pe?[pe]:[]),F(1)));let We=(0,X.useCallback)(e=>{let r=new URLSearchParams(t.search);r.delete(`q`),r.delete(`search`);for(let t of e)r.append(`q`,t);let i=r.toString();n(`${t.pathname}${i?`?${i}`:``}${t.hash}`)},[t.pathname,t.search,t.hash,n]),Ge=(0,X.useCallback)(e=>{let t=e.trim();if(!t)return;re(!1);let n=L.includes(t)?L:[...L,t];R(n),We(n)},[L,We]),Ke=(0,X.useCallback)(e=>{let t=e<0?[]:L.filter((t,n)=>n!==e);t.length===0&&re(!0),R(t),We(t)},[L,We]),G=(L[0]||``).trim(),qe=!!s.activeContextType&&(s.isDirty||G!==(s.savedSearchQuery||pe||``));(0,X.useEffect)(()=>{if(!e)return;let t=`context:${r?`${r}/`:``}${e}`,n=()=>B.emit(`subscribe`,{channel:t}),i=()=>B.emit(`unsubscribe`,{channel:t}),a=B.on(`connect`,n);n();let o=new Map,s=(t,n)=>{let r=Date.now(),i=`${t}:${n?.id||n?.contextId||e}`;return(o.get(i)||0)+1e3>r?!1:(o.set(i,r),!0)},c=t=>{let n=t,r=n?.context||n;(r?.id===e||r?.contextId===e)&&s(`ctx:updated`,r)&&(S(e=>e?{...e,...r}:null),r.url&&Ee())},l=t=>{let n=t,r=n?.id||n?.contextId||n?.context?.id,i=n?.url||n?.context?.url;r===e&&typeof i==`string`&&s(`ctx:url`,n)&&(S(e=>e?{...e,url:i}:null),Ee())},u=t=>{let n=t;(n?.contextId||n?.id||n?.context?.id)===e&&s(`doc:changed`,n)&&Ee()},d=[[`context.updated`,c],[`context:updated`,c],[`context.url.set`,l],[`context:url:set`,l],[`document.inserted`,u],[`document.updated`,u],[`document.removed`,u],[`document.removed.batch`,u],[`document.linked`,u],[`document.unlinked`,u],[`document.linked.batch`,u],[`document.unlinked.batch`,u],[`document.deleted`,u],[`document.deleted.batch`,u]];return d.forEach(([e,t])=>B.on(e,t)),()=>{a(),i(),d.forEach(([e,t])=>B.off(e,t))}},[e,r,Ee]);let Je=async e=>{if(x)try{await rl(x.id,[e],r,de),O(t=>t.filter(t=>t.id!==e)),M(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document removed from context.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Ye=async e=>{if(x)try{await _l(x.id,[e],r,de),O(t=>t.filter(t=>t.id!==e)),M(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Xe=async e=>{if(x)try{await rl(x.id,e,r,de),O(t=>t.filter(t=>!e.includes(t.id))),M(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) removed.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Ze=async e=>{if(x)try{await _l(x.id,e,r,de),O(t=>t.filter(t=>!e.includes(t.id))),M(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Qe=e=>{P(e),a({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},$e=async(e,t,n={})=>{if(!x)return!1;let i=o({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`});try{let a=n.targetTreeName&&!le?await Ko(x.workspaceName||x.workspaceId,e,t,n.targetTreeName,n.targetTreeType):await Al(x.id,e,t,r);return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(P([]),await Ee()),a}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},et=async(e,t)=>{if(!x)return!1;try{let n=await fl(x.workspaceId,t,e);return n&&(an(x.workspaceName||x.workspaceId,`context`,t),a({title:`Success`,description:`Imported ${e.length} document(s) to "${t}"`})),n}catch(e){return a({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},tt=async()=>{if(!x||!ce||le||se.current)return;let e={id:x.id,url:x.url,path:ce};se.current=!0,oe(!0);try{let t=await sl(e.id,`${x.workspaceName}://${e.path.replace(/^\/+/,``)}`);S(n=>n?.id===e.id&&n.url===e.url?{...n,url:t.url,path:e.path}:n),ae(null),F(1),window.dispatchEvent(new CustomEvent(`contexts:refresh`,{detail:{contextId:e.id}})),a({title:`Saved`,description:`Context path updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Could not update context path`,variant:`destructive`})}finally{se.current=!1,oe(!1)}};if(C)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading context...`})]})});if(T&&!x)return(0,Z.jsxs)(`div`,{className:`flex items-center justify-center h-full text-destructive`,children:[`Error: `,T]});if(!x)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Context not found.`});let nt=Jt(x.color);return(0,Z.jsx)(`div`,{className:`flex flex-col h-full min-h-0`,children:(0,Z.jsx)(ET,{onBack:m,accentColor:nt,navigationTabs:ve?(0,Z.jsx)(NT,{views:H,activeId:Se,onSelect:W,onSave:we,accentColor:nt}):void 0,workspaceLabel:ue?.label||x.workspaceName||x.workspaceId,workspaceIcon:ue?.icon,treeName:Tc,urlType:fe,urlDisplay:x.url,contextPath:de,workspaceId:x.workspaceName||x.workspaceId,documentSchema:U,linkTree:_e,documents:Me,isLoading:k,totalCount:j,currentPage:ee,pageSize:I,onPageChange:F,onPageSizeChange:e=>{te(e),F(1)},onRemoveDocument:de===`/`?void 0:Je,onDeleteDocument:Ye,onRemoveDocuments:de===`/`?void 0:Xe,onDeleteDocuments:Ze,onCopyDocuments:Qe,onPasteDocuments:$e,onImportDocuments:le?void 0:et,pastedDocumentIds:N,backendSearchQueries:L,onBackendSearch:Ge,serverSort:s.filters.sort,onServerSortChange:l,onRemoveBackendQuery:Ke,canSaveChanges:qe,isSavingChanges:s.isSaving,onSaveChanges:c,onBrowseTree:!le&&e?()=>p(`contexts`,`detail`,e):void 0,onBrowseWorkspaces:()=>f(`workspaces`),onNavigatePath:le?void 0:e=>{se.current||ae({id:x.id,url:x.url,path:e})},contentBanner:ce?(0,Z.jsxs)(`div`,{className:`border-b bg-warning/10 px-4 py-2`,role:`status`,children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Set this context to the selected path? Contents stay at the current path until you apply it.`}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(pn,{items:mt(ce,x.workspaceName),label:`Selected context path`}),(0,Z.jsx)(`button`,{type:`button`,disabled:z,onClick:()=>void tt(),className:`shrink-0 rounded border px-3 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:z?`Setting…`:`Set`}),(0,Z.jsx)(`button`,{type:`button`,disabled:z,onClick:()=>ae(null),className:`shrink-0 rounded px-2 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:`Cancel`})]})]}):void 0,children:Ce.kind===`columns`?(0,Z.jsx)(zT,{documents:Me,workspaceId:x.workspaceName||x.workspaceId,columns:Ce.columns??[],onColumnsChange:e=>we(H.map(t=>t.id===Ce.id?{...t,columns:e}:t))}):Ce.kind===`app`&&Ce.app&&Ce.app!==`notes`?(0,Z.jsx)(IT,{app:Ce.app,contextId:e,workspaceId:x.workspaceName||x.workspaceId,treeName:Tc,path:de}):null})})}function yD(){let{goBack:e}=qC();return e}function bD(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),{showToast:m}=wo(),h=(0,X.useRef)(null),g=(0,X.useCallback)(async()=>{try{r(!0);let e=await J.get(no.tokens),n=Array.isArray(e)?e:e.tokens||[];t(n),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch tokens`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}},[m]);(0,X.useEffect)(()=>{g()},[g]);let _=async()=>{if(!(!o.trim()||c)){l(!0);try{let e=await J.post(no.tokens,{name:o});s(``),await g(),e&&e.token&&(d(e.token),setTimeout(()=>{if(h.current){h.current.focus();let e=document.createRange();e.selectNodeContents(h.current);let t=window.getSelection();t&&(t.removeAllRanges(),t.addRange(e))}},100)),m({title:`Success`,description:`Token generated successfully`,variant:`default`})}catch(e){let t=e instanceof Error?e.message:`Failed to generate token`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{l(!1)}}},v=async e=>{if(confirm(`Are you sure you want to revoke this API token? This action cannot be undone.`))try{await J.delete(`${no.tokens}/${e}`),await g(),m({title:`Success`,description:`API token revoked successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to revoke API token`;m({title:`Error`,description:t,variant:`destructive`})}},y=async e=>{try{await navigator.clipboard.writeText(e),p(!0),m({title:`Success`,description:`Token copied to clipboard`}),setTimeout(()=>p(!1),2e3)}catch{m({title:`Error`,description:`Failed to copy token to clipboard`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`API Tokens`,onBack:yD(),description:`Create and manage API tokens for programmatic access`}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Generate New API Token`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Token Name (e.g., 'CLI Access', 'Automation')`,disabled:c,className:`flex-1`}),(0,Z.jsxs)(Y,{type:`button`,disabled:c||!o.trim(),onClick:_,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),c?`Generating...`:`Generate`]})]}),u&&(0,Z.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Your New API Token`}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>y(u),children:f?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(sr,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Jn,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-2`,children:`Make sure to copy your API token now. You won't be able to see it again!`}),(0,Z.jsx)(`div`,{ref:h,tabIndex:0,className:`p-2 bg-background border rounded font-mono text-sm break-all outline-none focus:ring-2 focus:ring-ring`,children:u})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your API Tokens`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading API tokens...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No API tokens found`}),e.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Last Used`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Expires`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.lastUsedAt?new Date(e.lastUsedAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3 text-right`,children:(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>v(e.id),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})})]},e.id))})]})})})]})]})}async function xD(){return await J.get(no.devices)||[]}async function SD(e,t){return await J.patch(`${no.devices}/${encodeURIComponent(e)}`,t)}async function CD(e){await J.delete(`${no.devices}/${encodeURIComponent(e)}`)}async function wD(e){return await J.get(`${no.workspaces}/${e}/devices`)||[]}async function TD(e,t){let{deviceId:n,name:r,description:i,platform:a,arch:o,type:s}=t,c=await J.post(`${no.workspaces}/${e}/devices`,{devices:[{deviceId:n,name:r,description:i,platform:a,arch:o,type:s}]});return Array.isArray(c)?c:[c]}async function ED(e,t){await J.delete(`${no.workspaces}/${e}/devices/${encodeURIComponent(t)}`)}function DD({device:e,onUpdated:t,onRemoved:n}){let[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(e.name),[s,c]=(0,X.useState)(e.description??``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),{showToast:h}=wo(),g=async()=>{m(!0);try{await CD(e.deviceId),n(e.deviceId),h({title:`Revoked`,description:`${e.name} can no longer sign in; a running mirror stops on its next request.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke device`,variant:`destructive`}),f(!1)}finally{m(!1)}},_=async()=>{let n=a.trim();if(n){if(n===e.name&&s.trim()===(e.description??``)){i(!1);return}u(!0);try{let r=await SD(e.deviceId,{name:n,description:s.trim()||void 0});t({...e,...r}),i(!1),h({title:`Saved`,description:`Device updated`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{u(!1)}}},v=()=>{o(e.name),c(e.description??``),i(!1)},y=e=>e?new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}):`—`;return(0,Z.jsx)(`div`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(mr,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[r?(0,Z.jsxs)(`div`,{className:`space-y-2 mb-2`,children:[(0,Z.jsx)(q,{value:a,onChange:e=>o(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,disabled:l,onKeyDown:e=>{e.key===`Enter`&&_(),e.key===`Escape`&&v()}}),(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,disabled:l,onKeyDown:e=>{e.key===`Enter`&&_(),e.key===`Escape`&&v()}})]}):(0,Z.jsxs)(`div`,{className:`mb-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] font-mono text-muted-foreground`,children:[(0,Z.jsx)(`span`,{title:`Device ID`,children:e.deviceId}),e.platform&&(0,Z.jsx)(`span`,{children:e.platform}),e.arch&&(0,Z.jsx)(`span`,{children:e.arch}),e.type&&(0,Z.jsx)(`span`,{className:`capitalize`,children:e.type})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 text-[11px] text-muted-foreground`,children:[e.createdAt&&(0,Z.jsxs)(`span`,{children:[`registered `,y(e.createdAt)]}),e.updatedAt&&e.updatedAt!==e.createdAt&&(0,Z.jsxs)(`span`,{children:[`updated `,y(e.updatedAt)]}),e.lastSeen&&(0,Z.jsxs)(`span`,{children:[`seen `,y(e.lastSeen)]})]})]})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:d?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,onClick:g,disabled:p,children:p?`Revoking…`:`Confirm revoke`}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!1),disabled:p,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}):r?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:_,disabled:l||!a.trim(),children:(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:v,disabled:l,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>i(!0),title:`Edit name / description`,children:(0,Z.jsx)(Lr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!0),title:`Revoke this device: its tokens stop working and its mirrors stop syncing`,children:(0,Z.jsx)(Di,{className:`h-3.5 w-3.5`})})]})})]})})}function OD(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),{showToast:i}=wo(),a=async()=>{r(!0);try{t(await xD())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}};(0,X.useEffect)(()=>{(async()=>{try{t(await xD())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}})()},[i]);let o=e=>t(t=>t.map(t=>t.deviceId===e.deviceId?e:t)),s=e=>t(t=>t.filter(t=>t.deviceId!==e));return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 space-y-6`,children:[(0,Z.jsx)(sw,{compact:!0,title:`Devices`,onBack:yD(),description:`All devices registered to your account. Link them to individual workspaces in Workspace › Settings › Devices.`,actions:(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:a,disabled:n,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${n?`animate-spin`:``}`}),`Refresh`]})}),n?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):e.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border p-6 text-center text-sm text-muted-foreground space-y-2`,children:[(0,Z.jsx)(mr,{className:`h-8 w-8 mx-auto text-muted-foreground/40`}),(0,Z.jsx)(`p`,{children:`No devices registered yet.`}),(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`Devices register themselves automatically on first connection via`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]})]}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,Z.jsx)(DD,{device:e,onUpdated:o,onRemoved:s},e.deviceId))}),e.length>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-dashed p-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Ri,{className:`h-3.5 w-3.5 shrink-0`}),`To link a device to a workspace, go to Workspace › Settings › Devices.`]})]})})}var kD=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:Bi},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:ra},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:Fr},{id:`db`,label:`Search & indexing`,description:`Rebuild indexes, tune search and choose embedding models`,icon:Fa},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:mr},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:Er},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:pi},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:Ri},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:gr},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:Gr}],AD={embedding:`db`,trash:`data`};function jD(e){return e?AD[e]?AD[e]:kD.some(t=>t.id===e)?e:`general`:`general`}var MD=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:Bi},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:Ri},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:ar}];function ND(e){return e&&MD.some(t=>t.id===e)?e:`general`}var PD=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:Bi},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:Cr},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:yi},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:Pr},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:Ra},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:ri},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:si}];function FD(e){return e&&PD.some(t=>t.id===e)?e:`identity`}var ID=class{static async handleStreamingResponse(e,t={}){let{onChunk:n,onError:r,onComplete:i,signal:a}=t;try{if(!e.body)throw Error(`Response body is null - streaming not supported`);if(typeof e.body.getReader!=`function`){console.warn(`ReadableStream.getReader not available, falling back to text response`);let t=await e.text();n&&n(t),i&&i();return}let t=e.body.getReader(),r=new TextDecoder;try{for(;;){if(a?.aborted)throw t.cancel(),Error(`Stream aborted`);let{done:e,value:o}=await t.read();if(e){i&&i();break}let s=r.decode(o,{stream:!0});s&&n&&n(s)}}finally{t.releaseLock()}}catch(e){console.error(`Streaming error:`,e),r&&r(e instanceof Error?e:Error(String(e)))}}static processSSEChunk(e){let t=[],n=e.split(`
|
|
26
|
+
`),r={};for(let e of n){let n=e.trim();if(n.startsWith(`data: `))try{let e=JSON.parse(n.slice(6));r={...r,...e}}catch{console.warn(`Failed to parse SSE data:`,n)}else n===``&&(r.agentId&&r.messageId&&t.push(r),r={})}return t}},LD=class{baseUrl;constructor(e,t=`/rest/v2/agents/anthropic`){this.baseUrl=t}async chatStream(e,t){let{agentId:n,messageId:r,onMessage:i,onError:a,onComplete:o,signal:s}=t;try{let t=await fetch(`${this.baseUrl}/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/plain, text/event-stream`,"Cache-Control":`no-cache`},body:JSON.stringify({message:e,agentId:n,messageId:r}),signal:s});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);await ID.handleStreamingResponse(t,{onChunk:e=>{try{ID.processSSEChunk(e).forEach(e=>{i&&i(e)})}catch(e){console.warn(`Failed to process streaming chunk:`,e)}},onError:e=>{let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e.message}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)},onComplete:o,signal:s})}catch(e){let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e instanceof Error?e.message:String(e)}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)}}},RD=class{wsUrl;socket=null;messageHandlers=new Map;constructor(e){this.wsUrl=e}connect(){return new Promise((e,t)=>{try{this.socket=new WebSocket(this.wsUrl),this.socket.onopen=()=>{console.log(`WebSocket connected for streaming`),e()},this.socket.onerror=e=>{console.error(`WebSocket error:`,e),t(Error(`WebSocket connection failed`))},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data),n=`${t.agentId}-${t.messageId}`,r=this.messageHandlers.get(n);r&&r(t)}catch(e){console.error(`Failed to parse WebSocket message:`,e)}},this.socket.onclose=()=>{console.log(`WebSocket disconnected`),this.socket=null}}catch(e){t(e)}})}startChatStream(e,t,n,r,i){if(!this.socket||this.socket.readyState!==WebSocket.OPEN){i&&i(Error(`WebSocket not connected`));return}let a=`${e}-${t}`;this.messageHandlers.set(a,r);try{this.socket.send(JSON.stringify({type:`chat_stream`,agentId:e,messageId:t,message:n}))}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}stopChatStream(e,t){let n=`${e}-${t}`;this.messageHandlers.delete(n)}disconnect(){this.socket&&=(this.socket.close(),null),this.messageHandlers.clear()}};function zD(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
27
|
+
`)||``}function BD(e){return e?typeof e?.metadata?.reasoning==`string`&&e.metadata.reasoning.trim()?e.metadata.reasoning.trim():Array.isArray(e.content)?e.content.filter(e=>e?.type===`thinking`||e?.type===`reasoning`).map(e=>typeof e?.thinking==`string`?e.thinking:typeof e?.reasoning==`string`?e.reasoning:typeof e?.text==`string`?e.text:``).filter(Boolean).join(`
|
|
28
|
+
`).trim():``:``}function VD(e){if(!e)return;let t=BD(e),n={...e.api?{api:e.api}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.stopReason?{stopReason:e.stopReason}:{},...e.timestamp===void 0?{}:{timestamp:e.timestamp},...e.responseId?{responseId:e.responseId}:{},...e.usage?{usage:e.usage}:{},...e.metadata?.toolCalls?{toolCalls:e.metadata.toolCalls}:{},...t?{reasoning:t}:{}};return Object.keys(n).length>0?n:void 0}function HD(e){if(typeof e==`number`)return new Date(e).toISOString();if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return new Date().toISOString()}function UD(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:zD(e),timestamp:HD(e.timestamp),...e.role===`assistant`?{metadata:VD(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function WD(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:UD(e?.messages||[])}}function GD(e){return{current:WD(e?.current),sessions:e?.sessions}}new class{connectors=new Map;wsService=null;messageCallbacks=new Map;constructor(){this.initializeWebSocketFallback()}async initializeWebSocketFallback(){try{let e=`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}/ws`;this.wsService=new RD(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new LD(e.apiKey||``,e.endpoint||`${yo}/agents/${e.id}`);this.connectors.set(e.id,t)}}async sendMessage(e,t,n={}){let{onMessage:r,onError:i,onComplete:a,useWebSocketFallback:o=!1}=n,s=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;r&&this.messageCallbacks.set(s,r);try{if(o&&this.wsService){await this.sendMessageViaWebSocket(e,s,t,r,i),a&&a();return}let n=this.connectors.get(e);n?await n.chatStream(t,{agentId:e,messageId:s,onMessage:e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},onError:n=>{if(console.error(`Agent connector error:`,n),n.message.includes(`getReader is not a function`)&&this.wsService){console.log(`Falling back to WebSocket streaming...`),this.sendMessageViaWebSocket(e,s,t,r,i);return}i&&i(n)},onComplete:a}):await this.sendMessageViaAPI(e,s,t,r,i,a)}catch(e){console.error(`Agent communication error:`,e),i&&i(e instanceof Error?e:Error(String(e)))}finally{this.messageCallbacks.delete(s)}}async sendMessageViaAPI(e,t,n,r,i,a){try{await J.stream(`${yo}/agents/${e}/chat/stream`,{message:n,messageId:t},{onChunk:n=>{try{let i=JSON.parse(n),a={id:t,agentId:e,content:i.content||n,timestamp:new Date,type:`agent`,streaming:!i.done,error:i.error};r&&r(a)}catch{r&&r({id:t,agentId:e,content:n,timestamp:new Date,type:`agent`,streaming:!0})}},onError:e=>{console.error(`API streaming error:`,e),i&&i(e)},onComplete:a})}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async sendMessageViaWebSocket(e,t,n,r,i){if(!this.wsService){i&&i(Error(`WebSocket service not available`));return}try{this.wsService.socket?.readyState!==WebSocket.OPEN&&await this.wsService.connect(),this.wsService.startChatStream(e,t,n,e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},i)}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async getAvailableAgents(){try{return(await J.get(`${yo}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await J.post(`${yo}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function KD(e){return await J.get(`${yo}/agents/${e}/access`)||null}async function qD(e,t){return await J.put(`${yo}/agents/${e}/access`,t)}async function JD(e){return await J.post(`${yo}/agents/${e}/access/token`)}async function YD(e){await J.delete(`${yo}/agents/${e}/access`)}async function XD(e){return await J.get(`${yo}/agents/${e}/tools`)||{tools:[],config:{}}}async function ZD(){try{return await J.get(`${yo}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function QD(e){return await J.get(`${yo}/agents/${e}`)}async function $D(e){return WD(await J.get(`${yo}/agents/${e}/session`))}async function eO(e){return await J.get(`${yo}/agents/${e}/sessions`)}async function tO(e,t){return GD(await J.post(`${yo}/agents/${e}/sessions`,t))}async function nO(e,t){return GD(await J.put(`${yo}/agents/${e}/session`,t))}async function rO(e,t,n){return GD(await J.patch(`${yo}/agents/${e}/sessions/${t}`,n))}async function iO(e,t){return GD(await J.delete(`${yo}/agents/${e}/sessions/${t}`))}async function aO(e){return await J.get(`${yo}/agents/${e}/skills`)||[]}async function oO(e,t){return await J.post(`${yo}/agents/${e}/skills`,t)||[]}async function sO(e,t){return await J.delete(`${yo}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function cO(e){return await J.post(`${yo}/agents`,e)}async function lO(e,t){return await J.put(`${yo}/agents/${e}`,t)}async function uO(e){await J.delete(`${yo}/agents/${e}`)}async function dO(e){return await J.post(`${yo}/agents/${e}/start`)}async function fO(e){return await J.post(`${yo}/agents/${e}/stop`)}async function pO(e){return await J.get(`${yo}/agents/${e}/status`)}async function mO(e,t,n={}){let{onStart:r,onMessage:i,onError:a,onComplete:o,context:s,mcpContext:c,maxTokens:l,temperature:u,images:d}=n,f=``;await J.stream(`${yo}/agents/${e}/prompt/stream`,{message:t,images:d,context:s,mcpContext:c,maxTokens:l,temperature:u},{onOpen:()=>{r?.()},onChunk:e=>{f+=e;let t=f.split(`
|
|
29
|
+
|
|
30
|
+
`);f=t.pop()||``;for(let e of t){let t=e.split(`
|
|
31
|
+
`).map(e=>e.trim()).filter(Boolean);for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t!==`[DONE]`)try{let e=JSON.parse(t);if(!i)continue;if(e.type===`chunk`)i(e.delta||``,!1,e.metadata||{});else if(e.type===`thinking`)i(``,!1,{...e.metadata||{},reasoningDelta:e.delta||``});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null;i(``,!0,{...e.metadata||{},...VD(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function hO(e,t){let{message:n,onMessage:r,onError:i,onComplete:a,context:o,mcpContext:s,maxTokens:c,temperature:l,images:u}=t;try{let t=await J.post(`${yo}/agents/${e}/prompt`,{message:n,images:u,context:o,mcpContext:s,maxTokens:c,temperature:l}),i=Array.isArray(t.messages)?[...t.messages].reverse().find(e=>e?.role===`assistant`):null,d={content:zD(i),metadata:VD(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function gO(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function _O(){return await J.get(`${yo}/voice/status`)}async function vO(e,t,n={}){let r=new FormData,i=(t.type.split(`/`)[1]||`webm`).split(`;`)[0];r.append(`file`,t,`voice.${i}`);let a=new URLSearchParams;n.tts===!1&&a.set(`tts`,`false`),n.voice&&a.set(`voice`,n.voice);let o=a.toString()?`?${a.toString()}`:``;return await J.post(`${yo}/agents/${e}/voice${o}`,r)}var yO=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:kD,load:async()=>(await Uo()).map(e=>({id:e.name,label:e.label||e.name}))},{id:`context`,label:`Context`,path:`contexts`,description:`Choose the tree and path a context opens, and who can access that view. File storage belongs to its workspace.`,sections:MD,load:async()=>(await ml()).map(e=>({id:e.id,label:e.name||e.id}))},{id:`agent`,label:`Agent`,path:`agents`,description:`Configure one assistant: its instructions, chat model, tools and access to Canvas.`,sections:PD,load:async()=>(await ZD()).map(e=>({id:e.id,label:e.label||e.name}))}];function bO({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(we,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(xi,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function xO({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>wC(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(bO,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function SO(){let{state:e}=qC(),[t,n]=(0,X.useState)(``),r=SC.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>wC(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=yO.some(e=>e.sections.some(n=>wC(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(bO,{to:e.path,...e},e.path))})]},e.id)),yO.map(e=>(0,Z.jsx)(xO,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(bO,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var CO=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],wO=`/wallpapers`;function TO(e){return CO.find(t=>t.id===e)}function EO(e,t={}){let n=typeof e==`string`?TO(e):e;if(!n)return null;let{base:r=wO,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function DO(e,t=wO){let n=typeof e==`string`?TO(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var OO=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],kO=`canvas:wallpaper`,AO=`canvas-wallpaper`,jO=`settings`,MO=`builtin:`,NO=CO;function PO(e){return DO(e)??``}function FO(e){return`${MO}${e}`}function IO(e){return e?.startsWith(MO)?e.slice(8):null}function LO(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function RO(){try{let e=localStorage.getItem(kO);if(e){let t=LO(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var zO=RO(),BO=null;function VO(){return zO}async function HO(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(AO,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(jO),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(jO,e?`readwrite`:`readonly`),a=i.objectStore(jO),o=e?a.put(e,kO):a.get(kO);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function UO(){try{localStorage.removeItem(kO)}catch{}}function WO(){return BO||=(async()=>{try{let e=LO(await HO());e?zO=e:await HO(zO),UO()}catch{}return QO(zO),zO})(),BO.then(()=>zO)}async function GO(e){await WO(),await HO(e),zO=e,UO(),QO(e)}function KO(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var qO=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function JO(e){if(!e)return null;let t=IO(e);if(t===null)return`url("${e}")`;let n=TO(t);if(!n)return null;let r=`url("${EO(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!qO||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${EO(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function YO(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var XO=null;function ZO(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function QO(e=VO()){let t=document.documentElement.style,n=XO,r=e.image;if(r?.startsWith(`data:`))try{XO?.dataUrl!==r&&(XO={dataUrl:r,objectUrl:URL.createObjectURL(ZO(r))}),r=XO.objectUrl}catch{XO=null,r=null}else XO=null;let i=JO(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,YO(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==XO&&URL.revokeObjectURL(n.objectUrl)}var $O=[{id:`cards`,name:`Cards`,description:`Nested cards with connector lines. Each level indents.`},{id:`accordion-mobile`,name:`Accordion on phones (beta)`,description:`Experimental. Full-width accordion rows on a phone, cards on wider screens.`},{id:`accordion`,name:`Accordion (beta)`,description:`Experimental. Full-width rows at every depth; a depth rail, tint and colour swatch replace the indent, and open parents stick to the top while you scroll.`}],ek=`canvas:treeStyle`;function tk(){try{let e=localStorage.getItem(ek);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var nk=tk(),rk=new Set;function ik(){return nk}function ak(e){try{e===`cards`?localStorage.removeItem(ek):localStorage.setItem(ek,e)}catch{}nk=e;for(let e of rk)e()}function ok(e){rk.add(e);let t=t=>{(t.key===ek||t.key===null)&&(nk=tk(),e())};return window.addEventListener(`storage`,t),()=>{rk.delete(e),window.removeEventListener(`storage`,t)}}function sk(){return(0,X.useSyncExternalStore)(ok,ik,()=>`cards`)}function ck(){let e=sk(),t=De();return e===`accordion`||e===`accordion-mobile`&&t}var lk=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],uk=lk.map(e=>e.id),dk=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],fk=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],pk={theme:`canvas`,scheme:`light`,density:`auto`},mk=`canvas.ui.theme`;function hk(e){return typeof e==`string`&&uk.includes(e)}function gk(e){return e===`light`||e===`dark`||e===`system`}function _k(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function vk(e){let t=typeof e==`object`&&e?e:{};return{theme:hk(t.theme)?t.theme:pk.theme,scheme:gk(t.scheme)?t.scheme:pk.scheme,density:_k(t.density)?t.density:pk.density}}var yk=`(prefers-color-scheme: dark)`;function bk(){return typeof document<`u`}function xk(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(yk).matches}function Sk(e){return e===`system`?xk()?`dark`:`light`:e}function Ck(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(yk),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function wk(e){return Ck(e)}function Tk(){return xk()?`dark`:`light`}function Ek(){return`light`}function Dk(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function Ok(e,t=bk()?document.documentElement:void 0){let n=Sk(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,Dk(t),n):n}function kk(e,t=bk()?document.documentElement:void 0){if(!t||typeof window>`u`)return Ok(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=Ok(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function Ak(e){let t=e??Nk();if(!t)return pk;try{let e=t.getItem(mk);return e?vk(JSON.parse(e)):pk}catch{return pk}}function jk(e,t){let n=t??Nk();if(n)try{n.setItem(mk,JSON.stringify(e))}catch{}}function Mk(e){let t=e??Nk();if(t)try{t.removeItem(mk)}catch{}}function Nk(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function Pk({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...Ak(n),...t})),o=(0,X.useSyncExternalStore)(wk,Tk,Ek),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{kk({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&jk(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?Tk():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{Mk(n),a(pk)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(Il.Provider,{value:p,children:e})}var Fk={system:mr,light:ji,dark:va};function Ik(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Ll(),c=re(),l=k(),u=PC(),d=L(),f=sk(),p=UC();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:lk.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)(sr,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)(Vk,{options:dk.map(e=>{let t=Fk[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)(Vk,{options:fk.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:fk.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)(Vk,{options:TC.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:MC}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:TC.find(e=>e.id===u)?.description}),u===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)(Vk,{options:FC.map(e=>({id:e.id,label:e.name,title:e.description})),value:p,onChange:VC}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[FC.find(e=>e.id===p)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)(Vk,{options:$O.map(e=>({id:e.id,label:e.name,title:e.description})),value:f,onChange:ak}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:$O.find(e=>e.id===f)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)(Vk,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:l,onChange:M}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Always-on content area`,description:`Keep a reading pane beside document lists on tablets and desktops. Remember the selected item in each folder, or show the first available item.`}),(0,Z.jsx)(Vk,{options:[{id:`on`,label:`On`},{id:`off`,label:`Off`}],value:c?`on`:`off`,onChange:e=>ze(e===`on`)}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`On by default. The reader uses roughly half the screen; drag its divider to resize. Phones keep tap-to-open navigation. When enabled, list selections use this pane regardless of the Open documents setting.`})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Bk,{title:`Document tiles`,description:`Choose the photo and media layout for tile view. Saved on this device.`}),(0,Z.jsx)(Vk,{options:Ie,value:d,onChange:He})]}),(0,Z.jsx)(Lk,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),M(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function Lk(){let[e,t]=(0,X.useState)(VO),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=!1;return WO().then(()=>{e||(t(VO()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await KO(n)}:e;await GO(i),t(i),r(null)}catch(e){r(e instanceof Error&&e.name!==`QuotaExceededError`?e.message:`Could not store the wallpaper. Free some browser storage or try a smaller image.`)}finally{c.current=!1,s(!1)}}},u=t=>{t&&l(e,t)},d=e.image!==null&&IO(e.image)===null,f=JO(e.image);return(0,Z.jsx)(`section`,{children:(0,Z.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,Z.jsx)(Bk,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(zk,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),NO.map(t=>(0,Z.jsx)(zk,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:IO(e.image)===t.id,onSelect:()=>l({...e,image:FO(t.id)}),children:(0,Z.jsx)(`img`,{src:PO(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,Z.jsx)(zk,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(Rk,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:YO(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,Z.jsx)(Vk,{options:OO.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function Rk(){let e=NO.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function zk({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)(sr,{className:`size-3`})})]})}function Bk({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function Vk({options:e,value:t,onChange:n}){return(0,Z.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function Hk(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Appearance`,onBack:yD(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(Ik,{})]})}var Uk={previousTree:`Alt+Q`,nextTree:`Alt+W`},Wk=`canvas:key-bindings`,Gk=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function Kk(){try{let e=JSON.parse(localStorage.getItem(Wk)||`{}`),t={...Uk};for(let n of Object.keys(t))(e[n]===``||Gk.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...Uk}:t}catch{return{...Uk}}}function qk(e){localStorage.setItem(Wk,JSON.stringify(e))}function Jk(e){return/^Key[A-Z]$/.test(e.code)?[e.ctrlKey&&`Ctrl`,e.altKey&&`Alt`,e.metaKey&&`Meta`,e.shiftKey&&`Shift`,e.code.slice(3)].filter(Boolean).join(`+`):``}function Yk(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function Xk(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Zk(){let[e,t]=(0,X.useState)(Kk),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{qk(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Key bindings`,onBack:yD(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||Uk[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||Uk[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...Uk}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var Qk=`offline-content-v1`,$k=`offline-api-v1`,eA=1073741824,tA={enabled:!1,budgetBytes:4*eA,excludedWorkspaces:[]},nA=1e3;function rA(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function iA(e,t,n){return`${e}:${t}:${rA(n)}`}var aA=`canvas-offline`,oA=2,sA=null;function cA(){return sA||(sA=new Promise((e,t)=>{let n=indexedDB.open(aA,oA);n.onupgradeneeded=e=>{let t=n.result;if(t.objectStoreNames.contains(`config`)||t.createObjectStore(`config`),t.objectStoreNames.contains(`entries`)||t.createObjectStore(`entries`,{keyPath:`url`}),e.oldVersion>=1&&t.objectStoreNames.contains(`pins`)){t.deleteObjectStore(`pins`);let e=n.transaction.objectStore(`entries`).openCursor();e.onsuccess=()=>{let t=e.result;if(!t)return;let n=t.value;n.pinned&&t.update({...n,pinned:!1}),t.continue()}}t.objectStoreNames.contains(`scopes`)||t.createObjectStore(`scopes`,{keyPath:`id`})},n.onsuccess=()=>{n.result.onversionchange=()=>{n.result.close(),sA=null},e(n.result)},n.onerror=()=>{sA=null,t(n.error)}}),sA)}function lA(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function uA(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function dA(e,t){return uA((await cA()).transaction(e).objectStore(e).get(t))}async function fA(e){return uA((await cA()).transaction(e).objectStore(e).getAll())}async function pA(e,t,n){let r=(await cA()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),lA(r)}async function mA(e,t){let n=(await cA()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),lA(n)}async function hA(e){let t=(await cA()).transaction(e,`readwrite`);return t.objectStore(e).clear(),lA(t)}async function gA(){try{let e=await dA(`config`,`settings`);return e?{...tA,...e}:tA}catch{return tA}}async function _A(e){await pA(`config`,e,`settings`)}async function vA(e,t){let n=(await cA()).transaction(`entries`,`readwrite`),r=n.objectStore(`entries`);for(let n of e){let e=r.get(n);e.onsuccess=()=>{let i=e.result;i?r.put({...i,pinned:t}):t&&r.put({url:n,kind:`content`,size:0,lastAccess:Date.now(),pinned:t})}}return lA(n)}async function yA(e){let t=await fA(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-nA)),i=t.filter(e=>e.kind===`content`),a=i.reduce((e,t)=>e+t.size,0),o=i.filter(e=>!e.pinned).sort((e,t)=>e.lastAccess-t.lastAccess),s=[];for(let t of o){if(a<=e)break;s.push(t),a-=t.size}if(!r.length&&!s.length)return;let[c,l]=await Promise.all([caches.open($k),caches.open(Qk)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await mA(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await mA(`entries`,e.url)})])}async function bA(){let e=await fA(`entries`),t=e.filter(e=>e.kind===`content`);return{contentBytes:t.reduce((e,t)=>e+t.size,0),contentCount:t.length,pinnedBytes:t.filter(e=>e.pinned).reduce((e,t)=>e+t.size,0),apiCount:e.length-t.length}}async function xA(){await Promise.all([caches.delete(Qk),caches.delete($k)]),await hA(`entries`),await hA(`scopes`)}async function SA(){return fA(`scopes`)}async function CA(e){return dA(`scopes`,e)}async function wA(e){await pA(`scopes`,e)}async function TA(e){let t=await dA(`scopes`,e);await mA(`scopes`,e),t?.urls.length&&await EA(t.urls)}async function EA(e){let t=await fA(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await vA(r,!1)}var DA=3,OA=`data/schema/file`,kA=128;async function AA({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await gA();if(!a.enabled)throw Error(`Enable the offline cache first`);if(a.excludedWorkspaces.includes(e))throw Error(`Workspace "${e}" is excluded from offline caching`);let o=iA(e,n,t),s=rA(t),c=await CA(o),l=((await Fs(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===OA),u=[],d=0,f=0,p=!1,m=l.length;i?.({done:f,total:m,bytes:d});let h=0;await Promise.all(Array.from({length:Math.min(DA,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await No(e,t.id);d+=n.size,u.push(`${no.workspaces}/${e}/documents/${t.id}/content`);try{await Cs(e,t.id,kA),u.push(`${no.workspaces}/${e}/documents/${t.id}/thumbnail?size=${kA}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await vA(u,!0);let g={id:o,workspaceRef:e,treeName:n,treeType:r,path:s,urls:u,bytes:d,warmedAt:Date.now(),...p?{truncated:!0}:{}};if(await wA(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await EA(t)}return g}var jA=[{label:`1 GB`,bytes:1*eA},{label:`2 GB`,bytes:2*eA},{label:`4 GB`,bytes:4*eA},{label:`8 GB`,bytes:8*eA}];function MA(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/eA).toFixed(2)} GB`}function NA(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function PA(){let{showSuccessToast:e,showErrorToast:t}=Oo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{gA().then(r).catch(()=>{}),bA().then(a).catch(()=>{}),SA().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Uo().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let b=async e=>{r(e),await _A(e),NA(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),yA(e.budgetBytes).then(v).catch(()=>{})},x=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];b({...n,excludedWorkspaces:t})},S=async()=>{h(!0);try{await xA(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},C=async n=>{let r=iA(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await AA(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${MA(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${MA(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},w=(e,t)=>{_(!1);for(let n of e)C({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},T=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),E=async e=>{await TA(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(FA,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>b({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(Ya,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,Z.jsx)(sr,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:jA.map(e=>(0,Z.jsx)(Y,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>b({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[MA(i.contentBytes),` of `,MA(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${MA(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:S,disabled:m,children:[m?(0,Z.jsx)(Ti,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(Qr,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(FA,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(Y,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(tr,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,Z.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${MA(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[MA(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>C(T(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>E(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(FA,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(ya,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(Y,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>x(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(Le,{onClose:()=>_(!1),children:(0,Z.jsx)(y,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:w,onClose:()=>_(!1)})})]}):null}function FA({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function IA(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Offline`,onBack:yD(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(PA,{})]})}function LA(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function RA({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function zA(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return J.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&r(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let i=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${LA(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`About`,onBack:yD(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(RA,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.14`}),e?.version&&(0,Z.jsx)(RA,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(RA,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var BA=[`onnx`,`clip`,`blip`,`openai`],VA=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],HA=[{id:`openai`,baseUrl:`https://api.openai.com/v1`,label:`OpenAI`},{id:`vllm`,baseUrl:`http://127.0.0.1:8000/v1`,label:`vLLM`},{id:`ollama`,baseUrl:`http://127.0.0.1:11434/v1`,label:`Ollama`}],UA=e=>`${no.workspaces}/${encodeURIComponent(e)}/inferd`;function WA(e,t){let n={};for(let[r,i]of Object.entries(e.providers||{})){let e={...i};delete e.apiKeySet,delete e.headerNames,t.has(r)&&i.apiKey?e.apiKey=i.apiKey:delete e.apiKey,n[r]=e}return{...e,providers:n}}async function GA(e){return await J.get(`${UA(e)}/status`)}async function KA(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await J.post(`${UA(e)}/summarize/images`,n)}async function qA(e){return await J.post(`${UA(e)}/summarize/images/stop`,{})}async function JA(e){return await J.get(`${UA(e)}/config`)}async function YA(e,t){return await J.put(`${UA(e)}/config`,t)}async function XA(e,t={}){let n={};return t.space&&(n.space=t.space),t.reindex!==void 0&&(n.reindex=t.reindex),t.scope&&(n.scope=t.scope),await J.post(`${UA(e)}/reindex`,n)}async function ZA(e){return await J.get(`${UA(e)}/vector-tables`)}async function QA(e,t){return await J.delete(`${UA(e)}/vector-tables/${encodeURIComponent(t)}`)}async function $A(){return await J.get(`${no.inferd}/config`)}async function ej(e){return await J.put(`${no.inferd}/config`,e)}async function tj(){return await J.get(`${no.inferd}/defaults`)}async function nj(e){return await J.put(`${no.inferd}/defaults`,e)}async function rj(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await J.post(`${no.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function ij(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await J.post(`${no.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var aj=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,oj=`font-semibold uppercase tracking-[0.08em]`,sj={openai:{url:{key:`baseUrl`,label:`Base URL`,placeholder:`http://gpu.local:8000/v1`,hint:`OpenAI-compatible embeddings endpoint — Ollama, vLLM, TEI, infinity, LM Studio and OpenAI itself all speak this. A trailing /v1 is optional; both http://host:8000 and http://host:8000/v1 work.`},apiKey:"Sent as `Authorization: Bearer …`. Leave empty for servers that do not check it.",imageInput:!0,timeoutMs:!0,headers:!0,where:e=>e.baseUrl||`no endpoint set`},ollama:{url:{key:`host`,label:`Host (legacy)`,placeholder:`http://127.0.0.1:11434`,hint:`Written by an older version. Switch the type to openai — the host becomes the base URL and the /v1 suffix is added for you.`},apiKey:"Sent as `Authorization: Bearer …`.",where:e=>e.host||`http://127.0.0.1:11434`},onnx:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`},clip:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`}},cj=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],lj=[{value:`data-uri`,label:`data-uri (default)`,hint:"Images ride in the ordinary `input` array as data URIs (infinity, TEI-style servers)."},{value:`messages`,label:`messages`,hint:`vLLM's multimodal shape: one request per image, wrapped in a chat message.`}],uj=12e4;function dj(e){if(typeof e!=`string`||e.trim()===``)return null;let t;try{t=new URL(e.trim())}catch{return`Must be an absolute URL including the scheme, e.g. http://127.0.0.1:11434`}return t.protocol!==`http:`&&t.protocol!==`https:`?`Unsupported scheme '${t.protocol.replace(`:`,``)}'. Use http or https.`:null}function fj({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,oj),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function pj({overridden:e,source:t}){return e?(0,Z.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function mj({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(pj,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function hj({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(pj,{overridden:n})]})}function gj({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(pj,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,Z.jsx)(q,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function _j({open:e,onClick:t,label:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(qr,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var vj={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function yj({value:e,effective:t,inherited:n,resolvedSpaces:r,invalid:i,attention:a,onFill:o,saving:s=!1,disabled:c=!1,saveLabel:l=`Save`,onSave:u}){let{showToast:d}=wo(),[f,p]=(0,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?sj[i.type]?.url?.key:void 0,o=a?dj(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await rj(i,r)===!1&&(y(!0),d({title:`Downloading model`,description:`'${r??`the configured model`}' is not in the server's cache yet; downloading now. A first test can take a few minutes; the model is then cached for good.`}))}catch{}let n=await ij(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?sj[i]?.url?.key:void 0;if(!a)continue;let o=dj(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),L=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(WA(f,m)),h(new Set)},R=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(dr,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(fj,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,vj[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,oj),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(lr,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(_j,{open:m,onClick:()=>R(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(pj,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:aj,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(mj,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(mj,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,Z.jsx)(mj,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(hj,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(hj,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(fj,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=VA.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?sj[l]:void 0,d=u?.url?dj(n[u.url.key]):null,p={...r,...n},h=cj.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(_j,{open:s,onClick:()=>R(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(pj,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:aj,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),BA.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!BA.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(mj,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,Z.jsx)(mj,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(pj,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:aj,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),lj.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:lj.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(mj,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??uj,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,Z.jsx)(gj,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),HA.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:L,disabled:s||!te||I.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function bj(){let{showToast:e}=wo(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>$A().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:yD(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(yj,{value:t.user||{},effective:t.effective||{},inherited:t.serverDefaults||{},invalid:t.invalid,saving:a,saveLabel:`Save defaults`,onSave:async t=>{o(!0);try{let n=await ej(t);e({title:`Defaults saved`,description:n.restartRequired?`${n.workspaces.length} running workspace(s) keep their current tables until restarted. Set the config on a workspace directly to change it live.`:`New workspaces will inherit this.`}),await l()}catch(t){e({title:`Save failed`,description:t instanceof Error?t.message:`Failed to save`,variant:`destructive`})}finally{o(!1)}}},JSON.stringify(t.user))]})}function xj(){let e=vn(),{showToast:t}=wo(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await J.get(e,{skipAuth:!0,headers:_()});d(t);let n=await J.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(sw,{onBack:yD(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(Y,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(au,{className:`mt-8`})]})}function Sj(e={}){let t=new URLSearchParams;e.tail&&t.set(`tail`,String(e.tail)),e.level&&t.set(`level`,e.level),e.module&&t.set(`module`,e.module);let n=t.toString();return n?`?${n}`:``}function Cj(){let e=localStorage.getItem(`authToken`);if(!e)throw Error(`Authentication required`);let t=localStorage.getItem(`appName`)||window.location.hostname;return{Authorization:`Bearer ${e}`,"X-App-Name":t,Accept:`text/event-stream`}}var wj={users:{async listUsers(e){let t=new URLSearchParams;e?.status&&t.append(`status`,e.status),e?.userType&&t.append(`userType`,e.userType);let n=t.toString(),r=n?`${no.admin.users}?${n}`:no.admin.users;return await J.get(r)},async getUser(e){return await J.get(`${no.admin.users}/${e}`)},async createUser(e){return await J.post(no.admin.users,e)},async updateUser(e,t){return await J.put(`${no.admin.users}/${e}`,t)},async deleteUser(e){await J.delete(`${no.admin.users}/${e}`)}},workspaces:{async listAllWorkspaces(){return await J.get(no.admin.workspaces)},async createWorkspace(e){return await J.post(no.admin.workspaces,e)},async deleteWorkspace(e){await J.delete(`${no.admin.workspaces}/${e}`)}},logs:{async getLogs(e={}){return(await J.get(`${no.admin.logs}${Sj(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${no.admin.logsStream}${Sj(e)}`,{method:`GET`,headers:Cj(),credentials:`include`,signal:n});if(!t.ok)throw Error(`Failed to open log stream (${t.status})`);if(!t.body)throw Error(`Streaming is not supported by this browser`);let i=t.body.getReader(),a=new TextDecoder,o=``,s=e=>{let t=e.split(`
|
|
32
|
+
`),n=`message`,i=[];for(let e of t)if(!(!e||e.startsWith(`:`))){if(e.startsWith(`event:`)){n=e.slice(6).trim();continue}e.startsWith(`data:`)&&i.push(e.slice(5).trim())}if(n!==`log`||i.length===0)return;let a=JSON.parse(i.join(`
|
|
33
|
+
`));r?.(a)};try{for(;;){let{done:e,value:t}=await i.read();if(e)break;o+=a.decode(t,{stream:!0});let n=o.split(`
|
|
34
|
+
|
|
35
|
+
`);o=n.pop()||``;for(let e of n)s(e)}o.trim()&&s(o)}finally{i.releaseLock()}}catch(e){if(n?.aborted)return;let t=e instanceof Error?e:Error(String(e));throw i?.(t),t}}}},Tj=()=>{let e=[`#FF6B6B`,`#4ECDC4`,`#45B7D1`,`#96CEB4`,`#FECA57`,`#FF9FF3`,`#54A0FF`,`#5F27CD`,`#00D2D3`,`#FF9F43`,`#10AC84`,`#EE5A24`,`#EA2027`,`#009432`,`#0652DD`];return e[Math.floor(Math.random()*e.length)]};function Ej(){let e=du()?.userType===`admin`,[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(e),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(e?null:`Access denied. Admin privileges required.`),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)({search:``,owner:``,type:``,status:``}),[_,v]=(0,X.useState)({userId:``,name:``,label:``,description:``,color:Tj(),type:`workspace`}),{showToast:y}=wo(),b=(0,X.useCallback)(async()=>{try{o(!0);let e=await wj.workspaces.listAllWorkspaces();n(e),u(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch workspaces`;u(t),y({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[y]);(0,X.useEffect)(()=>{e&&b()},[e,b]);let x=(0,X.useCallback)(async()=>{try{c(!0);let e=await wj.users.listUsers({status:`active`});i(e)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch users`;y({title:`Error`,description:t,variant:`destructive`})}finally{c(!1)}},[y]),S=async e=>{if(e.preventDefault(),!_.userId||!_.name.trim()){y({title:`Validation Error`,description:`User and workspace name are required`,variant:`destructive`});return}f(!0);try{let e={userId:_.userId,name:_.name.trim(),label:_.label.trim()||_.name.trim(),description:_.description.trim(),color:_.color,type:_.type};await wj.workspaces.createWorkspace(e),v({userId:``,name:``,label:``,description:``,color:Tj(),type:`workspace`}),m(!1),await b(),y({title:`Success`,description:`Workspace created successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to create workspace`;y({title:`Error`,description:t,variant:`destructive`})}finally{f(!1)}},C=async(e,t)=>{if(confirm(`Are you sure you want to delete workspace "${t}"? This action cannot be undone and will delete all data in the workspace.`))try{await wj.workspaces.deleteWorkspace(e),await b(),y({title:`Success`,description:`Workspace deleted successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete workspace`;y({title:`Error`,description:t,variant:`destructive`})}},w=async()=>{v({userId:``,name:``,label:``,description:``,color:Tj(),type:`workspace`}),m(!0),await x()},T=()=>{m(!1)};Ae(T,p);let E=t.filter(e=>{let t=h.search===``||e.name.toLowerCase().includes(h.search.toLowerCase())||e.label.toLowerCase().includes(h.search.toLowerCase())||e.ownerName&&e.ownerName.toLowerCase().includes(h.search.toLowerCase())||e.ownerEmail&&e.ownerEmail.toLowerCase().includes(h.search.toLowerCase()),n=h.owner===``||e.owner===h.owner,r=h.type===``||e.type===h.type,i=h.status===``||e.status===h.status;return t&&n&&r&&i}),D=Array.from(new Set(t.map(e=>e.owner))).map(e=>{let n=t.find(t=>t.owner===e);return{id:e,name:n?.ownerName||n?.ownerEmail||e}});return e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`Workspace Administration`,description:`Manage workspaces across all users`}),t.some(e=>e.status!==`active`&&e.protection?.mode&&e.protection.mode!==`none`)&&(0,Z.jsxs)(`p`,{className:`text-sm rounded border p-3`,children:[t.filter(e=>e.status!==`active`&&e.protection?.mode&&e.protection.mode!==`none`).length,` protected workspaces waiting for their owners to start them.`]}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsx)(q,{placeholder:`Search workspaces...`,value:h.search,onChange:e=>g(t=>({...t,search:e.target.value})),className:`md:w-64`}),(0,Z.jsxs)(`select`,{value:h.owner,onChange:e=>g(t=>({...t,owner:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Owners`}),D.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Z.jsxs)(`select`,{value:h.type,onChange:e=>g(t=>({...t,type:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`universe`,children:`Universe`})]}),(0,Z.jsxs)(`select`,{value:h.status,onChange:e=>g(t=>({...t,status:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`error`,children:`Error`})]})]}),(0,Z.jsxs)(Y,{onClick:w,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),l&&!t.length&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:l})}),!a&&!l&&E.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),E.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Label`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Owner`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Color`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:E.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium font-mono text-sm`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.label}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(ar,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`font-medium`,children:e.ownerName||`Unknown`}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.ownerEmail})]})]})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.type===`universe`?`bg-accent text-primary`:`bg-info-subtle text-info`}`,children:e.type})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.status===`active`?`bg-success-subtle text-success`:e.status===`inactive`?`bg-warning-subtle text-warning`:`bg-destructive-subtle text-destructive`}`,children:e.status})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`w-4 h-4 rounded border`,style:{backgroundColor:e.color}}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.color})]})}),(0,Z.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsxs)(`td`,{className:`p-3 text-right space-x-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>window.open(`/workspaces/${e.name}`,`_blank`),title:`View workspace`,children:(0,Z.jsx)(ja,{className:`h-4 w-4`})}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>C(e.id,e.name),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,title:`Delete workspace`,disabled:e.type===`universe`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})]})]},e.id))})]})})})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-4 gap-4 mt-8`,children:[(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Total Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.filter(e=>e.status===`active`).length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Active Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.filter(e=>e.type===`universe`).length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Universe Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:D.length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Unique Owners`})]})]}),p&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-card rounded-lg p-6 w-full max-w-md mx-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:`Create New Workspace`}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:T,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`form`,{onSubmit:S,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`userId`,children:`User`}),(0,Z.jsxs)(`select`,{id:`userId`,value:_.userId,onChange:e=>v(t=>({...t,userId:e.target.value})),disabled:d||s,className:`w-full px-3 py-2 border border-border rounded-md`,required:!0,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a user...`}),r.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` (`,e.email,`)`]},e.id))]}),s&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Loading users...`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Workspace Name`}),(0,Z.jsx)(q,{id:`name`,type:`text`,value:_.name,onChange:e=>v(t=>({...t,name:e.target.value})),placeholder:`my-workspace`,disabled:d,required:!0}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Lowercase letters, numbers, and hyphens only`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`label`,children:`Display Label`}),(0,Z.jsx)(q,{id:`label`,type:`text`,value:_.label,onChange:e=>v(t=>({...t,label:e.target.value})),placeholder:`My Workspace`,disabled:d})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`description`,children:`Description`}),(0,Z.jsx)(q,{id:`description`,type:`text`,value:_.description,onChange:e=>v(t=>({...t,description:e.target.value})),placeholder:`Workspace description (optional)`,disabled:d})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`type`,children:`Type`}),(0,Z.jsxs)(`select`,{id:`type`,value:_.type,onChange:e=>v(t=>({...t,type:e.target.value})),disabled:d,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`universe`,children:`Universe`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`color`,children:`Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{id:`color`,type:`color`,value:_.color,onChange:e=>v(t=>({...t,color:e.target.value})),className:`h-10 w-16 p-1`,disabled:d}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>v(e=>({...e,color:Tj()})),disabled:d,children:`Random`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:d||s,className:`flex-1`,children:d?`Creating...`:`Create Workspace`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:T,disabled:d,children:`Cancel`})]})]})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function Dj(){let e=du()?.userType===`admin`;return(0,X.useEffect)(()=>{},[e]),e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`All Contexts`,description:`Manage all contexts across all users`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Global context management is currently under development. Check back later for updates.`})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function Oj(){let e=du()?.userType===`admin`;return(0,X.useEffect)(()=>{},[e]),e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`All Agents`,description:`Manage all AI agents across all users`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Global agent management is currently under development. Check back later for updates.`})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}var kj={tail:200,level:``,module:``};function Aj(e){return e.slice(-1e3)}function jj(e){switch(e.levelLabel){case`fatal`:return`text-destructive`;case`error`:return`text-destructive`;case`warn`:return`text-warning`;case`info`:return`text-info`;case`debug`:return`text-muted-foreground`;case`trace`:return`text-muted-foreground`;default:return`text-success`}}function Mj(){let e=yD(),t=du()?.userType===`admin`,{showToast:n}=wo(),r=(0,X.useRef)(null),[i,a]=(0,X.useState)(kj),[o,s]=(0,X.useState)(kj),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)(t),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(t?null:`Access denied. Admin privileges required.`),v=(0,X.useCallback)(async e=>{try{d(!0);let t=await wj.logs.getLogs(e);l(Aj(t)),_(null)}catch(e){let t=e instanceof Error?e.message:`Failed to load server logs`;_(t),n({title:`Error`,description:t,variant:`destructive`})}finally{d(!1)}},[n]);(0,X.useEffect)(()=>{t&&v(i)},[i,t,v]),(0,X.useEffect)(()=>{if(!t||m)return;let e=new AbortController;return p(!0),wj.logs.streamLogs(i,{signal:e.signal,onEntry:e=>{l(t=>Aj([...t,e]))},onError:e=>{_(e.message)}}).catch(e=>{let t=e instanceof Error?e.message:`Log stream stopped`;_(t),n({title:`Stream error`,description:t,variant:`destructive`})}).finally(()=>{p(!1)}),()=>{e.abort()}},[i,t,m,n]),(0,X.useEffect)(()=>{!r.current||m||(r.current.scrollTop=r.current.scrollHeight)},[c,m]);let y=()=>{a({tail:Math.min(Math.max(Number(o.tail)||kj.tail,1),500),level:o.level||``,module:o.module.trim()})},b=(0,X.useMemo)(()=>[{value:``,label:`All levels`},{value:`trace`,label:`Trace`},{value:`debug`,label:`Debug`},{value:`info`,label:`Info`},{value:`warn`,label:`Warn`},{value:`error`,label:`Error`},{value:`fatal`,label:`Fatal`}],[]);return t?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{onBack:e,title:`Server Logs`,description:`Live tail for the unified canvas-server logger`,actions:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(ui,{className:`w-4 h-4 ${f?`text-success`:`text-muted-foreground`}`}),(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:m?`Paused`:f?`Streaming`:`Disconnected`})]})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-[140px_180px_1fr_auto]`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`tail`,children:`Tail`}),(0,Z.jsx)(q,{id:`tail`,type:`number`,min:1,max:500,value:o.tail,onChange:e=>s(t=>({...t,tail:Number(e.target.value)}))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`level`,children:`Level`}),(0,Z.jsx)(`select`,{id:`level`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:o.level,onChange:e=>s(t=>({...t,level:e.target.value})),children:b.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value||`all`))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`module`,children:`Module filter`}),(0,Z.jsx)(q,{id:`module`,placeholder:`auth, http, workspace...`,value:o.module,onChange:e=>s(t=>({...t,module:e.target.value}))})]}),(0,Z.jsx)(`div`,{className:`flex items-end`,children:(0,Z.jsx)(Y,{onClick:y,className:`w-full`,children:`Apply`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>h(e=>!e),children:[m?(0,Z.jsx)(Ar,{className:`w-4 h-4 mr-2`}):(0,Z.jsx)(Jr,{className:`w-4 h-4 mr-2`}),m?`Resume`:`Pause`]}),(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>v(i),children:[(0,Z.jsx)(Ba,{className:`w-4 h-4 mr-2`}),`Refresh`]}),(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>l([]),children:[(0,Z.jsx)(Qr,{className:`w-4 h-4 mr-2`}),`Clear buffer`]}),(0,Z.jsxs)(`span`,{className:`text-sm text-muted-foreground ml-auto`,children:[`Showing `,c.length,` lines`]})]}),g&&(0,Z.jsx)(`div`,{className:`rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive`,children:g}),(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,Z.jsx)(`div`,{ref:r,"data-scheme":`dark`,className:`bg-background text-success font-mono text-xs h-viewport-pane overflow-auto p-4 rounded-md`,children:u?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading logs...`}):c.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:c.map((e,t)=>(0,Z.jsx)(`div`,{className:jj(e),children:e.line},`${e.time||`log`}-${t}`))})})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}var Nj={async listRoles(e){let t=new URLSearchParams;e?.type&&t.append(`type`,e.type),e?.userId&&t.append(`userId`,e.userId),e?.workspaceId&&t.append(`workspaceId`,e.workspaceId),e?.status&&t.append(`status`,e.status);let n=t.toString(),r=n?`${no.roles}?${n}`:no.roles;return(await J.get(r)).roles||[]},async getRole(e){return(await J.get(`${no.roles}/${e}`)).role},async createRole(e){return(await J.post(no.roles,e)).role},async deleteRole(e,t=!1){let n=t?`?force=true`:``;await J.delete(`${no.roles}/${e}${n}`)},async startRole(e){return(await J.post(`${no.roles}/${e}/start`,{})).role},async stopRole(e){await J.post(`${no.roles}/${e}/stop`,{})},async restartRole(e){return(await J.post(`${no.roles}/${e}/restart`,{})).role},async getRoleLogs(e,t=100){return(await J.get(`${no.roles}/${e}/logs?tail=${t}`)).logs||[]},async getRoleStats(e){return(await J.get(`${no.roles}/${e}/stats`)).stats},async getRoleHealth(e){return(await J.get(`${no.roles}/${e}/health`)).health},async listTemplates(){return(await J.get(`${no.roleTemplates}`)).templates||[]},async getTemplate(e){return(await J.get(`${no.roleTemplates}/${e}`)).template}};function Pj({status:e}){let t={running:{icon:kr,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:Bn,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:Zn,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:Zn,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:er,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:ui,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:ui,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:Bn,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,Z.jsx)(r,{className:`w-3 h-3`}),n.label]})}function Fj({type:e}){return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${e===`global`?`bg-accent text-primary`:`bg-info-subtle text-info`}`,children:[(0,Z.jsx)(pi,{className:`w-3 h-3`}),e===`global`?`Global`:`Workspace`]})}function Ij(){let e=yD(),t=du()?.userType===`admin`,[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(t),[c,l]=(0,X.useState)(t?null:`Access denied. Admin privileges required.`),[u,d]=(0,X.useState)(!1);Ae(()=>d(!1),u);let[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1);Ae(()=>h(!1),m);let[g,_]=(0,X.useState)([]),[v,y]=(0,X.useState)({type:``,status:``,search:``}),[b,x]=(0,X.useState)({template:``,name:``,type:`global`}),{showToast:S}=wo(),C=(0,X.useRef)(v);(0,X.useEffect)(()=>{C.current=v},[v]);let w=(0,X.useCallback)(async()=>{try{s(!0);let{type:e,status:t}=C.current,n=await Nj.listRoles({type:e||void 0,status:t||void 0});r(n),l(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch roles`;l(t)}finally{s(!1)}},[]),T=(0,X.useCallback)(async()=>{try{let e=await Nj.listTemplates();a(e)}catch(e){console.error(`Failed to fetch templates:`,e)}},[]);(0,X.useEffect)(()=>{t&&(w(),T())},[t,w,T]);let E=async()=>{if(!b.template||!b.name){S({title:`Validation Error`,description:`Template and name are required`,variant:`destructive`});return}try{await Nj.createRole(b),S({title:`Success`,description:`Role "${b.name}" created successfully`}),d(!1),M(),w()}catch(e){let t=e instanceof Error?e.message:`Failed to create role`;S({title:`Error`,description:t,variant:`destructive`})}},D=async e=>{try{await Nj.startRole(e.id),S({title:`Success`,description:`Role "${e.name}" started successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to start role`;S({title:`Error`,description:t,variant:`destructive`})}},O=async e=>{try{await Nj.stopRole(e.id),S({title:`Success`,description:`Role "${e.name}" stopped successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to stop role`;S({title:`Error`,description:t,variant:`destructive`})}},k=async e=>{try{await Nj.restartRole(e.id),S({title:`Success`,description:`Role "${e.name}" restarted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to restart role`;S({title:`Error`,description:t,variant:`destructive`})}},A=async e=>{if(confirm(`Are you sure you want to delete role "${e.name}"?`))try{await Nj.deleteRole(e.id,e.status===`running`),S({title:`Success`,description:`Role "${e.name}" deleted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to delete role`;S({title:`Error`,description:t,variant:`destructive`})}},j=async e=>{try{let t=await Nj.getRoleLogs(e.id,100);_(t),p(e),h(!0)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch logs`;S({title:`Error`,description:t,variant:`destructive`})}},M=()=>{x({template:``,name:``,type:`global`})},N=()=>{M(),d(!0)},P=()=>{d(!1),M()},ee=n.filter(e=>!v.search||e.name.toLowerCase().includes(v.search.toLowerCase())||e.template.toLowerCase().includes(v.search.toLowerCase()));return t?c&&!t?(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:c})}):(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{onBack:e,title:`Role Management`,description:`Manage global and workspace roles for Canvas services`,actions:(0,Z.jsxs)(Y,{onClick:N,className:`gap-2`,children:[(0,Z.jsx)(br,{className:`w-4 h-4`}),`Create Role`]})}),(0,Z.jsxs)(`div`,{className:`flex gap-4 items-end`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsx)(G,{htmlFor:`search`,children:`Search`}),(0,Z.jsx)(q,{id:`search`,placeholder:`Search by name or template...`,value:v.search,onChange:e=>y({...v,search:e.target.value})})]}),(0,Z.jsxs)(`div`,{className:`w-48`,children:[(0,Z.jsx)(G,{htmlFor:`type`,children:`Type`}),(0,Z.jsxs)(`select`,{id:`type`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:v.type,onChange:e=>y({...v,type:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`global`,children:`Global`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`})]})]}),(0,Z.jsxs)(`div`,{className:`w-48`,children:[(0,Z.jsx)(G,{htmlFor:`status`,children:`Status`}),(0,Z.jsxs)(`select`,{id:`status`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:v.status,onChange:e=>y({...v,status:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`running`,children:`Running`}),(0,Z.jsx)(`option`,{value:`stopped`,children:`Stopped`}),(0,Z.jsx)(`option`,{value:`starting`,children:`Starting`}),(0,Z.jsx)(`option`,{value:`error`,children:`Error`})]})]}),(0,Z.jsxs)(Y,{onClick:w,variant:`outline`,children:[(0,Z.jsx)(Ba,{className:`w-4 h-4 mr-2`}),`Refresh`]})]}),o?(0,Z.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):ee.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-8 border rounded-lg`,children:[(0,Z.jsx)(pi,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:v.search||v.type||v.status?`No roles match your filters`:`No roles created yet`}),!v.search&&!v.type&&!v.status&&(0,Z.jsxs)(Y,{onClick:N,variant:`outline`,className:`mt-4`,children:[(0,Z.jsx)(br,{className:`w-4 h-4 mr-2`}),`Create Your First Role`]})]}):(0,Z.jsx)(`div`,{className:`border rounded-lg`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{className:`bg-muted/50`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Template`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Container`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-right p-4 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{className:`divide-y`,children:ee.map(e=>(0,Z.jsxs)(`tr`,{className:`hover:bg-muted/50`,children:[(0,Z.jsx)(`td`,{className:`p-4 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:e.template}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsx)(Fj,{type:e.type})}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsx)(Pj,{status:e.status})}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:e.container?.name||`-`}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[e.status===`stopped`||e.status===`created`?(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>D(e),title:`Start`,children:(0,Z.jsx)(Ar,{className:`w-4 h-4`})}):e.status===`running`?(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>O(e),title:`Stop`,children:(0,Z.jsx)(Sa,{className:`w-4 h-4`})}):null,e.status===`running`&&(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>k(e),title:`Restart`,children:(0,Z.jsx)(Ba,{className:`w-4 h-4`})}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>j(e),title:`View Logs`,children:(0,Z.jsx)(Ki,{className:`w-4 h-4`})}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>A(e),title:`Delete`,className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(ti,{className:`w-4 h-4`})})]})})]},e.id))})]})}),u&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsx)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-lg w-full mx-4 max-h-viewport-modal overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`p-6 space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-bold`,children:`Create New Role`}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:P,children:(0,Z.jsx)(vr,{className:`w-4 h-4`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`template`,children:`Template *`}),(0,Z.jsxs)(`select`,{id:`template`,className:`w-full px-3 py-2 border rounded-md bg-background mt-1`,value:b.template,onChange:e=>x({...b,template:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`Select a template...`}),i.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Role Name *`}),(0,Z.jsx)(q,{id:`name`,placeholder:`e.g., canvas-sshd`,value:b.name,onChange:e=>x({...b,name:e.target.value})})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`roleType`,children:`Type *`}),(0,Z.jsxs)(`select`,{id:`roleType`,className:`w-full px-3 py-2 border rounded-md bg-background mt-1`,value:b.type,onChange:e=>x({...b,type:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`global`,children:`Global (Server-wide)`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace (User-scoped)`})]})]}),b.template&&(0,Z.jsxs)(`div`,{className:`p-4 bg-muted rounded-lg`,children:[(0,Z.jsx)(`h3`,{className:`font-medium mb-2`,children:`Template Info`}),i.find(e=>e.id===b.template)&&(0,Z.jsxs)(`div`,{className:`text-sm space-y-1 text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Image:`}),` `,i.find(e=>e.id===b.template)?.container.image]}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Category:`}),` `,i.find(e=>e.id===b.template)?.category]}),i.find(e=>e.id===b.template)?.documentation?.readme&&(0,Z.jsx)(`p`,{className:`mt-2`,children:i.find(e=>e.id===b.template)?.documentation?.readme})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-4 border-t`,children:[(0,Z.jsx)(Y,{variant:`outline`,onClick:P,children:`Cancel`}),(0,Z.jsx)(Y,{onClick:E,children:`Create Role`})]})]})})}),m&&f&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-4xl w-full mx-4 max-h-viewport-modal flex flex-col`,children:[(0,Z.jsxs)(`div`,{className:`p-6 border-b flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-xl font-bold`,children:`Role Logs`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:f.name})]}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>h(!1),children:(0,Z.jsx)(vr,{className:`w-4 h-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,Z.jsx)(`div`,{"data-scheme":`dark`,className:`bg-background text-success p-4 rounded font-mono text-xs overflow-x-auto`,children:g.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`pre`,{children:g.join(`
|
|
36
|
+
`)})})}),(0,Z.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,Z.jsx)(Y,{onClick:()=>h(!1),children:`Close`})})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function Lj(){let e=yD(),t=du(),n=t?.userType===`admin`,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(n),[s,c]=(0,X.useState)(n?null:`Access denied. Admin privileges required.`),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)({status:``,userType:``,search:``}),[x,S]=(0,X.useState)({name:``,email:``,password:``,userType:`user`,status:`active`}),{showToast:C}=wo();(0,X.useEffect)(()=>{n&&(async()=>{try{let e=await gu(),t=!!e?.strategies?.local?.requireEmailVerification;g(t),v(e?.strategies?.local?.passwordPolicy||null)}catch{g(!1),v(null)}})()},[n]);let w=e=>{let t=e.trim().toLowerCase();return t.length<3||t.length>39?`Username must be 3-39 characters long`:/^[a-z0-9_-]+$/.test(t)?null:`Username can only contain lowercase letters, numbers, underscores, and hyphens`},T=e=>{let t=e||``,n=_||{},r=n.minLength??12,i=n.maxLength??128,a=[];return t.length<r&&a.push(`at least ${r} characters`),t.length>i&&a.push(`no more than ${i} characters`),(n.requireUppercase??!0)&&!/[A-Z]/.test(t)&&a.push(`an uppercase letter`),(n.requireLowercase??!0)&&!/[a-z]/.test(t)&&a.push(`a lowercase letter`),(n.requireNumbers??!0)&&!/[0-9]/.test(t)&&a.push(`a number`),(n.requireSpecialChars??!0)&&!/[^A-Za-z0-9]/.test(t)&&a.push(`a special character`),a.length?`Password must contain ${a.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`:null},E=()=>{let e=_||{},t=[],n=e.minLength??12;return t.push(`${n}+ chars`),(e.requireUppercase??!0)&&t.push(`uppercase`),(e.requireLowercase??!0)&&t.push(`lowercase`),(e.requireNumbers??!0)&&t.push(`number`),(e.requireSpecialChars??!0)&&t.push(`special`),t.join(`, `)},D=e=>{if(!e)return`-`;let t=new Date(e);return isNaN(t.getTime())?`-`:t.toLocaleString()},O=async e=>{try{await _u(e),C({title:`Verification email`,description:`If the account exists, a verification email was sent.`})}catch(e){let t=e instanceof Error?e.message:`Failed to send verification email`;C({title:`Error`,description:t,variant:`destructive`})}},k=(0,X.useCallback)(async()=>{try{o(!0);let{status:e,userType:t}=y,n=await wj.users.listUsers({status:e||void 0,userType:t||void 0});i(n),c(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch users`;c(t),C({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[y,C]);(0,X.useEffect)(()=>{n&&k()},[k,n]);let A=async e=>{if(e.preventDefault(),!x.name.trim()||!x.email.trim()){C({title:`Validation Error`,description:`Name and email are required`,variant:`destructive`});return}let t=w(x.name);if(t){C({title:`Validation Error`,description:t,variant:`destructive`});return}if(!x.password.trim()){C({title:`Validation Error`,description:`Password is required`,variant:`destructive`});return}let n=T(x.password);if(n){C({title:`Validation Error`,description:n,variant:`destructive`});return}u(!0);try{let e={name:x.name.trim().toLowerCase(),email:x.email.trim(),userType:x.userType,status:x.status};if(x.password.trim()&&(e.password=x.password),await wj.users.createUser(e),h&&x.status===`pending`)try{await _u(x.email.trim())}catch{}S({name:``,email:``,password:``,userType:`user`,status:h?`pending`:`active`}),m(!1),await k(),C({title:`Success`,description:`User created successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to create user`;C({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}},j=async e=>{if(e.preventDefault(),!d)return;let t=w(x.name);if(t){C({title:`Validation Error`,description:t,variant:`destructive`});return}if(x.password.trim()){let e=T(x.password);if(e){C({title:`Validation Error`,description:e,variant:`destructive`});return}}u(!0);try{let e={name:x.name.trim().toLowerCase(),email:x.email.trim(),userType:x.userType,status:x.status};x.password.trim()&&(e.password=x.password),await wj.users.updateUser(d.id,e),f(null),m(!1),await k(),C({title:`Success`,description:`User updated successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to update user`;C({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}},M=async(e,t)=>{if(confirm(`Are you sure you want to delete user "${t}"? This action cannot be undone.`))try{await wj.users.deleteUser(e),await k(),C({title:`Success`,description:`User deleted successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete user`;C({title:`Error`,description:t,variant:`destructive`})}},N=()=>{f(null),S({name:``,email:``,password:``,userType:`user`,status:h?`pending`:`active`}),m(!0)},P=e=>{f(e),S({name:e.name,email:e.email,password:``,userType:e.userType,status:e.status}),m(!0)},ee=()=>{m(!1),f(null)};Ae(ee,p);let F=r.filter(e=>y.search===``||e.name.toLowerCase().includes(y.search.toLowerCase())||e.email.toLowerCase().includes(y.search.toLowerCase()));return n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{onBack:e,title:`User Management`,description:`Manage user accounts and permissions`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsx)(q,{placeholder:`Search users...`,value:y.search,onChange:e=>b(t=>({...t,search:e.target.value})),className:`md:w-64`}),(0,Z.jsxs)(`select`,{value:y.status,onChange:e=>b(t=>({...t,status:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending`}),(0,Z.jsx)(`option`,{value:`deleted`,children:`Deleted`})]}),(0,Z.jsxs)(`select`,{value:y.userType,onChange:e=>b(t=>({...t,userType:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`user`,children:`User`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admin`})]})]}),(0,Z.jsxs)(Y,{onClick:N,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create User`]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading users...`}),s&&!r.length&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:s})}),!a&&!s&&F.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No users found`}),F.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Email`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Updated`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:F.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.email}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.userType===`admin`?`bg-destructive-subtle text-destructive`:`bg-info-subtle text-info`}`,children:e.userType})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.status===`active`?`bg-success-subtle text-success`:e.status===`inactive`?`bg-warning-subtle text-warning`:e.status===`pending`?`bg-info-subtle text-info`:`bg-destructive-subtle text-destructive`}`,children:e.status})}),(0,Z.jsx)(`td`,{className:`p-3`,children:D(e.createdAt)}),(0,Z.jsx)(`td`,{className:`p-3`,children:D(e.updatedAt)}),(0,Z.jsxs)(`td`,{className:`p-3 text-right space-x-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>P(e),children:(0,Z.jsx)(Za,{className:`h-4 w-4`})}),h&&e.status===`pending`&&(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>O(e.email),title:`Resend activation email`,children:`Resend activation`}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>M(e.id,e.name),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,disabled:e.id===t?.id,title:e.id===t?.id?`Cannot delete your own account`:`Delete user`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})]})]},e.id))})]})})})]}),p&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-card rounded-lg p-6 w-full max-w-md mx-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:d?`Edit User`:`Create New User`}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:ee,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`form`,{onSubmit:d?j:A,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,value:x.name,onChange:e=>S(t=>({...t,name:e.target.value.toLowerCase().replace(/\s+/g,``)})),placeholder:`Enter username`,disabled:l,required:!0}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,value:x.email,onChange:e=>S(t=>({...t,email:e.target.value})),placeholder:`Enter email address`,disabled:l,required:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(G,{htmlFor:`password`,children:[`Password `,d&&`(leave blank to keep current)`]}),(0,Z.jsx)(q,{id:`password`,type:`password`,value:x.password,onChange:e=>S(t=>({...t,password:e.target.value})),placeholder:d?`Leave blank to keep current`:`Enter password`,disabled:l,required:!d}),!d&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:[`Must satisfy: `,E()]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`userType`,children:`User Type`}),(0,Z.jsxs)(`select`,{id:`userType`,value:x.userType,onChange:e=>S(t=>({...t,userType:e.target.value})),disabled:l,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`user`,children:`User`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admin`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`status`,children:`Status`}),(0,Z.jsxs)(`select`,{id:`status`,value:x.status,onChange:e=>S(t=>({...t,status:e.target.value})),disabled:l,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending`}),(0,Z.jsx)(`option`,{value:`deleted`,children:`Deleted`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:l,className:`flex-1`,children:l?`Processing...`:d?`Update User`:`Create User`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:ee,disabled:l,children:`Cancel`})]})]})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function Rj(){let e=yD(),{showToast:t}=wo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(``),f=du()?.userType===`admin`,p=(0,X.useCallback)(()=>tj().then(e=>{r(e),d((e.allowHosts||[]).join(`, `)),l(null)}).catch(e=>l(e instanceof Error?e.message:`Failed to load server defaults`)).finally(()=>a(!1)),[]);(0,X.useEffect)(()=>{p()},[p]);let m=()=>{a(!0),p()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(sw,{onBack:e,compact:!0,className:`mb-6`,title:`Server search & AI defaults`,description:`Entire server · Set the embedding defaults accounts inherit. Account and workspace overrides take priority. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:m,disabled:i,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),!f&&(0,Z.jsxs)(`div`,{className:`mb-4 flex items-start gap-2 rounded-md border p-3 text-xs`,children:[(0,Z.jsx)(ha,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Read-only. Changing server defaults requires an admin account. This is what your workspaces inherit.`})]}),i?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):c||!n?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Server defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:c||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:m,children:`Retry`})]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Config file: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n.configPath})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Endpoint allowlist`}),(0,Z.jsx)(`p`,{className:`mb-2 mt-1 text-[11px] text-muted-foreground`,children:`Provider URLs are fetched by the server, so they are an SSRF surface. Link-local and cloud-metadata targets are always refused; list additional hosts here to permit them. Comma-separated, empty = only the always-blocked ranges apply.`}),(0,Z.jsx)(q,{value:u,disabled:!f,onChange:e=>d(e.target.value),placeholder:`gpu.internal, embeddings.example.com`,className:`h-8 text-sm`})]}),(0,Z.jsx)(yj,{value:n.serverDefaults||{},effective:n.serverDefaults||{},inherited:{},saving:o,disabled:!f,saveLabel:`Save server defaults`,onSave:async e=>{s(!0);try{let n=u.split(`,`).map(e=>e.trim()).filter(Boolean),r=await nj({...e,...n.length?{allowHosts:n}:{}});t({title:`Server defaults saved`,description:`Written to ${r.configPath}. Every user inherits these, so running workspaces keep their current tables until restarted.`}),await p()}catch(e){t({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save`,variant:`destructive`})}finally{s(!1)}}},JSON.stringify(n.serverDefaults))]})]})}function zj(){return J.get(no.admin.authConfig)}function Bj(e){return J.put(no.admin.authConfig,e)}function Vj(e,t,n){return J.post(`${no.admin.authConfig}/test`,{strategy:`ldap`,name:e,server:t,email:n})}function Hj(e,t,n){return J.post(`${no.admin.authConfig}/test`,{strategy:`imap`,domain:e,email:t,password:n})}var Uj=0,Wj=()=>`row-${++Uj}`;function Gj(e){let{servers:t,...n}=e.strategies.ldap,{domains:r,...i}=e.strategies.imap;return{allowUserRegistrations:e.allowUserRegistrations,local:e.strategies.local,ldap:{...n,servers:Object.entries(t).map(([e,t])=>({...t,id:Wj(),name:e,originalName:e}))},imap:{...i,domains:Object.entries(r).map(([e,t])=>({...t,id:Wj(),domain:e}))},google:e.strategies.google??{enabled:!1,defaultUserType:`user`,defaultStatus:`active`,clientId:``,clientSecretSet:!1,allowedDomains:[],autoCreateUsers:!0,webOrigins:[]}}}function Kj(e){let{id:t,name:n,originalName:r,...i}=e;return{...i,...r&&r!==e.name?{previousName:r}:{}}}function qj(e){return{allowUserRegistrations:e.allowUserRegistrations,strategies:{local:e.local,ldap:{enabled:e.ldap.enabled,defaultUserType:e.ldap.defaultUserType,defaultStatus:e.ldap.defaultStatus,servers:Object.fromEntries(e.ldap.servers.map(e=>[e.name.trim(),Kj(e)]))},imap:{enabled:e.imap.enabled,defaultUserType:e.imap.defaultUserType,defaultStatus:e.imap.defaultStatus,domains:Object.fromEntries(e.imap.domains.map(({id:e,domain:t,...n})=>[t.trim().toLowerCase(),n]))},google:e.google}}}function Jj({value:e,onChange:t,placeholder:n,disabled:r}){let i=e.join(`, `),[a,o]=(0,X.useState)(i),[s,c]=(0,X.useState)(i);return i!==s&&(c(i),a.split(/[\s,]+/).filter(Boolean).join(`, `)!==i&&o(i)),(0,Z.jsx)(q,{className:`h-8 text-sm`,value:a,placeholder:n,disabled:r,onChange:e=>{o(e.target.value),t(e.target.value.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean))}})}var Yj={originalName:null,url:`ldap://`,bindDN:``,bindPasswordSet:!1,bindPassword:void 0,searchBase:``,searchFilter:`(mail={{email}})`,attributes:[`mail`,`cn`,`displayName`,`memberOf`],groupAttribute:`memberOf`,tls:!1},Xj={domain:``,name:``,host:``,port:993,secure:!0,startTLS:!1,requireAppPassword:!1},Zj=`h-8 rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50`;function Qj({label:e,hint:t,children:n,className:r}){return(0,Z.jsxs)(`label`,{className:K(`flex min-w-0 flex-col gap-1`,r),children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:e}),n,t&&(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:t})]})}function $j({checked:e,onChange:t,disabled:n,label:r,hint:i}){return(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:e,disabled:n,onChange:e=>t(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[r,i&&(0,Z.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:i})]})]})}function eM({title:e,description:t,enabled:n,onToggle:r,disabled:i,children:a}){return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:t})]}),r&&(0,Z.jsxs)(`label`,{className:`flex shrink-0 items-center gap-2 text-xs font-medium`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:!!n,disabled:i,onChange:e=>r(e.target.checked)}),n?`Enabled`:`Disabled`]})]}),(0,Z.jsx)(`div`,{className:K(`mt-4 space-y-4`,r&&!n&&`opacity-60`),children:a})]})}function tM({result:e}){return e?(0,Z.jsxs)(`div`,{className:K(`flex items-start gap-2 rounded-md border p-2 text-xs`,e.ok?`border-emerald-500/40 bg-emerald-500/5`:`border-destructive/40 bg-destructive/5`),children:[e.ok?(0,Z.jsx)(Sr,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600`}):(0,Z.jsx)(Bn,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`p`,{children:e.message}),e.user&&e.user.groups.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 break-all text-muted-foreground`,children:[`Groups: `,e.user.groups.join(` · `)]})]})]}):null}function nM({value:e,onChange:t,disabled:n}){return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,Z.jsx)(Qj,{label:`New accounts are`,children:(0,Z.jsxs)(`select`,{className:Zj,value:e.defaultUserType,disabled:n,onChange:e=>t({defaultUserType:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`user`,children:`Users`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admins`})]})}),(0,Z.jsx)(Qj,{label:`Initial status`,children:(0,Z.jsxs)(`select`,{className:Zj,value:e.defaultStatus,disabled:n,onChange:e=>t({defaultStatus:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`active`,children:`Active — can sign in right away`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending — an admin activates them`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`})]})})]}),e.defaultUserType===`admin`&&(0,Z.jsxs)(`p`,{className:`flex items-start gap-1.5 text-[11px] text-destructive`,children:[(0,Z.jsx)(ha,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),`Everyone who can sign in through this backend becomes a server admin on first login.`]})]})}function rM({row:e,index:t,onChange:n,onRemove:r,disabled:i}){let[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),d=async()=>{c(!0),u(null);try{u(await Vj(e.originalName??e.name,Kj(e),a.trim()||void 0))}catch(e){u({ok:!1,message:e instanceof Error?e.message:`Test failed`})}finally{c(!1)}},f=e.bindPassword===null?`cleared on save`:typeof e.bindPassword==`string`?`replaced on save`:e.bindPasswordSet?`stored — leave empty to keep it`:`none set`;return(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0 text-[11px] text-muted-foreground`,children:[`#`,t+1]}),(0,Z.jsx)(q,{className:`h-8 max-w-[14rem] font-mono text-sm`,value:e.name,disabled:i,onChange:e=>n({name:e.target.value}),placeholder:`primary`,"aria-label":`Server name`}),(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:r,disabled:i,"aria-label":`Remove server`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)(Qj,{label:`Server URL`,hint:`ldap:// or ldaps://host:port`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.url,disabled:i,onChange:e=>n({url:e.target.value}),placeholder:`ldaps://dc1.example.com:636`})}),(0,Z.jsx)(Qj,{label:`Search base`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.searchBase,disabled:i,onChange:e=>n({searchBase:e.target.value}),placeholder:`ou=users,dc=example,dc=com`})}),(0,Z.jsx)(Qj,{label:`Bind DN`,hint:`Service account used to look users up. Empty = anonymous search.`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.bindDN,disabled:i,onChange:e=>n({bindDN:e.target.value}),placeholder:`cn=canvas,ou=services,dc=example,dc=com`})}),(0,Z.jsx)(Qj,{label:`Bind password`,hint:(0,Z.jsxs)(Z.Fragment,{children:[`Currently: `,f,e.bindPasswordSet&&e.bindPassword!==null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,disabled:i,onClick:()=>n({bindPassword:null}),children:`clear`})]})]}),children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`password`,autoComplete:`new-password`,value:typeof e.bindPassword==`string`?e.bindPassword:``,disabled:i,onChange:e=>n({bindPassword:e.target.value===``?void 0:e.target.value}),placeholder:e.bindPasswordSet&&e.bindPassword!==null?`••••••••`:``})}),(0,Z.jsx)(Qj,{label:`User search filter`,hint:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`font-mono`,children:`{{email}}`}),` is replaced by the address typed at sign-in.`]}),children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.searchFilter,disabled:i,onChange:e=>n({searchFilter:e.target.value})})}),(0,Z.jsx)(Qj,{label:`Group attribute`,hint:`Group memberships drive team workspace sharing.`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.groupAttribute,disabled:i,onChange:e=>n({groupAttribute:e.target.value}),placeholder:`memberOf`})}),(0,Z.jsx)(Qj,{label:`Attributes to read`,hint:`Comma-separated.`,className:`sm:col-span-2`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.attributes.join(`, `),disabled:i,onChange:e=>n({attributes:e.target.value.split(`,`).map(e=>e.trim()).filter(Boolean)})})})]}),(0,Z.jsx)($j,{checked:e.tls,disabled:i,onChange:e=>n({tls:e}),label:`Accept self-signed certificates`,hint:`Skips certificate verification for ldaps://. Only for directories with a private CA.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-end gap-2 border-t pt-3`,children:[(0,Z.jsx)(Qj,{label:`Test`,hint:`Binds with the settings above (unsaved edits included). Add an e-mail to also look that user up.`,className:`min-w-[14rem] flex-1`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`email`,value:a,onChange:e=>o(e.target.value),placeholder:`someone@example.com (optional)`})}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:d,disabled:s||i,className:`mb-5`,children:[s&&(0,Z.jsx)(Ti,{className:`mr-2 h-3.5 w-3.5 animate-spin`}),`Test connection`]})]}),(0,Z.jsx)(tM,{result:l})]})}function iM({row:e,onChange:t,onRemove:n,disabled:r}){let[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`@`}),(0,Z.jsx)(q,{className:`h-8 max-w-[16rem] font-mono text-sm`,value:e.domain,disabled:r,onChange:e=>t({domain:e.target.value}),placeholder:`example.com`,"aria-label":`E-mail domain`}),(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:n,disabled:r,"aria-label":`Remove domain`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[1fr_6rem_1fr]`,children:[(0,Z.jsx)(Qj,{label:`IMAP host`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.host,disabled:r,onChange:e=>t({host:e.target.value}),placeholder:`imap.example.com`})}),(0,Z.jsx)(Qj,{label:`Port`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`number`,min:1,max:65535,value:e.port,disabled:r,onChange:e=>t({port:Number(e.target.value)})})}),(0,Z.jsx)(Qj,{label:`Label on the sign-in form`,hint:`Optional.`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,value:e.name,disabled:r,onChange:e=>t({name:e.target.value}),placeholder:`Example Mail`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-2`,children:[(0,Z.jsx)($j,{checked:e.secure,disabled:r,onChange:e=>t({secure:e,...e?{startTLS:!1}:{}}),label:`TLS from the start`,hint:`Usually port 993.`}),(0,Z.jsx)($j,{checked:e.startTLS,disabled:r||e.secure,onChange:e=>t({startTLS:e}),label:`Require STARTTLS`,hint:`Plain port 143 upgraded to TLS.`}),(0,Z.jsx)($j,{checked:e.requireAppPassword,disabled:r,onChange:e=>t({requireAppPassword:e}),label:`Needs an app password`,hint:`Shown as a hint on the sign-in form.`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-end gap-2 border-t pt-3`,children:[(0,Z.jsx)(Qj,{label:`Test sign-in`,hint:`A real IMAP login with these credentials, logged straight out. Nothing is stored.`,className:`min-w-[12rem] flex-1`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`email`,value:i,onChange:e=>a(e.target.value),placeholder:`someone@${e.domain||`example.com`}`})}),(0,Z.jsx)(Qj,{label:`Password`,className:`mb-5 min-w-[10rem] flex-1`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`password`,autoComplete:`off`,value:o,onChange:e=>s(e.target.value)})}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:async()=>{l(!0),d(null);try{let{id:t,domain:n,...r}=e;d(await Hj(r,i.trim(),o))}catch(e){d({ok:!1,message:e instanceof Error?e.message:`Test failed`})}finally{l(!1),s(``)}},disabled:c||r||!i||!o,className:`mb-5`,children:[c&&(0,Z.jsx)(Ti,{className:`mr-2 h-3.5 w-3.5 animate-spin`}),`Test`]})]}),(0,Z.jsx)(tM,{result:u})]})}function aM(){let e=yD(),{showToast:t}=wo(),n=du()?.userType===`admin`,[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),_=(0,X.useCallback)(()=>zj().then(e=>{let t=Gj(e.config);i(e.configPath),o(t),c(t),m(null)}).catch(e=>m(e instanceof Error?e.message:`Failed to load auth configuration`)).finally(()=>u(!1)),[]);(0,X.useEffect)(()=>{n&&_()},[n,_]);let v=(0,X.useMemo)(()=>!!s&&!!a&&JSON.stringify(qj(s))!==JSON.stringify(qj(a)),[s,a]),y=e=>c(t=>t&&e(t)),b=(e,t)=>y(n=>({...n,ldap:{...n.ldap,servers:n.ldap.servers.map(n=>n.id===e?{...n,...t}:n)}})),x=(e,t)=>y(n=>({...n,imap:{...n.imap,domains:n.imap.domains.map(n=>n.id===e?{...n,...t}:n)}})),S=async()=>{if(!s)return;let e=s.ldap.servers.map(e=>e.name.trim()),n=s.imap.domains.map(e=>e.domain.trim().toLowerCase());if(e.some(e=>!e)||new Set(e).size!==e.length){g(`Every LDAP server needs a unique name.`);return}if(n.some(e=>!e)||new Set(n).size!==n.length){g(`Every IMAP domain must be filled in and listed once.`);return}f(!0),g(null);try{let e=Gj((await Bj(qj(s))).config);o(e),c(e),t({title:`Authentication settings saved`,description:`Applied immediately — the next sign-in uses them.`})}catch(e){g(e instanceof Error?e.message.replace(/^HTTP \d+:\s*/,``):`Failed to save`)}finally{f(!1)}},C=(0,Z.jsx)(sw,{onBack:e,compact:!0,className:`mb-6`,title:`Authentication`,description:`Entire server · Choose how people sign in: local passwords, your LDAP directory, or their mail server over IMAP.`,actions:n&&(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{u(!0),_()},disabled:l||d,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Reload`]})});return n?(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6 pb-24`,children:[C,l&&!s?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):p||!s?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Authentication settings unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:p||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{u(!0),_()},children:`Retry`})]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Config file: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r}),` · Sign-in picks the backend from the account: existing users keep the method they were created with; a new address tries LDAP first (when enabled), then IMAP for a listed domain, then local.`]}),(0,Z.jsxs)(eM,{title:`Sign-up & local passwords`,description:`Accounts whose password is stored on this server.`,children:[(0,Z.jsx)($j,{checked:s.allowUserRegistrations,onChange:e=>y(t=>({...t,allowUserRegistrations:e})),label:`Allow self-registration`,hint:`Off = only admins create accounts (and LDAP/IMAP users on first sign-in).`}),(0,Z.jsx)($j,{checked:s.local.enabled,onChange:e=>y(t=>({...t,local:{...t.local,enabled:e}})),label:`Local password accounts`,hint:`Off refuses new local registrations. Existing local accounts — admins included — can still sign in, so this cannot lock you out.`}),(0,Z.jsx)($j,{checked:s.local.requireEmailVerification,onChange:e=>y(t=>({...t,local:{...t.local,requireEmailVerification:e}})),label:`Require e-mail verification`,hint:`Needs working SMTP (config/smtp.json).`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-xs font-medium`,children:`Password policy`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start gap-4`,children:[(0,Z.jsx)(Qj,{label:`Min length`,children:(0,Z.jsx)(q,{className:`h-8 w-24 text-sm`,type:`number`,min:1,max:1024,value:s.local.passwordPolicy.minLength,onChange:e=>y(t=>({...t,local:{...t.local,passwordPolicy:{...t.local.passwordPolicy,minLength:Number(e.target.value)}}}))})}),(0,Z.jsx)(Qj,{label:`Max length`,children:(0,Z.jsx)(q,{className:`h-8 w-24 text-sm`,type:`number`,min:1,max:1024,value:s.local.passwordPolicy.maxLength,onChange:e=>y(t=>({...t,local:{...t.local,passwordPolicy:{...t.local.passwordPolicy,maxLength:Number(e.target.value)}}}))})}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-x-6 gap-y-1 pt-1`,children:[[`requireUppercase`,`Uppercase letter`],[`requireLowercase`,`Lowercase letter`],[`requireNumbers`,`Number`],[`requireSpecialChars`,`Special character`]].map(([e,t])=>(0,Z.jsx)($j,{checked:s.local.passwordPolicy[e],label:t,onChange:t=>y(n=>({...n,local:{...n.local,passwordPolicy:{...n.local.passwordPolicy,[e]:t}}}))},e))})]})]})]}),(0,Z.jsxs)(eM,{title:`LDAP / Active Directory`,description:`Users sign in with their directory password. Servers are tried in order, so later ones act as fallbacks.`,enabled:s.ldap.enabled,onToggle:e=>y(t=>({...t,ldap:{...t.ldap,enabled:e}})),children:[(0,Z.jsx)(nM,{value:s.ldap,onChange:e=>y(t=>({...t,ldap:{...t.ldap,...e}}))}),s.ldap.servers.map((e,t)=>(0,Z.jsx)(rM,{row:e,index:t,onChange:t=>b(e.id,t),onRemove:()=>y(t=>({...t,ldap:{...t.ldap,servers:t.ldap.servers.filter(t=>t.id!==e.id)}}))},e.id)),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>y(e=>({...e,ldap:{...e.ldap,servers:[...e.ldap.servers,{...Yj,id:Wj(),name:e.ldap.servers.length?`server${e.ldap.servers.length+1}`:`primary`}]}})),children:[(0,Z.jsx)(br,{className:`mr-2 h-3.5 w-3.5`}),` Add LDAP server`]})]}),(0,Z.jsxs)(eM,{title:`IMAP (mail server sign-in)`,description:`Users of a listed e-mail domain sign in with their mailbox password — the server checks it by logging in to IMAP.`,enabled:s.imap.enabled,onToggle:e=>y(t=>({...t,imap:{...t.imap,enabled:e}})),children:[(0,Z.jsx)(nM,{value:s.imap,onChange:e=>y(t=>({...t,imap:{...t.imap,...e}}))}),s.imap.domains.map(e=>(0,Z.jsx)(iM,{row:e,onChange:t=>x(e.id,t),onRemove:()=>y(t=>({...t,imap:{...t.imap,domains:t.imap.domains.filter(t=>t.id!==e.id)}}))},e.id)),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>y(e=>({...e,imap:{...e.imap,domains:[...e.imap.domains,{...Xj,id:Wj()}]}})),children:[(0,Z.jsx)(br,{className:`mr-2 h-3.5 w-3.5`}),` Add mail domain`]})]}),(0,Z.jsxs)(eM,{title:`Google sign-in`,description:(0,Z.jsxs)(Z.Fragment,{children:[`One-click sign-in with a Google account via OAuth. Needs a Google Cloud OAuth client of type `,(0,Z.jsx)(`em`,{children:`Web application`}),` whose authorized redirect URI is `,(0,Z.jsx)(`code`,{className:`select-all`,children:`${yo}/oauth/google/callback`}),`.`]}),enabled:s.google.enabled,onToggle:e=>y(t=>({...t,google:{...t.google,enabled:e}})),children:[(0,Z.jsx)(nM,{value:s.google,onChange:e=>y(t=>({...t,google:{...t.google,...e}}))}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)(Qj,{label:`OAuth client id`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:s.google.clientId,autoComplete:`off`,onChange:e=>y(t=>({...t,google:{...t.google,clientId:e.target.value}}))})}),(0,Z.jsx)(Qj,{label:`OAuth client secret`,hint:s.google.clientSecretSet&&s.google.clientSecret===void 0?`A secret is stored; leave blank to keep it.`:void 0,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,type:`password`,autoComplete:`off`,value:s.google.clientSecret??``,placeholder:s.google.clientSecretSet?`••••••••`:``,onChange:e=>y(t=>({...t,google:{...t.google,clientSecret:e.target.value===``?void 0:e.target.value}}))})}),(0,Z.jsx)(Qj,{label:`Allowed e-mail domains`,hint:`Comma separated. Empty = any Google account may sign in.`,children:(0,Z.jsx)(Jj,{value:s.google.allowedDomains,placeholder:`example.com, example.org`,onChange:e=>y(t=>({...t,google:{...t.google,allowedDomains:e}}))})}),(0,Z.jsx)(Qj,{label:`Extra web origins`,hint:`Only when the web UI is served from another origin than the API (e.g. a Vite dev server).`,children:(0,Z.jsx)(Jj,{value:s.google.webOrigins,placeholder:`http://localhost:5173`,onChange:e=>y(t=>({...t,google:{...t.google,webOrigins:e}}))})})]}),(0,Z.jsx)($j,{checked:s.google.autoCreateUsers,label:`Create an account on first sign-in`,hint:`Off: only users that already exist (by e-mail) can sign in with Google.`,onChange:e=>y(t=>({...t,google:{...t.google,autoCreateUsers:e}}))})]}),(v||h)&&(0,Z.jsxs)(`div`,{className:`sticky bottom-4 z-10 rounded-lg border bg-card p-3 shadow-elevation-4`,children:[h&&(0,Z.jsx)(`ul`,{className:`mb-2 space-y-0.5 text-xs text-destructive`,children:h.split(`; `).map(e=>(0,Z.jsx)(`li`,{children:e},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,Z.jsx)(`span`,{className:`mr-auto text-xs text-muted-foreground`,children:v?`Unsaved changes`:``}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:d,onClick:()=>{c(a),g(null)},children:`Discard`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,disabled:d||!v,onClick:()=>void S(),children:[d&&(0,Z.jsx)(Ti,{className:`mr-2 h-3.5 w-3.5 animate-spin`}),`Save`]})]})]})]})]}):(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[C,(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-md border p-3 text-xs`,children:[(0,Z.jsx)(ha,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Authentication settings are only available to server admins.`})]})]})}function oM({agent:e,onStart:t,onStop:n,onEnter:r}){let[i,a]=(0,X.useState)(!1),o=async()=>{a(!0);try{await t(e.name)}finally{a(!1)}},s=async()=>{a(!0);try{await n(e.name)}finally{a(!1)}},c=()=>{switch(e.status){case`active`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-success`});case`inactive`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-warning`});case`error`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-destructive`});default:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-muted-foreground`})}},l=()=>{switch(e.llmProvider){case`anthropic`:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-warning`});case`openai`:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-success`});case`ollama`:return(0,Z.jsx)(lr,{className:`h-4 w-4 text-info`});default:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-muted-foreground`})}},u=()=>{switch(e.status){case`active`:return`text-success bg-success-subtle border-success`;case`inactive`:return`text-warning bg-warning-subtle border-warning`;case`error`:return`text-destructive bg-destructive-subtle border-destructive`;case`available`:return`text-info bg-info-subtle border-info`;default:return`text-foreground bg-muted border-border`}},d=e.status===`available`||e.status===`inactive`,f=e.status===`active`;return(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 hover:shadow-elevation-2 transition-shadow bg-card`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[l(),(0,Z.jsx)(`h3`,{className:`text-lg font-semibold truncate`,children:e.label||e.name}),e.color&&(0,Z.jsx)(`div`,{className:`w-4 h-4 rounded border flex-shrink-0`,style:{backgroundColor:e.color},title:`Color: ${e.color}`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground font-mono`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[c(),(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs font-medium border ${u()}`,children:e.status})]})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Provider:`}),(0,Z.jsx)(`div`,{className:`font-medium capitalize`,children:e.llmProvider})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Model:`}),(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.model})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Created:`}),(0,Z.jsx)(`div`,{children:new Date(e.createdAt).toLocaleDateString()})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Last Access:`}),(0,Z.jsx)(`div`,{children:e.lastAccessed?new Date(e.lastAccessed).toLocaleDateString():`Never`})]})]}),e.config.mcp?.servers&&e.config.mcp.servers.length>0&&(0,Z.jsxs)(`div`,{className:`text-sm`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`MCP Servers:`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-1`,children:e.config.mcp.servers.map((e,t)=>(0,Z.jsx)(`span`,{className:`px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs`,children:e.name},t))})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-2 border-t`,children:[d&&(0,Z.jsxs)(Y,{onClick:o,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)(Ar,{className:`mr-2 h-4 w-4`}),`Start`]}),f&&(0,Z.jsxs)(Y,{onClick:s,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)(Sa,{className:`mr-2 h-4 w-4`}),`Stop`]}),(0,Z.jsxs)(Y,{onClick:()=>r(e.name),size:`sm`,className:`flex-1`,children:[(0,Z.jsx)(Ea,{className:`mr-2 h-4 w-4`}),`Chat`]})]})]})}function sM(){let e={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`},t={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`},[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(on()),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(`anthropic`),[v,y]=(0,X.useState)(t.anthropic),[b,x]=(0,X.useState)({apiKey:``,baseUrl:e.anthropic,maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(!1),E=aw(),[D,O]=hw(),{showToast:k}=wo(),A=ft(),j=Cw();fw(j,`agent`,{"agent:status:changed":e=>{r(t=>t.map(t=>t.id===e.agentId?{...t,status:e.status,isActive:e.isActive}:t))},"agent:created":e=>{r(t=>[...t,e.agent])},"agent:deleted":e=>{r(t=>t.filter(t=>t.id!==e.agentId))}});let M=n=>{_(n),y(t[n]),x({apiKey:``,baseUrl:e[n],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096})};(0,X.useEffect)(()=>((async()=>{try{a(!0);let e=await ZD();r(e),s(null)}catch(e){console.error(`Agent fetch error:`,e);let t=`Failed to fetch agents`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch agents`}s(t),k({title:`Error`,description:t,variant:`destructive`})}finally{a(!1)}})(),()=>{}),[j,k]);let N=async t=>{if(t.preventDefault(),c.trim()){T(!0);try{let t=await cO({name:c,label:m||c,description:u||void 0,color:f,llmProvider:g,model:v,config:{type:g,model:v,prompts:S?{system:S}:void 0,connectors:{[g]:{...b,...b.apiKey?{apiKey:b.apiKey}:{},...b.baseUrl?{baseUrl:b.baseUrl}:{},maxTokens:b.maxTokens,temperature:b.temperature,topP:b.topP,frequencyPenalty:b.frequencyPenalty,presencePenalty:b.presencePenalty,...g===`ollama`?{numCtx:b.numCtx}:{}}}},mcp:{enabled:!0,servers:[{name:`weather`,command:`node`,args:[`src/managers/agent/mcp-servers/weather.js`]}]}});r(e=>[...e,t]),l(``),d(``),p(on()),h(``),C(``),x({apiKey:``,baseUrl:e[g],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),k({title:`Success`,description:`Agent '${t.label||t.name}' created.`}),O(!1)}catch(e){console.error(`Agent creation error:`,e);let t=`Failed to create agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create agent`}k({title:`Error`,description:t,variant:`destructive`})}finally{T(!1)}}},P=async e=>{try{let t=await dO(e);r(e=>e.map(e=>e.name===t.name?t:e)),k({title:`Success`,description:`Agent '${t.label||t.name}' started.`})}catch(e){console.error(`Agent start error:`,e);let t=`Failed to start agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start agent`}k({title:`Error`,description:t,variant:`destructive`})}},ee=async e=>{try{await fO(e),r(t=>t.map(t=>t.name===e?{...t,status:`inactive`,isActive:!1}:t)),k({title:`Success`,description:`Agent '${e}' stopped.`})}catch(e){console.error(`Agent stop error:`,e);let t=`Failed to stop agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop agent`}k({title:`Error`,description:t,variant:`destructive`})}},F=e=>{A(`/agents/${e}`)};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`AI Agents`,description:`Create and manage your AI agents with multiple LLM providers`,actions:!E.local&&!D&&(0,Z.jsxs)(Y,{onClick:()=>O(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create agent`,title:`Create agent`,children:[(0,Z.jsx)(br,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Agent`})]})}),!E.local&&D&&(0,Z.jsx)(pw,{title:`Create New Agent`,onClose:()=>O(!1),children:(0,Z.jsxs)(`form`,{onSubmit:N,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Agent Name (e.g., 'my-assistant')`,disabled:w}),(0,Z.jsx)(q,{value:m,onChange:e=>h(e.target.value),placeholder:`Agent Label (display name, optional)`,disabled:w})]}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),placeholder:`Description (optional)`,disabled:w}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-provider`,className:`text-sm font-medium`,children:`LLM Provider`}),(0,Z.jsxs)(`select`,{id:`agent-provider`,value:g,onChange:e=>M(e.target.value),className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring`,disabled:w,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-model`,className:`text-sm font-medium`,children:`Model`}),(0,Z.jsx)(q,{id:`agent-model`,value:v,onChange:e=>y(e.target.value),placeholder:`Model name (e.g., 'gpt-4o')`,disabled:w})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`system-prompt`,className:`text-sm font-medium`,children:`System Prompt (Optional)`}),(0,Z.jsx)(`textarea`,{id:`system-prompt`,value:S,onChange:e=>C(e.target.value),placeholder:`Enter system prompt to define agent behavior...`,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-h-[80px] resize-y`,disabled:w})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`api-key`,className:`text-sm font-medium`,children:`API Key (Optional)`}),(0,Z.jsx)(q,{id:`api-key`,type:`password`,value:b.apiKey,onChange:e=>x(t=>({...t,apiKey:e.target.value})),placeholder:`Enter your API key`,disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`text-sm font-medium`,children:`Base URL (Optional)`}),(0,Z.jsx)(q,{id:`baseUrl`,value:b.baseUrl,onChange:e=>x(t=>({...t,baseUrl:e.target.value})),placeholder:e[g],disabled:w})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`LLM Parameters`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2 lg:grid-cols-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`max-tokens`,className:`text-sm font-medium`,children:`Max Tokens`}),(0,Z.jsx)(q,{id:`max-tokens`,type:`number`,min:`1`,max:`32768`,value:b.maxTokens,onChange:e=>x(t=>({...t,maxTokens:parseInt(e.target.value)||4096})),disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`temperature`,className:`text-sm font-medium`,children:`Temperature`}),(0,Z.jsx)(q,{id:`temperature`,type:`number`,min:`0`,max:`2`,step:`0.1`,value:b.temperature,onChange:e=>x(t=>({...t,temperature:parseFloat(e.target.value)||.7})),disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`top-p`,className:`text-sm font-medium`,children:`Top P`}),(0,Z.jsx)(q,{id:`top-p`,type:`number`,min:`0`,max:`1`,step:`0.1`,value:b.topP,onChange:e=>x(t=>({...t,topP:parseFloat(e.target.value)||1})),disabled:w})]}),g===`ollama`&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`num-ctx`,className:`text-sm font-medium`,children:`Context Length`}),(0,Z.jsx)(q,{id:`num-ctx`,type:`number`,min:`1024`,max:`32768`,value:b.numCtx,onChange:e=>x(t=>({...t,numCtx:parseInt(e.target.value)||4096})),disabled:w})]})]}),g!==`ollama`&&(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`frequency-penalty`,className:`text-sm font-medium`,children:`Frequency Penalty`}),(0,Z.jsx)(q,{id:`frequency-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.frequencyPenalty,onChange:e=>x(t=>({...t,frequencyPenalty:parseFloat(e.target.value)||0})),disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`presence-penalty`,className:`text-sm font-medium`,children:`Presence Penalty`}),(0,Z.jsx)(q,{id:`presence-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.presencePenalty,onChange:e=>x(t=>({...t,presencePenalty:parseFloat(e.target.value)||0})),disabled:w})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`agent-color`,className:`text-sm font-medium`,children:`Agent Color`}),(0,Z.jsx)(q,{id:`agent-color`,type:`color`,value:f,onChange:e=>p(e.target.value),className:`h-10 w-16 p-1`,disabled:w}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>p(on()),disabled:w,children:`Randomize`})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:w||!c.trim(),children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Agent`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Agents`}),i&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading agents...`}),o&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:o})}),!i&&!o&&n.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No agents found`}),n.length>0&&(0,Z.jsx)(`div`,{className:`grid gap-4`,children:n.map(e=>(0,Z.jsx)(oM,{agent:e,onStart:P,onStop:ee,onEnter:F},e.id))})]})]})}function cM(e){let t=e?.usage;if(!t)return null;let n=t.totalTokens,r=t.input,i=t.output;return typeof n==`number`&&typeof r==`number`&&typeof i==`number`?`${n} tok (${r} in / ${i} out)`:typeof n==`number`?`${n} tok`:null}function lM(e){let t=e?.usage?.cost?.total;return typeof t==`number`?`$${t.toFixed(t<.01?6:4)}`:null}function uM({reasoning:e,metadata:t,isStreaming:n=!1,compact:r=!1}){let i=t?.model,a=[t?.provider,i,cM(t),lM(t)].filter(Boolean);return!e&&a.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[e&&(0,Z.jsxs)(`details`,{open:n,className:`mb-2 rounded border border-border bg-background ${r?`px-2 py-1.5`:`px-3 py-2`}`,children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer font-medium text-foreground ${r?`text-[11px]`:`text-xs`}`,children:`Reasoning`}),(0,Z.jsx)(F,{content:e,className:`mt-1 text-foreground ${r?`text-[11px]`:`text-xs`}`})]}),a.length>0&&(0,Z.jsx)(`div`,{className:`mt-2 text-muted-foreground ${r?`text-[11px]`:`text-xs`}`,children:a.join(` • `)})]})}function dM({message:e,isStreaming:t=!1,connectionStatus:n=`disconnected`}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!0);(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=e.content,r=0,a=setInterval(()=>{r<n.length?(i(n.substring(0,r+1)),r++):clearInterval(a)},20);return()=>clearInterval(a)},[e.content,t,e.isComplete]);let s=t&&!e.isComplete?r:e.content;return(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=setInterval(()=>{o(e=>!e)},500);return()=>{clearInterval(n),o(!0)}},[t,e.isComplete]),(0,Z.jsx)(`div`,{className:`flex ${e.role===`user`?`justify-end`:`justify-start`}`,children:(0,Z.jsxs)(`div`,{className:`max-w-[70%] p-3 rounded-lg ${e.role===`user`?`bg-primary text-primary-foreground`:`bg-muted`} ${t&&!e.isComplete?`border-2 border-info`:``}`,children:[(0,Z.jsx)(uM,{reasoning:e.role===`assistant`?e.metadata?.reasoning?.trim():void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:t&&!e.isComplete}),(0,Z.jsxs)(`div`,{className:`text-sm`,children:[e.role===`assistant`?(0,Z.jsx)(F,{content:s}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap break-words`,children:s}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`inline-block w-2 ${a?`bg-current`:`bg-transparent`}`,children:`|`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-xs mt-2 opacity-70`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:new Date(e.timestamp).toLocaleTimeString()}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`text-info`,children:`• streaming...`})]}),e.role===`assistant`&&(()=>{switch(n){case`websocket`:return(0,Z.jsx)(`span`,{title:`WebSocket`,children:(0,Z.jsx)(Ja,{className:`h-3 w-3 text-success`})});case`sse`:return(0,Z.jsx)(`span`,{title:`Server-Sent Events`,children:(0,Z.jsx)($i,{className:`h-3 w-3 text-info`})});case`rest`:return(0,Z.jsx)(`span`,{title:`REST API`,children:(0,Z.jsx)(yi,{className:`h-3 w-3 text-warning`})});default:return(0,Z.jsx)(`span`,{title:`Disconnected`,children:(0,Z.jsx)(Hn,{className:`h-3 w-3 text-destructive`})})}})()]})]})})}var fM=(0,X.createContext)(null);function pM(e){let t=(0,X.useContext)(fM);if(!t)throw Error(`useAgentSessions must be used within an AgentSessionProvider`);let{getState:n,refresh:r,create:i,select:a,rename:o,remove:s}=t,c=n(e),l=(0,X.useCallback)(()=>r(e),[r,e]),u=(0,X.useCallback)(t=>i(e,t),[i,e]),d=(0,X.useCallback)(t=>a(e,t),[a,e]),f=(0,X.useCallback)((t,n)=>o(e,t,n),[o,e]),p=(0,X.useCallback)(t=>s(e,t),[s,e]);return(0,X.useMemo)(()=>({...c,refresh:l,create:u,select:d,rename:f,remove:p}),[c,l,u,d,f,p])}function mM(e={}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),s=(0,X.useRef)(e),c=(0,X.useRef)(null),l=(0,X.useRef)(!1);(0,X.useEffect)(()=>{s.current=e},[e]);let u=(0,X.useCallback)(()=>{if(!s.current.agentId||c.current||l.current)return;let e=localStorage.getItem(`authToken`);if(!e){console.warn(`No auth token available for WebSocket connection`);return}console.log(`[WebSocket] Using token type: ${e.startsWith(`canvas-`)?`API`:`JWT`}, length: ${e.length}`),l.current=!0,o(!0);let t=xo(no.ws,{auth:{token:e},transports:[`websocket`],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,timeout:1e4,forceNew:!0});t.on(`connect`,()=>{console.log(`Agent WebSocket connected successfully`),i(!0),l.current=!1,o(!1)}),t.on(`connect_error`,e=>{console.error(`Agent WebSocket connection error:`,e),i(!1),l.current=!1,o(!1),(e.message?.includes(`Auth error`)||e.message?.includes(`token`))&&console.warn(`WebSocket auth failed, will fallback to SSE for streaming`)}),t.on(`disconnect`,e=>{console.log(`Agent WebSocket disconnected:`,e),i(!1),l.current=!1,o(!1)}),t.on(`agent:chat:chunk`,e=>{console.log(`Received chat chunk:`,e),s.current.onMessage&&s.current.onMessage(e)}),t.on(`agent:chat:complete`,e=>{console.log(`Chat stream complete:`,e),s.current.onComplete&&s.current.onComplete(e.agentId,e.messageId,e.messages)}),t.on(`agent:chat:error`,e=>{console.error(`Chat stream error:`,e),s.current.onError&&s.current.onError(e)}),t.on(`agent:chat:start`,e=>{console.log(`Chat stream started:`,e)}),c.current=t,n(t)},[]),d=(0,X.useCallback)(()=>{let e=c.current;e&&(e.removeAllListeners(),e.close()),c.current=null,l.current=!1,n(null),i(!1),o(!1)},[]),f=(0,X.useCallback)(e=>{t&&r&&(console.log(`Subscribing to agent channel: ${e}`),t.emit(`agent:subscribe`,{agentId:e}))},[t,r]),p=(0,X.useCallback)(e=>{t&&r&&(console.log(`Unsubscribing from agent channel: ${e}`),t.emit(`agent:unsubscribe`,{agentId:e}))},[t,r]),m=(0,X.useCallback)((e,n)=>{if(!t||!r)throw Error(`WebSocket not connected`);let i=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return console.log(`Starting streaming chat for agent ${e}, message ${i}`),t.emit(`agent:chat:stream`,{agentId:e,messageId:i,...n}),i},[t,r]);return(0,X.useEffect)(()=>{if(e.agentId)return u(),()=>{d()}},[e.agentId,u,d]),(0,X.useEffect)(()=>{if(r&&e.agentId)return f(e.agentId),()=>{e.agentId&&p(e.agentId)}},[r,e.agentId,f,p]),{socket:t,isConnected:r,isConnecting:a,connect:u,disconnect:d,joinAgentChannel:f,leaveAgentChannel:p,startStreamingChat:m}}function hM(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
37
|
+
`)||``}function gM(e,t){return`${e||``}${t||``}`.trim()||void 0}function _M(e,t){if(!e&&!t)return;let{reasoningDelta:n,...r}=e||{};return{...r,...t?{reasoning:t}:{}}}function vM(e){let{agentId:t,initialMessages:n=[],historyKey:r,loadHistory:i=!0,onError:a,enableWebSocket:o=!0,enableSSE:s=!0,enableFallback:c=!0,llmProvider:l}=e,[u,d]=(0,X.useState)(gO(n)),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(`disconnected`),[v,y]=(0,X.useState)(null),b=(0,X.useRef)(n);(0,X.useEffect)(()=>{b.current=n});let x=`${t}${String(i)}${r??``}`,[S,C]=(0,X.useState)(x);S!==x&&(C(x),(!t||!i)&&d(gO(n))),(0,X.useEffect)(()=>{let e=!1;if(!(!t||!i))return $D(t).then(t=>{e||d(gO(t.messages))}).catch(()=>{e||d(gO(b.current))}),()=>{e=!0}},[t,i,r]);let w=(0,X.useRef)(null),T=(0,X.useRef)(null),{isConnected:E,startStreamingChat:D}=mM({agentId:o?t:void 0,onMessage:j,onComplete:M,onError:N}),O=o&&E,[k,A]=(0,X.useState)(!1);k!==O&&(A(O),_(O?`websocket`:e=>e===`websocket`?`disconnected`:e));function j(e){e.messageId===T.current&&(console.log(`Processing WebSocket chunk:`,{type:e.type,content:e.content,delta:e.delta}),e.type===`content`||e.type===`chunk`?h(t=>t?{...t,content:t.content+(e.delta||e.content||``),isComplete:!1,metadata:t.metadata}:{role:`assistant`,content:e.delta||e.content||``,timestamp:new Date().toISOString(),isComplete:!1}):e.type===`thinking`?h(t=>{let n=gM(t?.metadata?.reasoning,e.delta);return t?{...t,metadata:{...t.metadata||{},...n?{reasoning:n}:{}}}:{role:`assistant`,content:``,timestamp:new Date().toISOString(),isComplete:!1,metadata:n?{reasoning:n}:void 0}}):(e.type===`complete`||e.type===`done`)&&h(e=>{if(e){let t={...e,isComplete:!0};return d(e=>[...e,t]),p(!1),T.current=null,null}return null}))}function M(e,t,n){if(t===T.current){let e=Array.isArray(n)?[...n].reverse().find(e=>e?.role===`assistant`):null,t=hM(e),r=VD(e);h(e=>{if(e){let n={...e,content:t||e.content,isComplete:!0,metadata:{...e.metadata||{},...r||{}}};d(e=>[...e,n])}else t&&d(e=>[...e,{role:`assistant`,content:t,timestamp:new Date().toISOString(),isComplete:!0,metadata:r}]);return null}),p(!1),T.current=null}}function N(e){e.messageId===T.current&&(console.error(`WebSocket streaming error:`,e),y(e.error),p(!1),T.current=null,a&&a(Error(e.error)))}let P=(0,X.useCallback)(async(e,n={})=>{if(f)throw Error(`Cannot send message while streaming`);y(null);let r={role:`user`,content:e||(n.images?.length?`[${n.images.length} image${n.images.length===1?``:`s`} attached]`:``),timestamp:new Date().toISOString(),isComplete:!0};d(e=>[...e,r]),p(!0);let i={message:e,images:n.images,context:u.slice(-10),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature},m=Array.isArray(n.images)&&n.images.length>0,g=o&&E&&l!==`ollama`&&!m,v=s;if(l===`ollama`&&console.log(`🦙 Ollama detected: Using SSE streaming (WebSocket not supported by Ollama)`),g)try{console.log(`🔌 Attempting WebSocket streaming for ${l||`unknown`} provider...`);let e=D(t,i);T.current=e,_(`websocket`);return}catch(e){console.warn(`WebSocket streaming failed for ${l||`unknown`}, falling back to SSE:`,e)}if(v){let e=!1;try{console.log(`📡 ${l===`ollama`?`Using`:`Attempting`} SSE streaming for ${l||`unknown`} provider...`),_(`sse`),w.current=new AbortController;let r=``;await mO(t,i.message,{onStart:()=>{e=!0},onMessage:(e,t,n)=>{r+=e;let i=typeof n?.reasoningDelta==`string`?n.reasoningDelta:``;if(h(e=>{let a=n?.reasoning||gM(e?.metadata?.reasoning,i);return{role:`assistant`,content:r,timestamp:e?.timestamp||new Date().toISOString(),isComplete:t,metadata:_M({...e?.metadata||{},...n},a)}}),t){let e=n?.reasoning;d(t=>[...t,{role:`assistant`,content:r,timestamp:new Date().toISOString(),isComplete:!0,metadata:_M(n,e)}]),h(null),p(!1)}},onError:e=>{console.error(`SSE streaming error:`,e),y(e.message),p(!1),a&&a(e)},context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),images:n.images,mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature});return}catch(t){if(e){console.warn(`SSE stream failed after server accepted prompt for ${l||`unknown`}; refusing REST fallback to avoid duplicate prompt.`);return}console.warn(`SSE streaming failed for ${l||`unknown`}, falling back to REST:`,t)}}if(c)try{console.log(`⚙️ Using REST API fallback for ${l||`unknown`} provider...`),_(`rest`);let r=await hO(t,{message:e,images:n.images,context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature}),i={role:`assistant`,content:r.content,timestamp:new Date().toISOString(),isComplete:!0,metadata:r.metadata};d(e=>[...e,i]),p(!1)}catch(e){console.error(`All chat methods failed:`,e);let t=e instanceof Error?e.message:`Failed to send message`;y(t),p(!1),a&&a(e instanceof Error?e:Error(t))}else y(`All streaming methods failed and fallback is disabled`),p(!1)},[t,u,f,E,D,o,s,c,l,a]),ee=(0,X.useCallback)(()=>{d([]),h(null),y(null)},[]),F=(0,X.useCallback)(()=>{w.current&&=(w.current.abort(),null),T.current=null,p(!1),h(null)},[]);return(0,X.useEffect)(()=>()=>{w.current&&w.current.abort()},[]),{messages:u,isStreaming:f,currentStreamingMessage:m,connectionStatus:g,error:v,sendMessage:P,clearMessages:ee,stopStreaming:F,allMessages:m?[...u,m]:u,isWebSocketConnected:g===`websocket`,isUsingSSE:g===`sse`,isUsingREST:g===`rest`}}function yM(e){let{sessions:t,create:n}=pM(e),r=(t?.sessions.length??0)>0;return{hasSession:r,ensureSession:async()=>r?null:n({mode:`persistent`})}}async function bM(e){let t=await new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let[,e=``]=(typeof r.result==`string`?r.result:``).split(`,`,2);t(e)},r.onerror=()=>n(r.error||Error(`Failed to read image`)),r.readAsDataURL(e)});return{id:`${e.name}-${e.size}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:`image`,data:t,mimeType:e.type||`image/png`,name:e.name}}function xM(e){return String(e||``).trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}function SM({agentId:e,routeAgentId:t,initialMessages:n,llmProvider:r,sessionKey:i}){let{showToast:a}=wo(),{hasSession:o,ensureSession:s}=yM(e),c=ft(),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)([]),{allMessages:h,isStreaming:g,currentStreamingMessage:_,connectionStatus:v,error:y,sendMessage:b,clearMessages:x,stopStreaming:S}=vM({agentId:e,initialMessages:n,historyKey:i,loadHistory:!1,llmProvider:r,enableWebSocket:!1,onError:e=>{a({title:`Chat Error`,description:e.message,variant:`destructive`})}});return(0,X.useEffect)(()=>{l.current?.scrollIntoView({behavior:`smooth`})},[h,_]),(0,X.useEffect)(()=>{g||u.current?.focus()},[g,i]),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between border-b px-4 py-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Chat`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session conversation`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:v}),h.length>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:x,disabled:g,className:`text-destructive hover:underline disabled:opacity-50`,children:`Clear visible chat`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-4`,children:[h.length===0?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(Ea,{className:`mx-auto mb-4 h-10 w-10 opacity-40`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:o?`No messages yet.`:`No session yet.`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs`,children:o?`Send a message to start the conversation.`:`Type a message to auto-create a session, or pick one in the Sessions panel.`})]})}):h.map((e,t)=>(0,Z.jsx)(dM,{message:e,isStreaming:g&&e===_,connectionStatus:v},`${e.timestamp}-${t}`)),y&&(0,Z.jsx)(`div`,{className:`rounded-lg bg-destructive/10 p-3 text-sm text-destructive`,children:y}),(0,Z.jsx)(`div`,{ref:l})]}),(0,Z.jsxs)(`div`,{className:`border-t p-4`,children:[p.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2`,children:p.map(e=>(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-md border bg-muted/20`,children:[(0,Z.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:e.name||`Pasted image`,className:`h-16 w-16 object-cover`}),(0,Z.jsx)(`div`,{className:`max-w-16 truncate px-2 py-1 text-[10px] text-muted-foreground`,children:e.name||e.mimeType}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(t=>t.filter(t=>t.id!==e.id)),className:`absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:text-foreground`,title:`Remove image`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]},e.id))}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{e.preventDefault();let n=d.trim();if(!(!n&&p.length===0)){f(``);try{let e=await s();e?.current.sessionId&&c(`/agents/${encodeURIComponent(t)}/${encodeURIComponent(e.current.sessionId)}`,{replace:!0}),await b(n,{images:p.map(({id:e,...t})=>t)}),m([])}catch(e){a({title:`Chat Error`,description:e instanceof Error?e.message:`Failed to send message`,variant:`destructive`})}}},className:`flex gap-2`,children:[(0,Z.jsx)(`textarea`,{ref:u,value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())},onPaste:async e=>{let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!e);if(t.length!==0)try{let e=await Promise.all(t.map(bM));m(t=>[...t,...e])}catch(e){a({title:`Paste Error`,description:e instanceof Error?e.message:`Failed to read pasted image`,variant:`destructive`})}},placeholder:g?`Streaming in progress...`:o?`Type a message...`:`Type to start a new session…`,disabled:g,rows:2,className:`flex min-h-10 flex-1 resize-y rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50`}),g?(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:S,children:`Stop`}):(0,Z.jsx)(Y,{type:`submit`,disabled:!d.trim()&&p.length===0,children:`Send`})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(zn,{className:`h-3.5 w-3.5`}),`Paste image files from clipboard directly into the input.`]})]})]})}function CM(){let{agentId:e,sessionId:t}=yt(),n=vn(),r=ft(),{showToast:i}=wo(),{selectEntity:a,goBack:o}=qC(),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),y=(0,X.useRef)(null),{current:b,sessions:x,refresh:S,select:C}=pM(e||``),w=(0,X.useMemo)(()=>x?.sessions?x.currentSessionId?x.sessions.find(e=>e.id===x.currentSessionId)||null:x.currentSessionPath?x.sessions.find(e=>e.path===x.currentSessionPath)||null:x.sessions.find(e=>e.isCurrent)||null:null,[x]),T=[b?.mode||`persistent`,b?.sessionId||b?.sessionFile||`initial`].join(`:`);return(0,X.useEffect)(()=>{e&&(async()=>{u(!0);try{let i=await QD(e);a(i.id),c(i);let o=i.name||i.id;if(o&&decodeURIComponent(e)!==o){let e=n.pathname.endsWith(`/settings`)?`/agents/${encodeURIComponent(o)}/settings`:t?`/agents/${encodeURIComponent(o)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(o)}`;r(e,{replace:!0})}await S(),g(null)}catch(e){let t=e instanceof Error?e.message:`Failed to load agent`;g(t),i({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}})()},[e,t,n.pathname,r,S,a,i]),(0,X.useEffect)(()=>{if(!e||!t||!x)return;let n=decodeURIComponent(t),r=xM(n),a=x.sessions.find(e=>e.id===n||e.slug===n||xM(e.name)===r),o=!!(a&&(x.currentSessionId===a.id||x.currentSessionPath===a.path||b?.sessionId===a.id||b?.sessionFile===a.path)),s=b?.sessionId===n||x.currentSessionId===n;if(b?.mode===`persistent`&&o){y.current=null;return}if(!a){b?.mode===`persistent`&&s&&(y.current=null);return}y.current!==a.id&&(y.current=a.id,C({mode:`persistent`,sessionId:a.id}).catch(e=>{i({title:`Session Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}).finally(()=>{y.current===a.id&&(y.current=null)}))},[e,t,x,b?.mode,b?.sessionId,b?.sessionFile,C,i]),(0,X.useEffect)(()=>{if(!e)return;let t=async()=>{try{let t=await pO(e);c(e=>e?{...e,isActive:t.isActive,status:t.status,lastAccessed:t.lastAccessed}:null)}catch{}};t();let n=setInterval(t,5e3);return()=>clearInterval(n)},[e]),l?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-muted-foreground`,children:[(0,Z.jsx)(Nr,{className:`mx-auto mb-3 h-8 w-8 animate-pulse`}),(0,Z.jsx)(`p`,{children:`Loading agent...`})]})}):!s||h?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-destructive`,children:[(0,Z.jsx)(Nr,{className:`mx-auto mb-3 h-8 w-8`}),(0,Z.jsx)(`p`,{children:h||`Agent not found`})]})}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Z.jsx)(lw,{title:`Back to previous view`,onBack:o}),(0,Z.jsx)(`span`,{className:`h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:s.color||`#9ca3af`}}),(0,Z.jsx)(`h1`,{className:`truncate text-xl font-semibold`,children:s.label||s.name}),(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:s.status})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate text-sm text-muted-foreground`,children:s.description||`${s.llmProvider} / ${s.model}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s.isActive?(0,Z.jsxs)(Y,{variant:`outline`,onClick:async()=>{if(e){m(!0);try{let t=await fO(e);c(t),i({title:`Stopped`,description:`${t.label||t.name} is inactive`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to stop agent`,variant:`destructive`})}finally{m(!1)}}},disabled:p,children:[(0,Z.jsx)(Sa,{className:`mr-2 h-4 w-4`}),p?`Stopping...`:`Stop`]}):(0,Z.jsxs)(Y,{onClick:async()=>{if(e){f(!0);try{let t=await dO(e);c(t),i({title:`Started`,description:`${t.label||t.name} is active`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to start agent`,variant:`destructive`})}finally{f(!1)}}},disabled:d,children:[(0,Z.jsx)(Ar,{className:`mr-2 h-4 w-4`}),d?`Starting...`:`Start`]}),(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>{a(s.id),r(`/agents/${encodeURIComponent(s.name||s.id)}/settings/identity`)},children:[(0,Z.jsx)(Wi,{className:`mr-2 h-4 w-4`}),`Settings`]}),(0,Z.jsx)(cw,{className:`h-9 w-9`})]})]}),(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-cols-1 gap-4 grid-rows-[minmax(0,1fr)_auto] xl:grid-rows-none xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]`,children:[(0,Z.jsx)(SM,{agentId:s.id,routeAgentId:s.name||s.id,initialMessages:b?.messages||[],llmProvider:s.llmProvider,sessionKey:T},T),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),"aria-expanded":_,className:K(`flex w-full items-center justify-between gap-2 px-4 py-3 text-left xl:pointer-events-none`,_?`border-b`:`xl:border-b`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Contextual Information`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session and runtime state.`})]}),(0,Z.jsx)(qr,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform xl:hidden`,_&&`rotate-180`)})]}),(0,Z.jsxs)(`div`,{className:K(`space-y-4 overflow-y-auto p-4 text-sm max-xl:max-h-viewport-half`,!_&&`max-xl:hidden`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Mode`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.mode||x?.mode||`persistent`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Selected Session`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all`,children:w?.name||(w?.isExperimental?`Experimental`:null)||b?.sessionId||`Default session`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Known Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:x?.sessions.length||0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Thinking Level`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.thinkingLevel||`high`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Model`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.model?.modelId||s.model||`Not set`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Session File`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all text-xs text-muted-foreground`,children:b?.sessionFile||`In-memory / not persisted yet`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-muted/20 p-4 text-sm text-muted-foreground`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 font-medium text-foreground`,children:[(0,Z.jsx)(yi,{className:`h-4 w-4`}),`Shape`]}),(0,Z.jsx)(`p`,{children:`Session selection lives in M2. Main content stays focused on the active conversation and its context.`})]})]})]})]})]})}var wM={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`,"lm-studio":``,vllm:``,custom:``},TM={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`,"lm-studio":`http://localhost:1234/v1`,vllm:`http://localhost:8000/v1`,custom:``};function EM(e){return TM[e]||``}function DM(e,t,n){return[e.trim()?`## Role\n${e.trim()}`:``,t.trim()?`## Identity\n${t.trim()}`:``,n.trim()?`## Instructions\n${n.trim()}`:``].filter(Boolean).join(`
|
|
38
|
+
|
|
39
|
+
`)}function OM({label:e,hint:t,children:n}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:e}),t&&(0,Z.jsx)(`p`,{className:`mb-1 mt-0.5 text-xs text-muted-foreground`,children:t}),(0,Z.jsx)(`div`,{className:t?void 0:`mt-1`,children:n})]})}var kM=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-y`,AM=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`;function jM(){let{agentId:e,tab:t}=yt(),n=ft(),{showToast:r}=wo(),{selectEntity:i,goBack:a}=qC(),o=De(),s=FD(t);(0,X.useEffect)(()=>{t!==s&&e&&n(`/agents/${encodeURIComponent(e)}/settings/${s}`,{replace:!0})},[t,s,e,n]);let[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(on()),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(``),[M,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)(`anthropic`),[F,I]=(0,X.useState)(``),[te,L]=(0,X.useState)(``),[R,ne]=(0,X.useState)(``),[re,ie]=(0,X.useState)(.7),[ae,z]=(0,X.useState)(4096),[oe,se]=(0,X.useState)(1),[B,ce]=(0,X.useState)([]),[V,le]=(0,X.useState)(``),[ue,de]=(0,X.useState)(``),[fe,pe]=(0,X.useState)(``),[me,he]=(0,X.useState)(``),[ge,_e]=(0,X.useState)(!1),[ve,ye]=(0,X.useState)(null),[be,xe]=(0,X.useState)(null),[H,Se]=(0,X.useState)(null),[Ce,U]=(0,X.useState)(!1),[W,we]=(0,X.useState)(null),[Te,Ee]=(0,X.useState)(`context`),[Oe,ke]=(0,X.useState)(``),[Ae,je]=(0,X.useState)(`/`),[Me,Ne]=(0,X.useState)(``),[Pe,Fe]=(0,X.useState)(!0),[Ie,Le]=(0,X.useState)(!1),[Re,ze]=(0,X.useState)([]),[Be,Ve]=(0,X.useState)([]),[He,Ue]=(0,X.useState)(null),[We,Ge]=(0,X.useState)(`{}`),[Ke,G]=(0,X.useState)(null),[qe,Je]=(0,X.useState)(e);qe!==e&&(Je(e),d(!0),l(null)),(0,X.useEffect)(()=>{if(!e)return;let t=!1;return QD(e).then(async e=>{if(t)return;let n=e.config?.identity||{};l(e),i(e.id),y(e.name||``),x(e.label||``),C(e.description||``),T(e.color||on()),D(n.role||``),k(n.identity||``),j(n.instructions||``),N(e.config?.prompts?.system||``),ee(e.llmProvider||`anthropic`),I(e.config?.apiKey||``),L(e.config?.baseUrl||EM(e.llmProvider)),ne(e.model||wM[e.llmProvider]||``);let r=e.config?.connectors?.[e.llmProvider];r&&(ie(r.temperature??.7),z(r.maxTokens??4096),se(r.topP??1)),Ge(JSON.stringify(e.config?.tools??{},null,2)),G(null),p(null);try{ce(await aO(e.id))}catch{ce([])}}).catch(e=>{t||p(e instanceof Error?e.message:`Failed to load agent`)}).finally(()=>{t||d(!1)}),()=>{t=!0}},[e,i]),(0,X.useEffect)(()=>{if(s!==`access`&&s!==`tools`||!c?.id)return;let e=c.id,t=!1;return Promise.all([KD(c.id).catch(()=>null),Uo().catch(()=>[]),ml().catch(()=>[]),XD(c.id).catch(()=>null)]).then(([n,r,i,a])=>{t||(xe(n),ze(r),Ve(i),Ue(a?a.tools:[]),n&&(Ee(n.binding.type),ke(n.binding.workspace||``),je(n.binding.path||`/`),Ne(n.binding.context||``),Fe(n.permissions.includes(`read`)),Le(n.permissions.includes(`write`))),Se(e))}),()=>{t=!0}},[s,c?.id]);let Ye=()=>{let e=DM(E,O,A),t;try{let e=JSON.parse(We);e&&typeof e==`object`&&!Array.isArray(e)&&(t=e)}catch{}return{...t===void 0?{}:{tools:t},name:v.trim(),label:b.trim(),description:S.trim()||void 0,color:w,llmProvider:P,model:R,apiKey:F||void 0,baseUrl:te||void 0,config:{type:P,model:R,identity:{role:E.trim()||void 0,identity:O.trim()||void 0,instructions:A.trim()||void 0},prompts:M.trim()||e?{system:M.trim()||e}:void 0,connectors:{[P]:{temperature:re,maxTokens:ae,topP:oe}}}}},Xe=async e=>{if(e.preventDefault(),c){h(!0);try{let e=await lO(c.id,Ye());l(e),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Saved`,description:`Agent updated`}),e.name&&e.name!==c.name&&n(`/agents/${encodeURIComponent(e.name)}/settings/${s}`,{replace:!0})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{h(!1)}}},Ze=async()=>{if(c&&window.confirm(`Delete agent "${c.label||c.name}"? This cannot be undone.`)){_(!0);try{await uO(c.id),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Deleted`,description:`Agent removed`}),n(`/agents`)}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{_(!1)}}},Qe=()=>{le(``),de(``),pe(``),he(``)},$e=async()=>{if(!(!c||!me.trim()&&!fe.trim())){_e(!0);try{let e=await oO(c.id,me.trim()?{source:me.trim()}:{name:V,description:ue,content:fe});ce(e),Qe(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Installed`,description:`Skill saved`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill install failed`,variant:`destructive`})}finally{_e(!1)}}},et=async e=>{if(c){ye(e);try{let t=await sO(c.id,e);ce(t),(V===e||me===e)&&Qe(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Removed`,description:`Skill "${e}" removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill remove failed`,variant:`destructive`})}finally{ye(null)}}},tt=()=>Te===`global`?{type:`global`}:Te===`context`?Me?{type:`context`,context:Me}:null:Oe?Te===`path`?{type:`path`,workspace:Oe,path:Ae.trim()||`/`}:{type:`workspace`,workspace:Oe}:null,nt=async()=>{if(!c||Ce)return;let e=tt(),t=[];if(Pe&&t.push(`read`),Ie&&t.push(`write`),!e||t.length===0){r({title:`Invalid binding`,description:`Pick a scope target and at least one permission`,variant:`destructive`});return}if(!(e.type===`global`&&!window.confirm(`Global scope lets this agent ${Ie?`read and write`:`read`} ALL your workspaces. Continue?`))){U(!0);try{let n=await qD(c.id,{binding:e,permissions:t});xe(n.access),we(n.token),r({title:`Bound`,description:`Access bound — copy the token now, it is not shown again`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{U(!1)}}},rt=async()=>{if(!(!c||Ce)){U(!0);try{let e=await JD(c.id);xe(e.access),we(e.token),r({title:`Rotated`,description:`New token minted — the previous one no longer works`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Rotate failed`,variant:`destructive`})}finally{U(!1)}}},it=async()=>{if(!(!c||Ce)&&window.confirm(`Revoke this agent's canvas access? Its token stops working immediately.`)){U(!0);try{await YD(c.id),xe(null),we(null),r({title:`Revoked`,description:`Agent access removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Revoke failed`,variant:`destructive`})}finally{U(!1)}}},at=e=>{if(e.type===`global`)return`Global — all workspaces`;if(e.type===`context`){let t=Be.find(t=>t.id===e.context);return`Context ${t?`${t.id} (${t.url})`:e.context} — follows the context live`}let t=e.workspaceName||e.workspace;return e.type===`path`?`Workspace ${t}, path ${e.path||`/`}`:`Workspace ${t} (whole tree)`};if(u)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!c||f)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-destructive`,children:f||`Agent not found`});let ot=PD.find(e=>e.id===s),st=encodeURIComponent(c.name||c.id),ct=s===`identity`||s===`provider`||s===`models`||s===`tools`;return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${ot.label} - ${c.label||c.name}`,description:ot.description,backTo:`/agents/${st}`,onBack:o?a:void 0}),(0,Z.jsxs)(`form`,{onSubmit:Xe,className:`space-y-6`,children:[s===`identity`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(OM,{label:`Name`,hint:`ID: ${c.id}`,children:(0,Z.jsx)(q,{value:v,onChange:e=>y(e.target.value),placeholder:`lucy`})}),(0,Z.jsx)(OM,{label:`Label`,children:(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),placeholder:`Display name`})})]}),(0,Z.jsx)(OM,{label:`Description`,children:(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),placeholder:`Short description`})}),(0,Z.jsx)(OM,{label:`Color`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{type:`color`,value:w,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>T(on()),children:`Randomize`})]})})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Persona`}),(0,Z.jsx)(OM,{label:`Role`,children:(0,Z.jsx)(q,{value:E,onChange:e=>D(e.target.value),placeholder:`e.g. Software Engineer`})}),(0,Z.jsx)(OM,{label:`Identity`,children:(0,Z.jsx)(`textarea`,{value:O,onChange:e=>k(e.target.value),placeholder:`Who this agent is…`,className:`${kM} min-h-[80px]`})}),(0,Z.jsx)(OM,{label:`Instructions`,children:(0,Z.jsx)(`textarea`,{value:A,onChange:e=>j(e.target.value),placeholder:`Behavioral instructions…`,className:`${kM} min-h-[80px]`})}),(0,Z.jsx)(OM,{label:`System Prompt`,hint:`Compiled from Role + Identity + Instructions. Override manually.`,children:(0,Z.jsx)(`textarea`,{value:M,onChange:e=>N(e.target.value),placeholder:`System prompt sent to the LLM…`,className:`${kM} min-h-[140px] font-mono text-xs`})})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(Y,{type:`button`,variant:`destructive`,disabled:g,onClick:Ze,children:[(0,Z.jsx)(Qr,{className:`mr-2 h-4 w-4`}),g?`Deleting...`:`Delete Agent`]})]})]}),s===`provider`&&(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(OM,{label:`Provider`,children:(0,Z.jsxs)(`select`,{value:P,onChange:e=>{let t=e.target.value;ee(t),ne(wM[t]||``),L(EM(t))},className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`}),(0,Z.jsx)(`option`,{value:`lm-studio`,children:`LM Studio (Local)`}),(0,Z.jsx)(`option`,{value:`vllm`,children:`vLLM (Local)`}),(0,Z.jsx)(`option`,{value:`custom`,children:`Custom`})]})}),(0,Z.jsx)(OM,{label:`API Key`,hint:[`ollama`,`lm-studio`,`vllm`].includes(P)?`Any value works for local providers.`:void 0,children:(0,Z.jsx)(q,{type:`password`,value:F,onChange:e=>I(e.target.value),placeholder:P===`ollama`?`ollama`:P===`lm-studio`?`lm-studio`:`sk-…`})}),(0,Z.jsx)(OM,{label:`Host / Base URL`,children:(0,Z.jsx)(q,{value:te,onChange:e=>L(e.target.value),placeholder:EM(P)||`https://api.example.com`})})]}),s===`models`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Main Model`}),(0,Z.jsx)(OM,{label:`Model`,children:(0,Z.jsx)(q,{value:R,onChange:e=>ne(e.target.value),placeholder:`Model name`})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,Z.jsx)(OM,{label:`Temperature`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:2,step:.1,value:re,onChange:e=>ie(parseFloat(e.target.value)||.7)})}),(0,Z.jsx)(OM,{label:`Max Tokens`,children:(0,Z.jsx)(q,{type:`number`,min:1,max:2e5,value:ae,onChange:e=>z(parseInt(e.target.value)||4096)})}),(0,Z.jsx)(OM,{label:`Top P`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:1,step:.1,value:oe,onChange:e=>se(parseFloat(e.target.value)||1)})})]})]}),[`Governance`,`Memory Management`,`Subagent / Tool Use`].map(e=>(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:[e,` Model`]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Coming soon`})]},e))]}),s===`tools`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Runtime Tools`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Injected at start (pi defineTool): coding tools plus canvas tools scoped by the token binding (Access / ACL). Definitions live in the runtime — read-only here until the agent-runtime workspace lands.`})]}),He===null?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}):He.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No tools resolved.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:He.map(e=>(0,Z.jsxs)(`details`,{className:`rounded-md border px-3 py-2`,children:[(0,Z.jsxs)(`summary`,{className:`cursor-pointer text-sm`,children:[(0,Z.jsx)(`code`,{className:`font-mono text-xs font-medium`,children:e.name}),(0,Z.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:e.source})]}),e.description&&(0,Z.jsx)(`p`,{className:`mt-2 whitespace-pre-wrap text-xs text-muted-foreground`,children:e.description}),e.parameters!=null&&(0,Z.jsx)(`pre`,{className:`mt-2 overflow-x-auto rounded bg-muted p-2 font-mono text-[11px]`,children:JSON.stringify(e.parameters,null,2)})]},e.name))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:be?at(be.binding):`Unbound — no canvas tools are injected. Bind under Access / ACL.`})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Tools Config`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`config.tools JSON, merged server-side — e.g. {"canvas": {"enabled": false}} gates the canvas tools. Saved with Save Changes.`})]}),(0,Z.jsx)(`textarea`,{value:We,onChange:e=>{Ge(e.target.value);try{JSON.parse(e.target.value),G(null)}catch(e){G(e instanceof Error?e.message:`Invalid JSON`)}},className:`${kM} min-h-[120px] font-mono text-xs`}),Ke&&(0,Z.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Invalid JSON (not saved): `,Ke]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Skills`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Installed skills are saved immediately, independent of Save Changes.`})]}),B.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No skills installed.`}):B.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.name}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.package?e.source:e.description||`No description`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{le(e.name),de(e.description||``),pe(e.content||``),he(e.source||``)},children:`Edit`}),(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,disabled:ve===(e.source||e.name),onClick:()=>et(e.source||e.name),children:ve===(e.source||e.name)?`Removing…`:`Remove`})]})]},e.name)),(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-md border p-4`,children:[(0,Z.jsx)(OM,{label:`Package Source`,hint:`Use this for whole pi packages. Leave empty to save inline SKILL.md content.`,children:(0,Z.jsx)(q,{value:me,onChange:e=>he(e.target.value),placeholder:`npm:@foo/pi-tools or git:github.com/badlogic/pi-doom`})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(OM,{label:`Name`,children:(0,Z.jsx)(q,{value:V,onChange:e=>le(e.target.value),placeholder:`skill-name, or read from frontmatter`,disabled:!!me.trim()})}),(0,Z.jsx)(OM,{label:`Description`,children:(0,Z.jsx)(q,{value:ue,onChange:e=>de(e.target.value),placeholder:`What this skill helps with`,disabled:!!me.trim()})})]}),(0,Z.jsx)(OM,{label:`SKILL.md Content`,children:(0,Z.jsx)(`textarea`,{value:fe,onChange:e=>pe(e.target.value),placeholder:`# Skill instructions…`,disabled:!!me.trim(),className:`${kM} min-h-[160px] font-mono text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,disabled:ge||!me.trim()&&!fe.trim(),onClick:$e,children:ge?`Saving…`:`Install / Update Skill`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:Qe,children:`Clear`})]})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`MCP Servers`}),(c.config?.mcp?.servers||[]).length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No MCP servers configured.`}):(c.config?.mcp?.servers||[]).map((e,t)=>(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),(0,Z.jsxs)(`div`,{className:`font-mono text-xs text-muted-foreground`,children:[e.command,` `,(e.args||[]).join(` `)]})]},t))]})]}),s===`access`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Canvas Access`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The agent talks to canvas through its own scoped token; the server clamps every request to the binding. Bind, rotate and revoke apply immediately.`})]}),H===c.id?be?(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:at(be.binding)}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Permissions: `,be.permissions.join(`, `)||`none`,be.boundAt?` · bound ${new Date(be.boundAt).toLocaleString()}`:``,be.rotatedAt?` · token rotated ${new Date(be.rotatedAt).toLocaleString()}`:``]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-1`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:Ce,onClick:rt,children:`Rotate Token`}),(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,disabled:Ce,onClick:it,children:`Revoke Access`})]})]}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Unbound — this agent has no canvas access.`}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}),W&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border border-warning/50 bg-warning/10 p-3`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium`,children:`Agent token — shown once, store it now`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`code`,{className:`flex-1 truncate rounded bg-background px-2 py-1 font-mono text-xs`,children:W}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>navigator.clipboard?.writeText(W),children:`Copy`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>we(null),children:`Dismiss`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`In-process agents receive it automatically (canvas.env); external runtimes (agentd) take it as CANVAS_TOKEN.`})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:be?`Rebind`:`Bind`}),(0,Z.jsx)(OM,{label:`Scope`,hint:`Context bindings follow the context live; global spans all workspaces.`,children:(0,Z.jsxs)(`select`,{value:Te,onChange:e=>Ee(e.target.value),className:AM,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context (follows live)`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`path`,children:`Workspace path`}),(0,Z.jsx)(`option`,{value:`global`,children:`Global (all workspaces)`})]})}),Te===`context`&&(0,Z.jsx)(OM,{label:`Context`,children:(0,Z.jsxs)(`select`,{value:Me,onChange:e=>Ne(e.target.value),className:AM,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a context…`}),Be.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,` — `,e.url]},e.id))]})}),(Te===`workspace`||Te===`path`)&&(0,Z.jsx)(OM,{label:`Workspace`,children:(0,Z.jsxs)(`select`,{value:Oe,onChange:e=>ke(e.target.value),className:AM,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a workspace…`}),Re.map(e=>(0,Z.jsx)(`option`,{value:e.name||e.id,children:e.label||e.name},e.id))]})}),Te===`path`&&(0,Z.jsx)(OM,{label:`Base path`,hint:`The agent is clamped to this subtree.`,children:(0,Z.jsx)(q,{value:Ae,onChange:e=>je(e.target.value),placeholder:`/work/projects/foo`})}),(0,Z.jsx)(OM,{label:`Permissions`,children:(0,Z.jsxs)(`div`,{className:`flex gap-4 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Pe,onChange:e=>Fe(e.target.checked)}),` read`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Ie,onChange:e=>Le(e.target.checked)}),` write`]})]})}),(0,Z.jsx)(Y,{type:`button`,disabled:Ce,onClick:nt,children:Ce?`Working…`:be?`Rebind & Mint Token`:`Bind & Mint Token`})]})]}),s===`memory`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Memory Engine`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Loop-based memory management. Settings coming soon.`})]}),s===`integrations`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Integrations`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`IMAP, chat, SQL and REST API accounts. Coming soon.`})]}),ct&&(0,Z.jsx)(Y,{type:`submit`,disabled:m,children:m?`Saving…`:`Save Changes`})]})]})})}var MM=`workspace:backups`,NM=e=>`${no.workspaces}/${encodeURIComponent(e)}/db/backups`,PM=e=>J.get(NM(e)),FM=e=>J.post(NM(e),{action:`backup`}),IM=(e,t)=>J.post(NM(e),{action:`restore`,backupId:t,confirm:!0}),LM=new Map;function RM(e,t,n){let r=JSON.stringify([t,n.id]),i=LM.get(r);if(i)return i;let a=(async()=>{let r=n.action===`restore`,i=e({title:r?`Restoring workspace database`:`Backing up workspace database`,description:r?`Stopping the workspace and preserving its current database…`:`Copying and verifying all datasets…`});try{let e=n;for(;e.status===`running`;){let n=await PM(t),r=n.jobs.find(t=>t.id===e.id);if(!r)throw Error(`The server restarted. Refresh the backup list to check the result.`);e=r,window.dispatchEvent(new CustomEvent(MM,{detail:{workspace:t,status:n}})),e.status===`running`&&await new Promise(e=>setTimeout(e,1500))}if(e.status===`failed`)throw Error(e.error||`Database operation failed`);i.done({title:r?`Workspace database restored`:`Workspace backup verified`,description:r?`The workspace is stopped. Start it when you are ready; search indexes will rebuild.`:`Documents, relations and virtual tree placements are saved.`})}catch(e){throw i.fail({title:`Workspace backup needs attention`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}})();return LM.set(r,a),a.finally(()=>LM.delete(r)).catch(()=>{}),a}var zM={startup:`Startup`,hourly:`Hourly`,manual:`Manual`,"pre-restore":`Before restore`};function BM({workspaceId:e,onRestored:t}){let{showToast:n,showProgress:r}=wo(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),f=(0,X.useRef)(!1),p=(0,X.useRef)(!1),m=(0,X.useRef)(0),h=(0,X.useCallback)(()=>{let t=++m.current;return PM(e).then(n=>{if(!(!f.current||t!==m.current)){a(n),s(null);for(let t of n.jobs.filter(e=>e.status===`running`))RM(r,e,t).catch(()=>{})}}).catch(e=>{f.current&&t===m.current&&s(e instanceof Error?e.message:String(e))})},[e,r]);(0,X.useEffect)(()=>{f.current=!0,h();let t=t=>{let n=t.detail;n.workspace===e&&a(n.status)};return window.addEventListener(MM,t),()=>{f.current=!1,window.removeEventListener(MM,t)}},[e,h]);let g=async i=>{if(!p.current){p.current=!0,d(!0);try{let n=i?await IM(e,i.id):await FM(e);f.current&&a(e=>e&&{...e,jobs:[n,...e.jobs]}),await RM(r,e,n),i&&t()}catch(e){n({title:`Database operation did not complete`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{p.current=!1,f.current&&(d(!1),h())}}},_=u||!!i?.jobs.some(e=>e.status===`running`),v=i?.jobs[0];return(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-5`,children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(ra,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`font-semibold`,children:`Workspace checkpoints`}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,className:`ml-auto`,disabled:_||!i||!!o,onClick:()=>void g(),children:[_?(0,Z.jsx)(Ti,{className:`mr-2 h-4 w-4 animate-spin`}):(0,Z.jsx)(ra,{className:`mr-2 h-4 w-4`}),`Back up now`]})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Save a checkpoint before a bulk action. Each backup includes every document, relation and virtual tree placement in this workspace’s database.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-5 gap-y-2 text-sm`,children:[(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:i?.retention.hourly??24}),` hourly backups`]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:i?.retention.startup??14}),` startup backups`]}),(0,Z.jsx)(`span`,{children:`Manual checkpoints kept`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Hourly backups run while the workspace is active. These checkpoints cover the database only; files in storage backends and workspace settings need their own backups.`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Verified checkpoints`,i?` · ${i.backups.length}`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,onClick:()=>void h(),"aria-label":`Refresh backups`,children:(0,Z.jsx)(Er,{className:`h-4 w-4`})})]}),o&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:o}),v&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm ${v.status===`failed`?`text-destructive`:`text-muted-foreground`}`,children:v.status===`running`?`Database operation in progress…`:v.status===`failed`?v.error:v.action===`restore`?`Database restored. The workspace is stopped and ready to start.`:`Backup complete and verified.`}),!i&&!o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Loading backups…`}),i?.backups.length===0&&(0,Z.jsx)(`p`,{className:`rounded border border-dashed p-6 text-sm text-muted-foreground`,children:`No verified checkpoints yet. Create one before your next bulk action.`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:i?.backups.map(e=>(0,Z.jsxs)(`article`,{className:`flex min-w-0 flex-wrap items-center gap-3 rounded border p-3`,children:[(0,Z.jsx)(sr,{className:`h-4 w-4 shrink-0 text-muted-foreground`,"aria-label":`Verified`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:new Date(e.createdAt).toLocaleString()}),(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[zM[e.kind],` · `,Ts(e.bytes),` · `,(e.datasets.documents?.count??0).toLocaleString(),` documents`]})]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:_,onClick:()=>l(e),children:[(0,Z.jsx)(Vr,{className:`mr-2 h-3.5 w-3.5`}),`Restore`]})]},e.id))}),(0,Z.jsx)(vo,{open:!!c,onOpenChange:e=>{e||l(null)},children:(0,Z.jsxs)(lo,{className:`max-w-[calc(100vw-2rem)] sm:max-w-lg`,children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsx)(io,{children:`Restore this workspace checkpoint?`}),(0,Z.jsxs)(ro,{children:[`The workspace will stop and its current database will be backed up first. Documents, relations and virtual tree placements will return to `,c?new Date(c.createdAt).toLocaleString():`the selected checkpoint`,`. Files in storage backends and workspace settings will stay as they are. The workspace stays stopped after restoration.`]})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{disabled:_,onClick:()=>{c&&g(c)},children:`Back up current & restore`})]})]})})]})}var VM={collect:`Collect unused blobs`,verify:`Verify integrity`,compact:`Compact index`},HM=e=>e.status===`queued`||e.status===`running`,UM=e=>`${no.workspaces}/${encodeURIComponent(e)}/cache/maintenance`,WM=e=>J.get(UM(e)),GM=(e,t,n)=>J.post(UM(e),{store:t,action:n,...n===`verify`?{confirm:!0}:{}});function KM(e){if(e.status===`failed`)return e.error||`Maintenance failed`;if(e.status===`queued`)return`Waiting for active storage operations…`;if(e.status===`running`)return e.action===`verify`?`Reading and checking stored content…`:`Processing the cache index…`;let t=e.result||{};return e.action===`compact`?`${(t.compactedCount||0).toLocaleString()} keys compacted`:e.action===`verify`?`${(t.verifiedContent||0).toLocaleString()} blobs verified · ${(t.badContentCount||0).toLocaleString()} corrupted blobs removed · ${Ts(t.reclaimedSize||0)} reclaimed`:`${(t.reclaimedCount||0).toLocaleString()} unused blobs removed · ${Ts(t.reclaimedSize||0)} reclaimed`}var qM=new Map,JM=`workspace:cache-maintenance`;function YM(e,t,n){let r=JSON.stringify([t,n.id]),i=qM.get(r);if(i)return i;let a=(async()=>{let r=e({title:VM[n.action],description:`${n.store} · ${KM(n)}`});try{let e=n;for(;HM(e);){let i=await WM(t),a=i.jobs.find(e=>e.id===n.id);if(!a)throw Error(`Maintenance receipt is no longer available. The server may have restarted; refresh the cache settings.`);if(e=a,window.dispatchEvent(new CustomEvent(JM,{detail:{workspace:t,status:i}})),!HM(e))break;r.update({title:VM[e.action],description:`${e.store} · ${KM(e)}`}),await new Promise(e=>setTimeout(e,2e3))}if(e.status===`failed`)throw Error(KM(e));r.done({title:`${VM[e.action]} complete`,description:`${e.store} · ${KM(e)}`})}catch(e){throw r.fail({title:`Cache maintenance needs attention`,description:`${n.store} · ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return qM.set(r,a),a.finally(()=>{qM.get(r)===a&&qM.delete(r)}).catch(()=>{}),a}function XM({workspaceId:e,children:t}){let{showToast:n,showProgress:r}=wo(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(`workspace:cache`),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(!1),h=(0,X.useRef)(!1),g=(0,X.useCallback)(()=>WM(e).then(t=>{if(h.current){a(t),p(null);for(let n of t.jobs.filter(HM))YM(r,e,n).catch(()=>{})}}).catch(e=>{h.current&&p(e instanceof Error?e.message:`Cannot load maintenance status`)}),[e,r]);(0,X.useEffect)(()=>{h.current=!0,g();let t=t=>{let{workspace:n,status:r}=t.detail;n===e&&(a(r),p(null))};return window.addEventListener(JM,t),()=>{h.current=!1,window.removeEventListener(JM,t)}},[e,g]);let _=async t=>{if(!(m.current||i?.jobs.some(HM))){m.current=!0,l(!0);try{let n=await GM(e,o,t);h.current&&a(e=>e&&{...e,jobs:[n,...e.jobs.filter(e=>e.id!==n.id)]}),YM(r,e,n).catch(()=>{})}catch(e){n({title:`Could not start maintenance`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),g()}finally{m.current=!1,h.current&&l(!1)}}},v=c||!!i?.jobs.some(HM),y=i?.stores.find(e=>e.id===o),b=i?.jobs[0];return(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-(--panel-radius) border p-4`,"aria-label":`Workspace cache maintenance`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,Z.jsx)(Fa,{className:`h-4 w-4 shrink-0`}),`Workspace cache`]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Thumbnails, cached resources and pending transfers. Maintenance runs only when requested.`})]}),t&&(0,Z.jsx)(`fieldset`,{disabled:v,children:t})]}),(0,Z.jsxs)(`div`,{className:`space-y-3 border-t pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`cache-maintenance-store`,className:`text-xs font-medium`,children:`Store`}),(0,Z.jsxs)(`select`,{id:`cache-maintenance-store`,value:o,onChange:e=>s(e.target.value),disabled:v,className:`min-w-0 max-w-full rounded-md border bg-background px-2 py-1.5 text-xs`,children:[(0,Z.jsx)(`option`,{value:`workspace:cache`,children:`workspace:cache`}),(0,Z.jsx)(`option`,{value:`workspace:data`,children:`workspace:data`})]}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`icon`,onClick:()=>void g(),"aria-label":`Refresh cache maintenance status`,className:`ml-auto h-8 w-8`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:o===`workspace:data`?`Managed document blobs. Referenced content is kept during collection.`:`Working cache, including content awaiting transfer. Referenced content is kept during collection.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canCollect||!!f,onClick:()=>void _(`collect`),children:[(0,Z.jsx)(Qr,{className:`mr-2 h-3.5 w-3.5`}),`Collect unused blobs`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canCompact||!!f,onClick:()=>void _(`compact`),children:[(0,Z.jsx)(ra,{className:`mr-2 h-3.5 w-3.5`}),`Compact index`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canVerify||!!f,onClick:()=>d(!0),children:[(0,Z.jsx)(Fi,{className:`mr-2 h-3.5 w-3.5`}),`Verify integrity`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Collection removes unreferenced blobs. Compaction trims index history. Verification reads every blob and may remove corrupted content. Storage writes may wait during maintenance.`}),!i&&!f&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:`Loading maintenance status…`}),y&&!y.canCollect&&!y.canVerify&&!y.canCompact&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Update canvas-stored to enable maintenance for this store.`}),f&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,role:`alert`,children:f}),b&&(0,Z.jsxs)(`div`,{className:`rounded-md bg-muted/50 p-3 text-xs`,role:`status`,"aria-live":`polite`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 font-medium`,children:[HM(b)&&(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 animate-spin`}),VM[b.action],` · `,b.store]}),(0,Z.jsx)(`p`,{className:`mt-1 ${b.status===`failed`?`text-destructive`:`text-muted-foreground`}`,children:KM(b)}),(0,Z.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:b.finishedAt?`Finished ${new Date(b.finishedAt).toLocaleString()}`:`Requested ${new Date(b.createdAt).toLocaleString()}`})]})]}),(0,Z.jsx)(vo,{open:u,onOpenChange:d,children:(0,Z.jsxs)(lo,{className:`max-w-[calc(100vw-2rem)] sm:max-w-lg`,children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsxs)(io,{children:[`Verify `,o,`?`]}),(0,Z.jsx)(ro,{children:`This reads all stored content and can take a long time. Corrupted blobs and their index entries may be removed. Keep a recovery backup before running it. Storage writes may wait until it finishes.`})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{disabled:v,onClick:()=>void _(`verify`),children:`Verify and repair`})]})]})})]})}function ZM({workspaceId:e,backend:t,onSaved:n}){let r=t?.config||{},i=()=>({name:String(r.label||``),bucket:String(r.bucket||``),prefix:String(r.prefix||``),endpoint:String(r.endpoint||``),region:String(r.region||`us-east-1`),accessKeyId:``,secretAccessKey:``,sessionToken:``}),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(i),[l,u]=(0,X.useState)(r.forcePathStyle!==!1),[d,f]=(0,X.useState)(r.readOnly===!0),[p,m]=(0,X.useState)(r.watch===!0),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(!1),{showToast:y}=wo(),b=e=>({value:s[e],onChange:t=>c(n=>({...n,[e]:t.target.value}))});return a?(0,Z.jsxs)(`form`,{onSubmit:async r=>{r.preventDefault(),v(!0);try{let r={label:s.name.trim(),bucket:s.bucket.trim(),prefix:s.prefix.trim(),endpoint:s.endpoint.trim(),region:s.region.trim()||`us-east-1`,forcePathStyle:l,readOnly:d,watch:p,...Object.fromEntries([`accessKeyId`,`secretAccessKey`,`sessionToken`].flatMap(e=>{let t=s[e].trim();return t?[[e,t]]:[]})),...h?{sessionToken:``}:{}};t?await Fo(e,`s3`,t.address,r):await Zs(e,`s3`,r),o(!1),c(i()),y({title:t?`S3 backend updated`:`S3 backend added`,description:`Use Re-sync to check indexing progress, and filing policies to automate copies.`}),await n()}catch(e){y({title:`Could not connect S3`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{v(!1)}},className:`w-full space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,Z.jsx)(Fa,{className:`h-4 w-4`}),t?`Edit S3 connection`:`Add S3-compatible bucket`]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Amazon S3, MinIO, Garage, RustFS or Ceph RGW. Connect an existing bucket, optionally scoped to a prefix. Supports browsing, reads and filing copies; mirror policies and overwrites are unavailable.`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Name`,(0,Z.jsx)(q,{...b(`name`),required:!0,placeholder:`Accounting archive`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Bucket`,(0,Z.jsx)(q,{...b(`bucket`),disabled:!!t,required:!0,placeholder:`accounting`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Endpoint (blank for Amazon S3)`,(0,Z.jsx)(q,{...b(`endpoint`),disabled:!!t,type:`url`,placeholder:`https://s3.example.com`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Region`,(0,Z.jsx)(q,{...b(`region`),required:!0,placeholder:`us-east-1`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs sm:col-span-2`,children:[`Prefix (optional)`,(0,Z.jsx)(q,{...b(`prefix`),disabled:!!t,placeholder:`Augmentd/Accounting`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Access key ID`,(0,Z.jsx)(q,{...b(`accessKeyId`),required:!t,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Secret access key`,(0,Z.jsx)(q,{...b(`secretAccessKey`),type:`password`,required:!t,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs sm:col-span-2`,children:[`Session token (optional)`,(0,Z.jsx)(q,{...b(`sessionToken`),disabled:h,type:`password`,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),t&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:h,onChange:e=>g(e.target.checked)}),`Clear stored session token`]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),`Path-style addressing`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Read-only`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),`Poll for changes`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Writable connections test conflict protection using a temporary object, then delete it. The key needs list/read/write access and delete access under .canvas-probe/. Initial indexing reads file bytes; polling can incur request and download charges. Upload limit: 5 GiB per file.`}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,disabled:_,onClick:()=>{o(!1),c(i())},children:`Cancel`}),(0,Z.jsx)(Y,{disabled:_,children:_?`Checking connection…`:`Save connection`})]})]}):(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>{c(i()),u(r.forcePathStyle!==!1),f(r.readOnly===!0),m(r.watch===!0),g(!1),o(!0)},children:[t?(0,Z.jsx)(Lr,{className:`mr-2 h-3.5 w-3.5`}):(0,Z.jsx)(br,{className:`mr-2 h-3.5 w-3.5`}),t?`Edit S3 connection`:`Add S3 bucket`]})}function QM({workspaceId:e,isActive:t,currentMode:n,onChanged:r}){let[i,a]=(0,X.useState)(n===`workspace`?`workspace`:`secrets`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold text-sm`,children:`Workspace protection`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Protect service credentials with a PIN or password. Optionally require it to start the whole workspace. Files and document contents are not encrypted.`}),t&&(0,Z.jsx)(`p`,{className:`text-sm`,children:`Stop the workspace before changing protection.`}),(0,Z.jsxs)(`form`,{className:`space-y-3`,onSubmit:async t=>{if(t.preventDefault(),h(``),o!==c){h(`PIN/password confirmation does not match`);return}_(!0);try{let t=await J.put(`${no.workspaces}/${e}/protection`,{mode:i,passphrase:o,currentPassphrase:u||void 0});p(t.recoveryKey),s(``),l(``),d(``)}catch(e){h(e instanceof Error?e.message:`Could not save protection`)}finally{_(!1)}},children:[(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Protection mode`,(0,Z.jsxs)(`select`,{className:`block rounded border bg-background p-2 w-full`,value:i,onChange:e=>a(e.target.value),disabled:t||g,children:[(0,Z.jsx)(`option`,{value:`secrets`,children:`Secrets only — allow start without integrations`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Whole workspace — require PIN/password to start`})]})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Current PIN/password or recovery key (if already protected)`,(0,Z.jsx)(q,{type:`password`,autoComplete:`current-password`,value:u,onChange:e=>d(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`New PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,minLength:4,maxLength:1024,required:!0,value:o,onChange:e=>s(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Confirm new PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,required:!0,value:c,onChange:e=>l(e.target.value),disabled:t||g})]}),(0,Z.jsx)(Y,{disabled:t||g||!!f,children:g?`Saving…`:`Save protection`})]}),m&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:m}),f&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm`,children:`Save this recovery key now. It is shown only once and replaces any previous recovery key.`}),(0,Z.jsx)(`code`,{className:`block break-all select-all`,children:f}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>{p(``),r()},children:`I saved the recovery key`})]})]})}var $M=`h-8 rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`;function eN({title:e,hint:t,children:n}){let[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`overflow-hidden rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":r,className:`flex w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-muted/40`,children:[(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:e}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:t})]}),(0,Z.jsx)(qr,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none`,r&&`rotate-180`)})]}),r&&(0,Z.jsx)(`div`,{className:`border-t p-4`,children:n})]})}function tN({workspaceId:e,workspaceName:t,refreshKey:n,onRefresh:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),l=(0,X.useCallback)(()=>GA(e).then(e=>o(e.queue??null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{l();let e=window.setInterval(()=>{o(e=>(e&&(e.pending>0||e.draining)&&l(),e))},3e3);return()=>window.clearInterval(e)},[l,n]);let u=async()=>{if(a){c(!0);try{let e=await Oc(!a.paused,t);i({title:e.paused?`Embedding paused`:`Embedding resumed`,description:e.paused?`${e.pending.toLocaleString()} job(s) held for this workspace. Resume any time; a restart also resumes.`:`${e.pending.toLocaleString()} job(s) draining.`}),await l()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle the embedding queue (admin only)`,variant:`destructive`})}finally{c(!1)}}},d=!!a?.draining,f=a?a.paused?`bg-warning`:d?`bg-success`:`bg-muted-foreground/40`:`bg-muted-foreground/40`;return(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-lg border bg-muted/30 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`relative flex h-2 w-2 shrink-0`,"aria-hidden":!0,children:[d&&(0,Z.jsx)(`span`,{className:`absolute inline-flex h-full w-full animate-ping rounded-full bg-success opacity-60 motion-reduce:hidden`}),(0,Z.jsx)(`span`,{className:K(`relative inline-flex h-2 w-2 rounded-full`,f)})]}),(0,Z.jsx)(`span`,{className:`font-medium`,children:a?a.pending>0?(0,Z.jsxs)(Z.Fragment,{children:[a.pending.toLocaleString(),` `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`pending`})]}):a.paused?`Paused`:`Idle`:`Queue unavailable`}),a?.paused&&a.pending>0&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`held`}),a?.ingestDisabled&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,title:`CANVAS_INFERD_INGEST_DISABLED=true: nothing new is enqueued; existing vectors still serve search`,children:`ingest disabled`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[a&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s,onClick:u,title:a.paused?`Resume embedding; the held backlog drains`:`Pause after the current batch. Stops the CPU-heavy model inference; documents keep indexing and stay searchable by text.`,children:s?`…`:a.paused?`Resume`:`Pause`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:r,title:`Reload config, queue and tables`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})})]})]})}function nN({workspaceId:e,tables:t,error:n,onChanged:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(null),s=t.filter(e=>!e.active),c=async t=>{if(window.confirm(`Reclaim "${t.name}"?\n\nThis permanently deletes the vectors for ${t.model||`that model`} and its "already embedded" ledger. Switching back to it afterwards would cost a full re-embed rather than being instant.\n\nThis is the only irreversible step in the whole flow.`)){o(t.name);try{let n=await QA(e,t.name);if(!n.dropped)throw Error(n.error||`Failed to drop the vector table`);i({title:`Reclaimed`,description:`Dropped '${n.name||t.name}'.`}),r()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to reclaim`,variant:`destructive`})}finally{o(null)}}};return n?(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-destructive`,children:`Vector tables unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:n})]}):s.length===0?null:(0,Z.jsx)(eN,{title:`Previous models (${s.length})`,hint:`Kept on disk so switching back is instant. Reclaiming deletes their vectors for good (the only irreversible step here).`,children:(0,Z.jsx)(`div`,{className:`divide-y`,children:s.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4 py-2 first:pt-0 last:pb-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`p`,{className:`truncate font-mono text-xs`,children:[e.model||`unknown model`,e.dim?` · ${e.dim}-d`:``]}),(0,Z.jsxs)(`p`,{className:`truncate font-mono text-[11px] text-muted-foreground`,children:[`└─ `,e.name]})]}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,className:`text-destructive hover:text-destructive`,disabled:a===e.name,onClick:()=>c(e),title:`Permanently delete this model's vectors and ledger`,children:[(0,Z.jsx)(Qr,{className:`mr-1.5 h-3.5 w-3.5`}),a===e.name?`Reclaiming…`:`Reclaim`]})]},e.name))})})}function rN({workspaceId:e,workspaceName:t,spaces:n,onDone:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1);return(0,Z.jsxs)(eN,{title:`Fill a space`,hint:`Embed documents that are missing from a space. Narrow it to one subtree to try a model on a single project first.`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Space`}),(0,Z.jsxs)(`select`,{className:`${$M} w-full`,value:a,onChange:e=>o(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:`all spaces`}),n.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`label`,{className:`text-xs font-medium`,children:[`Limit to a path `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),placeholder:`ctx://work/project or dir://photos`,className:`h-8 font-mono text-sm`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>m(!0),title:`Pick a context or directory path from the tree`,children:(0,Z.jsx)(fr,{className:`h-3.5 w-3.5`})})]})]})]}),(0,Z.jsxs)(`label`,{className:`mt-3 flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:l,onChange:e=>u(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-embed documents that are already embedded`,l&&s.trim()&&(0,Z.jsx)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:`Combined with a path limit this clears the WHOLE space, not just that subtree. A partial clear is not expressible in the ledger. Leave this off unless you mean to redo everything.`})]})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,className:`mt-3`,onClick:async()=>{f(!0);try{let t=await XA(e,{space:a||void 0,reindex:l,scope:s.trim()||void 0});t.ingestDisabled?i({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`}):i({title:`Fill enqueued`,description:`${t.enqueued.toLocaleString()} document(s) queued${t.scope?` under ${t.scope}`:``}. The status line reports progress.`}),r()}catch(e){i({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}finally{f(!1)}},disabled:d,children:d?`Queueing…`:`Start fill`}),p&&(0,Z.jsx)(Le,{onClose:()=>m(!1),children:(0,Z.jsx)(y,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:t,multiple:!1,onClose:()=>m(!1),onConfirm:(e,t)=>{let n=e[0];if(n){let e=t.treeType===`directory`?`dir`:`ctx`;c(`${e}://${n.replace(/^\/+/,``)}`)}m(!1)}})})]})}var iN=[{provider:`blip`,model:`HuggingFaceTB/SmolVLM-500M-Instruct`,task:`instruct`,label:`SmolVLM 500M: prompted description (recommended)`,note:`~500 MB. Follows the prompt below, so architecture/materials/setting can be asked for.`},{provider:`blip`,model:`HuggingFaceTB/SmolVLM-256M-Instruct`,task:`instruct`,label:`SmolVLM 256M: prompted, smaller`,note:`~250 MB. Same prompting, weaker; for memory-tight boxes.`},{provider:`blip`,model:`onnx-community/Florence-2-base-ft`,task:`florence2`,label:`Florence-2 base: detailed caption`,note:`Detailed multi-sentence captions, but not steerable: no prompt, fixed task token.`},{provider:`blip`,model:`Xenova/vit-gpt2-image-captioning`,task:`caption`,label:`vit-gpt2: one short sentence (weakest)`,note:`The old default. Terse and repetition-prone; kept for continuity and low memory.`}],aN=`custom`,oN=[{value:`instruct`,label:`Instruct VLM (image + prompt)`},{value:`florence2`,label:`Florence-2 (task token)`},{value:`caption`,label:`Plain captioner (image only)`}],sN=`Describe this photograph in two or three sentences. If it shows a building or interior, name the architectural style, the main materials and the setting. Describe only what is visible.`;function cN({workspaceId:e,config:t,saving:n,onSave:r}){let{showToast:i}=wo(),a=t.workspace||{},o=t.effective||{},s=iN[0],c=a.summarize?.image||o.summarize?.image||{},[l,u]=(0,X.useState)(()=>o.summarize?.image?.enabled===!0||a.summarize?.image?.enabled===!0),[d,f]=(0,X.useState)(()=>{let e=iN.find(e=>e.provider===(c.provider||s.provider)&&e.model===c.model);return e?`${e.provider}::${e.model}`:c.model?aN:`${s.provider}::${s.model}`}),[p,m]=(0,X.useState)(()=>iN.some(e=>e.model===c.model)?``:c.model||``),[h,g]=(0,X.useState)(()=>c.task||`instruct`),[_,v]=(0,X.useState)(()=>c.prompt||``),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(!1),k=iN.find(e=>`${e.provider}::${e.model}`===d),A=d===aN,j=A?{provider:s.provider,model:p.trim(),task:h,label:`Custom`,note:``}:k||s,M=j.task===`instruct`,N=(0,X.useCallback)(()=>GA(e).then(e=>S(e.summarize||null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{N();let e=window.setInterval(()=>{S(e=>(e?.running&&N(),e))},2e3);return()=>window.clearInterval(e)},[N]);let P=async()=>{await r({...a,summarize:{...a.summarize||{},image:{enabled:l,provider:j.provider,model:j.model,task:j.task,...M&&_.trim()?{prompt:_.trim()}:{}}}}),b(!1)},ee=async()=>{E(!0);try{S(await qA(e)),i({title:`Stopping image summaries`,description:`The image being captioned finishes first; the rest are left for a later run.`})}catch(e){i({title:`Could not stop`,description:e instanceof Error?e.message:`Failed to stop`,variant:`destructive`})}finally{E(!1)}},F=async(t=!1)=>{w(!0);try{let n=await KA(e,{force:t});S(n),i({title:t?`Rebuilding image summaries`:`Backfilling image summaries`,description:`${n.total.toLocaleString()} candidate image(s). First run downloads model weights.`})}catch(e){i({title:`Summaries failed to start`,description:e instanceof Error?e.message:`Failed to start`,variant:`destructive`})}finally{w(!1)}},I=o.summarize?.image?.enabled===!0,te=x?.running===!0,L=x?.errors?.[0]?.error;return(0,Z.jsx)(eN,{title:`Summaries`,hint:`Generate descriptions for indexed images (metadata.summary); searchable via full-text and dense search`,children:(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l,disabled:n,onChange:e=>{u(e.target.checked),b(!0)}}),`Images`]}),(0,Z.jsxs)(`select`,{className:$M,value:d,disabled:n||!l,onChange:e=>{f(e.target.value),b(!0)},children:[iN.map(e=>(0,Z.jsx)(`option`,{value:`${e.provider}::${e.model}`,children:e.label},`${e.provider}::${e.model}`)),(0,Z.jsx)(`option`,{value:aN,children:`Custom model…`})]}),!A&&(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:j.model})]}),A&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{className:`h-8 w-72 font-mono text-xs`,placeholder:`org/model-id (Transformers.js / ONNX)`,value:p,disabled:n||!l,onChange:e=>{m(e.target.value),b(!0)}}),(0,Z.jsx)(`select`,{className:$M,value:h,disabled:n||!l,onChange:e=>{g(e.target.value),b(!0)},children:oN.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),l&&j.note&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:j.note}),l&&M&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`textarea`,{className:`w-full rounded-md border border-input bg-transparent p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,rows:3,placeholder:sN,value:_,disabled:n,onChange:e=>{v(e.target.value),b(!0)}}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`What to ask of every image. Empty uses the default shown above. Captions are indexed, so ask for the words you would search by.`})]}),x&&(x.running||x.total>0||x.finishedAt)&&(0,Z.jsxs)(`p`,{className:K(`text-xs`,x.aborted?`text-destructive`:`text-muted-foreground`),children:[te?`Running`:x.aborted?`Stopped`:x.cancelled?`Cancelled`:`Last run`,`: `,x.described,`/`,x.total,` described`,x.skipped?`, ${x.skipped} skipped`:``,x.failed?`, ${x.failed} failed`:``,x.aborted?`. ${x.abortedReason||`model worker died`}. Remaining images were not attempted; generate again to retry.`:x.cancelled?`. Stopped by you. The remaining images were left untouched; generate again to continue.`:L?`. ${L}`:``]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:D,disabled:n||te,onChange:e=>O(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-caption images that already have a summary`,D&&(0,Z.jsxs)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:[`Replaces every existing `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`metadata.summary`}),`, including ones written by a different model. Leave this off to fill in only what is missing.`]})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Enable + save, then run. Only the local caption provider is wired today. Candidates come from `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`data/mime/image`}),`.`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>void P(),disabled:n||!y,children:`Save summaries`}),(0,Z.jsx)(Y,{size:`sm`,onClick:()=>void F(D),disabled:n||y||C||te||!I,title:I?y?`Save config first`:D?`Re-caption every image, replacing existing summaries`:`Caption images that have no summary yet`:`Enable image summaries and save first`,children:te||C?`Running…`:D?`Rebuild`:`Backfill`}),te&&(0,Z.jsx)(Y,{size:`sm`,variant:`destructive`,onClick:()=>void ee(),disabled:T,title:`Finish the current image, then stop. The rest are left for later.`,children:T?`Stopping…`:`Stop`})]})]})]})})}function lN({workspaceId:e,workspaceName:t}){let{showToast:n}=wo(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(0),y=(0,X.useCallback)(()=>JA(e).then(e=>{i(e),m(null)}).catch(e=>m(e instanceof Error?e.message:`Failed to load the embedding config`)).finally(()=>u(!1)),[e]),b=(0,X.useCallback)(()=>ZA(e).then(e=>{o(e.tables||[]),c(e.error)}).catch(e=>c(e instanceof Error?e.message:`Failed to list vector tables`)),[e]);(0,X.useEffect)(()=>{y(),b()},[y,b]);let x=()=>{u(!0),y(),b(),v(e=>e+1)},S=async t=>{f(!0);try{let r=await YA(e,t);g(r.movedSpaces||[]),r.movedSpaces?.length?n({title:`Saved; fill to finish`,description:`${r.movedSpaces.join(`, `)} now targets a new model. The switch is live, but the new table is empty until you fill it.`}):r.applied===!1?n({title:`Saved; applies on next start`,description:`The workspace is not running, so the new spaces take effect when it starts.`}):n({title:`Saved`,description:`Embedding config updated.`}),await y(),await b()}catch(e){n({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save`,variant:`destructive`})}finally{f(!1)}},C=async t=>{try{let r=await XA(e,{space:t});if(r.ingestDisabled){n({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`});return}n({title:`Filling ${t}`,description:`${r.enqueued.toLocaleString()} document(s) queued. The status line reports progress.`}),g(e=>e.filter(e=>e!==t)),v(e=>e+1),b()}catch(e){n({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}};if(l)return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading the embedding config…`]});if(p||!r)return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding config unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:p||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:x,children:`Try again`})]});let w=Object.keys(r.effective.spaces||{}).sort();return(0,Z.jsxs)(`div`,{className:`space-y-5`,children:[(0,Z.jsx)(tN,{workspaceId:e,workspaceName:t,refreshKey:_,onRefresh:x}),(0,Z.jsx)(yj,{value:r.workspace||{},effective:r.effective||{},inherited:r.inherited||{},resolvedSpaces:r.spaces,invalid:r.invalid,attention:h,onFill:C,saving:d,saveLabel:`Save embedding config`,onSave:S},JSON.stringify(r.workspace)),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(cN,{workspaceId:e,config:r,saving:d,onSave:S},`summarize:${JSON.stringify(r.workspace?.summarize||{})}`),(0,Z.jsx)(rN,{workspaceId:e,workspaceName:t,spaces:w,onDone:()=>{b(),v(e=>e+1)}}),(0,Z.jsx)(nN,{workspaceId:e,tables:a,error:s,onChanged:()=>{b()}})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Stored in this workspace's own `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`workspace.json`}),`, so it travels with the workspace. Settings resolve in layers: built-in, then server, then your defaults, then this workspace, which wins. Changes apply live, with no restart.`]})]})}function uN(e){let t=(e||``).split(`.`).pop()?.toLowerCase();switch(t){case`js`:case`mjs`:case`ts`:return[l({typescript:t===`ts`})];case`json`:return[c()];case`sh`:case`bash`:return[a.define(u)];default:return[]}}function dN({value:e,onChange:t,path:n,className:r=``}){let i=(0,X.useMemo)(()=>uN(n),[n]),{resolvedScheme:a}=Ll();return(0,Z.jsx)(o,{value:e,onChange:t,extensions:i,theme:a===`dark`?`dark`:`light`,className:r,basicSetup:{lineNumbers:!0,foldGutter:!0,highlightActiveLine:!0,bracketMatching:!0,autocompletion:!1}})}var fN=[`pending`,`approved`,`declined`,`failed`,`expired`,`all`],pN={pending:`text-warning dark:text-warning`,approved:`text-success dark:text-success`,declined:`text-muted-foreground`,failed:`text-destructive`,expired:`text-muted-foreground line-through`};function mN(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`now`;if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function hN(e,t){return t.split(`.`).reduce((e,t)=>typeof e==`object`&&e?e[t]:void 0,e)}function gN(e){let t=e.split(`.`);return t.slice(Math.max(t.length-2,2)).join(`.`)}var _N=/(body|content|message|text|prompt)$/i;function vN({workspaceId:e,id:t,children:n}){let{open:r}=I(),{showToast:i}=wo(),[a,o]=(0,X.useState)(!1),s=async n=>{n.stopPropagation(),o(!0);try{r(await xc(e,t),e)}catch(e){i({title:`Document ${t} not available`,description:e instanceof Error?e.message:void 0,variant:`destructive`})}finally{o(!1)}};return(0,Z.jsx)(`button`,{type:`button`,disabled:a,onClick:e=>void s(e),className:`text-primary underline-offset-2 hover:underline disabled:opacity-60`,title:`Open document ${t}`,children:n??`doc ${t}`})}function yN({workspaceId:e,text:t}){let n=t.split(/(\bdoc \d+\b)/);return(0,Z.jsx)(Z.Fragment,{children:n.map((t,n)=>{let r=/^doc (\d+)$/.exec(t);return r?(0,Z.jsx)(vN,{workspaceId:e,id:Number(r[1])},n):(0,Z.jsx)(X.Fragment,{children:t},n)})})}function bN({action:e,amend:t,onAmend:n}){return e.editable?.length?(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.editable.map(r=>{let i=hN(e,r),a=typeof i==`string`,o=r in t?t[r]:i,s=a?String(o??``):JSON.stringify(o,null,2),c=a&&(_N.test(r)||s.length>80);return(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[(0,Z.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[gN(r),(0,Z.jsx)(`span`,{className:`ml-1.5 font-mono text-[10px] opacity-60`,children:r}),r in t&&(0,Z.jsx)(`span`,{className:`ml-1.5 text-warning dark:text-warning`,children:`edited`})]}),c?(0,Z.jsx)(`textarea`,{className:`mt-1 w-full rounded-md border bg-background px-2 py-1.5 font-mono text-xs outline-none focus:ring-2 focus:ring-ring min-h-[100px]`,value:s,onChange:e=>n(r,e.target.value)}):(0,Z.jsx)(`input`,{className:`mt-1 w-full h-8 rounded-md border bg-background px-2 font-mono text-xs outline-none focus:ring-2 focus:ring-ring`,value:s,onChange:e=>{if(a){n(r,e.target.value);return}try{n(r,JSON.parse(e.target.value))}catch{n(r,e.target.value)}}})]},r)})}):null}function xN({workspaceId:e,onPendingCount:t}){let{showToast:n}=wo(),r=Cw(),[i,a]=(0,X.useState)(`pending`),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!0),[u,d]=(0,X.useState)(new Set),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)({}),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>en(e,{status:i===`all`?void 0:i,limit:200}).then(e=>{s(e),d(t=>new Set(e.filter(e=>e.status===`pending`&&t.has(e.actionId)).map(e=>e.actionId))),t?.(i===`pending`?e.length:e.filter(e=>e.status===`pending`).length)}).catch(()=>{n({title:`Error`,description:`Failed to load pending actions`,variant:`destructive`})}).finally(()=>l(!1)),[e,i]),y=(0,X.useCallback)(async()=>{l(!0),await v()},[v]),[b,x]=(0,X.useState)(`${e}|${i}`),S=`${e}|${i}`;S!==b&&(x(S),l(!0)),(0,X.useEffect)(()=>{v()},[v]),fw(r,`workspace:${e}`,(0,X.useMemo)(()=>{let e=()=>{y()};return{"action.proposed":e,"action.approved":e,"action.declined":e,"action.failed":e}},[y]));let C=o.filter(e=>e.status===`pending`),w=C.length>0&&C.every(e=>u.has(e.actionId)),T=()=>{d(w?new Set:new Set(C.map(e=>e.actionId)))},E=e=>{d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},D=(e,t,n)=>{h(r=>({...r,[e]:{...r[e],[t]:n}}))},O=async(t,r)=>{if(!(!t.length&&!r.length)){_(!0);try{let i=await gt(e,{approve:t.map(e=>{let t=m[e];return t&&Object.keys(t).length?{actionId:e,amend:t}:e}),decline:r}),a=i.results.filter(e=>e.status===`error`||e.status===`failed`);a.length?n({title:`${a.length} of ${i.decided} failed`,description:a.map(e=>`${e.actionId}: ${e.error??`execution failed`}`).join(`; `),variant:`destructive`}):n({title:t.length&&r.length?`Decisions applied`:t.length?`Approved ${t.length}`:`Declined ${r.length}`,description:t.length?`Approved actions executed with their original provenance.`:void 0}),h(e=>{let n={...e};for(let e of[...t,...r])delete n[e];return n}),d(new Set),f&&[...t,...r].includes(f)&&p(null),await y()}catch(e){n({title:`Decision failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{_(!1)}}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-wrap`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:`h-8 rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring`,value:i,onChange:e=>a(e.target.value),children:fN.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>void y(),title:`Reload`,children:(0,Z.jsx)(Er,{className:`h-4 w-4`})})]}),u.size>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[u.size,` selected`]}),(0,Z.jsxs)(Y,{size:`sm`,disabled:g,onClick:()=>void O([...u],[]),children:[(0,Z.jsx)(sr,{className:`mr-1 h-3.5 w-3.5`}),` Approve`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,disabled:g,onClick:()=>void O([],[...u]),children:[(0,Z.jsx)(vr,{className:`mr-1 h-3.5 w-3.5`}),` Decline`]})]})]}),(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-auto max-h-[560px]`,children:c?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:i===`pending`?`Nothing waiting for review. Rules or hooks with approval enabled queue their actions here.`:`No ${i===`all`?``:i+` `}actions recorded.`}):(0,Z.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,Z.jsx)(`thead`,{className:`text-xs text-muted-foreground border-b sticky top-0 bg-background`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`px-3 py-2 w-8`,children:C.length>0&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:w,onChange:T,title:`Select all pending`})}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Proposed action`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Handler`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Age`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Status`}),(0,Z.jsx)(`th`,{className:`px-2 py-2 w-40`})]})}),(0,Z.jsx)(`tbody`,{children:o.map(t=>{let n=t.status===`pending`||t.status===`failed`,r=f===t.actionId,i=t.envelope?.payload?.document;return(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 align-top hover:bg-muted/40 cursor-pointer`,onClick:()=>p(r?null:t.actionId),children:[(0,Z.jsx)(`td`,{className:`px-3 py-2`,onClick:e=>e.stopPropagation(),children:t.status===`pending`&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:u.has(t.actionId),onChange:()=>E(t.actionId)})}),(0,Z.jsxs)(`td`,{className:`px-3 py-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 font-medium`,children:[r?(0,Z.jsx)(qr,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(Xa,{className:`h-3 w-3 shrink-0`}),t.title,t.editable?.length>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground shrink-0`,children:`editable`})]}),t.summary&&(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground pl-4`,children:(0,Z.jsx)(yN,{workspaceId:e,text:t.summary})})]}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 font-mono text-xs whitespace-nowrap`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[t.handlerType,`:`]}),t.handler,t.event&&(0,Z.jsxs)(`span`,{className:`block text-muted-foreground`,children:[t.event,i?.id!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsx)(vN,{workspaceId:e,id:i.id})]})]})]}),(0,Z.jsx)(`td`,{className:`px-3 py-2 text-xs whitespace-nowrap`,title:t.ts,children:mN(t.ts)}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:pN[t.status],children:t.status}),t.amended&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:`amended`}),t.decidedBy&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground truncate max-w-[120px]`,title:t.decidedBy,children:t.decidedBy})]}),(0,Z.jsx)(`td`,{className:`px-2 py-2 whitespace-nowrap text-right`,onClick:e=>e.stopPropagation(),children:n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{size:`sm`,className:`h-7 px-2`,disabled:g,title:t.status===`failed`?`Retry (re-approve)`:`Approve and execute`,onClick:()=>void O([t.actionId],[]),children:(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`})}),t.status===`pending`&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-7 px-2 text-muted-foreground`,disabled:g,title:`Decline`,onClick:()=>void O([],[t.actionId]),children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})})]}),r&&(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 bg-muted/20`,children:[(0,Z.jsx)(`td`,{className:`px-3 py-3`}),(0,Z.jsxs)(`td`,{className:`px-3 py-3 space-y-3`,colSpan:5,children:[n&&t.editable?.length>0&&(0,Z.jsx)(bN,{action:t,amend:m[t.actionId]??{},onAmend:(e,n)=>D(t.actionId,e,n)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Actions on approve`}),(0,Z.jsx)(`pre`,{className:`mt-1 rounded border bg-background p-2 font-mono text-xs overflow-auto max-h-56`,children:JSON.stringify(t.actions,null,2)})]}),t.result&&t.result.length>0&&(0,Z.jsx)(`div`,{className:`text-xs font-mono`,children:t.result.map((e,t)=>(0,Z.jsxs)(`span`,{className:`mr-2 ${e.status===`error`?`text-destructive`:`text-muted-foreground`}`,children:[e.action,`:`,e.status,e.error?` (${e.error})`:``]},t))}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground font-mono`,children:[t.actionId,` · origin `,t.provenance?.origin,t.provenance?.causedBy?` · causedBy ${t.provenance.causedBy}`:``,t.expiresAt?` · expires ${new Date(t.expiresAt).toLocaleString()}`:``]})]})]})]},t.actionId)})})]})})]})}var SN=`#!/usr/bin/env bash
|
|
40
|
+
# Called from a hook via: spawn('bash', [script, ...args])
|
|
41
|
+
set -euo pipefail
|
|
42
|
+
`;function CN({workspaceId:e,prefillRule:t,onPrefillConsumed:n,initialSection:r,initialRunsHandler:i,initialRunId:a}){let{showToast:o}=wo(),[s,c]=(0,X.useState)(r??`rules`),[l,u]=(0,X.useState)(t);t!==l&&(u(t),t&&c(`rules`));let[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)([]),[h,g]=(0,X.useState)(!0),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(!1),[O,k]=(0,X.useState)(null),[A,j]=(0,X.useState)(`document.inserted`),[M,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)([]),[F,I]=(0,X.useState)(!1),[te,L]=(0,X.useState)([]),[R,re]=(0,X.useState)(!1),[ie,ae]=(0,X.useState)(i||null),[z,oe]=(0,X.useState)(a?{runId:a,run:null}:null),se=e=>{oe(t=>t?.runId===e?null:{runId:e,run:null})};(0,X.useEffect)(()=>{if(!z||z.run||z.error)return;let t=!1;return dn(e,z.runId).then(e=>{t||oe(t=>t?.runId===e.runId?{runId:e.runId,run:e}:t)}).catch(e=>{t||oe(t=>t?.runId===z.runId?{...t,error:e instanceof Error?e.message:`Failed to load run`}:t)}),()=>{t=!0}},[e,z]);let[B,V]=(0,X.useState)(null),[le,ue]=(0,X.useState)(!1),[de,fe]=(0,X.useState)(0),[pe,me]=(0,X.useState)(null),[he,ge]=(0,X.useState)(()=>At()),[_e,ve]=(0,X.useState)(()=>String(At())),ye=()=>{let e=jn(_(_e));ge(e),ve(String(e))};(0,X.useEffect)(()=>{let t=!1;return en(e,{status:`pending`,limit:500}).then(e=>{t||fe(e.length)}).catch(()=>{}),()=>{t=!0}},[e]),Ae(()=>ue(!1),le);let be=async t=>{if(confirm(`Replay ${t.handlerType} "${t.handler}" for ${t.event} (docs ${(t.docIds||[]).join(`, `)})?`)){V(t.runId);try{let n=await Et(e,t.runId);o({title:`Replayed`,description:`${t.handler} → ${n.status}`}),await Se()}catch(e){o({title:`Replay failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{V(null)}}},xe=s===`scripts`?{list:Fe,get:ne,save:Ve,del:Re}:{list:bt,get:rt,save:Sn,del:Kt},H=s===`hooks`||s===`scripts`,Se=async()=>{if(s!==`rules`&&s!==`pending`){if(s===`runs`){try{g(!0),L(await Ht(e,{limit:100,failed:R||void 0,handler:ie||void 0}))}catch{o({title:`Error`,description:`Failed to load hook runs`,variant:`destructive`})}finally{g(!1)}return}try{g(!0),m(await xe.list(e))}catch{o({title:`Error`,description:`Failed to load ${s}`,variant:`destructive`})}finally{g(!1)}}};(0,X.useEffect)(()=>{Se()},[e,s,R,ie]);let Ce=e=>{e!==s&&(S&&!confirm(`Discard unsaved changes?`)||(c(e),y(null),x(``),C(!1),D(!1)))},U=async t=>{if(!(S&&!confirm(`Discard unsaved changes?`)))try{y(t),x(await xe.get(e,t)),C(!1)}catch{o({title:`Error`,description:`Failed to open ${t}`,variant:`destructive`})}},we=async()=>{if(v)try{T(!0),await xe.save(e,v,b),C(!1),o({title:`Saved`,description:`${v} saved`}),await Se()}catch{o({title:`Error`,description:`Failed to save ${v}`,variant:`destructive`})}finally{T(!1)}},Te=async t=>{let n=pt(t);try{let r=await ot(e,t,!n);v===t&&y(r),await Se(),o({title:n?`Disabled`:`Enabled`,description:r})}catch{o({title:`Error`,description:`Failed to toggle ${t}`,variant:`destructive`})}},Ee=async t=>{let n=zt(t);if(!n||!pt(t)&&!confirm(`${t} is disabled. Run it anyway?`))return;let r=n.startsWith(`document.`);if(!(r&&!confirm(`Run ${t} against up to ${he} existing documents (event ${n})?`))){me(t);try{if(r){let r=await W(e,{hookFile:t,event:n,limit:he});o({title:`Run finished`,description:`${r.processed} documents processed, ${r.failed} failed. Details in the Runs tab`,...r.failed?{variant:`destructive`}:{}})}else{let r=await $e(e,{hookFile:t,event:n});o({title:r.status===`error`?`Run failed`:`Run finished`,description:r.status===`error`?`${t}: ${r.error||`see the Runs tab`}`:`${t} → ${r.status}${r.durationMs==null?``:` in ${r.durationMs}ms`}`,...r.status===`error`?{variant:`destructive`}:{}})}}catch(e){o({title:`Run failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{me(null)}}},De=async t=>{if(confirm(`Delete ${s===`hooks`?`hook`:`script`} ${t}?`))try{await xe.del(e,t),v===t&&(y(null),x(``),C(!1)),await Se(),o({title:`Deleted`,description:`${t} deleted`})}catch{o({title:`Error`,description:`Failed to delete ${t}`,variant:`destructive`})}},Oe=async()=>{if(!O)try{k(await Xt(e))}catch{o({title:`Error`,description:`Failed to load hook metadata`,variant:`destructive`})}},ke=async()=>{D(!E),s===`hooks`&&await Oe()},je=async()=>{f(!d),await Oe()},Me=async()=>{let t=M.trim().replace(/^\/+/,``);if(!t){o({title:`Error`,description:`Give the script a name (e.g. on-image.sh)`,variant:`destructive`});return}try{I(!0),await Ve(e,t,SN),D(!1),N(``),await Se(),await U(t)}catch{o({title:`Error`,description:`Failed to create script`,variant:`destructive`})}finally{I(!1)}},Ne=e=>{ee(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},Pe=async()=>{if(!M.trim()){o({title:`Error`,description:`Give the hook a name`,variant:`destructive`});return}try{I(!0);let{path:t}=await cn(e,{event:A,name:M.trim(),actions:P});D(!1),N(``),ee([]),await Se(),await U(t),o({title:`Created`,description:`${t}. Edit the TODOs, then enable it`})}catch{o({title:`Error`,description:`Failed to create hook`,variant:`destructive`})}finally{I(!1)}},Ie=s===`hooks`?lt(p):{scripts:p},Le=`${yo}/workspaces/${e}/git/internal`;return(0,Z.jsxs)(`div`,{className:`@container space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 @3xl:flex-row @3xl:items-start @3xl:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 @3xl:min-w-[18rem] @3xl:flex-1`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`Automation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rules are simple click-to-build automations (Outlook-style). Hooks are their programmable big brother; scripts are the shell helpers hooks spawn. Everything commits to the workspace git repo.`})]}),(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2 @3xl:max-w-[60%] @3xl:flex-row @3xl:items-center`,children:(0,Z.jsx)(`div`,{className:`w-full min-w-0 @3xl:w-auto`,children:(0,Z.jsx)(ce,{className:`border-b-0`,active:s,onChange:Ce,tabs:[{id:`pending`,label:de>0?`Pending (${de})`:`Pending`,icon:wr},{id:`rules`,label:`Rules`,icon:Ta},{id:`hooks`,label:`Hooks`,icon:or},{id:`scripts`,label:`Scripts`,icon:ai},{id:`runs`,label:`Runs`,icon:xr}]})})})]}),(s===`runs`||H)&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[s===`runs`&&(0,Z.jsxs)(Z.Fragment,{children:[ie&&(0,Z.jsxs)(`button`,{type:`button`,className:`inline-flex items-center gap-1 rounded-full border bg-muted/50 px-2.5 py-1 font-mono text-xs hover:bg-muted`,title:`Showing runs of this rule / hook only — click to clear`,onClick:()=>ae(null),children:[ie,` `,(0,Z.jsx)(vr,{className:`h-3 w-3`})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:R,onChange:e=>re(e.target.checked)}),`failed only`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,onClick:Se,title:`Reload`,children:[(0,Z.jsx)(Er,{className:`mr-1.5 h-4 w-4`}),` Reload`]})]}),H&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,onClick:Se,title:`Reload`,children:[(0,Z.jsx)(Er,{className:`mr-1.5 h-4 w-4`}),` Reload`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,onClick:je,title:`Hook context API & classifier reference`,children:[(0,Z.jsx)(Ln,{className:`mr-1.5 h-4 w-4`}),` Reference`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:ke,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),` `,s===`hooks`?`New Hook`:`New Script`]})]})]}),s===`pending`&&(0,Z.jsx)(xN,{workspaceId:e,onPendingCount:fe}),s===`rules`&&(0,Z.jsx)(Mn,{workspaceId:e,backfillLimit:he,onShowRuns:e=>{ae(e),Ce(`runs`)},prefill:t,onPrefillConsumed:n,onOpenJson:async()=>{try{await rt(e,`rules.json`)}catch{await Sn(e,`rules.json`,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:[]},null,2)+`
|
|
43
|
+
`).catch(()=>{})}c(`hooks`),U(`rules.json`)}}),s===`runs`&&(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-auto max-h-[560px]`,children:h?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:`Loading...`}):te.length===0?(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground p-3`,children:[`No runs recorded yet`,R?` (failed only)`:``,`. Runs appear here every time a rule or hook executes.`]}):(0,Z.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,Z.jsx)(`thead`,{className:`text-xs text-muted-foreground border-b sticky top-0 bg-background`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Time`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Handler`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Event`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Docs`}),(0,Z.jsx)(`th`,{className:`text-right font-medium px-3 py-2`,children:`ms`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Status`}),(0,Z.jsx)(`th`,{className:`px-2 py-2`})]})}),(0,Z.jsx)(`tbody`,{children:te.map(e=>(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 align-top hover:bg-muted/40`,children:[(0,Z.jsx)(`td`,{className:`px-3 py-1.5 whitespace-nowrap text-xs text-muted-foreground`,title:e.ts,children:new Date(e.ts).toLocaleString()}),(0,Z.jsxs)(`td`,{className:`px-3 py-1.5 font-mono text-xs`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[e.handlerType,`:`]}),e.handler,e.origin!==`user`&&(0,Z.jsxs)(`span`,{className:`ml-1.5 text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground`,children:[e.origin,e.depth?` d${e.depth}`:``]})]}),(0,Z.jsxs)(`td`,{className:`px-3 py-1.5 font-mono text-xs`,children:[e.event,e.batch?` (batch)`:``]}),(0,Z.jsx)(`td`,{className:`px-3 py-1.5 font-mono text-xs`,children:(e.docIds||[]).join(`, `)}),(0,Z.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono text-xs`,children:e.durationMs}),(0,Z.jsxs)(`td`,{className:`px-3 py-1.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:e.status===`error`?`text-destructive font-medium`:e.status===`skipped`?`text-muted-foreground`:`text-success dark:text-success`,children:e.status}),e.error&&(0,Z.jsx)(`span`,{className:`block text-destructive/80 font-mono break-all`,children:e.error}),e.skipReason&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:e.skipReason}),e.actions&&e.actions.length>0&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground font-mono`,children:e.actions.map(e=>`${e.action}:${e.status}`).join(` `)}),e.actions?.filter(e=>e.error).map((e,t)=>(0,Z.jsxs)(`span`,{className:`block break-all font-mono ${e.status===`error`?`text-destructive/80`:`text-muted-foreground`}`,children:[e.action,`: `,e.error]},t))]}),(0,Z.jsxs)(`td`,{className:`px-2 py-1.5 whitespace-nowrap`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 touch-target`,title:e.traceLines?`Execution log (${e.traceLines} lines)`:`Execution log`,onClick:()=>se(e.runId),children:[(0,Z.jsx)(bi,{className:`h-3.5 w-3.5`}),(0,Z.jsx)(qr,{className:`ml-0.5 h-3 w-3 transition-transform ${z?.runId===e.runId?`rotate-180`:``}`})]}),e.handlerType!==`dispatch`&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 touch-target`,title:`Replay this run (reloads the document, re-runs the handler)`,disabled:B!==null,onClick:()=>be(e),children:(0,Z.jsx)(Vr,{className:`h-3 w-3 ${B===e.runId?`animate-spin`:``}`})})]})]}),z?.runId===e.runId&&(0,Z.jsx)(`tr`,{className:`border-b last:border-0 bg-muted/30`,children:(0,Z.jsx)(`td`,{colSpan:7,className:`px-3 py-2`,children:(0,Z.jsx)(wN,{state:z})})})]},e.runId))})]})}),H&&d&&O&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 bg-muted/30 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`h4`,{className:`font-medium mb-2`,children:[`Hook context (`,(0,Z.jsx)(`span`,{className:`font-mono`,children:`ctx`}),`)`]}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:O.contextApi?.map(e=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-xs`,children:e.signature}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]},e.name))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`h4`,{className:`font-medium mb-2`,children:[`Classifier (`,(0,Z.jsx)(`span`,{className:`font-mono`,children:`const c = ctx.classify()`}),`)`]}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:O.classifier.predicates.map(e=>(0,Z.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-xs`,children:e},e))}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-2`,children:[`Fields: `,O.classifier.fields.map(e=>(0,Z.jsxs)(`code`,{className:`font-mono`,children:[e,` `]},e)),`(never throws; all predicates are false for a null/unknown document).`]})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Full reference: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`docs/hooks.md`}),` in the server repo.`]})]}),E&&s===`scripts`&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-3 flex gap-2 items-center bg-muted/50`,children:[(0,Z.jsx)(q,{placeholder:`on-image.sh`,value:M,onChange:e=>N(e.target.value),className:`font-mono text-sm`}),(0,Z.jsx)(Y,{size:`sm`,onClick:Me,disabled:F,children:`Create`}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>D(!1),children:`Cancel`})]}),E&&s===`hooks`&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-3 bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground block mb-1`,children:`1. When (event)`}),(0,Z.jsx)(`select`,{className:`w-full h-9 rounded-md border bg-background px-2 font-mono text-sm outline-none focus:ring-2 focus:ring-ring`,value:A,onChange:e=>j(e.target.value),children:(O?.events??[]).map(e=>(0,Z.jsxs)(`option`,{value:e.name,children:[e.name,`: `,e.description]},e.name))}),O&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-1 font-mono`,children:[`payload: `,O.events.find(e=>e.name===A)?.payload]}),(0,Z.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground block mt-3 mb-1`,children:`2. Name`}),(0,Z.jsx)(q,{placeholder:`my-hook`,value:M,onChange:e=>N(e.target.value),className:`font-mono text-sm`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground block mb-1`,children:`3. Then (actions; pick any)`}),(0,Z.jsx)(`div`,{className:`space-y-1 max-h-52 overflow-auto pr-1`,children:(O?.actions??[]).map(e=>(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm rounded px-2 py-1 hover:bg-muted cursor-pointer`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-1`,checked:P.includes(e.id),onChange:()=>Ne(e.id)}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:e.label}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.description})]})]},e.id))})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Y,{size:`sm`,onClick:Pe,disabled:F||!O,children:F?`Creating…`:`Create skeleton`}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>D(!1),children:`Cancel`}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Creates a disabled skeleton. Edit the TODOs, then enable it. Simple match→action automations can also go into `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` (no code).`]})]})]}),H&&(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-3 gap-4`,children:[(0,Z.jsx)(`div`,{className:`md:col-span-1 border rounded-lg p-2 max-h-[480px] overflow-auto`,children:h?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-2`,children:`Loading...`}):p.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-2`,children:`No hooks yet.`}):Object.entries(Ie).map(([e,t])=>(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-semibold text-muted-foreground px-2 py-1`,children:e}),t.map(e=>{let t=pt(e.path);return(0,Z.jsxs)(`div`,{className:`flex items-center justify-between rounded px-2 py-1 cursor-pointer text-sm ${v===e.path?`bg-muted`:`hover:bg-muted/50`} ${t?``:`opacity-50`}`,onClick:()=>U(e.path),children:[(0,Z.jsxs)(`span`,{className:`font-mono truncate flex items-center gap-1.5`,children:[e.path,s===`hooks`&&yn(e.path)&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground shrink-0`,children:`example`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[s===`hooks`&&zt(e.path)&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 touch-target`,title:zt(e.path)?.startsWith(`document.`)?`Run against up to ${he} existing documents`:`Run now`,disabled:pe!==null,onClick:t=>{t.stopPropagation(),Ee(e.path)},children:(0,Z.jsx)(Ar,{className:`h-3 w-3 ${pe===e.path?`animate-pulse`:``}`})}),s===`hooks`&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 touch-target`,title:t?`Disable`:`Enable`,onClick:t=>{t.stopPropagation(),Te(e.path)},children:t?(0,Z.jsx)(Vn,{className:`h-3 w-3`}):(0,Z.jsx)(Xi,{className:`h-3 w-3 text-muted-foreground`})}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 text-destructive hover:text-destructive touch-target`,onClick:t=>{t.stopPropagation(),De(e.path)},children:(0,Z.jsx)(Qr,{className:`h-3 w-3`})})]})]},e.path)})]},e))}),(0,Z.jsx)(`div`,{className:le?`fixed inset-0 z-50 bg-background p-4 flex flex-col`:`md:col-span-2 border rounded-lg p-2 flex flex-col`,children:v?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`span`,{className:`font-mono text-sm truncate`,children:[v,S?` •`:``]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[s===`hooks`&&zt(v)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,className:`h-8`,title:pt(v)?`Disable this hook (renames it with a disabled- prefix)`:`Enable this hook (strips the prefix)`,onClick:()=>Te(v),children:pt(v)?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Vn,{className:`mr-1.5 h-3.5 w-3.5`}),` Enabled`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Xi,{className:`mr-1.5 h-3.5 w-3.5 text-muted-foreground`}),` Disabled`]})}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,className:`h-8`,title:`Run this hook now`,disabled:pe!==null||S,onClick:()=>Ee(v),children:[(0,Z.jsx)(Ar,{className:`mr-1.5 h-3.5 w-3.5 ${pe===v?`animate-pulse`:``}`}),` Run`]})]}),(0,Z.jsxs)(Y,{size:`sm`,onClick:we,disabled:w||!S,children:[(0,Z.jsx)(Yn,{className:`mr-2 h-4 w-4`}),` Save`]}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-8 w-8 p-0`,title:le?`Exit full screen (Esc)`:`Edit full screen`,onClick:()=>ue(!le),children:le?(0,Z.jsx)(ei,{className:`h-4 w-4`}):(0,Z.jsx)(ba,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-auto rounded border text-sm ${le?``:`min-h-[400px] max-h-viewport-pane`}`,children:(0,Z.jsx)(dN,{value:b,path:v,onChange:e=>{x(e),C(!0)}})})]}):(0,Z.jsxs)(`div`,{className:`flex-1 flex items-center justify-center text-sm text-muted-foreground min-h-[400px]`,children:[`Select a `,s===`hooks`?`hook`:`script`,` to edit, or create a new one.`]})})]}),(s===`rules`||s===`hooks`)&&(0,Z.jsxs)(`label`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground`,title:`1–10000. Raise it when "Apply to existing items" reports fewer matches than you expect.`,children:[(0,Z.jsx)(Ci,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.jsx)(`span`,{children:`Apply / run in batches of`}),(0,Z.jsx)(q,{type:`number`,min:1,max:1e4,step:100,value:_e,onChange:e=>ve(e.target.value),onBlur:ye,onKeyDown:e=>{e.key===`Enter`&&(ye(),e.target.blur())},className:`h-7 w-20 px-2 text-xs`}),(0,Z.jsx)(`span`,{children:`documents per pass — the rule "Apply" button and manual hook runs stop after that many.`})]}),(0,Z.jsxs)(`p`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(or,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.jsxs)(`span`,{children:[`Everything here lives in the workspace git repo. Clone it with`,` `,(0,Z.jsxs)(`code`,{className:`break-all rounded bg-muted px-1 py-0.5 font-mono select-all`,children:[`git clone `,Le.replace(`://`,`://canvas@`)]}),` `,`(password: a canvas API token; the `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`canvas@`}),` username is arbitrary but git needs one). Pushes hot-reload hooks.`]})]})]})}function wN({state:e}){if(e.error)return(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:e.error});if(!e.run)return(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading…`});let t=e.run,n={error:`text-destructive`,warn:`text-warning`,info:`text-foreground`,debug:`text-muted-foreground`};return(0,Z.jsxs)(`div`,{className:`space-y-2 text-xs`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-1 text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`run `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t.runId})]}),(0,Z.jsxs)(`span`,{children:[`trigger `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t.trigger})]}),t.eventId&&(0,Z.jsxs)(`span`,{children:[`event `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t.eventId})]}),(0,Z.jsxs)(`span`,{children:[t.durationMs,` ms`]})]}),t.actions&&t.actions.length>0&&(0,Z.jsx)(`ol`,{className:`space-y-0.5 font-mono`,children:t.actions.map((e,t)=>(0,Z.jsxs)(`li`,{className:e.status===`error`?`text-destructive`:e.status===`skipped`?`text-muted-foreground`:``,children:[t+1,`. `,e.action,` → `,e.status,e.error?` — ${e.error}`:``]},t))}),t.trace&&t.trace.length>0?(0,Z.jsx)(`pre`,{className:`max-h-96 overflow-auto rounded-md border bg-background p-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-all`,children:t.trace.map((e,t)=>(0,Z.jsxs)(`span`,{className:`block ${n[e.level]||``}`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[`+`,String(e.t).padStart(5,` `),`ms `]}),(0,Z.jsxs)(`span`,{className:`uppercase text-muted-foreground`,children:[e.level.padEnd(5,` `),` `]}),e.msg]},t))}):(0,Z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No execution log recorded for this run`,t.error?``:` (older runs predate tracing)`,`.`]})]})}var TN=e=>`/workspaces/${e}/storage-policies`;function EN(){return`policy-${crypto.randomUUID().slice(0,8)}`}function DN(e){return e.filter(e=>e.enabled&&e.capabilities?.upload&&!e.config?.readOnly&&e.driver!==`cacache`)}var ON=new Set([`file`]);function kN(e,t){return`${e===`directory`?`dir`:`ctx`}:${t.startsWith(`/`)?t:`/${t}`}`}function AN(e){let t=/^(ctx|dir):(\/.*)$/.exec(e);return t?{tree:t[1]===`dir`?`directory`:`context`,path:t[2]}:null}function jN(e){return(AN(e)?.path??e).replace(/^\/+/,``)}function MN(e){return`${e.backend}:${e.folder||`/`}`}async function NN(e){let t=await J.get(TN(e));return{...t,policies:t?.policies??[],revision:t.revision,blobBackend:t?.blobBackend??null}}async function PN(e,t,n){return J.put(TN(e),{policies:t,revision:n})}async function FN(e,t,n={}){return await J.post(`${TN(e)}/${encodeURIComponent(t)}/apply`,n)}async function IN(e,t,n){let{policies:r,revision:i}=n??await NN(e),a=r.findIndex(e=>e.id===t.id);return PN(e,a===-1?[...r,t]:r.map((e,n)=>n===a?t:e),i)}async function LN(e,t,n,r={}){let i={folders:0,processed:0,matched:0,failed:0},a=0;for(;a!==null;){let o=await FN(e,t,{limit:r.limit??100,offset:a,dryRun:r.dryRun});if(i.folders+=o.folders??0,i.processed+=o.processed??0,i.matched+=o.matched??0,i.failed+=o.failed??0,n?.(o,i),o.nextOffset===void 0)throw Error(`The policy is saved, but applying it to existing documents needs an updated server.`);a=o.nextOffset}return i}function RN(e,t,n){let r=kN(t,n),i=r.endsWith(`/`)?r:`${r}/`;return e.filter(e=>{if(!e.enabled)return!1;if(e.path===r)return!0;if(!e.recursive)return!1;let t=e.path.endsWith(`/`)?e.path:`${e.path}/`;return i.startsWith(t)})}function zN(e){let t=new Set;for(let n of e)for(let e of n.targets)t.add(MN(e));return[...t].join(`, `)}async function BN(e,t){await J.post(`${TN(e)}/operations/${encodeURIComponent(t)}/retry`,{})}function VN(e){return!e||!e.mime&&!e.filename&&(!e.schema||e.schema===`file`)?`files`:e.mime===`image/*`&&!e.filename&&(!e.schema||e.schema===`file`)?`images`:`custom`}function HN(e,t){return{backend:e?.address??``,folder:t,recursive:!0,recreateDirectories:!!e&&ON.has(e.driver),onConflict:`error`}}function UN({workspaceId:e,path:t,policy:n,onClose:r,onSaved:i}){let a=!!n,[o]=(0,X.useState)(()=>n?.id??EN()),[s,c]=(0,X.useState)(n?.kind||`mirror`),[l,u]=(0,X.useState)(n?.description??``),[d,f]=(0,X.useState)(n?.recursive??!0),[p,m]=(0,X.useState)(()=>VN(n?.filter)),[h,g]=(0,X.useState)(n?.filter?.mime??``),[_,v]=(0,X.useState)(n?.filter?.filename??``),[y,b]=(0,X.useState)(n?.targets??[]),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(null),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(!1),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(``),[N,P]=(0,X.useState)(0),[ee,F]=(0,X.useState)(0),[I,te]=(0,X.useState)(0);Ae(r,!D);let L=()=>{D||r()},R=(0,X.useMemo)(()=>jN(t),[t]),ne=(0,X.useMemo)(()=>DN(C??[]).filter(e=>s===`filing`||e.driver===`file`),[C,s]),re=(0,X.useMemo)(()=>new Map(ne.map(e=>[e.address,e])),[ne]);(0,X.useEffect)(()=>{let t=!1;return Promise.all([Rc(e),NN(e)]).then(([e,r])=>{if(t)return;if(n&&JSON.stringify(r.policies.find(e=>e.id===n.id))!==JSON.stringify(n))throw Error(`This policy changed. Close and reopen the editor.`);S(r),w(e);let i=DN(e).find(e=>n?.kind===`filing`||e.driver===`file`);i&&b(e=>e.length?e:[HN(i,R)])}).catch(e=>{t||(w([]),M(e instanceof Error?e.message:`Could not load backends`))}),()=>{t=!0}},[e,R,n]);let ae=(e,t)=>b(n=>n.map((n,r)=>r===e?{...n,...t}:n)),z=(e,t)=>{let n=re.get(t),r=!!n&&ON.has(n.driver);ae(e,{backend:t,recreateDirectories:r?y[e].recreateDirectories:!1})},oe=()=>{if(!y.length)throw Error(`Add at least one target.`);let e=y.map(e=>{if(!e.backend)throw Error(`Choose a backend for every target.`);let t={backend:e.backend,folder:e.folder.trim().replace(/^\/+|\/+$/g,``),recursive:e.recursive,recreateDirectories:e.recreateDirectories,onConflict:e.onConflict??`error`};if(s===`filing`&&e.key?.trim()&&(t.key=e.key.trim()),s===`filing`&&(t.recreateDirectories=!1),s===`mirror`&&t.folder.includes(`{{`))throw Error(`Folder templates require a filing policy.`);return t}),r;return p===`images`?r={schema:`file`,mime:`image/*`}:p===`custom`&&(r={schema:`file`},h.trim()&&(r.mime=h.trim()),_.trim()&&(r.filename=_.trim())),{id:o,kind:s,enabled:n?.enabled??!0,...l.trim()?{description:l.trim()}:{},path:t,recursive:d,...r?{filter:r}:{},targets:e}},se=async()=>{if(!D){O(!0),M(``);try{let t=oe();T||(await IN(e,t,x),E(!0),i?.(t)),P(0),F(0),te(0),await LN(e,o,(e,t)=>{P(t.matched),F(t.folders),te(t.failed)}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),A(!0)}catch(e){M(e instanceof Error?e.message:`Could not save the storage policy`)}finally{O(!1)}}},B=!!x&&y.length>0&&y.every(e=>e.backend);return(0,Z.jsx)(Le,{onClose:L,children:(0,Z.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-policy-title`,className:`${ie} flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`h2`,{id:`storage-policy-title`,className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(gr,{className:`h-4 w-4`}),a?`Edit storage policy`:`Storage policy`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:L,disabled:D,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Virtual path`}),(0,Z.jsx)(`p`,{className:`mt-1 break-words text-sm`,children:t})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Documents filed here are copied to every target in order. Uploads stay local until every destination has been verified. Mirrors move removed copies to Trash; filing policies keep their copies.`}),(0,Z.jsxs)(`fieldset`,{disabled:D||T,className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`block`,children:[`Behavior`,(0,Z.jsxs)(`select`,{"aria-label":`Storage behavior`,className:`ml-2 rounded border bg-background p-2`,value:s,onChange:e=>c(e.target.value),children:[(0,Z.jsx)(`option`,{value:`mirror`,children:`Mirror (recoverable removal)`}),(0,Z.jsx)(`option`,{value:`filing`,children:`File copies (keep after unlink)`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-description`,children:`Description (optional)`}),(0,Z.jsx)(`input`,{id:`policy-description`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g. Accounting archive`})]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked),className:`mt-1`}),`Apply to subfolders`]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-filter`,children:`Documents`}),(0,Z.jsxs)(`select`,{id:`policy-filter`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:p,onChange:e=>m(e.target.value),children:[(0,Z.jsx)(`option`,{value:`files`,children:`Files`}),(0,Z.jsx)(`option`,{value:`images`,children:`Images`}),(0,Z.jsx)(`option`,{value:`custom`,children:`Custom…`})]}),p===`custom`&&(0,Z.jsxs)(`div`,{className:`mt-2 grid grid-cols-2 gap-2`,children:[(0,Z.jsx)(`input`,{"aria-label":`MIME type`,className:`rounded-md border bg-background p-2`,value:h,onChange:e=>g(e.target.value),placeholder:`image/*`}),(0,Z.jsx)(`input`,{"aria-label":`Filename glob`,className:`rounded-md border bg-background p-2`,value:_,onChange:e=>v(e.target.value),placeholder:`img*`})]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:`Targets`}),C===null&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading backends…`}),C!==null&&!ne.length&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`No writable backend available. Add a folder or drive under Files & storage first.`}),y.map((e,t)=>{let n=re.get(e.backend),r=s===`mirror`&&!!n&&ON.has(n.driver);return(0,Z.jsxs)(`fieldset`,{disabled:D||T,className:`space-y-2 rounded-lg border p-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`select`,{"aria-label":`Backend`,className:`min-w-0 flex-1 rounded-md border bg-background p-2`,value:e.backend,onChange:e=>z(t,e.target.value),children:[!e.backend&&(0,Z.jsx)(`option`,{value:``,children:`Choose a backend…`}),ne.map(e=>(0,Z.jsxs)(`option`,{value:e.address,children:[e.address,` (`,e.driver,`)`]},e.address)),e.backend&&!n&&(0,Z.jsxs)(`option`,{value:e.backend,children:[e.backend,` (unavailable)`]})]}),(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Remove target`,onClick:()=>b(e=>e.filter((e,n)=>n!==t)),className:`p-1 disabled:opacity-40`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-folder-${t}`,children:`Folder on the backend`}),(0,Z.jsx)(`input`,{id:`policy-folder-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:e.folder,onChange:e=>ae(t,{folder:e.target.value}),placeholder:`(backend root)`})]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:e.recursive,onChange:e=>ae(t,{recursive:e.target.checked}),className:`mt-1`}),`Recreate sub-folder path in destination`]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 ${r?``:`opacity-60`}`,title:r?void 0:`Empty folders require a mirror on a supported file backend.`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:r&&e.recreateDirectories,disabled:!r,onChange:e=>ae(t,{recreateDirectories:e.target.checked}),className:`mt-1`}),`Create folders on the backend`]}),(0,Z.jsxs)(`details`,{children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer text-xs text-muted-foreground`,children:`Advanced`}),(0,Z.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[s===`filing`&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-key-${t}`,children:`File-name template (optional)`}),(0,Z.jsx)(`input`,{id:`policy-key-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2 font-mono text-xs`,value:e.key??``,onChange:e=>ae(t,{key:e.target.value}),placeholder:`{{YYYY}}{{MM}}{{DD}}_{{basename}}{{ext}}`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-conflict-${t}`,children:`On name conflict`}),(0,Z.jsxs)(`select`,{id:`policy-conflict-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:e.onConflict??`error`,onChange:e=>ae(t,{onConflict:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`error`,children:`Stop with an error`}),(0,Z.jsx)(`option`,{value:`rename`,children:`Rename the new file`}),n?.driver===`file`&&(0,Z.jsx)(`option`,{value:`overwrite`,children:`Overwrite (retain previous bytes)`})]})]})]})]})]},t)}),!T&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:D||!ne.length,onClick:()=>b(e=>[...e,HN(ne.find(t=>!e.some(e=>e.backend===t.address))??ne[0],R)]),children:[(0,Z.jsx)(br,{className:`mr-1 h-4 w-4`}),`Add target…`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applies to existing and future documents. Transfer progress and errors appear in Storage policies settings.`}),D&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:T?`Applying to existing documents… ${N} planned, ${ee} folders`:`Saving storage policy…`}),k&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Storage policy saved. `,N,` documents and `,ee,` folders planned. Replication continues in the background.`]}),I>0&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[I,` document operations failed. Check operation status in Storage policies settings.`]}),j&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[T?`The policy is saved. `:``,j]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Z.jsx)(Y,{variant:`ghost`,disabled:D,onClick:L,children:`Cancel`}),k?(0,Z.jsx)(Y,{onClick:r,children:`Done`}):(0,Z.jsx)(Y,{disabled:D||!B,onClick:se,children:D?`Applying…`:T?`Retry existing documents`:a?`Save policy`:`Enable policy`})]})]})})}var WN={policies:[],revision:``,loading:!1,error:``},GN=new Map,KN=new Set;function qN(){for(let e of KN)e()}function JN(e){return KN.add(e),()=>{KN.delete(e)}}function YN(e,t){GN.set(e,t),qN()}async function XN(e){YN(e,{...GN.get(e)??WN,loading:!0,error:``});try{let{policies:t,revision:n,status:r}=await NN(e);YN(e,{policies:t,revision:n,status:r,loading:!1,error:``})}catch(t){YN(e,{policies:[],revision:``,loading:!1,error:t instanceof Error?t.message:`Could not load storage policies`})}}function ZN(e){GN.delete(e),qN()}function QN(e){let t=(0,X.useSyncExternalStore)(JN,()=>e&&GN.get(e)||WN),n=!!e&&!GN.has(e);(0,X.useEffect)(()=>{e&&n&&XN(e)},[e,n]);let r=(0,X.useCallback)(async()=>{e&&await XN(e)},[e]);return(0,X.useEffect)(()=>{if(!e||!t.policies.length)return;let n=window.setInterval(()=>{!document.hidden&&!GN.get(e)?.loading&&XN(e)},5e3);return()=>window.clearInterval(n)},[e,t.policies.length]),{policies:t.policies,revision:t.revision,status:t.status,loading:t.loading,error:t.error,refresh:r}}function $N({checked:e,disabled:t,onClick:n,label:r}){return(0,Z.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e,"aria-label":r,disabled:t,onClick:n,className:`relative inline-flex h-5 w-9 shrink-0 rounded-full border-2 border-transparent transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${e?`bg-primary`:`bg-muted-foreground/30`}`,children:(0,Z.jsx)(`span`,{className:`pointer-events-none inline-block h-4 w-4 rounded-full bg-background shadow transition-transform ${e?`translate-x-4`:`translate-x-0`}`})})}function eP({children:e,title:t}){return(0,Z.jsx)(`span`,{title:t,className:`rounded border px-1 py-px text-[10px] uppercase tracking-wide text-muted-foreground`,children:e})}function tP(e){let t=e.filter;return!t||!t.mime&&!t.filename&&(!t.schema||t.schema===`file`)?`Files`:t.mime===`image/*`&&!t.filename?`Images`:[t.schema&&t.schema!==`file`?t.schema:null,t.mime,t.filename].filter(Boolean).join(` · `)}function nP({workspaceId:e}){let{policies:t,revision:n,status:r,loading:i,error:a,refresh:o}=QN(e),{showToast:s}=wo(),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(``),m=(e,t)=>s({title:`Error`,description:e instanceof Error?e.message:t,variant:`destructive`}),h=async r=>{d(r.id);try{await PN(e,t.map(e=>e.id===r.id?{...e,enabled:!e.enabled}:e),n),ZN(e)}catch(e){m(e,`Could not update the policy`)}finally{d(null)}},g=async r=>{if(window.confirm(`Delete the storage policy for "${r.path}"? Files already placed on the targets stay where they are.`)){d(r.id);try{await PN(e,t.filter(e=>e.id!==r.id),n),ZN(e)}catch(e){m(e,`Could not delete the policy`)}finally{d(null)}}},_=async t=>{d(t.id),p(`Applying…`);try{let n=await LN(e,t.id,(e,t)=>p(`Applying… ${t.matched} planned, ${t.folders} folders`));s({title:n.failed?`Planning errors`:`Replication queued`,description:`${n.matched} documents and ${n.folders} folders planned${n.failed?`, ${n.failed} failed — see operation status`:``}.`,variant:n.failed?`destructive`:void 0}),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}catch(e){m(e,`Could not apply the policy`)}finally{d(null),p(``)}};return(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(gr,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Storage policies`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`A mirror keeps filed documents on its targets and moves removed copies to Trash. A filing policy makes copies that stay on the targets. Uploads are kept locally until every required destination has been verified.`}),r?.error&&(0,Z.jsx)(`p`,{role:`alert`,className:`mt-2 text-xs text-destructive`,children:r.error.message}),r?.operations?.operations.filter(e=>e.state!==`complete`).map(t=>(0,Z.jsxs)(`div`,{className:`mt-2 rounded border p-2 text-xs`,children:[(0,Z.jsxs)(`p`,{children:[t.owner,`: `,t.state]}),(0,Z.jsx)(`p`,{children:t.error?.message}),t.outcomes.map(e=>(0,Z.jsxs)(`p`,{children:[e.backend,`:`,e.key,` — `,e.state]},`${e.backend}:${e.key}`)),t.state===`blocked`&&(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>{BN(e,t.id).then(o).catch(e=>m(e,`Retry failed`))},children:`Retry`})]},t.id)),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`mt-2 text-xs text-destructive`,children:a})]}),i&&!t.length&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading…`}),!i&&!t.length&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(gr,{className:`mx-auto h-6 w-6 text-muted-foreground`}),(0,Z.jsx)(`p`,{className:`mt-2 text-sm`,children:`No storage policies yet.`}),(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Right-click a folder in the context or directory tree and choose `,(0,Z.jsx)(`span`,{className:`font-medium text-foreground`,children:`Storage policy…`}),` to mirror it to a backend.`]})]}),t.map(e=>{let t=u===e.id;return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4 ${e.enabled?``:`opacity-70`}`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`h3`,{className:`break-all font-mono text-sm font-semibold`,children:e.path}),e.recursive&&(0,Z.jsx)(eP,{children:`subfolders`}),(0,Z.jsx)(eP,{children:tP(e)}),!e.enabled&&(0,Z.jsx)(eP,{children:`disabled`})]}),e.description&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:e.description}),(0,Z.jsx)(`ul`,{className:`mt-2 space-y-1`,children:e.targets.map((e,t)=>(0,Z.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:`font-mono`,children:MN(e)}),e.recursive&&(0,Z.jsx)(eP,{children:`sub-path`}),e.recreateDirectories&&(0,Z.jsx)(eP,{children:`folders`}),e.key&&(0,Z.jsx)(eP,{title:e.key,children:`named`}),e.onConflict&&e.onConflict!==`error`&&(0,Z.jsx)(eP,{children:e.onConflict})]},`${e.backend}:${t}`))}),t&&f&&(0,Z.jsx)(`p`,{role:`status`,className:`mt-2 text-xs text-muted-foreground`,children:f})]}),(0,Z.jsx)($N,{checked:e.enabled,disabled:t,onClick:()=>h(e),label:e.enabled?`Disable policy`:`Enable policy`})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:t,onClick:()=>l(e),children:[(0,Z.jsx)(Lr,{className:`mr-1 h-3.5 w-3.5`}),`Edit`]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:t||!e.enabled,onClick:()=>_(e),children:[(0,Z.jsx)(Ar,{className:`mr-1 h-3.5 w-3.5`}),`Apply to existing`]}),(0,Z.jsxs)(Y,{variant:`ghost`,size:`sm`,onClick:()=>{o()},children:[(0,Z.jsx)(ui,{className:`mr-1 h-3.5 w-3.5`}),`Refresh status`]}),(0,Z.jsxs)(Y,{variant:`ghost`,size:`sm`,disabled:t,className:`text-destructive`,onClick:()=>g(e),children:[(0,Z.jsx)(Qr,{className:`mr-1 h-3.5 w-3.5`}),`Delete`]})]})]},e.id)}),c&&(0,Z.jsx)(UN,{workspaceId:e,path:c.path,policy:c,onClose:()=>l(null),onSaved:()=>{ZN(e),o()}})]})}var rP=e=>`${no.workspaces}/${encodeURIComponent(e)}`;async function iP(e){return await J.get(`${rP(e)}/mirrors`)||[]}async function aP(e,t){await J.delete(`${rP(e)}/mirrors/${encodeURIComponent(t)}`)}async function oP(e,t=10){return J.get(`${rP(e)}/mirrors/protection?sample=${t}`)}async function sP(e,t,n){return(await J.patch(`${rP(e)}/mirrors/${encodeURIComponent(t)}`,n)).replica}async function cP(e){return await J.get(`${rP(e)}/sync/conflicts`)||[]}async function lP(e,t,n){return J.post(`${rP(e)}/sync/conflicts/${t}/resolve`,{keep:n})}var uP=e=>{if(e==null||e===``)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?`—`:t.toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`})},dP=e=>e==null?`—`:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`,fP=e=>e?e.slice(0,12):`—`;function pP({mirror:e,now:t,busy:n,onForget:r,onRequired:i}){let a=e.mirror,o=!e.lastSeen||t-new Date(e.lastSeen).getTime()>6e5,s=e.replica?.role===`cache`||a.client===`fuse`,c=e.replica?.required===!0,l=a.direction||(a.client===`fuse`?`bi`:void 0);return(0,Z.jsx)(`div`,{className:`rounded-lg border p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(Ha,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:e.name||e.deviceId}),a.client&&(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-mono uppercase`,children:a.client}),l&&(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-mono`,title:l===`pull`?`Backup target: the hub is the only writer`:l===`push`?`One-shot import: local is the only writer`:`Both ways`,children:l===`pull`?`⇣ pull`:l===`push`?`⇡ push`:`⇅ bi`}),c&&(0,Z.jsx)(`span`,{className:`rounded bg-emerald-500/15 px-1.5 py-0.5 text-[10px] font-mono text-emerald-700 dark:text-emerald-300`,title:`Counts toward protection`,children:`required`}),(0,Z.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] font-mono ${o?`bg-muted text-muted-foreground`:`bg-emerald-500/15 text-emerald-700 dark:text-emerald-300`}`,children:a.state||(o?`offline`:`online`)})]}),a.path&&(0,Z.jsx)(`p`,{className:`mt-0.5 text-[11px] font-mono text-muted-foreground truncate`,children:a.path}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 gap-y-0.5 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{title:`Change-log entries the device has not applied yet`,children:[`lag `,e.lag??`—`]}),(0,Z.jsxs)(`span`,{title:`Local changes waiting to be pushed`,children:[`pending `,a.pending??0]}),(a.failed??0)>0&&(0,Z.jsxs)(`span`,{className:`text-destructive`,children:[`failed `,a.failed]}),(a.conflicts??0)>0&&(0,Z.jsxs)(`span`,{className:`text-amber-600 dark:text-amber-400`,children:[`conflicts `,a.conflicts]}),(a.skipped??0)>0&&(0,Z.jsxs)(`span`,{children:[`skipped `,a.skipped]}),(a.reverted??0)>0&&(0,Z.jsxs)(`span`,{title:`Local edits parked in .workspace/conflicts and replaced by the hub version`,children:[`reverted `,a.reverted]}),e.behind!=null&&(0,Z.jsxs)(`span`,{title:`Documents whose current version this device does not hold yet`,className:e.behind>0&&c?`text-amber-600 dark:text-amber-400`:``,children:[`behind `,e.behind]}),(0,Z.jsxs)(`span`,{children:[`last sync `,uP(a.lastSync)]}),(0,Z.jsxs)(`span`,{children:[`seen `,uP(e.lastSeen)]}),a.prefixes&&a.prefixes.length>0&&(0,Z.jsx)(`span`,{className:`font-mono`,children:a.prefixes.join(`, `)})]}),a.lastError&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-destructive`,children:a.lastError}),(0,Z.jsxs)(`label`,{className:`mt-2 flex items-center gap-2 text-[11px] ${s?`text-muted-foreground`:``}`,title:s?`A cache never counts toward protection`:`A document is protected once every required replica holds its current version`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-3 w-3`,checked:c,disabled:n||s,onChange:e=>i(e.target.checked)}),`required for protection`]})]})]}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:r,disabled:n,title:`Forget this mirror record (the device is not revoked)`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]})})}function mP({p:e}){let t=e.required.length===0,n=e.unprotected??0,r=t||n>0?ha:Fi,i=t?`text-muted-foreground`:n>0?`text-amber-600 dark:text-amber-400`:`text-emerald-700 dark:text-emerald-300`;return(0,Z.jsx)(`div`,{className:`rounded-lg border p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 mt-0.5 shrink-0 ${i}`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 text-[11px]`,children:[t?(0,Z.jsxs)(`p`,{className:`text-sm`,children:[`No replica is marked `,(0,Z.jsx)(`span`,{className:`font-medium`,children:`required`}),` yet — nothing is counted as protected. Tick it on the device that must hold every document (the backup).`]}):(0,Z.jsxs)(`p`,{className:`text-sm`,children:[(0,Z.jsxs)(`span`,{className:`font-medium ${i}`,children:[e.protected??0,` of `,e.total-e.unversioned]}),` documents are held at their current version by every required replica`,n>0&&(0,Z.jsxs)(`span`,{className:i,children:[` · `,n,` not yet`]}),e.partial&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[` (first `,e.total,` checked)`]})]}),e.oldestUnprotected.length>0&&(0,Z.jsxs)(`ul`,{className:`mt-1 space-y-0.5 font-mono text-muted-foreground`,children:[e.oldestUnprotected.slice(0,5).map(e=>(0,Z.jsxs)(`li`,{className:`truncate`,title:`document ${e.docId} v${e.version}`,children:[e.key,` `,(0,Z.jsxs)(`span`,{className:`opacity-70`,children:[`· `,uP(e.mtime)]})]},`${e.docId}:${e.key}`)),e.oldestUnprotected.length>5&&(0,Z.jsxs)(`li`,{children:[`… and `,e.oldestUnprotected.length-5,` more`]})]})]})]})})}function hP({conflict:e,busy:t,onResolve:n}){let r=!e.hub;return(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Z.jsx)(dr,{className:`h-4 w-4 text-amber-500 mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium font-mono break-all`,children:e.key}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`from `,(0,Z.jsx)(`span`,{className:`font-medium`,children:e.deviceName||e.device||`unknown device`}),` · `,uP(e.ts),e.mode===`rename`&&e.conflictKey&&(0,Z.jsxs)(Z.Fragment,{children:[` · already on disk as `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.conflictKey})]})]})]})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 text-[11px] sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`rounded border border-dashed p-2`,children:[(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`Hub version (keeps the name)`}),e.hub?(0,Z.jsxs)(`div`,{className:`font-mono`,children:[fP(e.hub.sha256),` · `,dP(e.hub.size),` · `,uP(e.hub.mtime)]}):(0,Z.jsx)(`div`,{className:`italic text-muted-foreground`,children:`no file at this key any more`})]}),(0,Z.jsxs)(`div`,{className:`rounded border border-dashed p-2`,children:[(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`Incoming version (the device’s)`}),(0,Z.jsxs)(`div`,{className:`font-mono`,children:[fP(e.incoming.sha256),` · `,dP(e.incoming.size),` · `,uP(e.incoming.mtime)]})]})]}),e.resolvable?(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:t||r,onClick:()=>n(`hub`),title:`Discard the device's version`,children:`Keep hub`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:()=>n(`incoming`),title:`The device's bytes replace the hub's; tags, relations and placements move over`,children:`Keep incoming`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:()=>n(`both`),title:`Keep the hub file and add the device's version under a conflict name`,children:`Keep both`})]}):(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Dropbox-style conflict copy: both files are on disk, delete the one you do not need.`})]})}function gP({workspaceId:e,workspaceUuid:t}){let{showToast:n}=wo(),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(0),h=(0,X.useRef)(null),g=(0,X.useCallback)(async(t=!1)=>{if(e){t||u(!0);try{let[t,n,r]=await Promise.all([iP(e),cP(e),oP(e).catch(()=>null)]);i(t),o(n),c(r),m(Date.now())}catch(e){t||n({title:`Error`,description:e instanceof Error?e.message:`Failed to load sync state`,variant:`destructive`})}finally{t||u(!1)}}},[e]);(0,X.useEffect)(()=>{g()},[g]),(0,X.useEffect)(()=>{if(!t)return;let e=`workspace:${t}`,n=()=>B.emit(`subscribe`,{channel:e}),r=B.on(`connect`,n);n();let i=e=>{let n=e;n?.workspaceId&&n.workspaceId!==t||(h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,g(!0)},800))},a=[`backend.changed`,`sync.conflict.created`,`sync.conflict.resolved`].map(e=>B.on(e,i));return()=>{r(),a.forEach(e=>e()),B.emit(`unsubscribe`,{channel:e}),h.current&&=(clearTimeout(h.current),null)}},[t,g]);let _=async t=>{f(`mirror:${t}`);try{await aP(e,t),i(e=>e.filter(e=>e.deviceId!==t)),n({title:`Forgotten`,description:`Mirror record removed. The device keeps running and will report again if it still syncs this workspace.`})}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to forget mirror`,variant:`destructive`})}finally{f(null)}},v=async(t,r)=>{f(`mirror:${t}`);try{let n=await sP(e,t,{required:r});i(e=>e.map(e=>e.deviceId===t?{...e,replica:{role:n.role,required:n.required}}:e)),c(await oP(e).catch(()=>null))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to update replica policy`,variant:`destructive`})}finally{f(null)}},y=async(t,r)=>{f(`conflict:${t.docId}`);try{let i=await lP(e,t.docId,r);o(e=>e.filter(e=>e.docId!==t.docId));let a=r===`hub`?`kept the hub version`:r===`incoming`?`the device version now holds the name`:`kept both (${i.resultKey||`conflict copy`})`;n({title:`Resolved`,description:`${t.key}: ${a}`})}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to resolve conflict`,variant:`destructive`})}finally{f(null)}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Device mirrors`}),(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Devices keeping this workspace’s files in sync (canvas-fuse `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`--mirror`}),`, canvas-edge). Lag counts change-log entries the device has not applied yet.`]})]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>g(),disabled:l,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${l?`animate-spin`:``}`}),`Refresh`]})]}),l&&r.length===0&&a.length===0?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):r.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4 text-xs text-muted-foreground`,children:[`No device mirrors this workspace yet. Mount it with `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`canvas-fuse mount -w <workspace> ~/Workspaces --mirror`}),` on a device and it shows up here.`]}):(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[s&&(0,Z.jsx)(mP,{p:s}),r.map(e=>(0,Z.jsx)(pP,{mirror:e,now:p,busy:d===`mirror:${e.deviceId}`,onForget:()=>_(e.deviceId),onRequired:t=>v(e.deviceId,t)},e.deviceId))]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Conflicts`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`A device and the hub both changed the same file. The hub’s version keeps the filename; decide what happens to the device’s. Tags, relations and placements follow whichever version survives.`})]}),a.length===0?(0,Z.jsx)(`div`,{className:`rounded-lg border border-dashed p-4 text-xs text-muted-foreground`,children:`Nothing to resolve.`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:a.map(e=>(0,Z.jsx)(hP,{conflict:e,busy:d===`conflict:${e.docId}`,onResolve:t=>y(e,t)},e.docId))})]})}function _P({workspaceId:e,address:t,selectedChats:n=[],onSaved:r}){let[i,a]=(0,X.useState)(n),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(``);return(0,X.useEffect)(()=>{if(!c)return;let n=!1,r,i=async()=>{try{let r=await ue(e,t);n||(d(r),p(``))}catch(e){n||p(e instanceof Error?e.message:`Connection unavailable`)}n||(r=setTimeout(()=>void i(),3e3))};return i(),()=>{n=!0,clearTimeout(r)}},[e,t,c]),(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>{c||a(n),l(!c)},children:c?`Close connection panel`:`Pair / connection status`}),c&&(0,Z.jsxs)(`div`,{className:`space-y-2 p-2 text-xs`,children:[(0,Z.jsx)(`p`,{children:f||u?.state||`Connecting…`}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>{window.confirm(`Forget the current session and pair this account again?`)&&rn(e,t).catch(e=>p(e.message))},children:`Pair again`}),u?.qr&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{children:`WhatsApp → Settings → Linked devices → Link a device.`}),(0,Z.jsx)(`img`,{className:`max-w-full`,src:u.qr,width:256,height:256,alt:`WhatsApp device pairing QR code`})]}),u?.chats.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{children:`Select conversations to synchronize into this workspace.`}),(0,Z.jsx)(`div`,{className:`max-h-48 overflow-auto`,children:u.chats.map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:o,checked:i.includes(e.id),onChange:t=>a(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id))}),e.name,` · `,(0,Z.jsx)(`code`,{children:e.id})]},e.id))}),(0,Z.jsx)(Y,{size:`sm`,disabled:o,onClick:async()=>{s(!0),p(``);try{await Fo(e,`whatsapp`,t,{chats:i}),await r?.()}catch(e){p(e instanceof Error?e.message:`Could not save conversations`)}finally{s(!1)}},children:o?`Saving…`:`Save conversations and sync`}),!i.length&&(0,Z.jsx)(`p`,{children:`No conversations selected; messages will not be synchronized.`})]}):null]})]})}async function vP(){return(await J.get(`/oauth/google/redirect-uri`)).redirectUri}async function yP(e){let t=window.open(`about:blank`,`canvas-google-oauth`,`popup=yes,width=540,height=720`),n;try{n=await J.post(`/oauth/google/start`,e)}catch(e){throw t?.close(),e}if(!t)throw Error(`Popup blocked — allow popups for this site and try again`);t.location.href=n.url;let r=new URL(yo,window.location.origin).origin;return new Promise((e,i)=>{let a=!1,o=e=>{a||(a=!0,window.removeEventListener(`message`,s),window.clearInterval(c),window.clearTimeout(l),e())},s=t=>{if(t.origin!==r)return;let a=t.data;!a||a.type!==`canvas:oauth`||a.provider!==`google`||a.state!==n.state||(a.ok&&a.refreshToken?o(()=>e({refreshToken:a.refreshToken,account:a.account})):o(()=>i(Error(a.error||`Google sign-in failed`))))};window.addEventListener(`message`,s);let c=window.setInterval(()=>{t.closed&&window.setTimeout(()=>o(()=>i(Error(`Sign-in window closed before finishing`))),500)},500),l=window.setTimeout(()=>o(()=>{t.close(),i(Error(`Sign-in timed out`))}),n.expiresInMs||6e5)})}function bP({clientId:e,clientSecret:t,scope:n,onLinked:r,disabled:i}){let[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),{showToast:l}=wo(),u=e.trim().length>0&&t.trim().length>0;(0,X.useEffect)(()=>{let e=!1;return vP().then(t=>{e||c(t)}).catch(()=>{}),()=>{e=!0}},[]);let d=async()=>{o(!0);try{let i=await yP({clientId:e.trim(),clientSecret:t.trim(),scope:n});r(i),l({title:`Google account linked`,description:i.account?`Refresh token obtained for ${i.account}`:`Refresh token obtained`})}catch(e){l({title:`Google sign-in failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{o(!1)}};return(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:i||a||!u,onClick:()=>{d()},title:u?`Open the Google consent screen and fill in the refresh token`:`Enter the OAuth client id and secret first`,children:[(0,Z.jsx)(f,{icon:`mdi:google`,width:14,height:14,className:`mr-2`}),a?`Waiting for Google…`:`Sign in with Google to get a refresh token`]}),s&&(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground/80 break-all`,children:[`Register this redirect URI on the OAuth client (Google Cloud Console → Credentials → your Web application client → Authorized redirect URIs):`,` `,(0,Z.jsx)(`code`,{className:`select-all`,children:s})]})]})}var xP={git:{label:`Git repository`,icon:`mdi:git`,blurb:`Create a local repository or clone a remote into the workspace. Branches appear under Backends → Workspace → Git. Use Auto-Link on a branch or folder afterward to file its documents into a virtual tree.`,fields:[{key:`address`,label:`Repository name`,placeholder:`company-ui`,required:!0},{key:`url`,label:`Remote URL`,placeholder:`git@github.com:company/ui.git`,hint:`Leave empty for a local repository. Private repos use the server’s SSH keys or Git credential helper.`},{key:`branches`,label:`Branches to browse (empty means all)`,list:!0,placeholder:`main, jira-1234/myusername-int-qf`}]},github:{label:`GitHub Issues`,icon:`mdi:github`,blurb:`Issues from the listed github.com or GitHub Enterprise repos sync as todos. Token optional for public repos.`,fields:[{key:`address`,label:`Account label`,placeholder:`e.g. canvas-ui`,required:!0},{key:`baseUrl`,label:`GitHub Enterprise URL`,placeholder:`https://ghe.example.com`,hint:`Leave blank for github.com. Works with GitHub Enterprise Server (ghe.example.com) and GHE.com (yourco.ghe.com) — the web address is enough.`},{key:`token`,label:`Personal access token`,hint:`Optional for public repos; required for write-back and @me filters.`,secret:!0},{key:`repos`,label:`Repositories`,placeholder:`owner/repo, one per line`,hint:`owner/repo or the repo’s URL. Issues from each repo sync as todos.`,list:!0,required:!0},{key:`assignee`,label:`Only issues assigned to`,placeholder:`@me, a login, * or none`,hint:`Filters are applied by GitHub and combined with AND. Changing one re-syncs from scratch.`},{key:`creator`,label:`Only issues opened by`,placeholder:`@me or a login`},{key:`mentioned`,label:`Only issues mentioning`,placeholder:`@me or a login`},{key:`labels`,label:`Only issues with all of these labels`,placeholder:`one per line`,list:!0},{key:`openOnly`,label:`Skip closed issues on first import`,hint:`Issues closed later still sync as completed.`,bool:!0},{key:`writeBack`,label:`Manage issues from Canvas`,hint:`Create, edit and close issues. Needs a PAT with repo scope.`,bool:!0},{key:`pruneRemoved`,label:`Remove items deleted at the source`,hint:`After each sync, issues that no longer exist in the repo are dropped from the mirror (kept as location-less orphans until database retention GC; skipped whenever the repo can’t be fully listed).`,bool:!0}]},slack:{label:`Slack`,icon:`mdi:slack`,blurb:`Channel messages sync as message documents. Bot/user token with channels:read + channels:history.`,fields:[{key:`address`,label:`Workspace label`,placeholder:`e.g. acme`,required:!0},{key:`token`,label:`Token (xoxb-… / xoxp-…)`,secret:!0,required:!0},{key:`channels`,label:`Conversations (channel names or IDs; DM IDs need im:read + im:history)`,list:!0},{key:`directMessages`,label:`Include direct messages`,hint:`Requires im:read, im:history, mpim:read and mpim:history.`,bool:!0},{key:`writeBack`,label:`Allow sending from Canvas`,hint:`Token also needs chat:write.`,bool:!0},{key:`allowAgentSend`,label:`Allow agents with workspace write access to send`,bool:!0}]},whatsapp:{label:`WhatsApp (linked device)`,icon:`mdi:whatsapp`,blurb:`Pair your phone with Canvas, then choose conversations. Uses Baileys; separate from WhatsApp Business.`,fields:[{key:`address`,label:`Account label`,placeholder:`personal`,hint:`Any unique label; no phone number required. Keep it unchanged after pairing.`,required:!0},{key:`chats`,label:`Conversation IDs to sync (one per line; available after pairing)`,list:!0},{key:`writeBack`,label:`Allow sending from Canvas`,bool:!0},{key:`allowAgentSend`,label:`Allow agents with workspace write access to send`,bool:!0}]},gcal:{label:`Google Calendar`,icon:`mdi:calendar-month`,blurb:`Events sync as calendar entries (recurring series kept as series). Offline-access OAuth credentials.`,fields:[{key:`address`,label:`Account label`,placeholder:`e.g. me-gmail`,required:!0},{key:`clientId`,label:`OAuth client id`,required:!0},{key:`clientSecret`,label:`OAuth client secret`,secret:!0,required:!0},{key:`refreshToken`,label:`Refresh token`,secret:!0,required:!0,oauth:`google`,oauthScope:`calendar.readonly`},{key:`calendars`,label:`Calendar ids (empty = primary)`,list:!0}]},caldav:{label:`CalDAV`,icon:`mdi:calendar-sync`,blurb:`Any CalDAV endpoint (GroupOffice, Nextcloud, Radicale, SOGo…). Read-only by default; enable write-back to create events from Canvas.`,fields:[{key:`address`,label:`Account label`,placeholder:`e.g. groupoffice`,required:!0},{key:`url`,label:`CalDAV URL (calendar home or one calendar)`,placeholder:`https://host/caldav/user`,required:!0},{key:`username`,label:`Username`},{key:`password`,label:`Password`,secret:!0},{key:`calendars`,label:`Calendars (names, empty = all)`,list:!0},{key:`writeBack`,label:`Create events from Canvas`,hint:`Write-back into the CalDAV calendar.`,bool:!0}]},teams:{label:`MS Teams`,icon:`mdi:microsoft-teams`,blurb:`Channel messages via Microsoft Graph (app-only credentials, admin-consented ChannelMessage.Read.All).`,fields:[{key:`address`,label:`Tenant label`,placeholder:`e.g. corp`,required:!0},{key:`tenantId`,label:`Tenant id`,required:!0},{key:`clientId`,label:`Client id`,required:!0},{key:`clientSecret`,label:`Client secret`,secret:!0,required:!0},{key:`teams`,label:`Team ids (one per line)`,list:!0,required:!0}]}};function SP(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean)}function CP({workspaceId:e}){let{showToast:t}=wo(),[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)({}),[u,d]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),h=(0,X.useCallback)(async()=>{let t=await Rc(e).catch(()=>[]);r(t.filter(e=>e.kind===`connector`))},[e]),g=async()=>{m(!0);try{await h()}finally{m(!1)}};(0,X.useEffect)(()=>{let t=!1;return Rc(e).then(e=>{t||r(e.filter(e=>e.kind===`connector`))}).catch(()=>{}),()=>{t=!0}},[e]);let _=n.some(e=>e.status===`syncing`);(0,X.useEffect)(()=>{if(!_)return;let e=setInterval(()=>{h()},4e3);return()=>clearInterval(e)},[_,h]);let v=e=>{let t=xP[e.driver];if(!t)return;let n=e.config||{},r={};for(let i of t.fields){if(i.key===`address`){r.address=e.address;continue}if(i.secret)continue;if(i.key===`writeBack`){r.writeBack=n.readOnly===!1&&(![`slack`,`whatsapp`].includes(e.driver)||n.sendEnabled===!0)?`true`:``;continue}let t=n[i.key];if(i.list){r[i.key]=Array.isArray(t)?t.join(`
|
|
44
|
+
`):``;continue}t!=null&&(r[i.key]=String(t))}l(r),a(e.driver),s(e)},y=()=>{a(null),s(null),l({})},b=async()=>{if(!i)return;let n=xP[i],r={};for(let e of n.fields){let n=(c[e.key]||``).trim();if(!n){if(e.required&&!(o&&e.secret)){t({title:`${e.label} is required`,variant:`destructive`});return}o&&!e.secret&&(r[e.key]=e.list?[]:!e.bool&&``);continue}r[e.key]=e.list?SP(n):e.bool?n===`true`:n}n.fields.some(e=>e.key===`writeBack`)&&([`slack`,`whatsapp`].includes(i)&&(r.sendEnabled=r.writeBack===!0),r.readOnly=r.writeBack!==!0,delete r.writeBack),i===`git`&&(r.enabled=!0),d(!0);try{o?await Fo(e,o.driver,o.address,r):await Zs(e,i,r),y(),await h(),t({title:o?`Connector updated; sync restarted`:`Connector saved; first sync started`})}catch(e){t({title:`Failed to save connector`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{d(!1)}},x=async n=>{try{n.driver===`git`&&n.enabled===!1?await Fo(e,n.driver,n.address,{enabled:!0}):await Js(e,n.driver,n.address),t({title:`Syncing ${n.driver}/${n.address}`}),setTimeout(()=>{h()},1500)}catch(e){t({title:`Sync failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},S=async n=>{let r=n.driver===`git`?`Stop syncing ${n.address}? Its checkout and existing tree documents will stay available.`:`Remove ${n.driver}/${n.address}? Synced documents stay in the backends tree until purged.`;if(window.confirm(r))try{await Xo(e,n.driver,n.address),await h()}catch(e){t({title:`Remove failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}};return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Connectors`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Git repositories, GitHub issues, Slack, Google Calendar, CalDAV and MS Teams, polled into the backends tree (read-only unless write-back is enabled).`})]}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:p,onClick:()=>{g()},title:`Refresh`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5 ${p?`animate-spin`:``}`})})]}),n.length>0&&(0,Z.jsx)(`div`,{className:`mt-3 space-y-2`,children:n.map(t=>{let n=xP[t.driver];return(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[t.driver===`whatsapp`&&(0,Z.jsx)(_P,{workspaceId:e,address:t.address,selectedChats:Array.isArray(t.config?.chats)?t.config.chats:[],onSaved:h}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(f,{icon:n?.icon||`mdi:cloud-sync`,width:16,height:16,className:`shrink-0`}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:n?.label||t.driver}),(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:t.address}),(0,Z.jsx)(`span`,{className:`flex-1`}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:t.status===`syncing`,onClick:()=>{x(t)},children:[(0,Z.jsx)(Er,{className:`mr-1 h-3 w-3 ${t.status===`syncing`?`animate-spin`:``}`}),t.status===`syncing`?`Syncing`:t.driver===`git`&&t.enabled===!1?`Resume sync`:`Sync now`]}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>v(t),title:`Edit connector`,children:(0,Z.jsx)(Lr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{S(t)},disabled:t.driver===`git`&&t.enabled===!1,title:t.driver===`git`?`Stop syncing`:`Remove connector`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5 text-destructive`})})]}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`status: `,t.status]}),t.lastSyncAt&&(0,Z.jsxs)(`span`,{children:[`last sync: `,new Date(t.lastSyncAt).toLocaleString()]}),t.treePath&&(0,Z.jsx)(`span`,{className:`font-mono`,children:t.treePath})]}),t.lastError&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-destructive`,children:t.lastError})]},`${t.driver}:${t.address}`)})}),i?(0,Z.jsxs)(`div`,{className:`mt-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(f,{icon:xP[i].icon,width:16,height:16}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:o?`Edit ${xP[i].label}`:xP[i].label}),o&&(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:o.address}),(0,Z.jsx)(`span`,{className:`flex-1`}),(0,Z.jsx)(`button`,{type:`button`,onClick:y,className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:xP[i].blurb}),(0,Z.jsx)(`div`,{className:`mt-2 grid gap-2 sm:grid-cols-2`,children:xP[i].fields.map(e=>(0,Z.jsxs)(`label`,{className:`text-xs ${e.list||e.bool?`sm:col-span-2`:``}`,children:[!e.bool&&(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:e.label}),e.bool?(0,Z.jsxs)(`span`,{className:`mt-1 flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:c[e.key]===`true`,onChange:t=>l(n=>({...n,[e.key]:t.target.checked?`true`:``})),className:`h-4 w-4 accent-primary`}),(0,Z.jsx)(`span`,{children:e.label})]}):e.list?(0,Z.jsx)(`textarea`,{value:c[e.key]||``,onChange:t=>l(n=>({...n,[e.key]:t.target.value})),placeholder:e.placeholder,rows:2,className:`mt-1 w-full rounded-md border border-input bg-background px-2 py-1.5 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}):(0,Z.jsx)(q,{type:e.secret?`password`:`text`,value:c[e.key]||``,disabled:!!o&&e.key===`address`,onChange:t=>l(n=>({...n,[e.key]:t.target.value})),placeholder:o&&e.secret?`Leave blank to keep current`:e.placeholder,autoComplete:`off`,className:`mt-1 h-8 text-xs`}),e.hint&&(0,Z.jsx)(`span`,{className:`mt-0.5 block text-[11px] text-muted-foreground/80`,children:e.hint}),e.oauth===`google`&&(0,Z.jsx)(`span`,{className:`mt-1.5 block`,children:(0,Z.jsx)(bP,{clientId:c.clientId||``,clientSecret:c.clientSecret||``,scope:e.oauthScope||`calendar.readonly`,disabled:u,onLinked:({refreshToken:t,account:n})=>l(r=>({...r,[e.key]:t,address:(r.address||``).trim()||(n?n.replace(/[^a-z0-9]+/gi,`-`).replace(/^-|-$/g,``).toLowerCase():``)}))})})]},e.key))}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,className:`mt-3`,disabled:u,onClick:()=>{b()},children:u?`Saving…`:o?`Save changes & sync`:`Save & sync`})]}):(0,Z.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:Object.entries(xP).map(([e,t])=>(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{a(e),l({})},children:[(0,Z.jsx)(br,{className:`mr-1 h-3 w-3`}),(0,Z.jsx)(f,{icon:t.icon,width:14,height:14,className:`mr-1`}),t.label]},e))})]})}var wP={host:``,port:993,tls:!0,allowSelfSigned:!0,user:``,password:``,pollInterval:6e4,initialSyncDays:180,smtp:{enabled:!1,host:``,port:587,secure:!1,user:``,password:``,from:``,sentFolder:`Sent`,appendSent:!1,allowAgentSend:!1}};function TP(e){let t=e.config||{};return{host:String(t.host||``),port:Number(t.port??993),tls:t.tls!==!1,allowSelfSigned:t.allowSelfSigned!==!1,user:String(t.user||e.address),password:``,pollInterval:Number(t.pollInterval??6e4),initialSyncDays:Number(t.initialSyncDays??180),smtp:{...wP.smtp,...t.smtp||{},password:``}}}function EP(e,t,n,r){let{password:i,...a}=e.smtp;return{host:e.host.trim(),user:e.user.trim(),port:Number(e.port)||993,tls:e.tls,allowSelfSigned:e.allowSelfSigned,pollInterval:Number(e.pollInterval)||6e4,initialSyncDays:Math.max(0,Number(e.initialSyncDays)||0),smtp:{...a,...(!t||r)&&i?{password:i}:{}},...(!t||n)&&e.password?{password:e.password}:{}}}function DP({workspaceId:e,enabled:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)([]);(0,X.useEffect)(()=>{let t=!0;return Rc(e).then(e=>{t&&a(e.filter(e=>e.kind===`storage`))}).catch(()=>{}),()=>{t=!1}},[e]);let[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(wP),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),b=(0,X.useRef)(0),[x,S]=(0,X.useState)([]),[C,w]=(0,X.useState)([`INBOX`]),[T,E]=(0,X.useState)(!0),[D,O]=(0,X.useState)(!1),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(null),{showToast:N,showProgress:P}=wo(),ee=(0,X.useMemo)(()=>[...n].sort((e,t)=>e.address.localeCompare(t.address)),[n]),F=(0,X.useMemo)(()=>n.find(e=>e.address===c)||null,[n,c]),I=(0,X.useCallback)(()=>Rc(e,`imap`).then(e=>r(e)).catch(e=>{N({title:`Error`,description:e instanceof Error?e.message:`Failed to load IMAP accounts`,variant:`destructive`})}).finally(()=>E(!1)),[e,N]),te=(0,X.useCallback)(async()=>{E(!0),await I()},[I]),[L,R]=(0,X.useState)(e);e!==L&&(R(e),E(!0),l(null),d(!1),p(wP),S([]),w([`INBOX`]),y(!1),h(!1),_(!1)),(0,X.useEffect)(()=>{I()},[I]),(0,X.useEffect)(()=>()=>{b.current++},[e]);let ne=(0,X.useCallback)(async(t,n)=>{let r=++b.current;O(!0);try{let i=t?await Rs(e,`imap`,t.address):await ns(e,`imap`,{host:(n?.host||``).trim(),port:Number(n?.port)||993,tls:n?.tls!==!1,allowSelfSigned:n?.allowSelfSigned!==!1,user:(n?.user||``).trim(),password:n?.password||``,folder:`INBOX`});r===b.current&&S(i.filter(e=>e.selectable))}catch(e){r===b.current&&N({title:`IMAP Error`,description:e instanceof Error?e.message:`Failed to discover folders`,variant:`destructive`})}finally{r===b.current&&O(!1)}},[e,N]),re=()=>{b.current++,O(!1),d(!1),l(null),p(wP),S([]),w([`INBOX`]),h(!1),_(!1),y(!1)},ie=e=>{if(!k){if(c===e.address){re();return}b.current++,O(!1),d(!1),l(e.address),p(TP(e)),S([]),w((e.containers||[]).map(e=>e.name)),h(!1),_(!1),y(!1)}},ae=()=>{re(),d(!0)},z=(e,t)=>{y(!0),p(n=>({...n,[e]:t}))},oe=e=>{y(!0),w(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},se=(0,X.useMemo)(()=>{let e=new Map(x.map(e=>[e.path,e]));for(let t of C)e.has(t)||e.set(t,{name:t,path:t,delimiter:`/`,selectable:!0,attributes:[]});return[...e.values()].sort((e,t)=>e.path.localeCompare(t.path))},[x,C]),B=async()=>{A(!0);try{let t=C.length?C:[`INBOX`],n=EP(f,!!F,m,g);if(F){await Fo(e,`imap`,F.address,n);let r=new Set((F.containers||[]).map(e=>e.name)),i=t.filter(e=>!r.has(e)),a=[...r].filter(e=>!t.includes(e));i.length&&await Ns(e,`imap`,F.address,i);for(let t of a)await Os(e,`imap`,F.address,t)}else{await Zs(e,`imap`,{...n,password:f.password,folder:t[0]});let r=f.user.trim();t.length>1&&await Ns(e,`imap`,r,t.slice(1))}await te(),d(!1),l(f.user.trim()),p({...f,password:``,smtp:{...f.smtp,password:``}}),h(!1),_(!1),y(!1),N({title:`Saved`,description:`IMAP account ${f.user.trim()} saved; sync runs in the background`})}catch(e){N({title:`Error`,description:e instanceof Error?e.message:`Failed to save IMAP account`,variant:`destructive`})}finally{A(!1)}},ce=async()=>{if(!(!F||!window.confirm(`Delete IMAP account ${F.address} and all its folders?`))){M(`delete:${F.address}`);try{await Xo(e,`imap`,F.address),await te(),re(),N({title:`Deleted`,description:`IMAP account ${F.address} deleted`})}catch(e){N({title:`Error`,description:e instanceof Error?e.message:`Failed to delete account`,variant:`destructive`})}finally{M(null)}}},V=async(t,n)=>{M(`${t}:${n}`);try{t===`test`?await jc(e,`imap`,n):await et(P,e,`imap`,n,e=>{r(t=>t.map(t=>t.address===n?e:t))}),await te(),t===`test`&&N({title:`Success`,description:`${n} saved account test completed`})}catch(e){N({title:`Error`,description:e instanceof Error?e.message:`Failed to ${t}`,variant:`destructive`})}finally{M(null)}},le=async(t,n)=>{M(`folder-sync:${t}:${n}`);try{await js(e,`imap`,t,n),await te(),N({title:`Sync started`,description:`${t} · ${n} · rescanning the saved lookback window`})}catch(e){N({title:`Error`,description:e instanceof Error?e.message:`Failed to sync folder`,variant:`destructive`})}finally{M(null)}},ue=(0,Z.jsxs)(`form`,{className:`grid gap-3`,autoComplete:`off`,"aria-label":`IMAP account settings`,onSubmit:e=>e.preventDefault(),children:[(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`imap-host`,children:`Host`}),(0,Z.jsx)(q,{id:`imap-host`,name:`imap-host`,autoComplete:`off`,value:f.host,readOnly:!!F,onChange:e=>z(`host`,e.target.value),placeholder:`imap.example.com`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`imap-user`,children:`User (account)`}),(0,Z.jsx)(q,{id:`imap-user`,name:`imap-username`,autoComplete:`section-imap username`,value:f.user,readOnly:!!F,onChange:e=>z(`user`,e.target.value),placeholder:`me@example.com`})]}),(0,Z.jsx)(`div`,{className:`grid gap-2`,children:!F||m?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(G,{htmlFor:`imap-password`,children:F?`New IMAP password`:`Password`}),(0,Z.jsx)(q,{id:`imap-password`,name:`imap-password`,type:`password`,autoComplete:`section-imap new-password`,"data-lpignore":`true`,"data-1p-ignore":`true`,value:f.password,onChange:e=>z(`password`,e.target.value),placeholder:F?`Leave blank to keep current password`:`Password`})]}):(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-sm`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Saved IMAP password`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>h(!0),children:`Change IMAP password`})]})}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`imap-port`,children:`Port`}),(0,Z.jsx)(q,{id:`imap-port`,type:`number`,value:String(f.port),onChange:e=>z(`port`,Number(e.target.value||993))})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(G,{children:`Folders to sync`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void ne(F,f),disabled:D||!!F&&v||!F&&(!f.host.trim()||!f.user.trim()||!f.password),children:[D?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(ni,{className:`h-3 w-3`}),` Discover folders`]})]}),(0,Z.jsx)(`div`,{className:`max-h-56 overflow-y-auto rounded-md border p-2`,children:se.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?`Discovering folders…`:F?`No folders found on the server.`:`Fill in host, user and password, then discover the account’s folders. INBOX is synced by default.`}):(0,Z.jsx)(`div`,{className:`space-y-0.5`,children:se.map(e=>{let t=e.path.split(e.delimiter||`/`).length-1,n=x.some(t=>t.path===e.path);return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 rounded px-2 py-1 text-xs hover:bg-accent/50`,style:{paddingLeft:`${8+t*14}px`},children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:C.includes(e.path),onChange:()=>oe(e.path)}),(0,Z.jsx)(`span`,{className:`font-mono truncate`,children:e.path}),!n&&x.length>0&&(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`(subscribed, not on server)`})]},e.path)})})}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[C.length,` folder`,C.length===1?``:`s`,` selected; each synced as its own container. Unchecking a synced folder removes it on Save.`]})]}),(0,Z.jsxs)(`fieldset`,{className:`rounded border p-3 space-y-3 sm:col-span-2`,children:[(0,Z.jsx)(`legend`,{className:`px-1 text-sm font-medium`,children:`Outgoing email (SMTP)`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:!F||!f.smtp.enabled||k,onClick:()=>s(F.address),children:`Send test email`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Save your SMTP settings before testing. The test uses the saved account.`}),o&&(0,Z.jsx)(Ue,{workspaceId:e,initialAccount:{driver:`imap`,address:o},testEmail:!0,onClose:()=>s(null)}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:f.smtp.enabled,onChange:e=>z(`smtp`,{...f.smtp,enabled:e.target.checked})}),`Allow sending from Canvas`]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[[`host`,`user`,`from`,`sentFolder`].map(e=>(0,Z.jsxs)(`label`,{className:`text-xs`,children:[{host:`SMTP host`,user:`SMTP username`,from:`From address`,sentFolder:`Sent folder`}[e],(0,Z.jsx)(q,{name:`smtp-${e}`,value:f.smtp[e],autoComplete:e===`user`?`section-smtp username`:`off`,onChange:t=>z(`smtp`,{...f.smtp,[e]:t.target.value})})]},e)),f.smtp.enabled&&(!F||g)&&(0,Z.jsxs)(`label`,{className:`text-xs`,children:[`SMTP password (blank keeps current)`,(0,Z.jsx)(q,{name:`smtp-password`,type:`password`,autoComplete:`section-smtp new-password`,"data-lpignore":`true`,"data-1p-ignore":`true`,value:f.smtp.password,onChange:e=>z(`smtp`,{...f.smtp,password:e.target.value})})]}),F&&f.smtp.enabled&&!g&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>_(!0),children:`Change SMTP password`}),(0,Z.jsxs)(`label`,{className:`text-xs`,children:[`Port`,(0,Z.jsx)(q,{type:`number`,min:1,max:65535,value:f.smtp.port,onChange:e=>z(`smtp`,{...f.smtp,port:Number(e.target.value)})})]})]}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:f.smtp.secure,onChange:e=>z(`smtp`,{...f.smtp,secure:e.target.checked})}),`Implicit TLS (usually port 465; otherwise STARTTLS is required)`]}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:f.smtp.appendSent,onChange:e=>z(`smtp`,{...f.smtp,appendSent:e.target.checked})}),`Save a copy in the IMAP Sent folder (leave off if your provider does this automatically)`]}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:f.smtp.allowAgentSend,onChange:e=>z(`smtp`,{...f.smtp,allowAgentSend:e.target.checked})}),`Allow agents with workspace write access to send`]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`imap-lookback`,children:`Sync lookback (days)`}),(0,Z.jsx)(q,{id:`imap-lookback`,type:`number`,min:`0`,value:String(f.initialSyncDays),onChange:e=>z(`initialSyncDays`,Number(e.target.value||0))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Used for the first sync and every Resync. Set 0 to import the whole mailbox. Saving a wider window automatically fetches older mail; a narrower window keeps messages already imported.`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`imap-poll`,children:`Poll interval (ms)`}),(0,Z.jsx)(q,{id:`imap-poll`,type:`number`,value:String(f.pollInterval),onChange:e=>z(`pollInterval`,Number(e.target.value||6e4))})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:f.tls,onChange:e=>z(`tls`,e.target.checked)}),` TLS`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:f.allowSelfSigned,onChange:e=>z(`allowSelfSigned`,e.target.checked)}),` Allow self-signed`]})]})]});return(0,Z.jsxs)(`div`,{className:`space-y-3 border-t pt-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`h4`,{className:`text-sm font-medium`,children:`IMAP Accounts`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Each account mirrors under /imap/<account> in the backends tree; its folders are synced as containers. Click an account to edit its settings.`})]}),!t&&(0,Z.jsx)(`p`,{className:`rounded-md border bg-muted/40 p-2 text-xs text-muted-foreground`,children:`Enable the IMAP service before polling starts. Accounts can still be configured while it is off.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:u?re:ae,children:[(0,Z.jsx)(la,{className:`h-3 w-3`}),` `,u?`Cancel`:`New Account`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,onClick:te,disabled:T,children:[T?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Er,{className:`h-3 w-3`}),` Refresh`]})]}),(0,Z.jsx)(`div`,{className:`rounded-md border`,children:(0,Z.jsx)(`div`,{className:`max-h-[32rem] overflow-y-auto p-2 space-y-1`,children:ee.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No IMAP accounts configured.`}):ee.map(t=>{let n=c===t.address;return(0,Z.jsxs)(`div`,{className:`rounded px-2 py-2 text-xs transition-colors ${n?`bg-accent/40`:`hover:bg-accent/50`}`,children:[(0,Z.jsxs)(`button`,{onClick:()=>ie(t),className:`w-full text-left`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5 font-medium`,children:[n?(0,Z.jsx)(qr,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(Xa,{className:`h-3 w-3 shrink-0`}),t.address]}),(0,Z.jsx)(`span`,{className:`shrink-0 ${t.status===`error`?`text-destructive`:`text-muted-foreground`}`,children:t.status})]}),(0,Z.jsxs)(`div`,{className:`pl-[18px] text-muted-foreground`,children:[String(t.config?.host||``),` · `,(t.containers||[]).length,` folder(s)`]}),t.lastError&&(0,Z.jsxs)(`div`,{className:`pl-[18px] text-destructive`,children:[`error: `,t.lastError]})]}),n&&(0,Z.jsxs)(`div`,{className:`mt-2 space-y-3 border-t pt-2`,children:[(0,Z.jsx)(`div`,{className:`space-y-0.5`,children:(t.containers||[]).map(n=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded bg-background/60 px-2 py-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono truncate`,children:n.name}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[(0,Z.jsx)(`button`,{title:`Resync folder`,className:`p-1 hover:bg-accent rounded`,onClick:()=>le(t.address,n.name),disabled:!!j||v||k,children:j===`folder-sync:${t.address}:${n.name}`?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Er,{className:`h-3 w-3`})}),(0,Z.jsx)(`button`,{title:`Remove folder`,className:`p-1 hover:bg-destructive/10 text-destructive rounded`,onClick:()=>Os(e,`imap`,t.address,n.name).then(te).catch(e=>N({title:`Error`,description:e instanceof Error?e.message:`Failed to remove folder`,variant:`destructive`})),disabled:!!j,children:(0,Z.jsx)(Qr,{className:`h-3 w-3`})})]})]},n.name))}),(t.containers||[]).map(n=>(0,Z.jsxs)(`div`,{className:`rounded border p-2`,children:[(0,Z.jsx)(`p`,{className:`mb-2 font-medium`,children:n.name}),(0,Z.jsx)(Xw,{value:n.removalPolicy,backends:i,source:`imap:${n.mailboxId}`,destination:!1,onSave:async r=>{await qw(e,t.address,n.name,r),await te()}})]},`removal:${n.name}`)),ue,(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?`Save changes before testing, discovering folders or resyncing.`:`Test and Discover folders use the saved connection settings. Resync fetches the saved lookback window again.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{size:`sm`,onClick:B,disabled:k||!v,children:[k?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Yn,{className:`h-3 w-3`}),` Save`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,disabled:!!j||v||k,onClick:()=>V(`test`,t.address),children:[j===`test:${t.address}`?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(la,{className:`h-3 w-3`}),` Test`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,disabled:!!j||v||k,onClick:()=>V(`sync`,t.address),children:[j===`sync:${t.address}`?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Er,{className:`h-3 w-3`}),` Resync all`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`destructive`,disabled:!!j,onClick:ce,children:[j===`delete:${t.address}`?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Qr,{className:`h-3 w-3`}),` Delete`]})]})]})]},t.address)})})}),u&&(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsx)(`h5`,{className:`text-xs font-medium`,children:`New IMAP account`}),ue,(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{size:`sm`,onClick:B,disabled:k,children:[k?(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Yn,{className:`h-3 w-3`}),` Save`]}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:re,children:`Cancel`})]})]})]})}function OP({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)([`read`]),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(!0),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)(``),[x,S]=(0,X.useState)(!1),{showToast:C}=wo(),[w,T]=(0,X.useState)(e);e!==w&&(T(e),i(!0));let E=(0,X.useCallback)(()=>J.get(`/workspaces/${e}/tokens`).then(e=>{n((e||[]).map(e=>({...e,hash:e.hash||e.tokenHash||``})).filter(e=>e.hash))}).catch(()=>{C({title:`Error`,description:`Failed to load workspace tokens`,variant:`destructive`})}).finally(()=>{i(!1)}),[e,C]);(0,X.useEffect)(()=>{E()},[E]);let D=async()=>{if(!s.trim()){C({title:`Error`,description:`Token description is required`,variant:`destructive`});return}try{o(!0);let t=null;if(!p&&d){let e=new Date(d);e.setHours(23,59,59,999),t=e.toISOString()}let n={description:s,permissions:l,expiresAt:t},r=await J.post(`/workspaces/${e}/tokens`,n);r&&r.token&&b(r.token),c(``),u([`read`]),f(``),m(!0),g(!1),i(!0),await E(),C({title:`Success`,description:`Workspace sharing token created successfully`,variant:`default`})}catch{C({title:`Error`,description:`Failed to create token`,variant:`destructive`})}finally{o(!1)}},O=async t=>{try{await J.delete(`/workspaces/${e}/tokens/${t}`),C({title:`Success`,description:`Token revoked successfully`}),i(!0),await E()}catch{C({title:`Error`,description:`Failed to revoke token`,variant:`destructive`})}},k=e=>{let t=new Set(_);t.has(e)?t.delete(e):t.add(e),v(t)},A=e=>_.has(e)?e:`${e.substring(0,8)}...${e.substring(e.length-8)}`,j=async e=>{try{await navigator.clipboard.writeText(e),C({title:`Copied`,description:`Token hash copied to clipboard`})}catch{C({title:`Error`,description:`Failed to copy to clipboard`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`Workspace Sharing Tokens`}),(0,Z.jsxs)(Y,{onClick:()=>g(!h),size:`sm`,variant:`outline`,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Token`]})]}),h&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 bg-muted/50`,children:[(0,Z.jsx)(q,{placeholder:`Token description (e.g., 'John's laptop')`,value:s,onChange:e=>c(e.target.value)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium mb-2 block`,children:`Permissions`}),(0,Z.jsx)(`div`,{className:`flex gap-2 flex-wrap`,children:[`read`,`write`,`admin`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l.includes(e),onChange:t=>{t.target.checked?u([...l,e]):u(l.filter(t=>t!==e))}}),(0,Z.jsx)(`span`,{className:`text-sm`,children:e})]},e))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium mb-2 block`,children:`Token Expiry`}),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>{m(e.target.checked),e.target.checked&&f(``)}}),(0,Z.jsx)(`span`,{className:`text-sm`,children:`Never expires`})]}),!p&&(0,Z.jsx)(q,{type:`date`,placeholder:`Expiry date`,value:d,onChange:e=>f(e.target.value),min:new Date().toISOString().split(`T`)[0]})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{onClick:D,disabled:a,children:`Create Token`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>g(!1),children:`Cancel`})]})]}),y&&(0,Z.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Your New Workspace Sharing Token`}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(y),S(!0),C({title:`Success`,description:`Token copied to clipboard`}),setTimeout(()=>S(!1),2e3)}catch{C({title:`Error`,description:`Failed to copy token to clipboard`,variant:`destructive`})}},children:x?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(sr,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Jn,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-2`,children:`Make sure to copy your workspace sharing token now. You won't be able to see it again!`}),(0,Z.jsx)(`div`,{className:`p-2 bg-background border rounded font-mono text-sm break-all outline-none focus:ring-2 focus:ring-ring`,children:y}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,className:`mt-2`,onClick:()=>b(``),children:`Dismiss`})]}),(0,Z.jsx)(kP,{workspaceId:e}),r?(0,Z.jsxs)(`div`,{className:`text-center py-4`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Loading tokens...`})]}):t.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-8 text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No sharing tokens created yet.`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:`Create a token to share this workspace with others.`})]}):(0,Z.jsx)(`div`,{className:`space-y-3`,children:t.map(e=>(0,Z.jsxs)(`div`,{className:`border rounded-lg p-3 flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[(0,Z.jsx)(`span`,{className:`font-medium text-sm`,children:e.description}),(0,Z.jsx)(`span`,{className:`text-xs bg-muted px-2 py-1 rounded`,children:e.permissions.join(`, `)})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{className:`font-mono`,children:A(e.hash)}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>k(e.hash),children:_.has(e.hash)?(0,Z.jsx)(Ei,{className:`h-3 w-3`}):(0,Z.jsx)(ja,{className:`h-3 w-3`})}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>j(e.hash),children:(0,Z.jsx)(Jn,{className:`h-3 w-3`})})]}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Created: `,new Date(e.createdAt).toLocaleDateString(),e.expiresAt?(0,Z.jsxs)(`span`,{children:[` • Expires: `,new Date(e.expiresAt).toLocaleDateString()]}):(0,Z.jsx)(`span`,{children:` • Never expires`})]})]}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>O(e.hash),className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(Qr,{className:`h-4 w-4`})})]},e.hash))})]})}function kP({workspaceId:e}){let{showToast:t}=wo(),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)([`read`]),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)([]),u=(0,X.useCallback)(()=>J.get(`/workspaces/${e}/shares`).then(e=>l(Array.isArray(e)?e:e?.emailShares||[])).catch(()=>{}),[e]);(0,X.useEffect)(()=>{u()},[u]);let d=async()=>{if(n.trim())try{s(!0),await J.post(`/workspaces/${e}/shares`,{userEmail:n.trim(),permissions:i}),r(``),a([`read`]),await u(),t({title:`Success`,description:`Access granted`})}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{s(!1)}},f=async n=>{try{await J.delete(`/workspaces/${e}/shares/${encodeURIComponent(n)}`),await u(),t({title:`Success`,description:`Access revoked`})}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`h4`,{className:`font-medium`,children:`Email-based Shares`}),(0,Z.jsxs)(`div`,{className:`flex gap-2 flex-wrap items-center`,children:[(0,Z.jsx)(q,{placeholder:`user@local.server`,value:n,onChange:e=>r(e.target.value),className:`max-w-xs`}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:[`read`,`write`,`admin`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:i.includes(e),onChange:t=>{t.target.checked?a([...i,e]):a(i.filter(t=>t!==e))}}),e]},e))}),(0,Z.jsx)(Y,{size:`sm`,onClick:d,disabled:o,children:`Add`})]}),c.length>0&&(0,Z.jsx)(`div`,{className:`space-y-2`,children:c.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between border rounded p-2`,children:[(0,Z.jsxs)(`div`,{className:`text-sm`,children:[(0,Z.jsx)(`div`,{className:`font-medium`,children:e.userEmail}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[e.permissions.join(`, `),e.grantedAt?` • ${new Date(e.grantedAt).toLocaleDateString()}`:``]})]}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>f(e.userEmail),className:`text-destructive hover:text-destructive`,children:`Revoke`})]},e.userEmail))})]})}var AP=[{value:`read`,label:`Read`,hint:`Browse and search`},{value:`write`,label:`Read & write`,hint:`Add, edit and organise documents`},{value:`admin`,label:`Admin`,hint:`Everything except sharing and deleting`}],jP=e=>e.includes(`admin`)?`admin`:e.includes(`write`)?`write`:`read`;function MP({workspaceId:e}){let{showToast:t}=wo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(`user`),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(`read`),[m,h]=(0,X.useState)(e);e!==m&&(h(e),a(!0));let g=(0,X.useCallback)(()=>cs(e).then(r).catch(()=>r(null)).finally(()=>a(!1)),[e]);(0,X.useEffect)(()=>{g()},[g]);let _=n?.isOwner===!0,v=n?.members??[],y=async n=>{n.preventDefault();let r=u.trim();if(r){s(`grant`);try{let n=await kc(e,c===`user`?{email:r}:{group:r},[f]);d(``),await g();let i=c===`user`?r:`group ${r}`;t({title:`Shared`,description:n.type===`user`&&n.userExists===!1?`${i} has no account here yet — the share applies as soon as they sign in.`:`Access granted to ${i}.`})}catch(e){t({title:`Could not share`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{s(null)}}},b=async(n,r)=>{let i=`${n.type}:${n.principal}`;s(i);try{await Vo(e,n.type,n.principal,[r]),await g()}catch(e){t({title:`Could not update`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{s(null)}},x=async n=>{let r=`${n.type}:${n.principal}`;s(r);try{await fc(e,n.type,n.principal),await g(),t({title:`Access revoked`,description:`${n.principal} no longer has access.`})}catch(e){t({title:`Could not revoke`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{s(null)}};return n&&n.shareable===!1?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Your universe workspace is private and cannot be shared.`}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:_?`People and groups who can open this workspace.`:`You are a member of this workspace; only its owner can change the list.`}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{a(!0),g()},disabled:i,children:[(0,Z.jsx)(Er,{className:K(`mr-2 h-3.5 w-3.5`,i&&`animate-spin`)}),`Refresh`]})]}),i?(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`Loading members…`}):v.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):v.map(e=>{let t=`${e.type}:${e.principal}`,n=jP(e.permissions);return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[e.type===`group`?(0,Z.jsx)(ar,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}):(0,Z.jsx)(Hr,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,title:e.principal,children:e.principal}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[e.type===`group`?`Group`:`User`,e.description?` · ${e.description}`:``,e.grantedAt?` · since ${new Date(e.grantedAt).toLocaleDateString()}`:``]}),e.type===`user`&&e.userExists===!1&&(0,Z.jsxs)(`div`,{className:`mt-1 flex items-center gap-1 text-[11px] text-warning`,children:[(0,Z.jsx)(er,{className:`h-3 w-3`}),` No account yet — applies at first sign-in`]})]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[_?(0,Z.jsx)(`select`,{value:n,disabled:o===t,onChange:t=>b(e,t.target.value),className:`rounded-md border border-input bg-background px-2 py-1 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,title:`Access level`,children:AP.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs`,children:AP.find(e=>e.value===n)?.label}),_&&(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:o===t,onClick:()=>x(e),title:`Revoke access`,children:(0,Z.jsx)(nr,{className:`h-3.5 w-3.5`})})]})]},t)})]}),_&&(0,Z.jsxs)(`form`,{onSubmit:y,className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-sm font-medium`,children:[`Share with`,(0,Z.jsx)(`div`,{className:`inline-flex overflow-hidden rounded-md border`,children:[`user`,`group`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l(e),className:K(`px-3 py-1 text-xs`,c===e?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:bg-muted`),children:e===`user`?`a person`:`a group`},e))})]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[1fr_auto]`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(q,{type:c===`user`?`email`:`text`,value:u,onChange:e=>d(e.target.value),placeholder:c===`user`?`colleague@corp.tld`:`team-a or cn=team-a,ou=groups,dc=corp,dc=tld`,autoComplete:`off`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:c===`user`?`The share is keyed by e-mail: it works even before the person signs in for the first time.`:`Directory group (LDAP/AD memberOf — full DN or just the CN) or a group an admin assigned to local accounts.`})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(`select`,{value:f,onChange:e=>p(e.target.value),className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,title:AP.find(e=>e.value===f)?.hint,children:AP.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})})]}),(0,Z.jsx)(Y,{type:`submit`,size:`sm`,disabled:o===`grant`||!u.trim(),children:o===`grant`?`Sharing…`:`Share workspace`})]})]})}function NP({workspaceId:e,workspaceName:t,isActive:n,onChanged:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(!0),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),y=(0,X.useCallback)(async()=>{try{o(await bs(e))}catch{o([])}finally{c(!1)}},[e]);(0,X.useEffect)(()=>{y()},[y]);let b=async()=>{if(!(n&&!window.confirm(`'${t}' is running. It has to be stopped to be exported — its index is only consistent on disk once it has flushed.\n\nStop it and export now?`))){u(!0);try{let t=await Vc(e,{stop:!0});f(t.stoppedWorkspace),i({title:`Workspace exported`,description:`${t.name} — ${Ts(t.size)}`}),await y(),t.stoppedWorkspace&&r?.()}catch(e){i({title:`Export failed`,description:e instanceof Error?e.message:`Failed to export workspace`,variant:`destructive`})}finally{u(!1)}}},x=async()=>{m(!0);try{await Ks(e),f(!1),i({title:`Workspace started`,description:`'${t}' is running again.`}),r?.()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to start workspace`,variant:`destructive`})}finally{m(!1)}},S=async e=>{g(e.name);try{await qo(e.name)}catch(e){i({title:`Download failed`,description:e instanceof Error?e.message:`Failed to download archive`,variant:`destructive`})}finally{g(null)}},C=async e=>{if(window.confirm(`Delete ${e.name}? The archive is removed from the server; any copy you already downloaded is untouched.`)){g(e.name);try{await Lo(e.name),await y()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete archive`,variant:`destructive`})}finally{g(null)}}};return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Zr,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Export & Import`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Export packs this workspace into a single compressed archive you can download and move elsewhere. The workspace is stopped first — an export of a running workspace would capture a half-written index.`}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:l,onClick:b,children:[(0,Z.jsx)(Zr,{className:`mr-2 h-3.5 w-3.5 ${l?`animate-pulse`:``}`}),l?`Exporting…`:`Export Workspace`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:s||l,onClick:()=>void y(),children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${s?`animate-spin`:``}`}),`Refresh`]}),d&&(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:p,onClick:x,children:p?`Starting…`:`Start workspace again`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 border-t pt-3`,children:[(0,Z.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Archives`}),s?(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Loading…`}):a.length===0?(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`No exports yet.`}):(0,Z.jsx)(`ul`,{className:`mt-2 space-y-2`,children:a.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate font-mono text-xs`,children:e.name}),(0,Z.jsxs)(`div`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:[Ts(e.size),` · `,new Date(e.createdAt).toLocaleString()]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:h===e.name,onClick:()=>S(e),title:`Download (${Ts(e.size)})`,children:(0,Z.jsx)(zi,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:h===e.name,onClick:()=>C(e),className:`text-destructive hover:text-destructive`,title:`Delete archive`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]})]},e.name))})]}),(0,Z.jsxs)(`div`,{className:`mt-4 space-y-3 border-t pt-3`,children:[(0,Z.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Import workspace`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:l,onClick:()=>v(e=>!e),children:_?`Close import`:`Import workspace…`}),_&&(0,Z.jsx)(Nw,{disabled:l,onImported:()=>r?.()})]})]})}var PP={"workspace:home":{title:`Workspace Home`,description:`User-managed roaming home folder, exported through WebDAV and watched for changes. Mirrored into the backends tree.`},"workspace:data":{title:`Workspace Data`,description:`Managed content-addressable blob store (deduped, checksum-keyed). Opaque by design: the tree is the navigation; not meant for direct edits or export.`},imap:{title:`IMAP`,description:`Mailbox data source; ingested mail lands in the backends tree.`}},FP=[{id:`git`,title:`Git`,description:`Git-backed dotfile access.`},{id:`webdav`,title:`WebDAV`,description:`Mountable access to the workspace home backend.`},{id:`imapSync`,title:`IMAP Sync Worker`,description:`Background mailbox polling and ingestion.`}];function IP({checked:e,disabled:t,onClick:n}){return(0,Z.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:t,onClick:n,className:`relative inline-flex h-5 w-9 shrink-0 rounded-full border-2 border-transparent transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${e?`bg-primary`:`bg-muted-foreground/30`}`,children:(0,Z.jsx)(`span`,{className:`pointer-events-none inline-block h-4 w-4 rounded-full bg-background shadow transition-transform ${e?`translate-x-4`:`translate-x-0`}`})})}function LP({workspaceId:e,onAdded:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),{showToast:m}=wo(),h=()=>{a(``),s(``),l(!1),d(!1)};return n?(0,Z.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),!(!i.trim()||!o.trim())){p(!0);try{await Zs(e,`file`,{name:i.trim(),path:o.trim(),watch:c,readOnly:u}),m({title:`Added`,description:`${i.trim()} mounted; initial scan running in the background`}),h(),r(!1),await t()}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Failed to add folder backend`,variant:`destructive`})}finally{p(!1)}}},className:`w-full space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(ni,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Add local folder`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Index a folder on the server host as a data source. Files stay in place; the index records them as device-scoped locations, so they remain addressable if the workspace moves to another server.`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Name`}),(0,Z.jsx)(q,{value:i,onChange:e=>a(e.target.value),placeholder:`Financial Reports`,required:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Absolute path on server`}),(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`/mnt/data/reports`,required:!0,className:`font-mono`})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-6 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,children:[`watch`,(0,Z.jsx)(IP,{checked:c,onClick:()=>l(e=>!e)})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,title:`Never delete bytes in this folder. Destroy degrades to a reference drop. Recommended for folders managed outside Canvas.`,children:[`read-only`,(0,Z.jsx)(IP,{checked:u,onClick:()=>d(e=>!e)})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,size:`sm`,disabled:f||!i.trim()||!o.trim(),children:f?`Adding…`:`Add folder`}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,disabled:f,onClick:()=>{h(),r(!1)},children:`Cancel`})]})]}):(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:[(0,Z.jsx)(ni,{className:`mr-2 h-3.5 w-3.5`}),`Add local folder`]})}function RP({workspaceId:e,onAdded:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)({name:``,clientId:``,clientSecret:``,refreshToken:``,folderId:``}),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),{showToast:p}=wo(),m=e=>t=>a(n=>({...n,[e]:t.target.value})),h=()=>{a({name:``,clientId:``,clientSecret:``,refreshToken:``,folderId:``}),s(!1),l(!1)},g=i.name.trim()&&i.clientId.trim()&&i.clientSecret.trim()&&i.refreshToken.trim();return n?(0,Z.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),g){d(!0);try{await Zs(e,`gdrive`,{name:i.name.trim(),clientId:i.clientId.trim(),clientSecret:i.clientSecret.trim(),refreshToken:i.refreshToken.trim(),folderId:i.folderId.trim()||`root`,watch:o,readOnly:c}),p({title:`Added`,description:`${i.name.trim()} connected; initial scan running in the background`}),h(),r(!1),await t()}catch(e){p({title:`Error`,description:e instanceof Error?e.message:`Failed to add Google Drive backend`,variant:`destructive`})}finally{d(!1)}}},className:`w-full space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(f,{icon:`mdi:google-drive`,width:16,height:16,className:`text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Add Google Drive`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Index a Drive folder (or the whole My Drive) as a remote data source. Files are hashed from Drive metadata, uploads are queued through the workspace cache. Needs a Google OAuth client (Web application) — enter its id and secret, then sign in to obtain the offline-access refresh token, or paste one you already have.`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Name`}),(0,Z.jsx)(q,{value:i.name,onChange:m(`name`),placeholder:`Work Drive`,required:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Folder id (empty = My Drive root)`}),(0,Z.jsx)(q,{value:i.folderId,onChange:m(`folderId`),placeholder:`1AbC…`,className:`font-mono`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`OAuth client id`}),(0,Z.jsx)(q,{value:i.clientId,onChange:m(`clientId`),required:!0,className:`font-mono`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`OAuth client secret`}),(0,Z.jsx)(q,{type:`password`,value:i.clientSecret,onChange:m(`clientSecret`),required:!0,className:`font-mono`,autoComplete:`off`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1 sm:col-span-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Refresh token`}),(0,Z.jsx)(q,{type:`password`,value:i.refreshToken,onChange:m(`refreshToken`),required:!0,className:`font-mono`,autoComplete:`off`,placeholder:`Sign in below, or paste an offline-access refresh token`}),(0,Z.jsx)(bP,{clientId:i.clientId,clientSecret:i.clientSecret,scope:c?`drive.readonly`:`drive`,disabled:u,onLinked:({refreshToken:e,account:t})=>a(n=>({...n,refreshToken:e,name:n.name.trim()||(t?`Drive (${t})`:n.name)}))})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-6 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,title:`Poll the Drive changes feed (every 60s) so edits made in Drive show up without a manual re-sync.`,children:[`watch`,(0,Z.jsx)(IP,{checked:o,onClick:()=>s(e=>!e)})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,title:`Never delete files in this Drive. Destroy degrades to a reference drop.`,children:[`read-only`,(0,Z.jsx)(IP,{checked:c,onClick:()=>l(e=>!e)})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,size:`sm`,disabled:u||!g,children:u?`Checking…`:`Add Drive`}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,disabled:u,onClick:()=>{h(),r(!1)},children:`Cancel`})]})]}):(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:[(0,Z.jsx)(f,{icon:`mdi:google-drive`,width:14,height:14,className:`mr-2`}),`Add Google Drive`]})}function zP({workspaceId:e,backend:t}){let[n,r]=(0,X.useState)(t.usage??null),[i,a]=(0,X.useState)(!1),{showToast:o}=wo();return(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{a(!0);try{r(await Zo(e,t.driver,t.address))}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed to compute size`,variant:`destructive`})}finally{a(!1)}},disabled:i,className:`flex items-center gap-1.5 rounded border px-2 py-1 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50`,title:n?`Computed ${new Date(n.computedAt).toLocaleString()}; click to refresh`:`Compute on-disk size (walks the backend folder; may take a while)`,children:[(0,Z.jsx)(Fr,{className:`h-3 w-3 ${i?`animate-pulse`:``}`}),i?`Calculating…`:n?Ts(n.bytes):`Size`]})}function BP({workspaceId:e}){let[t,n]=(0,X.useState)(!1),{showToast:r}=wo();return(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:async()=>{n(!0);try{let{removed:t}=await oc(e);r({title:`Thumbnail cache cleared`,description:`${t} cached thumbnail(s) removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Failed to clear thumbnail cache`,variant:`destructive`})}finally{n(!1)}},title:`Remove all cached thumbnails; they regenerate on demand`,children:[(0,Z.jsx)(Qr,{className:`mr-2 h-3.5 w-3.5 ${t?`animate-pulse`:``}`}),t?`Clearing…`:`Clear thumbnails`]})}function VP({workspaceId:e}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!1),{showToast:a}=wo();return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Fr,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Disk usage`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Total on-disk size of this workspace (index, blobs, home, cache): what an export or sync would move. Computed on demand; may take a while on large workspaces.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[t&&(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:Ts(t.bytes)}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:r,onClick:async()=>{i(!0);try{n(await uc(e))}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to compute workspace size`,variant:`destructive`})}finally{i(!1)}},children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${r?`animate-spin`:``}`}),r?`Calculating…`:t?`Recalculate`:`Calculate size`]})]})]}),t&&(0,Z.jsx)(`div`,{className:`mt-3 grid grid-cols-2 gap-x-6 gap-y-1 border-t pt-3 sm:grid-cols-3`,children:Object.entries(t.breakdown).sort(([,e],[,t])=>t-e).map(([e,t])=>(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate font-mono text-muted-foreground`,children:e}),(0,Z.jsx)(`span`,{children:Ts(t)})]},e))})]})}function HP({backend:e,busy:t,onSave:n}){let r=e.config||{},i=Array.isArray(r.exclude)?r.exclude:[],a=Array.isArray(r.effectiveExclusions)?r.effectiveExclusions:[],o=Math.max(a.length-i.length,0),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(i.join(`
|
|
45
|
+
`)),[d,f]=(0,X.useState)(!1),p=i.join(`
|
|
46
|
+
`),[m,h]=(0,X.useState)(p);return m!==p&&(h(p),u(p)),(0,Z.jsxs)(`div`,{className:`mt-3 border-t pt-3`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`text-[11px] font-medium text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:[`Sync exclusions `,i.length>0?`(${i.length} custom`:`(defaults only`,o>0?`, ${o} default)`:`)`,` `,s?`▾`:`▸`]}),s&&(0,Z.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`One glob pattern per line, e.g. `,(0,Z.jsx)(`code`,{className:`font-mono`,children:`**/node_modules/**`}),` or `,(0,Z.jsx)(`code`,{className:`font-mono`,children:`**/target/**`}),`. Defaults (dotfiles, node_modules, __pycache__, caches, …) always apply. Changes take effect immediately for the watcher; run Re-sync to also unlink already-mirrored entries.`]}),(0,Z.jsx)(`textarea`,{className:`w-full min-h-[80px] rounded-md border bg-background p-2 font-mono text-xs`,value:l,onChange:e=>u(e.target.value),placeholder:`**/node_modules/**
|
|
47
|
+
**/dist/**`,spellCheck:!1}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,disabled:t||l.split(`
|
|
48
|
+
`).map(e=>e.trim()).filter(Boolean).join(`
|
|
49
|
+
`)===i.join(`
|
|
50
|
+
`),onClick:()=>n(l.split(`
|
|
51
|
+
`).map(e=>e.trim()).filter(Boolean)),children:`Save exclusions`}),o>0&&(0,Z.jsxs)(`button`,{type:`button`,className:`text-[11px] text-muted-foreground hover:text-foreground`,onClick:()=>f(!d),children:[d?`Hide`:`Show`,` default patterns`]})]}),d&&(0,Z.jsx)(`pre`,{className:`max-h-40 overflow-auto rounded-md bg-muted/50 p-2 font-mono text-[11px] text-muted-foreground`,children:a.filter(e=>!i.includes(e)).join(`
|
|
52
|
+
`)})]})]})}function UP({device:e,linked:t,busy:n,onLink:r,onUnlink:i,onUpdate:a}){let[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(e.name),[u,d]=(0,X.useState)(e.description??``),f=()=>{c.trim()&&(c!==e.name||u!==(e.description??``))&&a({name:c.trim(),description:u.trim()||void 0}),s(!1)},p=()=>{l(e.name),d(e.description??``),s(!1)};return(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(mr,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[o?(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground font-mono`,children:[(0,Z.jsx)(`span`,{children:e.deviceId}),e.platform&&(0,Z.jsx)(`span`,{children:e.platform}),e.arch&&(0,Z.jsx)(`span`,{children:e.arch}),e.type&&(0,Z.jsx)(`span`,{children:e.type})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:f,disabled:!c.trim(),children:(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:p,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>s(!0),title:`Edit name/description`,children:(0,Z.jsx)(Lr,{className:`h-3.5 w-3.5`})}),t?(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:i,className:`text-destructive hover:text-destructive`,title:`Remove from workspace`,children:(0,Z.jsx)(nr,{className:`h-3.5 w-3.5`})}):(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:r,title:`Link to workspace`,children:(0,Z.jsx)(Ri,{className:`h-3.5 w-3.5`})}),t&&(0,Z.jsx)(`span`,{className:`rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary`,children:`linked`})]})]})})}function WP({allDevices:e,linkedDevices:t,isLoading:n,deviceBusy:r,onRefresh:i,onLink:a,onUnlink:o,onUpdate:s}){let c=new Set(t.map(e=>e.deviceId));return n?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading devices…`]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[c.size,` of `,e.length,` registered device`,e.length===1?``:`s`,` linked to this workspace.`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:i,disabled:n,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),e.length===0?(0,Z.jsxs)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:[`No devices registered. Devices register themselves on first connection via `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,Z.jsx)(UP,{device:e,linked:c.has(e.deviceId),busy:r===e.deviceId,onLink:()=>a(e.deviceId),onUnlink:()=>o(e.deviceId),onUpdate:t=>s(e.deviceId,t)},e.deviceId))})]})}function GP({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-2 border-b last:border-0`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:e}),(0,Z.jsx)(`span`,{className:`text-xs text-right ${n?`font-mono`:``}`,children:t??`—`})]})}function KP({workspaceName:e,current:t,weights:n,floorMode:r,relativeMargin:i,onDone:a}){let[o,s]=(0,X.useState)(t==null?``:String(t)),[c,l]=(0,X.useState)(r??`relative`),[u,d]=(0,X.useState)(i==null?`0.035`:String(i)),[f,p]=(0,X.useState)(n?.fts==null?`2`:String(n.fts)),[m,h]=(0,X.useState)(n?.dense==null?`1`:String(n.dense)),[g,_]=(0,X.useState)(n?.image==null?`2`:String(n.image)),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(cE);return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`How photo relevance is decided`}),(0,Z.jsxs)(`select`,{value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-input bg-transparent px-2 text-xs`,children:[(0,Z.jsx)(`option`,{value:`relative`,children:`Relative to the best match (recommended)`}),(0,Z.jsx)(`option`,{value:`absolute`,children:`Absolute distance cutoff`})]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Photo-vs-text distances shift with every query and every model, so one fixed cutoff travels badly: a value tuned for one model keeps everything (or nothing) on the next. Relative anchors on the best match for THIS query and survives a re-embed.`})]}),c===`relative`&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Window width (distance from the best match)`}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),placeholder:`0.035`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Wider keeps photos that match your query only partly, which is what a photo matching TWO things (a snowy window) looks like, since it sits further from each one than a pure example does. Too wide and everything gets in.`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:c===`relative`?`Hard ceiling (cosine distance, 0–2; blank = off)`:`Image relevance floor (cosine distance, 0–2; blank = off)`}),(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`0.95`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:c===`relative`?`Nothing beyond this counts as a match however close it is to the best one. This is what lets a search of something you have no photos of come back empty. Without it, a relative window always returns its nearest photo.`:`Lower = stricter (fewer, more-relevant photos); raise if relevant photos are missing.`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Hybrid fusion weights (0 disables a signal)`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap items-end gap-x-3 gap-y-2`,children:[[`lexical`,f,p],[`text semantic`,m,h],[`image`,g,_]].map(([e,t,n])=>(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:e}),(0,Z.jsx)(q,{value:t,onChange:e=>n(e.target.value),className:`h-8 w-16 font-mono text-xs`,inputMode:`decimal`})]},e))}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Ranking mix: lexical (filenames/content) · text semantics · photo matches. Equal lexical/image ranks a matching photo like a matching document.`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:async()=>{y(!0),x(null);try{let t=o.trim(),n=t===``?null:Number(t);if(n!==null&&!Number.isFinite(n)){x(`Enter a number (e.g. 0.95) or leave empty`);return}let r={fts:Number(f),dense:Number(m),image:Number(g)};if(Object.values(r).some(e=>!Number.isFinite(e)||e<0)){x(`Weights must be numbers ≥ 0`);return}let i=Number(u.trim());if(c===`relative`&&(!Number.isFinite(i)||i<=0)){x(`Window width must be a positive number (e.g. 0.035)`);return}await Vs(e,{imageMaxDistance:n,imageFloorMode:c,...c===`relative`?{imageRelativeMargin:i}:{},searchWeights:r}),x(`Saved`),a()}catch(e){x(e instanceof Error?e.message:`Failed to save`)}finally{y(!1)}},disabled:v,children:v?`Saving…`:`Save`}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:b})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>{lE(e.target.checked),C(e.target.checked)}}),(0,Z.jsx)(`span`,{children:`Debug query`})]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Attaches the raw (unfloored) image distances to each search and shows them above the document list: the numbers this floor should be picked from. Local to this browser; costs a little extra work per query, so leave it off day to day.`})]})]})}function qP({stats:e,isLoading:t,onRefresh:n,workspaceName:r}){return t?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading stats…`]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Live snapshot from synapsd. Click refresh for updated counts.`}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:n,disabled:t,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),(0,Z.jsx)(ZP,{workspaceName:r,vectorSpaces:Object.keys(e?.semantic?.vectorSpaces||{}),onDone:n}),e?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(Fa,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Core Index`})]}),(0,Z.jsx)(GP,{label:`Backend`,value:e.dbBackend,mono:!0}),(0,Z.jsx)(GP,{label:`Status`,value:e.status}),(0,Z.jsx)(GP,{label:`Path`,value:e.dbPath,mono:!0}),(0,Z.jsx)(GP,{label:`Documents`,value:e.documentCount?.toLocaleString()}),(0,Z.jsx)(GP,{label:`Metadata entries`,value:e.metadataCount?.toLocaleString()}),(0,Z.jsx)(GP,{label:`Checksum index`,value:e.checksumIndexSize?.toLocaleString()}),(0,Z.jsx)(GP,{label:`Bitmap store`,value:e.bitmapStoreSize?.toLocaleString()}),(0,Z.jsx)(GP,{label:`Bitmap cache`,value:e.bitmapCacheSize?.toLocaleString()}),(0,Z.jsx)(GP,{label:`Deleted (pending GC)`,value:e.deletedDocumentsCount?.toLocaleString()})]}),e.fts&&(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(ui,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Full-Text Search (LanceDB)`})]}),`ready`in e.fts&&(0,Z.jsx)(GP,{label:`Ready`,value:String(e.fts.ready)}),e.fts.rowCount!==void 0&&(0,Z.jsx)(GP,{label:`Row count`,value:e.fts.rowCount?.toLocaleString()}),e.fts.error&&(0,Z.jsx)(GP,{label:`Error`,value:(0,Z.jsx)(`span`,{className:`text-destructive`,children:e.fts.error})})]}),e.semantic&&(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(ui,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Semantic / Vector Search`})]}),(0,Z.jsx)(GP,{label:`Enabled`,value:String(e.semantic.enabled)}),e.semantic.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[e.inferd?.routing?Object.entries(e.inferd.routing).map(([e,t])=>(0,Z.jsx)(GP,{label:`Embeds → ${e}`,value:(0,Z.jsx)(`span`,{className:`font-mono text-[11px]`,children:t.join(`, `)})},`route-${e}`)):(0,Z.jsx)(GP,{label:`Text-embeddable (gap default)`,value:e.semantic.embeddableSchemas?.join(`, `)}),e.semantic.vectorSpaces&&Object.entries(e.semantic.vectorSpaces).map(([e,t])=>(0,Z.jsx)(GP,{label:`Space: ${e} (${t.dim??`?`}-d)`,value:t.error?(0,Z.jsx)(`span`,{className:`text-destructive`,children:t.error}):`${(t.embeddedDocs??0).toLocaleString()} docs · ${(t.chunkRows??0).toLocaleString()} vectors`},e)),(0,Z.jsx)(GP,{label:`Photo relevance`,value:e.semantic.imageFloorMode===`absolute`?`absolute cutoff`:`relative ±${e.semantic.imageRelativeMargin??.035}`,mono:!0}),(0,Z.jsx)(GP,{label:e.semantic.imageFloorMode===`absolute`?`Image relevance floor`:`Hard ceiling`,value:e.semantic.imageMaxDistance==null?`off`:e.semantic.imageMaxDistance,mono:!0}),(0,Z.jsx)(GP,{label:`Fusion weights (lexical · text · image)`,value:`${e.semantic.searchWeights?.fts??2} · ${e.semantic.searchWeights?.dense??1} · ${e.semantic.searchWeights?.image??2}`,mono:!0}),(0,Z.jsx)(KP,{workspaceName:r,current:e.semantic.imageMaxDistance,weights:e.semantic.searchWeights,floorMode:e.semantic.imageFloorMode,relativeMargin:e.semantic.imageRelativeMargin,onDone:n})]})]})]}):(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No stats available.`})]})}function JP(){let{workspaceName:e}=yt();return(0,Z.jsx)(YP,{},e)}function YP(){let{workspaceName:e,tab:t}=yt(),[n,r]=$t(),i=n.get(`section`),a=[`pending`,`rules`,`hooks`,`scripts`,`runs`].find(e=>e===i),o=n.get(`handler`)||void 0,s=n.get(`run`)||void 0,c=n.get(`addRuleKind`),l=n.get(`addRulePath`),u=n.get(`addRuleTarget`),d=n.get(`addRuleStoreTo`),p=n.get(`addRuleStoreFolder`),m=(0,X.useMemo)(()=>c===`store`||c===`download`?!l&&!d&&!p?null:{kind:c,path:l||``,storeTo:d||``,storeFolder:p||``}:l?{kind:`mirror`,path:l,target:u||`dir:/`}:null,[c,l,u,d,p]),h=(0,X.useCallback)(()=>{r(e=>{for(let t of[`addRuleKind`,`addRulePath`,`addRuleTarget`,`addRuleStoreTo`,`addRuleStoreFolder`])e.delete(t);return e},{replace:!0})},[r]),g=ft(),{showToast:_,showProgress:v}=wo(),y=De(),{goBack:b}=qC(),x=jD(t);(0,X.useEffect)(()=>{t!==x&&g(`/workspaces/${e}/settings/${x}`,{replace:!0})},[t,x,e,g]);let[S,C]=(0,X.useState)(null),w=se(S),[T,E]=(0,X.useState)(0),[D,O]=(0,X.useState)(!0),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(!1),[N,P]=(0,X.useState)(``),[ee,F]=(0,X.useState)(``),[I,te]=(0,X.useState)(`#FFFFFF`),[L,R]=(0,X.useState)(null),[ne,re]=(0,X.useState)(null),[ie,ae]=(0,X.useState)([]),[z,oe]=(0,X.useState)(null),[B,ce]=(0,X.useState)([]),[V,le]=(0,X.useState)(null),[ue,de]=(0,X.useState)(null),[fe,pe]=(0,X.useState)(!1),[me,he]=(0,X.useState)([]),[ge,_e]=(0,X.useState)([]),[ve,ye]=(0,X.useState)(!1),[be,xe]=(0,X.useState)(null),H=e||S?.id||``,Se=(0,X.useRef)(H);(0,X.useEffect)(()=>{Se.current=H});let Ce=(0,X.useCallback)(async e=>{let t=e??Se.current;if(t)try{let e=await Mo(t);ae(e.publicCanvasShares)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load shares`,variant:`destructive`})}},[_]),U=(0,X.useCallback)(async e=>{let t=e??Se.current;if(t){pe(!0);try{let e=await Ec(t);de(e)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load DB stats`,variant:`destructive`})}finally{pe(!1)}}},[_]),W=(0,X.useCallback)(async e=>{let t=e??Se.current;if(t){ye(!0);try{let[e,n]=await Promise.all([xD(),wD(t)]);he(e),_e(n)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{ye(!1)}}},[_]),we=async e=>{xe(e);try{let t=me.find(t=>t.deviceId===e);if(!t)throw Error(`Device not found in your account`);await TD(H,t),await W(),_({title:`Linked`,description:`Device linked to workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to link device`,variant:`destructive`})}finally{xe(null)}},Te=async e=>{xe(e);try{await ED(H,e),_e(t=>t.filter(t=>t.deviceId!==e)),_({title:`Unlinked`,description:`Device removed from workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to unlink device`,variant:`destructive`})}finally{xe(null)}},Ee=async(e,t)=>{xe(`edit:${e}`);try{let n=await SD(e,t);he(t=>t.map(t=>t.deviceId===e?{...t,...n}:t)),_({title:`Saved`,description:`Device updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{xe(null)}},Oe=(0,X.useCallback)(async e=>{let t=e??Se.current;if(!t)return;let[n,r]=await Promise.all([wc(t).catch(()=>null),Rc(t).catch(()=>[])]);oe(n),ce(r.filter(e=>e.kind===`storage`))},[]),ke=B.some(e=>e.resyncing);(0,X.useEffect)(()=>{if(!w||!ke||!H)return;let e=setInterval(()=>{Oe()},4e3);return()=>clearInterval(e)},[w,ke,H,Oe]),(0,X.useEffect)(()=>{let t=!1;async function n(){try{let n=await Uo();if(t)return;let r=n.find(t=>t.id===e)??n.find(t=>t.name===e);if(C(r??null),r){if(!se(r))return;P(r.label||``),F(r.description||``),te(r.color||`#FFFFFF`),R(r.icon??null),r.status===`active`&&await Promise.all([Ce(e||r.id),Oe(e||r.id)])}}catch{t||_({title:`Error`,description:`Failed to load workspace`,variant:`destructive`})}finally{t||O(!1)}}return n(),()=>{t=!0}},[e,Ce,Oe,_,T]),(0,X.useEffect)(()=>{let e=()=>E(e=>e+1);return window.addEventListener(`workspaces:refresh`,e),()=>window.removeEventListener(`workspaces:refresh`,e)},[]);let Ae=(0,X.useRef)(!1),je=(0,X.useRef)(!1);(0,X.useEffect)(()=>{Ae.current=!!ue||fe,je.current=ve||me.length>0}),(0,X.useEffect)(()=>{w&&(S?.status===`active`&&x===`db`&&H&&!Ae.current&&U(),S?.status===`active`&&x===`devices`&&H&&!je.current&&W())},[w,x,H,S?.status,U,W]);let Me=async e=>{if(e.preventDefault(),S){A(!0);try{await Pc(H,{label:N.trim(),description:ee.trim(),color:I,icon:L}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Saved`,description:`Workspace settings updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{A(!1)}}},Ne=async()=>{if(S&&window.prompt(`Destroy workspace "${S.label||S.name}" and all its documents? This cannot be undone. Type the workspace name "${S.name}" to confirm:`)===S.name){M(!0);try{await fs(H),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Destroyed`,description:`${S.label||S.name} has been removed`}),g(`/workspaces`)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Destroy failed`,variant:`destructive`})}finally{M(!1)}}},Pe=()=>{for(let t of[e,S?.name,S?.id])t&&Ms(t,`backends`);window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:H}}))},Fe=async e=>{if(e.config?.supported!==!1){le(`backend:${e.address}`);try{await Fo(H,e.driver,e.address,{enabled:!e.enabled}),await Oe(),Pe(),_({title:`Saved`,description:`${e.address} ${e.enabled?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{le(null)}}},Ie=async(e,t,n)=>{le(`${n}:${e.address}`);try{await Fo(H,e.driver,e.address,t),await Oe()}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{le(null)}},Le=async e=>{let t=typeof e.config?.label==`string`&&e.config.label||e.address;if(window.confirm(`Remove backend "${t}"? No files are deleted; indexed entries remain until purged from the backends tree.`)){le(`remove:${e.address}`);try{await Xo(H,e.driver,e.address),await Oe(),Pe(),_({title:`Removed`,description:`${t} unmounted`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to remove backend`,variant:`destructive`})}finally{le(null)}}},Re=async e=>{le(`resync:${e.address}`);try{await et(v,H,e.driver,e.address,e=>{ce(t=>t.map(t=>t.driver===e.driver&&t.address===e.address?e:t))}),await Oe()}catch{}finally{le(null)}},ze=async e=>{le(`test:${e.address}`);try{await jc(H,e.driver,e.address),_({title:`Connected`,description:`${e.address}: credentials and root folder verified`})}catch(e){_({title:`Connection failed`,description:e instanceof Error?e.message:`Test failed`,variant:`destructive`})}finally{le(null)}},Be=async e=>{le(`stopsync:${e.address}`);try{await mc(H,e.driver,e.address),await Oe(),_({title:`Sync stopped`,description:`${e.address}: indexed files are kept; Re-sync resumes where it left off`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to stop sync`,variant:`destructive`})}finally{le(null)}},Ve=async(e,t)=>{le(`service:${e}`);try{t?await $s(H,e):await ps(H,e),await Oe(),_({title:t?`Disabled`:`Enabled`,description:`${e} ${t?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle service`,variant:`destructive`})}finally{le(null)}},He=async e=>{let t=`${window.location.origin}${e.url}`;await navigator.clipboard?.writeText(t),_({title:`Copied`,description:t})},Ue=async e=>{if(S&&window.confirm(`Revoke public share for "${e.path}"?`)){le(`share:${e.code}`);try{await Cc(H,e.code),await Ce(H),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:H}})),_({title:`Revoked`,description:`Public canvas link no longer works`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke share`,variant:`destructive`})}finally{le(null)}}},We=kD.find(e=>e.id===x);return D?(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`}):S?w?(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${We.label} - ${S.label||S.name}`,description:`This workspace · ${We.description}`,backTo:`/workspaces/${e}`,onBack:y?b:void 0}),S.status!==`active`&&x!==`general`&&x!==`backups`&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to access these settings. General settings and protection remain available while stopped.`}),x===`backups`&&(0,Z.jsx)(BM,{workspaceId:H,onRestored:()=>E(e=>e+1)}),x===`general`&&(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`form`,{onSubmit:Me,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ws-id`,className:`text-sm font-medium`,children:`Workspace ID`}),(0,Z.jsx)(q,{id:`ws-id`,value:S.id,readOnly:!0,className:`font-mono text-sm`,onFocus:e=>e.currentTarget.select()})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ws-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`ws-label`,value:N,onChange:e=>P(e.target.value),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ws-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`ws-description`,value:ee,onChange:e=>F(e.target.value),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Icon & color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>re({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(f,{icon:L||`ph:stack-fill`,width:22,height:22,color:Jt(I)})}),(0,Z.jsx)(q,{id:`ws-color`,type:`color`,value:I,onChange:e=>te(e.target.value),className:`h-10 w-16 p-1`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>te(on()),children:`Randomize`})]})]}),(0,Z.jsx)(Y,{type:`submit`,disabled:k||!N.trim(),children:k?`Saving...`:`Save Changes`})]}),ne&&(0,Z.jsx)(dw,{x:ne.x,y:ne.y,current:{icon:L??void 0,color:I},onChange:e=>{`icon`in e&&R(e.icon??null),`color`in e&&e.color&&te(e.color)},onClose:()=>re(null)}),(0,Z.jsx)(QM,{currentMode:S.protection?.mode,workspaceId:H,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),S.status===`active`&&(0,Z.jsx)(XP,{workspaceName:e}),S.status===`active`&&(0,Z.jsx)(VP,{workspaceId:H}),(0,Z.jsx)(NP,{workspaceId:H,workspaceName:S.label||S.name,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(Y,{variant:`destructive`,disabled:j,onClick:Ne,children:[(0,Z.jsx)(Qr,{className:`mr-2 h-4 w-4`}),j?`Destroying...`:`Destroy Workspace`]})]})]}),S.status===`active`&&x===`shares`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Members`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Share this workspace with teammates by e-mail or with a whole directory group. It shows up in their workspace list on this server.`})]}),(0,Z.jsx)(MP,{workspaceId:H})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Public Canvas Shares`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Active public canvas links for this workspace.`})]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>Ce(),children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),ie.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No public canvas shares. Good.`}):ie.map(e=>{let t=`${window.location.origin}${e.url}`;return(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate font-mono text-sm`,children:e.path}),(0,Z.jsxs)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[e.treeName,` / `,e.treeType,` - created `,new Date(e.createdAt).toLocaleString()]}),e.lockedBy?.length>0&&(0,Z.jsxs)(`div`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`locks: `,e.lockedBy.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>He(e),children:(0,Z.jsx)(Jn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>window.open(t,`_blank`,`noreferrer`),children:(0,Z.jsx)(Pi,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:V===`share:${e.code}`,onClick:()=>Ue(e),className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(nr,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`mt-2 truncate rounded bg-muted/40 px-2 py-1 font-mono text-xs text-muted-foreground`,children:t})]},e.code)})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workspace ACL Tokens`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Generate token-based workspace access for devices, scripts, and other users.`})]}),(0,Z.jsx)(OP,{workspaceId:H})]})]}),S.status===`active`&&x===`data`&&(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[B.map(e=>{let t=e.config||{},n=e.address,r=t.device||null,i=e.driver===`gdrive`,a=e.driver===`s3`,o=(e.driver===`file`||i||a)&&t.managed!==!0&&!PP[n],s=PP[n]||{title:typeof t.label==`string`&&t.label||n,description:a?`S3 bucket ${t.bucket||``}${t.prefix?`/${t.prefix}`:``}${t.endpoint?` at ${t.endpoint}`:``}. Filing copies only.`:i?`Google Drive${typeof t.account==`string`&&t.account&&t.account!==t.label?` (${t.account})`:``}, folder ${typeof t.folderId==`string`&&t.folderId?t.folderId:`root`}${e.treePath?`, mirrored at ${e.treePath}`:``}.`:o?`Local folder${r?.name?` on ${r.name}`:``}, indexed in place${e.treePath?` and mirrored at ${e.treePath}`:``}.`:`Workspace data backend.`},c=t.supported!==!1,l=n===`workspace:data`,u=c&&!l,d=u&&t.managed!==!0,p=vt(e);return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(f,{icon:p.icon,width:16,height:16,color:p.color,className:`shrink-0`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:s.title}),!c&&(0,Z.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,children:`unsupported`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s.description}),typeof t.root==`string`&&t.root&&(0,Z.jsx)(`p`,{className:`mt-2 truncate font-mono text-xs text-muted-foreground`,children:t.root}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`status: `,e.status]}),e.resyncing&&(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 font-medium text-primary`,children:[(0,Z.jsx)(Er,{className:`h-3 w-3 animate-spin`}),`indexing`,e.progress?` ${e.progress.scanned}${e.progress.total==null?``:` / ${e.progress.total}`}`:``]}),r?.name&&(0,Z.jsxs)(`span`,{title:r.id,children:[`device: `,r.name]}),t.readOnly===!0&&(0,Z.jsx)(`span`,{className:`rounded bg-warning/15 px-1.5 py-0.5 font-medium text-warning`,children:`read-only`}),e.lastSyncAt&&(0,Z.jsxs)(`span`,{children:[`last scan: `,new Date(e.lastSyncAt).toLocaleString()]})]}),e.lastError&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-destructive`,children:e.lastError}),t.readOnly===!0&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`Read-only: the web UI / REST API never deletes bytes on this backend. Destroy degrades to a reference drop. Recommended when the folder is exported elsewhere (e.g. via Samba).`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-3`,children:[e.capabilities?.sync&&c&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,title:`Scan this backend in the background whenever the workspace starts. Manual scans remain available when off.`,children:[`Scan on start`,(0,Z.jsx)(IP,{checked:t.scanOnStart===!0,disabled:V===`startup:${n}`,onClick:()=>Ie(e,{scanOnStart:t.scanOnStart!==!0},`startup`)})]}),(e.driver===`file`||i||a)&&u&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:i?`Poll the Drive changes feed so edits made in Drive show up without a manual re-sync.`:void 0,children:[`Watch for changes`,(0,Z.jsx)(IP,{checked:!!t.watch,disabled:!e.enabled||V===`watch:${n}`,onClick:()=>Ie(e,{watch:!t.watch},`watch`)})]}),d&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:`Read-only: Destroy never deletes bytes on this backend (references are dropped instead). Important when the folder is exported via Samba or shared otherwise.`,children:[`read-only`,(0,Z.jsx)(IP,{checked:t.readOnly===!0,disabled:V===`readonly:${n}`,onClick:()=>Ie(e,{readOnly:t.readOnly!==!0},`readonly`)})]}),(e.driver===`file`||e.driver===`cacache`)&&c&&(0,Z.jsx)(zP,{workspaceId:H,backend:e}),e.capabilities?.test&&(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:V===`test:${n}`,onClick:()=>ze(e),title:`Verify credentials and root folder`,children:[(0,Z.jsx)(ui,{className:`mr-2 h-3.5 w-3.5`}),V===`test:${n}`?`Testing…`:`Test`]}),e.capabilities?.sync&&(e.resyncing?(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:V===`stopsync:${n}`,onClick:()=>Be(e),title:`Stop the running scan. Files indexed so far are kept; Re-sync later resumes where it left off (unchanged files are skipped).`,children:[(0,Z.jsx)(Sa,{className:`mr-2 h-3.5 w-3.5 fill-current`}),V===`stopsync:${n}`?`Stopping…`:`Stop sync`]}):(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:V===`resync:${n}`,onClick:()=>Re(e),children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${V===`resync:${n}`?`animate-spin`:``}`}),`Re-sync`]})),l?(0,Z.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,title:`Structural workspace store; cannot be disabled`,children:`always on`}):(0,Z.jsx)(IP,{checked:!!e.enabled,disabled:!u||V===`backend:${n}`,onClick:()=>Fe(e)}),o&&(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:V===`remove:${n}`,title:`Unmount this folder (no files are deleted)`,onClick:()=>Le(e),children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]})]}),c&&(0,Z.jsx)(Xw,{value:t.removalPolicy,backends:B,source:n,destination:t.propagatedRemovalSupported===!0,onSave:async t=>{await Fo(H,e.driver,e.address,{removalPolicy:t}),await Oe()}}),a&&(0,Z.jsx)(ZM,{workspaceId:H,backend:e,onSaved:async()=>{await Oe(),Pe()}}),e.driver===`file`&&c&&!l&&(0,Z.jsx)(HP,{backend:e,busy:V===`exclude:${n}`,onSave:t=>Ie(e,{exclude:t},`exclude`)})]},n)}),(0,Z.jsx)(XM,{workspaceId:H,children:(0,Z.jsx)(BP,{workspaceId:H})},H),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start`,children:[(0,Z.jsx)(LP,{workspaceId:H,onAdded:async()=>{await Oe(),Pe()}}),(0,Z.jsx)(RP,{workspaceId:H,onAdded:async()=>{await Oe(),Pe()}}),(0,Z.jsx)(ZM,{workspaceId:H,onSaved:async()=>{await Oe(),Pe()}})]}),e&&(0,Z.jsx)(`section`,{className:`border-t pt-4`,children:(0,Z.jsx)(Qw,{workspaceName:e})})]}),S.status===`active`&&x===`db`&&(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[H&&(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Embeddings`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Which model turns this workspace's content into vectors, and where those vectors live.`})]}),(0,Z.jsx)(lN,{workspaceId:H,workspaceName:e})]}),(0,Z.jsx)(qP,{stats:ue,isLoading:fe,onRefresh:()=>U(),workspaceName:e})]}),S.status===`active`&&x===`devices`&&(0,Z.jsx)(WP,{allDevices:me,linkedDevices:ge,isLoading:ve,deviceBusy:be,onRefresh:()=>W(),onLink:we,onUnlink:Te,onUpdate:Ee}),S.status===`active`&&x===`sync`&&(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(gP,{workspaceId:H,workspaceUuid:S?.id})}),S.status===`active`&&x===`services`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[H&&(0,Z.jsx)(CP,{workspaceId:H}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:FP.map(e=>{let t=z?.[e.id]||z?.[e.id===`git`?`dotfiles`:e.id===`webdav`?`home`:`imap`],n=!!t?.enabled;return(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(pi,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:e.title})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[`initialized: `,t?.initialized?`true`:`false`]})]}),(0,Z.jsx)(IP,{checked:n,disabled:V===`service:${e.id}`,onClick:()=>Ve(e.id,n)})]})},e.id)})}),(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(DP,{workspaceId:H,enabled:!!(z?.imap?.enabled||z?.imapSync?.enabled)})})]}),S.status===`active`&&x===`policies`&&(0,Z.jsx)(nP,{workspaceId:H}),S.status===`active`&&x===`hooks`&&(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(CN,{workspaceId:H,prefillRule:m,onPrefillConsumed:h,initialSection:a,initialRunsHandler:o,initialRunId:s})})]})}):(0,Z.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,Z.jsx)(`h1`,{className:`font-semibold`,children:S.label||S.name}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Workspace settings are available to owners and admins.`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>g(`/workspaces/${e}`),children:`Back to workspace`})]}):(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Workspace not found`})}function XP({workspaceName:e}){let{selected:t,setSelected:n,tree:r,setTree:i,toggle:a}=Ew(),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null);return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Default folders`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Create a set of common folders with matching icons and colors.`}),(0,Z.jsx)(`div`,{className:`mt-3`,children:(0,Z.jsx)(Dw,{selected:t,onToggle:a,tree:r,onTreeChange:i,disabled:o,idPrefix:`settings-default-folders`})}),(0,Z.jsxs)(`div`,{className:`mt-3 flex items-center gap-3`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,disabled:o||t.size===0,onClick:async()=>{s(!0),l(null);let{ok:i,failed:a}=await Tw(e,Array.from(t),r);s(!1),l(a?`${i} created, ${a} failed`:`${i} folder(s) created`),n(new Set)},children:o?`Creating…`:`Create ${t.size||``} folder(s)`}),c&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:c})]})]})}function ZP({workspaceName:e,vectorSpaces:t,onDone:n}){let[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(null),s=async(e,t,r)=>{if(!(r&&!window.confirm(r))){i(e),o(null);try{let e=await t();o(e.message),n()}catch(e){o(e instanceof Error?e.message:`Reindex failed`)}finally{i(null)}}},c=[{title:`Bitmaps`,ops:[{key:`timelines`,label:`Reindex timelines`,description:`Rebuild the created/updated timelines from document data.`,fn:()=>vc(e)},{key:`mime`,label:`Reindex MIME types`,description:`Rebuild the per-MIME-type presence bitmaps (data/mime/*) from stored docs. Backfills blobs indexed before mime bitmaps existed.`,fn:()=>Wo(e)}]},{title:`Full-text (BM25)`,ops:[{key:`fts`,label:`Backfill`,description:`Index documents missing from the full-text table. Fast, skips already-indexed.`,fn:()=>$o(e)},{key:`fts-rebuild`,label:`Rebuild`,description:`Wipe the full-text table and rebuild from scratch. Use when counts drift.`,confirm:`Wipe the FTS index and rebuild it from scratch?`,fn:()=>$o(e,!0)},{key:`fts-optimize`,label:`Optimize`,description:`Compact fragments + prune old versions of the full-text table.`,fn:()=>ws(e,`fts`)}]},...t.length>0?[{title:`Vector tables (LanceDB)`,ops:t.map(t=>({key:`${t}-optimize`,label:`Optimize ${t}`,description:`Compact fragments + prune old versions of the '${t}' vector table and rebuild its ANN index.`,fn:()=>ws(e,t)}))}]:[]];return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Index maintenance`})]}),(0,Z.jsx)(`p`,{className:`mb-3 text-xs text-muted-foreground`,children:`Runs against this workspace. Reindex operations are idempotent.`}),(0,Z.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e.title}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.ops.map(e=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,className:`w-44 justify-start`,disabled:r!==null,onClick:()=>s(e.key,e.fn,e.confirm),children:[r===e.key&&(0,Z.jsx)(Er,{className:`mr-2 h-3 w-3 animate-spin`}),e.label]}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 basis-52 text-xs text-muted-foreground`,children:e.description})]},e.key))})]},e.title))}),a&&(0,Z.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:a})]})}var QP=[{value:`documentRead`,label:`Read`},{value:`documentWrite`,label:`Write`},{value:`documentReadWrite`,label:`Read & write`}];function $P(){let{contextId:e,tab:t}=yt(),[n]=$t(),r=n.get(`ownerId`)||void 0,i=ft(),{showToast:a}=wo(),{selectEntity:o,goBack:s,closeM2:c}=qC(),l=De(),u=ND(t),d=r?`?ownerId=${encodeURIComponent(r)}`:``;(0,X.useEffect)(()=>{t!==u&&e&&i(`/contexts/${e}/settings/${u}${d}`,{replace:!0})},[t,u,e,d,i]);let[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!0),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,w]=(0,X.useState)(``),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(``),[k,A]=(0,X.useState)(``),[j,M]=(0,X.useState)(),[N,P]=(0,X.useState)([]),[ee,F]=(0,X.useState)(!1),[I,te]=(0,X.useState)(``),[L,R]=(0,X.useState)(QP[0].value),[ne,re]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!e)return;let t=!1;return Tl(e,r).then(e=>{t||(p(e),o(e.id),x(e.name||``),w(e.description||``),E(typeof e.metadata?.ui?.color==`string`?e.metadata.ui.color:null),O(e.url||``),A(e.baseUrl||``))}).catch(()=>{t||a({title:`Error`,description:`Failed to load context`,variant:`destructive`})}).finally(()=>{t||h(!1)}),()=>{t=!0}},[e,r,o,a]);let ie=(t=e)=>{t&&(F(!0),jl(t).then(P).catch(()=>P([])).finally(()=>F(!1)))};(0,X.useEffect)(()=>{if(u!==`shares`||!e)return;let t=!1;return jl(e).then(e=>{t||P(e)}).catch(()=>{t||P([])}),()=>{t=!0}},[u,e]);let ae=async t=>{if(t.preventDefault(),e){_(!0);try{let t=await dl(e,{name:b.trim(),description:S.trim(),metadata:{...f?.metadata,ui:{...f?.metadata?.ui,color:T}}},r);p(t),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},z=async t=>{if(t.preventDefault(),e){_(!0);try{await Promise.all([sl(e,D.trim(),r,j),xl(e,{baseUrl:k.trim()||null},r)]),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context URL updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},oe=async()=>{if(e&&window.confirm(`Delete context "${e}"? This cannot be undone.`)){y(!0);try{await gl(e,r),c(),o(null),a({title:`Deleted`,description:`Context "${e}" removed`}),i(`/contexts`,{replace:!0})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{y(!1)}}},se=async t=>{if(t.preventDefault(),!(!e||!I.trim())){re(`grant`);try{await vl(e,I.trim(),L),te(``),ie(),a({title:`Shared`,description:`Access granted to ${I.trim()}`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{re(null)}}},B=async t=>{if(e&&window.confirm(`Revoke ${t.userEmail}'s access to "${e}"?`)){re(t.userEmail);try{await cl(e,t.userEmail),ie(),a({title:`Revoked`,description:`${t.userEmail} no longer has access`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke access`,variant:`destructive`})}finally{re(null)}}};if(m)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!f)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Context not found`});let ce=MD.find(e=>e.id===u),V=`/contexts/${e}${d}`;return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${ce.label} - ${f.name||f.id}`,description:ce.description,backTo:V,onBack:l?s:void 0}),u===`general`&&(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`form`,{onSubmit:ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Context ID`}),(0,Z.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:f.id})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-name`,className:`text-sm font-medium`,children:`Name`}),(0,Z.jsx)(q,{id:`ctx-name`,value:b,onChange:e=>x(e.target.value),placeholder:`My Context`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`ctx-description`,value:S,onChange:e=>w(e.target.value),placeholder:`Optional description`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-color`,className:`text-sm font-medium`,children:`Color`}),(0,Z.jsxs)(`div`,{className:`mt-1 flex items-center gap-2`,children:[(0,Z.jsx)(q,{id:`ctx-color`,type:`color`,value:/^#[0-9a-f]{6}$/i.test(T||f.color||``)?T||f.color:`#808080`,onChange:e=>E(e.target.value),className:`h-10 w-16 p-1`,disabled:g}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:g||T===null,onClick:()=>E(null),children:`Use inherited color`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:T===null?`Using the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Workspace`}),(0,Z.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 text-sm text-muted-foreground`,children:f.workspaceName||f.workspaceId||f.workspace})]}),(0,Z.jsx)(Y,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(Y,{variant:`destructive`,disabled:v,onClick:oe,children:[(0,Z.jsx)(Qr,{className:`mr-2 h-4 w-4`}),v?`Deleting...`:`Delete Context`]})]})]}),u===`location`&&(0,Z.jsxs)(`form`,{onSubmit:z,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-url`,className:`text-sm font-medium`,children:`URL`}),(0,Z.jsx)(C,{id:`ctx-url`,value:D,onChange:O,fixedWorkspaceName:f.workspaceName,pickerTitle:`Switch context to…`,placeholder:`workspace://path`,onPickTarget:(e,t)=>{O(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),M(t.treeName)}}),j&&(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Destination tree: `,j]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`label`,{htmlFor:`ctx-base-url`,className:`text-sm font-medium`,children:[`Base URL `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsx)(C,{id:`ctx-base-url`,value:k,onChange:A,fixedWorkspaceName:f.workspaceName,placeholder:`workspace://base/path`,pickerTitle:`Pick a base path…`})]}),(0,Z.jsx)(Y,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),u===`shares`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`People with access`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Only the context owner can see and change this list.`})]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ie(),disabled:ee,children:[(0,Z.jsx)(Er,{className:K(`mr-2 h-3.5 w-3.5`,ee&&`animate-spin`)}),`Refresh`]})]}),N.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):N.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.userEmail}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[QP.find(t=>t.value===e.accessLevel)?.label||e.accessLevel||`unknown access`,e.sharedAt&&` - since ${new Date(e.sharedAt).toLocaleDateString()}`]})]}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:ne===e.userEmail,onClick:()=>B(e),children:(0,Z.jsx)(nr,{className:`h-3.5 w-3.5`})})]},e.userEmail))]}),(0,Z.jsxs)(`form`,{onSubmit:se,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Grant access`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`share-email`,className:`text-sm font-medium`,children:`User email`}),(0,Z.jsx)(q,{id:`share-email`,type:`email`,value:I,onChange:e=>te(e.target.value),placeholder:`person@example.com`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`The user must already have an account on this server.`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`share-level`,className:`text-sm font-medium`,children:`Access level`}),(0,Z.jsx)(`select`,{id:`share-level`,value:L,onChange:e=>R(e.target.value),className:`mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:QP.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),(0,Z.jsx)(Y,{type:`submit`,disabled:ne===`grant`||!I.trim(),children:ne===`grant`?`Sharing...`:`Share context`})]})]})]})})}function eF({status:e}){let t={running:{icon:kr,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:Bn,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:Zn,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:Zn,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:er,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:ui,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:ui,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:Bn,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,Z.jsx)(r,{className:`w-3 h-3`}),n.label]})}function tF(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null);Ae(()=>s(null),o!==null);let[c,l]=hw(),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(``),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(!1),{showToast:S}=wo(),C=du(),w=(0,X.useCallback)(async()=>{try{r(!0);let e=await Nj.listRoles({type:`workspace`,userId:C?.id});t(e),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch roles`;a(t)}finally{r(!1)}},[C?.id]);(0,X.useEffect)(()=>{let e=()=>w();e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[w]),(0,X.useEffect)(()=>{c&&(Nj.listTemplates().then(e=>{let t=e.filter(e=>e.type===`workspace`);d(t),h(e=>e||t[0]?.id||``)}).catch(()=>d([])),Uo().then(e=>{p(e),y(t=>t||e[0]?.id||``)}).catch(()=>p([])))},[c]);let T=async e=>{if(e.preventDefault(),!(!m||!g.trim()||!v)){x(!0);try{let e=await Nj.createRole({template:m,name:g.trim(),type:`workspace`,userId:C?.id,workspaceId:v});_(``),l(!1),await w(),S({title:`Created`,description:`Role "${e.name}" created`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to create role`,variant:`destructive`})}finally{x(!1)}}},E=async e=>{try{await Nj.startRole(e.id),S({title:`Success`,description:`Role "${e.name}" started successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to start role`;S({title:`Error`,description:t,variant:`destructive`})}},D=async e=>{try{await Nj.stopRole(e.id),S({title:`Success`,description:`Role "${e.name}" stopped successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to stop role`;S({title:`Error`,description:t,variant:`destructive`})}},O=async e=>{try{await Nj.restartRole(e.id),S({title:`Success`,description:`Role "${e.name}" restarted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to restart role`;S({title:`Error`,description:t,variant:`destructive`})}},k=async e=>{try{let t=await Nj.getRoleLogs(e.id,100);s({role:e,logs:t})}catch(e){let t=e instanceof Error?e.message:`Failed to fetch logs`;S({title:`Error`,description:t,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`My Roles`,description:`Manage your workspace roles and services`,actions:(0,Z.jsxs)(Z.Fragment,{children:[!c&&(0,Z.jsxs)(Y,{onClick:()=>l(!0),children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Role`]}),(0,Z.jsxs)(Y,{onClick:w,variant:`outline`,children:[(0,Z.jsx)(Ba,{className:`mr-2 h-4 w-4`}),`Refresh`]})]})}),c&&(0,Z.jsx)(pw,{title:`Create New Role`,onClose:()=>l(!1),children:(0,Z.jsxs)(`form`,{onSubmit:T,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-template`,className:`mb-1 block text-sm font-medium`,children:`Template`}),(0,Z.jsxs)(`select`,{id:`role-template`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:m,onChange:e=>h(e.target.value),disabled:b||u.length===0,children:[u.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspace templates available`}),u.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-name`,className:`mb-1 block text-sm font-medium`,children:`Role Name`}),(0,Z.jsx)(q,{id:`role-name`,value:g,onChange:e=>_(e.target.value),placeholder:`e.g., canvas-sshd`,disabled:b})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-workspace`,className:`mb-1 block text-sm font-medium`,children:`Workspace`}),(0,Z.jsxs)(`select`,{id:`role-workspace`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:v,onChange:e=>y(e.target.value),disabled:b||f.length===0,children:[f.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),f.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label||e.name},e.id))]})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:b||!m||!g.trim()||!v,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),b?`Creating…`:`Create Role`]})]})}),n?(0,Z.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):i?(0,Z.jsx)(`div`,{className:`text-center py-8 text-destructive`,children:i}):e.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-12 border rounded-lg`,children:[(0,Z.jsx)(pi,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`You don't have any workspace roles yet`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Contact your administrator to set up roles for your workspaces`})]}):(0,Z.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:e.map(e=>(0,Z.jsxs)(`div`,{className:`border rounded-lg p-6 space-y-4 hover:shadow-elevation-2 transition-shadow`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold text-lg`,children:e.name}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.template})]}),(0,Z.jsx)(eF,{status:e.status})]}),e.container&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(pi,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.container.name})]})}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-2`,children:[e.status===`stopped`||e.status===`created`?(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>E(e),className:`flex-1`,children:[(0,Z.jsx)(Ar,{className:`w-4 h-4 mr-2`}),`Start`]}):e.status===`running`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>D(e),className:`flex-1`,children:[(0,Z.jsx)(Sa,{className:`w-4 h-4 mr-2`}),`Stop`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>O(e),className:`flex-1`,children:[(0,Z.jsx)(Ba,{className:`w-4 h-4 mr-2`}),`Restart`]})]}):(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,disabled:!0,className:`flex-1`,children:[(0,Z.jsx)(Zn,{className:`w-4 h-4 mr-2`}),e.status]}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>k(e),title:`View Logs`,children:(0,Z.jsx)(Ki,{className:`w-4 h-4`})})]})]},e.id))}),(0,Z.jsxs)(`div`,{className:`border-t pt-6`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold mb-4`,children:`Global Services`}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground space-y-2`,children:[(0,Z.jsx)(`p`,{children:`Global roles are server-wide services managed by your administrator. These include services like SSH access, storage, and other shared infrastructure.`}),(0,Z.jsx)(`p`,{children:`To check the status of global services, contact your system administrator.`})]})]}),o&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-4xl w-full mx-4 max-h-viewport-modal flex flex-col`,children:[(0,Z.jsxs)(`div`,{className:`p-6 border-b`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-bold`,children:[o.role.name,` - Logs`]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.role.template})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,Z.jsx)(`div`,{"data-scheme":`dark`,className:`bg-background text-success p-4 rounded font-mono text-xs overflow-x-auto`,children:o.logs.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`pre`,{children:o.logs.join(`
|
|
53
|
+
`)})})}),(0,Z.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,Z.jsx)(Y,{onClick:()=>s(null),children:`Close`})})]})})]})}function nF(){return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`Remotes`,description:`Connect to remote Canvas instances`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Remote connection management is currently under development. Check back later for updates.`})]})})]})}var rF=[`note`,`todo`,`link`,`file`,`photo`];function iF(){let{kind:e}=yt(),t=ft();return e===`sketch`?(0,Z.jsx)(ht,{to:`/apps/sketch?add=1`,replace:!0}):!e||!rF.includes(e)?(0,Z.jsx)(ht,{to:`/home`,replace:!0}):(0,Z.jsx)(XE,{initialKind:e,onInitialCardClose:()=>t(`/home`)})}var aF=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(sn,{index:!0,element:(0,Z.jsx)(oD,{})},`r1`),(0,Z.jsx)(sn,{path:`home`,element:(0,Z.jsx)(aD,{})},`r2`),(0,Z.jsx)(sn,{path:`share-target`,element:(0,Z.jsx)(pD,{})},`r3`),(0,Z.jsx)(sn,{path:`apps`,element:(0,Z.jsx)(rw,{})},`apps-index`),(0,Z.jsx)(sn,{path:`apps/:appletId`,element:(0,Z.jsx)(xC,{})},`apps-host`),(0,Z.jsx)(sn,{path:`apps/add/:kind`,element:(0,Z.jsx)(iF,{})},`r4`),(0,Z.jsx)(sn,{path:`workspaces`,element:(0,Z.jsx)(Rw,{})},`r5`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName`,element:(0,Z.jsx)(yE,{})},`r6`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/documents/by-id/:documentId`,element:(0,Z.jsx)(wE,{})},`workspace-document-by-id`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/documents/:documentId`,element:(0,Z.jsx)(wE,{})},`workspace-document`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/documents/by-hash/:algo/:checksum`,element:(0,Z.jsx)(wE,{})},`workspace-document-by-hash`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/documents/by-checksum/:algo/:checksum`,element:(0,Z.jsx)(wE,{})},`workspace-document-by-checksum`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/settings`,element:(0,Z.jsx)(JP,{})},`r7`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/settings/:tab`,element:(0,Z.jsx)(JP,{})},`r8`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/path/*`,element:(0,Z.jsx)(yE,{})},`r9`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/trees/:treeName`,element:(0,Z.jsx)(yE,{})},`r10`),(0,Z.jsx)(sn,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:(0,Z.jsx)(yE,{})},`r11`),(0,Z.jsx)(sn,{path:`contexts`,element:(0,Z.jsx)(gD,{})},`r12`),(0,Z.jsx)(sn,{path:`contexts/:contextId`,element:(0,Z.jsx)(vD,{})},`r13`),(0,Z.jsx)(sn,{path:`contexts/:contextId/settings`,element:(0,Z.jsx)($P,{})},`r14`),(0,Z.jsx)(sn,{path:`contexts/:contextId/settings/:tab`,element:(0,Z.jsx)($P,{})},`r15`),(0,Z.jsx)(sn,{path:`agents`,element:(0,Z.jsx)(sM,{})},`r16`),(0,Z.jsx)(sn,{path:`agents/:agentId`,element:(0,Z.jsx)(CM,{})},`r17`),(0,Z.jsx)(sn,{path:`agents/:agentId/:sessionId`,element:(0,Z.jsx)(CM,{})},`r18`),(0,Z.jsx)(sn,{path:`agents/:agentId/settings`,element:(0,Z.jsx)(jM,{})},`r19`),(0,Z.jsx)(sn,{path:`agents/:agentId/settings/:tab`,element:(0,Z.jsx)(jM,{})},`r20`),(0,Z.jsx)(sn,{path:`roles`,element:(0,Z.jsx)(tF,{})},`r21`),(0,Z.jsx)(sn,{path:`remotes`,element:(0,Z.jsx)(nF,{})},`r22`),(0,Z.jsx)(sn,{path:`settings`,element:(0,Z.jsx)(SO,{})},`settings`),(0,Z.jsx)(sn,{path:`appearance`,element:(0,Z.jsx)(Hk,{})},`r23`),(0,Z.jsx)(sn,{path:`key-bindings`,element:(0,Z.jsx)(Zk,{})},`key-bindings`),(0,Z.jsx)(sn,{path:`offline`,element:(0,Z.jsx)(IA,{})},`r24`),(0,Z.jsx)(sn,{path:`about`,element:(0,Z.jsx)(zA,{})},`r25`),(0,Z.jsx)(sn,{path:`api-tokens`,element:(0,Z.jsx)(bD,{})},`r26`),(0,Z.jsx)(sn,{path:`devices`,element:(0,Z.jsx)(OD,{})},`r27`),(0,Z.jsx)(sn,{path:`embedding`,element:(0,Z.jsx)(bj,{})},`r28`),(0,Z.jsx)(sn,{path:`shared`,element:(0,Z.jsx)(xj,{})},`r29`),(0,Z.jsx)(sn,{path:`admin/users`,element:(0,Z.jsx)(Lj,{})},`r30`),(0,Z.jsx)(sn,{path:`admin/contexts`,element:(0,Z.jsx)(Dj,{})},`r31`),(0,Z.jsx)(sn,{path:`admin/workspaces`,element:(0,Z.jsx)(Ej,{})},`r32`),(0,Z.jsx)(sn,{path:`admin/agents`,element:(0,Z.jsx)(Oj,{})},`r33`),(0,Z.jsx)(sn,{path:`admin/logs`,element:(0,Z.jsx)(Mj,{})},`r34`),(0,Z.jsx)(sn,{path:`admin/roles`,element:(0,Z.jsx)(Ij,{})},`r35`),(0,Z.jsx)(sn,{path:`admin/embedding`,element:(0,Z.jsx)(Rj,{})},`r36`),(0,Z.jsx)(sn,{path:`admin/auth`,element:(0,Z.jsx)(aM,{})},`r37`)]});function oF(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`)||/[\\\u0000-\u0020]/.test(e))return null;let t=new URL(e,`https://canvas.invalid`);return t.origin!==`https://canvas.invalid`||/^\/(?:login|register|pub|share-target|apps|next)(?:\/|$)/.test(t.pathname)||t.pathname===`/`||[...t.searchParams.keys()].some(e=>/token|password|secret|code/i.test(e))?null:t.pathname+t.search+t.hash}function sF(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var cF=un(aF),lF=e=>{let t=oF(e);return t&&ct(cF,t)?t:null};function uF(){let e=vn(),[t]=(0,X.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:lF(localStorage.getItem(sF(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,X.useEffect)(()=>{if(n)return;let t=lF(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(sF(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,Z.jsx)(ht,{to:t.path,replace:!0}):null}var dF={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function fF(e,t){switch(t.type){case`RESTORE_MENU`:return{...e,...t.menu,user:e.user};case`SET_SECTION`:return{...e,activeSection:t.section,m1Open:t.section!==null,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_SECTION`:return e.activeSection===t.section&&e.m1Open?{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_M0`:return e.m0Open?{...e,m0Open:!1,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,m0Open:!0};case`CLOSE_M0`:return{...e,m0Open:!1};case`CLOSE_M1`:return{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null};case`OPEN_M2`:return{...e,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId===void 0?e.selectedEntityId:t.entityId};case`OPEN_M2_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId};case`OPEN_M1_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`CLOSE_M2`:return{...e,m2Open:!1,m2View:null};case`SELECT_ENTITY`:return{...e,selectedEntityId:t.entityId};case`SYNC_FROM_URL`:{let n=!t.mobile&&!e.m2Open&&e.m2View===null&&t.section===e.activeSection&&t.entityId===e.selectedEntityId;return t.section===e.activeSection&&t.entityId===e.selectedEntityId&&t.m2View===e.m2View&&!(t.mobile&&(e.m1Open||e.m0Open))?e:{...e,activeSection:t.section,m0Open:!t.mobile&&e.m0Open,m1Open:!t.mobile&&t.section!==null,selectedEntityId:t.entityId,m2Open:!n&&t.m2View!==null,m2View:n?null:t.m2View}}case`SET_USER`:return{...e,user:t.user};default:return e}}function pF({children:e}){let[t,n]=(0,X.useReducer)(fF,dF),r=vn(),i=ft(),a=(0,X.useRef)(t);(0,X.useLayoutEffect)(()=>{a.current=t},[t]),YC(t,n);let o=(0,X.useCallback)((e,t=!1,o=!1)=>{let s=fF(a.current,e);if(a.current=s,n(e),!GC())return;let{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p}=s;i({pathname:r.pathname,search:r.search,hash:r.hash},{replace:t,state:{...r.state,canvasMenu:{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p},canvasMenuBack:o}})},[r,i]),s=(0,X.useCallback)(e=>{if(GC()&&a.current.m1Open){let{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l}=a.current;i(e,{replace:!0,state:{...r.state,canvasMenu:{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l},canvasMenuBack:!1}})}i(e)},[r.state,i]),c=(0,X.useCallback)(()=>{if(window.history.state?.idx>0){i(-1);return}let e=a.current;if(e.m1Open&&e.m2Open)o({type:`CLOSE_M2`},!0,!0);else if(e.m1Open)o({type:`CLOSE_M1`},!0,!0);else if(e.m0Open)o({type:`CLOSE_M0`},!0,!0);else{let{section:e,entityId:t,m2View:n}=JC(r.pathname);if(!GC()){i(e?`/${e}`:`/`);return}o(e&&t?{type:`OPEN_M2_DRAWER`,section:e,view:n,entityId:t}:{type:`TOGGLE_M0`},!0,!0)}},[o,r.pathname,i]);(0,X.useEffect)(()=>{let e=du();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return fu().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let l={state:t,dispatch:n,setSection:(0,X.useCallback)(e=>{o({type:`SET_SECTION`,section:e})},[o]),toggleSection:(0,X.useCallback)(e=>{o({type:`TOGGLE_SECTION`,section:e})},[o]),toggleM0:(0,X.useCallback)(()=>{o({type:`TOGGLE_M0`},a.current.m0Open)},[o]),closeM0:(0,X.useCallback)(()=>{o({type:`CLOSE_M0`},!0)},[o]),closeM1:(0,X.useCallback)(()=>{o({type:`CLOSE_M1`},!0)},[o]),openM2:(0,X.useCallback)((e,t)=>{o({type:`OPEN_M2`,view:e,entityId:t})},[o]),openM2Drawer:(0,X.useCallback)((e,t,n)=>{o({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:n})},[o]),openM1Drawer:(0,X.useCallback)(e=>{o({type:`OPEN_M1_DRAWER`,section:e})},[o]),closeM2:(0,X.useCallback)(()=>{GC()&&a.current.m1Open&&a.current.m2Open?c():n({type:`CLOSE_M2`})},[c]),selectEntity:(0,X.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[]),goBack:c,navigateFromMenu:s};return(0,Z.jsx)(KC.Provider,{value:l,children:e})}function mF(){return(0,X.useSyncExternalStore)(ho,oo,()=>!1)}function hF(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&oo()&&(i=setTimeout(()=>{s()},3e4))}function s(s=!1){if(n)return n;if(r)return Promise.resolve(!1);clearTimeout(i),a=new AbortController;let c=setTimeout(()=>a?.abort(),5e3);return n=(async()=>{try{let n=await fetch(e,{cache:`no-store`,credentials:`omit`,signal:a.signal});if(!n.ok||n.headers.get(`x-canvas-offline`)===`fallback`)throw Error(`Unavailable`);if((await n.json()).status!==`success`)throw Error(`Not a Canvas response`);if(r)return!1;let i=oo();return co(),(i||s)&&t(),!0}catch{return r||fo(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=ho(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var gF;function _F(){gF=hF(`${yo}/ping`,()=>B.retryNow());let e=()=>{gF?.retry()},t=B.on(`connect_error`,e),n=B.on(`disconnect`,e);return()=>{t(),n(),gF?.stop(),gF=void 0}}function vF(){return gF?.retry(!0)??Promise.resolve(!1)}function yF(){let e=mF(),[t,n]=(0,X.useState)(!1);return e?(0,Z.jsxs)(`details`,{className:`relative`,children:[(0,Z.jsx)(`summary`,{"aria-label":`Offline — connection options`,title:`Offline — cached content available`,className:`flex h-10 w-10 cursor-pointer list-none items-center justify-center rounded-lg text-amber-600 hover:bg-accent/50 [&::-webkit-details-marker]:hidden`,children:(0,Z.jsx)(Hn,{className:`h-5 w-5`})}),(0,Z.jsxs)(`div`,{className:`absolute bottom-0 left-full z-50 ml-2 w-60 max-w-[calc(100vw-5rem)] rounded-lg border bg-popover p-3 text-popover-foreground shadow-lg`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`You can browse cached documents. We’ll reconnect automatically when the server is available.`}),(0,Z.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await vF()}finally{n(!1)}},className:`mt-3 rounded-md bg-secondary px-3 py-2 text-xs font-medium hover:bg-accent disabled:opacity-50`,children:t?`Checking…`:`Retry now`})]})]}):null}var bF=Rr,xF=Kn,SF=La,CF=X.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,Z.jsx)(Va,{children:(0,Z.jsx)(_i,{ref:r,sideOffset:t,className:K(`z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in duration-fast 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 origin-[--radix-tooltip-content-transform-origin]`,e),...n})}));CF.displayName=_i.displayName;var wF=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(li,{ref:n,className:K(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));wF.displayName=li.displayName;var TF=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Wa,{ref:n,className:K(`aspect-square h-full w-full`,e),...t}));TF.displayName=Wa.displayName;var EF=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Na,{ref:n,className:K(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));EF.displayName=Na.displayName;function DF({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=qC(),o=i.activeSection===e;return(0,Z.jsxs)(xF,{children:[(0,Z.jsx)(SF,{asChild:!0,children:(0,Z.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:K(`relative flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,o?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`,r&&`opacity-30 cursor-not-allowed`),children:[o&&(0,Z.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,Z.jsx)(CF,{side:`right`,sideOffset:8,children:n})]})}function OF({path:e,icon:t,label:n,section:r=`settings`}){let i=ft(),{setSection:a}=qC();return(0,Z.jsxs)(xF,{children:[(0,Z.jsx)(SF,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":n,onClick:()=>{a(r),i(e)},className:`flex items-center justify-center w-10 h-10 rounded-lg text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors`,children:t})}),(0,Z.jsx)(CF,{side:`right`,sideOffset:8,children:n})]})}function kF(){let{state:e,toggleM0:t}=qC(),n=mF();return(0,Z.jsxs)(`button`,{type:`button`,onClick:t,"aria-label":`${e.m0Open?`Close menu`:`Open menu`}${n?` — offline, connection options in menu`:``}`,"data-shell":`rail`,className:`fixed bottom-rail-inset left-2 z-nav flex h-rail w-rail items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[e.m0Open?(0,Z.jsx)(vr,{className:`h-5 w-5`}):(0,Z.jsx)(sa,{className:`h-5 w-5`}),n&&(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`absolute right-0 top-0 h-3 w-3 rounded-full border-2 border-background bg-amber-500`})]})}function AF(){let{state:e,closeM0:t,closeM1:n}=qC(),{state:r,setView:i,closeT1:a}=ol(),o=ft(),{showToast:s}=wo(),c=e.user?.userType===`admin`,l=aw(),u=()=>{r.t1Open?a():i(`tools`),n(),t()},d=(0,X.useCallback)(async()=>{try{await J.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,Z.jsxs)(bF,{delayDuration:200,children:[e.m0Open&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{"data-shell":`rail`,className:K(`flex flex-col items-center w-rail h-full rounded-(--panel-radius) bg-transparent shrink-0`,e.m0Open?`max-md:fixed max-md:left-2 max-md:top-2 max-md:bottom-rail-stack max-md:z-rail max-md:h-auto max-md:bg-card max-md:surface-glass max-md:shadow-elevation-5`:`max-md:hidden`),children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Canvas home`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Z.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,Z.jsxs)(`nav`,{className:`flex flex-col items-center gap-1 py-2 flex-1 min-h-0 overflow-y-auto`,children:[(!l.local||l.workspace!==!1)&&(0,Z.jsx)(DF,{section:`contexts`,icon:(0,Z.jsx)(vi,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,Z.jsx)(DF,{section:`workspaces`,icon:(0,Z.jsx)(Ga,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,Z.jsx)(DF,{section:`agents`,icon:(0,Z.jsx)(ri,{className:`w-5 h-5`}),label:`Agents`}),(0,Z.jsx)(DF,{section:`apps`,icon:(0,Z.jsx)(Hi,{className:`w-5 h-5`}),label:`Apps`}),(!l.local||l.workspace!==!1)&&(0,Z.jsx)(OF,{path:`/roles`,section:null,icon:(0,Z.jsx)(Ma,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,Z.jsx)(OF,{path:`/admin/users`,icon:(0,Z.jsx)(ar,{className:`w-5 h-5`}),label:`All Users`}),(0,Z.jsx)(OF,{path:`/admin/logs`,icon:(0,Z.jsx)(Ki,{className:`w-5 h-5`}),label:`Server Logs`}),(0,Z.jsx)(OF,{path:`/admin/workspaces`,icon:(0,Z.jsx)($r,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,Z.jsx)(OF,{path:`/admin/agents`,icon:(0,Z.jsx)(ri,{className:`w-5 h-5`}),label:`All Agents`}),(0,Z.jsx)(OF,{path:`/admin/roles`,icon:(0,Z.jsx)(Ma,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,Z.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,Z.jsx)(yF,{}),(0,Z.jsxs)(xF,{children:[(0,Z.jsx)(SF,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,onClick:u,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:K(`flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,r.t1Open?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`),children:(0,Z.jsx)(Pr,{className:`w-5 h-5`})})}),(0,Z.jsx)(CF,{side:`right`,sideOffset:8,children:`Toolbox`})]}),!l.local&&(0,Z.jsx)(OF,{path:`/settings`,section:`settings`,icon:(0,Z.jsx)(Wi,{className:`w-5 h-5`}),label:`Settings`}),(0,Z.jsxs)(xF,{children:[(0,Z.jsx)(SF,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":e.user?.email?`Profile: ${e.user.email}`:`Profile`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Z.jsx)(wF,{className:`h-7 w-7 touch-target`,children:(0,Z.jsx)(EF,{className:`text-[10px] bg-muted`,children:e.user?.email?(e=>e.split(`@`)[0].split(`.`).map(e=>e.charAt(0).toUpperCase()).join(``).slice(0,2))(e.user.email):`U`})})})}),(0,Z.jsx)(CF,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,Z.jsxs)(xF,{children:[(0,Z.jsx)(SF,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Log out`,onClick:d,className:`flex items-center justify-center w-10 h-10 rounded-lg text-destructive hover:bg-destructive/10 transition-colors`,children:(0,Z.jsx)(wa,{className:`w-5 h-5`})})}),(0,Z.jsx)(CF,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}var jF=220,MF=560;function NF({width:e,onResize:t,onDragging:n}){let r=(0,X.useRef)(null),i=e=>t(Math.min(MF,Math.max(jF,e))),a=()=>{r.current=null,n?.(!1)};return(0,Z.jsx)(`div`,{role:`separator`,"aria-label":`Resize menu`,"aria-orientation":`vertical`,"aria-valuemin":jF,"aria-valuemax":MF,"aria-valuenow":e,tabIndex:0,title:`Drag to resize; use arrow keys to adjust; Home resets width`,className:`absolute inset-y-0 right-0 z-30 flex w-3 touch-none select-none cursor-col-resize items-center justify-center hover:bg-primary/10 focus-visible:bg-primary/10 focus-visible:outline-none [@media(pointer:coarse)]:w-6`,onPointerDown:t=>{t.button!==0||r.current||(t.preventDefault(),t.stopPropagation(),r.current={id:t.pointerId,x:t.clientX,width:e},t.currentTarget.setPointerCapture(t.pointerId),n?.(!0))},onPointerMove:e=>{r.current?.id===e.pointerId&&i(r.current.width+e.clientX-r.current.x)},onPointerUp:e=>{r.current?.id===e.pointerId&&(a(),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},onPointerCancel:a,onLostPointerCapture:a,onDoubleClick:()=>i(280),onKeyDown:t=>{[`ArrowLeft`,`ArrowRight`,`Home`].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),i(t.key===`Home`?280:e+(t.key===`ArrowRight`?1:-1)*(t.shiftKey?64:16)))},children:(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`h-10 w-1 rounded-full bg-border`})})}function PF(e,t,n,r=!0){let i=De(),a=vn(),o=(0,X.useRef)(null);(0,X.useLayoutEffect)(()=>{let s=window.history.state?.idx??0,c=o.current,l=a.state?.canvasMenuBack||!!c&&(s<c.index||s===c.index&&c.backwards);if(o.current={active:t,viewKey:n,index:s,backwards:l},!r||!i||!t||!c||c.active&&c.viewKey===n)return;let u=e.current;if(!u||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;let d=Number.parseFloat(getComputedStyle(u).getPropertyValue(`--motion-scale`)),f=Number.isFinite(d)?Math.max(0,d):1,p=u.animate([{transform:`translateX(${l?`-100%`:`100%`})`},{transform:`translateX(0)`}],{duration:70*f,easing:`cubic-bezier(0.2, 0, 0, 1)`});return()=>p.cancel()},[r,i,t,n,a.key,a.state,e])}function FF(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ml();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useRef)(s);(0,X.useEffect)(()=>{c.current=s});let l=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>B.emit(`subscribe`,{channel:`context`}),r=()=>B.emit(`unsubscribe`,{channel:`context`}),i=B.on(`connect`,()=>{t(),s()});t();let o=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.some(e=>e.id===t.id&&e.userId===t.userId)?e:[...e,t])},l=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},u=e=>{let t=e,r=t?.contextId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},d=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},f=()=>{a.current=!1,c.current()},p=[[`context:created`,o],[`context.created`,o],[`context:updated`,l],[`context.updated`,l],[`context:deleted`,u],[`context.deleted`,u],[`context:url:changed`,d],[`context.url.set`,d],[`context:url:set`,d],[`workspace:status:changed`,f],[`workspace.status.changed`,f]];return p.forEach(([e,t])=>B.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>B.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!il(e,t)))};return window.addEventListener(ll,e),()=>window.removeEventListener(ll,e)},[]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,X.useMemo)(()=>Pw(t),[t]),isLoading:r,refresh:l}}function IF(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=qC(),i=De(),{contexts:a,isLoading:o}=FF(e.activeSection===`contexts`),{showToast:s}=wo(),c=ft(),[l,u]=(0,X.useState)(null),d=l&&l.base===a?l.order:a,p=e=>e.isShared===!0||e.type===`shared`,{rowProps:m,handleProps:h,draggingIndex:g,insertLineClass:_}=Lw((e,t)=>{let n=Fw(d,e,t);u({base:a,order:n}),Iw(n,(e,t)=>p(e)?Promise.resolve():xl(e.id,{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e&&s({title:`Partial reorder`,description:`${e} context(s) could not be reordered`,variant:`destructive`})})}),v=e=>{t(e.id),c(`/contexts/${e.id}`)};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,Z.jsx)(XC,{}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{r(),c(`/contexts?create=1`)},title:`Create context`,"aria-label":`Create context`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Z.jsx)(br,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:d.map((r,a)=>{let o=e.selectedEntityId===r.id,s=p(r),l=r.workspaceActive!==!1,u=Jt(r.color);return(0,Z.jsxs)(`div`,{...m(a),"data-active":o||void 0,className:K(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,l?`cursor-pointer hover:shadow `+(o?`bg-accent shadow`:`bg-card hover:bg-accent/50`):`cursor-not-allowed opacity-50 bg-card`,_(a,d.length),g===a&&`opacity-60`),onClick:()=>l&&v(r),title:l?void 0:`Workspace "${r.workspaceName}" is not active`,children:[s?(0,Z.jsx)(`div`,{className:K(`absolute inset-y-0 right-0 w-4 rounded-r-(--card-radius)`,!u&&`bg-muted`),style:u?{backgroundColor:u}:void 0}):(0,Z.jsx)(`button`,{type:`button`,...h(a),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:K(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!u&&`bg-muted`),style:u?{backgroundColor:u}:void 0,children:(0,Z.jsx)(Un,{className:K(`h-3.5 w-3.5`,tt(u))})}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(f,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:u,className:K(`mt-0.5 shrink-0`,!u&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),s&&(0,Z.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),l&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),n(`detail`,r.id)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Switch context URL`,children:(0,Z.jsx)(Ri,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),i?n(`settings`,r.id):c(`/contexts/${r.id}/settings/general`)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Settings`,children:(0,Z.jsx)(Wi,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function LF({title:e,onBack:t,action:n,className:r,icon:i,accentColor:a}){let{closeM1:o}=qC(),s=Jt(a);return(0,Z.jsxs)(`div`,{className:K(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{borderBottomWidth:4,...s?{borderBottomColor:s}:{}},children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-0.5 h-8 rounded px-1 hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors flex-1 min-w-0`,title:`Back`,"aria-label":`Back to previous view`,children:[(0,Z.jsx)(Wn,{className:`w-4 h-4 shrink-0`}),i&&(0,Z.jsx)(f,{icon:i,width:16,height:16,color:s,className:K(`mr-1 shrink-0`,!s&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,Z.jsx)(`div`,{className:`shrink-0`,children:n}),(0,Z.jsx)(`button`,{type:`button`,onClick:o,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Close menu`,"aria-label":`Close menu`,children:(0,Z.jsx)(vr,{className:`w-4 h-4`})})]})}function RF(e,t,n){let r=e.indexOf(n);if(r<0)return new Set;let i=t===null?-1:e.indexOf(t);return new Set(i<0?[n]:e.slice(Math.min(i,r),Math.max(i,r)+1))}function zF(e){let t=[...e];return t.filter(e=>!t.some(t=>t!==e&&e.startsWith(`${t}/`)))}var BF=22,VF=44,HF=4;function UF(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?null:n[0]===`workspace`&&n.length>=2?{address:`workspace:${n[1]}`,key:n.slice(2).join(`/`)}:n[0]===`device`&&n.length>=3?{address:n[2],key:n.slice(3).join(`/`)}:n[0]===`file`&&n.length>=2?{address:n[1],key:n.slice(2).join(`/`)}:null}function WF(e,t){return!t||Hs(e)!==null}var GF=e=>Array.from(e.dataTransfer.types).includes(`application/json`);function KF(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?n[2]||null:n[0]===`workspace`&&n.length>=2?`workspace:${n[1]}`:n[0]===`device`?n.length>=3?n[2]:null:n.length>=2?n[1]:null}function qF({x:e,y:t,node:n,path:r,isBackendsTree:i,isDirectoryTree:a,backends:o,onClose:s,onShowContent:c,onOpenToSide:l,sourceLayer:u,targetLayers:d,clipboard:f,onStartInlineCreate:p,onChangeIcon:m,onNewCanvas:h,onShareCanvas:g,onRemove:_,onRename:v,onExportSubtree:y,onImportSubtree:b,onImportDocuments:x,onExportDocuments:S,onLock:C,onUnlock:w,onDestroy:T,onMerge:E,onSubtract:D,onMergeDown:O,onSubtractDown:k,onResyncBackend:A,canResyncBackend:j,onAddRule:M,onAddStoreRule:N,onStoragePolicy:P,onRenameBackendFolder:ee,onDeleteBackendFolder:F,onRestoreTrash:I,onDiscardTrash:te,onCopy:L,onCut:R,onPaste:ne,pastedDocumentIds:re,onPasteDocuments:ie,isPinned:ae,onTogglePin:z}){let oe=u&&d.size>0&&u.path===r,se=!i&&(O||k)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,B=u&&d.size>0&&(u.path===r||d.has(r)),ce=async e=>{s();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},V=(e,t,n,r=!1)=>(0,Z.jsxs)(`button`,{type:`button`,className:K(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>ce(n),children:[e,t]});return i&&n.metadata?.backendTrash?(0,Z.jsxs)(Dn,{x:e,y:t,onClose:s,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&V((0,Z.jsx)(Qr,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&I&&V((0,Z.jsx)(Vr,{className:`h-3 w-3`}),`Restore original paths`,()=>I(r)),r!==`/Trash`&&te&&V((0,Z.jsx)(Qr,{className:`h-3 w-3`}),`Empty Trash`,()=>te(r),!0)]}):(0,Z.jsxs)(Dn,{x:e,y:t,onClose:s,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&V((0,Z.jsx)(ja,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&V((0,Z.jsx)(ja,{className:`w-3 h-3`}),`Open to the side`,async()=>{l(r)}),(c||l)&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&g&&V((0,Z.jsx)(aa,{className:`w-3 h-3`}),`Share canvas`,async()=>{await g(r)}),n.type===`canvas`&&g&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),A&&(j?.(r)??!!KF(r,i))&&(0,Z.jsxs)(Z.Fragment,{children:[V((0,Z.jsx)(Er,{className:`w-3 h-3`}),`Refresh backend`,async()=>{await A(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&KF(r,i)&&(M||N)&&(0,Z.jsxs)(Z.Fragment,{children:[M&&V((0,Z.jsx)(_a,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{M(r)}),N&&UF(r,i)&&V((0,Z.jsx)(Fr,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{N(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(N||P)&&r!==`/`&&(0,Z.jsxs)(Z.Fragment,{children:[N&&V((0,Z.jsx)(Fr,{className:`w-3 h-3`}),`Create rule…`,async()=>{N(r)}),N&&V((0,Z.jsx)(zi,{className:`w-3 h-3`}),`Create download rule…`,async()=>{N(r,`download`)}),P&&n.type!==`canvas`&&V((0,Z.jsx)(gr,{className:`w-3 h-3`}),`Storage policy…`,async()=>{P(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||UF(r,i))&&(0,Z.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{p(r),s()},children:[(0,Z.jsx)(br,{className:`w-3 h-3`}),`New folder here`]}),ee&&UF(r,i)?.key&&V((0,Z.jsx)(Za,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await ee(r,t)}),F&&i&&Dc(r,o)&&V((0,Z.jsx)(Qr,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await F(r)},!0),h&&!i&&(0,Z.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{h(r),s()},children:[(0,Z.jsx)(Pa,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&z&&V(ae?(0,Z.jsx)(ur,{className:`w-3 h-3`}):(0,Z.jsx)(tr,{className:`w-3 h-3`}),ae?`Unpin`:`Pin`,async()=>{await z()}),r!==`/`&&m&&(0,Z.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{m(),s()},children:[(0,Z.jsx)(Wr,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&V((0,Z.jsx)(Za,{className:`w-3 h-3`}),`Rename`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New name:`,e);!t||t===e||await v(r,t)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),V((0,Z.jsx)(Jn,{className:`w-3 h-3`}),`Copy`,async()=>L(r)),!i&&V((0,Z.jsx)(Ua,{className:`w-3 h-3`}),`Cut`,async()=>R(r)),f&&!i&&V((0,Z.jsx)(Tr,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>ne(r)),re&&re.length>0&&ie&&WF(r,i)&&V((0,Z.jsx)(Tr,{className:`w-3 h-3`}),i?`Move ${re.length} message(s) here`:`Paste ${re.length} document(s)`,async()=>{await ie(r,re)}),x&&V((0,Z.jsx)(rr,{className:`w-3 h-3`}),`Import documents…`,()=>x(r)),S&&V((0,Z.jsx)(zi,{className:`w-3 h-3`}),`Export documents…`,()=>S(r)),(y||b)&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),y&&n.type!==`canvas`&&V((0,Z.jsx)(zi,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&V((0,Z.jsx)(rr,{className:`w-3 h-3`}),`Import subtree here…`,()=>b(r)),!i&&r!==`/`&&!n.locked&&_&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),V((0,Z.jsx)(Qr,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&V((0,Z.jsx)(Qr,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await _(r,!0)},!0)]}),!i&&(C||w||T)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?w&&V((0,Z.jsx)(ea,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await w(n.id)}):C&&V((0,Z.jsx)(Si,{className:`w-3 h-3`}),`Lock layer`,async()=>{await C(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`px-3 pt-1 pb-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Locked by`}),n.lockedBy.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:e,children:e}),w&&(0,Z.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>ce(async()=>{await w(n.id,e)}),children:(0,Z.jsx)(ea,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&T&&V((0,Z.jsx)(Qr,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await T(n.id)},!0)]}),se&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),O&&V((0,Z.jsx)(fa,{className:`w-3 h-3`}),`Merge down (into ancestors)`,async()=>{confirm(`Merge "${n.label||n.name}" into every layer above it on\n${r}\n\nAfter this, ${r} lists its documents.`)&&await O(r)}),k&&V((0,Z.jsx)(Ca,{className:`w-3 h-3`}),`Subtract from ancestors`,async()=>{confirm(`Remove "${n.label||n.name}"'s documents from every layer above it on\n${r}\n\nUndo of "Merge down". Documents an ancestor holds for other reasons are removed from it too.`)&&await k(r)})]}),oe&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&V((0,Z.jsx)(vi,{className:`w-3 h-3`}),`Merge this layer into ${d.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(d.keys()).join(`
|
|
54
|
+
`)}\n\nThe selected layers gain this layer's documents. This layer is unchanged.`)&&await E(n.id,Array.from(d.values()))}),D&&V((0,Z.jsx)(vi,{className:`w-3 h-3`}),`Subtract this layer from ${d.size} selected`,async()=>{confirm(`Subtract "${r}" (source) FROM:\n${Array.from(d.keys()).join(`
|
|
55
|
+
`)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await D(n.id,Array.from(d.values()))})]}),B&&!oe&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`div`,{className:`px-3 py-1.5 text-[10px] text-muted-foreground italic`,children:[`This is a target. Right-click the source (`,u?.path,`) to merge/subtract`]})]})]})}function JF({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,X.useRef)(null);(0,X.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,Z.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 bg-card ring-1 ring-primary/50 shadow-elevation-3 text-sm font-medium`,children:[(0,Z.jsx)(Xa,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,Z.jsx)(`input`,{ref:r,className:`flex-1 bg-transparent outline-none min-w-0 text-sm font-medium placeholder:font-normal placeholder:text-muted-foreground`,placeholder:n,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),i()),e.key===`Escape`&&t()},onBlur:i})]})}function YF(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function XF(e,t,n){let r=YF(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>XF(e,r,n))??!1}function ZF({expansionState:e,node:t,parentPath:n,depth:r,isLast:i,selectedPath:a,pendingPath:o,contentPath:s,readOnly:c,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:p,inlineCreateParent:m,onSelect:h,onAltSelect:g,selectedPaths:_,onRangeSelect:v,onShowContent:y,onCtrl:b,onCtxMenu:x,onConfirmCreate:S,onCancelCreate:C,onOpenPicker:w,styleOverrides:T,dragOverPath:E,isCopyDrag:D,onDragStart:O,onDragEnter:k,onDragOver:A,onDragLeave:j,onDragEnd:M,onDrop:N,resyncingPaths:P,policyBadgeFor:ee,removingPaths:F,accordion:I=!1,trail:te=[]}){let L=Ke(),R=YF(n,t.name),ne=ee?.(R)??null,re=T.get(R)??Qt(t),[ie,ae]=(0,X.useState)(()=>e?.get(t.id||R)??(a!==`/`&&(a===R||a.startsWith(R+`/`)))),[z,oe]=(0,X.useState)(a);if(z!==a&&(oe(a),a!==`/`&&a.startsWith(R+`/`)&&ae(!0)),(0,X.useEffect)(()=>{e?.set(t.id||R,ie)},[e,t.id,R,ie]),p&&!XF(t,n,p))return null;let se=ie||m===R||p.length>0,B=t.children&&t.children.length>0,ce=a===R||_.has(R),V=o===R,le=l?.path===R,ue=u.has(R),de=t.type===`canvas`,fe=e=>{if(e.shiftKey){v(R,e);return}if(e.ctrlKey||e.metaKey){b(R,t.id);return}if(e.altKey&&g){g(R);return}h(R)},pe=e=>{!B||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button, input, textarea, select, a, [contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),ae(e=>!e))},me=[...te].reverse().find(Boolean)??null,he=re.color||me,ge=I?[...te,he]:te,_e=a!==`/`&&a.startsWith(R+`/`),ve=!le&&!ue,ye=ve&&ce,be=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,xe=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,H=Math.min(r,5),Se=se&&!!B,Ce=ve&&!ye&&!t.locked&&Se,U=Math.min(3+H*2+(_e?4:0)+(V?3:0),18),W=ye?`var(--primary)`:le?be(`var(--info)`,12):ue?be(`var(--warning)`,12):Ce?`var(--accent)`:be(`var(--muted-foreground)`,U),we=ye?`text-primary-foreground`:Ce?`text-accent-foreground`:`text-foreground`,Te=I&&se&&B&&r<HF,Ee=(0,Z.jsxs)(`div`,{"data-tree-path":R,"data-selected":_.has(R)||void 0,"data-active":ce||void 0,className:K(`group relative flex cursor-pointer select-none items-stretch overflow-hidden text-sm`,`after:pointer-events-none after:absolute after:inset-0 after:bg-foreground/0 after:transition-colors hover:after:bg-foreground/[0.07]`,we,le&&`ring-1 ring-inset ring-info/40`,ue&&!le&&`ring-1 ring-inset ring-warning/40`,E===R&&!c&&!D&&`ring-2 ring-inset ring-info`,E===R&&!c&&D&&`ring-2 ring-inset ring-success`),style:{height:VF,background:W,borderBottom:`1px solid var(--border)`,...Te?{position:`sticky`,top:r*VF,zIndex:20-r}:{}},draggable:!c&&!t.metadata?.backendTrash,onClick:fe,onDoubleClick:pe,...c?{}:L,onContextMenu:e=>{c||(e.preventDefault(),x(e,R,t))},onDragStart:e=>{c||O(R,e)},onDragEnter:e=>{c||k(R,e)},onDragOver:e=>{c||A(R,e)},onDragLeave:e=>j(R,e),onDragEnd:()=>M(),onDrop:e=>{c||N(R,e)},children:[te.length>0&&(0,Z.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:te.map((e,t)=>(0,Z.jsx)(`span`,{className:`w-[3px]`,style:{background:e?`color-mix(in oklab, ${e} 35%, var(--border))`:`var(--border)`}},t))}),(()=>{let e=re.color?{background:re.color}:me?{background:`color-mix(in oklab, ${me} 45%, transparent)`}:{background:xe(10)},n=(0,Z.jsx)(f,{icon:re.icon||(de?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:K(`shrink-0`,re.color?tt(re.color):ye?`text-primary-foreground`:Ce?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return w?(0,Z.jsx)(`button`,{type:`button`,className:r,style:e,title:`Change icon`,onClick:e=>{to()||(e.stopPropagation(),w(e,R,t))},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w(e,R,t)},children:n}):(0,Z.jsx)(`span`,{className:r,style:e,children:n})})(),(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 self-center truncate px-2.5`,ce||_e||Se?`font-semibold`:`font-medium`),title:t.description||void 0,children:t.label||t.name}),F.has(R)&&(0,Z.jsx)(Er,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":F.get(R)}),P?.has(R)&&(0,Z.jsx)(Er,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),ne&&(0,Z.jsx)(gr,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":ne,children:(0,Z.jsx)(`title`,{children:ne})}),!c&&(0,Z.jsx)(`button`,{type:`button`,className:`reveal-on-hover shrink-0 self-center rounded p-1 hover:bg-foreground/10`,onClick:e=>{e.stopPropagation(),x(e,R,t)},children:(0,Z.jsx)(ia,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,className:K(`relative z-[1] flex w-12 shrink-0 cursor-pointer items-center justify-center transition-colors`,`bg-[color-mix(in_oklab,currentColor_9%,transparent)] hover:bg-[color-mix(in_oklab,currentColor_24%,transparent)] active:bg-[color-mix(in_oklab,currentColor_32%,transparent)]`,!B&&m!==R&&`invisible`),style:{borderLeft:`1px solid ${xe(16)}`},"aria-label":se?`Collapse`:`Expand`,"aria-expanded":se,title:se?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),ae(e=>!e)},children:se?(0,Z.jsx)(qr,{className:`h-5 w-5`,strokeWidth:2.25}):(0,Z.jsx)(Xa,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,Z.jsxs)(`div`,{className:`relative`,children:[I?Ee:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${BF/2}px`,...i?{height:`1.375rem`}:{bottom:0}}}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${BF/2}px`,width:`${BF/2}px`}}),(0,Z.jsxs)(`div`,{"data-tree-path":R,"data-selected":_.has(R)||void 0,"data-active":ce||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none overflow-hidden`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,le&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,ue&&!le&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!le&&!ue&&ce&&!t.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!le&&!ue&&ce&&t.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!le&&!ue&&!ce&&V&&`bg-primary/[0.03] before:bg-transparent`,!le&&!ue&&!ce&&!V&&!t.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!le&&!ue&&!ce&&t.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,E===R&&!c&&!D&&`ring-2 ring-info bg-info-subtle/50`,E===R&&!c&&D&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:re.color?`4px solid ${re.color}`:`4px solid transparent`},draggable:!c&&!t.metadata?.backendTrash,onClick:fe,onDoubleClick:pe,...c?{}:L,onContextMenu:e=>{c||(e.preventDefault(),x(e,R,t))},onDragStart:e=>{c||O(R,e)},onDragEnter:e=>{c||k(R,e)},onDragOver:e=>{c||A(R,e)},onDragLeave:e=>j(R,e),onDragEnd:()=>M(),onDrop:e=>{c||N(R,e)},children:[(0,Z.jsx)(`button`,{type:`button`,className:K(`shrink-0 text-muted-foreground hover:text-foreground`,!B&&m!==R&&`invisible`),"aria-label":se?`Collapse`:`Expand`,"aria-expanded":se,onClick:e=>{e.stopPropagation(),ae(e=>!e)},children:se?(0,Z.jsx)(qr,{className:`w-4 h-4`}):(0,Z.jsx)(Xa,{className:`w-4 h-4`})}),(()=>{let e=(0,Z.jsx)(f,{icon:re.icon||(de?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:re.color||void 0,className:K(`shrink-0`,!re.color&&(de?`text-primary`:`text-muted-foreground`))});return w?(0,Z.jsx)(`button`,{type:`button`,className:`shrink-0 rounded p-0.5 -m-0.5 hover:bg-muted-foreground/10 touch-target`,title:`Change icon`,onClick:e=>{to()||(e.stopPropagation(),w(e,R,t))},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w(e,R,t)},children:e}):e})(),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:t.description||void 0,children:t.label||t.name}),F.has(R)&&(0,Z.jsx)(Er,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":F.get(R)}),P?.has(R)&&(0,Z.jsx)(Er,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),ne&&(0,Z.jsx)(gr,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":ne,children:(0,Z.jsx)(`title`,{children:ne})}),!c&&(0,Z.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:e=>{e.stopPropagation(),x(e,R,t)},children:(0,Z.jsx)(ia,{className:`w-4 h-4`})})]})]}),se&&(B||m===R)&&(0,Z.jsxs)(`div`,{className:I?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[m===R&&(0,Z.jsx)(JF,{onConfirm:e=>S(R,e),onCancel:C}),t.children?.map((n,i)=>(0,Z.jsx)(ZF,{node:n,expansionState:e,parentPath:R,depth:r+1,isLast:i===(t.children?.length??0)-1,selectedPath:a,pendingPath:o,contentPath:s,readOnly:c,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:p,inlineCreateParent:m,onSelect:h,onAltSelect:g,selectedPaths:_,onRangeSelect:v,onShowContent:y,onCtrl:b,onCtxMenu:x,onConfirmCreate:S,onCancelCreate:C,onOpenPicker:w,styleOverrides:T,dragOverPath:E,isCopyDrag:D,onDragStart:O,onDragEnter:k,onDragOver:A,onDragLeave:j,onDragEnd:M,onDrop:N,resyncingPaths:P,policyBadgeFor:ee,removingPaths:F,accordion:I,trail:ge},n.id||n.name))]})]})}function QF({root:e,expansionState:t,workspaceId:n,treeName:r=`context`,isBackendsTree:i=!1,onRestoreTrash:a,onDiscardTrash:o,selectedPath:s,pendingPath:c,onSelect:l,isLoading:u=!1,readOnly:d=!1,onAddRule:f,onAddStoreRule:p,onStoragePolicy:m,policyBadgeFor:h,rootLabel:g,contentPath:_,onShowContent:v,onOpenToSide:y,onAltSelect:b,onInsertPath:x,onNewCanvas:S,onShareCanvas:C,onRemovePath:w,onRenamePath:T,onMovePath:E,onCopyPath:D,onExportSubtree:O,onImportSubtree:k,onImportDocuments:A,onExportDocuments:j,pastedDocumentIds:M,onPasteDocuments:N,onLockLayer:P,onUnlockLayer:ee,onDestroyLayer:F,onMergeLayer:I,onSubtractLayer:te,onMergeDown:L,onSubtractDown:R,onResyncBackend:ne,canResyncBackend:re,onCreateBackendFolder:ie,onRenameBackendFolder:ae,onDeleteBackendFolder:z,onUpdateNode:oe,isPathPinned:se,onTogglePin:B,searchQuery:ce=``,resyncingPaths:V,backends:le}){let ue=ck(),[fe,pe]=(0,X.useState)(new Set),me=(0,X.useRef)(null),he=e=>{me.current=e,pe(new Set),l(e)},ge=(e,t)=>{t.preventDefault();let n=t.currentTarget.closest(`[data-menu-tree]`)?.querySelectorAll(`[data-tree-path]`),r=Array.from(n||[],e=>e.dataset.treePath),i=me.current||s;pe(RF(r,i,e)),me.current=r.includes(i)?i:e},[_e,ve]=(0,X.useState)(null),[ye,be]=(0,X.useState)(null),[xe,H]=(0,X.useState)(new Map),[Se,Ce]=(0,X.useState)(null),[U,W]=(0,X.useState)(new Map),we=(0,X.useRef)(new Set),Te=(0,X.useCallback)(async(e,t=!1,n=!1,a=!1)=>{if(!(i?z:w)||[...we.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;we.current.add(e);let o=i?`Deleting from backend…`:a?`Removing documents and backend files…`:n?`Removing and purging documents…`:`Removing folder…`;W(t=>new Map(t).set(e,o));try{return i?await z(e):await w(e,r===`directory`||t,n,a)}finally{we.current.delete(e),W(t=>{let n=new Map(t);return n.delete(e),n})}},[w,z,i,r]),[Ee,De]=(0,X.useState)(null),[Oe,ke]=(0,X.useState)(new Map),[Ae,je]=(0,X.useState)(e),Me=(0,X.useRef)(new Map),Ne=(0,X.useRef)(null),[Pe,Fe]=(0,X.useState)(null);if(e!==Ae){je(e);let t=Pe;ke(t?new Map([[t.path,t.style]]):new Map)}let[Ie,Le]=(0,X.useState)(null),[Re,ze]=(0,X.useState)(null),[Be,Ve]=(0,X.useState)(!1),[He,Ue]=(0,X.useState)(!1),[We,Ge]=(0,X.useState)(!1),Ke=(0,X.useRef)(!1),G=(0,X.useRef)(null),qe=(0,X.useRef)(r),Je=(0,X.useRef)(!1),Ye=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=e=>{ve(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,X.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||Ye.current;Je.current=t,Ve(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let Xe=(0,X.useCallback)((e,t,n)=>{if(_t(qe.current,e)||_t(r,t))return!1;if(qe.current!==r)return!0;let i=e.endsWith(`/`)?e.slice(0,-1):e,a=t.endsWith(`/`)?t.slice(0,-1):t,o=i.substring(0,i.lastIndexOf(`/`))||`/`;return!(a.startsWith(i+`/`)||i===a||!n&&a===o)},[r]),Ze=(0,X.useCallback)((e,t)=>{if(_t(r,e)){t.preventDefault();return}G.current=e,qe.current=r,t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:r})),t.dataTransfer.effectAllowed=`copyMove`},[r]),Qe=e=>e.ctrlKey||e.altKey||Ye.current,$e=(0,X.useCallback)((e,t)=>{if(_t(r,e))return;let n=G.current,a=Qe(t);if(a!==Je.current&&(Je.current=a,Ve(a)),n){if(!Xe(n,e,a))return}else if(GF(t)&&!WF(e,i))return;t.preventDefault(),ze(e)},[Xe,r,i]),et=(0,X.useCallback)((e,t)=>{if(_t(r,e)){t.dataTransfer.dropEffect=`none`;return}let n=Qe(t);n!==Je.current&&(Je.current=n,Ve(n));let a=G.current;if(a){if(!Xe(a,e,n)){t.dataTransfer.dropEffect=`none`;return}}else if(GF(t)&&!WF(e,i)){t.dataTransfer.dropEffect=`none`;return}t.preventDefault(),t.dataTransfer.dropEffect=n&&!i?`copy`:`move`},[Xe,r,i]),tt=(0,X.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||ze(t=>t===e?null:t)},[]),nt=(0,X.useCallback)(()=>{G.current=null,qe.current=r,Je.current=!1,Ve(!1),ze(null)},[r]),rt=(0,X.useCallback)(async(e,t)=>{if(t.preventDefault(),t.stopPropagation(),_t(r,e))return;let a=(()=>{try{return JSON.parse(t.dataTransfer.getData(`application/json`))}catch{return null}})();if(a?.type===`document`&&Array.isArray(a.documentIds)&&a.documentIds.length){if(G.current=null,Je.current=!1,Ve(!1),ze(null),de(a,n,r,e))return;if(N&&WF(e,i))try{await N(e,a.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let o=(()=>{try{return JSON.parse(t.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),s=o?.path||t.dataTransfer.getData(`text/plain`),c=o?.treeName||qe.current||r;if(_t(c,s))return;let l=Qe(t)||Je.current;if(G.current=null,qe.current=r,Je.current=!1,Ve(!1),ze(null),!s)return;let u=t.shiftKey,d=c!==r;if(!(!d&&s===e)&&!(!d&&!Xe(s,e,l)))try{if(l&&D)await D(s,e,u,c,r);else if(!l&&E){let t=Ke.current&&!i&&!!L;await E(s,e,u,c,r,t?{mergeDown:t}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[Xe,D,E,N,n,r,i,L]),it=ce.toLowerCase().trim(),ot=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),Ce({x:e.clientX,y:e.clientY,path:t,node:n})},[]),st=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(Ne.current=null,Fe(null),De({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),ct=(0,X.useCallback)(e=>{if(!Ee||!oe)return;let t=Ee.path,n={...Oe.get(t)??(Ne.current?.path===t?Ne.current.style:Qt(Ee.node)),...e};Ne.current={path:t,style:n},Fe({path:t,style:n}),ke(e=>new Map(e).set(t,n));let r=Tt(Ee.node.metadata,n),i=Me.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),oe(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[Ee,oe,Oe]),lt=(0,X.useCallback)((e,t)=>{ye?e===ye.path?(be(null),H(new Map)):H(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(be({path:e,id:t}),H(new Map))},[ye]),ut=(0,X.useCallback)(async e=>{!_e||!E||!D||_e.treeName===r&&(e===_e.path||e.startsWith(_e.path+`/`))||(_e.mode===`cut`?(await E(_e.path,e,!1,_e.treeName,r),ve(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))):await D(_e.path,e,!0,_e.treeName,r))},[_e,E,D,r]);(0,X.useEffect)(()=>{if(d)return;let e=e=>{let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),_e?.mode===`cut`){ut(s);return}let n={mode:`cut`,path:s,treeName:r};ve(n),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:n}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[_e,ut,d,s,r]);let dt=(0,X.useCallback)(async(e,t)=>{Le(null);let n=e===`/`?`/${t}`:`${e}/${t}`;try{UF(e,i)&&ie?await ie(e,t)&&l(n):x&&await x(n,!0)&&l(n)}catch(e){alert(e instanceof Error?e.message:String(e))}},[x,ie,l,i]),ft=(0,X.useCallback)(()=>{Le(null)},[]),pt=(0,X.useCallback)((e,t)=>{let n={mode:t,path:e,treeName:r};ve(n),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:n}))},[r]),mt=(0,X.useCallback)(t=>{if(d||An(t.target)||s&&_t(r,s))return;if(at(t,`Mod+V`)){M?.length&&N&&s&&WF(s,i)?(t.preventDefault(),N(s,M).catch(()=>{})):_e&&s&&(t.preventDefault(),ut(s).catch(e=>alert(e instanceof Error?e.message:String(e))));return}if(s&&s!==`/`&&(at(t,`Mod+C`)||!i&&at(t,`Mod+X`))){t.preventDefault(),pt(s,t.key.toLowerCase()===`x`?`cut`:`copy`);return}if((i?!z||!Dc(s||``,le):!w)||t.key!==`Delete`&&t.key!==`Backspace`||!s||s===`/`)return;t.preventDefault();let n=xs(e,s);if(!i&&n?.locked){alert(`"${s}" is locked`);return}confirm(i?`Delete "${s}" and its contents from this backend?`:`Remove "${s}"${r===`directory`?` and all children`:``}?`)&&Te(s,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))},[d,w,z,Te,s,e,M,N,_e,ut,i,pt,r,le]),ht=(0,X.useCallback)(()=>{Ue(e=>{let t=!e;return Ye.current=t,Je.current=t,Ve(t),t})},[]);if(u)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let gt=ye||xe.size>0,vt={expansionState:t,accordion:ue,selectedPath:s,pendingPath:c,contentPath:_,readOnly:d,sourceLayer:ye,targetLayers:xe,clipboard:_e,searchQuery:it,inlineCreateParent:Ie,onSelect:he,onAltSelect:b,selectedPaths:fe,onRangeSelect:ge,onShowContent:v,onCtrl:lt,onCtxMenu:ot,onConfirmCreate:dt,onCancelCreate:ft,onOpenPicker:oe?st:void 0,styleOverrides:Oe,dragOverPath:Re,isCopyDrag:Be,onDragStart:Ze,onDragEnter:$e,onDragOver:et,onDragLeave:tt,onDragEnd:nt,onDrop:rt,resyncingPaths:V,backends:le,policyBadgeFor:i?void 0:h,removingPaths:U};return(0,Z.jsxs)(`div`,{"data-menu-tree":!0,className:`px-3 py-2 space-y-1.5 outline-none min-h-full`,tabIndex:0,onKeyDown:mt,onContextMenu:t=>{t.defaultPrevented||d||(t.preventDefault(),ot(t,`/`,e))},children:[U.size>0&&(0,Z.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-1 rounded-md border bg-muted/50 p-2 text-xs`,children:[...U].map(([e,t])=>(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(Er,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block`,children:t}),(0,Z.jsx)(`span`,{className:`block truncate text-muted-foreground`,title:e,children:e})]})]},e))}),!d&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:ht,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:K(`px-2 py-0.5 rounded-full border transition-colors select-none`,He?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:He?`Drag → Copy`:`Drag → Move`}),L&&!i&&!He&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>Ge(e=>(Ke.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:K(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,We?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:We?`+ merge down`:`merge down: off`})]}),gt&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:ye?`Source: ${ye.path} · ${xe.size} target(s)`:`Select source with ⌃-click`}),(0,Z.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{be(null),H(new Map)},children:`clear`})]}),(0,Z.jsxs)(`div`,{"data-active":s===`/`&&!_||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,s===`/`&&!_?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,Re===`/`&&!d&&!Be&&`ring-2 ring-info bg-info-subtle/50`,Re===`/`&&!d&&Be&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>he(`/`),onDragEnter:e=>{d||$e(`/`,e)},onDragOver:e=>{d||et(`/`,e)},onDragLeave:e=>tt(`/`,e),onDrop:e=>{d||rt(`/`,e)},onContextMenu:e=>{!d&&x&&(e.preventDefault(),Ce({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,Z.jsx)(qr,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,g&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,g,`]`]})]}),!d&&x&&(0,Z.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:e=>{e.stopPropagation(),Ce({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,Z.jsx)(ia,{className:`w-4 h-4`})})]}),(0,Z.jsxs)(`div`,{className:ue?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[Ie===`/`&&(0,Z.jsx)(JF,{onConfirm:e=>dt(`/`,e),onCancel:ft}),e.children?.map((t,n)=>(0,Z.jsx)(ZF,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...vt},t.id||t.name)),!e.children?.length&&Ie!==`/`&&(0,Z.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),Se&&fe.size>1&&fe.has(Se.path)?(0,Z.jsxs)(Dn,{x:Se.x,y:Se.y,onClose:()=>Ce(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[(0,Z.jsxs)(`div`,{className:`px-3 py-1.5 text-xs text-muted-foreground`,children:[fe.size,` folders selected`]}),(0,Z.jsx)(`button`,{type:`button`,className:`block w-full px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{navigator.clipboard?.writeText([...fe].join(`
|
|
56
|
+
`)),Ce(null)},children:`Copy paths`}),!d&&!i&&w&&(0,Z.jsx)(`button`,{type:`button`,className:`block w-full px-3 py-1.5 text-left text-xs text-destructive hover:bg-accent`,onClick:()=>{Ce(null);let e=zF(fe);confirm(`Remove ${fe.size} selected folders and their children?\n${e.join(`
|
|
57
|
+
`)}`)&&(async()=>{for(let t of e)await Te(t,!0);pe(new Set)})().catch(e=>alert(e instanceof Error?e.message:String(e)))},children:`Remove folders…`}),(0,Z.jsx)(`button`,{type:`button`,className:`block w-full px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{pe(new Set),Ce(null)},children:`Clear selection`})]}):Se&&(0,Z.jsx)(qF,{x:Se.x,y:Se.y,node:Se.node,path:Se.path,isBackendsTree:i,backends:le,isDirectoryTree:r===`directory`,onClose:()=>Ce(null),onShowContent:Se.node.metadata?.backendTrash?l:v,onRestoreTrash:d?void 0:a,onDiscardTrash:d?void 0:o,onOpenToSide:y?e=>y(e,r):void 0,sourceLayer:ye,targetLayers:xe,clipboard:_e,onStartInlineCreate:e=>Le(e),onChangeIcon:oe?()=>st({clientX:Se.x,clientY:Se.y,stopPropagation:()=>{}},Se.path,Se.node):void 0,onNewCanvas:S,onShareCanvas:C,onImportDocuments:d?void 0:A,onExportDocuments:j,onExportSubtree:O,onImportSubtree:d?void 0:k,onRemove:!d&&w&&![...U.keys()].some(e=>e===Se.path||e.startsWith(Se.path+`/`)||Se.path.startsWith(e+`/`))?Te:void 0,onRename:d?void 0:T,onLock:d?void 0:P,onUnlock:d?void 0:ee,onDestroy:d?void 0:F,onMerge:d?void 0:I,onSubtract:d?void 0:te,onMergeDown:d?void 0:L,onSubtractDown:d?void 0:R,canResyncBackend:re,onResyncBackend:ne,onAddRule:f,onAddStoreRule:p,onStoragePolicy:!d&&!i?m:void 0,onRenameBackendFolder:ae,onDeleteBackendFolder:!d&&z&&![...U.keys()].some(e=>e===Se.path||e.startsWith(Se.path+`/`)||Se.path.startsWith(e+`/`))?e=>Te(e,!0):void 0,onCopy:e=>pt(e,`copy`),onCut:e=>pt(e,`cut`),onPaste:ut,pastedDocumentIds:M,onPasteDocuments:N,isPinned:se?se(Se.path):!1,onTogglePin:B?()=>B(Se.path,Se.node):void 0}),Ee&&oe&&(0,Z.jsx)(dw,{x:Ee.x,y:Ee.y,current:Oe.get(Ee.path)??Qt(Ee.node),onChange:ct,onClose:()=>De(null)})]})}function $F(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=qC(),a=De(),o=ft(),s=e.selectedEntityId,{showToast:c}=wo(),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(`/`),[x,S]=(0,X.useState)(null),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(!1),A=(0,X.useCallback)(async e=>{T(!0);try{let t=await yl(e);f(t),D(null)}catch(e){D(e instanceof Error?e.message:`Failed to load the tree`)}finally{T(!1)}},[]);(0,X.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await Tl(e);if(t)return;u(n),m(n.url||``),g(void 0),v(``),S(null),b(n.path||`/`),T(!0);try{let n=await yl(e);t||(f(n),D(null))}catch(e){t||D(e instanceof Error?e.message:`Failed to load the tree`)}finally{t||T(!1)}}catch{t||c({title:`Error`,description:`Failed to load context`,variant:`destructive`})}}n();let r=t=>{t.detail?.contextId===e&&n()};return window.addEventListener(`contexts:refresh`,r),()=>{t=!0,window.removeEventListener(`contexts:refresh`,r)}},[s,c]);let j=Ut({contextId:s??void 0,onRefresh:()=>{s&&A(s)}}),M=e=>{g(void 0),S(e),m(l?.workspaceName?`${l.workspaceName}://${e.replace(/^\//,``)}`:e)},N=l!=null&&(p.trim()!==(l.url||``)||h!==void 0);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(LF,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s&&(a?i(`settings`,s):o(`/contexts/${s}/settings/general`))},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Settings`,children:(0,Z.jsx)(Wi,{className:`w-3.5 h-3.5`})})}),(0,Z.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(C,{presentation:`breadcrumbs`,value:p,fixedWorkspaceName:l?.workspaceName,pickerTitle:`Switch context to…`,onPickTarget:(e,t)=>{m(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),g(t.treeName),S(null)},onChange:e=>{m(e),S(h?null:`/`+e.replace(/^.*?:\/\//,``).replace(/^\/+/,``))},disabled:O,className:`min-w-0 flex-1`,inputClassName:K(`text-xs transition-colors`,N&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,Z.jsx)(Y,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;k(!0);try{await sl(e,p,void 0,h);let t=await Tl(e);u(t),m(t.url||``),b(t.path||`/`),S(null),g(void 0),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),await A(e),c({title:`Saved`,description:`Context URL updated`}),window.matchMedia(`(max-width: 767px)`).matches&&(n(),r())}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{k(!1)}},disabled:O||!N,children:O?`…`:`Set`})]})]}),h&&(0,Z.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,h,` · press Set to apply`]}),(0,Z.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,Z.jsx)(q,{type:`search`,name:`context-tree-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search context tree`,placeholder:`Search paths…`,value:_,onChange:e=>v(e.target.value),className:`h-7 text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,Z.jsxs)(`div`,{className:`text-[10px] text-muted-foreground px-3 pt-2 pb-1 font-medium uppercase tracking-wide shrink-0`,children:[l?.workspaceName||`Workspace`,` · `,d?.type===`directory`?`directory`:`context`,` tree`]}),E&&!d&&(0,Z.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:E}),(0,Z.jsx)(QF,{root:d,workspaceId:l?.workspaceName,searchQuery:_,selectedPath:y,pendingPath:x,onSelect:M,isLoading:w,rootLabel:l?.workspaceName,...j})]})]})}function eI({items:e,activeId:t,onSelect:n}){let[r,i]=(0,X.useState)(``),a=e.filter(e=>wC(r,e.label,e.description||``));return(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,Z.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,Z.jsx)(q,{type:`search`,name:`settings-section-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,Z.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching settings.`}),a.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:K(`flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left transition-colors`,r?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,Z.jsx)(`span`,{className:K(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,Z.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,Z.jsx)(Xa,{className:K(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}function tI(){let{state:e,closeM2:t}=qC(),n=De(),r=ft(),i=vn(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return Tl(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?ND(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,X.useMemo)(()=>MD.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(LF,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u&&r(u),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open context`,children:(0,Z.jsx)(Pi,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(eI,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function nI(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Uo();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>B.emit(`subscribe`,{channel:`workspace`}),r=()=>B.emit(`unsubscribe`,{channel:`workspace`}),i=B.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e,r=t?.workspaceId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},o=e=>{let t=e?.workspace??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},c=e=>{let t=e,r=t?.workspaceId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=[[`workspaces.scanned`,e=>{let t=e?.report;t&&(t.discovered.length||t.adopted.length||t.updated.length||t.missing.length)&&s()}],[`workspace:status:changed`,a],[`workspace.status.changed`,a],[`workspace:created`,o],[`workspace.created`,o],[`workspace:deleted`,c],[`workspace.deleted`,c]];return l.forEach(([e,t])=>B.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>B.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,X.useMemo)(()=>Pw(t),[t]),isLoading:r,refresh:c}}function rI({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function iI(){let[e,t]=(0,X.useState)(null),n=aw(),{state:r,selectEntity:i,openM2:a,closeM2:o}=qC(),s=De(),{workspaces:c,isLoading:l}=nI(r.activeSection===`workspaces`),{showToast:u}=wo(),d=ft(),[p,m]=(0,X.useState)(new Set),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(new Map),y=(0,X.useRef)(new Map),[b,x]=(0,X.useState)(null),S=b&&b.base===c?b.order:c,{rowProps:C,handleProps:w,draggingIndex:T,insertLineClass:E}=Lw((e,t)=>{let n=Fw(S,e,t);x({base:c,order:n}),Iw(n,(e,t)=>Pc(ow(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&u({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),D=e=>_.get(ow(e))??{icon:e.icon??void 0,color:e.color??void 0},O=(e,t,n)=>{let r={...t,...n};v(t=>new Map(t).set(e,r));let i=y.current,a=i.get(e);a&&clearTimeout(a),i.set(e,setTimeout(()=>{i.delete(e);let t={icon:r.icon??null};r.color&&(t.color=r.color),Pc(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>u({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},k=e=>{i(ow(e)),a(`detail`,ow(e)),!s&&xw(ow(e))&&d(Sw(ow(e)))},A=async(e,t)=>{e.stopPropagation(),m(e=>new Set(e).add(ow(t)));try{await Ks(ow(t)),u({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){u({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{m(e=>{let n=new Set(e);return n.delete(ow(t)),n})}},j=async(e,t)=>{e.stopPropagation(),m(e=>new Set(e).add(ow(t)));try{await hc(ow(t)),u({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){u({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{m(e=>{let n=new Set(e);return n.delete(ow(t)),n})}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,onContextMenu:e=>{e.defaultPrevented||n.local||e.target.closest(`[data-workspace-row]`)||(e.preventDefault(),t({x:e.clientX,y:e.clientY}))},children:[e&&(0,Z.jsx)(Dn,{...e,onClose:()=>t(null),className:`rounded-md border bg-popover p-1 shadow-elevation-3`,children:(0,Z.jsx)(`button`,{type:`button`,className:`px-3 py-1.5 text-xs hover:bg-accent`,onClick:()=>{t(null),o(),d(`/workspaces?create=1`)},children:`Create workspace…`})}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,Z.jsx)(XC,{}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`})]}),!n.local&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{o(),d(`/workspaces?create=1`)},title:`Create workspace`,"aria-label":`Create workspace`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Z.jsx)(br,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:l&&c.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):c.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:S.map((e,t)=>{let n=r.selectedEntityId===ow(e),o=se(e),c=p.has(ow(e)),l=e.status!==`active`,u=D(e),m=Jt(u.color);return(0,Z.jsxs)(`div`,{"data-workspace-row":!0,...C(t),"data-active":n||void 0,className:K(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,n?`bg-accent shadow cursor-pointer hover:shadow`:l?`bg-card opacity-60 cursor-not-allowed`:`bg-card hover:bg-accent/50 cursor-pointer hover:shadow`,E(t,S.length),T===t&&`opacity-60`),onClick:()=>{l||k(e)},children:[(0,Z.jsx)(`button`,{type:`button`,...w(t),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:K(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!m&&`bg-muted`),style:m?{backgroundColor:m}:void 0,children:(0,Z.jsx)(Un,{className:K(`h-3.5 w-3.5`,tt(m))})}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:o?`Change icon`:`Workspace appearance requires admin access`,onClick:t=>{!o||to()||(t.stopPropagation(),g({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:ow(e)}))},onContextMenu:t=>{o&&(t.preventDefault(),t.stopPropagation(),g({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:ow(e)}))},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,Z.jsx)(f,{icon:u.icon||`ph:stack-fill`,width:18,height:18,color:m,className:K(!m&&`text-muted-foreground`)})}),(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(rI,{status:e.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:c,onClick:t=>j(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,Z.jsx)(Sa,{className:`w-3.5 h-3.5`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:c,onClick:t=>A(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,Z.jsx)(Ar,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),i(ow(e)),s?a(`settings`,ow(e)):d(`/workspaces/${ow(e)}/settings/general`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,disabled:!o,title:o?`Settings`:`Workspace settings require admin access`,children:(0,Z.jsx)(Wi,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),h&&(()=>{let e=c.find(e=>ow(e)===h.name);if(!e)return null;let t=D(e);return(0,Z.jsx)(dw,{x:h.x,y:h.y,current:t,onChange:e=>O(h.name,t,e),onClose:()=>g(null)})})()]})}function aI(e,t){let n=(0,X.useRef)(null),r=(0,X.useRef)(0);return(0,X.useEffect)(()=>{if(!e)return;let n=e=>{if(e.defaultPrevented||e.repeat||e.isComposing||e.getModifierState(`AltGraph`))return;let n=e.target;if(n instanceof Element&&n.closest(`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="dialog"], [role="alertdialog"]`)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let r=Jk(e);if(!r)return;let i=Kk(),a=r===i.previousTree?-1:+(r===i.nextTree);a&&(e.preventDefault(),t(a))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),{onTouchStart(e){r.current=0,n.current=e.touches.length===1?{x:e.touches[0].clientX,y:e.touches[0].clientY}:null},onTouchMove(e){e.touches.length!==1&&(n.current=null)},onTouchCancel(){n.current=null},onTouchEnd(i){if(!n.current||!e)return;let a=i.changedTouches[0],o=Xk(a.clientX-n.current.x,a.clientY-n.current.y);n.current=null,o&&(r.current=Date.now()+500,i.stopPropagation(),t(o))},onClickCapture(e){Date.now()<r.current&&(e.preventDefault(),e.stopPropagation(),r.current=0)}}}function oI(e,t,n,r=!1){if(!t.startsWith(`/`)||!n.length)throw Error(`Choose a source folder and at least one destination.`);let i=new Map;for(let e of n){if(![`context`,`directory`].includes(e.tree)||!e.path.startsWith(`/`))throw Error(`Choose a context or directory destination.`);if(e.path.includes(`{{`))throw Error(`Auto-Link destinations cannot contain {{ template markers.`);i.set(`${e.tree}:${e.path}`,e)}return{id:e,enabled:!0,description:`Auto-Link backends:${t} → ${[...i.keys()].join(`, `)}`,cascade:!0,when:{event:[`document.inserted`,`document.updated`,`document.linked`],...r?{path:`backends:${t}`}:{pathExact:`backends:${t}`}},then:[...i.values()].map(e=>({action:`link`,paths:[`${e.tree===`context`?`ctx`:`dir`}:${e.path}`],...r?{recursive:!0}:{}}))}}function sI(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=oI(e,t,n,r);if(i===`forward`)return[c];if(a===`move`&&!s?.trim())throw Error(`Choose the source backend whose copy should be moved.`);if(r&&n.some(e=>e.tree===`context`))throw Error(`Recursive storage requires a directory source. Context paths can store files in a fixed backend folder.`);let l=t.split(`/`).filter(Boolean);if(l.length<2||t.includes(`{{`)||l.some(e=>e===`.`||e===`..`))throw Error(`Choose a backend folder with a valid storage address.`);if(!o)throw Error(`Choose a writable backend folder.`);let u=o.address,d=o.key,f=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],p={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${f.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:f.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:u,folder:d,mode:a,...a===`move`?{from:s.trim()}:{},autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[c,p]:[p]}function cI(e,t){let n=nl(e,t);if(t.find(e=>e.driver===n.driver&&e.address===n.address)?.capabilities.paths!==!0)throw Error(`This backend has not reported support for folder paths. Choose a writable storage folder to copy or move files here.`);return n}function lI({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(`forward`),u=c===`forward`||!i.some(e=>e.tree===`context`),[d,f]=(0,X.useState)(`copy`),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(!0),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!0),[w]=(0,X.useState)(()=>`autolink-${crypto.randomUUID()}`),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(``),{showToast:k,showProgress:A}=wo(),j=()=>{T||n()},M=_?`Checking whether this backend can receive files…`:``;if(!_)try{cI(t,h)}catch(e){M=e instanceof Error?e.message:`Choose a writable storage folder.`}let N=e=>{l(e),e!==`forward`&&(C(!1),i.some(e=>e.tree===`context`)&&x(!1))},P=e=>`${e.replace(/\/+$/,``)}/${b?`Subfolder/`:``}example.pdf`;return(0,X.useEffect)(()=>{let t=!1;return Rc(e).then(e=>{t||g(e)}).catch(()=>{t||O(`Could not load storage backends. Reopen Autolink to retry.`)}).finally(()=>{t||v(!1)}),()=>{t=!0}},[e]),(0,Z.jsx)(tn,{label:o?`Choose virtual paths`:`Autolink documents`,onClose:o?()=>s(!1):j,children:o?(0,Z.jsx)(y,{fixedWorkspaceName:e,tabs:c!==`forward`&&b?[`directory`]:[`context`,`directory`],initialTab:c===`forward`?void 0:`directory`,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-full rounded-none border-0 shadow-none`,onClose:()=>s(!1),onConfirm:(e,t)=>{c!==`forward`&&t.treeType===`context`&&x(!1),a(n=>{let r=[...n];for(let n of e)r.some(e=>e.tree===t.treeType&&e.path===n)||r.push({tree:t.treeType,path:n});return r}),s(!1)}}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b p-5`,children:[(0,Z.jsxs)(`h2`,{className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,Z.jsx)(Ri,{className:`h-5 w-5`}),`Autolink documents`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:j,disabled:T,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-5`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current backend folder`}),(0,Z.jsxs)(`p`,{className:`mt-1 break-words text-sm`,children:[`backends:`,t]})]}),(0,Z.jsxs)(`fieldset`,{disabled:T,className:`space-y-2 text-sm`,children:[(0,Z.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,Z.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>N(e.target.value),children:[(0,Z.jsx)(`option`,{value:`forward`,children:`Backend → virtual folders (link)`}),(0,Z.jsx)(`option`,{value:`reverse`,disabled:!!M,children:`Virtual folders → backend (Copy/Move)`}),(0,Z.jsx)(`option`,{value:`both`,disabled:!!M,children:`Both directions`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link documents from this backend folder into the selected virtual folders. Files stay where they are.`:`When a document is added or explicitly linked to a selected virtual folder, ${d} its file to the current backend folder.${c===`both`?` Documents arriving on the backend are also linked into the virtual folders.`:``}`}),M&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:_?M:`Reverse mapping unavailable: ${M}`}),c!==`forward`&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-lg border p-3`,children:[(0,Z.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-operation`,children:`File operation`}),(0,Z.jsxs)(`select`,{id:`autolink-operation`,className:`w-full rounded-md border bg-background p-2`,value:d,onChange:e=>f(e.target.value),children:[(0,Z.jsx)(`option`,{value:`copy`,children:`Copy files to this backend`}),(0,Z.jsx)(`option`,{value:`move`,children:`Move files to this backend`})]}),d===`copy`&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Keep the source file and its virtual-folder links.`}),d===`move`&&(0,Z.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,Z.jsx)(`label`,{className:`block`,htmlFor:`autolink-source-backend`,children:`Move files from`}),(0,Z.jsxs)(`select`,{id:`autolink-source-backend`,className:`w-full rounded-md border bg-background p-2`,value:p,onChange:e=>m(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:`Choose a source backend…`}),h.filter(e=>e.kind===`storage`&&e.enabled&&e.config?.readOnly!==!0).map(e=>(0,Z.jsx)(`option`,{value:e.address,children:e.address},e.address))]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Move the file from this source backend after it has been stored at the destination. Virtual-folder links stay in place. Files missing from this source are skipped; multiple source copies require Copy instead.`})]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:c===`reverse`?`Watch virtual folders`:`Virtual folders`}),i.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,Z.jsx)(`p`,{className:`break-words`,children:e.path})]}),(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:T,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:T,onClick:()=>s(!0),children:[(0,Z.jsx)(br,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Choose the virtual folders where backend documents should appear.`:`Choose a Directory tree folder to watch for newly added documents. Its files will be stored in the current backend folder.`})]}),(0,Z.jsxs)(`fieldset`,{disabled:T,className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:b,disabled:!u,onChange:e=>x(e.target.checked),className:`mt-1`}),`Include subfolders and recreate their path in the destination`]}),!u&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Context membership has no single folder path. To preserve subfolders on a backend, choose a directory source. Context paths store files directly in the selected backend folder.`}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>C(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),!!i.length&&(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`Mapping preview`,children:[(0,Z.jsx)(`h3`,{className:`font-medium`,children:`Example result`}),i.map(e=>(0,Z.jsxs)(`div`,{className:`space-y-2 break-all text-xs`,children:[c!==`reverse`&&(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Link `}),`backends:`,P(t),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Into `}),e.tree===`context`?`ctx`:`dir`,`:`,P(e.path)]}),c!==`forward`&&(0,Z.jsxs)(`p`,{children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[d===`move`?`Move`:`Copy`,` `]}),e.tree===`context`?`ctx`:`dir`,`:`,P(e.path),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`To `}),`backends:`,P(t)]})]},`preview:${e.tree}:${e.path}`)),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:b?`The selected folders are the roots. Only the subfolder path beneath each root is recreated at its destination.`:`Only direct folder contents are included.`})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[S?`Existing matching documents are processed in the background on the server once enabled.`:c===`forward`?`Future backend arrivals and updates are linked automatically.`:`Newly added or explicitly linked virtual-folder documents are processed automatically.`,` `,c===`both`&&`Both directions creates two rules in workspace Rules. `,`Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`]}),D&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:D})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Z.jsx)(Y,{variant:`ghost`,disabled:T,onClick:r,children:`Manage rules`}),(0,Z.jsx)(Y,{disabled:T||!i.length||c!==`forward`&&(!!M||d===`move`&&!p),onClick:async()=>{if(!T){E(!0),O(``);try{let r=c===`forward`?void 0:cI(t,await Rc(e)),a=sI(w,t,i,b,c,d,r,p);await Je(e,a),S?V(A,e,a.map(e=>e.id)):k({title:`Autolink enabled`,description:`Future documents are linked automatically.`}),n()}catch(e){O(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{E(!1)}}},children:T?`Saving…`:`Enable Autolink`})]})]})})}async function uI(){return await J.get(`${yo}/users/me/config/webui`)??{}}async function dI(e){return await J.put(`${yo}/users/me/config/webui`,e)??e}var fI=`application/x-canvas-workspace-pin`;function pI({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:i,onShowInTree:a,onUnpin:o,onMove:s}){let[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),p=n.toLowerCase().trim(),m=p?e.filter(e=>(e.label||e.name||``).toLowerCase().includes(p)||e.path.toLowerCase().includes(p)||(e.description||``).toLowerCase().includes(p)):e,h=()=>{l(null),d(null)},g=async()=>{let t=u,n=c;if(h(),!n||!t||t.id===n)return;let r=t.id;if(t.id&&!t.before&&(r=e[e.findIndex(e=>e.id===t.id)+1]?.id??null),r!==n)try{await s(n,r)}catch(e){alert(e instanceof Error?e.message:String(e))}};return t&&!e.length?(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,Z.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{c&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),c&&!u&&d({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=Jt(e.color),s=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===ss(e.tree,e.path),_=u?.id===e.id&&u.before,v=u?.id===e.id&&!u.before;return(0,Z.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(fI,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,l(e.id)},onDragEnd:h,onDragOver:t=>{if(!c||c===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;d(t=>t?.id===e.id&&t.before===r?t:{id:e.id,before:r})},onDrop:e=>{e.preventDefault(),e.stopPropagation(),g()},onClick:()=>{t||i(e)},onKeyDown:n=>{n.target===n.currentTarget&&(n.key===`Enter`||n.key===` `)&&!t&&(n.preventDefault(),i(e))},title:t?`${e.path} — folder no longer exists`:`Open ${e.tree}:${e.path}`,className:K(`group relative flex items-stretch gap-2.5 rounded-(--card-radius) border bg-card shadow-elevation-1 text-left transition-colors`,t?`opacity-70 cursor-default`:`cursor-pointer hover:bg-accent/40`,m&&`ring-1 ring-primary/60`,c===e.id&&`opacity-40`,_&&`border-t-2 border-t-primary`,v&&`border-b-2 border-b-primary`),style:{borderLeft:`5px solid ${n??`transparent`}`},children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-center w-12 shrink-0 rounded-l-[5px] my-0 self-stretch`,style:n?{backgroundColor:`${n}22`}:void 0,children:t?(0,Z.jsx)(dr,{className:`w-5 h-5 text-warning`}):(0,Z.jsx)(f,{icon:s,width:22,height:22,color:n,className:K(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,Z.jsx)(Si,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,Z.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,disabled:t,onClick:t=>{t.stopPropagation(),a(e)},title:`Show in tree`,"aria-label":`Show in tree`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover focus-visible:opacity-100 hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-default`,children:(0,Z.jsx)(rr,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await o(e)}catch(e){alert(e instanceof Error?e.message:String(e))}},title:`Unpin`,"aria-label":`Unpin`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Z.jsx)(ur,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Z.jsx)(Un,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,Z.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,Z.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,Z.jsx)(`p`,{children:`No pinned folders yet.`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,Z.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var mI=()=>({selectedPath:`/`,contentPath:null,searchQuery:``,expansion:new Map}),hI=[`pins`,`context`,`layers`,`directory`,`backends`],gI=e=>typeof e==`string`&&hI.includes(e),_I=e=>{let t=Array.isArray(e)?e.filter(gI).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...hI.filter(e=>!t.includes(e))]},vI={pins:(0,Z.jsx)(tr,{className:`w-3.5 h-3.5`}),context:(0,Z.jsx)(or,{className:`w-3.5 h-3.5`}),layers:(0,Z.jsx)(vi,{className:`w-3.5 h-3.5`}),directory:(0,Z.jsx)(rr,{className:`w-3.5 h-3.5`}),backends:(0,Z.jsx)(Fa,{className:`w-3.5 h-3.5`})},yI={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},bI=e=>e===`directory`||e===`backends`?e:Tc,xI=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function SI(){let{state:e}=qC();return e.selectedEntityId?(0,Z.jsx)(eT,{workspaceName:e.selectedEntityId,children:(0,Z.jsx)(CI,{},e.selectedEntityId)}):null}function CI(){let{state:e,closeM2:t,openM2:n,navigateFromMenu:r}=qC(),i=Nt(),a=De(),o=e.selectedEntityId,s=ft(),c=vn(),{treeName:l,path:u}=af(c.pathname),d=new URLSearchParams(c.search).get(`layer`)===`1`,f=new URLSearchParams(c.search).get(`layerId`),p=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!f,m=p?xI(l,f):hI[0],[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)({icon:null,color:null}),[C,w]=(0,X.useState)(m),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)([]),[N,P]=(0,X.useState)(!1),[ee,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(!1),[R,ne]=(0,X.useState)(!1),[re,ie]=(0,X.useState)(u),[ae,z]=(0,X.useState)([]),[oe,ce]=(0,X.useState)(new Set),[V,le]=(0,X.useState)(d&&u!==`/`?u:null),[ue,de]=(0,X.useState)(``),[fe,pe]=(0,X.useState)(null),[me,he]=(0,X.useState)(null),[ge,_e]=(0,X.useState)(null),{policies:ve,refresh:ye}=QN(o),be=(0,X.useCallback)(e=>{if(C!==`context`&&C!==`directory`||!ve.length)return null;let t=RN(ve,C,e);return t.length?`Storage policy targets: ${zN(t)} (see Settings for transfer status)`:null},[C,ve]),[xe,H]=(0,X.useState)([]),[Se,Ce]=(0,X.useState)(!1),[U,W]=(0,X.useState)(!1),we=(0,X.useRef)(null),Te=(0,X.useRef)(new Map),[Ee,Oe]=(0,X.useState)(()=>Object.fromEntries(hI.map(e=>[e,mI()])));(0,X.useLayoutEffect)(()=>{we.current&&(we.current.scrollTop=Te.current.get(C)??0)},[C]);let ke=Ee[C];(ke.selectedPath!==re||ke.contentPath!==V||ke.searchQuery!==ue)&&Oe({...Ee,[C]:{...ke,selectedPath:re,contentPath:V,searchQuery:ue}});let Ae=(0,X.useRef)(!1),[je,Me]=(0,X.useState)(!1),[Ne,Pe]=(0,X.useState)(hI),Fe=!p;(0,X.useEffect)(()=>{let e=!1;return uI().then(t=>{if(e)return;let n=_I(t?.m2?.tabOrder);Pe(n),Fe&&w(e=>e===hI[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Ie=(0,X.useCallback)(async e=>{let t=Ne;Pe(e);try{let t=await uI();await dI({...t,m2:{...t.m2,tabOrder:e}})}catch{Pe(t)}},[Ne]),[Le,Re]=(0,X.useState)(null),[ze,Be]=(0,X.useState)(null),Ve=()=>{Re(null),Be(null)},He=()=>{if(Le&&ze&&Le!==ze.id){let e=Ne.filter(e=>e!==Le),t=e.indexOf(ze.id);t>=0&&(e.splice(ze.before?t:t+1,0,Le),e.some((e,t)=>e!==Ne[t])&&Ie(e))}Ve()};(0,X.useEffect)(()=>{let e=e=>pe(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[Ue,We]=(0,X.useState)(u);u!==Ue&&(We(u),ie(u));let Ge=(0,X.useRef)(new Map),Ke=(0,X.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();Ge.current.set(t,i);let a=()=>Ge.current.get(t)===i,o=t===`context`?P:t===`directory`?F:L,s=t===`context`?E:t===`directory`?O:A;n||o(!0);try{n&&!r&&Ms(e,t);let i=await _c(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),G=(0,X.useCallback)(async(e,t=!1)=>{let n=Symbol();Ge.current.set(`pins`,n);let r=()=>Ge.current.get(`pins`)===n;t||Ce(!0);try{let t=await rc(e);r()&&H(t)}catch{}finally{r()&&Ce(!1)}},[]),qe=(0,X.useCallback)(async(e,t=!1)=>{let n=Symbol();Ge.current.set(`layers`,n);let r=()=>Ge.current.get(`layers`)===n;t||ne(!0);try{let t=await zo(e,`context`);r()&&M(t)}catch{}finally{r()&&ne(!1)}},[]);(0,X.useEffect)(()=>{if(!o)return;let e=o,t=!1,n=Ge.current;async function r(){Ws(e).then(e=>{t||(v(e.label||e.name),g(se(e)),b(e.id||null),S({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Ke(e,`context`),Ke(e,`directory`),Ke(e,`backends`),qe(e),G(e)])}return r(),()=>{t=!0,n.clear()}},[o,Ke,qe,G]);let Je=(0,X.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Ke(e,r,!0,n);(!t||t===`context`)&&qe(e,!0),G(e,!0)},[Ke,qe,G]),Ye=(0,X.useCallback)(()=>{o&&Je(o)},[o,Je]);(0,X.useEffect)(()=>{if(!o)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==o||Je(o,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[o,Je]),(0,X.useEffect)(()=>{if(!o)return;let e=!1,t=()=>Rc(o).then(t=>{e||(z(t),ce(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath))))}).catch(()=>{});t();let n=e=>{let n=e.detail;n?.workspaceName&&n.workspaceName!==o||(!n?.treeName||n.treeName===`backends`)&&t()};return window.addEventListener(`workspace:tree:refresh`,n),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,n)}},[o]),(0,X.useEffect)(()=>{if(!o)return;let e=[`workspace:${o}`,y?`workspace:${y}`:null].filter(Boolean),t=()=>e.forEach(e=>B.emit(`subscribe`,{channel:e})),n=B.on(`connect`,t);t();let r=Dt(o,y),i=e=>{if(e?.workspaceId&&y&&e.workspaceId!==y)return;let t=e?.treePath;t&&ce(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};B.on(`backend.resync.changed`,i);let a=e=>{e?.workspaceId&&y&&e.workspaceId!==y||G(o,!0)};return B.on(`pins.changed`,a),()=>{r(),n?.(),B.off(`backend.resync.changed`,i),B.off(`pins.changed`,a)}},[o,y,G]);let[Xe,Ze]=(0,X.useState)(null),Qe=`${c.pathname}|${c.search}`;if(Qe!==Xe){Ze(Qe);let{treeName:e,path:t}=af(c.pathname),n=new URLSearchParams(c.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!n;U?W(!1):w(r||je?r?xI(e,n):C:Ne[0]),ie(t),le(t===`/`?null:t)}let{showProgress:$e}=wo();(0,X.useEffect)(()=>{o&&te($e,o)},[o,$e]);let et=Ut({workspaceId:o??void 0,treeName:bI(C),onRefresh:Ye}),tt=(0,X.useRef)(new Map);(0,X.useEffect)(()=>{if(!o)return;let e=`${o}:${C}:${re}`,t=et;t.canResyncBackend(re)&&(Date.now()-(tt.current.get(e)||0)<6e4||(tt.current.set(e,Date.now()),t.onResyncBackend?.(re).catch(()=>{})))},[o,C,re,et]);let nt=new Set(xe.map(e=>ss(e.tree,e.path))),rt=bI(C),it=(0,X.useCallback)(e=>nt.has(ss(rt,e)),[xe,rt]),at=(0,X.useCallback)(async e=>{if(!o)return;let t=xe.find(t=>ss(t.tree,t.path)===ss(rt,e));t?await gs(o,t.id):await Ss(o,e,rt),await G(o)},[o,xe,rt,G]),ot=(0,X.useCallback)(async e=>{if(o){H(t=>t.filter(t=>t.id!==e.id));try{await gs(o,e.id)}finally{await G(o)}}},[o,G]),ct=(0,X.useCallback)(async(e,t)=>{if(!o)return;let n=xe.find(t=>t.id===e);if(!n)return;let r=xe.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let a=[...r.slice(0,i),n,...r.slice(i)];if(!a.every((e,t)=>e===xe[t])){H(a);try{H(await bc(o,a.map(e=>e.id)))}catch(e){throw await G(o),e}}},[o,xe,G]),lt=(0,X.useCallback)(e=>{if(!o)return;W(!0),ie(e.path),le(null);let t=of(o,e.path,e.tree);if(i){i.activateRow(`pin:${o}:${e.id}`,e.label||e.name||e.path,t);return}r(t)},[o,r,i]),dt=(0,X.useCallback)(e=>{!o||e.resolvable===!1||(W(!1),Me(!0),w(xI(e.tree)),ie(e.path),le(null),de(``),Ae.current=!0,i?.setFocus(`main`),r(of(o,e.path,e.tree)))},[o,r,i]),pt=C===`context`?T:C===`directory`?D:C===`backends`?k:null,mt=C===`context`?N:C===`directory`?ee:C===`backends`&&I;(0,X.useEffect)(()=>{if(!Ae.current||mt||C===`pins`)return;let e=we.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),Ae.current=!1)},[C,re,pt,mt]);let ht=(0,X.useCallback)(e=>{Me(!0),w(e);let t=Ee[e];ie(t.selectedPath),le(t.contentPath),de(t.searchQuery)},[Ee]),gt=(0,X.useCallback)(e=>{ht(Yk(Ne,C,e))},[Ne,C,ht]),_t=aI(e.m2Open,gt),vt=e=>{le(null),ie(e);let t=bI(C);i?.setFocus(`main`),r(of(o,e,t))},yt=(0,X.useCallback)((e,t)=>{ie(e),le(e);let n=bI(C),a=new URLSearchParams;a.set(`layer`,`1`),t&&a.set(`layerId`,t),i?.setFocus(`main`),r(`${of(o,e,n)}?${a.toString()}`)},[o,C,r,i]),bt=(0,X.useCallback)((e,t)=>{if(o){if(i){i.openCanvas({kind:`route`,location:of(o,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:t,path:e}}))}},[o,i]),xt=(0,X.useCallback)(async e=>{if(!o)return;let t=bI(C),n=await zc(o,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[o,C]),St=ue.toLowerCase().trim(),wt=St?j.filter(e=>e.name.toLowerCase().includes(St)||(e.label||``).toLowerCase().includes(St)||(e.description||``).toLowerCase().includes(St)):j;return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(LF,{title:_||o||`Workspace`,icon:x.icon||`ph:stack-fill`,accentColor:x.color,onBack:t,action:(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o&&r(Sw(o)),className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Open workspace`,children:(0,Z.jsx)(Pi,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,disabled:!h,onClick:()=>{a?n(`settings`,o??null):s(`/workspaces/${o}/settings/general`)},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,title:h?`Settings`:`Workspace settings require admin access`,children:(0,Z.jsx)(Wi,{className:`w-3.5 h-3.5`})})]})}),(0,Z.jsx)(`div`,{..._t,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:Ne.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>ht(e),title:`${yI[e]} — drag to reorder; the first tab opens by default`,"aria-label":yI[e],"aria-pressed":C===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,Re(e)},onDragEnd:Ve,onDragOver:t=>{if(!Le||Le===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;Be(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),He()},className:K(`relative flex-1 flex items-center justify-center py-2 transition-colors`,C===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,Le===e&&`opacity-40`,ze?.id===e&&ze.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,ze?.id===e&&!ze.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[vI[e],e===`pins`&&xe.length>0&&(0,Z.jsx)(`span`,{className:`absolute top-1 right-[calc(50%-14px)] min-w-[14px] h-[14px] px-0.5 rounded-full bg-primary text-primary-foreground text-[9px] leading-[14px] text-center font-medium`,children:xe.length})]},e))}),(0,Z.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,Z.jsx)(qa,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`search`,name:`workspace-tree-filter`,"aria-label":`Search workspace tree`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:C===`layers`?`Search layers…`:C===`pins`?`Search pins…`:`Search paths…`,value:ue,onChange:e=>de(e.target.value)})]})}),(0,Z.jsx)(`div`,{ref:we,onScroll:e=>{Te.current.set(C,e.currentTarget.scrollTop)},className:`flex-1 overflow-y-auto`,children:(0,Z.jsx)(Hw,{workspaceId:o,treeName:bI(C),readOnly:!h,className:`min-h-full`,children:C===`pins`?(0,Z.jsx)(pI,{pins:xe,isLoading:Se,searchQuery:ue,activeKey:ss(l,u),onOpen:lt,onShowInTree:dt,onUnpin:ot,onMove:ct}):C===`layers`?(0,Z.jsx)(AI,{layers:wt,isLoading:R,wsName:o??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),r(`${of(o,`/`)}?${t.toString()}`)},onLock:async e=>{await Jo(o,e.id,o,`context`),Je(o)},onUnlock:async e=>{await Lc(o,e.id,o,`context`),Je(o)},onRename:async(e,t)=>{await lc(o,e.id,t,`context`),Je(o)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await jo(o,e.id,`context`),Je(o))}}):(0,Z.jsx)(QF,{expansionState:Ee[C].expansion,root:pt,workspaceId:o??void 0,treeName:C,isBackendsTree:C===`backends`,onRestoreTrash:o?e=>ut(o,e):void 0,onDiscardTrash:o?e=>st(o,e):void 0,onAltSelect:i?e=>bt(e,bI(C)):void 0,selectedPath:re,contentPath:V,onSelect:vt,onShowContent:C===`context`?yt:void 0,onOpenToSide:bt,onShareCanvas:xt,onNewCanvas:o&&C!==`backends`?e=>{s(`${of(o,e,C)}?createCanvas=1`)}:void 0,isLoading:mt,rootLabel:o??void 0,searchQuery:ue,backends:ae,resyncingPaths:C===`backends`?oe:void 0,onAddRule:o&&C===`backends`?he:void 0,onAddStoreRule:o?(e,t=`store`)=>{let n=C===`backends`?(()=>{let n=On(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${C===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:hn(e)};s(`/workspaces/${o}/settings/hooks?${Ct(n).toString()}`)}:void 0,onStoragePolicy:o&&(C===`context`||C===`directory`)?e=>_e(kN(C,e)):void 0,policyBadgeFor:be,pastedDocumentIds:fe?.documentIds,isPathPinned:it,onTogglePin:o?at:void 0,onPasteDocuments:o&&C===`backends`?async(e,t)=>{let n=Hs(e);if(!n)return!1;let r=e.split(`/`).filter(Boolean).slice(2).join(`/`),i=$e({title:`Moving…`,description:`${t.length} message(s) → ${r}`});try{let{moved:a,results:s}=await Uc(o,n.address,t,e),c=s.filter(e=>!e.ok);return c.length?i.fail({title:`${c.length} message(s) not moved`,description:c[0].error||`Move failed`,variant:`destructive`}):i.done({title:`Moved`,description:`${a} message(s) → ${r}`}),fe&&a&&(pe(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:`/imap/${n.address}`,treeName:`backends`}})),a>0}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to move messages`,variant:`destructive`}),!1}}:o?async(e,t)=>{let n=C===`directory`?`directory`:`context`,r=C===`directory`?`directory`:Tc,i=$e({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await Ko(o,e,t,r,n)}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(fe&&(pe(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:e,treeName:r}}))),a}:void 0,...et},C)})}),me&&o&&(0,Z.jsx)(lI,{workspaceId:o,sourcePath:me,onClose:()=>he(null),onManageRules:()=>{he(null),s(`/workspaces/${o}/settings/hooks?section=rules`)}}),ge&&o&&(0,Z.jsx)(UN,{workspaceId:o,path:ge,onClose:()=>_e(null),onSaved:()=>{ye()}})]})}var wI={canvas:{label:`Canvases`,order:0},dataset:{label:`Datasets`,order:1},context:{label:`Context layers`,order:2},workspace:{label:`Workspaces`,order:3},universe:{label:`Universe`,order:4},label:{label:`Labels`,order:5},system:{label:`System`,order:6}},TI=100,EI=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),DI=e=>wI[e]??{label:`${EI(e)} layers`,order:TI};function OI({type:e}){return e===`canvas`?(0,Z.jsx)(Pa,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Z.jsx)(Fa,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Z.jsx)(vi,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function kI(e){let t=new Map;for(let n of e){let e=n.type||`context`,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({type:e,items:t,meta:DI(e)})).sort((e,t)=>e.meta.order-t.meta.order||e.meta.label.localeCompare(t.meta.label)).map(({type:e,items:t,meta:n})=>({type:e,label:n.label,items:t}))}function AI({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,X.useState)(null),l=(0,X.useRef)(null);if((0,X.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No layers found`});let u=async(e,t)=>{e.stopPropagation();try{await t()}catch(e){alert(e instanceof Error?e.message:String(e))}},d=async(e,t)=>{c(null);let n=t.trim();if(!(!n||n===e.name))try{await a(e,n)}catch(e){alert(e instanceof Error?e.message:String(e))}},f=kI(e);return(0,Z.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,Z.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,Z.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-l-md px-2 py-1.5 text-xs bg-card shadow-elevation-1 cursor-pointer hover:bg-accent/40 transition-colors`,style:{borderRight:e.color?`4px solid ${e.color}`:`4px solid transparent`},onClick:()=>s!==e.id&&n(e),children:[(0,Z.jsx)(`div`,{className:K(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,Z.jsx)(OI,{type:e.type}),s===e.id?(0,Z.jsx)(`input`,{ref:l,defaultValue:e.label||e.name,className:`flex-1 bg-transparent outline-none min-w-0 font-medium border-b border-primary`,onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&d(e,t.target.value),t.key===`Escape`&&c(null)},onBlur:t=>d(e,t.target.value)}):(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,Z.jsx)(Si,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,Z.jsx)(`button`,{type:`button`,title:`Unlock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-warning hover:text-foreground touch-target`,onClick:t=>u(t,()=>i(e)),children:(0,Z.jsx)(ea,{className:`w-3 h-3`})}):(0,Z.jsx)(`button`,{type:`button`,title:`Lock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>u(t,()=>r(e)),children:(0,Z.jsx)(Si,{className:`w-3 h-3`})}),!e.locked&&(0,Z.jsx)(`button`,{type:`button`,title:`Rename layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>{t.stopPropagation(),c(e.id)},children:(0,Z.jsx)(Za,{className:`w-3 h-3`})}),!e.locked&&(0,Z.jsx)(`button`,{type:`button`,title:`Destroy layer`,className:`p-0.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,onClick:t=>u(t,()=>o(e)),children:(0,Z.jsx)(Qr,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function jI(){let{state:e,closeM2:t}=qC(),n=De(),r=ft(),i=vn(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null),c=o?.address===a?o.workspace:null,l=c?.label||c?.name,u=se(c);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return Ws(a).then(t=>{e||s({address:a,workspace:t})}).catch(()=>{}),()=>{e=!0}},[a]);let d=i.pathname.split(`/`).filter(Boolean),f=d[2]===`settings`?jD(d[3]):null,p=(0,X.useMemo)(()=>kD.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(LF,{title:`Settings: ${l||a||`Workspace`}`,icon:c?.icon||`ph:stack-fill`,accentColor:c?.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a&&r(`/workspaces/${a}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open workspace`,children:(0,Z.jsx)(Pi,{className:`h-3.5 w-3.5`})})}),u?(0,Z.jsx)(eI,{items:p,activeId:f,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)}):(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:c?`Workspace settings are available to owners and admins.`:`Loading workspace…`})]})}function MI(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ZD();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>B.emit(`subscribe`,{channel:`agent`}),r=()=>B.emit(`unsubscribe`,{channel:`agent`}),i=B.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e?.agent??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},o=e=>{let t=e?.agent??e;t?.id&&n(e=>e.map(e=>e.id===t.id?{...e,...t}:e))},c=e=>{let t=e,r=t?.agentId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=e=>{let t=e,r=t?.agentId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},u=[[`agent:created`,a],[`agent.created`,a],[`agent:updated`,o],[`agent.updated`,o],[`agent:deleted`,c],[`agent.deleted`,c],[`agent:status:changed`,l],[`agent.status.changed`,l]];return u.forEach(([e,t])=>B.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>B.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`agents:refresh`,e),()=>window.removeEventListener(`agents:refresh`,e)},[s]),{agents:t,isLoading:r,refresh:c}}function NI({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function PI(){let e=aw(),{state:t,selectEntity:n,openM2:r,closeM2:i}=qC(),a=De(),{agents:o,isLoading:s,refresh:c}=MI(t.activeSection===`agents`),{showToast:l}=wo(),[u,d]=(0,X.useState)(new Set),f=ft(),p=e=>{n(e.id),r(`detail`,e.id),f(`/agents/${encodeURIComponent(e.name||e.id)}`)},m=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await dO(t.id),c(),l({title:`Success`,description:`${t.label||t.name} started`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}},h=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await fO(t.id),c(),l({title:`Success`,description:`${t.label||t.name} stopped`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,Z.jsx)(XC,{}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})]}),!e.local&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i(),f(`/agents?create=1`)},title:`Create agent`,"aria-label":`Create agent`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Z.jsx)(br,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No agents found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:o.map(e=>{let i=t.selectedEntityId===e.id,o=u.has(e.id);return(0,Z.jsxs)(`div`,{"data-active":i||void 0,className:K(`group relative rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all shadow-elevation-1 hover:shadow`,i?`bg-accent shadow`:`bg-card hover:bg-accent/50`),style:{borderRight:`6px solid ${e.color||`transparent`}`},onClick:()=>p(e),children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(NI,{status:e.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:o,onClick:t=>h(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,Z.jsx)(Sa,{className:`w-3.5 h-3.5`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:o,onClick:t=>m(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,Z.jsx)(Ar,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(e.id),a?r(`settings`,e.id):f(`/agents/${encodeURIComponent(e.name||e.id)}/settings/identity`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors`,title:`Settings`,children:(0,Z.jsx)(Wi,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description})]},e.id)})})})]})}function FI(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function II(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function LI(e){return e.sessions.sessions.find(t=>t.id===e.current.sessionId||t.path===e.current.sessionFile||t.id===e.sessions.currentSessionId||t.path===e.sessions.currentSessionPath||t.isCurrent)||null}function RI(){let{state:e,closeM2:t}=qC(),n=e.selectedEntityId||``,r=ft(),{showToast:i}=wo(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{current:h,sessions:g,isLoading:_,error:v,refresh:y,create:b,select:x,rename:S,remove:C}=pM(n);(0,X.useEffect)(()=>{n&&(QD(n).then(o).catch(()=>{}),y().catch(e=>{i({title:`Error`,description:e instanceof Error?e.message:`Failed to load sessions`,variant:`destructive`})}))},[n,y,i]);let w=(0,X.useMemo)(()=>g?.sessions?g.currentSessionId?g.sessions.find(e=>e.id===g.currentSessionId)||null:g.currentSessionPath?g.sessions.find(e=>e.path===g.currentSessionPath)||null:g.sessions.find(e=>e.isCurrent)||null:null,[g]),T=a?.name||n,E=e=>e?.slug||e?.id,D=e=>{let t=typeof e==`string`?e:E(e);r(t?`/agents/${encodeURIComponent(T)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(T)}`)},O=async()=>{try{let e=await b({mode:`persistent`,name:l.trim()||void 0});c(!1),u(``),D(LI(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create session`,variant:`destructive`})}},k=async()=>{try{let e=await b({mode:`experimental`});D(LI(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open experimental session`,variant:`destructive`})}},A=async()=>{try{await b({mode:`incognito`}),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open incognito session`,variant:`destructive`})}},j=async e=>{try{e.isExperimental?await x({mode:`experimental`}):await x({mode:`persistent`,sessionId:e.id}),D(e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}},M=async e=>{if(p.trim())try{let t=(await S(e.id,p.trim())).sessions.sessions.find(t=>t.id===e.id);f(null),m(``),w?.id===e.id&&D(t||e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to rename session`,variant:`destructive`})}},N=async e=>{if(!e.isExperimental&&window.confirm(`Delete session "${FI(e)}"?`))try{await C(e.id),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete session`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(LF,{title:a?.label||a?.name||n,onBack:t,action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(`/agents/${encodeURIComponent(T)}/settings`),className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Agent settings`,children:(0,Z.jsx)(Wi,{className:`h-3.5 w-3.5`})})}),(0,Z.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:g?.mode===`incognito`?`Incognito mode`:g?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:_,children:[(0,Z.jsx)(br,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:g?.mode===`experimental`?`default`:`outline`,onClick:k,disabled:_,children:[(0,Z.jsx)(Qn,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,Z.jsx)(Y,{size:`sm`,variant:g?.mode===`incognito`?`default`:`outline`,onClick:A,disabled:_,children:`Incognito`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[v&&(0,Z.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:v}),s&&(0,Z.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,Z.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),O()),e.key===`Escape`&&(c(!1),u(``))},placeholder:`Debugging auth`,className:`h-8`}),(0,Z.jsx)(Y,{size:`sm`,onClick:O,disabled:_,children:`Create`})]})]}),g?.sessions.length?(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:g.sessions.map(e=>{let t=w?.id===e.id&&g.mode!==`incognito`,n=d===e.id;return(0,Z.jsx)(`div`,{onClick:()=>j(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),j(e))},role:`button`,tabIndex:_?-1:0,className:`group w-full rounded-md border px-3 py-2 text-left transition-colors ${t?`border-foreground bg-accent`:`border-transparent hover:bg-accent/50`} ${_?`opacity-60`:``}`,children:(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:p,onChange:e=>m(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),M(e)),t.key===`Escape`&&(f(null),m(``))},placeholder:`Session name`,className:`h-8`}),(0,Z.jsx)(Y,{size:`sm`,onClick:t=>{t.stopPropagation(),M(e)},disabled:!p.trim()||_,children:`Save`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:FI(e)}),e.isExperimental&&(0,Z.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:II(e)})]})}),!n&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),m(e.name||FI(e))},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-muted-foreground/10 text-muted-foreground touch-target`,title:`Rename`,children:(0,Z.jsx)(Gn,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),N(e)},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,title:`Delete session`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-sm`,children:_?`Loading sessions...`:`No persistent sessions yet.`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),h?.mode===`incognito`&&(0,Z.jsx)(`div`,{className:`mt-3 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground`,children:`Incognito session is active. It lives in memory and stays out of the session list.`})]})]})}function zI(){let{state:e,closeM2:t}=qC(),n=De(),r=ft(),i=vn(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return QD(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?FD(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,X.useMemo)(()=>PD.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(LF,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u&&r(`/agents/${u}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open agent`,children:(0,Z.jsx)(Pi,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(eI,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function BI(){let e=vn(),{state:t}=qC(),[n,r]=(0,X.useState)(``),i=(0,X.useRef)(null);(0,X.useLayoutEffect)(()=>{let e=i.current,t=e?.querySelector(`[aria-current="page"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();r.top<n.top?e.scrollTop+=r.top-n.top:r.bottom>n.bottom&&(e.scrollTop+=r.bottom-n.bottom)},[e.pathname,t.user?.userType]);let a=SC.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>wC(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,Z.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.jsx)(XC,{}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`})]}),(0,Z.jsx)(q,{type:`search`,name:`settings-menu-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings menu`,placeholder:`Find a setting…`,value:n,onChange:e=>r(e.target.value)})]}),(0,Z.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,Z.jsxs)(`section`,{"aria-label":t.label,children:[(0,Z.jsx)(`h2`,{className:`px-3 py-2 text-xs font-semibold text-muted-foreground`,children:t.label}),t.items.map(({path:t,icon:n,label:r,description:i})=>(0,Z.jsxs)(we,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:K(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,Z.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,Z.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var VI=280;function HI(){let{state:e}=qC(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,Z.jsx)(tI,{});if(n===`detail`)return(0,Z.jsx)($F,{})}if(t===`workspaces`){if(n===`settings`)return(0,Z.jsx)(jI,{});if(n===`detail`)return(0,Z.jsx)(SI,{})}if(t===`agents`){if(n===`settings`)return(0,Z.jsx)(zI,{});if(n===`detail`)return(0,Z.jsx)(RI,{})}return null}function UI(){let{state:e,closeM1:t,closeM2:n}=qC();Ae(t,e.m1Open&&!e.m2Open),Ae(n,e.m1Open&&e.m2Open);let r=De(),i=(0,X.useRef)(null),a=(0,X.useRef)(null);PF(i,e.m1Open&&!e.m2Open,e.activeSection??``),PF(a,e.m1Open&&e.m2Open,`${e.activeSection}:${e.selectedEntityId}:${e.m2View}`);let[o,s]=(0,X.useState)(VI),[c,l]=(0,X.useState)(!1),u=r&&e.m1Open;return(0,Z.jsxs)(Z.Fragment,{children:[u&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:e.m1Open&&!u?{width:o}:void 0,className:K(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!c&&!u&&`transition-[width] duration-normal ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,u?`fixed bottom-2 left-[calc(0.5rem+var(--spacing-rail)+0.5rem)] right-2 top-2 z-40 shadow-elevation-5`:`relative`),children:[(0,Z.jsxs)(`div`,{ref:i,"data-menu-view":`list`,inert:!e.m1Open||e.m2Open,className:K(`absolute inset-0 flex flex-col transition-opacity duration-normal ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:u?void 0:{minWidth:o},children:[e.activeSection===`contexts`&&(0,Z.jsx)(IF,{}),e.activeSection===`workspaces`&&(0,Z.jsx)(iI,{}),e.activeSection===`agents`&&(0,Z.jsx)(PI,{}),e.activeSection===`admin`&&(0,Z.jsx)(BI,{}),e.activeSection===`apps`&&(0,Z.jsx)(rw,{}),e.activeSection===`settings`&&(0,Z.jsx)(BI,{})]}),(0,Z.jsx)(`div`,{ref:a,"data-menu-view":`detail`,inert:!e.m1Open||!e.m2Open,className:K(`absolute inset-0 z-10 bg-card flex flex-col md:transition-transform md:duration-normal md:ease-out`,e.m2Open?`translate-x-0`:`translate-x-full max-md:invisible`),children:e.m2Open&&(0,Z.jsx)(HI,{})}),e.m1Open&&!u&&(0,Z.jsx)(NF,{width:o,onResize:s,onDragging:l})]})]})}function WI(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function GI(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`,`apps`].includes(t)&&!!n}var KI=`max-md:fixed max-md:left-2 max-md:right-2 max-md:top-2 max-md:bottom-2 max-md:z-side max-md:py-0 max-md:mr-0 max-md:rounded-(--panel-radius) max-md:shadow-elevation-5 max-md:animate-fade-in`,qI=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function JI(){let e=w(),{pathname:t,search:n}=vn(),{state:r}=qC(),i=(0,X.useRef)(null);PF(i,!r.m1Open,t+n,!r.m0Open);let a=GI(t),o=WI(t),{entry:s,loading:c,error:l,close:u}=ye();return(0,Z.jsx)(`div`,{className:K(`relative flex flex-col flex-1 min-w-0`,!o&&`surface-sheet`),children:(0,Z.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,Z.jsx)(`main`,{ref:i,id:`content-area`,className:K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!a&&!o&&`p-page max-md:pb-rail-stack`),children:(0,Z.jsx)(Gt,{})}),(s||c||l)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:qI,onClick:u,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??420}px`},className:K(`relative z-10 flex shrink-0 items-stretch py-2 mr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_248px)]`,KI),children:[(0,Z.jsx)(je,{edge:`left`}),(0,Z.jsx)(O,{},s?`${s.workspaceId}:${s.document.id}`:`loading`)]})]})]})})}function YI(){let{state:e,setView:t}=ol(),{pathname:n}=vn();return e.t1Open||e.addOpen||!WI(n)?null:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`tools`),"aria-label":`Open toolbox`,title:`Open toolbox`,className:`fixed z-50 hidden md:flex h-16 w-16 items-center justify-center rounded-full shadow-elevation-4 transition-colors bottom-fab-inset right-6 bg-foreground text-background hover:bg-foreground`,children:(0,Z.jsx)(Ci,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var XI={current:null,sessions:null,isLoading:!1,error:null};function ZI(e){return e instanceof Error?e.message:`Session request failed`}function QI({children:e}){let[t,n]=(0,X.useState)({}),r=(0,X.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||XI,...t}}))},[]),i=(0,X.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,X.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([$D(e),eO(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:ZI(t)}),t}}},[r]),o=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await tO(e,t))}catch(t){throw r(e,{isLoading:!1,error:ZI(t)}),t}},[i,r]),s=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await nO(e,t))}catch(t){throw r(e,{isLoading:!1,error:ZI(t)}),t}},[i,r]),c=(0,X.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await rO(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:ZI(t)}),t}},[i,r]),l=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await iO(e,t))}catch(t){throw r(e,{isLoading:!1,error:ZI(t)}),t}},[i,r]),u=(0,X.useMemo)(()=>({getState:e=>t[e]||XI,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,Z.jsx)(fM.Provider,{value:u,children:e})}function $I(){let e=Dl(),{closeAdd:t}=ol(),{showSuccessToast:n,showErrorToast:r}=Oo(),[i,a]=(0,X.useState)(`Untitled.txt`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),u=!1;try{Ml(``,i.trim()),u=!0}catch{}return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`plaintext-filename`,children:`Filename`}),(0,Z.jsx)(q,{id:`plaintext-filename`,autoFocus:!0,value:i,onChange:e=>a(e.target.value)})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Content`}),(0,Z.jsx)(Zc,{kind:`text`,value:o,onChange:s,placeholder:`Write plain text…`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a file in the current storage folder. Existing files are never overwritten.`}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:t,disabled:c,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{if(!(c||!u||e?.mode!==`workspace`||e.treeName!==`backends`)){l(!0);try{let r=await bl(e.workspaceName,e.path);await Eo(e.workspaceName,{...r,key:Ml(r.key,i.trim())},new Blob([o],{type:`text/plain;charset=utf-8`}),{contentType:`text/plain;charset=utf-8`}),El(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),n(`Plaintext file created`),t()}catch(e){r(e instanceof Error?e.message:`Failed to create file`)}finally{l(!1)}}},disabled:c||!u,children:c?`Creating…`:`Create file`})]})]})}function eL(){let{closeAdd:e,state:t}=ol(),n=Dl(),{showSuccessToast:r,showErrorToast:i}=Oo(),a=iT(n,t.addRelateTo),o=ux(n,a.write,t.addRelateTo?`related:${t.addRelateTo.documents.map(e=>e.id).sort().join(`,`)}`:`add`),s=oT(t.activeWorkspaceName),c=!!n&&o.canSave,l=async()=>{if(n)try{let t=await o.save(n),i=await a.write(t);r(i?`Note created; some relations failed`:`Note created`),o.finish(),e()}catch(e){i(e instanceof Error?e.message:`Failed to create note`)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Body`}),(0,Z.jsx)(Zc,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`note-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`note-comment`,value:o.comment,onChange:e=>o.setComment(e.target.value),rows:2,placeholder:`Optional; context you can't infer from the body`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsx)(fT,{geotag:o.geotag,idPrefix:`note-geotag`}),(0,Z.jsx)(aT,{f:a,idPrefix:`note`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:Ol(n)}),(0,Z.jsx)($c,{...o,onRetry:o.retry}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:o.saving,children:`Close`}),(0,Z.jsx)(Y,{size:`sm`,onClick:l,disabled:!c,children:o.saving?`Saving…`:`Done`})]})]})}function tL(){let{closeAdd:e,state:t}=ol(),n=Dl(),{showSuccessToast:r,showErrorToast:i}=Oo(),a=FE(),o=iT(n,t.addRelateTo),s=oT(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsx)(fT,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,Z.jsx)(aT,{f:o,idPrefix:`link`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:Ol(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Link created; some relations failed`:`Link created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create link`)}},disabled:!c,children:a.saving?`Saving…`:`Save link`})]})]})}function nL(e){let[t,n]=(0,X.useState)({key:``,list:[]});return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return Rc(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await Mc(e,`github`,t.address).catch(()=>[]);for(let e of n){if(e.writable===!1)continue;let n=e.id||e.name;a.push({driver:`github`,address:t.address,container:n,label:`GitHub: ${n}`})}}t||n({key:e,list:a})}).catch(()=>{t||n({key:e,list:[]})}),()=>{t=!0}},[e]),e&&t.key===e?t.list:[]}function rL(){let{closeAdd:e,state:t}=ol(),n=Dl(),{showSuccessToast:r,showErrorToast:i}=Oo(),a=ve(),o=iT(n,t.addRelateTo),s=oT(t.activeWorkspaceName),c=nL(t.activeWorkspaceName),[l,u]=(0,X.useState)(`canvas`),[d,f]=(0,X.useState)(!1),p=c.find(e=>`${e.driver}:${e.address}:${e.container}`===l),m=p?a.title.trim().length>0&&!d:!!n&&a.canSave,h=async()=>{if(p){f(!0);try{await As(t.activeWorkspaceName||``,p.driver,p.address,p.container,{title:a.title.trim(),...a.description.trim()?{description:a.description.trim()}:{},...a.tags.length?{labels:a.tags}:{}}),r(`Issue created in ${p.container}`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create issue`)}finally{f(!1)}return}if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Todo created; some relations failed`:`Todo created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create todo`)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(Oe,{...a}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`todo-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`todo-comment`,value:a.comment,onChange:e=>a.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),c.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`todo-destination`,children:`Save to`}),(0,Z.jsxs)(`select`,{id:`todo-destination`,value:l,onChange:e=>u(e.target.value),className:`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,children:[(0,Z.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,Ol(n)]}),c.map(e=>(0,Z.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a GitHub issue (due date, priority and status stay Canvas-side until the issue syncs back).`})]}),(0,Z.jsx)(fT,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,Z.jsx)(aT,{f:o,idPrefix:`todo`}),!p&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:Ol(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function iL(){let{closeAdd:e,state:t}=ol(),n=Dl(),{showSuccessToast:r,showErrorToast:i}=Oo(),a=pe(),o=iT(n,t.addRelateTo),s=oT(t.activeWorkspaceName),c=async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Identity created; some relations failed`:`Identity created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create identity`)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(oe,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`identity-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`identity-comment`,value:a.comment,onChange:e=>a.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(aT,{f:o,idPrefix:`identity`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:Ol(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function aL(){let{closeAdd:e}=ol(),t=Dl(),{showSuccessToast:n,showErrorToast:r}=Oo(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),c=i.trim().replace(/^\/+|\/+$/g,``),l=!!t&&!!c&&!o,u=async()=>{if(!(!l||!t)){s(!0);try{let{workspaceName:r,path:i,treeName:a}=await pl(t),o=i===`/`?``:i;if(a===`backends`){let e=await bl(r,i);await Ns(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),El(t)}else await Ys(r,`${o}/${c}`,!0,a);n(`Folder created`),e()}catch(e){r(e instanceof Error?e.message:`Failed to create folder`)}finally{s(!1)}}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,Z.jsx)(q,{id:`add-folder-name`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&u()},placeholder:`e.g. projects/alpha`,autoFocus:!0}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,Ol(t)]})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function oL(){let{openAddPicker:e,closeAdd:t}=ol(),n=Dl(),{showSuccessToast:r,showErrorToast:i}=Oo(),[a,o]=(0,X.useState)(!1);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>e(),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(ae,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:n?.mode===`workspace`?n.workspaceName:void 0,saving:a,onConfirm:async e=>{o(!0);try{await Cl(n,e),r(`${e.length} document${e.length===1?``:`s`} added`),t()}catch(e){i(e instanceof Error?e.message:`Failed to add documents`)}finally{o(!1)}},onClose:e})})]})}function sL(){let{state:e,closeAdd:t}=ol(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Oo();return!n||!r?null:(0,Z.jsx)(cL,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a},`${r}:${n.id}`)}function cL({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=Gc(e,t),s=oT(t),c=async()=>{try{await o.save(),i(`Note updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update note`)}};return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`edit-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(G,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(Zc,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsx)($c,{...o,onRetry:o.save}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Close`}),(0,Z.jsx)(Y,{size:`sm`,onClick:c,disabled:!o.canSave,children:o.saving?`Saving…`:`Done`})]})]})}function lL(e,t){let n=Kc(e.metadata?.features),[r,i]=(0,X.useState)(String(e.data?.label??``)),[a,o]=(0,X.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,X.useState)(!1),l=!s;async function u(){c(!0);try{let n=a.map(e=>e.trim()).filter(Boolean);await ys(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data,...r.trim()?{label:r.trim()}:{},tags:n},metadata:{features:Qc(a)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{c(!1)}}return{url:String(e.data?.uri??e.data?.url??``),label:r,setLabel:i,tags:a,setTags:o,saving:s,canSave:l,save:u}}function uL(){let{state:e,closeAdd:t}=ol(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Oo();return!n||!r?null:(0,Z.jsx)(dL,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function dL({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=lL(e,t),s=oT(t);return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(G,{children:[`URL `,(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,Z.jsx)(q,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{htmlFor:`edit-link-label`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(G,{children:`Tags`}),(0,Z.jsx)(Be,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Link updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update link`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save link`})]})]})}var fL=380,pL=300,mL=560,hL={message:{label:`New Message`,icon:ki},note:{label:`New Note`,icon:Da},link:{label:`New Link`,icon:Ui},todo:{label:`New Todo`,icon:pa},identity:{label:`New Identity`,icon:Hr},sketch:{label:`New Sketch`,icon:pr},plaintext:{label:`New Plaintext File`,icon:Ki},file:{label:`Add Files`,icon:Yr},photo:{label:`Photo/Video`,icon:Ur},existing:{label:`Add Existing`,icon:ua},folder:{label:`New Folder`,icon:ni}};function gL(){let{state:e,openAdd:t,openAddPicker:n,closeAdd:r}=ol();Ae(r,e.addOpen);let{addOpen:i,addKind:a,editDocument:o,addModal:s}=e,c=Dl(),l=hl(c),u=l.isBackend&&!!a&&![`file`,`photo`,`folder`,`message`,`plaintext`].includes(a),d=e.activeWorkspaceName,f=!d||!!e.addRelateTo,p=u||a===`message`&&f,m=l.isBackend?[`note`,`link`,`todo`,`identity`,`sketch`,`existing`]:[`plaintext`];f&&m.push(`message`);let h=c?.mode===`workspace`?`${c.workspaceName}:${c.treeName}:${c.path}`:c?.contextId,g=ft();(0,X.useEffect)(()=>{!i||a!==`sketch`||l.isBackend||(r(),g(DE.createUrl(c)))},[i,a,c,r,g,l.isBackend]);let _=Nn(),[v,y]=(0,X.useState)(fL),b=(0,X.useRef)(null),x=(0,X.useCallback)(e=>{e.preventDefault(),b.current={startX:e.clientX,startWidth:v};let t=e=>{if(!b.current)return;let t=b.current.startX-e.clientX,n=Math.min(mL,Math.max(pL,b.current.startWidth+t));y(n)},n=()=>{b.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[v]);if(!i)return null;let S=!!o,C=!S&&(!a||p),w,T;S?(w=o.schema===`data/schema/note`?`Edit Note`:`Edit Link`,T=o.schema===`data/schema/note`?Da:Ui):a&&!p?(w=hL[a].label,T=hL[a].icon):(w=`Add`,T=br);let E=(0,Z.jsxs)(Z.Fragment,{children:[_&&!s&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:r,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:_||s?void 0:{width:v},className:K(`flex flex-col overflow-hidden rounded-[var(--panel-radius)] border bg-card surface-glass`,s?`h-full w-full`:_?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!_&&!s&&(0,Z.jsx)(`div`,{onMouseDown:x,className:`absolute left-0 top-0 bottom-0 z-10 w-1 cursor-col-resize transition-colors hover:bg-primary/20`}),(0,Z.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center gap-2 border-b-4 px-2`,style:e.activeAccentColor?{borderBottomColor:e.activeAccentColor}:void 0,children:[(0,Z.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,"aria-label":`Back one level`,onClick:()=>C||S?r():n(),children:(0,Z.jsx)(ka,{className:`h-5 w-5`})}),(0,Z.jsxs)(`span`,{className:`flex flex-1 items-center gap-2 text-sm font-medium`,children:[S?(0,Z.jsx)(Lr,{className:`h-4 w-4`}):(0,Z.jsx)(T,{className:`h-4 w-4`}),w]}),(0,Z.jsx)(`button`,{type:`button`,onClick:r,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Close`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[S&&o.schema===`data/schema/note`&&(0,Z.jsx)(sL,{}),S&&o.schema===`data/schema/link`&&(0,Z.jsx)(uL,{}),!S&&C&&e.addRelateTo&&(0,Z.jsxs)(`p`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`The new document will be related to `,e.addRelateTo.documents.length,` selected document`,e.addRelateTo.documents.length===1?``:`s`,`.`]}),!S&&l.isBackend&&a!==`message`&&(0,Z.jsx)(`p`,{className:`border-b px-4 py-3 text-xs text-muted-foreground`,children:l.loading?`Checking storage destination…`:l.error||`Files are saved directly to this backend folder. Notes and other database documents belong in context or directory trees.`}),!S&&C&&(!l.isBackend||l.destination)&&(0,Z.jsx)(AE,{onSelect:t,omit:m}),!S&&a===`message`&&!f&&d&&(0,Z.jsx)(R,{workspaceId:d,onClose:r},d),!S&&!l.isBackend&&a===`note`&&(0,Z.jsx)(eL,{},h),!S&&!l.isBackend&&a===`link`&&(0,Z.jsx)(tL,{}),!S&&!l.isBackend&&a===`todo`&&(0,Z.jsx)(rL,{}),!S&&!l.isBackend&&a===`identity`&&(0,Z.jsx)(iL,{}),!S&&l.destination&&a===`plaintext`&&(0,Z.jsx)($I,{},h),!S&&(!l.isBackend||l.destination)&&a===`file`&&(0,Z.jsx)(wT,{},h),!S&&(!l.isBackend||l.destination)&&a===`photo`&&(0,Z.jsx)(wT,{capture:!0},h),!S&&!l.isBackend&&a===`existing`&&(0,Z.jsx)(oL,{}),!S&&(!l.isBackend||l.destination)&&a===`folder`&&(0,Z.jsx)(aL,{},h)]})]})]});return s?(0,Z.jsx)(tn,{label:w,onClose:r,children:E}):E}var _L=(0,X.createContext)(null);function vL(){return(0,X.useContext)(_L)}function yL(){let e=vL(),t=e?.notifications??[];return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,Z.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,Z.jsx)(Zn,{className:`w-4 h-4`}),(0,Z.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(oa,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,Z.jsx)(Qr,{className:`w-3 h-3`})})]}),t.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-(--card-radius)`,children:`No notifications`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,Z.jsxs)(`div`,{className:`rounded-(--card-radius) border p-2.5`,children:[(0,Z.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,Z.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}function bL({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function xL(){let{openAgentT2:e}=ol(),{setSection:t}=qC(),n=ft(),{agents:r,isLoading:i,refresh:a}=MI(!0),{showToast:o}=wo(),[s,c]=(0,X.useState)(new Set),l=(e,t)=>c(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),u=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await dO(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}},d=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await fO(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,Z.jsx)(ri,{className:`w-8 h-8 opacity-30`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,Z.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,Z.jsxs)(`div`,{className:`group relative px-3 py-2.5 cursor-pointer transition-colors bg-card hover:bg-accent/50`,style:{borderLeft:`6px solid ${t.color||`transparent`}`},onClick:()=>e(t.id),children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(bL,{status:t.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,Z.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>d(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Stop`,children:(0,Z.jsx)(Sa,{className:`w-3 h-3`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>u(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Start`,children:(0,Z.jsx)(Ar,{className:`w-3 h-3`})})})]}),t.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function SL(){let e=vL(),[t,n]=(0,X.useState)(50),r=e?.notifications??[],i=r.slice(-t).reverse();return(0,Z.jsxs)(`section`,{"aria-label":`Notification history`,className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b px-4 py-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Notifications`,r.length>0&&(0,Z.jsx)(`span`,{className:`ml-2 font-normal text-muted-foreground`,children:r.length})]}),(0,Z.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:`Saved on this browser`})]}),r.length>0&&(0,Z.jsxs)(Y,{variant:`ghost`,size:`sm`,onClick:()=>void e?.clear(),title:`Clear all notifications`,className:`shrink-0 gap-1.5`,children:[(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`}),`Clear all`]})]}),e?.storageError&&(0,Z.jsx)(`p`,{role:`alert`,className:`border-b px-4 py-3 text-xs text-destructive`,children:`Couldn’t access notification history in this browser.`}),e?.loading?(0,Z.jsx)(`p`,{role:`status`,className:`p-4 text-sm text-muted-foreground`,children:`Loading notifications…`}):r.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,Z.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,Z.jsx)(oa,{className:`h-5 w-5 text-muted-foreground`})}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No notifications yet`})]}):(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[(0,Z.jsx)(`ol`,{className:`space-y-2`,children:i.map(t=>{let n=t.status===`error`?er:t.status===`completed`?Sr:t.status===`started`?Zn:oa;return(0,Z.jsx)(`li`,{"data-notification-id":t.id,className:`rounded-(--card-radius) border bg-card p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(n,{"aria-hidden":!0,className:`mt-0.5 h-4 w-4 shrink-0 ${t.status===`error`?`text-destructive`:`text-muted-foreground`}`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`break-words text-sm font-medium`,children:t.title}),t.text&&(0,Z.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap break-words text-xs text-muted-foreground`,children:t.text}),(0,Z.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsx)(`time`,{dateTime:t.timestamp,children:new Date(t.timestamp).toLocaleString()}),t.status===`started`&&(0,Z.jsx)(`span`,{children:` · Started`}),t.status===`completed`&&(0,Z.jsx)(`span`,{children:` · Completed`}),t.status===`error`&&(0,Z.jsx)(`span`,{children:` · Error`})]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>void e?.remove(t.id),"aria-label":`Clear notification: ${t.title}`,title:`Clear notification`,className:`-mr-1 -mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent focus-ring touch-target`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})},t.id)})}),r.length>t&&(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,className:`mt-3 w-full`,onClick:()=>n(e=>e+50),children:`Show older notifications`})]})]})}function CL(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
58
|
+
`)||``}function wL(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(null),s=(0,X.useRef)(null),[c,l]=(0,X.useState)(e);return c!==e&&(l(e),e||n([])),(0,X.useEffect)(()=>{let t=!1;if(e)return $D(e).then(e=>{t||n(e.messages.map(e=>({role:e.role,content:e.content,isComplete:!0,...e.metadata?.reasoning?{reasoning:e.metadata.reasoning}:{},...e.metadata?{metadata:e.metadata}:{}})))}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),{messages:t,isStreaming:r,error:a,send:(0,X.useCallback)(async t=>{if(r||!t.trim()||!e)return;o(null),n(e=>[...e,{role:`user`,content:t,isComplete:!0},{role:`assistant`,content:``,isComplete:!1}]),i(!0);try{await dO(e)}catch(e){let t=e instanceof Error?e.message:void 0;if(!t?.includes(`not active`)&&!t?.includes(`already`)){o(t??`Failed to start agent`),i(!1);return}}s.current=new AbortController;let a=``,c=``,l=``,u;try{await J.stream(`${yo}/agents/${e}/prompt/stream`,{message:t},{signal:s.current.signal,onChunk:e=>{a+=e;let t=a.split(`
|
|
59
|
+
`);a=t.pop()??``;for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t===`[DONE]`)return;try{let e=JSON.parse(t);if(e.type===`chunk`)c+=e.delta||``,n(e=>{let t=[...e];return t[t.length-1]={role:`assistant`,content:c,isComplete:!1,...l?{reasoning:l}:{},...u?{metadata:u}:{}},t});else if(e.type===`thinking`)l=`${l}${e.delta||``}`.trim(),n(e=>{let t=[...e],n=t[t.length-1]?.content||c;return t[t.length-1]={role:`assistant`,content:n,isComplete:!1,...l?{reasoning:l}:{},...u?{metadata:u}:{}},t});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null,r=CL(t),i=BD(t)||l;u=VD(t),n(e=>{let t=[...e],n=c||t[t.length-1]?.content||``;return t[t.length-1]={role:`assistant`,content:r||n,isComplete:!0,...i?{reasoning:i}:{},...u?{metadata:u}:{}},t})}else e.type===`error`&&o(e.error)}catch{}}},onError:e=>{e.name!==`AbortError`&&o(e.message)},onComplete:()=>{n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}})}catch(e){let t=e instanceof Error?e:null;t?.name!==`AbortError`&&o(t?.message??`Stream failed`),n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}},[e,r]),sendVoice:(0,X.useCallback)(async t=>{if(!(r||!e)){o(null),i(!0),n(e=>[...e,{role:`user`,content:`🎤 Transcribing…`,isComplete:!1}]);try{let r=await vO(e,t);n(e=>{let t=[...e];return t[t.length-1]={role:`user`,content:`🎤 ${r.transcript}`,isComplete:!0},[...t,{role:`assistant`,content:r.reply,isComplete:!0}]}),r.audio&&r.audioMimeType&&new Audio(`data:${r.audioMimeType};base64,${r.audio}`).play().catch(()=>{})}catch(e){o(e instanceof Error?e.message:`Voice prompt failed`),n(e=>{let t=[...e],n=t[t.length-1];return n?.role===`user`&&!n.isComplete&&t.pop(),t})}finally{i(!1)}}},[e,r]),stop:(0,X.useCallback)(()=>{s.current?.abort(),i(!1)},[]),clear:(0,X.useCallback)(()=>{n([]),o(null)},[])}}function TL(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(null),i=(0,X.useRef)(null),a=(0,X.useRef)([]);return{isRecording:e,recorderError:n,start:(0,X.useCallback)(async()=>{if(!i.current){if(r(null),!navigator.mediaDevices?.getUserMedia||typeof MediaRecorder>`u`){r(`Audio recording is not supported in this browser`);return}try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=MediaRecorder.isTypeSupported(`audio/webm;codecs=opus`)?`audio/webm;codecs=opus`:void 0,r=new MediaRecorder(e,n?{mimeType:n}:void 0);a.current=[],r.ondataavailable=e=>{e.data.size>0&&a.current.push(e.data)},r.start(),i.current=r,t(!0)}catch(e){let t=e instanceof Error?e:null;r(t?.name===`NotAllowedError`?`Microphone access denied`:t?.message??`Could not start recording`)}}},[]),stop:(0,X.useCallback)(()=>{let e=i.current;return e?new Promise(n=>{e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop()),i.current=null,t(!1);let r=e.mimeType||`audio/webm`,o=new Blob(a.current,{type:r});a.current=[],n(o.size>0?o:null)},e.stop()}):Promise.resolve(null)},[]),cancel:(0,X.useCallback)(()=>{let e=i.current;e&&(e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop())},e.stop(),i.current=null,a.current=[],t(!1))},[])}}function EL({agentId:e,onClose:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),{showToast:m}=wo(),h=ul(),g=h?.state.activeContextType===`context`?h.state.activeContextId:null,_=h?.state.activeContextPath??null,v=(0,X.useRef)(null),y=(0,X.useRef)(null),{messages:b,isStreaming:x,error:S,send:C,sendVoice:w,stop:T,clear:E}=wL(e),{isRecording:D,recorderError:O,start:k,stop:A}=TL();(0,X.useEffect)(()=>{QD(e).then(r).catch(()=>{}),KD(e).then(l).catch(()=>l(null))},[e]),(0,X.useEffect)(()=>{_O().then(e=>s(!!(e.enabled&&e.stt))).catch(()=>s(!1))},[]),(0,X.useEffect)(()=>{b.length!==0&&v.current?.scrollIntoView({behavior:`smooth`})},[b]);let j=c?.binding.type===`context`&&!!g&&c?.binding.context===g,M=c?c.binding.type===`global`?`scope: global`:c.binding.type===`context`?j?`scoped to this context`:`context-bound`:`scope: ${c.binding.workspaceName||c.binding.workspace}${c.binding.type===`path`?`:${c.binding.path||`/`}`:``}`:`no canvas access`,N=async()=>{if(!g||u)return;let t=g||_;if(window.confirm(`Bind "${n?.label||n?.name||e}" to the current context (${t})? This mints a new canvas token and restarts the agent if it is running.`)){d(!0);try{let t=await qD(e,{binding:{type:`context`,context:g},permissions:[`read`,`write`]});l(t.access),p(t.token)}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{d(!1)}}},P=async()=>{let e=i.trim();!e||x||(a(``),y.current?.focus(),await C(e))};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Back to agents`,children:(0,Z.jsx)(ka,{className:`w-4 h-4`})}),n?.color&&(0,Z.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0`,style:{backgroundColor:n.color}}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:n?.label||n?.name||e}),(0,Z.jsx)(`div`,{className:`text-[10px] leading-tight text-muted-foreground truncate`,title:M,children:M})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:E,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Clear chat`,children:(0,Z.jsx)(Qr,{className:`w-3.5 h-3.5`})})]}),g&&!j&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/40 text-xs shrink-0`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate text-muted-foreground`,title:g||_||void 0,children:[`Toolbox context: `,g||_]}),(0,Z.jsx)(`button`,{type:`button`,disabled:u,onClick:N,className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent disabled:opacity-50`,children:u?`Binding…`:`Bind to this context`})]}),f&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-warning/10 text-xs shrink-0`,children:[(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:`Token (shown once):`}),(0,Z.jsx)(`code`,{className:`flex-1 truncate font-mono`,children:f}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>navigator.clipboard?.writeText(f),className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent`,children:`Copy`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(null),className:`shrink-0 rounded px-1.5 py-1 hover:bg-accent`,title:`Dismiss`,children:`×`})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3 space-y-3`,children:[b.length===0&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10`,children:n?`Chat with ${n.label||n.name}`:`Loading…`}),b.map((e,t)=>(0,Z.jsxs)(`div`,{className:K(`text-sm rounded-lg px-3 py-2 max-w-[85%] break-words`,e.role===`user`?`ml-auto bg-foreground text-background`:`mr-auto bg-muted text-foreground`),children:[(0,Z.jsx)(uM,{reasoning:e.role===`assistant`?e.reasoning:void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:!e.isComplete,compact:!0}),e.role===`assistant`?(0,Z.jsx)(F,{content:e.content||(e.isComplete?``:`…`)}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap`,children:e.content})]},t)),(S||O)&&(0,Z.jsx)(`div`,{className:`text-xs text-destructive text-center py-1`,children:S||O}),(0,Z.jsx)(`div`,{ref:v})]}),(0,Z.jsx)(`div`,{className:`p-3 border-t border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2 items-end`,children:[(0,Z.jsx)(`textarea`,{ref:y,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),P())},placeholder:`Message…`,rows:2,className:`flex-1 resize-y text-sm px-3 py-2 border border-input bg-background rounded-md focus:outline-none focus:ring-1 focus:ring-ring min-h-[38px] max-h-[120px]`}),o&&(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(D){let e=await A();e&&await w(e)}else x||await k()},disabled:x&&!D,className:K(`flex items-center justify-center w-9 h-9 rounded-md transition-opacity shrink-0 disabled:opacity-40`,D?`bg-destructive text-destructive-foreground hover:opacity-90 animate-pulse`:`bg-muted text-foreground hover:bg-accent`),title:D?`Stop recording and send`:`Record a voice message`,children:D?(0,Z.jsx)(Sa,{className:`w-4 h-4`}):(0,Z.jsx)(ci,{className:`w-4 h-4`})}),x?(0,Z.jsx)(`button`,{type:`button`,onClick:T,className:`flex items-center justify-center w-9 h-9 rounded-md bg-destructive text-destructive-foreground hover:opacity-90 transition-opacity shrink-0`,title:`Stop`,children:(0,Z.jsx)(Sa,{className:`w-4 h-4`})}):(0,Z.jsx)(`button`,{type:`button`,onClick:P,disabled:!i.trim(),className:`flex items-center justify-center w-9 h-9 rounded-md bg-foreground text-background hover:opacity-90 disabled:opacity-40 transition-opacity shrink-0`,title:`Send`,children:(0,Z.jsx)(Ia,{className:`w-4 h-4`})})]})})]})}function DL(){let{state:e,openApplet:t}=ol(),[n,r]=(0,X.useState)(`context`),i=e.appsAppletId,a=i?_C.find(e=>e.id===i):null;if(a)return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(null),className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Back to applets`,title:`Back to applets`,children:(0,Z.jsx)(ka,{className:`h-4 w-4`})}),(0,Z.jsx)(a.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:a.label})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(a.Component,{})})]});let o=vC(n);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(`div`,{className:`flex shrink-0 border-b border-border`,children:[`context`,`global`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:K(`flex-1 py-2.5 text-xs capitalize transition-colors`,n===e?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e},e))}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[!o.length&&(0,Z.jsxs)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:[`No `,n,` applets yet.`]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:o.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex min-h-[4.5rem] flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border border-border bg-muted/40 p-3 text-foreground transition-colors hover:bg-muted`,title:e.description,children:[(0,Z.jsx)(e.icon,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:e.label})]},e.id))})]})]})}var OL=[{view:`apps`,icon:Ga,label:`Apps`},{view:`tools`,icon:Ci,label:`Filters`},{view:`agents`,icon:ri,label:`Agents`},{view:`notifications`,icon:oa,label:`Notifications`}],kL=340,AL=`toolbox:width`,jL=360,ML=48,NL=e=>{let t=typeof window<`u`?window.innerWidth:1600,n=Math.max(kL,Math.min(Math.round(t*.7),t-ML-jL));return Math.max(kL,Math.min(e,n))},PL=()=>typeof window<`u`?Math.round(window.innerWidth/2):720;function FL(){let{state:e,setView:t,closeT1:n,closeT2:r}=ol();Ae(n,e.t1Open&&!e.t2Open),Ae(r,e.t2Open);let{t1Open:i,t1View:a,t2Open:o,t2AgentId:s,activeAccentColor:c}=e,l=Nn(),[u,d]=(0,X.useState)(()=>{let e=typeof window<`u`?Number(localStorage.getItem(AL)):NaN;return Number.isFinite(e)&&e>0?e:420}),f=(0,X.useCallback)(e=>{d(e);try{localStorage.setItem(AL,String(e))}catch{}},[]),p=(0,X.useRef)(null),m=(0,X.useCallback)(e=>{e.preventDefault(),p.current={startX:e.clientX,startWidth:u};let t=e=>{if(!p.current)return;let t=NL(p.current.startWidth-(e.clientX-p.current.startX));d(t)},n=()=>{p.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),d(e=>{try{localStorage.setItem(AL,String(e))}catch{}return e})};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[u]),h=u>=PL()*.9;return(0,X.useEffect)(()=>{let e=()=>d(e=>NL(e));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),!i||!a?null:(0,Z.jsxs)(Z.Fragment,{children:[l&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:l?void 0:{width:u},className:K(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card surface-glass text-foreground`,l?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!l&&(0,Z.jsx)(`div`,{onMouseDown:m,className:`absolute left-0 top-0 z-20 h-full w-1.5 cursor-col-resize hover:bg-primary/20`,title:`Drag to resize`,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between gap-1 border-b-4 px-2`,style:c?{borderBottomColor:c}:void 0,children:[(0,Z.jsx)(`div`,{className:`flex items-center gap-1`,children:OL.map(({view:e,icon:n,label:r})=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e),"aria-label":r,title:r,className:K(`flex h-10 w-11 items-center justify-center rounded-md transition-colors`,a===e?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:(0,Z.jsx)(n,{className:`h-4 w-4 shrink-0`})},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[!l&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(h?420:NL(PL())),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":h?`Shrink toolbox`:`Expand toolbox`,title:h?`Shrink toolbox`:`Expand to half screen`,children:h?(0,Z.jsx)(ei,{className:`h-4 w-4`}):(0,Z.jsx)(ba,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Close toolbox`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]})]}),(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${o&&s?`invisible`:``}`,children:[a===`home`&&(0,Z.jsx)(yL,{}),a===`apps`&&(0,Z.jsx)(DL,{}),a===`tools`&&(0,Z.jsx)(pC,{}),a===`agents`&&(0,Z.jsx)(xL,{}),a===`notifications`&&(0,Z.jsx)(SL,{})]}),o&&s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex flex-col bg-background`,children:(0,Z.jsx)(EL,{agentId:s,onClose:r})})]})]})]})}function IL(){let{running:e,hasViewer:t,paused:n,snapshot:r,source:i,lastCount:a,error:o,setPaused:s,stop:c,reopen:l}=Ex();if(!e||t)return null;let u=i===`screen`?mr:i===`photo`?zn:Ur;return(0,Z.jsxs)(`div`,{className:K(`fixed right-4 w-56 overflow-hidden rounded-(--panel-radius) border border-border bg-card shadow-elevation-4 z-panel animate-fade-in`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`),role:`status`,"aria-label":`Lens feed running`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:l,title:`Back to Lens`,className:`relative block w-full cursor-pointer bg-black/80 aspect-video`,children:[(0,Z.jsx)(Bx,{className:`h-full w-full`}),r&&(0,Z.jsx)(`img`,{src:r,alt:``,className:`absolute inset-0 h-full w-full bg-black object-contain`}),n&&(0,Z.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white`,children:`paused`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1.5`,children:[(0,Z.jsx)(u,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-muted-foreground`,children:o?(0,Z.jsx)(`span`,{className:`text-destructive`,children:o}):n?`paused`:r?`${i===`photo`?`photo`:`snapshot`} · ${a??`…`} match${a===1?``:`es`}`:`live · ${a??`…`} match${a===1?``:`es`}`}),i!==`photo`&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>s(!n),"aria-label":n?`Resume Lens`:`Pause Lens`,title:n?`Resume searching`:`Pause searching (camera stays on)`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:n?(0,Z.jsx)(Ar,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Jr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:l,"aria-label":`Reopen Lens panel`,title:`Reopen Lens`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(ba,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Stop Lens feed`,title:`Stop the feed`,className:`rounded p-1 text-destructive transition-colors hover:bg-destructive/10`,children:(0,Z.jsx)(Yi,{className:`h-3.5 w-3.5`})})]})]})}var LL=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`];function RL(e){let t=new URLSearchParams(e.replace(/^#/,``)),n=t.get(`document`)??``,r=t.get(`workspace`);if(!r||!/^\d+$/.test(n)||!Number.isSafeInteger(Number(n))||Number(n)<=0)return null;let i=t.get(`section`);return{workspaceId:r,documentId:Number(n),section:LL.includes(i)?i:`view`,maximized:t.get(`fullscreen`)===`1`}}function zL(e){let t=new URLSearchParams({document:String(e.documentId),workspace:e.workspaceId});return e.section!==`view`&&t.set(`section`,e.section),e.maximized&&t.set(`fullscreen`,`1`),`#${t}`}function BL({children:e}){let t=vn(),n=ft(),r=(0,X.useMemo)(()=>RL(t.hash),[t.hash]),i=r?.workspaceId,a=r?.documentId,o=i&&a?JSON.stringify([i,a]):null,[s,c]=(0,X.useState)(0),[l,u]=(0,X.useState)(null),d=l?.key===o&&l?.revision===s?l:null;(0,X.useEffect)(()=>{if(!o||!i||!a||d)return;let e=!1;return xc(i,a).then(t=>{e||u({key:o,revision:s,document:t,error:t?void 0:`Document not found.`})}).catch(t=>{e||u({key:o,revision:s,document:null,error:t?.statusCode===404?`Document not found.`:`Unable to load this document.`})}),()=>{e=!0}},[o,i,a,s,d]);let f=(0,X.useCallback)((e,r)=>{u({key:JSON.stringify([r,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:zL({workspaceId:r,documentId:e.id,section:`view`,maximized:!1})},{state:t.state})},[n,t.pathname,t.search,t.state,s]),p=(0,X.useCallback)(()=>{r&&n({pathname:t.pathname,search:t.search,hash:``},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),m=(0,X.useCallback)((e,i)=>{r&&(u({key:JSON.stringify([i,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:zL({...r,workspaceId:i,documentId:e.id})},{replace:!0,state:t.state}))},[r,s,n,t.pathname,t.search,t.state]),h=(0,X.useCallback)(e=>{r&&n({pathname:t.pathname,search:t.search,hash:zL({...r,...e})},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),g=(0,X.useCallback)(()=>c(e=>e+1),[]),_=(0,X.useMemo)(()=>({entry:d?.document&&i?{document:d.document,workspaceId:i}:null,location:r,loading:!!r&&!d,error:d?.error,open:f,replace:m,close:p,update:h,retry:g}),[d,i,r,f,m,p,h,g]);return(0,Z.jsx)(ge.Provider,{value:_,children:e})}function VL({children:e}){let[t,n]=(0,X.useState)(null),r=(0,X.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,X.useCallback)(()=>n(null),[]),a=(0,X.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,Z.jsxs)(U.Provider,{value:a,children:[e,(0,Z.jsx)(Me,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var HL={key:`desk`,label:`Desk`,main:`/`,mainExpanded:!1,entries:[]},UL=0,WL=()=>`c${++UL}`;function GL(e,t){return e.kind===`route`&&t.kind===`route`?e.location===t.location:e.kind===`document`&&t.kind===`document`&&e.document.id===t.document.id&&e.workspaceId===t.workspaceId}function KL({children:e}){let t=vn(),n=ft(),[r,i]=(0,X.useState)([HL]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(S),l=(0,X.useRef)(r),u=(0,X.useRef)(a),d=(0,X.useRef)(s);(0,X.useEffect)(()=>{l.current=r,u.current=a,d.current=s},[r,a,s]);let f=(0,X.useCallback)((e,t)=>{let n=l.current.slice();n[e]=t,l.current=n,i(n)},[]),p=(0,X.useCallback)(e=>{let t=u.current,n=l.current[t];n&&f(t,e(n))},[f]),m=t.pathname+t.search;(0,X.useEffect)(()=>{p(e=>e.main===m?e:{...e,main:m})},[m,p]);let h=(0,X.useCallback)(e=>{let t=l.current[u.current];if(!t)return;let n=t.entries.find(t=>GL(e,t));if(n){c(n.id);return}let r={...e,id:WL()},i=t.entries.findIndex(e=>e.id===d.current),a=t.entries.slice();a.splice(i>=0?i+1:0,0,r),p(e=>({...e,entries:a})),d.current=r.id,c(r.id)},[p]),g=(0,X.useCallback)((e,t)=>{h({kind:`document`,document:e,workspaceId:t})},[h]),_=(0,X.useCallback)((e,t)=>{let n=`document-preview`;p(r=>{let i=r.entries.find(e=>e.id===n),a={kind:`document`,id:n,document:e,workspaceId:t,expanded:i?.expanded};return{...r,entries:[a,...r.entries.filter(e=>e.id!==n)]}}),d.current=n,c(n)},[p]),v=(0,X.useCallback)(e=>{p(t=>({...t,entries:t.entries.filter(t=>t.id!==e)})),c(t=>t===e?S:t)},[p]),y=(0,X.useCallback)((e,t)=>{p(n=>({...n,entries:n.entries.map(n=>n.id===e&&n.kind===`route`?{...n,location:t}:n)}))},[p]),b=(0,X.useCallback)(e=>{p(t=>e===`main`?{...t,mainExpanded:!t.mainExpanded}:{...t,entries:t.entries.map(t=>t.id===e?{...t,expanded:!t.expanded}:t)})},[p]),x=(0,X.useCallback)(e=>{let t=l.current[e];t&&(u.current=e,o(e),c(S),n(t.main))},[n]),C=(0,X.useCallback)((e,t,n)=>{let r=l.current.findIndex(t=>t.key===e);if(r>=0){x(r);return}let a=[...l.current,{key:e,label:t,main:n,mainExpanded:!1,entries:[]}];l.current=a,i(a),x(a.length-1)},[x]),w=(0,X.useCallback)(e=>{x(u.current+e)},[x]),T=(0,X.useCallback)(e=>{let t=l.current.findIndex(t=>t.key===e);if(t<=0)return;let n=l.current.filter(t=>t.key!==e);l.current=n,i(n);let r=u.current;r===t?x(Math.min(t,n.length-1)):r>t&&(u.current=r-1,o(r-1))},[x]),E=(0,X.useMemo)(()=>({rows:r,activeRow:a,focus:s,setFocus:c,openCanvas:h,openDocument:g,closeCanvas:v,navigateCanvas:y,toggleExpanded:b,activateRow:C,moveRow:w,closeRow:T}),[r,a,s,h,g,v,y,b,C,w,T]),D=(0,X.useMemo)(()=>({entry:null,open:g,preview:_,close:()=>{}}),[g,_]);return(0,Z.jsx)(It.Provider,{value:E,children:(0,Z.jsx)(ge.Provider,{value:D,children:e})})}function qL(e){return Yt(typeof e==`string`?Rt(e):e)}function JL({location:e,onNavigate:t}){let n=(0,X.useMemo)(()=>{let t=Rt(e);return{pathname:t.pathname||`/`,search:t.search||``,hash:t.hash||``,state:null,key:e}},[e]),r=(0,X.useMemo)(()=>({basename:`/`,static:!1,useTransitions:void 0,future:{},navigator:{createHref:qL,go:()=>{},push:e=>t(qL(e)),replace:e=>t(qL(e))}}),[t]);return(0,Z.jsx)(mn.Provider,{value:r,children:(0,Z.jsx)(v.Provider,{value:{location:n,navigationType:We.Push},children:(0,Z.jsx)(kt.Provider,{value:{outlet:null,matches:[],isDataRoute:!1},children:(0,Z.jsx)(nt,{children:aF})})})})}var YL=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,XL=420,ZL=e=>e<=0?0:e>=1?1:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2;function QL(e,t,n){if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return e.scrollLeft=t,n?.(),()=>{};let r=e.scrollLeft,i=t-r;if(Math.abs(i)<1)return n?.(),()=>{};let a=e.style.scrollSnapType;e.style.scrollSnapType=`none`;let o=performance.now(),s=0,c=t=>{let l=Math.min(1,(t-o)/XL);e.scrollLeft=r+i*ZL(l),l<1?s=requestAnimationFrame(c):(e.style.scrollSnapType=a,n?.())};return s=requestAnimationFrame(c),()=>{cancelAnimationFrame(s),e.style.scrollSnapType=a}}function $L(e,t){let n=parseFloat(getComputedStyle(e).gap)||0,r=t.getBoundingClientRect().left-e.getBoundingClientRect().left+e.scrollLeft,i=r+t.offsetWidth,a=e.scrollLeft,o=a+e.clientWidth;return r<a?Math.max(0,r-n):i>o?i+n-e.clientWidth:a}function eR({section:e}){return e===`contexts`?(0,Z.jsx)(IF,{}):e===`workspaces`?(0,Z.jsx)(iI,{}):e===`agents`?(0,Z.jsx)(PI,{}):e===`admin`?(0,Z.jsx)(BI,{}):e===`apps`?(0,Z.jsx)(rw,{}):e===`settings`?(0,Z.jsx)(BI,{}):null}function tR(e,t,n){if(e?.kind===`document`)return Ho(e.document).title;let r=(e?.kind===`route`?e.location:t).split(/[?#]/)[0];if(r===`/settings`)return`Settings`;let i=SC.flatMap(e=>[...e.items]).find(e=>e.path===r);if(i)return i.label;let a=r.split(`/`).filter(Boolean);if(a.length===0)return`Desk`;if(a[0]===`workspaces`&&a.length===2){let e=decodeURIComponent(a[1]),t=n.find(t=>t.id===e)??n.find(t=>t.name===e);return t?.label||t?.name||`Workspace`}return decodeURIComponent(a[a.length-1])}function nR({id:e,title:t,expanded:n,focused:r,onFocus:i,onToggleExpanded:a,onClose:o,badge:s,contentHeader:c,children:l}){let u=w();return(0,Z.jsxs)(`section`,{"data-reader-pane":c?!0:void 0,style:c&&!n?{"--reader-width":`${u??420}px`,...u?{transition:`none`}:{}}:void 0,"data-strip-col":e,className:K(`strip-canvas surface-sheet relative`,n&&`strip-canvas--wide`,r&&`strip-canvas--focused`),onPointerDownCapture:()=>i(e),"aria-label":t,children:[c&&!n&&(0,Z.jsx)(je,{edge:`right`}),!c&&(0,Z.jsxs)(`header`,{className:`strip-canvas-bar`,children:[s&&(0,Z.jsx)(`span`,{className:`strip-row-label`,children:s}),(0,Z.jsx)(`span`,{className:`strip-canvas-title`,title:t,children:t}),(0,Z.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:n?`Card size`:`Expand to full width`,"aria-pressed":n,onClick:()=>a(e),children:n?(0,Z.jsx)(ei,{className:`size-3.5`}):(0,Z.jsx)(ba,{className:`size-3.5`})}),o&&(0,Z.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:s?`Close row`:`Close canvas`,onClick:()=>o(e),children:(0,Z.jsx)(vr,{className:`size-3.5`})})]}),(0,Z.jsx)(`div`,{className:`strip-canvas-body`,children:l})]})}function rR(e){return K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!GI(e)&&!WI(e)&&`p-page`)}function iR({row:e,pathname:t,rowLabel:n,onCloseRow:r,workspaces:i}){let{focus:a,setFocus:o,toggleExpanded:s,closeCanvas:c,navigateCanvas:l}=Nt(),u=(0,X.useCallback)(e=>t=>l(e,t),[l]);return(0,Z.jsxs)(Z.Fragment,{children:[t===`/`?(0,Z.jsx)(`div`,{hidden:!0,children:(0,Z.jsx)(Gt,{})}):(0,Z.jsx)(nR,{id:S,title:tR(null,t,i),expanded:e.mainExpanded,focused:a===S,onFocus:o,onToggleExpanded:s,badge:n,onClose:r,children:(0,Z.jsx)(`main`,{id:`content-area`,className:rR(t),children:(0,Z.jsx)(Gt,{})})}),e.entries.map(e=>(0,Z.jsx)(nR,{id:e.id,title:tR(e,t,i),expanded:!!e.expanded,focused:a===e.id,onFocus:o,onToggleExpanded:s,contentHeader:e.kind===`document`,onClose:c,children:e.kind===`route`?(0,Z.jsx)(`div`,{className:rR(e.location.split(`?`)[0]),children:(0,Z.jsx)(JL,{location:e.location,onNavigate:u(e.id)})}):(0,Z.jsx)(`div`,{className:`flex flex-1 min-h-0 min-w-0 items-stretch`,children:(0,Z.jsx)(O,{entry:e,onClose:()=>c(e.id),frame:{expanded:!!e.expanded,onToggleExpanded:()=>s(e.id)}})})},e.id))]})}function aR({row:e,workspaces:t}){return(0,Z.jsxs)(`div`,{className:`strip-ghost-row`,"aria-hidden":!0,children:[(0,Z.jsx)(`span`,{className:`strip-ghost-chip strip-ghost-chip--main`,children:tR(null,e.main,t)}),e.entries.map(n=>(0,Z.jsx)(`span`,{className:`strip-ghost-chip`,children:tR(n,e.main,t)},n.id))]})}function oR(){let{state:e,closeM1:t,closeM2:n}=qC(),[r,i]=(0,X.useState)(280),{rows:a,activeRow:o,focus:s,setFocus:c,moveRow:l,closeRow:u}=Nt(),{pathname:d}=vn(),{workspaces:f}=nI(d.startsWith(`/workspaces/`)||a.some(e=>e.main.startsWith(`/workspaces/`)||e.entries.some(e=>e.kind===`route`&&e.location.startsWith(`/workspaces/`)))),p=UC(),m=(0,X.useRef)(null);Ae(t,e.m1Open&&!e.m2Open),Ae(n,e.m2Open),(0,X.useLayoutEffect)(()=>{let e=m.current;if(!e)return;let t=()=>{e.style.setProperty(`--strip-w`,`${e.clientWidth}px`),e.style.setProperty(`--strip-h`,`${e.clientHeight}px`)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let h=(0,X.useRef)(e.m1Open);(0,X.useEffect)(()=>{e.m1Open&&!h.current&&!e.m2Open&&c(`m1`),h.current=e.m1Open},[e.m1Open,e.m2Open,c]);let g=(0,X.useRef)(e.m2Open);(0,X.useEffect)(()=>{e.m2Open&&!g.current&&c(`m2`),!e.m2Open&&g.current&&s===`m2`&&c(e.m1Open?`m1`:S),g.current=e.m2Open},[e.m2Open,e.m1Open,s,c]),(0,X.useEffect)(()=>{!e.m1Open&&s===`m1`&&c(S)},[e.m1Open,s,c]),(0,X.useEffect)(()=>{let e=m.current,t=e?.querySelector(`[data-strip-col="${CSS.escape(s)}"]`);if(!(!e||!t))return QL(e,$L(e,t))},[s,a,o,e.m1Open,e.m2Open]);let _=(0,X.useCallback)(()=>{let t=a[o];return[...e.m1Open?[`m1`]:[],...e.m2Open?[`m2`]:[],...d===`/`?[]:[S],...t?t.entries.map(e=>e.id):[]]},[a,o,e.m1Open,e.m2Open,d]);return(0,X.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||!e.key.startsWith(`Arrow`)||!WC(e,p))return;let t=e.target;if(!(t?.closest(YL)||t?.closest(`[role="dialog"]`))){if(e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=_(),n=t[Math.max(0,t.indexOf(s))+(e.key===`ArrowRight`?1:-1)];if(!n)return;e.preventDefault(),c(n)}else(e.key===`ArrowUp`||e.key===`ArrowDown`)&&a.length>1&&(e.preventDefault(),l(e.key===`ArrowDown`?1:-1))}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[_,s,c,l,a.length,p]),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`strip-shell flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(AF,{}),(0,Z.jsxs)(`div`,{ref:m,className:`strip-scroller`,style:{"--strip-menu-space":`${(e.m1Open?280:0)+(e.m2Open?r:0)}px`},children:[e.m1Open&&(0,Z.jsx)(`div`,{"data-strip-col":`m1`,className:K(`strip-col strip-menu-col`,s===`m1`&&`strip-col--focused`),onPointerDownCapture:()=>c(`m1`),children:(0,Z.jsx)(eR,{section:e.activeSection})}),e.m2Open&&(0,Z.jsxs)(`div`,{"data-strip-col":`m2`,style:{width:r,position:`relative`},className:K(`strip-col strip-menu-col`,s===`m2`&&`strip-col--focused`),onPointerDownCapture:()=>c(`m2`),children:[(0,Z.jsx)(HI,{}),(0,Z.jsx)(NF,{width:r,onResize:i})]}),(0,Z.jsx)(`div`,{className:`strip-rows`,style:{transform:`translateY(${-o*100}%)`},children:a.map((e,t)=>(0,Z.jsx)(`div`,{className:K(`strip-row`,t===o&&`strip-row--active`),children:(0,Z.jsx)(`div`,{className:`strip-row-canvases`,children:t===o?(0,Z.jsx)(iR,{row:e,workspaces:f,pathname:d,rowLabel:a.length>1?e.label:void 0,onCloseRow:t>0?()=>u(e.key):void 0}):(0,Z.jsx)(aR,{row:e,workspaces:f})})},e.key))})]}),(0,Z.jsx)(gL,{}),(0,Z.jsx)(FL,{})]}),(0,Z.jsx)(YI,{}),(0,Z.jsx)(kF,{}),(0,Z.jsx)(IL,{})]})}function sR(){let e=PC();return(0,Z.jsx)(pF,{children:(0,Z.jsx)(QI,{children:(0,Z.jsx)(fS,{children:(0,Z.jsx)(Vx,{children:(0,Z.jsx)(BL,{children:e===`strip`?(0,Z.jsx)(KL,{children:(0,Z.jsx)(VL,{children:(0,Z.jsx)(oR,{})})}):(0,Z.jsxs)(VL,{children:[(0,Z.jsxs)(`div`,{className:`flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(AF,{}),(0,Z.jsx)(UI,{}),(0,Z.jsx)(JI,{}),(0,Z.jsx)(gL,{}),(0,Z.jsx)(FL,{})]}),(0,Z.jsx)(YI,{}),(0,Z.jsx)(kF,{}),(0,Z.jsx)(IL,{})]})})})})})})}var cR=da,lR=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Ii,{ref:n,className:K(`fixed top-0 right-0 z-toast flex max-h-screen w-full flex-col-reverse gap-2 p-4 sm:right-0 sm:flex-col md:max-w-[420px]`,e),...t}));lR.displayName=Ii.displayName;var uR=Qa(`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-elevation-3 transition-all duration-normal 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`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),dR=X.forwardRef(({className:e,variant:t,...n},r)=>(0,Z.jsx)(na,{ref:r,className:K(uR({variant:t}),e),...n}));dR.displayName=na.displayName;var fR=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Oa,{ref:n,className:K(`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}));fR.displayName=Oa.displayName;var pR=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(wi,{ref:n,className:K(`absolute right-2 top-2 rounded-md p-1 text-foreground/50 reveal-on-hover hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:text-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-destructive`,e),"toast-close":``,...t,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})}));pR.displayName=wi.displayName;var mR=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Vi,{ref:n,className:K(`text-sm font-semibold`,e),...t}));mR.displayName=Vi.displayName;var hR=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Mi,{ref:n,className:K(`text-sm opacity-90`,e),...t}));hR.displayName=Mi.displayName;var gR=`canvas-notifications`,_R=`notifications`,vR=`canvas:notification-history`,yR,bR;function xR(){try{let e=localStorage.getItem(`authToken`);if(e){let t=eo(e),n=t.sub||t.userId||t.id||t.email;if(typeof n==`string`||typeof n==`number`)return JSON.stringify([t.iss||``,n])}}catch{}return`anonymous`}function SR(){return yR||=new Promise((e,t)=>{let n=indexedDB.open(gR,1);n.onupgradeneeded=()=>{n.result.createObjectStore(_R,{keyPath:[`account`,`id`]}).createIndex(`account`,`account`)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),yR=void 0},e(t)},n.onerror=()=>t(n.error)}).catch(e=>{throw yR=void 0,e}),yR}function CR(){return!bR&&typeof BroadcastChannel<`u`&&(bR=new BroadcastChannel(vR),bR.onmessage=e=>window.dispatchEvent(new CustomEvent(vR,{detail:e.data}))),bR}function wR(e,t=!1){let n={account:e,error:t};window.dispatchEvent(new CustomEvent(vR,{detail:n})),t||CR()?.postMessage(n)}function TR(e,t){CR();let n=n=>{let r=n.detail;r?.account===e&&t(!!r.error)};return window.addEventListener(vR,n),()=>window.removeEventListener(vR,n)}async function ER(e){let t=await SR();return new Promise((n,r)=>{let i=t.transaction(_R,`readonly`),a=i.objectStore(_R).index(`account`).getAll(e);i.oncomplete=()=>n(a.result.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)||e.id.localeCompare(t.id))),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error)})}async function DR(e,t){try{let n=await SR();await new Promise((e,r)=>{let i=n.transaction(_R,`readwrite`);i.oncomplete=()=>e(),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error),t(i.objectStore(_R))}),wR(e)}catch(t){throw wR(e,!0),t}}function OR(e,t){return DR(e,n=>{let r=n.get([e,t.id]);r.onsuccess=()=>{r.result||n.put({...t,account:e})}})}function kR(e,t,n){return DR(e,r=>{let i=r.get([e,t]);i.onsuccess=()=>{i.result&&r.put({...i.result,...n})}})}function AR(e,t){return DR(e,n=>{n.delete([e,t])})}function jR(e){return DR(e,t=>{let n=t.index(`account`).openKeyCursor(e);n.onsuccess=()=>{n.result&&(t.delete(n.result.primaryKey),n.result.continue())}})}function MR({children:e}){let[t,n]=(0,X.useState)([]),r=(0,X.useRef)(new Set),i=(0,X.useCallback)((e,t=!0)=>{if(ao(e.description)||ao(e.title))return;let i=`${e.title}:${e.description??``}`;if(t&&(e.historyId||!r.current.has(i))){let t=e.timestamp?new Date(e.timestamp):new Date;OR(xR(),{id:e.historyId||crypto.randomUUID(),title:e.title,text:e.description||``,timestamp:Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString(),status:e.variant===`destructive`?`error`:`info`}).catch(()=>{})}if(r.current.has(i))return;r.current.add(i);let a=Math.random().toString(36).substring(2,9);n(t=>[...t,{...e,id:a}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==a)),r.current.delete(i)},5e3)},[]),a=(0,X.useCallback)(e=>{let t=crypto.randomUUID(),r=xR();OR(r,{id:t,title:e.title,text:e.description||``,timestamp:new Date().toISOString(),status:`started`}).catch(()=>{}),n(n=>[...n,{...e,id:t,busy:!0}]);let a=!1,o=(e,o=!1)=>{a||(a=!0,n(e=>e.filter(e=>e.id!==t)),kR(r,t,{...e?{title:e.title,text:e.description||``}:{},status:o||e?.variant===`destructive`?`error`:`completed`}).catch(()=>{}),e&&i(e,!1))};return{update:e=>{a||n(n=>n.map(n=>n.id===t?{...n,...e}:n))},done:e=>o(e),fail:e=>o(e,!0)}},[i]),o=(0,X.useMemo)(()=>({showToast:i,showProgress:a}),[i,a]);return(0,Z.jsx)(Co.Provider,{value:o,children:(0,Z.jsxs)(cR,{children:[e,t.map(e=>(0,Z.jsxs)(dR,{variant:e.variant,duration:e.busy?1/0:void 0,children:[(0,Z.jsxs)(`div`,{className:`grid gap-1`,children:[(0,Z.jsxs)(mR,{className:`flex items-center gap-2`,children:[e.busy&&(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 shrink-0 animate-spin`}),e.title]}),e.description!=null&&(0,Z.jsx)(hR,{children:e.description})]}),e.busy&&e.action&&(0,Z.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-md border px-2 py-1 text-xs hover:bg-secondary`,onClick:e.action.onClick,children:e.action.label}),!e.busy&&(0,Z.jsx)(pR,{})]},e.id)),(0,Z.jsx)(lR,{})]})})}function NR({children:e}){let[t]=(0,X.useState)(xR),[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),{showToast:c}=wo();(0,X.useEffect)(()=>{let e=!0,n=0,i=async()=>{let i=++n;try{let o=await ER(t);e&&i===n&&(r(o),a(!1))}catch{e&&(s(!0),a(!1))}},o=TR(t,e=>{s(e),e||i()});return i(),()=>{e=!1,o()}},[t]),(0,X.useEffect)(()=>B.on(`notification`,e=>{let t=e;!t||![`string`,`number`].includes(typeof t.id)||typeof t.text!=`string`||!t.text||c({title:`Notification`,description:t.text,historyId:`message:${t.id}`,timestamp:typeof t.timestamp==`string`?t.timestamp:void 0})}),[c]);let l=(0,X.useCallback)(async()=>{try{await jR(t)}catch{}},[t]),u=(0,X.useCallback)(async e=>{try{await AR(t,e)}catch{}},[t]);return(0,Z.jsx)(_L.Provider,{value:{notifications:n,loading:i,storageError:o,clear:l,remove:u},children:e})}var PR=e=>`${e.workspaceName}\0${e.treeName}\0${e.path}`;function FR({children:e}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0);(0,X.useEffect)(()=>{let e=!1;return uI().then(t=>{e||n(t)}).catch(()=>{e||n({})}).finally(()=>{e||i(!1)}),()=>{e=!0}},[]);let a=(0,X.useMemo)(()=>t?.home?.pinnedCanvases??[],[t]),[o]=(0,X.useState)(()=>tD(uI,dI,n)),s=(0,X.useCallback)(e=>a.some(t=>PR(t)===PR(e)),[a]),c=(0,X.useCallback)(async e=>{let t=crypto.randomUUID();await o(n=>n.some(t=>PR(t)===PR(e))?n:[...n,{id:t,...e}])},[o]),l=(0,X.useCallback)(async e=>{await o(t=>t.filter(t=>t.id!==e))},[o]),u=(0,X.useCallback)(async(e,t)=>{await o(n=>n.map(n=>n.id===e?{...n,minimized:t}:n))},[o]),d=(0,X.useCallback)(async(e,t)=>{await o(n=>{let r=n.find(t=>t.id===e);if(!r||e===t)return n;let i=n.filter(t=>t.id!==e),a=t===null?i.length:i.findIndex(e=>e.id===t);return a===-1?n:[...i.slice(0,a),r,...i.slice(a)]})},[o]),f=(0,X.useMemo)(()=>({pins:a,isLoading:r,isPinned:s,pin:c,unpin:l,movePin:d,setMinimized:u}),[a,r,s,c,l,d,u]);return(0,Z.jsx)(XT.Provider,{value:f,children:e})}var IR=(0,X.lazy)(()=>g(()=>import(`./NextShell-Byg6OtC2.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])));function LR(){let{showToast:e}=wo();return(0,X.useEffect)(()=>{so((t,n)=>{e({title:`Error`,description:n?`${t.message} (${n})`:t.message,variant:`destructive`})})},[e]),(0,X.useEffect)(()=>_F(),[]),(0,Z.jsxs)(Ye,{children:[(0,Z.jsx)(uF,{}),(0,Z.jsx)($f,{}),(0,Z.jsxs)(nt,{children:[(0,Z.jsx)(sn,{path:`/login`,element:(0,Z.jsx)(wu,{children:(0,Z.jsx)(bu,{})})}),(0,Z.jsx)(sn,{path:`/register`,element:(0,Z.jsx)(wu,{children:(0,Z.jsx)(xu,{})})}),(0,Z.jsx)(sn,{path:`/auth/google/callback`,element:(0,Z.jsx)(wu,{children:(0,Z.jsx)(Su,{})})}),(0,Z.jsx)(sn,{path:`/pub/c/:code`,element:(0,Z.jsx)(Vf,{})}),(0,Z.jsx)(sn,{path:`/next/*`,element:(0,Z.jsx)(Cu,{children:(0,Z.jsx)(X.Suspense,{fallback:null,children:(0,Z.jsx)(IR,{})})})}),(0,Z.jsx)(sn,{path:`/`,element:(0,Z.jsx)(Cu,{children:(0,Z.jsx)(NR,{children:(0,Z.jsx)(FR,{children:(0,Z.jsx)(sR,{})})})}),children:aF}),(0,Z.jsx)(sn,{path:`*`,element:(0,Z.jsx)(ht,{to:`/`,replace:!0})})]})]})}function RR(){return(0,Z.jsx)(Pk,{children:(0,Z.jsx)(MR,{children:(0,Z.jsx)(LR,{})})})}QO(),WO(),(0,Rl.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(X.StrictMode,{children:(0,Z.jsx)(RR,{})}));
|