@augmentd-labs/canvas-web 2.26.0 → 2.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdf-Ciz5_WNq.js","assets/preload-helper-Czpn1I53.js","assets/markdown-html-XoABNf32.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BQnKd3jw.js","assets/sanitize-DrVcFY1Q.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/markdown-html-DtQ7-esK.css","assets/SketchEditor-CCh9_zKT.js","assets/react-BzqgEMSQ.js","assets/ui-NWo4bzrd.js","assets/utils-BxVxyehK.js","assets/alert-dialog-CDKOX-MP.js","assets/utils-2pl1SbIp.js","assets/blobs-NdFfDbao.js","assets/workspace-Dh0Dd0r4.js","assets/sha256-BhArj2aT.js","assets/chunk-K2UTITRG-zQFDOW3Q.js","assets/chunk-SRAX5OIU-Dhm3gOdh.js","assets/chunk-6U3AYISY-C6-Mtja1.js","assets/chunk-Z3N5DIM6-D9TMVU7m.js","assets/EditorOverlay-DqlaCJe7.js","assets/SketchEditor-DtRVLazd.css","assets/TextDocumentEditor-S5KKs7E_.js","assets/text-documents-iLXAAr-8.js","assets/LocationTab-BONJQfYM.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/subtree-transfer-dialog-CSjPDp4d.js","assets/NextShell-CX994BbA.js","assets/NextShell-BT6-_CFY.css"])))=>i.map(i=>d[i]);
2
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,$r as y,$t as b,An as x,Ar as S,At as C,B as w,Bn as T,Br as E,Bt as D,C as O,Cn as k,Cr as A,Ct as j,Dn as M,Dr as N,Dt as P,En as F,Er as I,Et as L,F as R,Fr as z,Ft as ee,G as te,Gn as ne,Gr as B,Gt as re,H as ie,Hn as ae,Hr as oe,Ht as V,I as H,Ir as U,It as se,J as W,Jn as ce,Jr as le,Jt as ue,K as de,Kn as fe,Kr as pe,Kt as me,L as G,Ln as he,Lr as ge,Lt as _e,Mn as ve,Mr as K,Mt as q,Nn as ye,Nr as be,Nt as xe,On as Se,Or as Ce,Ot as we,P as Te,Pn as Ee,Pr as De,Pt as Oe,Q as ke,Qn as Ae,Qr as je,Qt as Me,R as Ne,Rn as Pe,Rr as Fe,Rt as Ie,S as Le,Sn as Re,Sr as ze,St as Be,Tn as Ve,Tr as He,Tt as Ue,U as We,Un as Ge,Ur as Ke,Ut as qe,V as Je,Vn as Ye,Vr as Xe,Vt as Ze,W as Qe,Wn as $e,Wr as et,Wt as tt,X as nt,Xn as rt,Xr as it,Xt as at,Y as ot,Yn as st,Yr as ct,Yt as lt,Z as ut,Zn as dt,Zr as ft,Zt as pt,_ as mt,_i as ht,_n as gt,_r as _t,_t as vt,ai as yt,an as bt,ar as xt,at as St,b as Ct,bn as wt,br as Tt,bt as Et,ci as Dt,cn as Ot,cr as kt,ct as At,d as jt,di as Mt,dr as Nt,dt as Pt,ei as Ft,en as It,er as Lt,et as Rt,f as zt,fi as Bt,fn as Vt,fr as Ht,ft as Ut,g as Wt,gi as Gt,gn as Kt,gr as qt,gt as Jt,h as Yt,hi as Xt,hn as Zt,hr as Qt,ht as $t,ii as en,in as tn,ir as nn,it as rn,jn as an,jr as on,jt as sn,kn as cn,kr as ln,kt as un,li as dn,ln as fn,lr as pn,lt as mn,m as hn,mi as gn,mn as _n,mr as vn,mt as yn,ni as bn,nn as xn,nr as Sn,nt as Cn,oi as wn,on as Tn,or as En,ot as Dn,p as On,pi as kn,pr as An,pt as jn,q as Mn,qn as Nn,qr as Pn,qt as Fn,ri as In,rn as Ln,rr as Rn,rt as zn,si as Bn,sn as Vn,sr as Hn,st as Un,tn as Wn,tr as Gn,tt as Kn,u as qn,ui as Jn,un as Yn,ur as Xn,ut as Zn,v as Qn,vn as $n,vr as er,vt as tr,w as nr,wr as rr,wt as ir,x as ar,xn as or,xr as sr,xt as cr,y as lr,yn as ur,yr as dr,yt as fr,z as pr,zn as mr,zr as hr,zt as gr}from"./ui-NWo4bzrd.js";import{i as _r,n as vr,r as yr}from"./utils-BxVxyehK.js";import{n as br,t as J}from"./utils-2pl1SbIp.js";import{_ as xr,a as Sr,b as Y,c as Cr,d as wr,f as Tr,g as Er,h as Dr,i as Or,l as kr,m as Ar,n as jr,o as Mr,p as Nr,r as Pr,s as Fr,t as Ir,u as X,v as Lr,x as Z,y as Rr}from"./alert-dialog-CDKOX-MP.js";import{t as zr}from"./socket-hM4c-ZSl.js";import{a as Br,c as Vr,i as Hr,n as Ur,o as Wr,s as Gr,t as Kr}from"./blobs-NdFfDbao.js";import{$ as qr,$t as Jr,A as Yr,An as Xr,At as Zr,B as Qr,Bn as $r,Bt as ei,C as ti,Cn as ni,Ct as ri,D as ii,Dn as ai,Dt as oi,E as si,En as ci,Et as li,F as ui,Fn as di,Ft as fi,G as pi,Gt as mi,H as hi,Hn as gi,Ht as _i,I as vi,It as yi,J as bi,Jt as xi,K as Si,Kt as Ci,L as wi,Ln as Ti,Lt as Ei,M as Di,Mn as Oi,Mt as ki,Nt as Ai,O as ji,On as Mi,Ot as Ni,P as Pi,Pt as Fi,Q as Ii,Qt as Li,R as Ri,Rt as zi,S as Bi,Sn as Vi,St as Hi,T as Ui,Tn as Wi,Tt as Gi,U as Ki,Ut as qi,V as Ji,Vn as Yi,Vt as Xi,W as Zi,Wt as Qi,X as $i,Xt as ea,Y as ta,Yt as na,Z as ra,_ as ia,_n as aa,_t as oa,a as sa,an as ca,at as la,b as ua,bn as da,bt as fa,c as pa,cn as ma,ct as ha,d as ga,dn as _a,dt as va,en as ya,et as ba,f as xa,fn as Sa,ft as Ca,g as wa,gn as Ta,gt as Ea,h as Da,hn as Oa,ht as ka,i as Aa,in as ja,it as Ma,j as Na,jn as Pa,jt as Fa,k as Ia,kn as La,kt as Ra,l as za,ln as Ba,lt as Va,m as Ha,mn as Ua,mt as Wa,n as Ga,nn as Ka,nt as qa,o as Ja,on as Ya,ot as Xa,p as Za,pn as Qa,pt as $a,q as eo,qt as to,r as no,rn as ro,rt as io,s as ao,sn as oo,st as so,t as co,tn as lo,tt as uo,u as fo,un as po,ut as mo,v as ho,vn as go,vt as _o,w as vo,wt as yo,x as bo,xn as xo,xt as So,y as Co,yn as wo,yt as To,z as Eo,zn as Do,zt as Oo}from"./workspace-Dh0Dd0r4.js";import{_ as ko,a as Ao,c as jo,d as Mo,f as No,g as Po,h as Fo,i as Io,l as Lo,m as Ro,n as zo,o as Bo,p as Vo,r as Ho,s as Uo,t as Wo,u as Go,v as Ko,y as qo}from"./text-documents-iLXAAr-8.js";import{n as Jo,t as Yo}from"./map-BxCwdK0d.js";import{t as Xo}from"./search-COMZIxA7.js";import{A as Zo,B as Qo,C as $o,D as es,E as ts,F as ns,H as rs,I as is,L as as,M as os,N as ss,O as cs,P as ls,R as us,S as ds,T as fs,V as ps,_ as ms,a as hs,b as gs,c as _s,d as vs,f as ys,g as bs,h as xs,i as Ss,j as Cs,k as ws,l as Ts,m as Es,o as Ds,p as Os,r as ks,s as As,t as js,u as Ms,v as Ns,w as Ps,x as Fs,y as Is,z as Ls}from"./sha256-BhArj2aT.js";import{t as Rs}from"./sanitize-DrVcFY1Q.js";import{t as zs}from"./markdown-it-DRESbtwK.js";import{n as Bs,t as Vs}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 Q=n(d(),1),Hs=m(),Us=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,Ws=/^[\\/]{2}/;function Gs(e,t){return t+e.replace(/\\/g,`/`)}var Ks=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(Ks||{}),qs=`popstate`;function Js(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function Ys(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return ec(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:tc(t)}return rc(t,n,null,e)}function Xs(e,t){if(e===!1||e==null)throw Error(t)}function Zs(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function Qs(){return Math.random().toString(36).substring(2,10)}function $s(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function ec(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?nc(t):t,state:n,key:t&&t.key||r||Qs(),mask:i}}function tc({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function nc(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function rc(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=Js(e)?e:ec(h.location,e,t);n&&n(r,e),l=u()+1;let d=$s(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=Js(e)?e:ec(h.location,e,t);n&&n(r,e),l=u();let i=$s(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return ic(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(qs,d),c=e,()=>{i.removeEventListener(qs,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function ic(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Xs(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:tc(t);return i=i.replace(/ $/,`%20`),!n&&Ws.test(i)&&(i=r+i),new URL(i,r)}function ac(e,t,n=`/`){return oc(e,t,n,!1)}function oc(e,t,n,r,i){let a=Tc((typeof t==`string`?nc(t):t).pathname||`/`,n);if(a==null)return null;let o=i??sc(e),s=null,c=wc(a);for(let e=0;s==null&&e<o.length;++e)s=bc(o[e],c,r);return s}function sc(e){let t=cc(e);return uc(t),t}function cc(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;Xs(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=Nc([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Xs(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),cc(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:vc(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Cc(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of lc(e.path))a(e,t,!0,n)}),t}function lc(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=lc(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function uc(e){e.sort((e,t)=>e.score===t.score?yc(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var dc=/^:[\w-]+$/,fc=3,pc=2,mc=1,hc=10,gc=-2,_c=e=>e===`*`;function vc(e,t){let n=e.split(`/`),r=n.length;return n.some(_c)&&(r+=gc),t&&(r+=pc),n.filter(e=>!_c(e)).reduce((e,t)=>e+(dc.test(t)?fc:t===``?mc:hc),r)}function yc(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function bc(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?Sc(u,l,s.matcher,s.compiledParams):xc(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=xc({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:Nc([a,d.pathname]),pathnameBase:Fc(Nc([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=Nc([a,d.pathnameBase]))}return o}function xc(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Cc(e.path,e.caseSensitive,e.end);return Sc(e,t,n,r)}function Sc(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function Cc(e,t=!1,n=!0){Zs(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function wc(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return Zs(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Tc(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function Ec(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?nc(e):e,a;return n?(n=Mc(n),a=n.startsWith(`/`)?Dc(n.substring(1),`/`):Dc(n,t)):a=t,{pathname:a,search:Ic(r),hash:Lc(i)}}function Dc(e,t){let n=Pc(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Oc(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function kc(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Ac(e){let t=kc(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function jc(e,t,n,r=!1){let i;typeof e==`string`?i=nc(e):(i={...e},Xs(!i.pathname||!i.pathname.includes(`?`),Oc(`?`,`pathname`,`search`,i)),Xs(!i.pathname||!i.pathname.includes(`#`),Oc(`#`,`pathname`,`hash`,i)),Xs(!i.search||!i.search.includes(`#`),Oc(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=Ec(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Mc=e=>e.replace(/[\\/]{2,}/g,`/`),Nc=e=>Mc(e.join(`/`)),Pc=e=>e.replace(/\/+$/,``),Fc=e=>Pc(e).replace(/^\/*/,`/`),Ic=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Lc=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,Rc=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function zc(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Bc(e){return Nc(e.map(e=>e.route.path).filter(Boolean))||`/`}var Vc=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Hc(e,t){let n=e;if(typeof n!=`string`||!Us.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(Vc)try{let e=new URL(window.location.href),r=Ws.test(n)?new URL(Gs(n,e.protocol)):new URL(n),a=Tc(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{Zs(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var Uc=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Uc);var Wc=[`GET`,...Uc];new Set(Wc);var Gc=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Kc(e){try{return Gc.includes(new URL(e).protocol)}catch{return!1}}var qc=Q.createContext(null);qc.displayName=`DataRouter`;var Jc=Q.createContext(null);Jc.displayName=`DataRouterState`;var Yc=Q.createContext(!1);function Xc(){return Q.useContext(Yc)}var Zc=Q.createContext({isTransitioning:!1});Zc.displayName=`ViewTransition`;var Qc=Q.createContext(new Map);Qc.displayName=`Fetchers`;var $c=Q.createContext(null);$c.displayName=`Await`;var el=Q.createContext(null);el.displayName=`Navigation`;var tl=Q.createContext(null);tl.displayName=`Location`;var nl=Q.createContext({outlet:null,matches:[],isDataRoute:!1});nl.displayName=`Route`;var rl=Q.createContext(null);rl.displayName=`RouteError`;var il=`REACT_ROUTER_ERROR`,al=`REDIRECT`,ol=`ROUTE_ERROR_RESPONSE`;function sl(e){if(e.startsWith(`${il}:${al}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function cl(e){if(e.startsWith(`${il}:${ol}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new Rc(t.status,t.statusText,t.data)}catch{}}function ll(e,{relative:t}={}){Xs(ul(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=Q.useContext(el),{hash:i,pathname:a,search:o}=yl(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:Nc([n,a])),r.createHref({pathname:s,search:o,hash:i})}function ul(){return Q.useContext(tl)!=null}function dl(){return Xs(ul(),`useLocation() may be used only in the context of a <Router> component.`),Q.useContext(tl).location}var fl=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function pl(e){Q.useContext(el).static||Q.useLayoutEffect(e)}function ml(){let{isDataRoute:e}=Q.useContext(nl);return e?Il():hl()}function hl(){Xs(ul(),`useNavigate() may be used only in the context of a <Router> component.`);let e=Q.useContext(qc),{basename:t,navigator:n}=Q.useContext(el),{matches:r}=Q.useContext(nl),{pathname:i}=dl(),a=JSON.stringify(Ac(r)),o=Q.useRef(!1);return pl(()=>{o.current=!0}),Q.useCallback((r,s={})=>{if(Zs(o.current,fl),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=jc(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:Nc([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var gl=Q.createContext(null);function _l(e){let t=Q.useContext(nl).outlet;return Q.useMemo(()=>t&&Q.createElement(gl.Provider,{value:e},t),[t,e])}function vl(){let{matches:e}=Q.useContext(nl);return e[e.length-1]?.params??{}}function yl(e,{relative:t}={}){let{matches:n}=Q.useContext(nl),{pathname:r}=dl(),i=JSON.stringify(Ac(n));return Q.useMemo(()=>jc(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function bl(e,t){return xl(e,t)}function xl(e,t,n){Xs(ul(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=Q.useContext(el),{matches:i}=Q.useContext(nl),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;Rl(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${s}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
3
3
 
4
- Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=dl(),d;if(t){let e=typeof t==`string`?nc(t):t;Xs(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):ac(e,{pathname:p});Zs(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Zs(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=Ol(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Nc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:Nc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?Q.createElement(tl.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function Sl(){let e=Fl(),t=zc(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=Q.createElement(Q.Fragment,null,Q.createElement(`p`,null,`💿 Hey developer 👋`),Q.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,Q.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,Q.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),Q.createElement(Q.Fragment,null,Q.createElement(`h2`,null,`Unexpected Application Error!`),Q.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?Q.createElement(`pre`,{style:i},n):null,o)}var Cl=Q.createElement(Sl,null),wl=class extends Q.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=cl(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:Q.createElement(nl.Provider,{value:this.props.routeContext},Q.createElement(rl.Provider,{value:e,children:this.props.component}));return this.context?Q.createElement(El,{error:e},t):t}};wl.contextType=Yc;var Tl=new WeakMap;function El({children:e,error:t}){let{basename:n}=Q.useContext(el);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=sl(t.digest);if(e){let r=Tl.get(t);if(r)throw r;let i=Hc(e.location,n),a=i.absoluteURL||i.to;if(Kc(a))throw Error(`Invalid redirect location`);if(Vc&&!Tl.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw Tl.set(t,n),n}}return Q.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function Dl({routeContext:e,match:t,children:n}){let r=Q.useContext(qc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),Q.createElement(nl.Provider,{value:e},n)}function Ol(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);Xs(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Bc(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||Cl,o&&(s<0&&c===0?(Rl(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?Q.createElement(n.route.Component,null):n.route.element?n.route.element:e,Q.createElement(Dl,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?Q.createElement(wl,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function kl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Al(e){let t=Q.useContext(qc);return Xs(t,kl(e)),t}function jl(e){let t=Q.useContext(Jc);return Xs(t,kl(e)),t}function Ml(e){let t=Q.useContext(nl);return Xs(t,kl(e)),t}function Nl(e){let t=Ml(e),n=t.matches[t.matches.length-1];return Xs(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Pl(){return Nl(`useRouteId`)}function Fl(){let e=Q.useContext(rl),t=jl(`useRouteError`),n=Nl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Il(){let{router:e}=Al(`useNavigate`),t=Nl(`useNavigate`),n=Q.useRef(!1);return pl(()=>{n.current=!0}),Q.useCallback(async(r,i={})=>{Zs(n.current,fl),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Ll={};function Rl(e,t,n){!t&&!Ll[e]&&(Ll[e]=!0,Zs(!1,n))}Q.memo(zl);function zl({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return xl(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Bl({to:e,replace:t,state:n,relative:r}){Xs(ul(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=Q.useContext(el);Zs(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=Q.useContext(nl),{pathname:o}=dl(),s=ml(),c=jc(e,Ac(a),o,r===`path`),l=JSON.stringify(c);return Q.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function Vl(e){return _l(e.context)}function Hl(e){Xs(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function Ul({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Xs(!ul(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=Q.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=nc(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=Q.useMemo(()=>{let e=Tc(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return Zs(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:Q.createElement(el.Provider,{value:c},Q.createElement(tl.Provider,{children:t,value:h}))}function Wl({children:e,location:t}){return bl(Gl(e),t)}Q.Component;function Gl(e,t=[]){let n=[];return Q.Children.forEach(e,(e,r)=>{if(!Q.isValidElement(e))return;let i=[...t,r];if(e.type===Q.Fragment){n.push.apply(n,Gl(e.props.children,i));return}Xs(e.type===Hl,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Xs(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=Gl(e.props.children,i)),n.push(a)}),n}var Kl=`get`,ql=`application/x-www-form-urlencoded`;function Jl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Yl(e){return Jl(e)&&e.tagName.toLowerCase()===`button`}function Xl(e){return Jl(e)&&e.tagName.toLowerCase()===`form`}function Zl(e){return Jl(e)&&e.tagName.toLowerCase()===`input`}function Ql(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function $l(e,t){return e.button===0&&(!t||t===`_self`)&&!Ql(e)}function eu(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function tu(e,t){let n=eu(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var nu=null;function ru(){if(nu===null)try{new FormData(document.createElement(`form`),0),nu=!1}catch{nu=!0}return nu}var iu=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function au(e){return e!=null&&!iu.has(e)?(Zs(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${ql}"`),null):e}function ou(e,t){let n,r,i,a,o;if(Xl(e)){let o=e.getAttribute(`action`);r=o?Tc(o,t):null,n=e.getAttribute(`method`)||Kl,i=au(e.getAttribute(`enctype`))||ql,a=new FormData(e)}else if(Yl(e)||Zl(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?Tc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Kl,i=au(e.getAttribute(`formenctype`))||au(o.getAttribute(`enctype`))||ql,a=new FormData(o,e),!ru()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(Jl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Kl,r=null,i=ql,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function su(e,t){if(e===!1||e==null)throw Error(t)}function cu(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return i.pathname=n?i.pathname.endsWith(`/`)?`${i.pathname}_.${r}`:`${i.pathname}.${r}`:i.pathname===`/`?`_root.${r}`:t&&Tc(i.pathname,t)===`/`?`${Pc(t)}/_root.${r}`:`${Pc(i.pathname)}.${r}`,i}async function lu(e,t){if(e.id in t)return t[e.id];try{let n=await g(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function uu(e){return e!=null&&typeof e.page==`string`}function du(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function fu(e,t,n){return _u((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await lu(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(du).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function pu(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function mu(e,t,{includeHydrateFallback:n}={}){return hu(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function hu(e){return[...new Set(e)]}function gu(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function _u(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!uu(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(gu(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function vu(){let e=Q.useContext(qc);return su(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function yu(){let e=Q.useContext(Jc);return su(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var bu=Q.createContext(void 0);bu.displayName=`FrameworkContext`;function xu(){let e=Q.useContext(bu);return su(e,`You must render this element inside a <HydratedRouter> element`),e}function Su(e,t){let n=Q.useContext(bu),[r,i]=Q.useState(!1),[a,o]=Q.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=Q.useRef(null);Q.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),Q.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:Cu(s,p),onBlur:Cu(c,m),onMouseEnter:Cu(l,p),onMouseLeave:Cu(u,m),onTouchStart:Cu(d,p)}]:[a,f,{}]:[!1,f,{}]}function Cu(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function wu({page:e,...t}){let n=Xc(),{nonce:r}=xu(),{router:i}=vu(),a=Q.useMemo(()=>ac(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?Q.createElement(Eu,{page:e,matches:a,...t}):Q.createElement(Du,{page:e,matches:a,...t})):null}function Tu(e){let{manifest:t,routeModules:n}=xu(),[r,i]=Q.useState([]);return Q.useEffect(()=>{let r=!1;return fu(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Eu({page:e,matches:t,...n}){let r=dl(),{future:i}=xu(),{basename:a}=vu(),o=Q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=cu(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return Q.createElement(Q.Fragment,null,o.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function Du({page:e,matches:t,...n}){let r=dl(),{future:i,manifest:a,routeModules:o}=xu(),{basename:s}=vu(),{loaderData:c,matches:l}=yu(),u=Q.useMemo(()=>pu(e,t,l,a,r,`data`),[e,t,l,a,r]),d=Q.useMemo(()=>pu(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=Q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=cu(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=Q.useMemo(()=>mu(d,a),[d,a]),m=Tu(d);return Q.createElement(Q.Fragment,null,f.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>Q.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>Q.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Ou(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}Q.Component;var ku=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{ku&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Au({basename:e,children:t,useTransitions:n,window:r}){let i=Q.useRef();i.current??=Ys({window:r,v5Compat:!0});let a=i.current,[o,s]=Q.useState({action:a.action,location:a.location}),c=Q.useCallback(e=>{n===!1?s(e):Q.startTransition(()=>s(e))},[n]);return Q.useLayoutEffect(()=>a.listen(c),[a,c]),Q.createElement(Ul,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var ju=Q.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=Q.useContext(el),v=typeof l==`string`&&Us.test(l),y=Hc(l,h);l=y.to;let b=ll(l,{relative:r}),x=dl(),S=null;if(o){let e=jc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:Nc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=Su(n,p),E=Iu(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=Q.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:Ou(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?Q.createElement(Q.Fragment,null,k,Q.createElement(wu,{page:b})):k});ju.displayName=`Link`;var Mu=Q.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=yl(a,{relative:c.relative}),d=dl(),f=Q.useContext(Jc),{navigator:p,basename:m}=Q.useContext(el),h=f!=null&&Hu(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=Tc(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return Q.createElement(ju,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Mu.displayName=`NavLink`;var Nu=Q.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Kl,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=Q.useContext(el),g=Bu(),_=Vu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Us.test(s);return Q.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?Q.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});Nu.displayName=`Form`;function Pu(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Fu(e){let t=Q.useContext(qc);return Xs(t,Pu(e)),t}function Iu(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=ml(),d=dl(),f=yl(e,{relative:o});return Q.useCallback(p=>{if($l(p,t)){p.preventDefault();let t=n===void 0?tc(d)===tc(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?Q.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function Lu(e){Zs(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=Q.useRef(eu(e)),n=Q.useRef(!1),r=dl(),i=Q.useMemo(()=>tu(r.search,n.current?null:t.current),[r.search]),a=ml();return[i,Q.useCallback((e,t)=>{let r=eu(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Ru=0,zu=()=>`__${String(++Ru)}__`;function Bu(){let{router:e}=Fu(`useSubmit`),{basename:t}=Q.useContext(el),n=Pl(),r=e.fetch,i=e.navigate;return Q.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=ou(e,t);if(a.navigate===!1){let e=a.fetcherKey||zu();await r(e,n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync})}else await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function Vu(e,{relative:t}={}){let{basename:n}=Q.useContext(el),r=Q.useContext(nl);Xs(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...yl(e||`.`,{relative:t})},o=dl();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:Nc([n,a.pathname])),tc(a)}function Hu(e,{relative:t}={}){let n=Q.useContext(Zc);Xs(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Fu(`useViewTransitionState`),i=yl(e,{relative:t});if(!n.isTransitioning)return!1;let a=Tc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Tc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return xc(i.pathname,o)!=null||xc(i.pathname,a)!=null}var $=s(),Uu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(ht,{ref:n,className:J(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Uu.displayName=ht.displayName;var Wu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Wu.displayName=`Card`;var Gu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex flex-col space-y-1.5 p-6`,e),...t}));Gu.displayName=`CardHeader`;var Ku=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`h3`,{ref:n,className:J(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Ku.displayName=`CardTitle`;var qu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`p`,{ref:n,className:J(`text-sm text-muted-foreground`,e),...t}));qu.displayName=`CardDescription`;var Ju=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`p-6 pt-0`,e),...t}));Ju.displayName=`CardContent`;var Yu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex items-center p-6 pt-0`,e),...t}));Yu.displayName=`CardFooter`;var Xu=`2.26.0`,Zu=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Qu(e){(0,Q.useEffect)(()=>{if(window.particlesJS!==void 0)Zu(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`),Zu(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var $u=`session.open`,ed=`session.set`,td=`session.ids`,nd=`session.materialize`,rd=`session.close`,id=`session.delta`;function ad(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await X.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 od=`https://github.com/canvas-ui/canvas-server`,sd=null;function cd(){return sd||=X.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||od,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),sd=null,{sourceUrl:od,version:null,commit:null,license:null})),sd}function ld(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;return cd().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function ud({className:e=``}){let t=ld();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,$.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,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function dd({children:e}){Qu(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=ad();return(0,$.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,$.jsxs)(Wu,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,$.jsxs)(ju,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,$.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,$.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,$.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Xu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,$.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,$.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,$.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,$.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,$.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,$.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,$.jsx)(`span`,{children:`View on GitHub`})]}),(0,$.jsx)(ud,{className:`mt-4 text-center`})]})]})})]})})}function fd(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var pd=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=Rr,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||fd();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=zr(this.baseUrl,{transports:[`websocket`],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.5,timeout:1e4,forceNew:!0,extraHeaders:{Authorization:`Bearer ${t}`,"X-Connection-ID":this.connectionId},auth:{token:t}}),this.setupDefaultHandlers(),this.registerHandlers(),this.socket.connect())}cleanupSocket(){this.socket?.removeAllListeners(),this.socket?.disconnect(),this.socket=null,this.connected=!1,this.socketWrappers.clear()}setupDefaultHandlers(){this.socket&&(this.socket.on(`connect`,()=>{this.connected=!0;for(let e of this.desiredSubscriptions)this.socket?.emit(`subscribe`,{channel:e})}),this.socket.on(`disconnect`,()=>{this.connected=!1}),this.socket.on(`connect_error`,()=>{this.connected=!1}))}registerHandlers(){this.socket&&this.handlers.forEach((e,t)=>{e.forEach(e=>{this.attach(t,e)})})}attach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e);if(n||(n=new Map,this.socketWrappers.set(e,n)),n.has(t))return;let r=(...e)=>t(...e);n.set(t,r),this.socket.on(e,r)}detach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e),r=n?.get(t);r&&(this.socket.off(e,r),n?.delete(t),n&&n.size===0&&this.socketWrappers.delete(e))}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);let n=this.handlers.get(e);return n.has(t)?()=>this.off(e,t):(n.add(t),this.socket&&this.attach(e,t),()=>this.off(e,t))}off(e,t){let n=this.handlers.get(e);n&&n.has(t)&&(n.delete(t),n.size===0&&this.handlers.delete(e),this.detach(e,t))}request(e,t,n=1e4){return new Promise((r,i)=>{if(!this.socket||!this.connected){i(Error(`Socket not connected`));return}let a=!1,o=setTimeout(()=>{a||(a=!0,i(Error(`Socket request timed out: ${e}`)))},n);try{this.socket.emit(e,t??{},t=>{a||(a=!0,clearTimeout(o),t?.status===`error`?i(Error(t.message||`${e} failed`)):r(t?.payload??t))})}catch(e){a=!0,clearTimeout(o),i(e instanceof Error?e:Error(String(e)))}})}emit(e,...t){if(e===`subscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.add(e)}else if(e===`unsubscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.delete(e)}if(this.socket&&this.connected)try{this.socket.emit(e,...t)}catch(t){console.error(`Error emitting event ${e}:`,t),this.reconnect()}else this.connect()}disconnect(){this.cleanupSocket(),this.authToken=null,this.desiredSubscriptions.clear()}isConnected(){return this.connected}retryNow(){this.connected||(this.cleanupSocket(),this.connect())}reconnect(){this.connect()}};async function md(e,t,n=`auto`){try{let r=await X.post(xr.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)+`...`),X.setAuthToken(i.token),pd.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)+`...`),X.setAuthToken(i.payload.token),pd.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),X.clearAuthToken(),e}}async function hd(e,t,n){try{return await X.post(xr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function gd(e){return e instanceof Error&&/^Network error/i.test(e.message)}function _d(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return yr(e).exp*1e3>Date.now()}catch{return!1}}function vd(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=yr(e);return t.exp*1e3<Date.now()?(X.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),X.clearAuthToken(),null}}async function yd(){try{if(!X.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await X.get(xr.me);return console.log(`Current user response:`,e),e&&e?(pd.isConnected()||pd.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),gd(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),X.clearAuthToken(),pd.disconnect(),null):null}}function bd(){return X.isAuthenticated()}function xd(){let e=new URL(`${Lr}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function Sd(e){let t=await X.post(`${Lr}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);X.setAuthToken(t.token),pd.connect(t.token)}async function Cd(){try{let e=await X.get(xr.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 wd(e){try{await X.post(xr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var Td=e=>e?.strategies?.local?.enabled!==!1,Ed=e=>e?.allowUserRegistrations!==!1;function Dd(){let e=ml(),[t,n]=Q.useState(!1),[r,i]=Q.useState(``),[a,o]=Q.useState(``),[s,c]=Q.useState(!1),[l,u]=Q.useState({}),[d,p]=Q.useState(null),[m,h]=Q.useState({email:``,password:``,strategy:`auto`});Q.useEffect(()=>{bd()&&e(`/workspaces`),fetch(`${Lr}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),Cd().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 md(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,$.jsx)(dd,{children:(0,$.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(X.setAuthToken(r.trim()),!await yd())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){X.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,$.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,$.jsx)(Uu,{htmlFor:`local-token`,children:`Local access token`}),(0,$.jsx)(Y,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(Z,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,$.jsx)(dd,{children:(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,$.jsx)(`form`,{onSubmit:v,children:(0,$.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Uu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,$.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,$.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,$.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,$.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Uu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{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,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Uu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,$.jsxs)(Z,{type:`button`,variant:`outline`,disabled:s,onClick:()=>xd(),children:[(0,$.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),Td(d)&&Ed(d)&&(0,$.jsx)(Z,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function Od(){let e=ml(),{showToast:t}=Vr(),[n,r]=Q.useState(!1),[i,a]=Q.useState({}),[o,s]=Q.useState({name:``,email:``,password:``}),[c,l]=Q.useState(!1),[u,d]=Q.useState(!1),[f,p]=Q.useState(null);Q.useEffect(()=>{(async()=>{let t=await Cd(),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=Q.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,$.jsxs)(dd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,$.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,$.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,$.jsx)(Z,{asChild:!0,className:`w-full`,children:(0,$.jsx)(ju,{to:`/login`,children:`Go to Login`})})})]}):(0,$.jsxs)(dd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,$.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await hd(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,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Uu,{htmlFor:`name`,children:`Username`}),(0,$.jsx)(Y,{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,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Uu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Uu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,$.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,$.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,$.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,$.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,$.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,$.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,$.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,$.jsx)(Z,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,$.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,$.jsx)(ju,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,$.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,$.jsx)(ju,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,$.jsx)(ju,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function kd(){let e=ml(),[t]=Lu(),[n,r]=Q.useState(t.get(`error`)),i=Q.useRef(!1);return Q.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,Sd(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,$.jsx)(dd,{children:(0,$.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Ad({className:e=`h-5 w-5`,...t}){return(0,$.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,$.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,$.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}function jd({children:e}){let[t,n]=(0,Q.useState)(`loading`);return(0,Q.useEffect)(()=>{(async()=>{try{if(!bd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await yd();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),gd(e)){n(_d()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),X.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,$.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,$.jsx)(Ad,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,$.jsx)(Bl,{to:`/login`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}function Md({children:e}){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{(async()=>{try{await X.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),X.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,$.jsx)(Bl,{to:`/workspaces`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}var Nd=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})}))})),Pd=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)}})),Fd=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=oe,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=z,e.setTopLeft=te,e.setTransform=ee,e.sortLayoutItems=ne,e.sortLayoutItemsByColRow=re,e.sortLayoutItemsByRowCol=B,e.synchronizeLayoutWithChildren=ie,e.validateLayout=ae,e.withLayoutItem=p;var t=Nd(),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=Pd();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=ne(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=ne(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)}},F=(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)}},I=(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)}},L=(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)}},R={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},e:F,se:function(){return L(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},s:L,sw:function(){return L(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])},w:I,nw:function(){return P(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])}};function z(e,t,n,r){let i=R[e];return i?i(t,a(a({},t),n),r):n}function ee(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 te(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 ne(e,t){return t===`horizontal`?re(e):t===`vertical`?B(e):e}function B(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 re(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 ie(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 ae(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 oe(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Id=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)}})),Ld=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),Rd=i(((e,t)=>{var n=Ld();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}})),zd=i(((e,t)=>{t.exports=Rd()()})),Bd=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:()=>K,default:()=>q}),t.exports=f(p);var m=u(d()),g=u(zd()),_=u(h()),v=vr();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 F(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function I(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function L(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function R(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 z(e,t){let n=te(e,t,`px`);return{[E(`transform`,O)]:n}}function ee(e,t){return te(e,t,``)}function te({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 ne(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function B(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function re(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ie(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??re();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
4
+ Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=dl(),d;if(t){let e=typeof t==`string`?nc(t):t;Xs(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):ac(e,{pathname:p});Zs(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Zs(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=Ol(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Nc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:Nc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?Q.createElement(tl.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function Sl(){let e=Fl(),t=zc(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=Q.createElement(Q.Fragment,null,Q.createElement(`p`,null,`💿 Hey developer 👋`),Q.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,Q.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,Q.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),Q.createElement(Q.Fragment,null,Q.createElement(`h2`,null,`Unexpected Application Error!`),Q.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?Q.createElement(`pre`,{style:i},n):null,o)}var Cl=Q.createElement(Sl,null),wl=class extends Q.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=cl(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:Q.createElement(nl.Provider,{value:this.props.routeContext},Q.createElement(rl.Provider,{value:e,children:this.props.component}));return this.context?Q.createElement(El,{error:e},t):t}};wl.contextType=Yc;var Tl=new WeakMap;function El({children:e,error:t}){let{basename:n}=Q.useContext(el);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=sl(t.digest);if(e){let r=Tl.get(t);if(r)throw r;let i=Hc(e.location,n),a=i.absoluteURL||i.to;if(Kc(a))throw Error(`Invalid redirect location`);if(Vc&&!Tl.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw Tl.set(t,n),n}}return Q.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function Dl({routeContext:e,match:t,children:n}){let r=Q.useContext(qc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),Q.createElement(nl.Provider,{value:e},n)}function Ol(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);Xs(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Bc(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||Cl,o&&(s<0&&c===0?(Rl(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?Q.createElement(n.route.Component,null):n.route.element?n.route.element:e,Q.createElement(Dl,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?Q.createElement(wl,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function kl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Al(e){let t=Q.useContext(qc);return Xs(t,kl(e)),t}function jl(e){let t=Q.useContext(Jc);return Xs(t,kl(e)),t}function Ml(e){let t=Q.useContext(nl);return Xs(t,kl(e)),t}function Nl(e){let t=Ml(e),n=t.matches[t.matches.length-1];return Xs(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Pl(){return Nl(`useRouteId`)}function Fl(){let e=Q.useContext(rl),t=jl(`useRouteError`),n=Nl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Il(){let{router:e}=Al(`useNavigate`),t=Nl(`useNavigate`),n=Q.useRef(!1);return pl(()=>{n.current=!0}),Q.useCallback(async(r,i={})=>{Zs(n.current,fl),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Ll={};function Rl(e,t,n){!t&&!Ll[e]&&(Ll[e]=!0,Zs(!1,n))}Q.memo(zl);function zl({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return xl(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Bl({to:e,replace:t,state:n,relative:r}){Xs(ul(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=Q.useContext(el);Zs(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=Q.useContext(nl),{pathname:o}=dl(),s=ml(),c=jc(e,Ac(a),o,r===`path`),l=JSON.stringify(c);return Q.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function Vl(e){return _l(e.context)}function Hl(e){Xs(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function Ul({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Xs(!ul(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=Q.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=nc(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=Q.useMemo(()=>{let e=Tc(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return Zs(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:Q.createElement(el.Provider,{value:c},Q.createElement(tl.Provider,{children:t,value:h}))}function Wl({children:e,location:t}){return bl(Gl(e),t)}Q.Component;function Gl(e,t=[]){let n=[];return Q.Children.forEach(e,(e,r)=>{if(!Q.isValidElement(e))return;let i=[...t,r];if(e.type===Q.Fragment){n.push.apply(n,Gl(e.props.children,i));return}Xs(e.type===Hl,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Xs(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=Gl(e.props.children,i)),n.push(a)}),n}var Kl=`get`,ql=`application/x-www-form-urlencoded`;function Jl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Yl(e){return Jl(e)&&e.tagName.toLowerCase()===`button`}function Xl(e){return Jl(e)&&e.tagName.toLowerCase()===`form`}function Zl(e){return Jl(e)&&e.tagName.toLowerCase()===`input`}function Ql(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function $l(e,t){return e.button===0&&(!t||t===`_self`)&&!Ql(e)}function eu(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function tu(e,t){let n=eu(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var nu=null;function ru(){if(nu===null)try{new FormData(document.createElement(`form`),0),nu=!1}catch{nu=!0}return nu}var iu=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function au(e){return e!=null&&!iu.has(e)?(Zs(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${ql}"`),null):e}function ou(e,t){let n,r,i,a,o;if(Xl(e)){let o=e.getAttribute(`action`);r=o?Tc(o,t):null,n=e.getAttribute(`method`)||Kl,i=au(e.getAttribute(`enctype`))||ql,a=new FormData(e)}else if(Yl(e)||Zl(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?Tc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Kl,i=au(e.getAttribute(`formenctype`))||au(o.getAttribute(`enctype`))||ql,a=new FormData(o,e),!ru()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(Jl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Kl,r=null,i=ql,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function su(e,t){if(e===!1||e==null)throw Error(t)}function cu(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return i.pathname=n?i.pathname.endsWith(`/`)?`${i.pathname}_.${r}`:`${i.pathname}.${r}`:i.pathname===`/`?`_root.${r}`:t&&Tc(i.pathname,t)===`/`?`${Pc(t)}/_root.${r}`:`${Pc(i.pathname)}.${r}`,i}async function lu(e,t){if(e.id in t)return t[e.id];try{let n=await g(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function uu(e){return e!=null&&typeof e.page==`string`}function du(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function fu(e,t,n){return _u((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await lu(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(du).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function pu(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function mu(e,t,{includeHydrateFallback:n}={}){return hu(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function hu(e){return[...new Set(e)]}function gu(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function _u(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!uu(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(gu(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function vu(){let e=Q.useContext(qc);return su(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function yu(){let e=Q.useContext(Jc);return su(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var bu=Q.createContext(void 0);bu.displayName=`FrameworkContext`;function xu(){let e=Q.useContext(bu);return su(e,`You must render this element inside a <HydratedRouter> element`),e}function Su(e,t){let n=Q.useContext(bu),[r,i]=Q.useState(!1),[a,o]=Q.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=Q.useRef(null);Q.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),Q.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:Cu(s,p),onBlur:Cu(c,m),onMouseEnter:Cu(l,p),onMouseLeave:Cu(u,m),onTouchStart:Cu(d,p)}]:[a,f,{}]:[!1,f,{}]}function Cu(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function wu({page:e,...t}){let n=Xc(),{nonce:r}=xu(),{router:i}=vu(),a=Q.useMemo(()=>ac(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?Q.createElement(Eu,{page:e,matches:a,...t}):Q.createElement(Du,{page:e,matches:a,...t})):null}function Tu(e){let{manifest:t,routeModules:n}=xu(),[r,i]=Q.useState([]);return Q.useEffect(()=>{let r=!1;return fu(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Eu({page:e,matches:t,...n}){let r=dl(),{future:i}=xu(),{basename:a}=vu(),o=Q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=cu(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return Q.createElement(Q.Fragment,null,o.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function Du({page:e,matches:t,...n}){let r=dl(),{future:i,manifest:a,routeModules:o}=xu(),{basename:s}=vu(),{loaderData:c,matches:l}=yu(),u=Q.useMemo(()=>pu(e,t,l,a,r,`data`),[e,t,l,a,r]),d=Q.useMemo(()=>pu(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=Q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=cu(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=Q.useMemo(()=>mu(d,a),[d,a]),m=Tu(d);return Q.createElement(Q.Fragment,null,f.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>Q.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>Q.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Ou(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}Q.Component;var ku=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{ku&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Au({basename:e,children:t,useTransitions:n,window:r}){let i=Q.useRef();i.current??=Ys({window:r,v5Compat:!0});let a=i.current,[o,s]=Q.useState({action:a.action,location:a.location}),c=Q.useCallback(e=>{n===!1?s(e):Q.startTransition(()=>s(e))},[n]);return Q.useLayoutEffect(()=>a.listen(c),[a,c]),Q.createElement(Ul,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var ju=Q.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=Q.useContext(el),v=typeof l==`string`&&Us.test(l),y=Hc(l,h);l=y.to;let b=ll(l,{relative:r}),x=dl(),S=null;if(o){let e=jc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:Nc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=Su(n,p),E=Iu(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=Q.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:Ou(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?Q.createElement(Q.Fragment,null,k,Q.createElement(wu,{page:b})):k});ju.displayName=`Link`;var Mu=Q.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=yl(a,{relative:c.relative}),d=dl(),f=Q.useContext(Jc),{navigator:p,basename:m}=Q.useContext(el),h=f!=null&&Hu(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=Tc(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return Q.createElement(ju,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Mu.displayName=`NavLink`;var Nu=Q.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Kl,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=Q.useContext(el),g=Bu(),_=Vu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Us.test(s);return Q.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?Q.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});Nu.displayName=`Form`;function Pu(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Fu(e){let t=Q.useContext(qc);return Xs(t,Pu(e)),t}function Iu(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=ml(),d=dl(),f=yl(e,{relative:o});return Q.useCallback(p=>{if($l(p,t)){p.preventDefault();let t=n===void 0?tc(d)===tc(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?Q.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function Lu(e){Zs(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=Q.useRef(eu(e)),n=Q.useRef(!1),r=dl(),i=Q.useMemo(()=>tu(r.search,n.current?null:t.current),[r.search]),a=ml();return[i,Q.useCallback((e,t)=>{let r=eu(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Ru=0,zu=()=>`__${String(++Ru)}__`;function Bu(){let{router:e}=Fu(`useSubmit`),{basename:t}=Q.useContext(el),n=Pl(),r=e.fetch,i=e.navigate;return Q.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=ou(e,t);if(a.navigate===!1){let e=a.fetcherKey||zu();await r(e,n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync})}else await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function Vu(e,{relative:t}={}){let{basename:n}=Q.useContext(el),r=Q.useContext(nl);Xs(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...yl(e||`.`,{relative:t})},o=dl();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:Nc([n,a.pathname])),tc(a)}function Hu(e,{relative:t}={}){let n=Q.useContext(Zc);Xs(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Fu(`useViewTransitionState`),i=yl(e,{relative:t});if(!n.isTransitioning)return!1;let a=Tc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Tc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return xc(i.pathname,o)!=null||xc(i.pathname,a)!=null}var $=s(),Uu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(ht,{ref:n,className:J(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Uu.displayName=ht.displayName;var Wu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Wu.displayName=`Card`;var Gu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex flex-col space-y-1.5 p-6`,e),...t}));Gu.displayName=`CardHeader`;var Ku=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`h3`,{ref:n,className:J(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Ku.displayName=`CardTitle`;var qu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`p`,{ref:n,className:J(`text-sm text-muted-foreground`,e),...t}));qu.displayName=`CardDescription`;var Ju=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`p-6 pt-0`,e),...t}));Ju.displayName=`CardContent`;var Yu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex items-center p-6 pt-0`,e),...t}));Yu.displayName=`CardFooter`;var Xu=`2.26.1`,Zu=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Qu(e){(0,Q.useEffect)(()=>{if(window.particlesJS!==void 0)Zu(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`),Zu(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var $u=`session.open`,ed=`session.set`,td=`session.ids`,nd=`session.materialize`,rd=`session.close`,id=`session.delta`;function ad(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await X.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 od=`https://github.com/canvas-ui/canvas-server`,sd=null;function cd(){return sd||=X.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||od,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),sd=null,{sourceUrl:od,version:null,commit:null,license:null})),sd}function ld(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;return cd().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function ud({className:e=``}){let t=ld();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,$.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,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function dd({children:e}){Qu(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=ad();return(0,$.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,$.jsxs)(Wu,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,$.jsxs)(ju,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,$.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,$.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,$.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Xu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,$.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,$.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,$.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,$.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,$.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,$.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,$.jsx)(`span`,{children:`View on GitHub`})]}),(0,$.jsx)(ud,{className:`mt-4 text-center`})]})]})})]})})}function fd(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var pd=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=Rr,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||fd();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=zr(this.baseUrl,{transports:[`websocket`],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.5,timeout:1e4,forceNew:!0,extraHeaders:{Authorization:`Bearer ${t}`,"X-Connection-ID":this.connectionId},auth:{token:t}}),this.setupDefaultHandlers(),this.registerHandlers(),this.socket.connect())}cleanupSocket(){this.socket?.removeAllListeners(),this.socket?.disconnect(),this.socket=null,this.connected=!1,this.socketWrappers.clear()}setupDefaultHandlers(){this.socket&&(this.socket.on(`connect`,()=>{this.connected=!0;for(let e of this.desiredSubscriptions)this.socket?.emit(`subscribe`,{channel:e})}),this.socket.on(`disconnect`,()=>{this.connected=!1}),this.socket.on(`connect_error`,()=>{this.connected=!1}))}registerHandlers(){this.socket&&this.handlers.forEach((e,t)=>{e.forEach(e=>{this.attach(t,e)})})}attach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e);if(n||(n=new Map,this.socketWrappers.set(e,n)),n.has(t))return;let r=(...e)=>t(...e);n.set(t,r),this.socket.on(e,r)}detach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e),r=n?.get(t);r&&(this.socket.off(e,r),n?.delete(t),n&&n.size===0&&this.socketWrappers.delete(e))}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);let n=this.handlers.get(e);return n.has(t)?()=>this.off(e,t):(n.add(t),this.socket&&this.attach(e,t),()=>this.off(e,t))}off(e,t){let n=this.handlers.get(e);n&&n.has(t)&&(n.delete(t),n.size===0&&this.handlers.delete(e),this.detach(e,t))}request(e,t,n=1e4){return new Promise((r,i)=>{if(!this.socket||!this.connected){i(Error(`Socket not connected`));return}let a=!1,o=setTimeout(()=>{a||(a=!0,i(Error(`Socket request timed out: ${e}`)))},n);try{this.socket.emit(e,t??{},t=>{a||(a=!0,clearTimeout(o),t?.status===`error`?i(Error(t.message||`${e} failed`)):r(t?.payload??t))})}catch(e){a=!0,clearTimeout(o),i(e instanceof Error?e:Error(String(e)))}})}emit(e,...t){if(e===`subscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.add(e)}else if(e===`unsubscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.delete(e)}if(this.socket&&this.connected)try{this.socket.emit(e,...t)}catch(t){console.error(`Error emitting event ${e}:`,t),this.reconnect()}else this.connect()}disconnect(){this.cleanupSocket(),this.authToken=null,this.desiredSubscriptions.clear()}isConnected(){return this.connected}retryNow(){this.connected||(this.cleanupSocket(),this.connect())}reconnect(){this.connect()}};async function md(e,t,n=`auto`){try{let r=await X.post(xr.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)+`...`),X.setAuthToken(i.token),pd.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)+`...`),X.setAuthToken(i.payload.token),pd.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),X.clearAuthToken(),e}}async function hd(e,t,n){try{return await X.post(xr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function gd(e){return e instanceof Error&&/^Network error/i.test(e.message)}function _d(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return yr(e).exp*1e3>Date.now()}catch{return!1}}function vd(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=yr(e);return t.exp*1e3<Date.now()?(X.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),X.clearAuthToken(),null}}async function yd(){try{if(!X.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await X.get(xr.me);return console.log(`Current user response:`,e),e&&e?(pd.isConnected()||pd.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),gd(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),X.clearAuthToken(),pd.disconnect(),null):null}}function bd(){return X.isAuthenticated()}function xd(){let e=new URL(`${Lr}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function Sd(e){let t=await X.post(`${Lr}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);X.setAuthToken(t.token),pd.connect(t.token)}async function Cd(){try{let e=await X.get(xr.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 wd(e){try{await X.post(xr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var Td=e=>e?.strategies?.local?.enabled!==!1,Ed=e=>e?.allowUserRegistrations!==!1;function Dd(){let e=ml(),[t,n]=Q.useState(!1),[r,i]=Q.useState(``),[a,o]=Q.useState(``),[s,c]=Q.useState(!1),[l,u]=Q.useState({}),[d,p]=Q.useState(null),[m,h]=Q.useState({email:``,password:``,strategy:`auto`});Q.useEffect(()=>{bd()&&e(`/workspaces`),fetch(`${Lr}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),Cd().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 md(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,$.jsx)(dd,{children:(0,$.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(X.setAuthToken(r.trim()),!await yd())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){X.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,$.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,$.jsx)(Uu,{htmlFor:`local-token`,children:`Local access token`}),(0,$.jsx)(Y,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(Z,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,$.jsx)(dd,{children:(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,$.jsx)(`form`,{onSubmit:v,children:(0,$.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Uu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,$.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,$.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,$.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,$.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Uu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{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,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Uu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,$.jsxs)(Z,{type:`button`,variant:`outline`,disabled:s,onClick:()=>xd(),children:[(0,$.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),Td(d)&&Ed(d)&&(0,$.jsx)(Z,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function Od(){let e=ml(),{showToast:t}=Vr(),[n,r]=Q.useState(!1),[i,a]=Q.useState({}),[o,s]=Q.useState({name:``,email:``,password:``}),[c,l]=Q.useState(!1),[u,d]=Q.useState(!1),[f,p]=Q.useState(null);Q.useEffect(()=>{(async()=>{let t=await Cd(),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=Q.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,$.jsxs)(dd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,$.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,$.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,$.jsx)(Z,{asChild:!0,className:`w-full`,children:(0,$.jsx)(ju,{to:`/login`,children:`Go to Login`})})})]}):(0,$.jsxs)(dd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,$.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await hd(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,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Uu,{htmlFor:`name`,children:`Username`}),(0,$.jsx)(Y,{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,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Uu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Uu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,$.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,$.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,$.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,$.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,$.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,$.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,$.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,$.jsx)(Z,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,$.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,$.jsx)(ju,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,$.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,$.jsx)(ju,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,$.jsx)(ju,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function kd(){let e=ml(),[t]=Lu(),[n,r]=Q.useState(t.get(`error`)),i=Q.useRef(!1);return Q.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,Sd(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,$.jsx)(dd,{children:(0,$.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Ad({className:e=`h-5 w-5`,...t}){return(0,$.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,$.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,$.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}function jd({children:e}){let[t,n]=(0,Q.useState)(`loading`);return(0,Q.useEffect)(()=>{(async()=>{try{if(!bd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await yd();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),gd(e)){n(_d()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),X.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,$.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,$.jsx)(Ad,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,$.jsx)(Bl,{to:`/login`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}function Md({children:e}){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{(async()=>{try{await X.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),X.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,$.jsx)(Bl,{to:`/workspaces`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}var Nd=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})}))})),Pd=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)}})),Fd=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=oe,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=z,e.setTopLeft=te,e.setTransform=ee,e.sortLayoutItems=ne,e.sortLayoutItemsByColRow=re,e.sortLayoutItemsByRowCol=B,e.synchronizeLayoutWithChildren=ie,e.validateLayout=ae,e.withLayoutItem=p;var t=Nd(),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=Pd();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=ne(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=ne(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)}},F=(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)}},I=(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)}},L=(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)}},R={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},e:F,se:function(){return L(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},s:L,sw:function(){return L(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])},w:I,nw:function(){return P(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])}};function z(e,t,n,r){let i=R[e];return i?i(t,a(a({},t),n),r):n}function ee(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 te(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 ne(e,t){return t===`horizontal`?re(e):t===`vertical`?B(e):e}function B(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 re(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 ie(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 ae(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 oe(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Id=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)}})),Ld=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),Rd=i(((e,t)=>{var n=Ld();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}})),zd=i(((e,t)=>{t.exports=Rd()()})),Bd=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:()=>K,default:()=>q}),t.exports=f(p);var m=u(d()),g=u(zd()),_=u(h()),v=vr();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 F(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function I(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function L(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function R(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 z(e,t){let n=te(e,t,`px`);return{[E(`transform`,O)]:n}}function ee(e,t){return te(e,t,``)}function te({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 ne(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function B(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function re(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ie(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??re();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
5
5
  `,n.innerHTML+=`.react-draggable-transparent-selection *::selection {all: inherit;}
6
6
  `,e.getElementsByTagName(`head`)[0].appendChild(n)}e.body&&V(e.body,`react-draggable-transparent-selection`)}function ae(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{oe(e)}):oe(e)}function oe(e){if(e)try{e.body&&H(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 V(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function H(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function U(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:fe(r);let i=pe(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:L(a)-F(i)-i.offsetLeft+S(s.paddingRight)-S(o.marginRight),bottom:I(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 se(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function W(e){return e.props.axis===`both`||e.props.axis===`x`}function ce(e){return e.props.axis===`both`||e.props.axis===`y`}function le(e,t,n){let r=typeof t==`number`?ne(e,t):null;if(typeof t==`number`&&!r)return null;let i=pe(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return R(r||e,a,n.props.scale)}function ue(e,t,n){let r=!x(e.lastX),i=pe(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 de(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 fe(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function pe(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var me=u(d()),G=u(zd()),he=u(h()),ge=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},_e={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},ve=_e.mouse,K=class extends me.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=B(e);this.touchIdentifier=r;let i=le(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=ue(this,a,o);ge(`DraggableCore: handleDragStart: %j`,s),ge(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&ie(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,ve.move,this.handleDrag),M(n,ve.stop,this.handleDragStop))},this.handleDrag=e=>{let t=le(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]=se(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=ue(this,n,r);if(ge(`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=le(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]=se(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=ue(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&ae(a.ownerDocument),ge(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(ge(`DraggableCore: Removing handlers`),N(a.ownerDocument,ve.move,this.handleDrag),N(a.ownerDocument,ve.stop,this.handleDragStop))},this.onMouseDown=e=>(ve=_e.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(ve=_e.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(ve=_e.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(ve=_e.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,_e.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,_e.mouse.move,this.handleDrag),N(t,_e.touch.move,this.handleDrag),N(t,_e.mouse.stop,this.handleDragStop),N(t,_e.touch.stop,this.handleDragStop),N(e,_e.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&ae(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=he.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(ge(`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 me.cloneElement(me.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};K.displayName=`DraggableCore`,K.propTypes={allowAnyClick:G.default.bool,allowMobileScroll:G.default.bool,children:G.default.node.isRequired,disabled:G.default.bool,enableUserSelectHack:G.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:G.default.arrayOf(G.default.number),handle:G.default.string,cancel:G.default.string,nodeRef:G.default.object,nonce:G.default.string,onStart:G.default.func,onDrag:G.default.func,onStop:G.default.func,onMouseDown:G.default.func,scale:G.default.number,className:C,style:C,transform:C},K.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var q=class extends m.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(ge(`Draggable: onDragStart: %j`,t),this.props.onStart(e,de(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;ge(`Draggable: onDrag: %j`,t);let n=de(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]=U(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,de(this,t))===!1)return!1;ge(`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)?(ge(`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:W(this)&&p?this.state.x:h.x,y:ce(this)&&p?this.state.y:h.y};this.state.isElementSVG?f=ee(g,c):d=z(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(K,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},m.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};q.displayName=`Draggable`,q.propTypes={...K.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},q.defaultProps={...K.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:K})})),Vd=i(((e,t)=>{var n=Bd(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),Hd=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)}})),Ud=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(zd());Vd();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)}}})),Wd=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=Vd(),r=Hd(),i=Ud(),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}})),Gd=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(zd()),r=o(Wd()),i=Ud(),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})})),Kd=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=Wd().default,t.exports.ResizableBox=Gd().default})),qd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(zd()),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&&Fd().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}})),Jd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=u(d()),n=h(),r=u(zd()),i=Vd(),a=Kd(),o=Fd(),s=Id(),c=qd(),l=u(vr());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})})),Yd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=Nd(),r=c(vr()),i=Fd(),a=Id(),o=c(Jd()),s=c(qd());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})})),Xd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=Fd();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]})}})),Zd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(zd()),r=Nd(),i=Fd(),a=Xd(),o=c(Yd()),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})})),Qd=r({default:()=>Of});function $d(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){pf(a)}function s(){var e=Date.now();if(n){if(e-i<mf)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function ef(e){return parseFloat(e)||0}function tf(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+ef(r)},0)}function nf(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]=ef(o)}return n}function rf(e){var t=e.getBBox();return lf(0,0,t.width,t.height)}function af(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return xf;var r=bf(e).getComputedStyle(e),i=nf(r),a=i.left+i.right,o=i.top+i.bottom,s=ef(r.width),c=ef(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=tf(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=tf(r,`top`,`bottom`)+o)),!of(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 lf(i.left,i.top,s,c)}function of(e){return e===bf(e).document.documentElement}function sf(e){return df?Sf(e)?rf(e):af(e):xf}function cf(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return yf(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function lf(e,t,n,r){return{x:e,y:t,width:n,height:r}}var uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf=t((()=>{uf=(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}()})(),df=typeof window<`u`&&typeof document<`u`&&window.document===document,ff=(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`)()})(),pf=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(ff):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),mf=2,hf=20,gf=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],_f=typeof MutationObserver<`u`,vf=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=$d(this.refresh.bind(this),hf)}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(){!df||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),_f?(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(){!df||!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;gf.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),yf=(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}),bf=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||ff}),xf=lf(0,0,0,0),Sf=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof bf(e).SVGGraphicsElement}:function(e){return e instanceof bf(e).SVGElement&&typeof e.getBBox==`function`}})(),Cf=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=lf(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=sf(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}(),wf=function(){function e(e,t){var n=cf(t);yf(this,{target:e,contentRect:n})}return e}(),Tf=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new uf,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 bf(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new Cf(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 bf(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 wf(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}(),Ef=typeof WeakMap<`u`?new WeakMap:new uf,Df=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 Tf(t,vf.getInstance(),this);Ef.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){Df.prototype[e]=function(){var t;return(t=Ef.get(this))[e].apply(t,arguments)}}),Of=(function(){return ff.ResizeObserver===void 0?Df:ff.ResizeObserver})()})),Af=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(zd()),i=s((kf(),e(Qd))),a=s(vr()),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}})),jf=n(i(((e,t)=>{t.exports=Yd().default,t.exports.utils=Fd(),t.exports.calculateUtils=Id(),t.exports.Responsive=Zd().default,t.exports.Responsive.utils=Xd(),t.exports.WidthProvider=Af().default}))(),1),Mf=new Map;function Nf(e){Mf.set(e.type,e)}function Pf(e){return Mf.get(e)}function Ff(){return[...Mf.values()]}async function If(e,t,n){let r={successful:[],failed:[],pending:[]},i=[...new Set(e)],a=0;n.onProgress(0,i.length);for(let e of i){if(n.shouldStop())break;try{let n=await t([e]);r.successful.push(...n.successful),r.failed.push(...n.failed)}catch(t){r.failed.push({id:e,reason:t instanceof Error?t.message:String(t)}),a++,n.onProgress(a,i.length);break}a++,n.onProgress(a,i.length)}return r.pending=i.slice(a),r}function Lf(e){return`/workspaces/${e}/hooks`}async function Rf(e){return await X.get(Lf(e))||[]}async function zf(e,t){return(await X.get(`${Lf(e)}/${t}`))?.content??``}async function Bf(e,t,n){await X.put(`${Lf(e)}/${t}`,{content:n})}async function Vf(e,t){await X.delete(`${Lf(e)}/${t}`)}var Hf=[`example-`,`disabled-`,`_`];function Uf(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function Wf(e){return Hf.find(t=>e.startsWith(t))??null}function Gf(e){return Wf(Uf(e).base)===null}function Kf(e){return Uf(e).base.startsWith(`example-`)}function qf(e){let{dir:t,base:n}=Uf(e),r=Wf(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function Jf(e,t,n){if(Gf(t)===n)return t;let r=qf(t);return await Bf(e,r,await zf(e,t)),await Vf(e,t),r}function Yf(e){let t={};for(let n of e){let e;e=n.path.includes(`/`)?n.path.split(`/`)[0]:/^(?:example-|disabled-|_)?rules\.json$/.test(n.path)?`rules`:n.path.replace(/\.js$/,``),(t[e]||=[]).push(n)}return t}function Xf(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function Zf(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function Qf(e){let t=String(e||``).split(`/`).filter(Boolean);return t[0]===`workspace`&&t.length>=2?{backend:`workspace:${t[1]}`,rel:t.slice(2).join(`/`)}:t[0]===`device`?t.length>=3?{backend:t[2],rel:t.slice(3).join(`/`)}:null:t.length>=2?{backend:t[1],rel:t.slice(2).join(`/`)}:null}function $f(e){let t=new URLSearchParams;return e.kind&&e.kind!==`mirror`&&t.set(`addRuleKind`,e.kind),e.path&&t.set(`addRulePath`,e.path),e.target&&t.set(`addRuleTarget`,e.target),e.storeTo&&t.set(`addRuleStoreTo`,e.storeTo),e.storeFolder&&t.set(`addRuleStoreFolder`,e.storeFolder),t}function ep(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var tp=`rules.json`;async function np(e){try{let t=await zf(e,tp),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function rp(e,t){await Bf(e,tp,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
7
7
  `)}async function ip(e,t={}){let n=new URLSearchParams;t.status&&n.set(`status`,t.status),t.handler&&n.set(`handler`,t.handler),t.limit&&n.set(`limit`,String(t.limit));let r=n.toString();return await X.get(`${Lf(e)}/pending${r?`?${r}`:``}`)||[]}async function ap(e,t){return await X.post(`${Lf(e)}/pending/decisions`,t)}async function op(e,t){return await X.get(`${Lf(e)}/runs/${encodeURIComponent(t)}`)}async function sp(e,t={}){let n=new URLSearchParams;t.limit&&n.set(`limit`,String(t.limit)),t.handler&&n.set(`handler`,t.handler),t.event&&n.set(`event`,t.event),t.failed&&n.set(`failed`,`true`);let r=n.toString();return await X.get(`${Lf(e)}/runs${r?`?${r}`:``}`)||[]}var cp=1e4,lp=`canvas.hooks.backfillLimit`;function up(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?100:Math.min(t,cp)}function dp(){try{let e=localStorage.getItem(lp);return e?up(e):100}catch{return 100}}function fp(e){let t=up(e);try{localStorage.setItem(lp,String(t))}catch{}return t}function pp(e){if(e.includes(`/`)){let t=e.split(`/`)[0];return t===`lib`||t===`rules`?null:t}return e.endsWith(`.js`)?e.replace(/\.js$/,``).replace(/^(?:example-|disabled-|_)/,``):null}async function mp(e,t){return await X.post(`${Lf(e)}/backfill`,t)}async function hp(e,t){return await X.post(`${Lf(e)}/run`,t)}async function gp(e,t){return await X.post(`${Lf(e)}/runs/${t}/replay`,{})}async function _p(e){return await X.get(`${Lf(e)}/meta`)}async function vp(e,t){return await X.post(`${Lf(e)}/generate`,t)}async function yp(e,t){let n=await zf(e,tp),r=JSON.parse(n),i=Array.isArray(r)?r:r?.rules;if(!Array.isArray(i))throw Error(`The workspace rules file is invalid. Fix it in Rules before adding a rule.`);let a=(Array.isArray(t)?t:[t]).filter(e=>!i.some(t=>t.id===e.id));if(!a.length)return;let o=Array.isArray(r)?[...i,...a]:{...r,rules:[...i,...a]};await Bf(e,tp,JSON.stringify(o,null,2)+`
@@ -26,7 +26,7 @@ Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})
26
26
  `).trim():``:``}function JO(e){if(!e)return;let t=qO(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 YO(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 XO(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:KO(e),timestamp:YO(e.timestamp),...e.role===`assistant`?{metadata:JO(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function ZO(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:XO(e?.messages||[])}}function QO(e){return{current:ZO(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 GO(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new WO(e.apiKey||``,e.endpoint||`${Lr}/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 X.stream(`${Lr}/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 X.get(`${Lr}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await X.post(`${Lr}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function $O(e){return await X.get(`${Lr}/agents/${e}/access`)||null}async function ek(e,t){return await X.put(`${Lr}/agents/${e}/access`,t)}async function tk(e){return await X.post(`${Lr}/agents/${e}/access/token`)}async function nk(e){await X.delete(`${Lr}/agents/${e}/access`)}async function rk(e){return await X.get(`${Lr}/agents/${e}/tools`)||{tools:[],config:{}}}async function ik(){try{return await X.get(`${Lr}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function ak(e){return await X.get(`${Lr}/agents/${e}`)}async function ok(e){return ZO(await X.get(`${Lr}/agents/${e}/session`))}async function sk(e){return await X.get(`${Lr}/agents/${e}/sessions`)}async function ck(e,t){return QO(await X.post(`${Lr}/agents/${e}/sessions`,t))}async function lk(e,t){return QO(await X.put(`${Lr}/agents/${e}/session`,t))}async function uk(e,t,n){return QO(await X.patch(`${Lr}/agents/${e}/sessions/${t}`,n))}async function dk(e,t){return QO(await X.delete(`${Lr}/agents/${e}/sessions/${t}`))}async function fk(e){return await X.get(`${Lr}/agents/${e}/skills`)||[]}async function pk(e,t){return await X.post(`${Lr}/agents/${e}/skills`,t)||[]}async function mk(e,t){return await X.delete(`${Lr}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function hk(e){return await X.post(`${Lr}/agents`,e)}async function gk(e,t){return await X.put(`${Lr}/agents/${e}`,t)}async function _k(e){await X.delete(`${Lr}/agents/${e}`)}async function vk(e){return await X.post(`${Lr}/agents/${e}/start`)}async function yk(e){return await X.post(`${Lr}/agents/${e}/stop`)}async function bk(e){return await X.get(`${Lr}/agents/${e}/status`)}async function xk(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 X.stream(`${Lr}/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(`
27
27
 
28
28
  `);f=t.pop()||``;for(let e of t){let t=e.split(`
29
- `).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||{},...JO(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function Sk(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 X.post(`${Lr}/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:KO(i),metadata:JO(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function Ck(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function wk(){return await X.get(`${Lr}/voice/status`)}async function Tk(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 X.post(`${Lr}/agents/${e}/voice${o}`,r)}var Ek=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:IO,load:async()=>(await Ai()).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:zO,load:async()=>(await ds()).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:VO,load:async()=>(await ik()).map(e=>({id:e.id,label:e.label||e.name}))}];function Dk({to:e,label:t,description:n,icon:r}){return(0,$.jsxs)(ju,{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,$.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,$.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,$.jsx)(Dt,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function Ok({group:e,query:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(`loading`),[c,l]=(0,Q.useState)(0);(0,Q.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=>lT(t,e.label,n.label,n.description));return u.length?(0,$.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,$.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,$.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,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,$.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,$.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,$.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,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,$.jsx)(Dk,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function kk(){let{state:e}=MT(),[t,n]=(0,Q.useState)(``),r=sT.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>lT(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Ek.some(e=>e.sections.some(n=>lT(t,e.label,n.label,n.description)));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,$.jsx)(Gw,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,$.jsx)(Y,{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,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Dk,{to:e.path,...e},e.path))})]},e.id)),Ek.map(e=>(0,$.jsx)(Ok,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Dk,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Ak=[{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`}],jk=`/wallpapers`;function Mk(e){return Ak.find(t=>t.id===e)}function Nk(e,t={}){let n=typeof e==`string`?Mk(e):e;if(!n)return null;let{base:r=jk,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 Pk(e,t=jk){let n=typeof e==`string`?Mk(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var Fk=[{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`}],Ik=`canvas:wallpaper`,Lk=`canvas-wallpaper`,Rk=`settings`,zk=`builtin:`,Bk=Ak;function Vk(e){return Pk(e)??``}function Hk(e){return`${zk}${e}`}function Uk(e){return e?.startsWith(zk)?e.slice(8):null}function Wk(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 Gk(){try{let e=localStorage.getItem(Ik);if(e){let t=Wk(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var Kk=Gk(),qk=null;function Jk(){return Kk}async function Yk(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(Lk,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(Rk),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(Rk,e?`readwrite`:`readonly`),a=i.objectStore(Rk),o=e?a.put(e,Ik):a.get(Ik);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function Xk(){try{localStorage.removeItem(Ik)}catch{}}function Zk(){return qk||=(async()=>{try{let e=Wk(await Yk());e?Kk=e:await Yk(Kk),Xk()}catch{}return aA(Kk),Kk})(),qk.then(()=>Kk)}async function Qk(e){await Zk(),await Yk(e),Kk=e,Xk(),aA(e)}function $k(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 eA=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function tA(e){if(!e)return null;let t=Uk(e);if(t===null)return`url("${e}")`;let n=Mk(t);if(!n)return null;let r=`url("${Nk(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!eA||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Nk(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function nA(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var rA=null;function iA(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 aA(e=Jk()){let t=document.documentElement.style,n=rA,r=e.image;if(r?.startsWith(`data:`))try{rA?.dataUrl!==r&&(rA={dataUrl:r,objectUrl:URL.createObjectURL(iA(r))}),r=rA.objectUrl}catch{rA=null,r=null}else rA=null;let i=tA(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,nA(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==rA&&URL.revokeObjectURL(n.objectUrl)}var oA=[{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.`}],sA=`canvas:treeStyle`;function cA(){try{let e=localStorage.getItem(sA);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var lA=cA(),uA=new Set;function dA(){return lA}function fA(e){try{e===`cards`?localStorage.removeItem(sA):localStorage.setItem(sA,e)}catch{}lA=e;for(let e of uA)e()}function pA(e){uA.add(e);let t=t=>{(t.key===sA||t.key===null)&&(lA=cA(),e())};return window.addEventListener(`storage`,t),()=>{uA.delete(e),window.removeEventListener(`storage`,t)}}function mA(){return(0,Q.useSyncExternalStore)(pA,dA,()=>`cards`)}function hA(){let e=mA(),t=s_();return e===`accordion`||e===`accordion-mobile`&&t}var gA=[{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)`]}],_A=gA.map(e=>e.id),vA=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],yA=[{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`}],bA={theme:`canvas`,scheme:`light`,density:`auto`},xA=`canvas.ui.theme`;function SA(e){return typeof e==`string`&&_A.includes(e)}function CA(e){return e===`light`||e===`dark`||e===`system`}function wA(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function TA(e){let t=typeof e==`object`&&e?e:{};return{theme:SA(t.theme)?t.theme:bA.theme,scheme:CA(t.scheme)?t.scheme:bA.scheme,density:wA(t.density)?t.density:bA.density}}var EA=`(prefers-color-scheme: dark)`;function DA(){return typeof document<`u`}function OA(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(EA).matches}function kA(e){return e===`system`?OA()?`dark`:`light`:e}function AA(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(EA),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function jA(e){return AA(e)}function MA(){return OA()?`dark`:`light`}function NA(){return`light`}function PA(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 FA(e,t=DA()?document.documentElement:void 0){let n=kA(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,PA(t),n):n}function IA(e,t=DA()?document.documentElement:void 0){if(!t||typeof window>`u`)return FA(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=FA(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function LA(e){let t=e??BA();if(!t)return bA;try{let e=t.getItem(xA);return e?TA(JSON.parse(e)):bA}catch{return bA}}function RA(e,t){let n=t??BA();if(n)try{n.setItem(xA,JSON.stringify(e))}catch{}}function zA(e){let t=e??BA();if(t)try{t.removeItem(xA)}catch{}}function BA(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function VA({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Q.useState)(()=>({...LA(n),...t})),o=(0,Q.useSyncExternalStore)(jA,MA,NA),s=i.scheme===`system`?o:i.scheme;(0,Q.useEffect)(()=>{IA({...i,scheme:s})},[i,s]),(0,Q.useEffect)(()=>{r&&RA(i,n)},[i,r,n]);let c=(0,Q.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Q.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Q.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Q.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?MA():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Q.useCallback)(()=>{zA(n),a(bA)},[n]),p=(0,Q.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,$.jsx)(Bs.Provider,{value:p,children:e})}var HA={system:Fn,light:Rt,dark:me};function UA(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Vs(),c=Gg(),l=yT(),u=mA(),d=OT();return(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,$.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:gA.map(t=>{let n=t.id===e;return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:J(`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,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,$.jsx)(oe,{className:`size-4 shrink-0 text-primary`})]}),(0,$.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,$.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,$.jsx)(JA,{options:vA.map(e=>{let t=HA[e.id];return{id:e.id,label:e.name,icon:(0,$.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,$.jsx)(JA,{options:yA.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:yA.find(e=>e.id===n)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,$.jsx)(JA,{options:uT.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:_T}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:uT.find(e=>e.id===l)?.description}),l===`strip`&&(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,$.jsx)(JA,{options:bT.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:ET}),(0,$.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[bT.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,$.jsx)(JA,{options:oA.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:fA}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:oA.find(e=>e.id===u)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,$.jsx)(JA,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:Ug}),(0,$.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,$.jsx)(WA,{}),(0,$.jsx)(`section`,{children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s(),Ug(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function WA(){let[e,t]=(0,Q.useState)(Jk),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=!1;return Zk().then(()=>{e||(t(Jk()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await $k(n)}:e;await Qk(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&&Uk(e.image)===null,f=tA(e.image);return(0,$.jsx)(`section`,{children:(0,$.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,$.jsx)(qA,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,$.jsx)(KA,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,$.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),Bk.map(t=>(0,$.jsx)(KA,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:Uk(e.image)===t.id,onSelect:()=>l({...e,image:Hk(t.id)}),children:(0,$.jsx)(`img`,{src:Vk(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,$.jsx)(KA,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,$.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,$.jsx)(GA,{}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:nA(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.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,$.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,$.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,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,$.jsx)(JA,{options:Fk.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function GA(){let e=Bk.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.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 KA({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:J(`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,$.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,$.jsx)(oe,{className:`size-3`})})]})}function qA({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function JA({options:e,value:t,onChange:n}){return(0,$.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,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:J(`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 YA(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`Appearance`,onBack:EO(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,$.jsx)(UA,{})]})}var XA={previousTree:`Alt+Q`,nextTree:`Alt+W`},ZA=`canvas:key-bindings`,QA=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function $A(){try{let e=JSON.parse(localStorage.getItem(ZA)||`{}`),t={...XA};for(let n of Object.keys(t))(e[n]===``||QA.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...XA}:t}catch{return{...XA}}}function ej(e){localStorage.setItem(ZA,JSON.stringify(e))}function tj(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 nj(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function rj(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function ij(){let[e,t]=(0,Q.useState)($A),[n,r]=(0,Q.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{ej(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`Key bindings`,onBack:EO(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,$.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,$.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)||XA[t].slice(-1)}`:``}),children:[(0,$.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]}),(0,$.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)||XA[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,$.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,$.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...XA}),children:`Restore defaults`}),(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var aj=`offline-content-v1`,oj=`offline-api-v1`,sj=1073741824,cj={enabled:!1,budgetBytes:4*sj,excludedWorkspaces:[]},lj=1e3;function uj(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function dj(e,t,n){return`${e}:${t}:${uj(n)}`}var fj=`canvas-offline`,pj=2,mj=null;function hj(){return mj||(mj=new Promise((e,t)=>{let n=indexedDB.open(fj,pj);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(),mj=null},e(n.result)},n.onerror=()=>{mj=null,t(n.error)}}),mj)}function gj(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function _j(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function vj(e,t){return _j((await hj()).transaction(e).objectStore(e).get(t))}async function yj(e){return _j((await hj()).transaction(e).objectStore(e).getAll())}async function bj(e,t,n){let r=(await hj()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),gj(r)}async function xj(e,t){let n=(await hj()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),gj(n)}async function Sj(e){let t=(await hj()).transaction(e,`readwrite`);return t.objectStore(e).clear(),gj(t)}async function Cj(){try{let e=await vj(`config`,`settings`);return e?{...cj,...e}:cj}catch{return cj}}async function wj(e){await bj(`config`,e,`settings`)}async function Tj(e,t){let n=(await hj()).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 gj(n)}async function Ej(e){let t=await yj(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-lj)),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(oj),caches.open(aj)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await xj(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await xj(`entries`,e.url)})])}async function Dj(){let e=await yj(`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 Oj(){await Promise.all([caches.delete(aj),caches.delete(oj)]),await Sj(`entries`),await Sj(`scopes`)}async function kj(){return yj(`scopes`)}async function Aj(e){return vj(`scopes`,e)}async function jj(e){await bj(`scopes`,e)}async function Mj(e){let t=await vj(`scopes`,e);await xj(`scopes`,e),t?.urls.length&&await Nj(t.urls)}async function Nj(e){let t=await yj(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await Tj(r,!1)}var Pj=3,Fj=`data/schema/file`,Ij=128;async function Lj({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await Cj();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=dj(e,n,t),s=uj(t),c=await Aj(o),l=((await Ma(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===Fj),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(Pj,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Eo(e,t.id);d+=n.size,u.push(`${xr.workspaces}/${e}/documents/${t.id}/content`);try{await Qr(e,t.id,Ij),u.push(`${xr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${Ij}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await Tj(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 jj(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await Nj(t)}return g}var Rj=[{label:`1 GB`,bytes:1*sj},{label:`2 GB`,bytes:2*sj},{label:`4 GB`,bytes:4*sj},{label:`8 GB`,bytes:8*sj}];function zj(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/sj).toFixed(2)} GB`}function Bj(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function Vj(){let{showSuccessToast:e,showErrorToast:t}=Wr(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)({}),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useCallback)(()=>{Cj().then(r).catch(()=>{}),Dj().then(a).catch(()=>{}),kj().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,Q.useEffect)(()=>{v(),Ai().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await wj(e),Bj(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),Ej(e.budgetBytes).then(v).catch(()=>{})},b=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];y({...n,excludedWorkspaces:t})},x=async()=>{h(!0);try{await Oj(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},S=async n=>{let r=dj(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await Lj(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${zj(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${zj(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},C=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},w=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),T=async e=>{await Mj(e),v()};return n?(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Hj,{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,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:J(`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,$.jsx)(mr,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,$.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,$.jsx)(oe,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Rj.map(e=>(0,$.jsx)(Z,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,$.jsxs)(`span`,{children:[zj(i.contentBytes),` of `,zj(n.budgetBytes),` used`]}),(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${zj(i.pinnedBytes)} pinned`:``]})]}),(0,$.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,$.jsx)(`div`,{children:(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,$.jsx)(Yn,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(nt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Hj,{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,$.jsx)(`div`,{className:`mb-3`,children:(0,$.jsxs)(Z,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,$.jsx)(Oe,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,$.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.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,$.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,$.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${zj(t.bytes)}`:`listing…`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[zj(e.bytes),e.truncated?` (partial)`:``]}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>S(w(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,$.jsx)(P,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>T(e.id),"aria-label":`Unpin ${e.id}`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,$.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,$.jsxs)(`section`,{children:[(0,$.jsx)(Hj,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,$.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(`span`,{className:J(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,$.jsx)(In,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,$.jsx)(Z,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,$.jsx)(Zp,{onClose:()=>_(!1),children:(0,$.jsx)(nh,{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:C,onClose:()=>_(!1)})})]}):null}function Hj({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function Uj(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`Offline`,onBack:EO(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,$.jsx)(Vj,{})]})}function Wj(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 Gj({name:e,version:t,detail:n}){return(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,$.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function Kj(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!0;return X.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 ${Wj(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`About`,onBack:EO(),description:`Versions of every Canvas component this installation is running.`}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,$.jsx)(Gj,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.0`}),e?.version&&(0,$.jsx)(Gj,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,$.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,$.jsx)(Gj,{name:e,version:`v${t}`},e))})]}),n&&(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,$.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var qj=[`onnx`,`clip`,`blip`,`openai`],Jj=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],Yj=[{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`}],Xj=e=>`${xr.workspaces}/${encodeURIComponent(e)}/inferd`;function Zj(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 Qj(e){return await X.get(`${Xj(e)}/status`)}async function $j(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await X.post(`${Xj(e)}/summarize/images`,n)}async function eM(e){return await X.post(`${Xj(e)}/summarize/images/stop`,{})}async function tM(e){return await X.get(`${Xj(e)}/config`)}async function nM(e,t){return await X.put(`${Xj(e)}/config`,t)}async function rM(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 X.post(`${Xj(e)}/reindex`,n)}async function iM(e){return await X.get(`${Xj(e)}/vector-tables`)}async function aM(e,t){return await X.delete(`${Xj(e)}/vector-tables/${encodeURIComponent(t)}`)}async function oM(){return await X.get(`${xr.inferd}/config`)}async function sM(e){return await X.put(`${xr.inferd}/config`,e)}async function cM(){return await X.get(`${xr.inferd}/defaults`)}async function lM(e){return await X.put(`${xr.inferd}/defaults`,e)}async function uM(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await X.post(`${xr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function dM(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await X.post(`${xr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var fM=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,pM=`font-semibold uppercase tracking-[0.08em]`,mM={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`}},hM=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],gM=[{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.`}],_M=12e4;function vM(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 yM({title:e,hint:t}){return(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`h3`,{className:J(`text-[11px] text-muted-foreground`,pM),children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function bM({overridden:e,source:t}){return e?(0,$.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,$.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 xM({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,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,$.jsx)(bM,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,$.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,$.jsx)(Y,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:J(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,$.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function SM({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,$.jsx)(bM,{overridden:n})]})}function CM({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,Q.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,$.jsx)(bM,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,$.jsxs)($.Fragment,{children:[`Stored: `,(0,$.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{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,$.jsx)(Y,{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,$.jsx)(Z,{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,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function wM({open:e,onClick:t,label:n}){return(0,$.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,$.jsx)(Xe,{className:J(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var TM={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function EM({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}=Vr(),[f,p]=(0,Q.useState)(()=>structuredClone(e)),[m,h]=(0,Q.useState)(new Set),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,Q.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}`)}},F=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),I=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=F(n),a=i.type?mM[i.type]?.url?.key:void 0,o=a?vM(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await uM(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 dM(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)}},L=(0,Q.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?mM[i]?.url?.key:void 0;if(!a)continue;let o=vM(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),R=(0,Q.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),z=async()=>{if(L.length>0){d({title:`Fix the endpoint first`,description:L.join(` · `),variant:`destructive`});return}await u(Zj(f,m)),h(new Set)},ee=e=>T(t=>t===e?null:e);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,$.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,$.jsx)(W,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,$.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(yM,{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,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,$.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,$.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,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`span`,{className:J(`absolute inset-y-0 left-0 w-[3px]`,TM[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,$.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,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:J(`text-[11px]`,pM),children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,$.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,$.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,$.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,$.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,$.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,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>I(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,$.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,$.jsx)(wM,{open:m,onClick:()=>ee(p),label:`Edit ${e}`})]})]}),m&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,$.jsx)(bM,{overridden:s.provider!==void 0,source:u.provider})]}),(0,$.jsxs)(`select`,{className:fM,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]})]}),(0,$.jsx)(xM,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,$.jsx)(xM,{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,$.jsx)(xM,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,$.jsx)(SM,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,$.jsx)(SM,{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,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{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,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(yM,{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,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=Jj.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?mM[l]:void 0,d=u?.url?vM(n[u.url.key]):null,p={...r,...n},h=hM.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,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,$.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(wM,{open:s,onClick:()=>ee(o),label:`Edit ${e}`})]})]}),s&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,$.jsx)(bM,{overridden:n.type!==void 0,source:r.type})]}),(0,$.jsxs)(`select`,{className:fM,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),qj.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),l&&!qj.includes(l)&&(0,$.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,$.jsx)(xM,{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,$.jsx)(xM,{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,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,$.jsx)(bM,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,$.jsxs)(`select`,{className:fM,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),gM.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:gM.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,$.jsx)(xM,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??_M,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,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,$.jsx)(Y,{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,$.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,$.jsx)(CM,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,$.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,$.jsxs)(`span`,{children:[`Not used by type `,(0,$.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,$.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,$.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,$.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{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,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),Yj.filter(e=>!D.includes(e.id)).map(e=>(0,$.jsx)(Z,{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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:R?`default`:`outline`,onClick:z,disabled:s||!R||L.length>0,children:s?`Saving…`:l}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!R,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:L.length>0?(0,$.jsxs)(`span`,{className:`font-medium text-destructive`,children:[L.length,` endpoint `,L.length===1?`needs`:`need`,` fixing`]}):R?`Unsaved changes`:`Everything saved`})]})]})}function DM(){let{showToast:e}=Vr(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=(0,Q.useCallback)(()=>oM().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,Q.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,$.jsx)(Gw,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:EO(),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,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,$.jsx)(EM,{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 sM(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 OM(){let e=dl(),{showToast:t}=Vr(),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,Q.useState)(i),[c,l]=(0,Q.useState)(a),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),g=(0,Q.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 X.get(e,{skipAuth:!0,headers:_()});d(t);let n=await X.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,Q.useRef)(v);return(0,Q.useEffect)(()=>{y.current()},[]),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(Gw,{onBack:EO(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,$.jsx)(Z,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,$.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,$.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,$.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,$.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,$.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,$.jsx)(ud,{className:`mt-8`})]})}function kM(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 AM(){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 jM={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?`${xr.admin.users}?${n}`:xr.admin.users;return await X.get(r)},async getUser(e){return await X.get(`${xr.admin.users}/${e}`)},async createUser(e){return await X.post(xr.admin.users,e)},async updateUser(e,t){return await X.put(`${xr.admin.users}/${e}`,t)},async deleteUser(e){await X.delete(`${xr.admin.users}/${e}`)}},MM={async listAllWorkspaces(){return await X.get(xr.admin.workspaces)},async createWorkspace(e){return await X.post(xr.admin.workspaces,e)},async deleteWorkspace(e){await X.delete(`${xr.admin.workspaces}/${e}`)}},NM={async getLogs(e={}){return(await X.get(`${xr.admin.logs}${kM(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${xr.admin.logsStream}${kM(e)}`,{method:`GET`,headers:AM(),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(`
29
+ `).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||{},...JO(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function Sk(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 X.post(`${Lr}/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:KO(i),metadata:JO(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function Ck(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function wk(){return await X.get(`${Lr}/voice/status`)}async function Tk(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 X.post(`${Lr}/agents/${e}/voice${o}`,r)}var Ek=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:IO,load:async()=>(await Ai()).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:zO,load:async()=>(await ds()).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:VO,load:async()=>(await ik()).map(e=>({id:e.id,label:e.label||e.name}))}];function Dk({to:e,label:t,description:n,icon:r}){return(0,$.jsxs)(ju,{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,$.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,$.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,$.jsx)(Dt,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function Ok({group:e,query:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(`loading`),[c,l]=(0,Q.useState)(0);(0,Q.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=>lT(t,e.label,n.label,n.description));return u.length?(0,$.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,$.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,$.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,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,$.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,$.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,$.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,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,$.jsx)(Dk,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function kk(){let{state:e}=MT(),[t,n]=(0,Q.useState)(``),r=sT.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>lT(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Ek.some(e=>e.sections.some(n=>lT(t,e.label,n.label,n.description)));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,$.jsx)(Gw,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,$.jsx)(Y,{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,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Dk,{to:e.path,...e},e.path))})]},e.id)),Ek.map(e=>(0,$.jsx)(Ok,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Dk,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Ak=[{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`}],jk=`/wallpapers`;function Mk(e){return Ak.find(t=>t.id===e)}function Nk(e,t={}){let n=typeof e==`string`?Mk(e):e;if(!n)return null;let{base:r=jk,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 Pk(e,t=jk){let n=typeof e==`string`?Mk(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var Fk=[{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`}],Ik=`canvas:wallpaper`,Lk=`canvas-wallpaper`,Rk=`settings`,zk=`builtin:`,Bk=Ak;function Vk(e){return Pk(e)??``}function Hk(e){return`${zk}${e}`}function Uk(e){return e?.startsWith(zk)?e.slice(8):null}function Wk(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 Gk(){try{let e=localStorage.getItem(Ik);if(e){let t=Wk(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var Kk=Gk(),qk=null;function Jk(){return Kk}async function Yk(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(Lk,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(Rk),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(Rk,e?`readwrite`:`readonly`),a=i.objectStore(Rk),o=e?a.put(e,Ik):a.get(Ik);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function Xk(){try{localStorage.removeItem(Ik)}catch{}}function Zk(){return qk||=(async()=>{try{let e=Wk(await Yk());e?Kk=e:await Yk(Kk),Xk()}catch{}return aA(Kk),Kk})(),qk.then(()=>Kk)}async function Qk(e){await Zk(),await Yk(e),Kk=e,Xk(),aA(e)}function $k(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 eA=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function tA(e){if(!e)return null;let t=Uk(e);if(t===null)return`url("${e}")`;let n=Mk(t);if(!n)return null;let r=`url("${Nk(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!eA||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Nk(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function nA(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var rA=null;function iA(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 aA(e=Jk()){let t=document.documentElement.style,n=rA,r=e.image;if(r?.startsWith(`data:`))try{rA?.dataUrl!==r&&(rA={dataUrl:r,objectUrl:URL.createObjectURL(iA(r))}),r=rA.objectUrl}catch{rA=null,r=null}else rA=null;let i=tA(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,nA(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==rA&&URL.revokeObjectURL(n.objectUrl)}var oA=[{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.`}],sA=`canvas:treeStyle`;function cA(){try{let e=localStorage.getItem(sA);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var lA=cA(),uA=new Set;function dA(){return lA}function fA(e){try{e===`cards`?localStorage.removeItem(sA):localStorage.setItem(sA,e)}catch{}lA=e;for(let e of uA)e()}function pA(e){uA.add(e);let t=t=>{(t.key===sA||t.key===null)&&(lA=cA(),e())};return window.addEventListener(`storage`,t),()=>{uA.delete(e),window.removeEventListener(`storage`,t)}}function mA(){return(0,Q.useSyncExternalStore)(pA,dA,()=>`cards`)}function hA(){let e=mA(),t=s_();return e===`accordion`||e===`accordion-mobile`&&t}var gA=[{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)`]}],_A=gA.map(e=>e.id),vA=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],yA=[{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`}],bA={theme:`canvas`,scheme:`light`,density:`auto`},xA=`canvas.ui.theme`;function SA(e){return typeof e==`string`&&_A.includes(e)}function CA(e){return e===`light`||e===`dark`||e===`system`}function wA(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function TA(e){let t=typeof e==`object`&&e?e:{};return{theme:SA(t.theme)?t.theme:bA.theme,scheme:CA(t.scheme)?t.scheme:bA.scheme,density:wA(t.density)?t.density:bA.density}}var EA=`(prefers-color-scheme: dark)`;function DA(){return typeof document<`u`}function OA(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(EA).matches}function kA(e){return e===`system`?OA()?`dark`:`light`:e}function AA(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(EA),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function jA(e){return AA(e)}function MA(){return OA()?`dark`:`light`}function NA(){return`light`}function PA(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 FA(e,t=DA()?document.documentElement:void 0){let n=kA(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,PA(t),n):n}function IA(e,t=DA()?document.documentElement:void 0){if(!t||typeof window>`u`)return FA(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=FA(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function LA(e){let t=e??BA();if(!t)return bA;try{let e=t.getItem(xA);return e?TA(JSON.parse(e)):bA}catch{return bA}}function RA(e,t){let n=t??BA();if(n)try{n.setItem(xA,JSON.stringify(e))}catch{}}function zA(e){let t=e??BA();if(t)try{t.removeItem(xA)}catch{}}function BA(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function VA({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Q.useState)(()=>({...LA(n),...t})),o=(0,Q.useSyncExternalStore)(jA,MA,NA),s=i.scheme===`system`?o:i.scheme;(0,Q.useEffect)(()=>{IA({...i,scheme:s})},[i,s]),(0,Q.useEffect)(()=>{r&&RA(i,n)},[i,r,n]);let c=(0,Q.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Q.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Q.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Q.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?MA():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Q.useCallback)(()=>{zA(n),a(bA)},[n]),p=(0,Q.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,$.jsx)(Bs.Provider,{value:p,children:e})}var HA={system:Fn,light:Rt,dark:me};function UA(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Vs(),c=Gg(),l=yT(),u=mA(),d=OT();return(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,$.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:gA.map(t=>{let n=t.id===e;return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:J(`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,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,$.jsx)(oe,{className:`size-4 shrink-0 text-primary`})]}),(0,$.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,$.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,$.jsx)(JA,{options:vA.map(e=>{let t=HA[e.id];return{id:e.id,label:e.name,icon:(0,$.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,$.jsx)(JA,{options:yA.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:yA.find(e=>e.id===n)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,$.jsx)(JA,{options:uT.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:_T}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:uT.find(e=>e.id===l)?.description}),l===`strip`&&(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,$.jsx)(JA,{options:bT.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:ET}),(0,$.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[bT.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,$.jsx)(JA,{options:oA.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:fA}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:oA.find(e=>e.id===u)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(qA,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,$.jsx)(JA,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:Ug}),(0,$.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,$.jsx)(WA,{}),(0,$.jsx)(`section`,{children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s(),Ug(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function WA(){let[e,t]=(0,Q.useState)(Jk),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=!1;return Zk().then(()=>{e||(t(Jk()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await $k(n)}:e;await Qk(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&&Uk(e.image)===null,f=tA(e.image);return(0,$.jsx)(`section`,{children:(0,$.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,$.jsx)(qA,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,$.jsx)(KA,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,$.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),Bk.map(t=>(0,$.jsx)(KA,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:Uk(e.image)===t.id,onSelect:()=>l({...e,image:Hk(t.id)}),children:(0,$.jsx)(`img`,{src:Vk(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,$.jsx)(KA,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,$.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,$.jsx)(GA,{}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:nA(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.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,$.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,$.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,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,$.jsx)(JA,{options:Fk.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function GA(){let e=Bk.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.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 KA({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:J(`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,$.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,$.jsx)(oe,{className:`size-3`})})]})}function qA({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function JA({options:e,value:t,onChange:n}){return(0,$.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,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:J(`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 YA(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`Appearance`,onBack:EO(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,$.jsx)(UA,{})]})}var XA={previousTree:`Alt+Q`,nextTree:`Alt+W`},ZA=`canvas:key-bindings`,QA=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function $A(){try{let e=JSON.parse(localStorage.getItem(ZA)||`{}`),t={...XA};for(let n of Object.keys(t))(e[n]===``||QA.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...XA}:t}catch{return{...XA}}}function ej(e){localStorage.setItem(ZA,JSON.stringify(e))}function tj(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 nj(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function rj(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function ij(){let[e,t]=(0,Q.useState)($A),[n,r]=(0,Q.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{ej(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`Key bindings`,onBack:EO(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,$.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,$.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)||XA[t].slice(-1)}`:``}),children:[(0,$.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]}),(0,$.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)||XA[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,$.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,$.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...XA}),children:`Restore defaults`}),(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var aj=`offline-content-v1`,oj=`offline-api-v1`,sj=1073741824,cj={enabled:!1,budgetBytes:4*sj,excludedWorkspaces:[]},lj=1e3;function uj(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function dj(e,t,n){return`${e}:${t}:${uj(n)}`}var fj=`canvas-offline`,pj=2,mj=null;function hj(){return mj||(mj=new Promise((e,t)=>{let n=indexedDB.open(fj,pj);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(),mj=null},e(n.result)},n.onerror=()=>{mj=null,t(n.error)}}),mj)}function gj(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function _j(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function vj(e,t){return _j((await hj()).transaction(e).objectStore(e).get(t))}async function yj(e){return _j((await hj()).transaction(e).objectStore(e).getAll())}async function bj(e,t,n){let r=(await hj()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),gj(r)}async function xj(e,t){let n=(await hj()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),gj(n)}async function Sj(e){let t=(await hj()).transaction(e,`readwrite`);return t.objectStore(e).clear(),gj(t)}async function Cj(){try{let e=await vj(`config`,`settings`);return e?{...cj,...e}:cj}catch{return cj}}async function wj(e){await bj(`config`,e,`settings`)}async function Tj(e,t){let n=(await hj()).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 gj(n)}async function Ej(e){let t=await yj(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-lj)),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(oj),caches.open(aj)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await xj(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await xj(`entries`,e.url)})])}async function Dj(){let e=await yj(`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 Oj(){await Promise.all([caches.delete(aj),caches.delete(oj)]),await Sj(`entries`),await Sj(`scopes`)}async function kj(){return yj(`scopes`)}async function Aj(e){return vj(`scopes`,e)}async function jj(e){await bj(`scopes`,e)}async function Mj(e){let t=await vj(`scopes`,e);await xj(`scopes`,e),t?.urls.length&&await Nj(t.urls)}async function Nj(e){let t=await yj(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await Tj(r,!1)}var Pj=3,Fj=`data/schema/file`,Ij=128;async function Lj({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await Cj();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=dj(e,n,t),s=uj(t),c=await Aj(o),l=((await Ma(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===Fj),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(Pj,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Eo(e,t.id);d+=n.size,u.push(`${xr.workspaces}/${e}/documents/${t.id}/content`);try{await Qr(e,t.id,Ij),u.push(`${xr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${Ij}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await Tj(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 jj(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await Nj(t)}return g}var Rj=[{label:`1 GB`,bytes:1*sj},{label:`2 GB`,bytes:2*sj},{label:`4 GB`,bytes:4*sj},{label:`8 GB`,bytes:8*sj}];function zj(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/sj).toFixed(2)} GB`}function Bj(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function Vj(){let{showSuccessToast:e,showErrorToast:t}=Wr(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)({}),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useCallback)(()=>{Cj().then(r).catch(()=>{}),Dj().then(a).catch(()=>{}),kj().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,Q.useEffect)(()=>{v(),Ai().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await wj(e),Bj(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),Ej(e.budgetBytes).then(v).catch(()=>{})},b=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];y({...n,excludedWorkspaces:t})},x=async()=>{h(!0);try{await Oj(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},S=async n=>{let r=dj(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await Lj(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${zj(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${zj(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},C=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},w=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),T=async e=>{await Mj(e),v()};return n?(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Hj,{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,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:J(`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,$.jsx)(mr,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,$.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,$.jsx)(oe,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Rj.map(e=>(0,$.jsx)(Z,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,$.jsxs)(`span`,{children:[zj(i.contentBytes),` of `,zj(n.budgetBytes),` used`]}),(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${zj(i.pinnedBytes)} pinned`:``]})]}),(0,$.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,$.jsx)(`div`,{children:(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,$.jsx)(Yn,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(nt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Hj,{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,$.jsx)(`div`,{className:`mb-3`,children:(0,$.jsxs)(Z,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,$.jsx)(Oe,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,$.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.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,$.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,$.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${zj(t.bytes)}`:`listing…`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[zj(e.bytes),e.truncated?` (partial)`:``]}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>S(w(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,$.jsx)(P,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>T(e.id),"aria-label":`Unpin ${e.id}`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,$.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,$.jsxs)(`section`,{children:[(0,$.jsx)(Hj,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,$.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(`span`,{className:J(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,$.jsx)(In,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,$.jsx)(Z,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,$.jsx)(Zp,{onClose:()=>_(!1),children:(0,$.jsx)(nh,{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:C,onClose:()=>_(!1)})})]}):null}function Hj({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function Uj(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`Offline`,onBack:EO(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,$.jsx)(Vj,{})]})}function Wj(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 Gj({name:e,version:t,detail:n}){return(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,$.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function Kj(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!0;return X.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 ${Wj(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(Gw,{className:`mb-6`,title:`About`,onBack:EO(),description:`Versions of every Canvas component this installation is running.`}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,$.jsx)(Gj,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.1`}),e?.version&&(0,$.jsx)(Gj,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,$.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,$.jsx)(Gj,{name:e,version:`v${t}`},e))})]}),n&&(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,$.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var qj=[`onnx`,`clip`,`blip`,`openai`],Jj=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],Yj=[{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`}],Xj=e=>`${xr.workspaces}/${encodeURIComponent(e)}/inferd`;function Zj(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 Qj(e){return await X.get(`${Xj(e)}/status`)}async function $j(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await X.post(`${Xj(e)}/summarize/images`,n)}async function eM(e){return await X.post(`${Xj(e)}/summarize/images/stop`,{})}async function tM(e){return await X.get(`${Xj(e)}/config`)}async function nM(e,t){return await X.put(`${Xj(e)}/config`,t)}async function rM(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 X.post(`${Xj(e)}/reindex`,n)}async function iM(e){return await X.get(`${Xj(e)}/vector-tables`)}async function aM(e,t){return await X.delete(`${Xj(e)}/vector-tables/${encodeURIComponent(t)}`)}async function oM(){return await X.get(`${xr.inferd}/config`)}async function sM(e){return await X.put(`${xr.inferd}/config`,e)}async function cM(){return await X.get(`${xr.inferd}/defaults`)}async function lM(e){return await X.put(`${xr.inferd}/defaults`,e)}async function uM(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await X.post(`${xr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function dM(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await X.post(`${xr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var fM=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,pM=`font-semibold uppercase tracking-[0.08em]`,mM={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`}},hM=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],gM=[{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.`}],_M=12e4;function vM(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 yM({title:e,hint:t}){return(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`h3`,{className:J(`text-[11px] text-muted-foreground`,pM),children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function bM({overridden:e,source:t}){return e?(0,$.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,$.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 xM({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,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,$.jsx)(bM,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,$.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,$.jsx)(Y,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:J(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,$.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function SM({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,$.jsx)(bM,{overridden:n})]})}function CM({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,Q.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,$.jsx)(bM,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,$.jsxs)($.Fragment,{children:[`Stored: `,(0,$.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{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,$.jsx)(Y,{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,$.jsx)(Z,{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,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function wM({open:e,onClick:t,label:n}){return(0,$.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,$.jsx)(Xe,{className:J(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var TM={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function EM({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}=Vr(),[f,p]=(0,Q.useState)(()=>structuredClone(e)),[m,h]=(0,Q.useState)(new Set),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,Q.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}`)}},F=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),I=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=F(n),a=i.type?mM[i.type]?.url?.key:void 0,o=a?vM(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await uM(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 dM(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)}},L=(0,Q.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?mM[i]?.url?.key:void 0;if(!a)continue;let o=vM(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),R=(0,Q.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),z=async()=>{if(L.length>0){d({title:`Fix the endpoint first`,description:L.join(` · `),variant:`destructive`});return}await u(Zj(f,m)),h(new Set)},ee=e=>T(t=>t===e?null:e);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,$.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,$.jsx)(W,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,$.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(yM,{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,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,$.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,$.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,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`span`,{className:J(`absolute inset-y-0 left-0 w-[3px]`,TM[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,$.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,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:J(`text-[11px]`,pM),children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,$.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,$.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,$.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,$.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,$.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,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>I(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,$.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,$.jsx)(wM,{open:m,onClick:()=>ee(p),label:`Edit ${e}`})]})]}),m&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,$.jsx)(bM,{overridden:s.provider!==void 0,source:u.provider})]}),(0,$.jsxs)(`select`,{className:fM,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]})]}),(0,$.jsx)(xM,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,$.jsx)(xM,{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,$.jsx)(xM,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,$.jsx)(SM,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,$.jsx)(SM,{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,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{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,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(yM,{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,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=Jj.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?mM[l]:void 0,d=u?.url?vM(n[u.url.key]):null,p={...r,...n},h=hM.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,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,$.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(wM,{open:s,onClick:()=>ee(o),label:`Edit ${e}`})]})]}),s&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,$.jsx)(bM,{overridden:n.type!==void 0,source:r.type})]}),(0,$.jsxs)(`select`,{className:fM,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),qj.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),l&&!qj.includes(l)&&(0,$.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,$.jsx)(xM,{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,$.jsx)(xM,{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,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,$.jsx)(bM,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,$.jsxs)(`select`,{className:fM,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),gM.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:gM.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,$.jsx)(xM,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??_M,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,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,$.jsx)(Y,{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,$.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,$.jsx)(CM,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,$.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,$.jsxs)(`span`,{children:[`Not used by type `,(0,$.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,$.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,$.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,$.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{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,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),Yj.filter(e=>!D.includes(e.id)).map(e=>(0,$.jsx)(Z,{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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:R?`default`:`outline`,onClick:z,disabled:s||!R||L.length>0,children:s?`Saving…`:l}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!R,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:L.length>0?(0,$.jsxs)(`span`,{className:`font-medium text-destructive`,children:[L.length,` endpoint `,L.length===1?`needs`:`need`,` fixing`]}):R?`Unsaved changes`:`Everything saved`})]})]})}function DM(){let{showToast:e}=Vr(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=(0,Q.useCallback)(()=>oM().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,Q.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,$.jsx)(Gw,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:EO(),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,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,$.jsx)(EM,{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 sM(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 OM(){let e=dl(),{showToast:t}=Vr(),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,Q.useState)(i),[c,l]=(0,Q.useState)(a),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),g=(0,Q.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 X.get(e,{skipAuth:!0,headers:_()});d(t);let n=await X.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,Q.useRef)(v);return(0,Q.useEffect)(()=>{y.current()},[]),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(Gw,{onBack:EO(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,$.jsx)(Z,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,$.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,$.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,$.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,$.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,$.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,$.jsx)(ud,{className:`mt-8`})]})}function kM(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 AM(){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 jM={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?`${xr.admin.users}?${n}`:xr.admin.users;return await X.get(r)},async getUser(e){return await X.get(`${xr.admin.users}/${e}`)},async createUser(e){return await X.post(xr.admin.users,e)},async updateUser(e,t){return await X.put(`${xr.admin.users}/${e}`,t)},async deleteUser(e){await X.delete(`${xr.admin.users}/${e}`)}},MM={async listAllWorkspaces(){return await X.get(xr.admin.workspaces)},async createWorkspace(e){return await X.post(xr.admin.workspaces,e)},async deleteWorkspace(e){await X.delete(`${xr.admin.workspaces}/${e}`)}},NM={async getLogs(e={}){return(await X.get(`${xr.admin.logs}${kM(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${xr.admin.logsStream}${kM(e)}`,{method:`GET`,headers:AM(),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(`
30
30
  `),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(`
31
31
  `));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(`
32
32
 
@@ -48,7 +48,7 @@ set -euo pipefail
48
48
  `),onClick:()=>n(l.split(`
49
49
  `).map(e=>e.trim()).filter(Boolean)),children:`Save exclusions`}),o>0&&(0,$.jsxs)(`button`,{type:`button`,className:`text-[11px] text-muted-foreground hover:text-foreground`,onClick:()=>f(!d),children:[d?`Hide`:`Show`,` default patterns`]})]}),d&&(0,$.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(`
50
50
  `)})]})]})}function nI({device:e,linked:t,busy:n,onLink:r,onUnlink:i,onUpdate:a}){let[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(e.name),[u,d]=(0,Q.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,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,$.jsx)(Fn,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[o?(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Y,{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,$.jsx)(Y,{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,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,$.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,$.jsx)(`span`,{children:e.deviceId}),e.platform&&(0,$.jsx)(`span`,{children:e.platform}),e.arch&&(0,$.jsx)(`span`,{children:e.arch}),e.type&&(0,$.jsx)(`span`,{children:e.type})]})]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:f,disabled:!c.trim(),children:(0,$.jsx)(oe,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:p,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}):(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>s(!0),title:`Edit name/description`,children:(0,$.jsx)(_e,{className:`h-3.5 w-3.5`})}),t?(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:i,className:`text-destructive hover:text-destructive`,title:`Remove from workspace`,children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})}):(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:r,title:`Link to workspace`,children:(0,$.jsx)(Zt,{className:`h-3.5 w-3.5`})}),t&&(0,$.jsx)(`span`,{className:`rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary`,children:`linked`})]})]})})}function rI({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,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading devices…`]}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.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,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:i,disabled:n,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),e.length===0?(0,$.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,$.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]}):(0,$.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,$.jsx)(nI,{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 iI({label:e,value:t,mono:n=!1}){return(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-2 border-b last:border-0`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:e}),(0,$.jsx)(`span`,{className:`text-xs text-right ${n?`font-mono`:``}`,children:t??`—`})]})}function aI({workspaceName:e,current:t,weights:n,floorMode:r,relativeMargin:i,onDone:a}){let[o,s]=(0,Q.useState)(t==null?``:String(t)),[c,l]=(0,Q.useState)(r??`relative`),[u,d]=(0,Q.useState)(i==null?`0.035`:String(i)),[f,p]=(0,Q.useState)(n?.fts==null?`2`:String(n.fts)),[m,h]=(0,Q.useState)(n?.dense==null?`1`:String(n.dense)),[g,_]=(0,Q.useState)(n?.image==null?`2`:String(n.image)),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(YE);return(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`How photo relevance is decided`}),(0,$.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,$.jsx)(`option`,{value:`relative`,children:`Relative to the best match (recommended)`}),(0,$.jsx)(`option`,{value:`absolute`,children:`Absolute distance cutoff`})]}),(0,$.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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Window width (distance from the best match)`}),(0,$.jsx)(Y,{value:u,onChange:e=>d(e.target.value),placeholder:`0.035`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,$.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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.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,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`0.95`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,$.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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Hybrid fusion weights (0 disables a signal)`}),(0,$.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,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:e}),(0,$.jsx)(Y,{value:t,onChange:e=>n(e.target.value),className:`h-8 w-16 font-mono text-xs`,inputMode:`decimal`})]},e))}),(0,$.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,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{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 ja(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,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:b})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>{XE(e.target.checked),C(e.target.checked)}}),(0,$.jsx)(`span`,{children:`Debug query`})]}),(0,$.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 oI({stats:e,isLoading:t,onRefresh:n,workspaceName:r}){return t?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading stats…`]}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Live snapshot from synapsd. Click refresh for updated counts.`}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:n,disabled:t,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),(0,$.jsx)(uI,{workspaceName:r,vectorSpaces:Object.keys(e?.semantic?.vectorSpaces||{}),onDone:n}),e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(er,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Core Index`})]}),(0,$.jsx)(iI,{label:`Backend`,value:e.dbBackend,mono:!0}),(0,$.jsx)(iI,{label:`Status`,value:e.status}),(0,$.jsx)(iI,{label:`Path`,value:e.dbPath,mono:!0}),(0,$.jsx)(iI,{label:`Documents`,value:e.documentCount?.toLocaleString()}),(0,$.jsx)(iI,{label:`Metadata entries`,value:e.metadataCount?.toLocaleString()}),(0,$.jsx)(iI,{label:`Checksum index`,value:e.checksumIndexSize?.toLocaleString()}),(0,$.jsx)(iI,{label:`Bitmap store`,value:e.bitmapStoreSize?.toLocaleString()}),(0,$.jsx)(iI,{label:`Bitmap cache`,value:e.bitmapCacheSize?.toLocaleString()}),(0,$.jsx)(iI,{label:`Deleted (pending GC)`,value:e.deletedDocumentsCount?.toLocaleString()})]}),e.fts&&(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(Gt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Full-Text Search (LanceDB)`})]}),`ready`in e.fts&&(0,$.jsx)(iI,{label:`Ready`,value:String(e.fts.ready)}),e.fts.rowCount!==void 0&&(0,$.jsx)(iI,{label:`Row count`,value:e.fts.rowCount?.toLocaleString()}),e.fts.error&&(0,$.jsx)(iI,{label:`Error`,value:(0,$.jsx)(`span`,{className:`text-destructive`,children:e.fts.error})})]}),e.semantic&&(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(Gt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Semantic / Vector Search`})]}),(0,$.jsx)(iI,{label:`Enabled`,value:String(e.semantic.enabled)}),e.semantic.enabled&&(0,$.jsxs)($.Fragment,{children:[e.inferd?.routing?Object.entries(e.inferd.routing).map(([e,t])=>(0,$.jsx)(iI,{label:`Embeds → ${e}`,value:(0,$.jsx)(`span`,{className:`font-mono text-[11px]`,children:t.join(`, `)})},`route-${e}`)):(0,$.jsx)(iI,{label:`Text-embeddable (gap default)`,value:e.semantic.embeddableSchemas?.join(`, `)}),e.semantic.vectorSpaces&&Object.entries(e.semantic.vectorSpaces).map(([e,t])=>(0,$.jsx)(iI,{label:`Space: ${e} (${t.dim??`?`}-d)`,value:t.error?(0,$.jsx)(`span`,{className:`text-destructive`,children:t.error}):`${(t.embeddedDocs??0).toLocaleString()} docs · ${(t.chunkRows??0).toLocaleString()} vectors`},e)),(0,$.jsx)(iI,{label:`Photo relevance`,value:e.semantic.imageFloorMode===`absolute`?`absolute cutoff`:`relative ±${e.semantic.imageRelativeMargin??.035}`,mono:!0}),(0,$.jsx)(iI,{label:e.semantic.imageFloorMode===`absolute`?`Image relevance floor`:`Hard ceiling`,value:e.semantic.imageMaxDistance==null?`off`:e.semantic.imageMaxDistance,mono:!0}),(0,$.jsx)(iI,{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,$.jsx)(aI,{workspaceName:r,current:e.semantic.imageMaxDistance,weights:e.semantic.searchWeights,floorMode:e.semantic.imageFloorMode,relativeMargin:e.semantic.imageRelativeMargin,onDone:n})]})]})]}):(0,$.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No stats available.`})]})}function sI(){let{workspaceName:e}=vl();return(0,$.jsx)(cI,{},e)}function cI(){let{workspaceName:e,tab:t}=vl(),[n,r]=Lu(),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,Q.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,Q.useCallback)(()=>{r(e=>{for(let t of[`addRuleKind`,`addRulePath`,`addRuleTarget`,`addRuleStoreTo`,`addRuleStoreFolder`])e.delete(t);return e},{replace:!0})},[r]),g=ml(),{showToast:_,showProgress:v}=Vr(),y=s_(),{goBack:b}=MT(),x=RO(t);(0,Q.useEffect)(()=>{t!==x&&g(`/workspaces/${e}/settings/${x}`,{replace:!0})},[t,x,e,g]);let[S,C]=(0,Q.useState)(null),w=Ep(S),[T,E]=(0,Q.useState)(0),[D,O]=(0,Q.useState)(!0),[k,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(``),[L,R]=(0,Q.useState)(``),[z,ee]=(0,Q.useState)(`#FFFFFF`),[ne,B]=(0,Q.useState)(null),[re,ie]=(0,Q.useState)(null),[ae,oe]=(0,Q.useState)([]),[V,H]=(0,Q.useState)(null),[U,se]=(0,Q.useState)([]),[W,ce]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(null),[de,fe]=(0,Q.useState)(!1),[pe,me]=(0,Q.useState)([]),[G,he]=(0,Q.useState)([]),[ge,_e]=(0,Q.useState)(!1),[ve,K]=(0,Q.useState)(null),q=e||S?.id||``,ye=(0,Q.useRef)(q);(0,Q.useEffect)(()=>{ye.current=q});let be=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t)try{let e=await Ni(t);oe(e.publicCanvasShares)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load shares`,variant:`destructive`})}},[_]),xe=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t){fe(!0);try{let e=await ba(t);ue(e)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load DB stats`,variant:`destructive`})}finally{fe(!1)}}},[_]),Se=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t){_e(!0);try{let[e,n]=await Promise.all([OO(),jO(t)]);me(e),he(n)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{_e(!1)}}},[_]),Ce=async e=>{K(e);try{await MO(q,e),await Se(),_({title:`Linked`,description:`Device linked to workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to link device`,variant:`destructive`})}finally{K(null)}},we=async e=>{K(e);try{await NO(q,e),he(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{K(null)}},Te=async(e,t)=>{K(`edit:${e}`);try{let n=await kO(e,t);me(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{K(null)}},Ee=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(!t)return;let[n,r]=await Promise.all([Xa(t).catch(()=>null),To(t).catch(()=>[])]);H(n),se(r.filter(e=>e.kind===`storage`))},[]),De=U.some(e=>e.resyncing);(0,Q.useEffect)(()=>{if(!w||!De||!q)return;let e=setInterval(()=>{Ee()},4e3);return()=>clearInterval(e)},[w,De,q,Ee]),(0,Q.useEffect)(()=>{let t=!1;async function n(){try{let n=await Ai();if(t)return;let r=n.find(t=>t.id===e)??n.find(t=>t.name===e);if(C(r??null),r){if(!Ep(r))return;I(r.label||``),R(r.description||``),ee(r.color||`#FFFFFF`),B(r.icon??null),r.status===`active`&&await Promise.all([be(e||r.id),Ee(e||r.id)])}}catch{t||_({title:`Error`,description:`Failed to load workspace`,variant:`destructive`})}finally{t||O(!1)}}return n(),()=>{t=!0}},[e,be,Ee,_,T]),(0,Q.useEffect)(()=>{let e=()=>E(e=>e+1);return window.addEventListener(`workspaces:refresh`,e),()=>window.removeEventListener(`workspaces:refresh`,e)},[]);let Oe=(0,Q.useRef)(!1),ke=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{Oe.current=!!le||de,ke.current=ge||pe.length>0}),(0,Q.useEffect)(()=>{w&&(S?.status===`active`&&x===`db`&&q&&!Oe.current&&xe(),S?.status===`active`&&x===`devices`&&q&&!ke.current&&Se())},[w,x,q,S?.status,xe,Se]);let Ae=async e=>{if(e.preventDefault(),S){j(!0);try{await aa(q,{label:F.trim(),description:L.trim(),color:z,icon:ne}),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{j(!1)}}},je=async()=>{if(S&&window.confirm(`Destroy workspace "${S.label||S.name}"? This cannot be undone.`)){N(!0);try{await mi(q),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{N(!1)}}},Me=()=>{for(let t of[e,S?.name,S?.id])t&&ka(t,`backends`);window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:q}}))},Ne=async e=>{if(e.config?.supported!==!1){ce(`backend:${e.address}`);try{await Ta(q,e.driver,e.address,{enabled:!e.enabled}),await Ee(),Me(),_({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{ce(null)}}},Pe=async(e,t,n)=>{ce(`${n}:${e.address}`);try{await Ta(q,e.driver,e.address,t),await Ee()}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{ce(null)}},Fe=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.`)){ce(`remove:${e.address}`);try{await Xi(q,e.driver,e.address),await Ee(),Me(),_({title:`Removed`,description:`${t} unmounted`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to remove backend`,variant:`destructive`})}finally{ce(null)}}},Ie=async e=>{ce(`resync:${e.address}`);try{await wb(v,q,e.driver,e.address,e=>{se(t=>t.map(t=>t.driver===e.driver&&t.address===e.address?e:t))}),await Ee()}catch{}finally{ce(null)}},Le=async e=>{ce(`test:${e.address}`);try{await _a(q,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{ce(null)}},Re=async e=>{ce(`stopsync:${e.address}`);try{await Za(q,e.driver,e.address),await Ee(),_({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{ce(null)}},ze=async(e,t)=>{ce(`service:${e}`);try{t?await Na(q,e):await wi(q,e),await Ee(),_({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{ce(null)}},Be=async e=>{let t=`${window.location.origin}${e.url}`;await navigator.clipboard?.writeText(t),_({title:`Copied`,description:t})},Ve=async e=>{if(S&&window.confirm(`Revoke public share for "${e.path}"?`)){ce(`share:${e.code}`);try{await ya(q,e.code),await be(q),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:q}})),_({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{ce(null)}}},He=IO.find(e=>e.id===x);return D?(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`}):S?w?(0,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,$.jsx)(Gw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${He.label} - ${S.label||S.name}`,description:`This workspace · ${He.description}`,backTo:`/workspaces/${e}`,onBack:y?b:void 0}),S.status!==`active`&&x!==`general`&&x!==`backups`&&(0,$.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,$.jsx)(tP,{workspaceId:q,onRestored:()=>E(e=>e+1)}),x===`general`&&(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`form`,{onSubmit:Ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-id`,className:`text-sm font-medium`,children:`Workspace ID`}),(0,$.jsx)(Y,{id:`ws-id`,value:S.id,readOnly:!0,className:`font-mono text-sm`,onFocus:e=>e.currentTarget.select()})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-label`,className:`text-sm font-medium`,children:`Label`}),(0,$.jsx)(Y,{id:`ws-label`,value:F,onChange:e=>I(e.target.value),placeholder:`Workspace Label`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`ws-description`,value:L,onChange:e=>R(e.target.value),placeholder:`Description (optional)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Icon & color`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>ie({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,$.jsx)(f,{icon:ne||`ph:stack-fill`,width:22,height:22,color:jm(z)})}),(0,$.jsx)(Y,{id:`ws-color`,type:`color`,value:z,onChange:e=>ee(e.target.value),className:`h-10 w-16 p-1`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ee(Om()),children:`Randomize`})]})]}),(0,$.jsx)(Z,{type:`submit`,disabled:k||!F.trim(),children:k?`Saving...`:`Save Changes`})]}),re&&(0,$.jsx)(Yw,{x:re.x,y:re.y,current:{icon:ne??void 0,color:z},onChange:e=>{`icon`in e&&B(e.icon??null),`color`in e&&e.color&&ee(e.color)},onClose:()=>ie(null)}),(0,$.jsx)(pP,{currentMode:S.protection?.mode,workspaceId:q,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),S.status===`active`&&(0,$.jsx)(lI,{workspaceName:e}),S.status===`active`&&(0,$.jsx)(eI,{workspaceId:q}),(0,$.jsx)(KF,{workspaceId:q,workspaceName:S.label||S.name,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),(0,$.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,$.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,$.jsxs)(Z,{variant:`destructive`,disabled:M,onClick:je,children:[(0,$.jsx)(nt,{className:`mr-2 h-4 w-4`}),M?`Destroying...`:`Destroy Workspace`]})]})]}),S.status===`active`&&x===`shares`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Members`}),(0,$.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,$.jsx)(GF,{workspaceId:q})]}),(0,$.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Public Canvas Shares`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Active public canvas links for this workspace.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>be(),children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),ae.length===0?(0,$.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No public canvas shares. Good.`}):ae.map(e=>{let t=`${window.location.origin}${e.url}`;return(0,$.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate font-mono text-sm`,children:e.path}),(0,$.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,$.jsxs)(`div`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`locks: `,e.lockedBy.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>Be(e),children:(0,$.jsx)(A,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>window.open(t,`_blank`,`noreferrer`),children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`share:${e.code}`,onClick:()=>Ve(e),className:`text-destructive hover:text-destructive`,children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})})]})]}),(0,$.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,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workspace ACL Tokens`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Generate token-based workspace access for devices, scripts, and other users.`})]}),(0,$.jsx)(VF,{workspaceId:q})]})]}),S.status===`active`&&x===`data`&&(0,$.jsxs)(`div`,{className:`space-y-3`,children:[U.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&&!qF[n],s=qF[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=xm(e);return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(f,{icon:p.icon,width:16,height:16,color:p.color,className:`shrink-0`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:s.title}),!c&&(0,$.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,children:`unsupported`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s.description}),typeof t.root==`string`&&t.root&&(0,$.jsx)(`p`,{className:`mt-2 truncate font-mono text-xs text-muted-foreground`,children:t.root}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[`status: `,e.status]}),e.resyncing&&(0,$.jsxs)(`span`,{className:`flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 font-medium text-primary`,children:[(0,$.jsx)(P,{className:`h-3 w-3 animate-spin`}),`indexing`,e.progress?` ${e.progress.scanned}${e.progress.total==null?``:` / ${e.progress.total}`}`:``]}),r?.name&&(0,$.jsxs)(`span`,{title:r.id,children:[`device: `,r.name]}),t.readOnly===!0&&(0,$.jsx)(`span`,{className:`rounded bg-warning/15 px-1.5 py-0.5 font-medium text-warning`,children:`read-only`}),e.lastSyncAt&&(0,$.jsxs)(`span`,{children:[`last scan: `,new Date(e.lastSyncAt).toLocaleString()]})]}),e.lastError&&(0,$.jsx)(`p`,{className:`mt-2 text-xs text-destructive`,children:e.lastError}),t.readOnly===!0&&(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-3`,children:[e.capabilities?.sync&&c&&(0,$.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,$.jsx)(YF,{checked:t.scanOnStart===!0,disabled:W===`startup:${n}`,onClick:()=>Pe(e,{scanOnStart:t.scanOnStart!==!0},`startup`)})]}),(e.driver===`file`||i||a)&&u&&(0,$.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,$.jsx)(YF,{checked:!!t.watch,disabled:!e.enabled||W===`watch:${n}`,onClick:()=>Pe(e,{watch:!t.watch},`watch`)})]}),d&&(0,$.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,$.jsx)(YF,{checked:t.readOnly===!0,disabled:W===`readonly:${n}`,onClick:()=>Pe(e,{readOnly:t.readOnly!==!0},`readonly`)})]}),(e.driver===`file`||e.driver===`cacache`)&&c&&(0,$.jsx)(QF,{workspaceId:q,backend:e}),e.capabilities?.test&&(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`test:${n}`,onClick:()=>Le(e),title:`Verify credentials and root folder`,children:[(0,$.jsx)(Gt,{className:`mr-2 h-3.5 w-3.5`}),W===`test:${n}`?`Testing…`:`Test`]}),e.capabilities?.sync&&(e.resyncing?(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`stopsync:${n}`,onClick:()=>Re(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,$.jsx)(zn,{className:`mr-2 h-3.5 w-3.5 fill-current`}),W===`stopsync:${n}`?`Stopping…`:`Stop sync`]}):(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`resync:${n}`,onClick:()=>Ie(e),children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${W===`resync:${n}`?`animate-spin`:``}`}),`Re-sync`]})),l?(0,$.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,$.jsx)(YF,{checked:!!e.enabled,disabled:!u||W===`backend:${n}`,onClick:()=>Ne(e)}),o&&(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:W===`remove:${n}`,title:`Unmount this folder (no files are deleted)`,onClick:()=>Fe(e),children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})]}),c&&(0,$.jsx)(sE,{value:t.removalPolicy,backends:U,source:n,destination:t.propagatedRemovalSupported===!0,onSave:async t=>{await Ta(q,e.driver,e.address,{removalPolicy:t}),await Ee()}}),a&&(0,$.jsx)(fP,{workspaceId:q,backend:e,onSaved:async()=>{await Ee(),Me()}}),e.driver===`file`&&c&&!l&&(0,$.jsx)(tI,{backend:e,busy:W===`exclude:${n}`,onSave:t=>Pe(e,{exclude:t},`exclude`)})]},n)}),(0,$.jsx)(dP,{workspaceId:q,children:(0,$.jsx)($F,{workspaceId:q})},q),(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start`,children:[(0,$.jsx)(XF,{workspaceId:q,onAdded:async()=>{await Ee(),Me()}}),(0,$.jsx)(ZF,{workspaceId:q,onAdded:async()=>{await Ee(),Me()}}),(0,$.jsx)(fP,{workspaceId:q,onSaved:async()=>{await Ee(),Me()}})]}),e&&(0,$.jsx)(`section`,{className:`border-t pt-4`,children:(0,$.jsx)(lE,{workspaceName:e})})]}),S.status===`active`&&x===`db`&&(0,$.jsxs)(`div`,{className:`space-y-8`,children:[q&&(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Embeddings`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Which model turns this workspace's content into vectors, and where those vectors live.`})]}),(0,$.jsx)(wP,{workspaceId:q,workspaceName:e})]}),(0,$.jsx)(oI,{stats:le,isLoading:de,onRefresh:()=>xe(),workspaceName:e})]}),S.status===`active`&&x===`devices`&&(0,$.jsx)(rI,{allDevices:pe,linkedDevices:G,isLoading:ge,deviceBusy:ve,onRefresh:()=>Se(),onLink:Ce,onUnlink:we,onUpdate:Te}),S.status===`active`&&x===`sync`&&(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(kF,{workspaceId:q,workspaceUuid:S?.id})}),S.status===`active`&&x===`services`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[q&&(0,$.jsx)(IF,{workspaceId:q}),(0,$.jsx)(`div`,{className:`space-y-3`,children:JF.map(e=>{let t=V?.[e.id]||V?.[e.id===`git`?`dotfiles`:e.id===`webdav`?`home`:`imap`],n=!!t?.enabled;return(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Jt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:e.title})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:e.description}),(0,$.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[`initialized: `,t?.initialized?`true`:`false`]})]}),(0,$.jsx)(YF,{checked:n,disabled:W===`service:${e.id}`,onClick:()=>ze(e.id,n)})]})},e.id)})}),(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(BF,{workspaceId:q,enabled:!!(V?.imap?.enabled||V?.imapSync?.enabled)})})]}),S.status===`active`&&x===`policies`&&(0,$.jsx)(hF,{workspaceId:q}),S.status===`active`&&x===`hooks`&&(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(IP,{workspaceId:q,prefillRule:m,onPrefillConsumed:h,initialSection:a,initialRunsHandler:o,initialRunId:s})})]})}):(0,$.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,$.jsx)(`h1`,{className:`font-semibold`,children:S.label||S.name}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Workspace settings are available to owners and admins.`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>g(`/workspaces/${e}`),children:`Back to workspace`})]}):(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Workspace not found`})}function lI({workspaceName:e}){let{selected:t,setSelected:n,tree:r,setTree:i,toggle:a}=RT(),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(null);return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Default folders`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Create a set of common folders with matching icons and colors.`}),(0,$.jsx)(`div`,{className:`mt-3`,children:(0,$.jsx)(zT,{selected:t,onToggle:a,tree:r,onTreeChange:i,disabled:o,idPrefix:`settings-default-folders`})}),(0,$.jsxs)(`div`,{className:`mt-3 flex items-center gap-3`,children:[(0,$.jsx)(Z,{type:`button`,size:`sm`,disabled:o||t.size===0,onClick:async()=>{s(!0),l(null);let{ok:i,failed:a}=await LT(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,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:c})]})]})}function uI({workspaceName:e,vectorSpaces:t,onDone:n}){let[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.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:()=>FM(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:()=>RM(e)}]},{title:`Full-text (BM25)`,ops:[{key:`fts`,label:`Backfill`,description:`Index documents missing from the full-text table. Fast, skips already-indexed.`,fn:()=>IM(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:()=>IM(e,!0)},{key:`fts-optimize`,label:`Optimize`,description:`Compact fragments + prune old versions of the full-text table.`,fn:()=>LM(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:()=>LM(e,t)}))}]:[]];return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,$.jsx)(P,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Index maintenance`})]}),(0,$.jsx)(`p`,{className:`mb-3 text-xs text-muted-foreground`,children:`Runs against this workspace. Reindex operations are idempotent.`}),(0,$.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e.title}),(0,$.jsx)(`div`,{className:`space-y-2`,children:e.ops.map(e=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,$.jsxs)(Z,{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,$.jsx)(P,{className:`mr-2 h-3 w-3 animate-spin`}),e.label]}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 basis-52 text-xs text-muted-foreground`,children:e.description})]},e.key))})]},e.title))}),a&&(0,$.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:a})]})}var dI=[{value:`documentRead`,label:`Read`},{value:`documentWrite`,label:`Write`},{value:`documentReadWrite`,label:`Read & write`}];function fI(){let{contextId:e,tab:t}=vl(),[n]=Lu(),r=n.get(`ownerId`)||void 0,i=ml(),{showToast:a}=Vr(),{selectEntity:o,goBack:s,closeM2:c}=MT(),l=s_(),u=BO(t),d=r?`?ownerId=${encodeURIComponent(r)}`:``;(0,Q.useEffect)(()=>{t!==u&&e&&i(`/contexts/${e}/settings/${u}${d}`,{replace:!0})},[t,u,e,d,i]);let[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(!0),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(``),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(),[M,N]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(``),[z,ee]=(0,Q.useState)(dI[0].value),[ne,B]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return xs(e,r).then(e=>{t||(p(e),o(e.id),x(e.name||``),C(e.description||``),T(typeof e.metadata?.ui?.color==`string`?e.metadata.ui.color:null),D(e.url||``),k(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 re=(t=e)=>{t&&(I(!0),Fs(t).then(N).catch(()=>N([])).finally(()=>I(!1)))};(0,Q.useEffect)(()=>{if(u!==`shares`||!e)return;let t=!1;return Fs(e).then(e=>{t||N(e)}).catch(()=>{t||N([])}),()=>{t=!0}},[u,e]);let ie=async t=>{if(t.preventDefault(),e){_(!0);try{let t=await es(e,{name:b.trim(),description:S.trim(),metadata:{...f?.metadata,ui:{...f?.metadata?.ui,color:w}}},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)}}},ae=async t=>{if(t.preventDefault(),e){_(!0);try{await Promise.all([ns(e,E.trim(),r,A),ss(e,{baseUrl:O.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 Os(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)}}},V=async t=>{if(t.preventDefault(),!(!e||!L.trim())){B(`grant`);try{await Ns(e,L.trim(),z),R(``),re(),a({title:`Shared`,description:`Access granted to ${L.trim()}`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{B(null)}}},H=async t=>{if(e&&window.confirm(`Revoke ${t.userEmail}'s access to "${e}"?`)){B(t.userEmail);try{await Zo(e,t.userEmail),re(),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{B(null)}}};if(m)return(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!f)return(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Context not found`});let U=zO.find(e=>e.id===u),se=`/contexts/${e}${d}`;return(0,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,$.jsx)(Gw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${U.label} - ${f.name||f.id}`,description:U.description,backTo:se,onBack:l?s:void 0}),u===`general`&&(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`form`,{onSubmit:ie,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Context ID`}),(0,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-name`,className:`text-sm font-medium`,children:`Name`}),(0,$.jsx)(Y,{id:`ctx-name`,value:b,onChange:e=>x(e.target.value),placeholder:`My Context`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`ctx-description`,value:S,onChange:e=>C(e.target.value),placeholder:`Optional description`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-color`,className:`text-sm font-medium`,children:`Color`}),(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-2`,children:[(0,$.jsx)(Y,{id:`ctx-color`,type:`color`,value:/^#[0-9a-f]{6}$/i.test(w||f.color||``)?w||f.color:`#808080`,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`,disabled:g}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:g||w===null,onClick:()=>T(null),children:`Use inherited color`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:w===null?`Using the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Workspace`}),(0,$.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,$.jsx)(Z,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),(0,$.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,$.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,$.jsxs)(Z,{variant:`destructive`,disabled:v,onClick:oe,children:[(0,$.jsx)(nt,{className:`mr-2 h-4 w-4`}),v?`Deleting...`:`Delete Context`]})]})]}),u===`location`&&(0,$.jsxs)(`form`,{onSubmit:ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-url`,className:`text-sm font-medium`,children:`URL`}),(0,$.jsx)(rh,{id:`ctx-url`,value:E,onChange:D,fixedWorkspaceName:f.workspaceName,pickerTitle:`Switch context to…`,placeholder:`workspace://path`,onPickTarget:(e,t)=>{D(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),j(t.treeName)}}),A&&(0,$.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Destination tree: `,A]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`label`,{htmlFor:`ctx-base-url`,className:`text-sm font-medium`,children:[`Base URL `,(0,$.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,$.jsx)(rh,{id:`ctx-base-url`,value:O,onChange:k,fixedWorkspaceName:f.workspaceName,placeholder:`workspace://base/path`,pickerTitle:`Pick a base path…`})]}),(0,$.jsx)(Z,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),u===`shares`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`People with access`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Only the context owner can see and change this list.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>re(),disabled:F,children:[(0,$.jsx)(P,{className:J(`mr-2 h-3.5 w-3.5`,F&&`animate-spin`)}),`Refresh`]})]}),M.length===0?(0,$.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):M.map(e=>(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.userEmail}),(0,$.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[dI.find(t=>t.value===e.accessLevel)?.label||e.accessLevel||`unknown access`,e.sharedAt&&` - since ${new Date(e.sharedAt).toLocaleDateString()}`]})]}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:ne===e.userEmail,onClick:()=>H(e),children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})})]},e.userEmail))]}),(0,$.jsxs)(`form`,{onSubmit:V,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Grant access`}),(0,$.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`share-email`,className:`text-sm font-medium`,children:`User email`}),(0,$.jsx)(Y,{id:`share-email`,type:`email`,value:L,onChange:e=>R(e.target.value),placeholder:`person@example.com`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`The user must already have an account on this server.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`share-level`,className:`text-sm font-medium`,children:`Access level`}),(0,$.jsx)(`select`,{id:`share-level`,value:z,onChange:e=>ee(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:dI.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),(0,$.jsx)(Z,{type:`submit`,disabled:ne===`grant`||!L.trim(),children:ne===`grant`?`Sharing...`:`Share context`})]})]})]})})}function pI({status:e}){let t={running:{icon:De,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:S,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:N,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:N,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:z,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:Gt,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:Gt,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:S,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,$.jsx)(r,{className:`w-3 h-3`}),n.label]})}function mI(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null);Np(()=>s(null),o!==null);let[c,l]=$w(),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(!1),{showToast:S}=Vr(),C=vd(),w=(0,Q.useCallback)(async()=>{try{r(!0);let e=await JM.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,Q.useEffect)(()=>{let e=()=>w();e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[w]),(0,Q.useEffect)(()=>{c&&(JM.listTemplates().then(e=>{let t=e.filter(e=>e.type===`workspace`);d(t),h(e=>e||t[0]?.id||``)}).catch(()=>d([])),Ai().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 JM.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 JM.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 JM.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 JM.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 JM.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,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(Gw,{title:`My Roles`,description:`Manage your workspace roles and services`,actions:(0,$.jsxs)($.Fragment,{children:[!c&&(0,$.jsxs)(Z,{onClick:()=>l(!0),children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),`Create Role`]}),(0,$.jsxs)(Z,{onClick:w,variant:`outline`,children:[(0,$.jsx)(j,{className:`mr-2 h-4 w-4`}),`Refresh`]})]})}),c&&(0,$.jsx)(Zw,{title:`Create New Role`,onClose:()=>l(!1),children:(0,$.jsxs)(`form`,{onSubmit:T,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-template`,className:`mb-1 block text-sm font-medium`,children:`Template`}),(0,$.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,$.jsx)(`option`,{value:``,children:`No workspace templates available`}),u.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-name`,className:`mb-1 block text-sm font-medium`,children:`Role Name`}),(0,$.jsx)(Y,{id:`role-name`,value:g,onChange:e=>_(e.target.value),placeholder:`e.g., canvas-sshd`,disabled:b})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-workspace`,className:`mb-1 block text-sm font-medium`,children:`Workspace`}),(0,$.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,$.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),f.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label||e.name},e.id))]})]}),(0,$.jsxs)(Z,{type:`submit`,disabled:b||!m||!g.trim()||!v,children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),b?`Creating…`:`Create Role`]})]})}),n?(0,$.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):i?(0,$.jsx)(`div`,{className:`text-center py-8 text-destructive`,children:i}):e.length===0?(0,$.jsxs)(`div`,{className:`text-center py-12 border rounded-lg`,children:[(0,$.jsx)(Jt,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`You don't have any workspace roles yet`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Contact your administrator to set up roles for your workspaces`})]}):(0,$.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`border rounded-lg p-6 space-y-4 hover:shadow-elevation-2 transition-shadow`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,$.jsxs)(`div`,{className:`flex-1`,children:[(0,$.jsx)(`h3`,{className:`font-semibold text-lg`,children:e.name}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.template})]}),(0,$.jsx)(pI,{status:e.status})]}),e.container&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(Jt,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:e.container.name})]})}),(0,$.jsxs)(`div`,{className:`flex gap-2 pt-2`,children:[e.status===`stopped`||e.status===`created`?(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>E(e),className:`flex-1`,children:[(0,$.jsx)(xe,{className:`w-4 h-4 mr-2`}),`Start`]}):e.status===`running`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>D(e),className:`flex-1`,children:[(0,$.jsx)(zn,{className:`w-4 h-4 mr-2`}),`Stop`]}),(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>O(e),className:`flex-1`,children:[(0,$.jsx)(j,{className:`w-4 h-4 mr-2`}),`Restart`]})]}):(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,disabled:!0,className:`flex-1`,children:[(0,$.jsx)(N,{className:`w-4 h-4 mr-2`}),e.status]}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:()=>k(e),title:`View Logs`,children:(0,$.jsx)(nn,{className:`w-4 h-4`})})]})]},e.id))}),(0,$.jsxs)(`div`,{className:`border-t pt-6`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold mb-4`,children:`Global Services`}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground space-y-2`,children:[(0,$.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,$.jsx)(`p`,{children:`To check the status of global services, contact your system administrator.`})]})]}),o&&(0,$.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,$.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,$.jsxs)(`div`,{className:`p-6 border-b`,children:[(0,$.jsxs)(`h2`,{className:`text-xl font-bold`,children:[o.role.name,` - Logs`]}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.role.template})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,$.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,$.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,$.jsx)(`pre`,{children:o.logs.join(`
51
- `)})})}),(0,$.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,$.jsx)(Z,{onClick:()=>s(null),children:`Close`})})]})})]})}function hI(){return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(Gw,{title:`Remotes`,description:`Connect to remote Canvas instances`}),(0,$.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,$.jsxs)(`div`,{className:`text-center`,children:[(0,$.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,$.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Remote connection management is currently under development. Check back later for updates.`})]})})]})}var gI=[`note`,`todo`,`link`,`file`,`photo`];function _I(){let{kind:e}=vl(),t=ml();return e===`sketch`?(0,$.jsx)(Bl,{to:`/apps/sketch?add=1`,replace:!0}):!e||!gI.includes(e)?(0,$.jsx)(Bl,{to:`/home`,replace:!0}):(0,$.jsx)(rO,{initialKind:e,onInitialCardClose:()=>t(`/home`)})}var vI=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Hl,{index:!0,element:(0,$.jsx)(pO,{})},`r1`),(0,$.jsx)(Hl,{path:`home`,element:(0,$.jsx)(fO,{})},`r2`),(0,$.jsx)(Hl,{path:`share-target`,element:(0,$.jsx)(bO,{})},`r3`),(0,$.jsx)(Hl,{path:`apps/add/:kind`,element:(0,$.jsx)(_I,{})},`r4`),(0,$.jsx)(Hl,{path:`workspaces`,element:(0,$.jsx)(XT,{})},`r5`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName`,element:(0,$.jsx)(oD,{})},`r6`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/by-id/:documentId`,element:(0,$.jsx)(dD,{})},`workspace-document-by-id`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/:documentId`,element:(0,$.jsx)(dD,{})},`workspace-document`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/by-hash/:algo/:checksum`,element:(0,$.jsx)(dD,{})},`workspace-document-by-hash`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/by-checksum/:algo/:checksum`,element:(0,$.jsx)(dD,{})},`workspace-document-by-checksum`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/settings`,element:(0,$.jsx)(sI,{})},`r7`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/settings/:tab`,element:(0,$.jsx)(sI,{})},`r8`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/path/*`,element:(0,$.jsx)(oD,{})},`r9`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/trees/:treeName`,element:(0,$.jsx)(oD,{})},`r10`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:(0,$.jsx)(oD,{})},`r11`),(0,$.jsx)(Hl,{path:`contexts`,element:(0,$.jsx)(CO,{})},`r12`),(0,$.jsx)(Hl,{path:`contexts/:contextId`,element:(0,$.jsx)(TO,{})},`r13`),(0,$.jsx)(Hl,{path:`contexts/:contextId/settings`,element:(0,$.jsx)(fI,{})},`r14`),(0,$.jsx)(Hl,{path:`contexts/:contextId/settings/:tab`,element:(0,$.jsx)(fI,{})},`r15`),(0,$.jsx)(Hl,{path:`agents`,element:(0,$.jsx)(SN,{})},`r16`),(0,$.jsx)(Hl,{path:`agents/:agentId`,element:(0,$.jsx)(RN,{})},`r17`),(0,$.jsx)(Hl,{path:`agents/:agentId/:sessionId`,element:(0,$.jsx)(RN,{})},`r18`),(0,$.jsx)(Hl,{path:`agents/:agentId/settings`,element:(0,$.jsx)(KN,{})},`r19`),(0,$.jsx)(Hl,{path:`agents/:agentId/settings/:tab`,element:(0,$.jsx)(KN,{})},`r20`),(0,$.jsx)(Hl,{path:`roles`,element:(0,$.jsx)(mI,{})},`r21`),(0,$.jsx)(Hl,{path:`remotes`,element:(0,$.jsx)(hI,{})},`r22`),(0,$.jsx)(Hl,{path:`settings`,element:(0,$.jsx)(kk,{})},`settings`),(0,$.jsx)(Hl,{path:`appearance`,element:(0,$.jsx)(YA,{})},`r23`),(0,$.jsx)(Hl,{path:`key-bindings`,element:(0,$.jsx)(ij,{})},`key-bindings`),(0,$.jsx)(Hl,{path:`offline`,element:(0,$.jsx)(Uj,{})},`r24`),(0,$.jsx)(Hl,{path:`about`,element:(0,$.jsx)(Kj,{})},`r25`),(0,$.jsx)(Hl,{path:`api-tokens`,element:(0,$.jsx)(DO,{})},`r26`),(0,$.jsx)(Hl,{path:`devices`,element:(0,$.jsx)(FO,{})},`r27`),(0,$.jsx)(Hl,{path:`embedding`,element:(0,$.jsx)(DM,{})},`r28`),(0,$.jsx)(Hl,{path:`shared`,element:(0,$.jsx)(OM,{})},`r29`),(0,$.jsx)(Hl,{path:`admin/users`,element:(0,$.jsx)(QM,{})},`r30`),(0,$.jsx)(Hl,{path:`admin/contexts`,element:(0,$.jsx)(HM,{})},`r31`),(0,$.jsx)(Hl,{path:`admin/workspaces`,element:(0,$.jsx)(VM,{})},`r32`),(0,$.jsx)(Hl,{path:`admin/agents`,element:(0,$.jsx)(UM,{})},`r33`),(0,$.jsx)(Hl,{path:`admin/logs`,element:(0,$.jsx)(qM,{})},`r34`),(0,$.jsx)(Hl,{path:`admin/roles`,element:(0,$.jsx)(ZM,{})},`r35`),(0,$.jsx)(Hl,{path:`admin/embedding`,element:(0,$.jsx)($M,{})},`r36`),(0,$.jsx)(Hl,{path:`admin/auth`,element:(0,$.jsx)(bN,{})},`r37`)]});function yI(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 bI(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var xI=Gl(vI),SI=e=>{let t=yI(e);return t&&ac(xI,t)?t:null};function CI(){let e=dl(),[t]=(0,Q.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:SI(localStorage.getItem(bI(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,Q.useEffect)(()=>{if(n)return;let t=SI(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(bI(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,$.jsx)(Bl,{to:t.path,replace:!0}):null}var wI={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function TI(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`: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:t.m2View!==null,m2View:t.m2View};case`SET_USER`:return{...e,user:t.user};default:return e}}function EI({children:e}){let[t,n]=(0,Q.useReducer)(TI,wI),r=dl(),i=ml(),a=(0,Q.useRef)(t);(0,Q.useLayoutEffect)(()=>{a.current=t},[t]),PT(t,n);let o=(0,Q.useCallback)((e,t=!1,o=!1)=>{let s=TI(a.current,e);if(a.current=s,n(e),!AT())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,Q.useCallback)(e=>{if(AT()&&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,Q.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}=NT(r.pathname);if(!AT()){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,Q.useEffect)(()=>{let e=vd();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return yd().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let l={state:t,dispatch:n,setSection:(0,Q.useCallback)(e=>{o({type:`SET_SECTION`,section:e})},[o]),toggleSection:(0,Q.useCallback)(e=>{o({type:`TOGGLE_SECTION`,section:e})},[o]),toggleM0:(0,Q.useCallback)(()=>{o({type:`TOGGLE_M0`},a.current.m0Open)},[o]),closeM0:(0,Q.useCallback)(()=>{o({type:`CLOSE_M0`},!0)},[o]),closeM1:(0,Q.useCallback)(()=>{o({type:`CLOSE_M1`},!0)},[o]),openM2:(0,Q.useCallback)((e,t)=>{o({type:`OPEN_M2`,view:e,entityId:t})},[o]),openM2Drawer:(0,Q.useCallback)((e,t,n)=>{o({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:n})},[o]),openM1Drawer:(0,Q.useCallback)(e=>{o({type:`OPEN_M1_DRAWER`,section:e})},[o]),closeM2:(0,Q.useCallback)(()=>{AT()&&a.current.m1Open&&a.current.m2Open?c():n({type:`CLOSE_M2`})},[c]),selectEntity:(0,Q.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[]),goBack:c,navigateFromMenu:s};return(0,$.jsx)(jT.Provider,{value:l,children:e})}function DI(){return(0,Q.useSyncExternalStore)(Nr,Tr,()=>!1)}function OI(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&Tr()&&(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=Tr();return Dr(),(i||s)&&t(),!0}catch{return r||Ar(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=Nr(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var kI;function AI(){kI=OI(`${Lr}/ping`,()=>pd.retryNow());let e=()=>{kI?.retry()},t=pd.on(`connect_error`,e),n=pd.on(`disconnect`,e);return()=>{t(),n(),kI?.stop(),kI=void 0}}function jI(){return kI?.retry(!0)??Promise.resolve(!1)}function MI(){let e=DI(),[t,n]=(0,Q.useState)(!1);return e?(0,$.jsxs)(`details`,{className:`relative`,children:[(0,$.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,$.jsx)(w,{className:`h-5 w-5`})}),(0,$.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,$.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,$.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,$.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await jI()}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 NI=Le,PI=O,FI=nr,II=Q.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,$.jsx)(ar,{children:(0,$.jsx)(Ct,{ref:r,sideOffset:t,className:J(`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})}));II.displayName=Ct.displayName;var LI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(mt,{ref:n,className:J(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));LI.displayName=mt.displayName;var RI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(lr,{ref:n,className:J(`aspect-square h-full w-full`,e),...t}));RI.displayName=lr.displayName;var zI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(Qn,{ref:n,className:J(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));zI.displayName=Qn.displayName;function BI({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=MT(),o=i.activeSection===e;return(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:J(`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,$.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,$.jsx)(II,{side:`right`,sideOffset:8,children:n})]})}function VI({path:e,icon:t,label:n,section:r=`settings`}){let i=ml(),{setSection:a}=MT();return(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.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,$.jsx)(II,{side:`right`,sideOffset:8,children:n})]})}function HI(){let{state:e,toggleM0:t}=MT(),n=DI();return(0,$.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,$.jsx)(G,{className:`h-5 w-5`}):(0,$.jsx)(Wn,{className:`h-5 w-5`}),n&&(0,$.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 UI(){let{state:e,closeM0:t,closeM1:n}=MT(),{state:r,setView:i,closeT1:a}=Ls(),o=ml(),{showToast:s}=Vr(),c=e.user?.userType===`admin`,l=Uw(),u=()=>{r.t1Open?a():i(`tools`),n(),t()},d=(0,Q.useCallback)(async()=>{try{await X.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,$.jsxs)(NI,{delayDuration:200,children:[e.m0Open&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,$.jsxs)(`div`,{"data-shell":`rail`,className:J(`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,$.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,$.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,$.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,$.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,$.jsx)(BI,{section:`contexts`,icon:(0,$.jsx)(ur,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,$.jsx)(BI,{section:`workspaces`,icon:(0,$.jsx)($n,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,$.jsx)(BI,{section:`agents`,icon:(0,$.jsx)(ct,{className:`w-5 h-5`}),label:`Agents`}),(!l.local||l.workspace!==!1)&&(0,$.jsx)(VI,{path:`/roles`,section:null,icon:(0,$.jsx)(mn,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,$.jsx)(VI,{path:`/admin/users`,icon:(0,$.jsx)(ie,{className:`w-5 h-5`}),label:`All Users`}),(0,$.jsx)(VI,{path:`/admin/logs`,icon:(0,$.jsx)(nn,{className:`w-5 h-5`}),label:`Server Logs`}),(0,$.jsx)(VI,{path:`/admin/workspaces`,icon:(0,$.jsx)(rt,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,$.jsx)(VI,{path:`/admin/agents`,icon:(0,$.jsx)(ct,{className:`w-5 h-5`}),label:`All Agents`}),(0,$.jsx)(VI,{path:`/admin/roles`,icon:(0,$.jsx)(mn,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,$.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,$.jsx)(MI,{}),(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,onClick:u,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:J(`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,$.jsx)(Ne,{className:`w-5 h-5`})})}),(0,$.jsx)(II,{side:`right`,sideOffset:8,children:`Toolbox`})]}),!l.local&&(0,$.jsx)(VI,{path:`/settings`,section:`settings`,icon:(0,$.jsx)(yn,{className:`w-5 h-5`}),label:`Settings`}),(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.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,$.jsx)(LI,{className:`h-7 w-7 touch-target`,children:(0,$.jsx)(zI,{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,$.jsx)(II,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.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,$.jsx)(Tn,{className:`w-5 h-5`})})}),(0,$.jsx)(II,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}function WI(e,t,n,r=!0){let i=s_(),a=dl(),o=(0,Q.useRef)(null);(0,Q.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 GI(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ds();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useRef)(s);(0,Q.useEffect)(()=>{c.current=s});let l=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>pd.emit(`subscribe`,{channel:`context`}),r=()=>pd.emit(`unsubscribe`,{channel:`context`}),i=pd.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])=>pd.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>pd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!as(e,t)))};return window.addEventListener(is,e),()=>window.removeEventListener(is,e)},[]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,Q.useMemo)(()=>KT(t),[t]),isLoading:r,refresh:l}}function KI(){let{goBack:e}=MT();return(0,$.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,$.jsx)(Jn,{className:`h-5 w-5`})})}function qI(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=MT(),i=s_(),{contexts:a,isLoading:o}=GI(e.activeSection===`contexts`),{showToast:s}=Vr(),c=ml(),[l,u]=(0,Q.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:_}=YT((e,t)=>{let n=qT(d,e,t);u({base:a,order:n}),JT(n,(e,t)=>p(e)?Promise.resolve():ss(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,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(KI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`})]}),(0,$.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,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,$.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=jm(r.color);return(0,$.jsxs)(`div`,{...m(a),"data-active":o||void 0,className:J(`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,$.jsx)(`div`,{className:J(`absolute inset-y-0 right-0 w-4 rounded-r-(--card-radius)`,!u&&`bg-muted`),style:u?{backgroundColor:u}:void 0}):(0,$.jsx)(`button`,{type:`button`,...h(a),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:J(`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,$.jsx)(T,{className:J(`h-3.5 w-3.5`,Mm(u))})}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(f,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:u,className:J(`mt-0.5 shrink-0`,!u&&`text-muted-foreground`)}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),s&&(0,$.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),l&&(0,$.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,$.jsx)(Zt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,$.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,$.jsx)(yn,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function JI({title:e,onBack:t,action:n,className:r,icon:i,accentColor:a}){let{closeM1:o}=MT(),s=jm(a);return(0,$.jsxs)(`div`,{className:J(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{borderBottomWidth:4,...s?{borderBottomColor:s}:{}},children:[(0,$.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,$.jsx)(E,{className:`w-4 h-4 shrink-0`}),i&&(0,$.jsx)(f,{icon:i,width:16,height:16,color:s,className:J(`mr-1 shrink-0`,!s&&`text-muted-foreground`)}),(0,$.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,$.jsx)(`div`,{className:`shrink-0`,children:n}),(0,$.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,$.jsx)(G,{className:`w-4 h-4`})})]})}var YI=22,XI=44,ZI=4;function QI(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 $I(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 eL({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,onLock:x,onUnlock:S,onDestroy:C,onMerge:w,onSubtract:T,onMergeDown:E,onSubtractDown:D,onResyncBackend:O,onAddRule:k,onAddStoreRule:j,onStoragePolicy:M,onRenameBackendFolder:N,onDeleteBackendFolder:F,onRestoreTrash:I,onDiscardTrash:L,onCopy:R,onCut:z,onPaste:te,pastedDocumentIds:B,onPasteDocuments:re,isPinned:ie,onTogglePin:ae}){let oe=u&&d.size>0&&u.path===r,H=!i&&(E||D)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,U=u&&d.size>0&&(u.path===r||d.has(r)),se=async e=>{s();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},W=(e,t,n,r=!1)=>(0,$.jsxs)(`button`,{type:`button`,className:J(`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:()=>se(n),children:[e,t]});return i&&n.metadata?.backendTrash?(0,$.jsxs)(Qp,{x:e,y:t,onClose:s,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&W((0,$.jsx)(nt,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&I&&W((0,$.jsx)(ir,{className:`h-3 w-3`}),`Restore original paths`,()=>I(r)),r!==`/Trash`&&L&&W((0,$.jsx)(nt,{className:`h-3 w-3`}),`Empty Trash`,()=>L(r),!0)]}):(0,$.jsxs)(Qp,{x:e,y:t,onClose:s,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&W((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&W((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Open to the side`,async()=>{l(r)}),(c||l)&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&g&&W((0,$.jsx)(jn,{className:`w-3 h-3`}),`Share canvas`,async()=>{await g(r)}),n.type===`canvas`&&g&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),O&&$I(r,i)&&(0,$.jsxs)($.Fragment,{children:[W((0,$.jsx)(P,{className:`w-3 h-3`}),`Resync backend (${$I(r,i)})`,async()=>{await O(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&$I(r,i)&&(k||j)&&(0,$.jsxs)($.Fragment,{children:[k&&W((0,$.jsx)(Nn,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{k(r)}),j&&QI(r,i)&&W((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{j(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(j||M)&&r!==`/`&&(0,$.jsxs)($.Fragment,{children:[j&&W((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create rule…`,async()=>{j(r)}),j&&W((0,$.jsx)(qt,{className:`w-3 h-3`}),`Create download rule…`,async()=>{j(r,`download`)}),M&&n.type!==`canvas`&&W((0,$.jsx)(fe,{className:`w-3 h-3`}),`Storage policy…`,async()=>{M(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||QI(r,i))&&(0,$.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,$.jsx)(sn,{className:`w-3 h-3`}),`New folder here`]}),N&&QI(r,i)?.key&&W((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await N(r,t)}),F&&i&&fo(r,o)&&W((0,$.jsx)(nt,{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,$.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,$.jsx)(gt,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&ae&&W(ie?(0,$.jsx)(ee,{className:`w-3 h-3`}):(0,$.jsx)(Oe,{className:`w-3 h-3`}),ie?`Unpin`:`Pin`,async()=>{await ae()}),r!==`/`&&m&&(0,$.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,$.jsx)(V,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&W((0,$.jsx)(Ie,{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,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),W((0,$.jsx)(A,{className:`w-3 h-3`}),`Copy`,async()=>R(r)),!i&&W((0,$.jsx)(Et,{className:`w-3 h-3`}),`Cut`,async()=>z(r)),f&&!i&&W((0,$.jsx)(Ce,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>te(r)),B&&B.length>0&&re&&W((0,$.jsx)(Ce,{className:`w-3 h-3`}),`Paste ${B.length} document(s)`,async()=>{await re(r,B)}),(y||b)&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),y&&n.type!==`canvas`&&W((0,$.jsx)(qt,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&W((0,$.jsx)(ne,{className:`w-3 h-3`}),`Import subtree here…`,()=>b(r)),!i&&r!==`/`&&!n.locked&&_&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await _(r,!0)},!0)]}),!i&&(x||S||C)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?S&&W((0,$.jsx)(Ot,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await S(n.id)}):x&&W((0,$.jsx)(Vn,{className:`w-3 h-3`}),`Lock layer`,async()=>{await x(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,$.jsx)(`span`,{className:`truncate`,title:e,children:e}),S&&(0,$.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>se(async()=>{await S(n.id,e)}),children:(0,$.jsx)(Ot,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&C&&W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await C(n.id)},!0)]}),H&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&W((0,$.jsx)(kn,{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 E(r)}),D&&W((0,$.jsx)(Bn,{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 D(r)})]}),oe&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),w&&W((0,$.jsx)(ur,{className:`w-3 h-3`}),`Merge this layer into ${d.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(d.keys()).join(`
51
+ `)})})}),(0,$.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,$.jsx)(Z,{onClick:()=>s(null),children:`Close`})})]})})]})}function hI(){return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(Gw,{title:`Remotes`,description:`Connect to remote Canvas instances`}),(0,$.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,$.jsxs)(`div`,{className:`text-center`,children:[(0,$.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,$.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Remote connection management is currently under development. Check back later for updates.`})]})})]})}var gI=[`note`,`todo`,`link`,`file`,`photo`];function _I(){let{kind:e}=vl(),t=ml();return e===`sketch`?(0,$.jsx)(Bl,{to:`/apps/sketch?add=1`,replace:!0}):!e||!gI.includes(e)?(0,$.jsx)(Bl,{to:`/home`,replace:!0}):(0,$.jsx)(rO,{initialKind:e,onInitialCardClose:()=>t(`/home`)})}var vI=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Hl,{index:!0,element:(0,$.jsx)(pO,{})},`r1`),(0,$.jsx)(Hl,{path:`home`,element:(0,$.jsx)(fO,{})},`r2`),(0,$.jsx)(Hl,{path:`share-target`,element:(0,$.jsx)(bO,{})},`r3`),(0,$.jsx)(Hl,{path:`apps/add/:kind`,element:(0,$.jsx)(_I,{})},`r4`),(0,$.jsx)(Hl,{path:`workspaces`,element:(0,$.jsx)(XT,{})},`r5`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName`,element:(0,$.jsx)(oD,{})},`r6`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/by-id/:documentId`,element:(0,$.jsx)(dD,{})},`workspace-document-by-id`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/:documentId`,element:(0,$.jsx)(dD,{})},`workspace-document`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/by-hash/:algo/:checksum`,element:(0,$.jsx)(dD,{})},`workspace-document-by-hash`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/documents/by-checksum/:algo/:checksum`,element:(0,$.jsx)(dD,{})},`workspace-document-by-checksum`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/settings`,element:(0,$.jsx)(sI,{})},`r7`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/settings/:tab`,element:(0,$.jsx)(sI,{})},`r8`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/path/*`,element:(0,$.jsx)(oD,{})},`r9`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/trees/:treeName`,element:(0,$.jsx)(oD,{})},`r10`),(0,$.jsx)(Hl,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:(0,$.jsx)(oD,{})},`r11`),(0,$.jsx)(Hl,{path:`contexts`,element:(0,$.jsx)(CO,{})},`r12`),(0,$.jsx)(Hl,{path:`contexts/:contextId`,element:(0,$.jsx)(TO,{})},`r13`),(0,$.jsx)(Hl,{path:`contexts/:contextId/settings`,element:(0,$.jsx)(fI,{})},`r14`),(0,$.jsx)(Hl,{path:`contexts/:contextId/settings/:tab`,element:(0,$.jsx)(fI,{})},`r15`),(0,$.jsx)(Hl,{path:`agents`,element:(0,$.jsx)(SN,{})},`r16`),(0,$.jsx)(Hl,{path:`agents/:agentId`,element:(0,$.jsx)(RN,{})},`r17`),(0,$.jsx)(Hl,{path:`agents/:agentId/:sessionId`,element:(0,$.jsx)(RN,{})},`r18`),(0,$.jsx)(Hl,{path:`agents/:agentId/settings`,element:(0,$.jsx)(KN,{})},`r19`),(0,$.jsx)(Hl,{path:`agents/:agentId/settings/:tab`,element:(0,$.jsx)(KN,{})},`r20`),(0,$.jsx)(Hl,{path:`roles`,element:(0,$.jsx)(mI,{})},`r21`),(0,$.jsx)(Hl,{path:`remotes`,element:(0,$.jsx)(hI,{})},`r22`),(0,$.jsx)(Hl,{path:`settings`,element:(0,$.jsx)(kk,{})},`settings`),(0,$.jsx)(Hl,{path:`appearance`,element:(0,$.jsx)(YA,{})},`r23`),(0,$.jsx)(Hl,{path:`key-bindings`,element:(0,$.jsx)(ij,{})},`key-bindings`),(0,$.jsx)(Hl,{path:`offline`,element:(0,$.jsx)(Uj,{})},`r24`),(0,$.jsx)(Hl,{path:`about`,element:(0,$.jsx)(Kj,{})},`r25`),(0,$.jsx)(Hl,{path:`api-tokens`,element:(0,$.jsx)(DO,{})},`r26`),(0,$.jsx)(Hl,{path:`devices`,element:(0,$.jsx)(FO,{})},`r27`),(0,$.jsx)(Hl,{path:`embedding`,element:(0,$.jsx)(DM,{})},`r28`),(0,$.jsx)(Hl,{path:`shared`,element:(0,$.jsx)(OM,{})},`r29`),(0,$.jsx)(Hl,{path:`admin/users`,element:(0,$.jsx)(QM,{})},`r30`),(0,$.jsx)(Hl,{path:`admin/contexts`,element:(0,$.jsx)(HM,{})},`r31`),(0,$.jsx)(Hl,{path:`admin/workspaces`,element:(0,$.jsx)(VM,{})},`r32`),(0,$.jsx)(Hl,{path:`admin/agents`,element:(0,$.jsx)(UM,{})},`r33`),(0,$.jsx)(Hl,{path:`admin/logs`,element:(0,$.jsx)(qM,{})},`r34`),(0,$.jsx)(Hl,{path:`admin/roles`,element:(0,$.jsx)(ZM,{})},`r35`),(0,$.jsx)(Hl,{path:`admin/embedding`,element:(0,$.jsx)($M,{})},`r36`),(0,$.jsx)(Hl,{path:`admin/auth`,element:(0,$.jsx)(bN,{})},`r37`)]});function yI(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 bI(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var xI=Gl(vI),SI=e=>{let t=yI(e);return t&&ac(xI,t)?t:null};function CI(){let e=dl(),[t]=(0,Q.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:SI(localStorage.getItem(bI(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,Q.useEffect)(()=>{if(n)return;let t=SI(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(bI(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,$.jsx)(Bl,{to:t.path,replace:!0}):null}var wI={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function TI(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 EI({children:e}){let[t,n]=(0,Q.useReducer)(TI,wI),r=dl(),i=ml(),a=(0,Q.useRef)(t);(0,Q.useLayoutEffect)(()=>{a.current=t},[t]),PT(t,n);let o=(0,Q.useCallback)((e,t=!1,o=!1)=>{let s=TI(a.current,e);if(a.current=s,n(e),!AT())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,Q.useCallback)(e=>{if(AT()&&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,Q.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}=NT(r.pathname);if(!AT()){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,Q.useEffect)(()=>{let e=vd();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return yd().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let l={state:t,dispatch:n,setSection:(0,Q.useCallback)(e=>{o({type:`SET_SECTION`,section:e})},[o]),toggleSection:(0,Q.useCallback)(e=>{o({type:`TOGGLE_SECTION`,section:e})},[o]),toggleM0:(0,Q.useCallback)(()=>{o({type:`TOGGLE_M0`},a.current.m0Open)},[o]),closeM0:(0,Q.useCallback)(()=>{o({type:`CLOSE_M0`},!0)},[o]),closeM1:(0,Q.useCallback)(()=>{o({type:`CLOSE_M1`},!0)},[o]),openM2:(0,Q.useCallback)((e,t)=>{o({type:`OPEN_M2`,view:e,entityId:t})},[o]),openM2Drawer:(0,Q.useCallback)((e,t,n)=>{o({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:n})},[o]),openM1Drawer:(0,Q.useCallback)(e=>{o({type:`OPEN_M1_DRAWER`,section:e})},[o]),closeM2:(0,Q.useCallback)(()=>{AT()&&a.current.m1Open&&a.current.m2Open?c():n({type:`CLOSE_M2`})},[c]),selectEntity:(0,Q.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[]),goBack:c,navigateFromMenu:s};return(0,$.jsx)(jT.Provider,{value:l,children:e})}function DI(){return(0,Q.useSyncExternalStore)(Nr,Tr,()=>!1)}function OI(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&Tr()&&(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=Tr();return Dr(),(i||s)&&t(),!0}catch{return r||Ar(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=Nr(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var kI;function AI(){kI=OI(`${Lr}/ping`,()=>pd.retryNow());let e=()=>{kI?.retry()},t=pd.on(`connect_error`,e),n=pd.on(`disconnect`,e);return()=>{t(),n(),kI?.stop(),kI=void 0}}function jI(){return kI?.retry(!0)??Promise.resolve(!1)}function MI(){let e=DI(),[t,n]=(0,Q.useState)(!1);return e?(0,$.jsxs)(`details`,{className:`relative`,children:[(0,$.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,$.jsx)(w,{className:`h-5 w-5`})}),(0,$.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,$.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,$.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,$.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await jI()}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 NI=Le,PI=O,FI=nr,II=Q.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,$.jsx)(ar,{children:(0,$.jsx)(Ct,{ref:r,sideOffset:t,className:J(`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})}));II.displayName=Ct.displayName;var LI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(mt,{ref:n,className:J(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));LI.displayName=mt.displayName;var RI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(lr,{ref:n,className:J(`aspect-square h-full w-full`,e),...t}));RI.displayName=lr.displayName;var zI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(Qn,{ref:n,className:J(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));zI.displayName=Qn.displayName;function BI({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=MT(),o=i.activeSection===e;return(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:J(`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,$.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,$.jsx)(II,{side:`right`,sideOffset:8,children:n})]})}function VI({path:e,icon:t,label:n,section:r=`settings`}){let i=ml(),{setSection:a}=MT();return(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.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,$.jsx)(II,{side:`right`,sideOffset:8,children:n})]})}function HI(){let{state:e,toggleM0:t}=MT(),n=DI();return(0,$.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,$.jsx)(G,{className:`h-5 w-5`}):(0,$.jsx)(Wn,{className:`h-5 w-5`}),n&&(0,$.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 UI(){let{state:e,closeM0:t,closeM1:n}=MT(),{state:r,setView:i,closeT1:a}=Ls(),o=ml(),{showToast:s}=Vr(),c=e.user?.userType===`admin`,l=Uw(),u=()=>{r.t1Open?a():i(`tools`),n(),t()},d=(0,Q.useCallback)(async()=>{try{await X.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,$.jsxs)(NI,{delayDuration:200,children:[e.m0Open&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,$.jsxs)(`div`,{"data-shell":`rail`,className:J(`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,$.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,$.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,$.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,$.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,$.jsx)(BI,{section:`contexts`,icon:(0,$.jsx)(ur,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,$.jsx)(BI,{section:`workspaces`,icon:(0,$.jsx)($n,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,$.jsx)(BI,{section:`agents`,icon:(0,$.jsx)(ct,{className:`w-5 h-5`}),label:`Agents`}),(!l.local||l.workspace!==!1)&&(0,$.jsx)(VI,{path:`/roles`,section:null,icon:(0,$.jsx)(mn,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,$.jsx)(VI,{path:`/admin/users`,icon:(0,$.jsx)(ie,{className:`w-5 h-5`}),label:`All Users`}),(0,$.jsx)(VI,{path:`/admin/logs`,icon:(0,$.jsx)(nn,{className:`w-5 h-5`}),label:`Server Logs`}),(0,$.jsx)(VI,{path:`/admin/workspaces`,icon:(0,$.jsx)(rt,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,$.jsx)(VI,{path:`/admin/agents`,icon:(0,$.jsx)(ct,{className:`w-5 h-5`}),label:`All Agents`}),(0,$.jsx)(VI,{path:`/admin/roles`,icon:(0,$.jsx)(mn,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,$.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,$.jsx)(MI,{}),(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,onClick:u,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:J(`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,$.jsx)(Ne,{className:`w-5 h-5`})})}),(0,$.jsx)(II,{side:`right`,sideOffset:8,children:`Toolbox`})]}),!l.local&&(0,$.jsx)(VI,{path:`/settings`,section:`settings`,icon:(0,$.jsx)(yn,{className:`w-5 h-5`}),label:`Settings`}),(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.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,$.jsx)(LI,{className:`h-7 w-7 touch-target`,children:(0,$.jsx)(zI,{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,$.jsx)(II,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,$.jsxs)(PI,{children:[(0,$.jsx)(FI,{asChild:!0,children:(0,$.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,$.jsx)(Tn,{className:`w-5 h-5`})})}),(0,$.jsx)(II,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}function WI(e,t,n,r=!0){let i=s_(),a=dl(),o=(0,Q.useRef)(null);(0,Q.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 GI(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ds();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useRef)(s);(0,Q.useEffect)(()=>{c.current=s});let l=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>pd.emit(`subscribe`,{channel:`context`}),r=()=>pd.emit(`unsubscribe`,{channel:`context`}),i=pd.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])=>pd.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>pd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!as(e,t)))};return window.addEventListener(is,e),()=>window.removeEventListener(is,e)},[]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,Q.useMemo)(()=>KT(t),[t]),isLoading:r,refresh:l}}function KI(){let{goBack:e}=MT();return(0,$.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,$.jsx)(Jn,{className:`h-5 w-5`})})}function qI(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=MT(),i=s_(),{contexts:a,isLoading:o}=GI(e.activeSection===`contexts`),{showToast:s}=Vr(),c=ml(),[l,u]=(0,Q.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:_}=YT((e,t)=>{let n=qT(d,e,t);u({base:a,order:n}),JT(n,(e,t)=>p(e)?Promise.resolve():ss(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,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(KI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`})]}),(0,$.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,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,$.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=jm(r.color);return(0,$.jsxs)(`div`,{...m(a),"data-active":o||void 0,className:J(`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,$.jsx)(`div`,{className:J(`absolute inset-y-0 right-0 w-4 rounded-r-(--card-radius)`,!u&&`bg-muted`),style:u?{backgroundColor:u}:void 0}):(0,$.jsx)(`button`,{type:`button`,...h(a),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:J(`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,$.jsx)(T,{className:J(`h-3.5 w-3.5`,Mm(u))})}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(f,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:u,className:J(`mt-0.5 shrink-0`,!u&&`text-muted-foreground`)}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),s&&(0,$.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),l&&(0,$.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,$.jsx)(Zt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,$.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,$.jsx)(yn,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function JI({title:e,onBack:t,action:n,className:r,icon:i,accentColor:a}){let{closeM1:o}=MT(),s=jm(a);return(0,$.jsxs)(`div`,{className:J(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{borderBottomWidth:4,...s?{borderBottomColor:s}:{}},children:[(0,$.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,$.jsx)(E,{className:`w-4 h-4 shrink-0`}),i&&(0,$.jsx)(f,{icon:i,width:16,height:16,color:s,className:J(`mr-1 shrink-0`,!s&&`text-muted-foreground`)}),(0,$.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,$.jsx)(`div`,{className:`shrink-0`,children:n}),(0,$.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,$.jsx)(G,{className:`w-4 h-4`})})]})}var YI=22,XI=44,ZI=4;function QI(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 $I(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 eL({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,onLock:x,onUnlock:S,onDestroy:C,onMerge:w,onSubtract:T,onMergeDown:E,onSubtractDown:D,onResyncBackend:O,onAddRule:k,onAddStoreRule:j,onStoragePolicy:M,onRenameBackendFolder:N,onDeleteBackendFolder:F,onRestoreTrash:I,onDiscardTrash:L,onCopy:R,onCut:z,onPaste:te,pastedDocumentIds:B,onPasteDocuments:re,isPinned:ie,onTogglePin:ae}){let oe=u&&d.size>0&&u.path===r,H=!i&&(E||D)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,U=u&&d.size>0&&(u.path===r||d.has(r)),se=async e=>{s();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},W=(e,t,n,r=!1)=>(0,$.jsxs)(`button`,{type:`button`,className:J(`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:()=>se(n),children:[e,t]});return i&&n.metadata?.backendTrash?(0,$.jsxs)(Qp,{x:e,y:t,onClose:s,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&W((0,$.jsx)(nt,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&I&&W((0,$.jsx)(ir,{className:`h-3 w-3`}),`Restore original paths`,()=>I(r)),r!==`/Trash`&&L&&W((0,$.jsx)(nt,{className:`h-3 w-3`}),`Empty Trash`,()=>L(r),!0)]}):(0,$.jsxs)(Qp,{x:e,y:t,onClose:s,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&W((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&W((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Open to the side`,async()=>{l(r)}),(c||l)&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&g&&W((0,$.jsx)(jn,{className:`w-3 h-3`}),`Share canvas`,async()=>{await g(r)}),n.type===`canvas`&&g&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),O&&$I(r,i)&&(0,$.jsxs)($.Fragment,{children:[W((0,$.jsx)(P,{className:`w-3 h-3`}),`Resync backend (${$I(r,i)})`,async()=>{await O(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&$I(r,i)&&(k||j)&&(0,$.jsxs)($.Fragment,{children:[k&&W((0,$.jsx)(Nn,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{k(r)}),j&&QI(r,i)&&W((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{j(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(j||M)&&r!==`/`&&(0,$.jsxs)($.Fragment,{children:[j&&W((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create rule…`,async()=>{j(r)}),j&&W((0,$.jsx)(qt,{className:`w-3 h-3`}),`Create download rule…`,async()=>{j(r,`download`)}),M&&n.type!==`canvas`&&W((0,$.jsx)(fe,{className:`w-3 h-3`}),`Storage policy…`,async()=>{M(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||QI(r,i))&&(0,$.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,$.jsx)(sn,{className:`w-3 h-3`}),`New folder here`]}),N&&QI(r,i)?.key&&W((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await N(r,t)}),F&&i&&fo(r,o)&&W((0,$.jsx)(nt,{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,$.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,$.jsx)(gt,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&ae&&W(ie?(0,$.jsx)(ee,{className:`w-3 h-3`}):(0,$.jsx)(Oe,{className:`w-3 h-3`}),ie?`Unpin`:`Pin`,async()=>{await ae()}),r!==`/`&&m&&(0,$.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,$.jsx)(V,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&W((0,$.jsx)(Ie,{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,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),W((0,$.jsx)(A,{className:`w-3 h-3`}),`Copy`,async()=>R(r)),!i&&W((0,$.jsx)(Et,{className:`w-3 h-3`}),`Cut`,async()=>z(r)),f&&!i&&W((0,$.jsx)(Ce,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>te(r)),B&&B.length>0&&re&&W((0,$.jsx)(Ce,{className:`w-3 h-3`}),`Paste ${B.length} document(s)`,async()=>{await re(r,B)}),(y||b)&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),y&&n.type!==`canvas`&&W((0,$.jsx)(qt,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&W((0,$.jsx)(ne,{className:`w-3 h-3`}),`Import subtree here…`,()=>b(r)),!i&&r!==`/`&&!n.locked&&_&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await _(r,!0)},!0)]}),!i&&(x||S||C)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?S&&W((0,$.jsx)(Ot,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await S(n.id)}):x&&W((0,$.jsx)(Vn,{className:`w-3 h-3`}),`Lock layer`,async()=>{await x(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,$.jsx)(`span`,{className:`truncate`,title:e,children:e}),S&&(0,$.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>se(async()=>{await S(n.id,e)}),children:(0,$.jsx)(Ot,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&C&&W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await C(n.id)},!0)]}),H&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&W((0,$.jsx)(kn,{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 E(r)}),D&&W((0,$.jsx)(Bn,{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 D(r)})]}),oe&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),w&&W((0,$.jsx)(ur,{className:`w-3 h-3`}),`Merge this layer into ${d.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(d.keys()).join(`
52
52
  `)}\n\nThe selected layers gain this layer's documents. This layer is unchanged.`)&&await w(n.id,Array.from(d.values()))}),T&&W((0,$.jsx)(ur,{className:`w-3 h-3`}),`Subtract this layer from ${d.size} selected`,async()=>{confirm(`Subtract "${r}" (source) FROM:\n${Array.from(d.keys()).join(`
53
53
  `)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await T(n.id,Array.from(d.values()))})]}),U&&!oe&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,$.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 tL({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,$.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,$.jsx)(hr,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,$.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 nL(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function rL(e,t,n){let r=nL(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>rL(e,r,n))??!1}function iL({node:e,parentPath:t,depth:n,isLast:r,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:c,targetLayers:l,clipboard:u,searchQuery:d,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,policyBadgeFor:M,removingPaths:N,accordion:F=!1,trail:I=[]}){let L=wp(),R=nL(t,e.name),z=M?.(R)??null,ee=S.get(R)??Sm(e),[te,ne]=(0,Q.useState)(()=>i!==`/`&&(i===R||i.startsWith(R+`/`))),[B,re]=(0,Q.useState)(i);if(B!==i&&(re(i),i!==`/`&&i.startsWith(R+`/`)&&ne(!0)),d&&!rL(e,t,d))return null;let ie=te||p===R||d.length>0,ae=e.children&&e.children.length>0,oe=i===R,V=a===R,H=c?.path===R,U=l.has(R),se=e.type===`canvas`,W=t=>{if(t.ctrlKey||t.metaKey){_(R,e.id);return}if(t.shiftKey&&h){h(R);return}m(R)},ce=e=>{!ae||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button, input, textarea, select, a, [contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),ne(e=>!e))},le=[...I].reverse().find(Boolean)??null,ue=ee.color||le,de=F?[...I,ue]:I,pe=i!==`/`&&i.startsWith(R+`/`),me=!H&&!U,G=me&&oe,he=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,ge=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,_e=Math.min(n,5),ve=ie&&!!ae,K=n>0&&le?le:ue,q=me&&!G&&!e.locked&&ve,ye=K?Math.min(12+_e*5+(pe?6:0),34):Math.min(_e*7+(pe?5:0)+(V?3:0),30),be=G?`var(--primary)`:H?he(`var(--info)`,22):U?he(`var(--warning)`,22):e.locked?he(`var(--warning)`,20+_e*4):q?ue?he(ue,84):he(`var(--foreground)`,38):he(K||`var(--foreground)`,ye),xe=G?`text-primary-foreground`:q&&ue?Nm(ue):`text-foreground`,Se=F&&ie&&ae&&n<ZI,Ce=(0,$.jsxs)(`div`,{"data-active":oe||void 0,className:J(`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]`,xe,H&&`ring-1 ring-inset ring-info/40`,U&&!H&&`ring-1 ring-inset ring-warning/40`,C===R&&!s&&!w&&`ring-2 ring-inset ring-info`,C===R&&!s&&w&&`ring-2 ring-inset ring-success`),style:{height:XI,background:be,borderBottom:`1px solid ${ge(14)}`,...Se?{position:`sticky`,top:n*XI,zIndex:20-n}:{}},draggable:!s&&!e.metadata?.backendTrash,onClick:W,onDoubleClick:ce,...s?{}:L,onContextMenu:t=>{s||(t.preventDefault(),v(t,R,e))},onDragStart:e=>{s||T(R,e)},onDragEnter:e=>{s||E(R,e)},onDragOver:e=>{s||D(R,e)},onDragLeave:e=>O(R,e),onDragEnd:()=>k(),onDrop:e=>{s||A(R,e)},children:[I.length>0&&(0,$.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:I.map((e,t)=>(0,$.jsx)(`span`,{className:`w-[3px]`,style:{background:e||ge(28)}},t))}),(()=>{let t=ee.color?{background:ee.color}:le?{background:`color-mix(in oklab, ${le} 45%, transparent)`}:{background:ge(10)},n=(0,$.jsx)(f,{icon:ee.icon||(se?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:J(`shrink-0`,ee.color?Mm(ee.color):G?`text-primary-foreground`:q?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return x?(0,$.jsx)(`button`,{type:`button`,className:r,style:t,title:`Change icon`,onClick:t=>{br()||(t.stopPropagation(),x(t,R,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,R,e)},children:n}):(0,$.jsx)(`span`,{className:r,style:t,children:n})})(),(0,$.jsx)(`span`,{className:J(`min-w-0 flex-1 self-center truncate px-2.5`,oe||pe||ve?`font-semibold`:`font-medium`),title:e.description||void 0,children:e.label||e.name}),N.has(R)&&(0,$.jsx)(P,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":N.get(R)}),j?.has(R)&&(0,$.jsx)(P,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),z&&(0,$.jsx)(fe,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":z,children:(0,$.jsx)(`title`,{children:z})}),!s&&(0,$.jsx)(`button`,{type:`button`,className:`reveal-on-hover shrink-0 self-center rounded p-1 hover:bg-foreground/10`,onClick:t=>{t.stopPropagation(),v(t,R,e)},children:(0,$.jsx)(vn,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{type:`button`,className:J(`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)]`,!ae&&p!==R&&`invisible`),style:{borderLeft:`1px solid ${ge(16)}`},"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,title:ie?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,$.jsx)(Xe,{className:`h-5 w-5`,strokeWidth:2.25}):(0,$.jsx)(hr,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,$.jsxs)(`div`,{className:`relative`,children:[F?Ce:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${YI/2}px`,...r?{height:`1.375rem`}:{bottom:0}}}),(0,$.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${YI/2}px`,width:`${YI/2}px`}}),(0,$.jsxs)(`div`,{"data-active":oe||void 0,className:J(`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`,H&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,U&&!H&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!H&&!U&&oe&&!e.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!H&&!U&&oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!H&&!U&&!oe&&V&&`bg-primary/[0.03] before:bg-transparent`,!H&&!U&&!oe&&!V&&!e.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!H&&!U&&!oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,C===R&&!s&&!w&&`ring-2 ring-info bg-info-subtle/50`,C===R&&!s&&w&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:ee.color?`4px solid ${ee.color}`:`4px solid transparent`},draggable:!s&&!e.metadata?.backendTrash,onClick:W,onDoubleClick:ce,...s?{}:L,onContextMenu:t=>{s||(t.preventDefault(),v(t,R,e))},onDragStart:e=>{s||T(R,e)},onDragEnter:e=>{s||E(R,e)},onDragOver:e=>{s||D(R,e)},onDragLeave:e=>O(R,e),onDragEnd:()=>k(),onDrop:e=>{s||A(R,e)},children:[(0,$.jsx)(`button`,{type:`button`,className:J(`shrink-0 text-muted-foreground hover:text-foreground`,!ae&&p!==R&&`invisible`),"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,$.jsx)(Xe,{className:`w-4 h-4`}):(0,$.jsx)(hr,{className:`w-4 h-4`})}),(()=>{let t=(0,$.jsx)(f,{icon:ee.icon||(se?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:ee.color||void 0,className:J(`shrink-0`,!ee.color&&(se?`text-primary`:`text-muted-foreground`))});return x?(0,$.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:t=>{br()||(t.stopPropagation(),x(t,R,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,R,e)},children:t}):t})(),(0,$.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name}),N.has(R)&&(0,$.jsx)(P,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":N.get(R)}),j?.has(R)&&(0,$.jsx)(P,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),z&&(0,$.jsx)(fe,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":z,children:(0,$.jsx)(`title`,{children:z})}),!s&&(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:t=>{t.stopPropagation(),v(t,R,e)},children:(0,$.jsx)(vn,{className:`w-4 h-4`})})]})]}),ie&&(ae||p===R)&&(0,$.jsxs)(`div`,{className:F?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[p===R&&(0,$.jsx)(tL,{onConfirm:e=>y(R,e),onCancel:b}),e.children?.map((t,r)=>(0,$.jsx)(iL,{node:t,parentPath:R,depth:n+1,isLast:r===(e.children?.length??0)-1,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:c,targetLayers:l,clipboard:u,searchQuery:d,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,policyBadgeFor:M,removingPaths:N,accordion:F,trail:de},t.id||t.name))]})]})}function aL({root:e,workspaceId:t,treeName:n=`context`,isBackendsTree:r=!1,onRestoreTrash:i,onDiscardTrash:a,selectedPath:o,pendingPath:s,onSelect:c,isLoading:l=!1,readOnly:u=!1,onAddRule:d,onAddStoreRule:f,onStoragePolicy:p,policyBadgeFor:m,rootLabel:h,contentPath:g,onShowContent:_,onOpenToSide:v,onShiftSelect:y,onInsertPath:b,onNewCanvas:x,onShareCanvas:S,onRemovePath:C,onRenamePath:w,onMovePath:T,onCopyPath:E,onExportSubtree:D,onImportSubtree:O,pastedDocumentIds:k,onPasteDocuments:A,onLockLayer:j,onUnlockLayer:M,onDestroyLayer:N,onMergeLayer:F,onSubtractLayer:I,onMergeDown:L,onSubtractDown:R,onResyncBackend:z,onCreateBackendFolder:ee,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onUpdateNode:B,isPathPinned:re,onTogglePin:ie,searchQuery:ae=``,resyncingPaths:oe,backends:V}){let H=hA(),[U,se]=(0,Q.useState)(null),[W,ce]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(new Map),[de,fe]=(0,Q.useState)(null),[pe,me]=(0,Q.useState)(new Map),G=(0,Q.useRef)(new Set),he=(0,Q.useCallback)(async(e,t=!1,i=!1,a=!1)=>{if(!(r?ne:C)||[...G.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;G.current.add(e);let o=r?`Deleting from backend…`:a?`Removing documents and backend files…`:i?`Removing and purging documents…`:`Removing folder…`;me(t=>new Map(t).set(e,o));try{return r?await ne(e):await C(e,n===`directory`||t,i,a)}finally{G.current.delete(e),me(t=>{let n=new Map(t);return n.delete(e),n})}},[C,ne,r,n]),[ge,_e]=(0,Q.useState)(null),[ve,K]=(0,Q.useState)(new Map),[q,ye]=(0,Q.useState)(e),be=(0,Q.useRef)(new Map),xe=(0,Q.useRef)(null),[Se,Ce]=(0,Q.useState)(null);if(e!==q){ye(e);let t=Se;K(t?new Map([[t.path,t.style]]):new Map)}let[we,Te]=(0,Q.useState)(null),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)(!1),[Ae,je]=(0,Q.useState)(!1),[Me,Ne]=(0,Q.useState)(!1),Pe=(0,Q.useRef)(!1),Fe=(0,Q.useRef)(null),Ie=(0,Q.useRef)(n),Le=(0,Q.useRef)(!1),Re=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=e=>{se(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||Re.current;Le.current=t,ke(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let ze=(0,Q.useCallback)((e,t,r)=>{if(db(Ie.current,e)||db(n,t))return!1;if(Ie.current!==n)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||!r&&a===o)},[n]),Be=(0,Q.useCallback)((e,t)=>{if(db(n,e)){t.preventDefault();return}Fe.current=e,Ie.current=n,t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:n})),t.dataTransfer.effectAllowed=`copyMove`},[n]),Ve=e=>e.ctrlKey||e.altKey||Re.current,He=(0,Q.useCallback)((e,t)=>{if(db(n,e))return;let r=Fe.current,i=Ve(t);i!==Le.current&&(Le.current=i,ke(i)),!(r&&!ze(r,e,i))&&(t.preventDefault(),De(e))},[ze,n]),Ue=(0,Q.useCallback)((e,t)=>{if(db(n,e)){t.dataTransfer.dropEffect=`none`;return}let r=Ve(t);r!==Le.current&&(Le.current=r,ke(r));let i=Fe.current;if(i&&!ze(i,e,r)){t.dataTransfer.dropEffect=`none`;return}t.preventDefault(),t.dataTransfer.dropEffect=r?`copy`:`move`},[ze,n]),We=(0,Q.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||De(t=>t===e?null:t)},[]),Ge=(0,Q.useCallback)(()=>{Fe.current=null,Ie.current=n,Le.current=!1,ke(!1),De(null)},[n]),Ke=(0,Q.useCallback)(async(e,i)=>{if(i.preventDefault(),i.stopPropagation(),db(n,e))return;let a=(()=>{try{return JSON.parse(i.dataTransfer.getData(`application/json`))}catch{return null}})();if(a?.type===`document`&&Array.isArray(a.documentIds)&&a.documentIds.length){if(Fe.current=null,Le.current=!1,ke(!1),De(null),hg(a,t,n,e))return;if(A)try{await A(e,a.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let o=(()=>{try{return JSON.parse(i.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),s=o?.path||i.dataTransfer.getData(`text/plain`),c=o?.treeName||Ie.current||n;if(db(c,s))return;let l=Ve(i)||Le.current;if(Fe.current=null,Ie.current=n,Le.current=!1,ke(!1),De(null),!s)return;let u=i.shiftKey,d=c!==n;if(!(!d&&s===e)&&!(!d&&!ze(s,e,l)))try{if(l&&E)await E(s,e,u,c,n);else if(!l&&T){let t=Pe.current&&!r&&!!L;await T(s,e,u,c,n,t?{mergeDown:t}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[ze,E,T,A,t,n,r,L]),qe=ae.toLowerCase().trim(),Je=(0,Q.useCallback)((e,t,n)=>{e.stopPropagation(),fe({x:e.clientX,y:e.clientY,path:t,node:n})},[]),Ye=(0,Q.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(xe.current=null,Ce(null),_e({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),Ze=(0,Q.useCallback)(e=>{if(!ge||!B)return;let t=ge.path,n={...ve.get(t)??(xe.current?.path===t?xe.current.style:Sm(ge.node)),...e};xe.current={path:t,style:n},Ce({path:t,style:n}),K(e=>new Map(e).set(t,n));let r=wm(ge.node.metadata,n),i=be.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),B(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[ge,B,ve]),Qe=(0,Q.useCallback)((e,t)=>{W?e===W.path?(ce(null),ue(new Map)):ue(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(ce({path:e,id:t}),ue(new Map))},[W]),$e=(0,Q.useCallback)(async e=>{!U||!T||!E||U.treeName===n&&(e===U.path||e.startsWith(U.path+`/`))||(U.mode===`cut`?(await T(U.path,e,!1,U.treeName,n),se(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))):await E(U.path,e,!0,U.treeName,n))},[U,T,E,n]);(0,Q.useEffect)(()=>{if(u)return;let e=e=>{let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),U?.mode===`cut`){$e(o);return}let r={mode:`cut`,path:o,treeName:n};se(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[U,$e,u,o,n]);let et=(0,Q.useCallback)(async(e,t)=>{Te(null);let n=e===`/`?`/${t}`:`${e}/${t}`;try{QI(e,r)&&ee?await ee(e,t)&&c(n):b&&await b(n,!0)&&c(n)}catch(e){alert(e instanceof Error?e.message:String(e))}},[b,ee,c,r]),tt=(0,Q.useCallback)(()=>{Te(null)},[]),nt=(0,Q.useCallback)((e,t)=>{let r={mode:t,path:e,treeName:n};se(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))},[n]),rt=(0,Q.useCallback)(t=>{if(u||rm(t.target)||o&&db(n,o))return;if(nm(t,`Mod+V`)){k?.length&&A&&o?(t.preventDefault(),A(o,k).catch(()=>{})):U&&o&&(t.preventDefault(),$e(o).catch(e=>alert(e instanceof Error?e.message:String(e))));return}if(o&&o!==`/`&&(nm(t,`Mod+C`)||!r&&nm(t,`Mod+X`))){t.preventDefault(),nt(o,t.key.toLowerCase()===`x`?`cut`:`copy`);return}if((r?!ne||!fo(o||``,V):!C)||t.key!==`Delete`&&t.key!==`Backspace`||!o||o===`/`)return;t.preventDefault();let i=hi(e,o);if(!r&&i?.locked){alert(`"${o}" is locked`);return}confirm(r?`Delete "${o}" and its contents from this backend?`:`Remove "${o}"${n===`directory`?` and all children`:``}?`)&&he(o,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))},[u,C,ne,he,o,e,k,A,U,$e,r,nt,n,V]),it=(0,Q.useCallback)(()=>{je(e=>{let t=!e;return Re.current=t,Le.current=t,ke(t),t})},[]);if(l)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let at=W||le.size>0,ot={accordion:H,selectedPath:o,pendingPath:s,contentPath:g,readOnly:u,sourceLayer:W,targetLayers:le,clipboard:U,searchQuery:qe,inlineCreateParent:we,onSelect:c,onShiftSelect:y,onShowContent:_,onCtrl:Qe,onCtxMenu:Je,onConfirmCreate:et,onCancelCreate:tt,onOpenPicker:B?Ye:void 0,styleOverrides:ve,dragOverPath:Ee,isCopyDrag:Oe,onDragStart:Be,onDragEnter:He,onDragOver:Ue,onDragLeave:We,onDragEnd:Ge,onDrop:Ke,resyncingPaths:oe,backends:V,policyBadgeFor:r?void 0:m,removingPaths:pe};return(0,$.jsxs)(`div`,{className:`px-3 py-2 space-y-1.5 outline-none`,tabIndex:0,onKeyDown:rt,children:[pe.size>0&&(0,$.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-1 rounded-md border bg-muted/50 p-2 text-xs`,children:[...pe].map(([e,t])=>(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(P,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block`,children:t}),(0,$.jsx)(`span`,{className:`block truncate text-muted-foreground`,title:e,children:e})]})]},e))}),!u&&(0,$.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:it,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:J(`px-2 py-0.5 rounded-full border transition-colors select-none`,Ae?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:Ae?`Drag → Copy`:`Drag → Move`}),L&&!r&&!Ae&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>Ne(e=>(Pe.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:J(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,Me?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:Me?`+ merge down`:`merge down: off`})]}),at&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,$.jsx)(`span`,{children:W?`Source: ${W.path} · ${le.size} target(s)`:`Select source with ⌃-click`}),(0,$.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{ce(null),ue(new Map)},children:`clear`})]}),(0,$.jsxs)(`div`,{"data-active":o===`/`&&!g||void 0,className:J(`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`,o===`/`&&!g?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,Ee===`/`&&!u&&!Oe&&`ring-2 ring-info bg-info-subtle/50`,Ee===`/`&&!u&&Oe&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>c(`/`),onDragEnter:e=>{u||He(`/`,e)},onDragOver:e=>{u||Ue(`/`,e)},onDragLeave:e=>We(`/`,e),onDrop:e=>{u||Ke(`/`,e)},onContextMenu:e=>{!u&&b&&(e.preventDefault(),fe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,$.jsx)(Xe,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,h&&(0,$.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,h,`]`]})]}),!u&&b&&(0,$.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(),fe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,$.jsx)(vn,{className:`w-4 h-4`})})]}),(0,$.jsxs)(`div`,{className:H?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[we===`/`&&(0,$.jsx)(tL,{onConfirm:e=>et(`/`,e),onCancel:tt}),e.children?.map((t,n)=>(0,$.jsx)(iL,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...ot},t.id||t.name)),!e.children?.length&&we!==`/`&&(0,$.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),de&&(0,$.jsx)(eL,{x:de.x,y:de.y,node:de.node,path:de.path,isBackendsTree:r,backends:V,isDirectoryTree:n===`directory`,onClose:()=>fe(null),onShowContent:de.node.metadata?.backendTrash?c:_,onRestoreTrash:u?void 0:i,onDiscardTrash:u?void 0:a,onOpenToSide:v?e=>v(e,n):void 0,sourceLayer:W,targetLayers:le,clipboard:U,onStartInlineCreate:e=>Te(e),onChangeIcon:B?()=>Ye({clientX:de.x,clientY:de.y,stopPropagation:()=>{}},de.path,de.node):void 0,onNewCanvas:x,onShareCanvas:S,onExportSubtree:D,onImportSubtree:u?void 0:O,onRemove:!u&&C&&![...pe.keys()].some(e=>e===de.path||e.startsWith(de.path+`/`)||de.path.startsWith(e+`/`))?he:void 0,onRename:u?void 0:w,onLock:u?void 0:j,onUnlock:u?void 0:M,onDestroy:u?void 0:N,onMerge:u?void 0:F,onSubtract:u?void 0:I,onMergeDown:u?void 0:L,onSubtractDown:u?void 0:R,onResyncBackend:z,onAddRule:d,onAddStoreRule:f,onStoragePolicy:!u&&!r?p:void 0,onRenameBackendFolder:te,onDeleteBackendFolder:!u&&ne&&![...pe.keys()].some(e=>e===de.path||e.startsWith(de.path+`/`)||de.path.startsWith(e+`/`))?e=>he(e,!0):void 0,onCopy:e=>nt(e,`copy`),onCut:e=>nt(e,`cut`),onPaste:$e,pastedDocumentIds:k,onPasteDocuments:A,isPinned:re?re(de.path):!1,onTogglePin:ie?()=>ie(de.path,de.node):void 0}),ge&&B&&(0,$.jsx)(Yw,{x:ge.x,y:ge.y,current:ve.get(ge.path)??Sm(ge.node),onChange:Ze,onClose:()=>_e(null)})]})}function oL(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=MT(),a=s_(),o=ml(),s=e.selectedEntityId,{showToast:c}=Vr(),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(`/`),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(!1),k=(0,Q.useCallback)(async e=>{w(!0);try{let t=await ms(e);f(t),E(null)}catch(e){E(e instanceof Error?e.message:`Failed to load the tree`)}finally{w(!1)}},[]);(0,Q.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await xs(e);if(t)return;u(n),m(n.url||``),g(void 0),v(``),S(null),b(n.path||`/`),w(!0);try{let n=await ms(e);t||(f(n),E(null))}catch(e){t||E(e instanceof Error?e.message:`Failed to load the tree`)}finally{t||w(!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 A=kb({contextId:s??void 0,onRefresh:()=>{s&&k(s)}}),j=e=>{g(void 0),S(e),m(l?.workspaceName?`${l.workspaceName}://${e.replace(/^\//,``)}`:e)},M=l!=null&&(p.trim()!==(l.url||``)||h!==void 0);return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(JI,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,$.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,$.jsx)(yn,{className:`w-3.5 h-3.5`})})}),(0,$.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(rh,{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:D,className:`min-w-0 flex-1`,inputClassName:J(`text-xs transition-colors`,M&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,$.jsx)(Z,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;O(!0);try{await ns(e,p,void 0,h);let t=await xs(e);u(t),m(t.url||``),b(t.path||`/`),S(null),g(void 0),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),await k(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{O(!1)}},disabled:D||!M,children:D?`…`:`Set`})]})]}),h&&(0,$.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,h,` · press Set to apply`]}),(0,$.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,$.jsx)(Y,{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,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,$.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`]}),T&&!d&&(0,$.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:T}),(0,$.jsx)(aL,{root:d,workspaceId:l?.workspaceName,searchQuery:_,selectedPath:y,pendingPath:x,onSelect:j,isLoading:C,rootLabel:l?.workspaceName,...A})]})]})}function sL({items:e,activeId:t,onSelect:n}){let[r,i]=(0,Q.useState)(``),a=e.filter(e=>lT(r,e.label,e.description||``));return(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,$.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,$.jsx)(Y,{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,$.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,$.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:J(`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,$.jsx)(`span`,{className:J(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,$.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,$.jsx)(hr,{className:J(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}function cL(){let{state:e,closeM2:t}=MT(),n=s_(),r=ml(),i=dl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return xs(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?BO(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,Q.useMemo)(()=>zO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(JI,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,$.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,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),(0,$.jsx)(sL,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function lL(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Ai();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>pd.emit(`subscribe`,{channel:`workspace`}),r=()=>pd.emit(`unsubscribe`,{channel:`workspace`}),i=pd.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=[[`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])=>pd.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>pd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,Q.useMemo)(()=>KT(t),[t]),isLoading:r,refresh:c}}function uL({status:e}){return(0,$.jsx)(`span`,{className:J(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function dL(){let e=Uw(),{state:t,selectEntity:n,openM2:r,closeM2:i}=MT(),a=s_(),{workspaces:o,isLoading:s}=lL(t.activeSection===`workspaces`),{showToast:c}=Vr(),l=ml(),[u,d]=(0,Q.useState)(new Set),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(new Map),_=(0,Q.useRef)(new Map),[v,y]=(0,Q.useState)(null),b=v&&v.base===o?v.order:o,{rowProps:x,handleProps:S,draggingIndex:C,insertLineClass:w}=YT((e,t)=>{let n=qT(b,e,t);y({base:o,order:n}),JT(n,(e,t)=>aa(Ww(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&c({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),E=e=>h.get(Ww(e))??{icon:e.icon??void 0,color:e.color??void 0},D=(e,t,n)=>{let r={...t,...n};g(t=>new Map(t).set(e,r));let i=_.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),aa(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>c({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},O=e=>{n(Ww(e)),r(`detail`,Ww(e)),!a&&aT(Ww(e))&&l(oT(Ww(e)))},k=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(Ww(t)));try{await ca(Ww(t)),c({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(Ww(t)),n})}},A=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(Ww(t)));try{await Ya(Ww(t)),c({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(Ww(t)),n})}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(KI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`})]}),!e.local&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{i(),l(`/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,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,$.jsx)(`div`,{className:`space-y-1.5 px-2`,children:b.map((e,i)=>{let o=t.selectedEntityId===Ww(e),s=Ep(e),c=u.has(Ww(e)),d=e.status!==`active`,p=E(e),h=jm(p.color);return(0,$.jsxs)(`div`,{...x(i),"data-active":o||void 0,className:J(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,o?`bg-accent shadow cursor-pointer hover:shadow`:d?`bg-card opacity-60 cursor-not-allowed`:`bg-card hover:bg-accent/50 cursor-pointer hover:shadow`,w(i,b.length),C===i&&`opacity-60`),onClick:()=>{d||O(e)},children:[(0,$.jsx)(`button`,{type:`button`,...S(i),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:J(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!h&&`bg-muted`),style:h?{backgroundColor:h}:void 0,children:(0,$.jsx)(T,{className:J(`h-3.5 w-3.5`,Mm(h))})}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:s?`Change icon`:`Workspace appearance requires admin access`,onClick:t=>{!s||br()||(t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Ww(e)}))},onContextMenu:t=>{s&&(t.preventDefault(),t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Ww(e)}))},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,$.jsx)(f,{icon:p.icon||`ph:stack-fill`,width:18,height:18,color:h,className:J(!h&&`text-muted-foreground`)})}),(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(uL,{status:e.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,$.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:`Stop`,children:(0,$.jsx)(zn,{className:`w-3.5 h-3.5`})}):(0,$.jsx)(`button`,{type:`button`,disabled:c,onClick:t=>k(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,$.jsx)(xe,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(Ww(e)),a?r(`settings`,Ww(e)):l(`/workspaces/${Ww(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:!s,title:s?`Settings`:`Workspace settings require admin access`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),p&&(()=>{let e=o.find(e=>Ww(e)===p.name);if(!e)return null;let t=E(e);return(0,$.jsx)(Yw,{x:p.x,y:p.y,current:t,onChange:e=>D(p.name,t,e),onClose:()=>m(null)})})()]})}function fL(e,t){let n=(0,Q.useRef)(null),r=(0,Q.useRef)(0);return(0,Q.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=tj(e);if(!r)return;let i=$A(),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=rj(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 pL(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 mL(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=pL(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 hL(e,t){let n=rs(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 gL({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(`forward`),u=c===`forward`||!i.some(e=>e.tree===`context`),[d,f]=(0,Q.useState)(`copy`),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)(!0),[y,b]=(0,Q.useState)(0),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(!0),[T]=(0,Q.useState)(()=>`autolink-${crypto.randomUUID()}`),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(0),[I,L]=(0,Q.useState)(0),[R,z]=(0,Q.useState)(0),[ee]=(0,Q.useState)(dp),[te,ne]=(0,Q.useState)(1),[B,re]=(0,Q.useState)(0),[ie,ae]=(0,Q.useState)(),[oe,V]=(0,Q.useState)(0),H=()=>{O||n()},U=_?`Checking whether this backend can receive files…`:``;if(!_)try{hL(t,h)}catch(e){U=e instanceof Error?e.message:`Choose a writable storage folder.`}let se=e=>{l(e),e!==`forward`&&(w(!1),i.some(e=>e.tree===`context`)&&S(!1))},W=e=>`${e.replace(/\/+$/,``)}/${x?`Subfolder/`:``}example.pdf`;return(0,Q.useEffect)(()=>{let t=!1;return To(e).then(e=>{t||g(e)}).catch(()=>{t||N(`Could not load storage backends. Reopen Autolink to retry.`)}).finally(()=>{t||v(!1)}),()=>{t=!0}},[e]),(0,$.jsx)(Fp,{label:o?`Choose virtual paths`:`Autolink documents`,onClose:o?()=>s(!1):H,children:o?(0,$.jsx)(nh,{fixedWorkspaceName:e,tabs:c!==`forward`&&x?[`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`&&S(!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,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b p-5`,children:[(0,$.jsxs)(`h2`,{className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,$.jsx)(Zt,{className:`h-5 w-5`}),`Autolink documents`]}),(0,$.jsx)(`button`,{type:`button`,onClick:H,disabled:O,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-5`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current backend folder`}),(0,$.jsxs)(`p`,{className:`mt-1 break-words text-sm`,children:[`backends:`,t]})]}),(0,$.jsxs)(`fieldset`,{disabled:O||E,className:`space-y-2 text-sm`,children:[(0,$.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,$.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>se(e.target.value),children:[(0,$.jsx)(`option`,{value:`forward`,children:`Backend → virtual folders (link)`}),(0,$.jsx)(`option`,{value:`reverse`,disabled:!!U,children:`Virtual folders → backend (Copy/Move)`}),(0,$.jsx)(`option`,{value:`both`,disabled:!!U,children:`Both directions`})]}),(0,$.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.`:``}`}),U&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:_?U:`Reverse mapping unavailable: ${U}`}),c!==`forward`&&(0,$.jsxs)(`div`,{className:`space-y-2 rounded-lg border p-3`,children:[(0,$.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-operation`,children:`File operation`}),(0,$.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,$.jsx)(`option`,{value:`copy`,children:`Copy files to this backend`}),(0,$.jsx)(`option`,{value:`move`,children:`Move files to this backend`})]}),d===`copy`&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Keep the source file and its virtual-folder links.`}),d===`move`&&(0,$.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,$.jsx)(`label`,{className:`block`,htmlFor:`autolink-source-backend`,children:`Move files from`}),(0,$.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,$.jsx)(`option`,{value:``,children:`Choose a source backend…`}),h.filter(e=>e.kind===`storage`&&e.enabled&&e.config?.readOnly!==!0).map(e=>(0,$.jsx)(`option`,{value:e.address,children:e.address},e.address))]}),(0,$.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,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`h3`,{className:`text-sm font-medium`,children:c===`reverse`?`Watch virtual folders`:`Virtual folders`}),i.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,$.jsx)(`p`,{className:`break-words`,children:e.path})]}),!E&&(0,$.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:O,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(G,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),!E&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,disabled:O,onClick:()=>s(!0),children:[(0,$.jsx)(sn,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,$.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,$.jsxs)(`fieldset`,{disabled:O||E,className:`space-y-3 text-sm`,children:[(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:x,disabled:!u,onChange:e=>S(e.target.checked),className:`mt-1`}),`Include subfolders and recreate their path in the destination`]}),!u&&(0,$.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,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),!!i.length&&(0,$.jsxs)(`div`,{className:`space-y-3 rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`Mapping preview`,children:[(0,$.jsx)(`h3`,{className:`font-medium`,children:`Example result`}),i.map(e=>(0,$.jsxs)(`div`,{className:`space-y-2 break-all text-xs`,children:[c!==`reverse`&&(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Link `}),`backends:`,W(t),(0,$.jsx)(`br`,{}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Into `}),e.tree===`context`?`ctx`:`dir`,`:`,W(e.path)]}),c!==`forward`&&(0,$.jsxs)(`p`,{children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground`,children:[d===`move`?`Move`:`Copy`,` `]}),e.tree===`context`?`ctx`:`dir`,`:`,W(e.path),(0,$.jsx)(`br`,{}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`To `}),`backends:`,W(t)]})]},`preview:${e.tree}:${e.path}`)),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:x?`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,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[C?`Existing matching documents are processed when you enable this rule.`: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.`]}),O&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:E?`${te>1?`Rule ${Math.min(y+1,te)}/${te}: `:``}Processing ${B}${ie===void 0?``:`/${ie}`} existing documents… ${I} matches applied.`:`Saving Auto-Link…`}),A&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Auto-Link is enabled for future documents.`,C?` ${oe} document${te>1?` checks across ${te} rules`:`s checked`}. ${I} matches applied.`:``]}),R>0&&(0,$.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[R,` document operations failed. Check the rule’s run log in Rules and rerun it after resolving the errors.`]}),M&&(0,$.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[E?`Auto-Link is enabled. `:``,M]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,$.jsx)(Z,{variant:`ghost`,disabled:O,onClick:r,children:`Manage rules`}),A?(0,$.jsx)(Z,{onClick:n,children:`Done`}):(0,$.jsx)(Z,{disabled:O||!i.length||c!==`forward`&&(!!U||d===`move`&&!p),onClick:async()=>{if(!O){k(!0),N(``);try{let n=c===`forward`?void 0:hL(t,await To(e)),r=mL(T,t,i,x,c,d,n,p);if(ne(r.length),E||(await bp(e,r),D(!0)),C){for(let t=y;t<r.length;t++){let n=t===y?P:0;re(n),ae(void 0);let i=await mp(e,{ruleId:r[t].id,limit:1,offset:n,dryRun:!0});for(ae(i.total);n!==null;){let i=await mp(e,{ruleId:r[t].id,limit:ee,offset:n});if(L(e=>e+i.matched-i.failed),z(e=>e+i.failed),re(n+i.processed),V(e=>e+i.processed),ae(i.total),i.nextOffset===void 0)throw Error(`The rule is enabled, but applying the full folder needs an updated server. Use Rules to rerun existing documents after updating.`);n=i.nextOffset,n!==null&&F(n)}b(t+1),F(0)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}j(!0)}catch(e){N(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{k(!1)}}},children:O?`Applying…`:E?`Retry existing documents`:`Enable Autolink`})]})]})})}async function _L(){return await X.get(`${Lr}/users/me/config/webui`)??{}}async function vL(e){return await X.put(`${Lr}/users/me/config/webui`,e)??e}var yL=`application/x-canvas-workspace-pin`;function bL({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:i,onShowInTree:a,onUnpin:o,onMove:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.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,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,$.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=jm(e.color),s=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===xo(e.tree,e.path),_=u?.id===e.id&&u.before,v=u?.id===e.id&&!u.before;return(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(yL,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:J(`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,$.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,$.jsx)(W,{className:`w-5 h-5 text-warning`}):(0,$.jsx)(f,{icon:s,width:22,height:22,color:n,className:J(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,$.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,$.jsx)(Vn,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,$.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,$.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,$.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.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,$.jsx)(ne,{className:`w-3.5 h-3.5`})}),(0,$.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,$.jsx)(ee,{className:`w-3.5 h-3.5`})})]}),!p&&(0,$.jsx)(T,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,$.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,$.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,$.jsx)(`p`,{children:`No pinned folders yet.`}),(0,$.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,$.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var xL=[`pins`,`context`,`layers`,`directory`,`backends`],SL=e=>typeof e==`string`&&xL.includes(e),CL=e=>{let t=Array.isArray(e)?e.filter(SL).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...xL.filter(e=>!t.includes(e))]},wL={pins:(0,$.jsx)(Oe,{className:`w-3.5 h-3.5`}),context:(0,$.jsx)(ae,{className:`w-3.5 h-3.5`}),layers:(0,$.jsx)(ur,{className:`w-3.5 h-3.5`}),directory:(0,$.jsx)(ne,{className:`w-3.5 h-3.5`}),backends:(0,$.jsx)(er,{className:`w-3.5 h-3.5`})},TL={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},EL=e=>e===`directory`||e===`backends`?e:co,DL=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function OL(){let{state:e}=MT();return e.selectedEntityId?(0,$.jsx)(dE,{workspaceName:e.selectedEntityId,children:(0,$.jsx)(kL,{},e.selectedEntityId)}):null}function kL(){let{state:e,closeM2:t,openM2:n,navigateFromMenu:r}=MT(),i=my(),a=s_(),o=e.selectedEntityId,s=ml(),c=dl(),{treeName:l,path:u}=Mx(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?DL(l,f):xL[0],[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)({icon:null,color:null}),[C,w]=(0,Q.useState)(m),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)([]),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),[z,ee]=(0,Q.useState)(!1),[te,ne]=(0,Q.useState)(u),[B,re]=(0,Q.useState)([]),[ie,ae]=(0,Q.useState)(new Set),[oe,V]=(0,Q.useState)(d&&u!==`/`?u:null),[H,U]=(0,Q.useState)(``),[se,W]=(0,Q.useState)(null),[ce,le]=(0,Q.useState)(null),[ue,de]=(0,Q.useState)(null),{policies:fe,refresh:pe}=dF(o),me=(0,Q.useCallback)(e=>{if(C!==`context`&&C!==`directory`||!fe.length)return null;let t=ZP(fe,C,e);return t.length?`Storage policy targets: ${QP(t)} (see Settings for transfer status)`:null},[C,fe]),[G,he]=(0,Q.useState)([]),[ge,_e]=(0,Q.useState)(!1),[ve,K]=(0,Q.useState)(!1),q=(0,Q.useRef)(null),ye=(0,Q.useRef)(!1),[be,xe]=(0,Q.useState)(!1),[Se,Ce]=(0,Q.useState)(xL),we=!p;(0,Q.useEffect)(()=>{let e=!1;return _L().then(t=>{if(e)return;let n=CL(t?.m2?.tabOrder);Ce(n),we&&w(e=>e===xL[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Te=(0,Q.useCallback)(async e=>{let t=Se;Ce(e);try{let t=await _L();await vL({...t,m2:{...t.m2,tabOrder:e}})}catch{Ce(t)}},[Se]),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)(null),Ae=()=>{De(null),ke(null)},je=()=>{if(Ee&&Oe&&Ee!==Oe.id){let e=Se.filter(e=>e!==Ee),t=e.indexOf(Oe.id);t>=0&&(e.splice(Oe.before?t:t+1,0,Ee),e.some((e,t)=>e!==Se[t])&&Te(e))}Ae()};(0,Q.useEffect)(()=>{let e=e=>W(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[Me,Ne]=(0,Q.useState)(u);u!==Me&&(Ne(u),ne(u));let Pe=(0,Q.useRef)(new Map),Fe=(0,Q.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();Pe.current.set(t,i);let a=()=>Pe.current.get(t)===i,o=t===`context`?P:t===`directory`?I:R,s=t===`context`?E:t===`directory`?O:A;n||o(!0);try{n&&!r&&ka(e,t);let i=await Si(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ie=(0,Q.useCallback)(async(e,t=!1)=>{let n=Symbol();Pe.current.set(`pins`,n);let r=()=>Pe.current.get(`pins`)===n;t||_e(!0);try{let t=await oi(e);r()&&he(t)}catch{}finally{r()&&_e(!1)}},[]),Le=(0,Q.useCallback)(async(e,t=!1)=>{let n=Symbol();Pe.current.set(`layers`,n);let r=()=>Pe.current.get(`layers`)===n;t||ee(!0);try{let t=await Gi(e,`context`);r()&&M(t)}catch{}finally{r()&&ee(!1)}},[]);(0,Q.useEffect)(()=>{if(!o)return;let e=o,t=!1,n=Pe.current;async function r(){qr(e).then(e=>{t||(v(e.label||e.name),g(Ep(e)),b(e.id||null),S({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Fe(e,`context`),Fe(e,`directory`),Fe(e,`backends`),Le(e),Ie(e)])}return r(),()=>{t=!0,n.clear()}},[o,Fe,Le,Ie]);let Re=(0,Q.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Fe(e,r,!0,n);(!t||t===`context`)&&Le(e,!0),Ie(e,!0)},[Fe,Le,Ie]),ze=(0,Q.useCallback)(()=>{o&&Re(o)},[o,Re]);(0,Q.useEffect)(()=>{if(!o)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==o||Re(o,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[o,Re]),(0,Q.useEffect)(()=>{if(!o)return;let e=!1,t=()=>To(o).then(t=>{e||(re(t),ae(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,Q.useEffect)(()=>{if(!o)return;let e=[`workspace:${o}`,y?`workspace:${y}`:null].filter(Boolean),t=()=>e.forEach(e=>pd.emit(`subscribe`,{channel:e})),n=pd.on(`connect`,t);t();let r=Ob(o,y),i=e=>{if(e?.workspaceId&&y&&e.workspaceId!==y)return;let t=e?.treePath;t&&ae(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};pd.on(`backend.resync.changed`,i);let a=e=>{e?.workspaceId&&y&&e.workspaceId!==y||Ie(o,!0)};return pd.on(`pins.changed`,a),()=>{r(),n?.(),pd.off(`backend.resync.changed`,i),pd.off(`pins.changed`,a)}},[o,y,Ie]);let[Be,Ve]=(0,Q.useState)(null),He=`${c.pathname}|${c.search}`;if(He!==Be){Ve(He);let{treeName:e,path:t}=Mx(c.pathname),n=new URLSearchParams(c.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!n;ve?K(!1):w(r||be?r?DL(e,n):C:Se[0]),ne(t),V(t===`/`?null:t)}let{showProgress:Ue}=Vr(),We=kb({workspaceId:o??void 0,treeName:EL(C),onRefresh:ze}),Ge=new Set(G.map(e=>xo(e.tree,e.path))),Ke=EL(C),qe=(0,Q.useCallback)(e=>Ge.has(xo(Ke,e)),[G,Ke]),Je=(0,Q.useCallback)(async e=>{if(!o)return;let t=G.find(t=>xo(t.tree,t.path)===xo(Ke,e));t?await Oa(o,t.id):await Oo(o,e,Ke),await Ie(o)},[o,G,Ke,Ie]),Ye=(0,Q.useCallback)(async e=>{if(o){he(t=>t.filter(t=>t.id!==e.id));try{await Oa(o,e.id)}finally{await Ie(o)}}},[o,Ie]),Xe=(0,Q.useCallback)(async(e,t)=>{if(!o)return;let n=G.find(t=>t.id===e);if(!n)return;let r=G.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===G[t])){he(a);try{he(await ea(o,a.map(e=>e.id)))}catch(e){throw await Ie(o),e}}},[o,G,Ie]),Ze=(0,Q.useCallback)(e=>{if(!o)return;K(!0),ne(e.path),V(null);let t=Nx(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]),Qe=(0,Q.useCallback)(e=>{!o||e.resolvable===!1||(K(!1),xe(!0),w(DL(e.tree)),ne(e.path),V(null),U(``),ye.current=!0,i?.setFocus(`main`),r(Nx(o,e.path,e.tree)))},[o,r,i]),$e=C===`context`?T:C===`directory`?D:C===`backends`?k:null,et=C===`context`?N:C===`directory`?F:C===`backends`&&L;(0,Q.useEffect)(()=>{if(!ye.current||et||C===`pins`)return;let e=q.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),ye.current=!1)},[C,te,$e,et]);let tt=(0,Q.useCallback)(e=>{xe(!0),w(e),ne(`/`),V(null),U(``)},[]),nt=(0,Q.useCallback)(e=>{tt(nj(Se,C,e))},[Se,C,tt]),rt=fL(e.m2Open,nt),it=e=>{V(null),ne(e);let t=EL(C);i?.setFocus(`main`),r(Nx(o,e,t))},at=(0,Q.useCallback)((e,t)=>{ne(e),V(e);let n=EL(C),a=new URLSearchParams;a.set(`layer`,`1`),t&&a.set(`layerId`,t),i?.setFocus(`main`),r(`${Nx(o,e,n)}?${a.toString()}`)},[o,C,r,i]),ot=(0,Q.useCallback)((e,t)=>{if(o){if(i){i.openCanvas({kind:`route`,location:Nx(o,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:t,path:e}}))}},[o,i]),st=(0,Q.useCallback)(async e=>{if(!o)return;let t=EL(C),n=await Co(o,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[o,C]),ct=H.toLowerCase().trim(),lt=ct?j.filter(e=>e.name.toLowerCase().includes(ct)||(e.label||``).toLowerCase().includes(ct)||(e.description||``).toLowerCase().includes(ct)):j;return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(JI,{title:_||o||`Workspace`,icon:x.icon||`ph:stack-fill`,accentColor:x.color,onBack:t,action:(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>o&&r(oT(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,$.jsx)(Ht,{className:`w-3.5 h-3.5`})}),(0,$.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,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})}),(0,$.jsx)(`div`,{...rt,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:Se.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>tt(e),title:`${TL[e]} — drag to reorder; the first tab opens by default`,"aria-label":TL[e],"aria-pressed":C===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,De(e)},onDragEnd:Ae,onDragOver:t=>{if(!Ee||Ee===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;ke(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),je()},className:J(`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`,Ee===e&&`opacity-40`,Oe?.id===e&&Oe.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Oe?.id===e&&!Oe.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[wL[e],e===`pins`&&G.length>0&&(0,$.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:G.length})]},e))}),(0,$.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,$.jsx)(tr,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,$.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:H,onChange:e=>U(e.target.value)})]})}),(0,$.jsx)(`div`,{ref:q,className:`flex-1 overflow-y-auto`,children:C===`pins`?(0,$.jsx)(bL,{pins:G,isLoading:ge,searchQuery:H,activeKey:xo(l,u),onOpen:Ze,onShowInTree:Qe,onUnpin:Ye,onMove:Xe}):C===`layers`?(0,$.jsx)(IL,{layers:lt,isLoading:z,wsName:o??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),r(`${Nx(o,`/`)}?${t.toString()}`)},onLock:async e=>{await Fi(o,e.id,o,`context`),Re(o)},onUnlock:async e=>{await Ua(o,e.id,o,`context`),Re(o)},onRename:async(e,t)=>{await na(o,e.id,t,`context`),Re(o)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await Yr(o,e.id,`context`),Re(o))}}):(0,$.jsx)(aL,{root:$e,workspaceId:o??void 0,treeName:C,isBackendsTree:C===`backends`,onRestoreTrash:o?e=>yb(o,e):void 0,onDiscardTrash:o?e=>xb(o,e):void 0,onShiftSelect:i?e=>ot(e,EL(C)):void 0,selectedPath:te,contentPath:oe,onSelect:it,onShowContent:C===`context`?at:void 0,onOpenToSide:ot,onShareCanvas:st,onNewCanvas:o&&C!==`backends`?e=>{s(`${Nx(o,e,C)}?createCanvas=1`)}:void 0,isLoading:et,rootLabel:o??void 0,searchQuery:H,backends:B,resyncingPaths:C===`backends`?ie:void 0,onAddRule:o&&C===`backends`?le:void 0,onAddStoreRule:o?(e,t=`store`)=>{let n=C===`backends`?(()=>{let n=Qf(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${C===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:ep(e)};s(`/workspaces/${o}/settings/hooks?${$f(n).toString()}`)}:void 0,onStoragePolicy:o&&(C===`context`||C===`directory`)?e=>de(HP(C,e)):void 0,policyBadgeFor:me,pastedDocumentIds:se?.documentIds,isPathPinned:qe,onTogglePin:o?Je:void 0,onPasteDocuments:o&&C!==`backends`?async(e,t)=>{let n=C===`directory`?`directory`:`context`,r=C===`directory`?`directory`:co,i=Ue({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await zi(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&&(se&&(W(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,...We})}),ce&&o&&(0,$.jsx)(gL,{workspaceId:o,sourcePath:ce,onClose:()=>le(null),onManageRules:()=>{le(null),s(`/workspaces/${o}/settings/hooks?section=rules`)}}),ue&&o&&(0,$.jsx)(nF,{workspaceId:o,path:ue,onClose:()=>de(null),onSaved:()=>{pe()}})]})}var AL={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}},jL=100,ML=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),NL=e=>AL[e]??{label:`${ML(e)} layers`,order:jL};function PL({type:e}){return e===`canvas`?(0,$.jsx)(gt,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,$.jsx)(er,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,$.jsx)(ur,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function FL(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:NL(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 IL({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(null);if((0,Q.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,$.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=FL(e);return(0,$.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,$.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,$.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,$.jsx)(`div`,{className:J(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,$.jsx)(PL,{type:e.type}),s===e.id?(0,$.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,$.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,$.jsx)(Vn,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,$.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,$.jsx)(Ot,{className:`w-3 h-3`})}):(0,$.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,$.jsx)(Vn,{className:`w-3 h-3`})}),!e.locked&&(0,$.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,$.jsx)(Ie,{className:`w-3 h-3`})}),!e.locked&&(0,$.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,$.jsx)(nt,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function LL(){let{state:e,closeM2:t}=MT(),n=s_(),r=ml(),i=dl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null),c=o?.address===a?o.workspace:null,l=c?.label||c?.name,u=Ep(c);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return qr(a).then(t=>{e||s({address:a,workspace:t})}).catch(()=>{}),()=>{e=!0}},[a]);let d=i.pathname.split(`/`).filter(Boolean),f=d[2]===`settings`?RO(d[3]):null,p=(0,Q.useMemo)(()=>IO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(JI,{title:`Settings: ${l||a||`Workspace`}`,icon:c?.icon||`ph:stack-fill`,accentColor:c?.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,$.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,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),u?(0,$.jsx)(sL,{items:p,activeId:f,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)}):(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:c?`Workspace settings are available to owners and admins.`:`Loading workspace…`})]})}function RL(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ik();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>pd.emit(`subscribe`,{channel:`agent`}),r=()=>pd.emit(`unsubscribe`,{channel:`agent`}),i=pd.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])=>pd.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>pd.off(e,t))}},[e,s]),(0,Q.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 zL({status:e}){return(0,$.jsx)(`span`,{className:J(`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 BL(){let e=Uw(),{state:t,selectEntity:n,openM2:r,closeM2:i}=MT(),a=s_(),{agents:o,isLoading:s,refresh:c}=RL(t.activeSection===`agents`),{showToast:l}=Vr(),[u,d]=(0,Q.useState)(new Set),f=ml(),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 vk(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 yk(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,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(KI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})]}),!e.local&&(0,$.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,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No agents found`}):(0,$.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,$.jsxs)(`div`,{"data-active":i||void 0,className:J(`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,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(zL,{status:e.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,$.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,$.jsx)(zn,{className:`w-3.5 h-3.5`})}):(0,$.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,$.jsx)(xe,{className:`w-3.5 h-3.5`})}),(0,$.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,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description})]},e.id)})})})]})}function VL(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function HL(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function UL(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 WL(){let{state:e,closeM2:t}=MT(),n=e.selectedEntityId||``,r=ml(),{showToast:i}=Vr(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),{current:h,sessions:g,isLoading:_,error:v,refresh:y,create:b,select:x,rename:S,remove:C}=ON(n);(0,Q.useEffect)(()=>{n&&(ak(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,Q.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(UL(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(UL(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 "${VL(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,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(JI,{title:a?.label||a?.name||n,onBack:t,action:(0,$.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,$.jsx)(yn,{className:`h-3.5 w-3.5`})})}),(0,$.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,$.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,$.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:g?.mode===`incognito`?`Incognito mode`:g?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,$.jsxs)(Z,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:_,children:[(0,$.jsx)(sn,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,$.jsxs)(Z,{size:`sm`,variant:g?.mode===`experimental`?`default`:`outline`,onClick:k,disabled:_,children:[(0,$.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,$.jsx)(Z,{size:`sm`,variant:g?.mode===`incognito`?`default`:`outline`,onClick:A,disabled:_,children:`Incognito`})]})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[v&&(0,$.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:v}),s&&(0,$.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,$.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{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,$.jsx)(Z,{size:`sm`,onClick:O,disabled:_,children:`Create`})]})]}),g?.sessions.length?(0,$.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,$.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,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{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,$.jsx)(Z,{size:`sm`,onClick:t=>{t.stopPropagation(),M(e)},disabled:!p.trim()||_,children:`Save`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:VL(e)}),e.isExperimental&&(0,$.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,$.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,$.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:HL(e)})]})}),!n&&(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),m(e.name||VL(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,$.jsx)(gr,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,$.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,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-sm`,children:_?`Loading sessions...`:`No persistent sessions yet.`}),(0,$.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),h?.mode===`incognito`&&(0,$.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 GL(){let{state:e,closeM2:t}=MT(),n=s_(),r=ml(),i=dl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return ak(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?HO(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,Q.useMemo)(()=>VO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(JI,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,$.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,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),(0,$.jsx)(sL,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function KL(){let e=dl(),{state:t}=MT(),[n,r]=(0,Q.useState)(``),i=(0,Q.useRef)(null);(0,Q.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=sT.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>lT(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,$.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(KI,{}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`})]}),(0,$.jsx)(Y,{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,$.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,$.jsxs)(`section`,{"aria-label":t.label,children:[(0,$.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,$.jsxs)(ju,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:J(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,$.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,$.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,$.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var qL=280,JL=220,YL=560;function XL(){let{state:e}=MT(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,$.jsx)(cL,{});if(n===`detail`)return(0,$.jsx)(oL,{})}if(t===`workspaces`){if(n===`settings`)return(0,$.jsx)(LL,{});if(n===`detail`)return(0,$.jsx)(OL,{})}if(t===`agents`){if(n===`settings`)return(0,$.jsx)(GL,{});if(n===`detail`)return(0,$.jsx)(WL,{})}return null}function ZL(){let{state:e,closeM1:t,closeM2:n}=MT();Np(t,e.m1Open&&!e.m2Open),Np(n,e.m1Open&&e.m2Open);let r=s_(),i=(0,Q.useRef)(null),a=(0,Q.useRef)(null);WI(i,e.m1Open&&!e.m2Open,e.activeSection??``),WI(a,e.m1Open&&e.m2Open,`${e.activeSection}:${e.selectedEntityId}:${e.m2View}`);let[o,s]=(0,Q.useState)(qL),[c,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),d=(0,Q.useCallback)(e=>{e.preventDefault(),l(!0),u.current={startX:e.clientX,startWidth:o};let t=e=>{if(!u.current)return;let t=e.clientX-u.current.startX,n=Math.min(YL,Math.max(JL,u.current.startWidth+t));s(n)},n=()=>{u.current=null,l(!1),window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[o]),f=r&&e.m1Open;return(0,$.jsxs)($.Fragment,{children:[f&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,$.jsxs)(`div`,{style:e.m1Open&&!f?{width:o}:void 0,className:J(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!c&&!f&&`transition-[width] duration-normal ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,f?`fixed bottom-2 left-[calc(0.5rem+var(--spacing-rail)+0.5rem)] right-2 top-2 z-40 shadow-elevation-5`:`relative`),children:[(0,$.jsxs)(`div`,{ref:i,"data-menu-view":`list`,inert:!e.m1Open||e.m2Open,className:J(`absolute inset-0 flex flex-col transition-opacity duration-normal ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:f?void 0:{minWidth:o},children:[e.activeSection===`contexts`&&(0,$.jsx)(qI,{}),e.activeSection===`workspaces`&&(0,$.jsx)(dL,{}),e.activeSection===`agents`&&(0,$.jsx)(BL,{}),e.activeSection===`admin`&&(0,$.jsx)(KL,{}),e.activeSection===`settings`&&(0,$.jsx)(KL,{})]}),(0,$.jsx)(`div`,{ref:a,"data-menu-view":`detail`,inert:!e.m1Open||!e.m2Open,className:J(`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,$.jsx)(XL,{})}),e.m1Open&&!f&&(0,$.jsx)(`div`,{onMouseDown:d,className:`absolute right-0 top-0 bottom-0 z-20 w-1 cursor-col-resize hover:bg-primary/20 transition-colors`})]})]})}var QL=`canvas:readerWidth`,$L=320,eR=1600;function tR(){try{let e=Number(sessionStorage.getItem(QL));return Number.isFinite(e)&&e>=$L&&e<=eR?e:null}catch{return null}}var nR=tR(),rR=new Set;function iR(e){return rR.add(e),()=>{rR.delete(e)}}function aR(e){nR=e===null?null:Math.round(Math.max($L,Math.min(eR,e)));try{nR===null?sessionStorage.removeItem(QL):sessionStorage.setItem(QL,String(nR))}catch{}rR.forEach(e=>e())}function oR(){return(0,Q.useSyncExternalStore)(iR,()=>nR,()=>null)}var sR=320,cR=1600;function lR({edge:e}){let t=oR(),n=(0,Q.useRef)(null),r=e===`left`?-1:1;return(0,$.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":sR,"aria-valuemax":cR,"aria-valuenow":t??420,tabIndex:0,title:`Drag to resize; arrow keys adjust width; double-click to reset`,className:`absolute inset-y-0 ${e===`left`?`left-0`:`right-0`} z-20 hidden w-2 touch-none cursor-col-resize select-none hover:bg-primary/20 focus-visible:bg-primary/20 focus-visible:outline-none md:block`,onPointerDown:t=>{if(t.button!==0)return;t.preventDefault(),t.stopPropagation();let r=t.currentTarget.closest(`[data-reader-pane]`),i=e===`left`?(r.parentElement?.clientWidth??window.innerWidth)-248:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(sR,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&aR(Math.min(n.current.max,n.current.width+r*(e.clientX-n.current.x)))},onPointerUp:e=>{n.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{n.current=null},onLostPointerCapture:()=>{n.current=null},onDoubleClick:()=>aR(null),onKeyDown:e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`&&e.key!==`Home`)return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.closest(`[data-reader-pane]`);e.key===`Home`?aR(null):aR(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function uR(e){return e.schema===`data/schema/note`?Kn:e.schema===`data/schema/tab`?_n:e.schema===`data/schema/file`?Rn:e.schema===`data/schema/message/email`?bt:Hn}function dR({entry:e,onClose:t,frame:n}={}){let r=wg(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=zy(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,$.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,$.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between border-b-[3px] bg-muted pl-4 pr-2`,children:[(0,$.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,$.jsx)(`button`,{type:`button`,onClick:a,className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent`,"aria-label":`Close`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,$.jsx)(`button`,{type:`button`,className:`ml-2 underline`,onClick:r.retry,children:`Retry`})]})]}):null;let{workspaceId:c}=i,l=t=>{s(t),t&&t.id!==i.document.id&&!e&&r.replace?.(t,c)};return(0,$.jsx)(xD,{title:Mi(o).title,icon:uR(o),onClose:a,onSave:async e=>(await zi(c,e.path,[o.id],e.treeName,e.treeType),[o.id]),canSave:!0,successMessage:`Linked`,lockedWorkspaceName:c,relationSubjectId:o.id,frame:n,fillParent:!0,fullWidthContent:_v(o)===y_,maximized:e?void 0:r.location?.maximized,onMaximizedChange:e?void 0:e=>r.update?.({maximized:e}),children:t=>(0,$.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,$.jsx)(Ry,{document:o,workspaceId:c,onChanged:l,compact:!0,tabActions:t,initialTab:e?void 0:r.location?.section,onTabChange:e?void 0:e=>r.update?.({section:e})},`${c}:${o.id}`)})})}function fR(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function pR(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`].includes(t)&&!!n}var mR=`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`,hR=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function gR(){let e=oR(),{pathname:t,search:n}=dl(),{state:r}=MT(),i=(0,Q.useRef)(null);WI(i,!r.m1Open,t+n,!r.m0Open);let a=pR(t),o=fR(t),{entry:s,loading:c,error:l,close:u}=wg();return(0,$.jsx)(`div`,{className:J(`relative flex flex-col flex-1 min-w-0`,!o&&`surface-sheet`),children:(0,$.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,$.jsx)(`main`,{ref:i,id:`content-area`,className:J(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!a&&!o&&`p-page max-md:pb-rail-stack`),children:(0,$.jsx)(Vl,{})}),(s||c||l)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:hR,onClick:u,"aria-hidden":!0}),(0,$.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??420}px`},className:J(`relative z-10 flex shrink-0 items-stretch py-2 mr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_248px)]`,mR),children:[(0,$.jsx)(lR,{edge:`left`}),(0,$.jsx)(dR,{},s?`${s.workspaceId}:${s.document.id}`:`loading`)]})]})]})})}function _R(){let{state:e,setView:t}=Ls(),{pathname:n}=dl();return e.t1Open||e.addOpen||!fR(n)?null:(0,$.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,$.jsx)(Un,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var vR={current:null,sessions:null,isLoading:!1,error:null};function yR(e){return e instanceof Error?e.message:`Session request failed`}function bR({children:e}){let[t,n]=(0,Q.useState)({}),r=(0,Q.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||vR,...t}}))},[]),i=(0,Q.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,Q.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([ok(e),sk(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:yR(t)}),t}}},[r]),o=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await ck(e,t))}catch(t){throw r(e,{isLoading:!1,error:yR(t)}),t}},[i,r]),s=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await lk(e,t))}catch(t){throw r(e,{isLoading:!1,error:yR(t)}),t}},[i,r]),c=(0,Q.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await uk(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:yR(t)}),t}},[i,r]),l=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await dk(e,t))}catch(t){throw r(e,{isLoading:!1,error:yR(t)}),t}},[i,r]),u=(0,Q.useMemo)(()=>({getState:e=>t[e]||vR,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,$.jsx)(DN.Provider,{value:u,children:e})}function xR(){let e=Ts(),{closeAdd:t}=Ls(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,Q.useState)(`Untitled.txt`),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),u=!1;try{ps(``,i.trim()),u=!0}catch{}return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`plaintext-filename`,children:`Filename`}),(0,$.jsx)(Y,{id:`plaintext-filename`,autoFocus:!0,value:i,onChange:e=>a(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Content`}),(0,$.jsx)(Bo,{kind:`text`,value:o,onChange:s,placeholder:`Write plain text…`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a file in the current storage folder. Existing files are never overwritten.`}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:t,disabled:c,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(!(c||!u||e?.mode!==`workspace`||e.treeName!==`backends`)){l(!0);try{let r=await Ds(e.workspaceName,e.path);await Br(e.workspaceName,{...r,key:ps(r.key,i.trim())},new Blob([o],{type:`text/plain;charset=utf-8`}),{contentType:`text/plain;charset=utf-8`}),hs(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`})]})]})}var SR=`references`;function CR(e){return e?e.documents.map(e=>({predicate:SR,direction:`out`,targetId:e.id,document:e})):[]}function wR(e,t){let[n,r]=(0,Q.useState)(()=>CR(t)),[i,a]=(0,Q.useState)([...no]),o=e?.mode===`context`?e.contextId:null,[s,c]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!o)return;let e=!1;return As({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,Q.useEffect)(()=>{let e=!1;if(l)return Ii(l).then(t=>{e||a(t)}),()=>{e=!0}},[l]),{rows:n,predicates:i,workspaceName:l,add:(0,Q.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?qa(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,Q.useCallback)((e,t)=>{r(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),remove:(0,Q.useCallback)(e=>{r(t=>t.filter((t,n)=>n!==e))},[]),write:(0,Q.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 ho(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&&Ig(),r},[n,l]),hasRows:n.length>0}}function TR({f:e,idPrefix:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(!1),o=!e.workspaceName;return(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(Uu,{children:`Related documents`}),(0,$.jsxs)(Z,{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,$.jsx)(sn,{className:`mr-1 h-3 w-3`}),` Add`]})]}),e.rows.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None. Relations are written right after the document is created.`}):(0,$.jsx)(`ul`,{className:`space-y-1`,children:e.rows.map((n,r)=>{let i=n.document?Mi(n.document).title:`Document ${n.targetId}`,a=`${t}-relation-${r}`;return(0,$.jsxs)(`li`,{className:`flex items-center gap-1.5 rounded-md border border-input px-2 py-1.5 text-sm`,children:[(0,$.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,$.jsx)(Dt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Jn,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`label`,{htmlFor:a,className:`sr-only`,children:`Predicate`}),(0,$.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,$.jsx)(`option`,{value:e,children:e},e))}),n.document?(0,$.jsx)(Um,{document:n.document,size:3.5}):null,(0,$.jsx)(`span`,{className:J(`min-w-0 flex-1 truncate`,!n.document&&`italic text-muted-foreground`),title:i,children:i}),(0,$.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,$.jsx)(G,{className:`h-3.5 w-3.5`})})]},`${n.direction}:${n.predicate}:${n.targetId}`)})}),n&&e.workspaceName&&(0,$.jsx)(Zp,{onClose:()=>{i||r(!1)},children:(0,$.jsx)(nh,{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 ER(){let{closeAdd:e,state:t}=Ls(),n=Ts(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=wR(n,t.addRelateTo),o=_S(n,a.write,t.addRelateTo?`related:${t.addRelateTo.documents.map(e=>e.id).sort().join(`,`)}`:`add`),s=zD(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,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Body`}),(0,$.jsx)(Bo,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`note-comment`,children:`Comment`}),(0,$.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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Tags`}),(0,$.jsx)(eg,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsx)(yD,{geotag:o.geotag,idPrefix:`note-geotag`}),(0,$.jsx)(TR,{f:a,idPrefix:`note`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ks(n)}),(0,$.jsx)(Uo,{...o,onRetry:o.retry}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:o.saving,children:`Close`}),(0,$.jsx)(Z,{size:`sm`,onClick:l,disabled:!c,children:o.saving?`Saving…`:`Done`})]})]})}function DR(){let{closeAdd:e,state:t}=Ls(),n=Ts(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=ED(),o=wR(n,t.addRelateTo),s=zD(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`link-url`,children:`URL`}),(0,$.jsx)(Y,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`link-title`,children:`Title`}),(0,$.jsx)(Y,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Tags`}),(0,$.jsx)(eg,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsx)(yD,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,$.jsx)(TR,{f:o,idPrefix:`link`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ks(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,$.jsx)(Z,{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 OR(e){let[t,n]=(0,Q.useState)({key:``,list:[]});return(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return To(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await Ea(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 kR(){let{closeAdd:e,state:t}=Ls(),n=Ts(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=K_(),o=wR(n,t.addRelateTo),s=zD(t.activeWorkspaceName),c=OR(t.activeWorkspaceName),[l,u]=(0,Q.useState)(`canvas`),[d,f]=(0,Q.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 ia(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,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsx)(Uv,{...a}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Tags`}),(0,$.jsx)(eg,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`todo-comment`,children:`Comment`}),(0,$.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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`todo-destination`,children:`Save to`}),(0,$.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,$.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,ks(n)]}),c.map(e=>(0,$.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,$.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,$.jsx)(yD,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,$.jsx)(TR,{f:o,idPrefix:`todo`}),!p&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ks(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function AR(){let{closeAdd:e,state:t}=Ls(),n=Ts(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=Qv(),o=wR(n,t.addRelateTo),s=zD(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,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsx)(ry,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Tags`}),(0,$.jsx)(eg,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`identity-comment`,children:`Comment`}),(0,$.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,$.jsx)(TR,{f:o,idPrefix:`identity`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ks(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function jR({capture:e=!1}={}){let{closeAdd:t,state:n}=Ls(),r=Ts(),i=r?.mode===`workspace`&&r.treeName===`backends`,a=wR(r,n.addRelateTo),{showSuccessToast:o,showErrorToast:s}=Wr(),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(!1),d=MD(),{items:f,running:p}=d,[m,h]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(r?.mode!==`context`)return;let e=!1;return As(r).then(t=>{e||h({contextId:r.contextId,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[r]);let g=HD(r?.mode===`workspace`?r.workspaceName:r&&m?.contextId===r.contextId?m.workspaceName:null),_=e=>{e&&d.addFiles(Array.from(e))},v=e=>{e.preventDefault(),u(!1),_(e.dataTransfer.files)},y=f.filter(e=>e.status===`error`).length,b=f.filter(e=>e.status===`done`).length,x=f.length-b,S=!!r&&!p&&x>0;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,onClick:()=>c.current?.click(),className:J(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,l?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,$.jsx)(Qe,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,$.jsx)(`p`,{className:`text-sm`,children:e?`Take a photo or video`:`Drag & drop files here`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`click to open the camera`:`or click to browse`}),(0,$.jsx)(`input`,{ref:c,type:`file`,multiple:!0,accept:e?`image/*,video/*`:void 0,capture:e?`environment`:void 0,className:`hidden`,onChange:e=>{_(e.target.files),e.target.value=``}})]}),(0,$.jsx)(LD,{items:f,running:p,onRemove:d.removeItem}),!i&&(0,$.jsx)(GD,{fields:g,idPrefix:`file`,multiple:f.length>1}),(0,$.jsx)(TR,{f:a,idPrefix:`file`}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[ks(r),i?`. Existing files are never overwritten.`:``]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>p?d.cancel():t(),children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(!(!S||!r))try{let e=i?null:await g.geotag.capture(),n=await d.start(r,(t,n)=>UD(t,n,{tags:g.tags,comment:g.comment,geo:e})),c=await a.write(n.docIds);if(n.failed===0){let e=n.resumed?` (${n.resumed} already uploaded)`:``,r=c?`; some relations failed`:``;o(`${n.done} file(s) uploaded${e}${r}`),t()}else s(`${n.failed} of ${n.total} file(s) failed — retry keeps what already made it`)}catch(e){s(e instanceof Error?e.message:`Failed to upload files`)}},disabled:!S,children:p?`Uploading…`:y>0?(0,$.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(ir,{className:`h-3.5 w-3.5`}),`Retry failed (`,y,`)`]}):`Add files`})]})]})}function MR(){let{closeAdd:e}=Ls(),t=Ts(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.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 As(t),o=i===`/`?``:i;if(a===`backends`){let e=await Ds(r,i);await sa(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),hs(t)}else await Wa(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,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,$.jsx)(Y,{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,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,ks(t)]})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function NR(){let{openAddPicker:e,closeAdd:t}=Ls(),n=Ts(),{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,Q.useState)(!1);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>e(),"aria-hidden":!0}),(0,$.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,$.jsx)(xg,{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 Ss(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 PR(){let{state:e,closeAdd:t}=Ls(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,$.jsx)(FR,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a},`${r}:${n.id}`)}function FR({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=jo(e,t),s=zD(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,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`edit-note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,$.jsx)(Uu,{children:`Body`}),(0,$.jsx)(`div`,{className:`flex-1`,children:(0,$.jsx)(Bo,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Tags`}),(0,$.jsx)(eg,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsx)(Uo,{...o,onRetry:o.save}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Close`}),(0,$.jsx)(Z,{size:`sm`,onClick:c,disabled:!o.canSave,children:o.saving?`Saving…`:`Done`})]})]})}function IR(e,t){let n=Ko(e.metadata?.features),[r,i]=(0,Q.useState)(String(e.data?.label??``)),[a,o]=(0,Q.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,Q.useState)(!1),l=!s;async function u(){c(!0);try{let n=a.map(e=>e.trim()).filter(Boolean);await go(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data,...r.trim()?{label:r.trim()}:{},tags:n},metadata:{features:qo(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 LR(){let{state:e,closeAdd:t}=Ls(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,$.jsx)(RR,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function RR({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=IR(e,t),s=zD(t);return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(Uu,{children:[`URL `,(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,$.jsx)(Y,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{htmlFor:`edit-link-label`,children:`Label`}),(0,$.jsx)(Y,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Uu,{children:`Tags`}),(0,$.jsx)(eg,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,$.jsx)(Z,{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 zR=380,BR=300,VR=560,HR={message:{label:`New Message`,icon:b},note:{label:`New Note`,icon:Kn},link:{label:`New Link`,icon:_n},todo:{label:`New Todo`,icon:Vt},identity:{label:`New Identity`,icon:We},sketch:{label:`New Sketch`,icon:le},plaintext:{label:`New Plaintext File`,icon:nn},file:{label:`Add Files`,icon:Qe},photo:{label:`Photo/Video`,icon:Ke},existing:{label:`Add Existing`,icon:En},folder:{label:`New Folder`,icon:st}};function UR(){let{state:e,openAdd:t,openAddPicker:n,closeAdd:r}=Ls();Np(r,e.addOpen);let{addOpen:i,addKind:a,editDocument:o,addModal:s}=e,c=Ts(),l=Ms(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=ml();(0,Q.useEffect)(()=>{!i||a!==`sketch`||l.isBackend||(r(),g(mD.createUrl(c)))},[i,a,c,r,g,l.isBackend]);let _=c_(),[v,y]=(0,Q.useState)(zR),b=(0,Q.useRef)(null),x=(0,Q.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(VR,Math.max(BR,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`?Kn:_n):a&&!p?(w=HR[a].label,T=HR[a].icon):(w=`Add`,T=sn);let E=(0,$.jsxs)($.Fragment,{children:[_&&!s&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:r,"aria-hidden":!0}),(0,$.jsxs)(`div`,{style:_||s?void 0:{width:v},className:J(`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,$.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,$.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,$.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,"aria-label":`Back one level`,onClick:()=>C||S?r():n(),children:(0,$.jsx)(Jn,{className:`h-5 w-5`})}),(0,$.jsxs)(`span`,{className:`flex flex-1 items-center gap-2 text-sm font-medium`,children:[S?(0,$.jsx)(_e,{className:`h-4 w-4`}):(0,$.jsx)(T,{className:`h-4 w-4`}),w]}),(0,$.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,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[S&&o.schema===`data/schema/note`&&(0,$.jsx)(PR,{}),S&&o.schema===`data/schema/link`&&(0,$.jsx)(LR,{}),!S&&C&&e.addRelateTo&&(0,$.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,$.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,$.jsx)(_D,{onSelect:t,omit:m}),!S&&a===`message`&&!f&&d&&(0,$.jsx)(Cv,{workspaceId:d,onClose:r},d),!S&&!l.isBackend&&a===`note`&&(0,$.jsx)(ER,{},h),!S&&!l.isBackend&&a===`link`&&(0,$.jsx)(DR,{}),!S&&!l.isBackend&&a===`todo`&&(0,$.jsx)(kR,{}),!S&&!l.isBackend&&a===`identity`&&(0,$.jsx)(AR,{}),!S&&l.destination&&a===`plaintext`&&(0,$.jsx)(xR,{},h),!S&&(!l.isBackend||l.destination)&&a===`file`&&(0,$.jsx)(jR,{},h),!S&&(!l.isBackend||l.destination)&&a===`photo`&&(0,$.jsx)(jR,{capture:!0},h),!S&&!l.isBackend&&a===`existing`&&(0,$.jsx)(NR,{}),!S&&(!l.isBackend||l.destination)&&a===`folder`&&(0,$.jsx)(MR,{},h)]})]})]});return s?(0,$.jsx)(Fp,{label:w,onClose:r,children:E}):E}var WR=(0,Q.createContext)(null);function GR(){return(0,Q.useContext)(WR)}function KR(){let e=GR(),t=e?.notifications??[];return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,$.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,$.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,$.jsx)(N,{className:`w-4 h-4`}),(0,$.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(bn,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,$.jsx)(nt,{className:`w-3 h-3`})})]}),t.length===0?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-(--card-radius)`,children:`No notifications`}):(0,$.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,$.jsxs)(`div`,{className:`rounded-(--card-radius) border p-2.5`,children:[(0,$.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,$.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}function qR({status:e}){return(0,$.jsx)(`span`,{className:J(`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 JR(){let{openAgentT2:e}=Ls(),{setSection:t}=MT(),n=ml(),{agents:r,isLoading:i,refresh:a}=RL(!0),{showToast:o}=Vr(),[s,c]=(0,Q.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 vk(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 yk(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,$.jsx)(ct,{className:`w-8 h-8 opacity-30`}),(0,$.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,$.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,$.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,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(qR,{status:t.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,$.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,$.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,$.jsx)(zn,{className:`w-3 h-3`})}):(0,$.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,$.jsx)(xe,{className:`w-3 h-3`})})})]}),t.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function YR(){let e=GR(),[t,n]=(0,Q.useState)(50),r=e?.notifications??[],i=r.slice(-t).reverse();return(0,$.jsxs)(`section`,{"aria-label":`Notification history`,className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b px-4 py-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Notifications`,r.length>0&&(0,$.jsx)(`span`,{className:`ml-2 font-normal text-muted-foreground`,children:r.length})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:`Saved on this browser`})]}),r.length>0&&(0,$.jsxs)(Z,{variant:`ghost`,size:`sm`,onClick:()=>void e?.clear(),title:`Clear all notifications`,className:`shrink-0 gap-1.5`,children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),`Clear all`]})]}),e?.storageError&&(0,$.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,$.jsx)(`p`,{role:`status`,className:`p-4 text-sm text-muted-foreground`,children:`Loading notifications…`}):r.length===0?(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,$.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,$.jsx)(bn,{className:`h-5 w-5 text-muted-foreground`})}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No notifications yet`})]}):(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[(0,$.jsx)(`ol`,{className:`space-y-2`,children:i.map(t=>{let n=t.status===`error`?z:t.status===`completed`?be:t.status===`started`?N:bn;return(0,$.jsx)(`li`,{"data-notification-id":t.id,className:`rounded-(--card-radius) border bg-card p-3`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(n,{"aria-hidden":!0,className:`mt-0.5 h-4 w-4 shrink-0 ${t.status===`error`?`text-destructive`:`text-muted-foreground`}`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`break-words text-sm font-medium`,children:t.title}),t.text&&(0,$.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap break-words text-xs text-muted-foreground`,children:t.text}),(0,$.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[(0,$.jsx)(`time`,{dateTime:t.timestamp,children:new Date(t.timestamp).toLocaleString()}),t.status===`started`&&(0,$.jsx)(`span`,{children:` · Started`}),t.status===`completed`&&(0,$.jsx)(`span`,{children:` · Completed`}),t.status===`error`&&(0,$.jsx)(`span`,{children:` · Error`})]})]}),(0,$.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,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})},t.id)})}),r.length>t&&(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,className:`mt-3 w-full`,onClick:()=>n(e=>e+50),children:`Show older notifications`})]})]})}function XR(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(`
54
54
  `)||``}function ZR(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(null),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(e);return c!==e&&(l(e),e||n([])),(0,Q.useEffect)(()=>{let t=!1;if(e)return ok(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,Q.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 vk(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 X.stream(`${Lr}/agents/${e}/prompt/stream`,{message:t},{signal:s.current.signal,onChunk:e=>{a+=e;let t=a.split(`