@robthepcguy/rag-vault 1.8.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -43
- package/dist/hyde/index.d.ts +47 -0
- package/dist/hyde/index.d.ts.map +1 -0
- package/dist/hyde/index.js +203 -0
- package/dist/hyde/index.js.map +1 -0
- package/dist/reranker/index.d.ts +76 -0
- package/dist/reranker/index.d.ts.map +1 -0
- package/dist/reranker/index.js +199 -0
- package/dist/reranker/index.js.map +1 -0
- package/dist/server/index.d.ts +25 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +103 -14
- package/dist/server/index.js.map +1 -1
- package/dist/server/schemas.d.ts +21 -100
- package/dist/server/schemas.d.ts.map +1 -1
- package/dist/server/schemas.js +3 -3
- package/dist/server/schemas.js.map +1 -1
- package/dist/utils/config-parsers.d.ts +14 -0
- package/dist/utils/config-parsers.d.ts.map +1 -1
- package/dist/utils/config-parsers.js +26 -0
- package/dist/utils/config-parsers.js.map +1 -1
- package/dist/utils/config.d.ts +23 -0
- package/dist/utils/config.d.ts.map +1 -1
- package/dist/utils/config.js +39 -1
- package/dist/utils/config.js.map +1 -1
- package/dist/utils/file-utils.d.ts.map +1 -1
- package/dist/utils/file-utils.js +17 -1
- package/dist/utils/file-utils.js.map +1 -1
- package/dist/vectordb/index.d.ts +33 -7
- package/dist/vectordb/index.d.ts.map +1 -1
- package/dist/vectordb/index.js +161 -47
- package/dist/vectordb/index.js.map +1 -1
- package/package.json +8 -7
- package/skills/rag-vault/SKILL.md +3 -3
- package/skills/rag-vault/references/html-ingestion.md +1 -1
- package/web-ui/dist/assets/{CollectionsPage-CjLs8_5j.js → CollectionsPage-wbfgYFTw.js} +1 -1
- package/web-ui/dist/assets/{FilesPage-Bw9x9aMr.js → FilesPage-D6TlldaR.js} +1 -1
- package/web-ui/dist/assets/{ReaderPage-JPNiOF-x.js → ReaderPage-Sgy0vMZ6.js} +1 -1
- package/web-ui/dist/assets/{ReaderSettingsContext-BLFJnEne.js → ReaderSettingsContext-DsvLXuaf.js} +1 -1
- package/web-ui/dist/assets/{SearchPage-D3_Vtbdw.js → SearchPage-mPKXZEyq.js} +1 -1
- package/web-ui/dist/assets/{SettingsPage-BAxB2264.js → SettingsPage-DXeWwfvd.js} +1 -1
- package/web-ui/dist/assets/{StatusPage-CzJZW8Gs.js → StatusPage-AirpfsGF.js} +1 -1
- package/web-ui/dist/assets/{UploadPage-DW8OujeJ.js → UploadPage-Cob25kDa.js} +1 -1
- package/web-ui/dist/assets/index-BZMzEssr.js +6 -0
- package/web-ui/dist/assets/motion-DdHBXDWx.js +9 -0
- package/web-ui/dist/assets/query-DbAD_nLW.js +1 -0
- package/web-ui/dist/assets/{vendor-DSXQOR6A.js → vendor-DNJ-hWNb.js} +1 -1
- package/web-ui/dist/index.html +3 -3
- package/web-ui/dist/assets/index-ANt8Xo4z.js +0 -6
- package/web-ui/dist/assets/motion-Brxs0UET.js +0 -9
- package/web-ui/dist/assets/query-DPt-uCb6.js +0 -1
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ReaderPage-Sgy0vMZ6.js","assets/query-DbAD_nLW.js","assets/ReaderSettingsContext-DsvLXuaf.js","assets/vendor-DNJ-hWNb.js","assets/motion-DdHBXDWx.js","assets/SearchPage-mPKXZEyq.js","assets/UploadPage-Cob25kDa.js","assets/FilesPage-D6TlldaR.js","assets/CollectionsPage-wbfgYFTw.js","assets/StatusPage-AirpfsGF.js","assets/format-DOJ3IkRX.js","assets/SettingsPage-DXeWwfvd.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a,j as i,u as B,b as H,c as _,Q as Ye,d as Ze}from"./query-DbAD_nLW.js";import{r as et,u as tt,R as nt,a as J,N as st,b as ot,B as rt}from"./vendor-DNJ-hWNb.js";(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const t of document.querySelectorAll('link[rel="modulepreload"]'))e(t);new MutationObserver(t=>{for(const r of t)if(r.type==="childList")for(const l of r.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&e(l)}).observe(document,{childList:!0,subtree:!0});function s(t){const r={};return t.integrity&&(r.integrity=t.integrity),t.referrerPolicy&&(r.referrerPolicy=t.referrerPolicy),t.crossOrigin==="use-credentials"?r.credentials="include":t.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function e(t){if(t.ep)return;t.ep=!0;const r=s(t);fetch(t.href,r)}})();var ee={},le;function at(){if(le)return ee;le=1;var n=et();return ee.createRoot=n.createRoot,ee.hydrateRoot=n.hydrateRoot,ee}var it=at();class lt extends a.Component{constructor(o){super(o),this.state={hasError:!1,error:null}}static getDerivedStateFromError(o){return{hasError:!0,error:o}}componentDidCatch(o,s){console.error("ErrorBoundary caught an error:",o,s)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:i.jsx("div",{className:"min-h-screen flex items-center justify-center p-4",style:{background:"var(--ws-surface-1)"},children:i.jsxs("div",{className:"max-w-md w-full rounded-lg shadow-lg p-6 text-center",style:{background:"var(--ws-surface-raised)"},children:[i.jsx("div",{className:"text-red-500 mb-4",children:i.jsx("svg",{className:"w-16 h-16 mx-auto",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),i.jsx("h1",{className:"text-xl font-semibold mb-2",style:{color:"var(--ws-text)"},children:"Something went wrong"}),i.jsx("p",{className:"mb-4",style:{color:"var(--ws-text-secondary)"},children:"An unexpected error occurred. Please try again."}),this.state.error&&i.jsx("pre",{className:"text-left text-sm p-3 rounded mb-4 overflow-auto max-h-32",style:{background:"var(--ws-surface-1)",color:"var(--ws-text-secondary)"},children:this.state.error.message}),i.jsxs("div",{className:"flex gap-3 justify-center",children:[i.jsx("button",{type:"button",onClick:this.handleRetry,className:"px-4 py-2 text-white rounded-lg transition-colors",style:{background:"var(--ws-accent)"},children:"Try Again"}),i.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"px-4 py-2 rounded-lg transition-colors",style:{background:"var(--ws-surface-2)",color:"var(--ws-text-secondary)"},children:"Reload Page"})]})]})}):this.props.children}}const ce={docId:null,chunkIndex:null,chunkRef:null,source:null},Ne=a.createContext(null);function ct({children:n}){const[o,s]=a.useState(ce),e=a.useCallback(r=>{s({docId:r.docId,chunkIndex:r.chunkIndex??null,chunkRef:r.chunkRef??null,source:r.source})},[]),t=a.useCallback(()=>{s(ce)},[]);return i.jsx(Ne.Provider,{value:{selection:o,select:e,clearSelection:t},children:n})}function V(){const n=a.useContext(Ne);if(!n)throw new Error("useSelection must be used within a SelectionProvider");return n}const de=100;function dt(){const[n,o]=a.useState([]),[s,e]=a.useState(-1),t=a.useRef(s);t.current=s;const r=a.useRef(n);r.current=n;const l=a.useMemo(()=>s>=0&&s<n.length?n[s]??null:null,[n,s]),c=s>0,u=s<n.length-1,m=a.useCallback((y,h)=>{o(v=>{const k=t.current,w=k>=0&&k<v.length?v[k]:null;if(w&&w.docId===y&&w.chunkIndex===h)return v;const x={docId:y,chunkIndex:h??null,timestamp:Date.now()},d=[...v.slice(0,k+1),x];if(d.length>de){const p=d.slice(d.length-de);return e(p.length-1),p}return e(d.length-1),d})},[]),f=a.useCallback(()=>{const y=t.current;if(y<=0)return null;const h=y-1;return e(h),r.current[h]??null},[]),g=a.useCallback(()=>{const y=t.current,h=r.current;if(y>=h.length-1)return null;const v=y+1;return e(v),h[v]??null},[]);return{push:m,goBack:f,goForward:g,canGoBack:c,canGoForward:u,current:l,history:n,currentIndex:s}}function F(n,o){const[s,e]=a.useState(()=>{try{const r=window.localStorage.getItem(n);return r?JSON.parse(r):o}catch{return o}}),t=a.useCallback(r=>{e(l=>{const c=r instanceof Function?r(l):r;try{window.localStorage.setItem(n,JSON.stringify(c))}catch(u){console.warn(`Failed to persist "${n}" to localStorage:`,u)}return c})},[n]);return a.useEffect(()=>{const r=l=>{if(l.key===n&&l.newValue!==null)try{e(JSON.parse(l.newValue))}catch{}};return window.addEventListener("storage",r),()=>window.removeEventListener("storage",r)},[n]),[s,t]}function ue(n){const{storageKey:o,defaultWidth:s,min:e,max:t}=n,[r,l]=F(`ws-panel-${o}`,{width:s,collapsed:!1}),c=a.useCallback(f=>{const g=Math.max(e,Math.min(t,f));l(y=>({...y,width:g}))},[e,t,l]),u=a.useCallback(()=>{l(f=>({...f,collapsed:!f.collapsed}))},[l]),m=a.useCallback(f=>{l(g=>({...g,collapsed:f}))},[l]);return{width:r.width,collapsed:r.collapsed,setWidth:c,toggleCollapsed:u,setCollapsed:m}}function ut(n){const o=a.useRef(n);o.current=n,a.useEffect(()=>{function s(e){if(e.metaKey||e.ctrlKey)switch(e.key){case"[":e.preventDefault(),o.current.onToggleLeftRail?.();break;case"]":e.preventDefault(),o.current.onToggleRightRail?.();break;case"ArrowLeft":e.preventDefault(),o.current.onNavigateBack?.();break;case"ArrowRight":e.preventDefault(),o.current.onNavigateForward?.();break}}return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[])}const Re="/api/v1",ht=3e4,ft=3e5;async function q(n,o,s=ht){const e=new AbortController,t=setTimeout(()=>e.abort(),s);try{const r=await fetch(`${Re}${n}`,{headers:{"Content-Type":"application/json",...o?.headers},...o,signal:e.signal}),l=await r.json();if(!r.ok)throw new Error(l.error||"Request failed");return l}catch(r){throw r instanceof Error&&r.name==="AbortError"?new Error("Request timed out"):r}finally{clearTimeout(t)}}async function Ns(n,o){return(await q("/search",{method:"POST",body:JSON.stringify({query:n,limit:o})})).results}async function Rs(n){const o=new AbortController,s=setTimeout(()=>o.abort(),ft);try{const e=new FormData;e.append("file",n);const t=await fetch(`${Re}/files/upload`,{method:"POST",body:e,signal:o.signal}),r=await t.json();if(!t.ok)throw new Error(r.error||"Upload failed");return r}catch(e){throw e instanceof Error&&e.name==="AbortError"?new Error("Upload timed out"):e}finally{clearTimeout(s)}}async function Ps(n,o,s){return q("/data",{method:"POST",body:JSON.stringify({content:n,metadata:{source:o,format:s}})})}async function Pe(){return(await q("/files")).files}async function gt(n){await q("/files",{method:"DELETE",body:JSON.stringify(n)})}async function Ms(){return q("/status")}async function Me(n){const o=encodeURIComponent(n);return(await q(`/documents/chunks?filePath=${o}`)).chunks}async function mt(n,o,s){const e=new URLSearchParams({filePath:n,chunkIndex:String(o)});return(await q(`/chunks/related?${e.toString()}`)).related.map(r=>({...r,connectionReason:r.explanation?pt(r.explanation):Oe(r.score,r.filePath===n)}))}function pt(n){switch(n.reasonLabel){case"same_doc":return"Same document";case"very_similar":return"Very similar";case"related_topic":return"Related topic";case"loosely_related":return"Loosely related";default:return"Related"}}async function Os(n,o){const s=await q("/chunks/batch-related",{method:"POST",body:JSON.stringify({chunks:n,limit:o})}),e={};for(const[t,r]of Object.entries(s.results)){const[l]=t.split(":");e[t]=r.map(c=>({...c,connectionReason:Oe(c.score,c.filePath===l)}))}return e}function Oe(n,o){return o?"Same document":n<.3?"Very similar":n<.5?"Related topic":"Loosely related"}async function he(n,o,s){await q("/feedback",{method:"POST",body:JSON.stringify({type:n,source:o,target:s})})}const bt={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-8 w-8"};function xt({size:n="md",className:o="",style:s}){return i.jsxs("svg",{className:`animate-spin ${bt[n]} text-current ${o}`,style:s,fill:"none",viewBox:"0 0 24 24",role:"status","aria-label":"Loading",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.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"})]})}const yt={success:{container:"ws-toast--success",icon:"ws-toast-icon--success"},error:{container:"ws-toast--error",icon:"ws-toast-icon--error"},info:{container:"ws-toast--info",icon:"ws-toast-icon--info"}};function wt({toast:n,onDismiss:o}){const s=yt[n.type],[e,t]=a.useState(!1),r=a.useRef(o);r.current=o,a.useEffect(()=>{const c=setTimeout(()=>{t(!0),setTimeout(()=>r.current(n.id),200)},5e3);return()=>clearTimeout(c)},[n.id]);const l=()=>{t(!0),setTimeout(()=>o(n.id),200)};return i.jsxs("div",{className:`ws-toast ${s.container} ${e?"ws-toast--exiting":""}`,role:"alert","aria-live":"polite",children:[i.jsxs("div",{className:`ws-toast-icon ${s.icon}`,children:[n.type==="success"&&i.jsx(kt,{}),n.type==="error"&&i.jsx(vt,{}),n.type==="info"&&i.jsx(St,{})]}),i.jsxs("div",{className:"ws-toast-content",children:[i.jsx("p",{className:"ws-toast-title",children:n.title}),n.message&&i.jsx("p",{className:"ws-toast-message",children:n.message})]}),i.jsx("button",{type:"button",onClick:l,className:"ws-toast-close","aria-label":"Dismiss",children:i.jsx(Ct,{})})]})}function kt(){return i.jsx("svg",{className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function vt(){return i.jsx("svg",{className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function St(){return i.jsx("svg",{className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Ct(){return i.jsx("svg",{className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}function It({toasts:n,onDismiss:o}){return i.jsx("div",{className:"ws-toast-container",children:n.map(s=>i.jsx(wt,{toast:s,onDismiss:o},s.id))})}const De=a.createContext(null);function Et({children:n}){const[o,s]=a.useState([]),e=a.useCallback(r=>{const l=`${Date.now()}-${Math.random().toString(36).slice(2,9)}`;s(c=>[...c,{...r,id:l}])},[]),t=a.useCallback(r=>{s(l=>l.filter(c=>c.id!==r))},[]);return i.jsxs(De.Provider,{value:{addToast:e,removeToast:t},children:[n,i.jsx(It,{toasts:o,onDismiss:t})]})}function K(){const n=a.useContext(De);if(!n)throw new Error("useToast must be used within a ToastProvider");return n}function jt(){const n=B(),{addToast:o}=K(),{data:s=[],isLoading:e,error:t}=H({queryKey:["files"],queryFn:Pe}),r=_({mutationFn:gt,onSuccess:()=>{n.invalidateQueries({queryKey:["files"]}),o({type:"success",title:"File deleted",message:"The file has been removed from the knowledge base."})},onError:l=>{o({type:"error",title:"Failed to delete file",message:l.message})}});return{files:s,isLoading:e,error:t,deleteFile:r.mutate,isDeleting:r.isPending}}function fe(n,o){if(!o)return!0;const s=n.toLowerCase(),e=o.toLowerCase();return s.includes(e)}function Tt(){const[n,o]=a.useState(!1),[s,e]=a.useState(""),[t,r]=a.useState(0),{files:l}=jt(),{select:c}=V(),u=tt(),m=a.useCallback(()=>{o(!0),e(""),r(0)},[]),f=a.useCallback(()=>{o(!1)},[]),g=a.useCallback(()=>{o(k=>(k||(e(""),r(0)),!k))},[]),y=a.useMemo(()=>{const k=l.map(b=>{const d=b.filePath.split("/").pop()||b.filePath;return{id:`doc:${b.filePath}`,label:d,description:b.filePath,icon:"D",category:"document",onSelect:()=>{c({docId:b.filePath,source:"command-palette"}),u(`/reader?doc=${encodeURIComponent(b.filePath)}`)}}}),w=[{id:"nav:search",label:"Search",description:"Go to search page",icon:"S",category:"navigation",onSelect:()=>u("/")},{id:"nav:upload",label:"Upload",description:"Go to upload page",icon:"U",category:"navigation",onSelect:()=>u("/upload")},{id:"nav:files",label:"Files",description:"Go to files page",icon:"F",category:"navigation",onSelect:()=>u("/files")},{id:"nav:collections",label:"Collections",description:"Go to collections page",icon:"C",category:"navigation",onSelect:()=>u("/collections")},{id:"nav:status",label:"Status",description:"Go to status page",icon:"T",category:"navigation",onSelect:()=>u("/status")},{id:"nav:settings",label:"Settings",description:"Go to settings page",icon:"G",category:"navigation",onSelect:()=>u("/settings")}],x=[{id:"action:toggle-left-rail",label:"Toggle left rail",description:"Show or hide the left sidebar",icon:"L",category:"action",onSelect:()=>{window.dispatchEvent(new CustomEvent("ws:toggle-left-rail"))}},{id:"action:toggle-right-rail",label:"Toggle right rail",description:"Show or hide the right sidebar",icon:"R",category:"action",onSelect:()=>{window.dispatchEvent(new CustomEvent("ws:toggle-right-rail"))}}];return[...k,...w,...x]},[l,c,u]),h=a.useMemo(()=>s?y.filter(k=>fe(k.label,s)||k.description&&fe(k.description,s)):y,[y,s]);a.useEffect(()=>{r(k=>h.length===0?0:Math.min(k,h.length-1))},[h.length]);const v=a.useCallback(()=>{const k=h[t];k&&(k.onSelect(),f())},[h,t,f]);return a.useEffect(()=>{function k(w){(w.metaKey||w.ctrlKey)&&w.key==="k"&&(w.preventDefault(),g())}return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[g]),{isOpen:n,open:m,close:f,toggle:g,query:s,setQuery:e,results:h,selectedIndex:t,setSelectedIndex:r,executeSelected:v}}function At(n){switch(n){case"document":return"Documents";case"navigation":return"Navigation";case"action":return"Actions"}}function Nt(){const{isOpen:n,close:o,query:s,setQuery:e,results:t,selectedIndex:r,setSelectedIndex:l,executeSelected:c}=Tt(),u=a.useRef(null),m=a.useRef(null);a.useEffect(()=>{if(n){const h=requestAnimationFrame(()=>{u.current?.focus()});return()=>cancelAnimationFrame(h)}},[n]),a.useEffect(()=>{if(!n||!m.current)return;const h=m.current.querySelector('[data-selected="true"]');h&&h.scrollIntoView({block:"nearest"})},[r,n]);function f(h){switch(h.key){case"ArrowDown":h.preventDefault(),l(Math.min(r+1,t.length-1));break;case"ArrowUp":h.preventDefault(),l(Math.max(r-1,0));break;case"Enter":h.preventDefault(),c();break;case"Escape":h.preventDefault(),o();break}}if(!n)return null;const g=[],y=new Set;for(let h=0;h<t.length;h++){const v=t[h];y.has(v.category)||(y.add(v.category),g.push({category:v.category,items:[]})),g.find(w=>w.category===v.category)?.items.push({action:v,globalIndex:h})}return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"ws-command-palette-backdrop",onClick:o,onKeyDown:h=>{h.key==="Escape"&&o()}}),i.jsxs("div",{className:"ws-command-palette",role:"dialog","aria-modal":"true","aria-label":"Command palette",onKeyDown:f,children:[i.jsx("input",{ref:u,className:"ws-command-palette-input ws-input",type:"text",placeholder:"Search documents, pages, actions...",value:s,onChange:h=>e(h.target.value),"aria-label":"Command palette search","aria-controls":"command-palette-results","aria-activedescendant":t[r]?`command-palette-item-${t[r].id}`:void 0,role:"combobox","aria-expanded":"true","aria-autocomplete":"list"}),i.jsxs("div",{ref:m,id:"command-palette-results",className:"ws-command-palette-results",role:"listbox","aria-label":"Command palette results",children:[t.length===0&&i.jsx("div",{className:"ws-command-palette-empty",children:"No results found"}),g.map(h=>i.jsxs("div",{className:"ws-command-palette-group",children:[i.jsx("div",{className:"ws-command-palette-category",children:At(h.category)}),h.items.map(({action:v,globalIndex:k})=>i.jsxs("button",{id:`command-palette-item-${v.id}`,className:`ws-command-palette-item ${k===r?"ws-command-palette-item--selected":""}`,role:"option","aria-selected":k===r,"data-selected":k===r,onClick:()=>{l(k),v.onSelect(),o()},onMouseEnter:()=>l(k),type:"button",children:[i.jsx("span",{className:"ws-command-palette-item-icon",children:v.icon}),i.jsxs("span",{className:"ws-command-palette-item-content",children:[i.jsx("span",{className:"ws-command-palette-item-label",children:v.label}),v.description&&i.jsx("span",{className:"ws-command-palette-item-description",children:v.description})]})]},v.id))]},h.category))]}),i.jsxs("div",{className:"ws-command-palette-footer",children:[i.jsxs("span",{className:"ws-command-palette-hint",children:[i.jsx("kbd",{children:"↑↓"})," navigate"]}),i.jsxs("span",{className:"ws-command-palette-hint",children:[i.jsx("kbd",{children:"Enter"})," select"]}),i.jsxs("span",{className:"ws-command-palette-hint",children:[i.jsx("kbd",{children:"Esc"})," close"]})]})]})]})}const Rt="modulepreload",Pt=function(n){return"/"+n},ge={},G=function(o,s,e){let t=Promise.resolve();if(s&&s.length>0){let u=function(m){return Promise.all(m.map(f=>Promise.resolve(f).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");t=u(s.map(m=>{if(m=Pt(m),m in ge)return;ge[m]=!0;const f=m.endsWith(".css"),g=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${g}`))return;const y=document.createElement("link");if(y.rel=f?"stylesheet":Rt,f||(y.as="script"),y.crossOrigin="",y.href=m,c&&y.setAttribute("nonce",c),document.head.appendChild(y),f)return new Promise((h,v)=>{y.addEventListener("load",h),y.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${m}`)))})}))}function r(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return t.then(l=>{for(const c of l||[])c.status==="rejected"&&r(c.reason);return o().catch(r)})},me=8;function pe(){const n=crypto.randomUUID();return{tabs:[{tabId:n,kind:"search",title:"Search",scrollTop:0,lastActiveAt:Date.now(),pinned:!0}],activeTabId:n}}function be(n,o){const s=n.filter(t=>!t.pinned&&t.tabId!==o);if(s.length===0)return n;let e=s[0];for(const t of s)t.lastActiveAt<e.lastActiveAt&&(e=t);return n.filter(t=>t.tabId!==e.tabId)}const Le=a.createContext(null);function Mt({dbId:n,children:o}){const s=`rag-vault-tabs-v1-${n}`,[e,t]=F(s,pe()),r=a.useCallback((h,v,k)=>{t(w=>{const x=w.tabs.find(p=>p.kind==="doc"&&p.docId===h);if(x)return{...w,activeTabId:x.tabId,tabs:w.tabs.map(p=>p.tabId===x.tabId?{...p,lastActiveAt:Date.now()}:p)};const b={tabId:crypto.randomUUID(),kind:"doc",docId:h,chunkRef:k,title:v,scrollTop:0,lastActiveAt:Date.now(),pinned:!1};let d=[...w.tabs,b];return d.length>me&&(d=be(d,b.tabId)),{tabs:d,activeTabId:b.tabId}})},[t]),l=a.useCallback((h,v)=>{t(k=>{const w=k.tabs.find(d=>d.kind===h);if(w)return{...k,activeTabId:w.tabId,tabs:k.tabs.map(d=>d.tabId===w.tabId?{...d,lastActiveAt:Date.now()}:d)};const x={tabId:crypto.randomUUID(),kind:h,title:v,scrollTop:0,lastActiveAt:Date.now(),pinned:!1};let b=[...k.tabs,x];return b.length>me&&(b=be(b,x.tabId)),{tabs:b,activeTabId:x.tabId}})},[t]),c=a.useCallback(h=>{t(v=>{const k=v.tabs.findIndex(b=>b.tabId===h);if(k===-1)return v;const w=v.tabs.filter(b=>b.tabId!==h);if(w.length===0)return pe();let x=v.activeTabId;if(v.activeTabId===h){const b=Math.min(k,w.length-1);x=w[b].tabId}return{tabs:w,activeTabId:x}})},[t]),u=a.useCallback(h=>{t(v=>({...v,activeTabId:h,tabs:v.tabs.map(k=>k.tabId===h?{...k,lastActiveAt:Date.now()}:k)}))},[t]),m=a.useCallback((h,v)=>{t(k=>({...k,tabs:k.tabs.map(w=>w.tabId===h?{...w,scrollTop:v}:w)}))},[t]),f=a.useCallback((h,v)=>{t(k=>({...k,tabs:k.tabs.map(w=>w.tabId===h?{...w,pinned:v}:w)}))},[t]),g=a.useMemo(()=>e.tabs.find(h=>h.tabId===e.activeTabId),[e.tabs,e.activeTabId]),y=a.useMemo(()=>({tabs:e.tabs,activeTabId:e.activeTabId,activeTab:g,openDoc:r,openPage:l,closeTab:c,setActiveTab:u,updateTabScroll:m,pinTab:f}),[e.tabs,e.activeTabId,g,r,l,c,u,m,f]);return i.jsx(Le.Provider,{value:y,children:o})}function Ot(){const n=a.useContext(Le);if(!n)throw new Error("useTabs must be used within a TabsProvider");return n}const Dt=a.forwardRef(({variant:n="default",size:o="md",className:s="",children:e,...t},r)=>i.jsx("button",{ref:r,"data-variant":n,"data-size":o,className:`ws-button ${s}`,...t,children:e}));Dt.displayName="WsButton";const Lt=a.forwardRef(({error:n,className:o="",...s},e)=>i.jsx("input",{ref:e,"data-error":n||void 0,className:`ws-input ${o}`,...s}));Lt.displayName="WsInput";const Ft=a.forwardRef(({error:n,className:o="",children:s,...e},t)=>i.jsx("select",{ref:t,"data-error":n||void 0,className:`ws-select ${o}`,...e,children:s}));Ft.displayName="WsSelect";function Fe({tabs:n,activeId:o,onSelect:s,onClose:e,variant:t="underline",className:r=""}){const l=a.useRef(null),c=u=>{const m=l.current?.querySelectorAll('[role="tab"]');if(!m?.length)return;const f=Array.from(m).indexOf(document.activeElement);let g=f;if(u.key==="ArrowRight"?(u.preventDefault(),g=f+1>=m.length?0:f+1):u.key==="ArrowLeft"&&(u.preventDefault(),g=f-1<0?m.length-1:f-1),g!==f){const y=m[g];if(y){y.focus();const h=y.dataset.tabId;h&&s(h)}}};return i.jsx("div",{ref:l,role:"tablist",className:`ws-tabs ws-tabs--${t} ${r}`,onKeyDown:c,children:n.map(u=>{const m=u.id===o;return i.jsxs("button",{role:"tab",type:"button","aria-selected":m,tabIndex:m?0:-1,"data-tab-id":u.id,className:"ws-tab",onClick:()=>s(u.id),children:[u.icon&&i.jsx("span",{className:"ws-tab-icon",children:u.icon}),u.label,u.badge!==void 0&&i.jsx("span",{className:"ws-tab-badge",children:u.badge}),u.closeable&&!u.pinned&&i.jsx("span",{role:"button",tabIndex:-1,className:"ws-tab-close",onClick:f=>{f.stopPropagation(),e?.(u.id)},onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.stopPropagation(),e?.(u.id))},children:"x"})]},u.id)})})}function oe({variant:n="default",count:o,children:s,className:e="",...t}){return i.jsxs("span",{"data-variant":n,className:`ws-badge ${e}`,...t,children:[s,o!==void 0&&i.jsx("span",{className:"ws-badge-count",children:o})]})}function $t({content:n,side:o="top",delay:s=300,children:e}){const[t,r]=a.useState(!1),l=a.useRef(null),c=a.useCallback(()=>{l.current=setTimeout(()=>r(!0),s)},[s]),u=a.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),r(!1)},[]);return a.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]),i.jsxs("span",{className:"ws-tooltip-anchor",onMouseEnter:c,onMouseLeave:u,onFocus:c,onBlur:u,children:[e,t&&i.jsx("span",{className:`ws-tooltip ws-tooltip--${o}`,role:"tooltip",children:n})]})}function _t(){const{tabs:n,activeTabId:o,setActiveTab:s,closeTab:e}=Ot(),t=n.map(r=>({id:r.tabId,label:r.title,closeable:!r.pinned,pinned:r.pinned}));return i.jsx("div",{className:"ws-tab-bar",children:i.jsx(Fe,{tabs:t,activeId:o,onSelect:s,onClose:e,variant:"pill"})})}const Kt=a.lazy(()=>G(()=>import("./ReaderPage-Sgy0vMZ6.js"),__vite__mapDeps([0,1,2,3,4])).then(n=>({default:n.ReaderPage}))),zt=a.lazy(()=>G(()=>import("./SearchPage-mPKXZEyq.js"),__vite__mapDeps([5,1,3])).then(n=>({default:n.SearchPage}))),Wt=a.lazy(()=>G(()=>import("./UploadPage-Cob25kDa.js"),__vite__mapDeps([6,1,3])).then(n=>({default:n.UploadPage}))),Bt=a.lazy(()=>G(()=>import("./FilesPage-D6TlldaR.js"),__vite__mapDeps([7,1,3])).then(n=>({default:n.FilesPage}))),qt=a.lazy(()=>G(()=>import("./CollectionsPage-wbfgYFTw.js"),__vite__mapDeps([8,1,4,3])).then(n=>({default:n.CollectionsPage}))),Ut=a.lazy(()=>G(()=>import("./StatusPage-AirpfsGF.js"),__vite__mapDeps([9,1,10,3])).then(n=>({default:n.StatusPage}))),Ht=a.lazy(()=>G(()=>import("./SettingsPage-DXeWwfvd.js"),__vite__mapDeps([11,1,10,4,3])).then(n=>({default:n.SettingsPage}))),Vt=a.lazy(()=>G(()=>import("./ReaderSettingsContext-DsvLXuaf.js"),__vite__mapDeps([2,1,3])).then(n=>({default:n.ReaderSettingsProvider})));function xe(){return i.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:i.jsx(xt,{})})}function Gt(){return i.jsxs("div",{className:"ws-center-pane",children:[i.jsx(_t,{}),i.jsx("div",{className:"ws-center-content",children:i.jsx(a.Suspense,{fallback:i.jsx(xe,{}),children:i.jsxs(nt,{children:[i.jsx(J,{path:"/",element:i.jsx(zt,{})}),i.jsx(J,{path:"/read",element:i.jsx(a.Suspense,{fallback:i.jsx(xe,{}),children:i.jsx(Vt,{children:i.jsx(Kt,{})})})}),i.jsx(J,{path:"/upload",element:i.jsx(Wt,{})}),i.jsx(J,{path:"/files",element:i.jsx(Bt,{})}),i.jsx(J,{path:"/collections",element:i.jsx(qt,{})}),i.jsx(J,{path:"/status",element:i.jsx(Ut,{})}),i.jsx(J,{path:"/settings",element:i.jsx(Ht,{})})]})})})]})}const Jt={theme:"system",lastBrowsedPath:"/",showHiddenFiles:!1,statsRefreshInterval:0},$e=a.createContext(null);function Qt(){return typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Xt({children:n}){const[o,s]=F("rag-vault-preferences",Jt),e=o.theme==="system"?Qt():o.theme;a.useEffect(()=>{const u=document.documentElement;e==="dark"?u.classList.add("dark"):u.classList.remove("dark")},[e]),a.useEffect(()=>{if(o.theme!=="system")return;const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=document.documentElement;u.matches?f.classList.add("dark"):f.classList.remove("dark")};return u.addEventListener("change",m),()=>u.removeEventListener("change",m)},[o.theme]);const t=a.useCallback(u=>{s(m=>({...m,theme:u}))},[s]),r=a.useCallback(u=>{s(m=>({...m,lastBrowsedPath:u}))},[s]),l=a.useCallback(u=>{s(m=>({...m,showHiddenFiles:u}))},[s]),c=a.useCallback(u=>{s(m=>({...m,statsRefreshInterval:u}))},[s]);return i.jsx($e.Provider,{value:{preferences:o,setTheme:t,setLastBrowsedPath:r,setShowHiddenFiles:l,setStatsRefreshInterval:c,effectiveTheme:e},children:n})}function Ds(){const n=a.useContext($e);if(!n)throw new Error("usePreferences must be used within a PreferencesProvider");return n}const Yt="/api/v1/config",Zt=3e4;async function D(n,o,s=Zt){const e=new AbortController,t=setTimeout(()=>e.abort(),s);try{const r=await fetch(`${Yt}${n}`,{headers:{"Content-Type":"application/json",...o?.headers},...o,signal:e.signal}),l=await r.json();if(!r.ok)throw new Error(l.error||"Request failed");return l}catch(r){throw r instanceof Error&&r.name==="AbortError"?new Error("Request timed out"):r}finally{clearTimeout(t)}}async function en(){return D("/current")}async function tn(){return(await D("/databases")).databases}async function nn(n){return(await D("/databases/switch",{method:"POST",body:JSON.stringify({dbPath:n})})).config}async function sn(n,o,s){return(await D("/databases/create",{method:"POST",body:JSON.stringify({dbPath:n,name:o,modelName:s})})).config}async function on(n){return(await D("/databases/scan",{method:"POST",body:JSON.stringify({scanPath:n})})).databases}async function rn(n,o=!1){return(await D("/databases",{method:"DELETE",body:JSON.stringify({dbPath:n,deleteFiles:o})})).databases}async function an(){return D("/allowed-roots")}async function ln(n){return D("/allowed-roots",{method:"POST",body:JSON.stringify({path:n})})}async function cn(n){return D("/allowed-roots",{method:"DELETE",body:JSON.stringify({path:n})})}async function dn(n,o=!1){const s=new URLSearchParams({path:n});return o&&s.set("showHidden","true"),D(`/browse?${s.toString()}`)}async function un(){return(await D("/models")).models}async function hn(){return D("/export")}async function fn(n){return D("/import",{method:"POST",body:JSON.stringify({config:n})})}async function gn(){return(await D("/hybrid-weight")).weight}async function mn(n){await D("/hybrid-weight",{method:"PUT",body:JSON.stringify({weight:n})})}function pn(n=0){const{data:o,isLoading:s,error:e,refetch:t,isFetching:r}=H({queryKey:["config","current"],queryFn:en,refetchInterval:n>0?n:!1});return{config:o,isLoading:s,error:e,refetch:t,isFetching:r}}function Ls(){const{data:n,isLoading:o,error:s,refetch:e}=H({queryKey:["config","databases"],queryFn:tn});return{databases:n||[],isLoading:o,error:s,refetch:e}}function Fs(){const n=B(),{addToast:o}=K(),s=_({mutationFn:e=>nn(e),onSuccess:(e,t)=>{n.invalidateQueries({queryKey:["config"]}),n.invalidateQueries({queryKey:["files"]}),n.invalidateQueries({queryKey:["status"]}),o({type:"success",title:"Database switched",message:`Now using ${t.split("/").pop()||t}`})},onError:e=>{o({type:"error",title:"Failed to switch database",message:e.message})}});return{switchDatabase:s.mutate,switchDatabaseAsync:s.mutateAsync,isLoading:s.isPending,error:s.error,isSuccess:s.isSuccess}}function $s(){const n=B(),{addToast:o}=K(),s=_({mutationFn:({dbPath:e,name:t,modelName:r})=>sn(e,t,r),onSuccess:(e,t)=>{n.invalidateQueries({queryKey:["config"]}),n.invalidateQueries({queryKey:["files"]}),n.invalidateQueries({queryKey:["status"]}),o({type:"success",title:"Database created",message:`Created and switched to ${t.dbPath.split("/").pop()||t.dbPath}`})},onError:e=>{o({type:"error",title:"Failed to create database",message:e.message})}});return{createDatabase:s.mutate,createDatabaseAsync:s.mutateAsync,isLoading:s.isPending,error:s.error,isSuccess:s.isSuccess}}function _s(){const{addToast:n}=K(),o=_({mutationFn:s=>on(s),onError:s=>{n({type:"error",title:"Scan failed",message:s.message})}});return{scan:o.mutate,scanAsync:o.mutateAsync,isLoading:o.isPending,error:o.error,data:o.data,reset:o.reset}}function Ks(){const n=B(),{addToast:o}=K(),s=_({mutationFn:({dbPath:e,deleteFiles:t})=>rn(e,t),onSuccess:(e,t)=>{n.invalidateQueries({queryKey:["config","databases"]});const r=t.dbPath.split("/").pop()||t.dbPath;o({type:"success",title:"Database removed",message:t.deleteFiles?`Deleted ${r} and its files`:`Removed ${r} from list`})},onError:e=>{o({type:"error",title:"Failed to delete database",message:e.message})}});return{deleteDatabase:s.mutate,deleteDatabaseAsync:s.mutateAsync,isLoading:s.isPending,error:s.error}}function zs(){const{data:n,isLoading:o,error:s,refetch:e}=H({queryKey:["config","allowed-roots"],queryFn:an});return{data:n,isLoading:o,error:s,refetch:e}}function Ws(){const n=B(),{addToast:o}=K(),s=_({mutationFn:e=>ln(e),onSuccess:()=>{n.invalidateQueries({queryKey:["config","allowed-roots"]}),o({type:"success",title:"Root added",message:"Allowed root added successfully"})},onError:e=>{o({type:"error",title:"Failed to add root",message:e.message})}});return{addRoot:s.mutate,addRootAsync:s.mutateAsync,isLoading:s.isPending,error:s.error}}function Bs(){const n=B(),{addToast:o}=K(),s=_({mutationFn:e=>cn(e),onSuccess:()=>{n.invalidateQueries({queryKey:["config","allowed-roots"]}),o({type:"success",title:"Root removed",message:"Allowed root removed successfully"})},onError:e=>{o({type:"error",title:"Failed to remove root",message:e.message})}});return{removeRoot:s.mutate,removeRootAsync:s.mutateAsync,isLoading:s.isPending,error:s.error}}function qs(){const{addToast:n}=K(),o=_({mutationFn:({path:t,showHidden:r=!1})=>dn(t,r),onError:t=>{n({type:"error",title:"Failed to browse directory",message:t.message})}}),s=a.useCallback((t,r=!1)=>o.mutate({path:t,showHidden:r}),[o.mutate]),e=a.useCallback((t,r=!1)=>o.mutateAsync({path:t,showHidden:r}),[o.mutateAsync]);return{browse:s,browseAsync:e,isLoading:o.isPending,error:o.error,data:o.data,reset:o.reset}}function Us(){const{data:n,isLoading:o,error:s}=H({queryKey:["config","models"],queryFn:un});return{models:n||[],isLoading:o,error:s}}function Hs(){const{addToast:n}=K(),o=_({mutationFn:hn,onSuccess:()=>{n({type:"success",title:"Configuration exported",message:"Download should begin automatically"})},onError:s=>{n({type:"error",title:"Failed to export configuration",message:s.message})}});return{exportConfig:o.mutate,exportConfigAsync:o.mutateAsync,isLoading:o.isPending,error:o.error,data:o.data}}function Vs(){const n=B(),{addToast:o}=K(),s=_({mutationFn:e=>fn(e),onSuccess:()=>{n.invalidateQueries({queryKey:["config","allowed-roots"]}),o({type:"success",title:"Configuration imported",message:"Settings have been restored"})},onError:e=>{o({type:"error",title:"Failed to import configuration",message:e.message})}});return{importConfig:s.mutate,importConfigAsync:s.mutateAsync,isLoading:s.isPending,error:s.error}}function Gs(){const{data:n,isLoading:o,error:s,refetch:e}=H({queryKey:["config","hybrid-weight"],queryFn:gn});return{weight:n??.6,isLoading:o,error:s,refetch:e}}function Js(){const n=B(),{addToast:o}=K(),s=_({mutationFn:e=>mn(e),onSuccess:()=>{n.invalidateQueries({queryKey:["config","hybrid-weight"]}),o({type:"success",title:"Search weight updated",message:"Hybrid search weight has been adjusted"})},onError:e=>{o({type:"error",title:"Failed to update search weight",message:e.message})}});return{setWeight:s.mutate,setWeightAsync:s.mutateAsync,isLoading:s.isPending,error:s.error}}function bn(n){const{data:o=[],isLoading:s,error:e,refetch:t}=H({queryKey:["documentChunks",n],queryFn:()=>n?Me(n):Promise.resolve([]),enabled:!!n,staleTime:3e5});return{chunks:o,isLoading:s,error:e,refetch:t}}function _e(n,o,s){const{data:e=[],isLoading:t,error:r,refetch:l}=H({queryKey:["relatedChunks",n,o,s],queryFn:()=>n&&o!==null?mt(n,o):Promise.resolve([]),enabled:!!n&&o!==null,staleTime:3e5});return{related:e,isLoading:t,error:r,refetch:l}}function te(){return crypto.randomUUID()}async function ye(n){const s=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("")}function Q(n,o){return n.fingerprint&&o.fingerprint?n.fingerprint===o.fingerprint:n.filePath===o.filePath&&n.chunkIndex===o.chunkIndex}const xn={version:1,vaultId:"",pins:[],trails:[],bookmarks:[]},Ke=a.createContext(null);function yn({children:n,vaultId:o="default"}){const s=`rag-vault-links-v1-${o}`,[e,t]=F(s,{...xn,vaultId:o}),r=a.useCallback((R,T,C,I,N)=>{const j={id:te(),createdAt:new Date().toISOString(),sourceKey:R,sourceText:C.slice(0,200),sourceFingerprint:"",targetKey:T,targetText:I.slice(0,200),targetFingerprint:"",label:N?.label,autoGenerated:N?.autoGenerated??!1,originalScore:N?.originalScore};return Promise.all([ye(C),ye(I)]).then(([P,O])=>{t($=>({...$,pins:$.pins.map(Y=>Y.id===j.id?{...Y,sourceFingerprint:P,targetFingerprint:O}:Y)})),he("pin",{...R,fingerprint:P},{...T,fingerprint:O}).catch(()=>{})}).catch(P=>{console.warn("Failed to hash text for pin fingerprints, removing incomplete pin:",P),t(O=>({...O,pins:O.pins.filter($=>$.id!==j.id)}))}),t(P=>({...P,pins:[...P.pins,j]})),j},[t]),l=a.useCallback(R=>{const T=e.pins.find(C=>C.id===R);t(C=>({...C,pins:C.pins.filter(I=>I.id!==R)})),T&&he("unpin",{...T.sourceKey,fingerprint:T.sourceFingerprint},{...T.targetKey,fingerprint:T.targetFingerprint}).catch(()=>{})},[t,e.pins]),c=a.useCallback((R,T)=>{t(C=>({...C,pins:C.pins.map(I=>I.id===R?{...I,label:T}:I)}))},[t]),u=a.useCallback(R=>e.pins.filter(T=>Q(T.sourceKey,R)),[e.pins]),m=a.useCallback(R=>e.pins.filter(T=>Q(T.targetKey,R)),[e.pins]),f=a.useCallback((R,T)=>e.pins.some(C=>Q(C.sourceKey,R)&&Q(C.targetKey,T)),[e.pins]),[g,y]=F(`rag-vault-current-trail-${o}`,null),h=a.useCallback(()=>{const R={id:te(),name:"",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),steps:[]};y(R)},[y]),v=a.useCallback((R,T)=>{y(C=>{if(!C)return{id:te(),name:"",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),steps:[{chunkKey:R,visitedAt:new Date().toISOString(),connectionReason:T}]};const I=C.steps[C.steps.length-1];return I&&Q(I.chunkKey,R)?C:{...C,updatedAt:new Date().toISOString(),steps:[...C.steps,{chunkKey:R,visitedAt:new Date().toISOString(),connectionReason:T}]}})},[y]),k=a.useCallback(R=>{if(!g)throw new Error("No current trail to save");const T={...g,name:R,updatedAt:new Date().toISOString()};return t(C=>({...C,trails:[...C.trails,T]})),y(null),T},[g,t,y]),w=a.useCallback(R=>{const T=e.trails.find(C=>C.id===R);return T&&y({...T}),T||null},[e.trails,y]),x=a.useCallback(R=>{t(T=>({...T,trails:T.trails.filter(C=>C.id!==R)}))},[t]),b=a.useCallback(()=>{y(null)},[y]),d=a.useCallback((R,T)=>{const C={id:te(),chunkKey:R,note:T,createdAt:new Date().toISOString()};return t(I=>({...I,bookmarks:[...I.bookmarks||[],C]})),C},[t]),p=a.useCallback(R=>{t(T=>({...T,bookmarks:(T.bookmarks||[]).filter(C=>C.id!==R)}))},[t]),S=a.useCallback((R,T)=>{t(C=>({...C,bookmarks:(C.bookmarks||[]).map(I=>I.id===R?{...I,note:T}:I)}))},[t]),E=a.useCallback(R=>(e.bookmarks||[]).filter(T=>T.chunkKey.filePath===R).sort((T,C)=>T.chunkKey.chunkIndex-C.chunkKey.chunkIndex),[e.bookmarks]),A=a.useCallback(R=>(e.bookmarks||[]).some(T=>Q(T.chunkKey,R)),[e.bookmarks]),M=a.useCallback(R=>{const T=(e.bookmarks||[]).find(C=>Q(C.chunkKey,R));return T?(p(T.id),!1):(d(R),!0)},[e.bookmarks,d,p]),z=a.useCallback(()=>JSON.stringify(e,null,2),[e]),W=a.useCallback(R=>{const T=[];let C=0;try{const I=JSON.parse(R);if(I.version!==1)return T.push(`Unsupported version: ${I.version}`),{imported:C,errors:T};if(Array.isArray(I.pins))for(const N of I.pins)N.id&&N.sourceKey&&N.targetKey&&!e.pins.some(j=>j.id===N.id)&&(t(j=>({...j,pins:[...j.pins,N]})),C++);if(Array.isArray(I.trails))for(const N of I.trails)N.id&&N.name&&Array.isArray(N.steps)&&!e.trails.some(j=>j.id===N.id)&&(t(j=>({...j,trails:[...j.trails,N]})),C++);if(Array.isArray(I.bookmarks))for(const N of I.bookmarks)N.id&&N.chunkKey&&!(e.bookmarks||[]).some(j=>j.id===N.id)&&(t(j=>({...j,bookmarks:[...j.bookmarks||[],N]})),C++)}catch(I){T.push(`Invalid JSON: ${I.message}`)}return{imported:C,errors:T}},[e,t]),U=a.useMemo(()=>({pins:e.pins,createPin:r,deletePin:l,updatePinLabel:c,getPinsFromChunk:u,getBacklinks:m,isPinned:f,trails:e.trails,currentTrail:g,startNewTrail:h,addToTrail:v,saveTrail:k,loadTrail:w,deleteTrail:x,clearCurrentTrail:b,bookmarks:e.bookmarks||[],createBookmark:d,deleteBookmark:p,updateBookmarkNote:S,getBookmarksForDocument:E,isBookmarked:A,toggleBookmark:M,exportLinks:z,importLinks:W}),[e.pins,e.trails,e.bookmarks,r,l,c,u,m,f,g,h,v,k,w,x,b,d,p,S,E,A,M,z,W]);return i.jsx(Ke.Provider,{value:U,children:n})}function ze(){const n=a.useContext(Ke);if(!n)throw new Error("useLinks must be used within a LinksProvider");return n}function wn(){const n=ze(),o=a.useMemo(()=>{const e=new Set;for(const t of n.pins)e.add(`${t.targetKey.filePath}:${t.targetKey.chunkIndex}`);return e},[n.pins]),s=a.useCallback((e,t,r,l,c)=>{const u=n.pins.find(m=>m.sourceKey.filePath===e.filePath&&m.sourceKey.chunkIndex===e.chunkIndex&&m.targetKey.filePath===t.filePath&&m.targetKey.chunkIndex===t.chunkIndex);u?n.deletePin(u.id):n.createPin(e,t,r,l,{autoGenerated:!1,originalScore:c})},[n]);return{pins:n.pins,pinnedChunkKeys:o,createPin:n.createPin,deletePin:n.deletePin,updatePinLabel:n.updatePinLabel,isPinned:n.isPinned,togglePin:s,getPinsFromChunk:n.getPinsFromChunk}}function kn(n,o){const s=ze(),e=a.useMemo(()=>!n||o===null?[]:s.getBacklinks({filePath:n,chunkIndex:o}),[s,n,o]);return{backlinks:e,hasBacklinks:e.length>0,backlinkCount:e.length}}const vn=/^(#{1,6})\s+(.+)$/m,Sn=/^([A-Z][A-Z0-9\s]{4,79})$/m,Cn=/^(\d+(?:\.\d+)*)\s+(.+)$/m;function In(n){const o=n.match(vn);if(o){const[,t,r]=o;if(t&&r)return{text:r.trim(),level:t.length,type:"markdown"}}const s=n.match(Cn);if(s){const[,t,r]=s;if(t&&r){const l=t.split(".").length;return{text:`${t} ${r.trim()}`,level:l,type:"numbered"}}}const e=n.trim();if(e.length>=5&&e.length<=80){const t=e.match(Sn);if(t?.[1]){const r=t[1].match(/[A-Z]/g);if(r&&r.length>=3)return{text:t[1].trim(),level:1,type:"allcaps"}}}return null}function En(n,o){const s=[],e=n.split(`
|
|
3
|
+
`);for(const t of e){const r=In(t);r&&s.push({...r,chunkIndex:o,text:r.text.length>80?`${r.text.slice(0,77)}...`:r.text})}return s}function jn(n){const o=Math.max(1,Math.floor(n.length/10));return n.filter((s,e)=>e%o===0).map((s,e)=>({id:`fallback-${s.chunkIndex}`,text:`Section ${e+1}`,level:1,chunkIndex:s.chunkIndex,type:"fallback"}))}function Tn({chunks:n,minHeadings:o=2}){return a.useMemo(()=>{if(n.length===0)return{entries:[],hasHeadings:!1,isFallback:!1};const e=[];for(const l of n){const c=En(l.text,l.chunkIndex);e.push(...c)}const t=[];for(const l of e){const c=t[t.length-1];(!c||c.text!==l.text||c.chunkIndex!==l.chunkIndex)&&t.push(l)}return t.length<o?{entries:jn(n),hasHeadings:!1,isFallback:!0}:{entries:t.map((l,c)=>({...l,id:`toc-${c}-${l.chunkIndex}`})),hasHeadings:!0,isFallback:!1}},[n,o])}function we(){return crypto.randomUUID()}function An(n,o){return n.filePath===o.filePath&&n.chunkIndex===o.chunkIndex}const Nn={version:1,vaultId:"",highlights:[],annotations:[]},We=a.createContext(null);function Rn({children:n,vaultId:o="default"}){const s=`rag-vault-annotations-v1-${o}`,[e,t]=F(s,{...Nn,vaultId:o}),r=a.useCallback((w,x,b,d,p,S)=>{const E={id:we(),chunkKey:w,range:x,text:b,contextBefore:d.slice(-30),contextAfter:p.slice(0,30),color:S,createdAt:new Date().toISOString()};return t(A=>({...A,highlights:[...A.highlights,E]})),E},[t]),l=a.useCallback(w=>{t(x=>({...x,highlights:x.highlights.filter(b=>b.id!==w),annotations:x.annotations.filter(b=>b.highlightId!==w)}))},[t]),c=a.useCallback((w,x)=>{t(b=>({...b,highlights:b.highlights.map(d=>d.id===w?{...d,color:x}:d)}))},[t]),u=a.useCallback(w=>e.highlights.filter(x=>An(x.chunkKey,w)).sort((x,b)=>x.range.startOffset-b.range.startOffset),[e.highlights]),m=a.useCallback((w,x)=>{const b={id:we(),highlightId:w,note:x,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t(d=>({...d,annotations:[...d.annotations,b]})),b},[t]),f=a.useCallback((w,x)=>{t(b=>({...b,annotations:b.annotations.map(d=>d.id===w?{...d,note:x,updatedAt:new Date().toISOString()}:d)}))},[t]),g=a.useCallback(w=>{t(x=>({...x,annotations:x.annotations.filter(b=>b.id!==w)}))},[t]),y=a.useCallback(w=>e.annotations.find(x=>x.highlightId===w),[e.annotations]),h=a.useCallback(()=>JSON.stringify(e,null,2),[e]),v=a.useCallback(w=>{const x=[];let b=0;try{const d=JSON.parse(w);if(d.version!==1)return x.push(`Unsupported version: ${d.version}`),{imported:b,errors:x};if(Array.isArray(d.highlights))for(const p of d.highlights)p.id&&p.chunkKey&&p.range&&!e.highlights.some(S=>S.id===p.id)&&(t(S=>({...S,highlights:[...S.highlights,p]})),b++);if(Array.isArray(d.annotations))for(const p of d.annotations)p.id&&p.highlightId&&!e.annotations.some(S=>S.id===p.id)&&(t(S=>({...S,annotations:[...S.annotations,p]})),b++)}catch(d){x.push(`Invalid JSON: ${d.message}`)}return{imported:b,errors:x}},[e,t]),k=a.useMemo(()=>({highlights:e.highlights,createHighlight:r,deleteHighlight:l,updateHighlightColor:c,getHighlightsForChunk:u,annotations:e.annotations,createAnnotation:m,updateAnnotation:f,deleteAnnotation:g,getAnnotationForHighlight:y,exportAnnotations:h,importAnnotations:v}),[e.highlights,e.annotations,r,l,c,u,m,f,g,y,h,v]);return i.jsx(We.Provider,{value:k,children:n})}function Qs(){const n=a.useContext(We);if(!n)throw new Error("useAnnotations must be used within an AnnotationsProvider");return n}function Pn({filePath:n,activeChunkIndex:o,relatedChunks:s,pins:e,maxNodes:t=150}){const r=a.useMemo(()=>{const c=new Map,u=[],m=o!==null?`${n}:${o}`:null;m&&c.set(m,{id:m,filePath:n,chunkIndex:o,text:"(current chunk)"});for(const h of s){const v=`${h.filePath}:${h.chunkIndex}`;c.has(v)||c.set(v,{id:v,filePath:h.filePath,chunkIndex:h.chunkIndex,text:h.text.slice(0,100)+(h.text.length>100?"...":"")}),m&&m!==v&&u.push({source:m,target:v,score:h.score,type:"semantic",label:h.connectionReason})}for(const h of e){const v=`${h.sourceKey.filePath}:${h.sourceKey.chunkIndex}`,k=`${h.targetKey.filePath}:${h.targetKey.chunkIndex}`;c.has(v)||c.set(v,{id:v,filePath:h.sourceKey.filePath,chunkIndex:h.sourceKey.chunkIndex,text:h.sourceText.slice(0,100)+(h.sourceText.length>100?"...":"")}),c.has(k)||c.set(k,{id:k,filePath:h.targetKey.filePath,chunkIndex:h.targetKey.chunkIndex,text:h.targetText.slice(0,100)+(h.targetText.length>100?"...":"")});const w=u.findIndex(x=>x.source===v&&x.target===k);if(w>=0){const x=u[w];x&&(u[w]={...x,type:"pinned",label:h.label||x.label})}else u.push({source:v,target:k,score:h.originalScore??.5,type:"pinned",label:h.label})}let f=Array.from(c.values());if(f.length>t){const h=new Set(e.flatMap(x=>[`${x.sourceKey.filePath}:${x.sourceKey.chunkIndex}`,`${x.targetKey.filePath}:${x.targetKey.chunkIndex}`])),v=f.filter(x=>x.id===m||h.has(x.id)),k=Math.max(0,t-v.length),w=f.filter(x=>x.id!==m&&!h.has(x.id)).slice(0,k);f=v.concat(w)}const g=new Set(f.map(h=>h.id)),y=u.filter(h=>g.has(h.source)&&g.has(h.target));return{nodes:f,edges:y}},[n,o,s,e,t]),l=o!==null?`${n}:${o}`:null;return{graphData:r,currentNodeId:l}}function ke(){return crypto.randomUUID()}const Mn={version:1,vaultId:"",updatedAt:new Date().toISOString(),tags:[],taggedItems:[]},Xs={red:{bg:"bg-red-100 dark:bg-red-900/40",text:"text-red-700 dark:text-red-300",border:"border-red-200 dark:border-red-800"},orange:{bg:"bg-orange-100 dark:bg-orange-900/40",text:"text-orange-700 dark:text-orange-300",border:"border-orange-200 dark:border-orange-800"},yellow:{bg:"bg-yellow-100 dark:bg-yellow-900/40",text:"text-yellow-700 dark:text-yellow-300",border:"border-yellow-200 dark:border-yellow-800"},green:{bg:"bg-green-100 dark:bg-green-900/40",text:"text-green-700 dark:text-green-300",border:"border-green-200 dark:border-green-800"},blue:{bg:"bg-blue-100 dark:bg-blue-900/40",text:"text-blue-700 dark:text-blue-300",border:"border-blue-200 dark:border-blue-800"},purple:{bg:"bg-purple-100 dark:bg-purple-900/40",text:"text-purple-700 dark:text-purple-300",border:"border-purple-200 dark:border-purple-800"},pink:{bg:"bg-pink-100 dark:bg-pink-900/40",text:"text-pink-700 dark:text-pink-300",border:"border-pink-200 dark:border-pink-800"},gray:{bg:"bg-gray-100 dark:bg-gray-700",text:"text-gray-700 dark:text-gray-300",border:"border-gray-200 dark:border-gray-600"}},Be=a.createContext(null);function On({children:n,vaultId:o="default"}){const s=`rag-vault-tags-v1-${o}`,[e,t]=F(s,{...Mn,vaultId:o}),r=a.useCallback((d,p)=>{const S={id:ke(),name:d.trim(),color:p,usageCount:0,lastUsedAt:new Date().toISOString(),createdAt:new Date().toISOString()};return t(E=>({...E,updatedAt:new Date().toISOString(),tags:[...E.tags,S]})),S},[t]),l=a.useCallback((d,p)=>{t(S=>({...S,updatedAt:new Date().toISOString(),tags:S.tags.map(E=>{if(E.id!==d)return E;const A={...p};return A.name!==void 0&&(A.name=A.name.trim()),{...E,...A}})}))},[t]),c=a.useCallback(d=>{t(p=>({...p,updatedAt:new Date().toISOString(),tags:p.tags.filter(S=>S.id!==d),taggedItems:p.taggedItems.filter(S=>S.tagId!==d)}))},[t]),u=a.useCallback(d=>e.tags.find(p=>p.id===d),[e.tags]),m=a.useCallback((d,p,S)=>{const E={id:ke(),tagId:d,targetType:p,targetKey:S,createdAt:new Date().toISOString()};return t(A=>({...A,updatedAt:new Date().toISOString(),taggedItems:[...A.taggedItems,E],tags:A.tags.map(M=>M.id===d?{...M,usageCount:M.usageCount+1,lastUsedAt:new Date().toISOString()}:M)})),E},[t]),f=a.useCallback(d=>{t(p=>({...p,updatedAt:new Date().toISOString(),taggedItems:p.taggedItems.filter(S=>S.id!==d)}))},[t]),g=a.useCallback((d,p,S)=>{t(E=>({...E,updatedAt:new Date().toISOString(),taggedItems:E.taggedItems.filter(A=>!(A.tagId===d&&A.targetType===p&&A.targetKey===S))}))},[t]),y=a.useCallback((d,p)=>{const S=e.taggedItems.filter(E=>E.targetType===d&&E.targetKey===p).map(E=>E.tagId);return e.tags.filter(E=>S.includes(E.id))},[e.tags,e.taggedItems]),h=a.useCallback(d=>e.taggedItems.filter(p=>p.tagId===d),[e.taggedItems]),v=a.useCallback((d,p,S)=>e.taggedItems.some(E=>E.tagId===d&&E.targetType===p&&E.targetKey===S),[e.taggedItems]),k=a.useCallback((d=10)=>[...e.tags].sort((p,S)=>S.usageCount!==p.usageCount?S.usageCount-p.usageCount:new Date(S.lastUsedAt).getTime()-new Date(p.lastUsedAt).getTime()).slice(0,d),[e.tags]),w=a.useCallback(()=>JSON.stringify(e,null,2),[e]),x=a.useCallback(d=>{const p=[];let S=0;try{const E=JSON.parse(d);if(E.version!==1)return p.push(`Unsupported version: ${E.version}`),{imported:S,errors:p};if(Array.isArray(E.tags))for(const A of E.tags)A.id&&A.name&&!e.tags.some(M=>M.id===A.id)&&(t(M=>({...M,updatedAt:new Date().toISOString(),tags:[...M.tags,A]})),S++);if(Array.isArray(E.taggedItems))for(const A of E.taggedItems)A.id&&A.tagId&&A.targetKey&&!e.taggedItems.some(M=>M.id===A.id)&&(t(M=>({...M,updatedAt:new Date().toISOString(),taggedItems:[...M.taggedItems,A]})),S++)}catch(E){p.push(`Invalid JSON: ${E.message}`)}return{imported:S,errors:p}},[e,t]),b=a.useMemo(()=>({tags:e.tags,createTag:r,updateTag:l,deleteTag:c,getTag:u,taggedItems:e.taggedItems,addTag:m,removeTag:f,removeTagFromTarget:g,getTagsForTarget:y,getTargetsForTag:h,isTagged:v,getTagSuggestions:k,exportTags:w,importTags:x}),[e.tags,e.taggedItems,r,l,c,u,m,f,g,y,h,v,k,w,x]);return i.jsx(Be.Provider,{value:b,children:n})}function Ys(){const n=a.useContext(Be);if(!n)throw new Error("useTags must be used within a TagsProvider");return n}function Dn(){return crypto.randomUUID()}const Ln={version:1,vaultId:"",updatedAt:new Date().toISOString(),collections:[]},Zs=["red","orange","yellow","green","blue","purple","pink","gray"],eo={red:{bg:"bg-red-100 dark:bg-red-900/40",text:"text-red-700 dark:text-red-300",border:"border-red-200 dark:border-red-800"},orange:{bg:"bg-orange-100 dark:bg-orange-900/40",text:"text-orange-700 dark:text-orange-300",border:"border-orange-200 dark:border-orange-800"},yellow:{bg:"bg-yellow-100 dark:bg-yellow-900/40",text:"text-yellow-700 dark:text-yellow-300",border:"border-yellow-200 dark:border-yellow-800"},green:{bg:"bg-green-100 dark:bg-green-900/40",text:"text-green-700 dark:text-green-300",border:"border-green-200 dark:border-green-800"},blue:{bg:"bg-blue-100 dark:bg-blue-900/40",text:"text-blue-700 dark:text-blue-300",border:"border-blue-200 dark:border-blue-800"},purple:{bg:"bg-purple-100 dark:bg-purple-900/40",text:"text-purple-700 dark:text-purple-300",border:"border-purple-200 dark:border-purple-800"},pink:{bg:"bg-pink-100 dark:bg-pink-900/40",text:"text-pink-700 dark:text-pink-300",border:"border-pink-200 dark:border-pink-800"},gray:{bg:"bg-gray-100 dark:bg-gray-700",text:"text-gray-700 dark:text-gray-300",border:"border-gray-200 dark:border-gray-600"}},qe=a.createContext(null);function Fn({children:n,vaultId:o="default"}){const s=`rag-vault-collections-v1-${o}`,[e,t]=F(s,{...Ln,vaultId:o}),r=a.useCallback((x,b,d)=>{const p={id:Dn(),name:x.trim(),description:d?.trim(),color:b,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t(S=>({...S,updatedAt:new Date().toISOString(),collections:[...S.collections,p]})),p},[t]),l=a.useCallback((x,b)=>{t(d=>({...d,updatedAt:new Date().toISOString(),collections:d.collections.map(p=>p.id===x?{...p,...b,updatedAt:new Date().toISOString()}:p)}))},[t]),c=a.useCallback(x=>{t(b=>({...b,updatedAt:new Date().toISOString(),collections:b.collections.filter(d=>d.id!==x)}))},[t]),u=a.useCallback(x=>e.collections.find(b=>b.id===x),[e.collections]),m=a.useCallback((x,b)=>{t(d=>({...d,updatedAt:new Date().toISOString(),collections:d.collections.map(p=>p.id!==x||p.documents.includes(b)?p:{...p,documents:[...p.documents,b],updatedAt:new Date().toISOString()})}))},[t]),f=a.useCallback((x,b)=>{t(d=>({...d,updatedAt:new Date().toISOString(),collections:d.collections.map(p=>p.id!==x?p:{...p,documents:p.documents.filter(S=>S!==b),updatedAt:new Date().toISOString()})}))},[t]),g=a.useCallback(x=>e.collections.filter(b=>b.documents.includes(x)),[e.collections]),y=a.useCallback(x=>e.collections.find(d=>d.id===x)?.documents??[],[e.collections]),h=a.useCallback((x,b)=>e.collections.find(p=>p.id===x)?.documents.includes(b)??!1,[e.collections]),v=a.useCallback(()=>JSON.stringify(e,null,2),[e]),k=a.useCallback(x=>{const b=[];let d=0;try{const p=JSON.parse(x);if(p.version!==1)return b.push(`Unsupported version: ${p.version}`),{imported:d,errors:b};if(Array.isArray(p.collections))for(const S of p.collections)S.id&&S.name&&!e.collections.some(E=>E.id===S.id)&&(t(E=>({...E,updatedAt:new Date().toISOString(),collections:[...E.collections,S]})),d++)}catch(p){b.push(`Invalid JSON: ${p.message}`)}return{imported:d,errors:b}},[e,t]),w=a.useMemo(()=>({collections:e.collections,createCollection:r,updateCollection:l,deleteCollection:c,getCollection:u,addDocumentToCollection:m,removeDocumentFromCollection:f,getCollectionsForDocument:g,getDocumentsInCollection:y,isDocumentInCollection:h,exportCollections:v,importCollections:k}),[e.collections,r,l,c,u,m,f,g,y,h,v,k]);return i.jsx(qe.Provider,{value:w,children:n})}function to(){const n=a.useContext(qe);if(!n)throw new Error("useCollections must be used within a CollectionsProvider");return n}const re={pan:{x:0,y:0},zoom:1},ve={version:1,vaultId:"",nodePositions:{},viewState:re},$n=a.createContext(null);function _n({children:n,vaultId:o="default"}){const s=`rag-vault-graph-state-v1-${o}`,[e,t]=F(s,{...ve,vaultId:o}),r=a.useCallback(w=>e.nodePositions[w],[e.nodePositions]),l=a.useCallback((w,x)=>{t(b=>({...b,nodePositions:{...b.nodePositions,[w]:{x:x.x,y:x.y,fixedAt:new Date().toISOString()}}}))},[t]),c=a.useCallback(()=>{t(w=>({...w,nodePositions:{}}))},[t]),u=a.useCallback(w=>{t(x=>({...x,viewState:{...x.viewState,pan:w}}))},[t]),m=a.useCallback(w=>{t(x=>({...x,viewState:{...x.viewState,zoom:w}}))},[t]),f=a.useCallback(w=>{t(x=>({...x,viewState:w}))},[t]),g=a.useCallback(()=>{t(w=>({...w,viewState:re}))},[t]),y=a.useCallback(()=>{t(w=>({...ve,vaultId:w.vaultId}))},[t]),h=a.useCallback(()=>JSON.stringify(e,null,2),[e]),v=a.useCallback(w=>{try{const x=JSON.parse(w);return x.version!==1?{success:!1,error:`Unsupported version: ${x.version}`}:(t(b=>({...b,nodePositions:x.nodePositions||{},viewState:x.viewState||re})),{success:!0})}catch(x){return{success:!1,error:`Invalid JSON: ${x.message}`}}},[t]),k=a.useMemo(()=>({nodePositions:e.nodePositions,getNodePosition:r,setNodePosition:l,clearNodePositions:c,viewState:e.viewState,setPan:u,setZoom:m,setViewState:f,resetViewState:g,resetAll:y,exportGraphState:h,importGraphState:v}),[e.nodePositions,e.viewState,r,l,c,u,m,f,g,y,h,v]);return i.jsx($n.Provider,{value:k,children:n})}const Kn={version:1,vaultId:"",documents:{}},zn=a.createContext(null);function Wn({children:n,vaultId:o="default"}){const s=`rag-vault-reading-stats-v1-${o}`,[e,t]=F(s,{...Kn,vaultId:o}),r=a.useCallback(b=>e.documents[b],[e.documents]),l=a.useCallback((b,d)=>{const p=e.documents[b];if(p)return p.chunkStats[d]},[e.documents]),c=a.useCallback((b,d)=>{const p=e.documents[b];return p?p.totalChunks!==d?{...p,totalChunks:d}:p:{filePath:b,totalChunks:d,chunksRead:0,totalTimeMs:0,sessions:[],chunkStats:{}}},[e.documents]),u=a.useCallback((b,d,p)=>{t(S=>{const E=c(b,p),A=E.chunkStats[d]||{totalTimeMs:0,readCount:0,lastReadAt:""},M=A.readCount===0,z={...A,readCount:A.readCount+1,lastReadAt:new Date().toISOString()},W={...E,chunksRead:M?E.chunksRead+1:E.chunksRead,chunkStats:{...E.chunkStats,[d]:z}};return{...S,documents:{...S.documents,[b]:W}}})},[t,c]),m=a.useCallback((b,d,p)=>{p<=0||t(S=>{const E=S.documents[b];if(!E)return S;const A=E.chunkStats[d]||{totalTimeMs:0,readCount:0,lastReadAt:new Date().toISOString()},M={...A,totalTimeMs:A.totalTimeMs+p},z=!E.chunkStats[d],W={...E,totalTimeMs:E.totalTimeMs+p,chunksRead:z?E.chunksRead+1:E.chunksRead,chunkStats:{...E.chunkStats,[d]:M}};return{...S,documents:{...S.documents,[b]:W}}})},[t]),f=a.useCallback(b=>{t(d=>{const p=d.documents[b];if(!p)return d;const S=p.sessions[p.sessions.length-1];if(S&&!S.endedAt)return d;const E={startedAt:new Date().toISOString(),endedAt:"",durationMs:0},A=[...p.sessions,E].slice(-10);return{...d,documents:{...d.documents,[b]:{...p,sessions:A}}}})},[t]),g=a.useCallback(b=>{t(d=>{const p=d.documents[b];if(!p)return d;const S=[...p.sessions],E=S[S.length-1];if(!E||E.endedAt)return d;const A=new Date().toISOString(),M=new Date(A).getTime()-new Date(E.startedAt).getTime();return S[S.length-1]={...E,endedAt:A,durationMs:M},{...d,documents:{...d.documents,[b]:{...p,sessions:S}}}})},[t]),y=a.useCallback(b=>{const d=e.documents[b];return!d||d.totalChunks===0?0:Math.round(d.chunksRead/d.totalChunks*100)},[e.documents]),h=a.useCallback(b=>e.documents[b]?.totalTimeMs??0,[e.documents]),v=a.useCallback(b=>{const d=e.documents[b];return!d||d.chunksRead===0?0:Math.round(d.totalTimeMs/d.chunksRead)},[e.documents]),k=a.useCallback(()=>JSON.stringify(e,null,2),[e]),w=a.useCallback(b=>{t(b?d=>{const{[b]:p,...S}=d.documents;return{...d,documents:S}}:d=>({...d,documents:{}}))},[t]),x=a.useMemo(()=>({getDocumentStats:r,getChunkStats:l,recordChunkView:u,recordTimeSpent:m,startSession:f,endSession:g,getCompletionPercent:y,getTotalReadingTime:h,getAverageTimePerChunk:v,exportStats:k,clearStats:w}),[r,l,u,m,f,g,y,h,v,k,w]);return i.jsx(zn.Provider,{value:x,children:n})}const Bn=[{to:"/",label:"Search",shortcut:""},{to:"/upload",label:"Upload",shortcut:""},{to:"/files",label:"Files",shortcut:""},{to:"/collections",label:"Collections",shortcut:""},{to:"/status",label:"Status",shortcut:""},{to:"/settings",label:"Settings",shortcut:""}];function qn({collapsed:n,onToggle:o,width:s}){const{config:e}=pn();return i.jsxs("aside",{className:"ws-left-rail",style:{width:n?"var(--ws-left-rail-collapsed)":s},children:[i.jsx("nav",{className:"ws-left-rail-nav",children:Bn.map(t=>i.jsx($t,{content:t.label,side:"right",delay:n?100:1e3,children:i.jsxs(st,{to:t.to,className:({isActive:r})=>`ws-nav-item ${r?"ws-nav-item--active":""} ${n?"ws-nav-item--collapsed":""}`,end:t.to==="/",children:[i.jsx("span",{className:"ws-nav-icon",children:t.label.charAt(0)}),!n&&i.jsx("span",{className:"ws-nav-label",children:t.label})]})},t.to))}),i.jsx("div",{style:{flex:1}}),e&&!n&&i.jsx("div",{className:"ws-left-rail-footer",children:i.jsxs("div",{className:"ws-db-indicator",title:e.dbPath,children:[i.jsx("span",{className:"ws-db-dot"}),i.jsx("span",{className:"ws-db-name",children:e.name}),i.jsxs("span",{className:"ws-db-count",children:[e.documentCount," docs"]})]})}),i.jsx("button",{type:"button",className:"ws-rail-toggle",onClick:o,"aria-label":"Toggle left rail",children:n?"›":"‹"})]})}function Se({onResize:n,direction:o}){const s=a.useRef(0),e=a.useRef(null);a.useEffect(()=>()=>{e.current?.()},[]);const t=a.useCallback(r=>{r.preventDefault(),s.current=r.clientX;const l=u=>{const m=u.clientX-s.current;s.current=u.clientX,n(o==="right"?-m:m)},c=()=>{document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",c),document.body.style.cursor="",document.body.style.userSelect="",e.current=null};document.addEventListener("mousemove",l),document.addEventListener("mouseup",c),document.body.style.cursor="col-resize",document.body.style.userSelect="none",e.current=()=>{document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",c),document.body.style.cursor="",document.body.style.userSelect=""}},[n,o]);return i.jsx("div",{className:"ws-resize-handle",onMouseDown:t,role:"separator","aria-orientation":"vertical","aria-valuenow":50,tabIndex:0})}const Ce=12;function ae(n={}){const{delay:o=300,hideDelay:s=150}=n,[e,t]=a.useState({isVisible:!1,position:{x:0,y:0},targetRef:null}),r=a.useRef(null),l=a.useRef(null),c=a.useCallback(()=>{r.current!==null&&(clearTimeout(r.current),r.current=null)},[]),u=a.useCallback(()=>{l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),m=a.useCallback(()=>{c(),u()},[c,u]),f=a.useCallback((k,w)=>{u();const x=w.left+w.width/2,b=w.bottom+8,d=Math.max(Ce,Math.min(x,window.innerWidth-Ce)),S=window.innerHeight-w.bottom<200?w.top-8:b;c(),r.current=setTimeout(()=>{t({isVisible:!0,position:{x:d,y:S},targetRef:k})},o)},[o,u,c]),g=a.useCallback(()=>{c(),l.current=setTimeout(()=>{t(k=>({...k,isVisible:!1,targetRef:null}))},s)},[s,c]),y=a.useCallback(()=>{u()},[u]),h=a.useCallback(()=>{l.current=setTimeout(()=>{t(k=>({...k,isVisible:!1,targetRef:null}))},s)},[s]),v=a.useCallback(()=>{m(),t({isVisible:!1,position:{x:0,y:0},targetRef:null})},[m]);return a.useEffect(()=>()=>m(),[m]),{state:e,onHoverStart:f,onHoverEnd:g,onPreviewEnter:y,onPreviewLeave:h,hide:v}}const se=150,X=12;function Un(n){if(n.length<=se)return n;const o=n.slice(0,se),s=o.lastIndexOf(" ");return s>se*.6?`${o.slice(0,s)}...`:`${o}...`}function Hn(n){return`${Math.round(n*100)}%`}function ie({docTitle:n,excerpt:o,backlinkCount:s,score:e,position:t,onNavigate:r,onOpenInNewTab:l,onPinAsLink:c,onMouseEnter:u,onMouseLeave:m}){const f=a.useRef(null),[g,y]=a.useState(t),[h,v]=a.useState(!0),k=s!==void 0&&s>0||e!==void 0,w=l!==void 0||c!==void 0;return a.useEffect(()=>{const x=f.current;if(!x)return;const b=x.getBoundingClientRect();let{x:d,y:p}=t;d=d-b.width/2,d+b.width>window.innerWidth-X&&(d=window.innerWidth-X-b.width),d<X&&(d=X),p+b.height>window.innerHeight-X&&(p=t.y-b.height-16),p<X&&(p=X),y({x:d,y:p})},[t]),a.useEffect(()=>{const x=requestAnimationFrame(()=>{v(!1)});return()=>cancelAnimationFrame(x)},[]),i.jsxs("div",{ref:f,className:`ws-hover-preview ${h?"ws-hover-preview--entering":""}`,style:{left:g.x,top:g.y},onMouseEnter:u,onMouseLeave:m,children:[i.jsx("div",{className:"ws-hover-preview-title",children:n}),o&&i.jsx("p",{className:"ws-hover-preview-excerpt",children:Un(o)}),k&&i.jsxs("div",{className:"ws-hover-preview-meta",children:[s!==void 0&&s>0&&i.jsxs("span",{className:"ws-badge","data-variant":"link-backlink",children:[s," ",s===1?"backlink":"backlinks"]}),e!==void 0&&i.jsxs("span",{className:"ws-badge","data-variant":"link-semantic",children:[Hn(e)," match"]})]}),i.jsxs("div",{className:"ws-hover-preview-actions",children:[i.jsx("button",{type:"button",className:"ws-button","data-variant":"primary","data-size":"sm",onClick:r,children:"Open"}),w&&i.jsxs("div",{className:"ws-hover-preview-secondary-actions",children:[l&&i.jsx("button",{type:"button",className:"ws-button","data-variant":"ghost","data-size":"sm",onClick:l,children:"New Tab"}),c&&i.jsx("button",{type:"button",className:"ws-button","data-variant":"ghost","data-size":"sm",onClick:c,children:"Pin as Link"})]})]})]})}function L({message:n}){return i.jsx("div",{className:"ws-rail-empty-state",children:i.jsx("p",{children:n})})}function Z(n,o,s){let e=s.initialDeps??[],t,r=!0;function l(){var c,u,m;let f;s.key&&((c=s.debug)!=null&&c.call(s))&&(f=Date.now());const g=n();if(!(g.length!==e.length||g.some((v,k)=>e[k]!==v)))return t;e=g;let h;if(s.key&&((u=s.debug)!=null&&u.call(s))&&(h=Date.now()),t=o(...g),s.key&&((m=s.debug)!=null&&m.call(s))){const v=Math.round((Date.now()-f)*100)/100,k=Math.round((Date.now()-h)*100)/100,w=k/16,x=(b,d)=>{for(b=String(b);b.length<d;)b=" "+b;return b};console.info(`%c⏱ ${x(k,5)} /${x(v,5)} ms`,`
|
|
4
|
+
font-size: .6rem;
|
|
5
|
+
font-weight: bold;
|
|
6
|
+
color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,s?.key)}return s?.onChange&&!(r&&s.skipInitialOnChange)&&s.onChange(t),r=!1,t}return l.updateDeps=c=>{e=c},l}function Ie(n,o){if(n===void 0)throw new Error("Unexpected undefined");return n}const Vn=(n,o)=>Math.abs(n-o)<1.01,Gn=(n,o,s)=>{let e;return function(...t){n.clearTimeout(e),e=n.setTimeout(()=>o.apply(this,t),s)}},Ee=n=>{const{offsetWidth:o,offsetHeight:s}=n;return{width:o,height:s}},Jn=n=>n,Qn=n=>{const o=Math.max(n.startIndex-n.overscan,0),s=Math.min(n.endIndex+n.overscan,n.count-1),e=[];for(let t=o;t<=s;t++)e.push(t);return e},Xn=(n,o)=>{const s=n.scrollElement;if(!s)return;const e=n.targetWindow;if(!e)return;const t=l=>{const{width:c,height:u}=l;o({width:Math.round(c),height:Math.round(u)})};if(t(Ee(s)),!e.ResizeObserver)return()=>{};const r=new e.ResizeObserver(l=>{const c=()=>{const u=l[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){t({width:m.inlineSize,height:m.blockSize});return}}t(Ee(s))};n.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return r.observe(s,{box:"border-box"}),()=>{r.unobserve(s)}},je={passive:!0},Te=typeof window>"u"?!0:"onscrollend"in window,Yn=(n,o)=>{const s=n.scrollElement;if(!s)return;const e=n.targetWindow;if(!e)return;let t=0;const r=n.options.useScrollendEvent&&Te?()=>{}:Gn(e,()=>{o(t,!1)},n.options.isScrollingResetDelay),l=f=>()=>{const{horizontal:g,isRtl:y}=n.options;t=g?s.scrollLeft*(y&&-1||1):s.scrollTop,r(),o(t,f)},c=l(!0),u=l(!1);s.addEventListener("scroll",c,je);const m=n.options.useScrollendEvent&&Te;return m&&s.addEventListener("scrollend",u,je),()=>{s.removeEventListener("scroll",c),m&&s.removeEventListener("scrollend",u)}},Zn=(n,o,s)=>{if(o?.borderBoxSize){const e=o.borderBoxSize[0];if(e)return Math.round(e[s.options.horizontal?"inlineSize":"blockSize"])}return n[s.options.horizontal?"offsetWidth":"offsetHeight"]},es=(n,{adjustments:o=0,behavior:s},e)=>{var t,r;const l=n+o;(r=(t=e.scrollElement)==null?void 0:t.scrollTo)==null||r.call(t,{[e.options.horizontal?"left":"top"]:l,behavior:s})};class ts{constructor(o){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var s,e,t;return((t=(e=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:e.now)==null?void 0:t.call(e))??Date.now()},this.observer=(()=>{let s=null;const e=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(t=>{t.forEach(r=>{const l=()=>{const c=r.target,u=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(c,r,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()})}));return{disconnect:()=>{var t;(t=e())==null||t.disconnect(),s=null},observe:t=>{var r;return(r=e())==null?void 0:r.observe(t,{box:"border-box"})},unobserve:t=>{var r;return(r=e())==null?void 0:r.unobserve(t)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([e,t])=>{typeof t>"u"&&delete s[e]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Jn,rangeExtractor:Qn,onChange:()=>{},measureElement:Zn,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...s}},this.notify=s=>{var e,t;(t=(e=this.options).onChange)==null||t.call(e,this,s)},this.maybeNotify=Z(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}this.scrollElement=e,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(t=>{this.observer.observe(t)}),this.unsubs.push(this.options.observeElementRect(this,t=>{this.scrollRect=t,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(t,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<t?"forward":"backward":null,this.scrollOffset=t,this.isScrolling=r,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(s,e)=>{const t=new Map,r=new Map;for(let l=e-1;l>=0;l--){const c=s[l];if(t.has(c.lane))continue;const u=r.get(c.lane);if(u==null||c.end>u.end?r.set(c.lane,c):c.end<u.end&&t.set(c.lane,!0),t.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((l,c)=>l.end===c.end?l.index-c.index:l.end-c.end)[0]:void 0},this.getMeasurementOptions=Z(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes],(s,e,t,r,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:e,scrollMargin:t,getItemKey:r,enabled:l,lanes:c}),{key:!1}),this.getMeasurements=Z(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:e,scrollMargin:t,getItemKey:r,enabled:l,lanes:c},u)=>{if(!l)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const y of this.laneAssignments.keys())y>=s&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const m=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1);const f=this.measurementsCache.slice(0,m),g=new Array(c).fill(void 0);for(let y=0;y<m;y++){const h=f[y];h&&(g[h.lane]=y)}for(let y=m;y<s;y++){const h=r(y),v=this.laneAssignments.get(y);let k,w;if(v!==void 0&&this.options.lanes>1){k=v;const p=g[k],S=p!==void 0?f[p]:void 0;w=S?S.end+this.options.gap:e+t}else{const p=this.options.lanes===1?f[y-1]:this.getFurthestMeasurement(f,y);w=p?p.end+this.options.gap:e+t,k=p?p.lane:y%this.options.lanes,this.options.lanes>1&&this.laneAssignments.set(y,k)}const x=u.get(h),b=typeof x=="number"?x:this.options.estimateSize(y),d=w+b;f[y]={index:y,start:w,size:b,end:d,key:h,lane:k},g[k]=y}return this.measurementsCache=f,f},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Z(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,e,t,r)=>this.range=s.length>0&&e>0?ns({measurements:s,outerSize:e,scrollOffset:t,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Z(()=>{let s=null,e=null;const t=this.calculateRange();return t&&(s=t.startIndex,e=t.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,e]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,e]},(s,e,t,r,l)=>r===null||l===null?[]:s({startIndex:r,endIndex:l,overscan:e,count:t}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const e=this.options.indexAttribute,t=s.getAttribute(e);return t?parseInt(t,10):(console.warn(`Missing attribute name '${e}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var e;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const t=this.scrollState.index??((e=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:e.index);if(t!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),l=Math.max(0,t-r),c=Math.min(this.options.count-1,t+r);return s>=l&&s<=c}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((l,c)=>{l.isConnected||(this.observer.unobserve(l),this.elementsCache.delete(c))});return}const e=this.indexFromElement(s),t=this.options.getItemKey(e),r=this.elementsCache.get(t);r!==s&&(r&&this.observer.unobserve(r),this.observer.observe(s),this.elementsCache.set(t,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(e)&&this.resizeItem(e,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,e)=>{var t;const r=this.measurementsCache[s];if(!r)return;const l=this.itemSizeCache.get(r.key)??r.size,c=e-l;c!==0&&(((t=this.scrollState)==null?void 0:t.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,c,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=c,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,e)),this.notify(!1))},this.getVirtualItems=Z(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,e)=>{const t=[];for(let r=0,l=s.length;r<l;r++){const c=s[r],u=e[c];t.push(u)}return t},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const e=this.getMeasurements();if(e.length!==0)return Ie(e[Ue(0,e.length-1,t=>Ie(e[t]).start,s)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(s,e,t=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),l=this.getScrollOffset();e==="auto"&&(e=s>=l+r?"end":"start"),e==="center"?s+=(t-r)/2:e==="end"&&(s-=r);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,s),0)},this.getOffsetForIndex=(s,e="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const t=this.getSize(),r=this.getScrollOffset(),l=this.measurementsCache[s];if(!l)return;if(e==="auto")if(l.end>=r+t-this.options.scrollPaddingEnd)e="end";else if(l.start<=r+this.options.scrollPaddingStart)e="start";else return[r,e];if(e==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),e];const c=e==="end"?l.end+this.options.scrollPaddingEnd:l.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,e,l.size),e]},this.scrollToOffset=(s,{align:e="start",behavior:t="auto"}={})=>{const r=this.getOffsetForAlignment(s,e),l=this.now();this.scrollState={index:null,align:e,behavior:t,startedAt:l,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:e="auto",behavior:t="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const r=this.getOffsetForIndex(s,e);if(!r)return;const[l,c]=r,u=this.now();this.scrollState={index:s,align:c,behavior:t,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:e="auto"}={})=>{const t=this.getScrollOffset()+s,r=this.now();this.scrollState={index:null,align:"start",behavior:e,startedAt:r,lastTargetOffset:t,stableFrames:0},this._scrollToOffset(t,{adjustments:void 0,behavior:e}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var s;const e=this.getMeasurements();let t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1)t=((s=e[e.length-1])==null?void 0:s.end)??0;else{const r=Array(this.options.lanes).fill(null);let l=e.length-1;for(;l>=0&&r.some(c=>c===null);){const c=e[l];r[c.lane]===null&&(r[c.lane]=c.end),l--}t=Math.max(...r.filter(c=>c!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:e,behavior:t})=>{this.options.scrollToFn(s,{behavior:t,adjustments:e},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(o)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const e=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,t=e?e[0]:this.scrollState.lastTargetOffset,r=1,l=t!==this.scrollState.lastTargetOffset;if(!l&&Vn(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=r){this.scrollState=null;return}}else this.scrollState.stableFrames=0,l&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Ue=(n,o,s,e)=>{for(;n<=o;){const t=(n+o)/2|0,r=s(t);if(r<e)n=t+1;else if(r>e)o=t-1;else return t}return n>0?n-1:0};function ns({measurements:n,outerSize:o,scrollOffset:s,lanes:e}){const t=n.length-1,r=u=>n[u].start;if(n.length<=e)return{startIndex:0,endIndex:t};let l=Ue(0,t,r,s),c=l;if(e===1)for(;c<t&&n[c].end<s+o;)c++;else if(e>1){const u=Array(e).fill(0);for(;c<t&&u.some(f=>f<s+o);){const f=n[c];u[f.lane]=f.end,c++}const m=Array(e).fill(s+o);for(;l>=0&&m.some(f=>f>=s);){const f=n[l];m[f.lane]=f.start,l--}l=Math.max(0,l-l%e),c=Math.min(t,c+(e-1-c%e))}return{startIndex:l,endIndex:c}}const Ae=typeof document<"u"?a.useLayoutEffect:a.useEffect;function ss({useFlushSync:n=!0,...o}){const s=a.useReducer(()=>({}),{})[1],e={...o,onChange:(r,l)=>{var c;n&&l?ot.flushSync(s):s(),(c=o.onChange)==null||c.call(o,r,l)}},[t]=a.useState(()=>new ts(e));return t.setOptions(e),Ae(()=>t._didMount(),[]),Ae(()=>t._willUpdate()),t}function os(n){return ss({observeElementRect:Xn,observeElementOffset:Yn,scrollToFn:es,...n})}const rs=50,as=72;function ne({items:n,renderItem:o,getKey:s}){const e=a.useRef(null),t=os({count:n.length,getScrollElement:()=>e.current,estimateSize:()=>as,overscan:5});return n.length<=rs?i.jsx("div",{className:"ws-rail-list",children:n.map((r,l)=>i.jsx("div",{children:o(r,l)},s(r,l)))}):i.jsx("div",{ref:e,className:"ws-rail-list",style:{height:"100%",overflow:"auto"},children:i.jsx("div",{style:{height:t.getTotalSize(),width:"100%",position:"relative"},children:t.getVirtualItems().map(r=>{const l=n[r.index];return i.jsx("div",{"data-index":r.index,ref:t.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${r.start}px)`},children:o(l,r.index)},s(l,r.index))})})})}function He(){const{selection:n,select:o}=V(),{backlinks:s,backlinkCount:e}=kn(n.docId??null,n.chunkIndex??null),{state:t,onHoverStart:r,onHoverEnd:l,onPreviewEnter:c,onPreviewLeave:u,hide:m}=ae();if(!n.docId)return i.jsx(L,{message:"Select a document to see backlinks"});if(e===0)return i.jsx(L,{message:"No backlinks found for this document"});const f=t.isVisible?s.find(g=>g.id===t.targetRef):null;return i.jsxs(i.Fragment,{children:[i.jsx(ne,{items:s,getKey:g=>g.id,renderItem:g=>{const y=g.sourceKey.filePath.split("/").pop()??g.sourceKey.filePath;return i.jsxs("button",{type:"button",className:"ws-rail-item",onClick:()=>{m(),o({docId:g.sourceKey.filePath,chunkIndex:g.sourceKey.chunkIndex,source:"backlink"})},onMouseEnter:h=>r(g.id,h.currentTarget.getBoundingClientRect()),onMouseLeave:l,children:[i.jsx("span",{className:"ws-rail-item-title",children:y}),i.jsxs("span",{className:"ws-rail-item-meta",children:["Chunk #",g.sourceKey.chunkIndex]}),g.label&&i.jsx("span",{className:"ws-rail-item-label",children:g.label}),i.jsxs("p",{className:"ws-rail-item-excerpt",children:[g.sourceText.slice(0,120),"..."]})]})}}),f&&i.jsx(ie,{docTitle:f.sourceKey.filePath.split("/").pop()??f.sourceKey.filePath,excerpt:f.sourceText,backlinkCount:e,position:t.position,onNavigate:()=>{m(),o({docId:f.sourceKey.filePath,chunkIndex:f.sourceKey.chunkIndex,source:"backlink"})},onMouseEnter:c,onMouseLeave:u})]})}function is(){const{selection:n,select:o}=V(),{related:s,isLoading:e}=_e(n.docId??null,n.chunkIndex??null),{state:t,onHoverStart:r,onHoverEnd:l,onPreviewEnter:c,onPreviewLeave:u,hide:m}=ae();if(!n.docId)return i.jsx(L,{message:"Select a document to see related passages"});if(e)return i.jsx("div",{className:"ws-rail-loading",children:"Loading related..."});if(!s||s.length===0)return i.jsx(L,{message:"No related passages found"});const f=t.isVisible?s.find(g=>`${g.filePath}-${g.chunkIndex}`===t.targetRef):null;return i.jsxs(i.Fragment,{children:[i.jsx(ne,{items:s,getKey:g=>`${g.filePath}-${g.chunkIndex}`,renderItem:g=>{const y=`${g.filePath}-${g.chunkIndex}`;return i.jsxs("button",{type:"button",className:"ws-rail-item",onClick:()=>{m(),o({docId:g.filePath,chunkIndex:g.chunkIndex,source:"backlink"})},onMouseEnter:h=>r(y,h.currentTarget.getBoundingClientRect()),onMouseLeave:l,children:[i.jsx("span",{className:"ws-rail-item-title",children:g.filePath.split("/").pop()}),i.jsxs("span",{className:"ws-rail-item-meta",children:["Score: ",g.score.toFixed(3)]}),i.jsxs("p",{className:"ws-rail-item-excerpt",children:[g.text.slice(0,120),"..."]})]})}}),f&&i.jsx(ie,{docTitle:f.filePath.split("/").pop()??f.filePath,excerpt:f.text,score:f.score,position:t.position,onNavigate:()=>{m(),o({docId:f.filePath,chunkIndex:f.chunkIndex,source:"backlink"})},onMouseEnter:c,onMouseLeave:u})]})}function ls(){const{selection:n}=V(),{chunks:o}=bn(n.docId??null),{entries:s}=Tn({chunks:o??[]});return n.docId?s.length===0?i.jsx(L,{message:"No headings found in this document"}):i.jsx("nav",{className:"ws-rail-list",children:s.map(e=>i.jsx("button",{type:"button",className:"ws-rail-item",style:{paddingLeft:`calc(var(--ws-space-3) + ${(e.level-1)*12}px)`},children:i.jsx("span",{className:"ws-rail-item-title",children:e.text})},e.id))}):i.jsx(L,{message:"Select a document to see its outline"})}function cs(){const n=a.useRef(null),[o,s]=a.useState(null),[e,t]=a.useState(!1),[r,l]=a.useState(null);a.useEffect(()=>{const m=new Worker(new URL("/assets/link-indexer.worker-DGXNsXmZ.js",import.meta.url),{type:"module"});return m.onmessage=f=>{const g=f.data;g.type==="scan-complete"&&g.index?(s(g.index),t(!1),l(null)):g.type==="error"&&(l(new Error(g.message??"Worker error")),t(!1))},m.onerror=f=>{l(new Error(f.message||"Worker initialization error")),t(!1)},n.current=m,()=>{m.terminate(),n.current=null}},[]);const c=a.useCallback(m=>{n.current&&(t(!0),l(null),n.current.postMessage({type:"scan",documents:m}))},[]),u=a.useCallback(async()=>{t(!0),l(null);try{const m=await Pe(),f=await Promise.all(m.map(async g=>{const y=await Me(g.filePath);return{filePath:g.filePath,chunks:y.map(h=>({chunkIndex:h.chunkIndex,text:h.text}))}}));if(!n.current)return;n.current.postMessage({type:"scan",documents:f})}catch(m){l(m instanceof Error?m:new Error("Failed to fetch documents for scan")),t(!1)}},[]);return{index:o,isScanning:e,error:r,scan:c,rescan:u}}const Ve=a.createContext(null);function ds({children:n}){const{index:o,isScanning:s,rescan:e}=cs(),t=B();a.useEffect(()=>{e()},[e]),a.useEffect(()=>t.getQueryCache().subscribe(g=>{g.type==="updated"&&g.query.queryKey[0]==="files"&&g.action.type==="success"&&e()}),[t,e]);const r=a.useMemo(()=>{if(!o)return new Set;const f=new Set,g=new Set;if(o.outgoing)for(const y of Object.keys(o.outgoing))g.add(y);if(o.incoming)for(const y of Object.values(o.incoming))for(const h of y)g.add(h.sourceDoc);for(const y of g){const h=y.split("/"),v=h[h.length-1]??y,k=v.replace(/\.[^.]+$/,"");f.add(k.toLowerCase()),f.add(v.toLowerCase())}return f},[o]),l=a.useCallback(f=>o?o.outgoing[f]??[]:[],[o]),c=a.useCallback(f=>o?o.incoming[f]??[]:[],[o]),u=a.useCallback(f=>r.has(f.toLowerCase()),[r]),m=a.useMemo(()=>({index:o,isScanning:s,rescan:e,getOutgoingLinks:l,getIncomingLinks:c,isResolved:u}),[o,s,e,l,c,u]);return i.jsx(Ve.Provider,{value:m,children:n})}function Ge(){const n=a.useContext(Ve);if(!n)throw new Error("useLinkIndexContext must be used within a LinkIndexProvider");return n}function us(){const{selection:n,select:o}=V(),{getOutgoingLinks:s,isResolved:e,isScanning:t}=Ge(),{state:r,onHoverStart:l,onHoverEnd:c,onPreviewEnter:u,onPreviewLeave:m,hide:f}=ae(),g=a.useMemo(()=>n.docId?s(n.docId):[],[n.docId,s]);if(!n.docId)return i.jsx(L,{message:"Select a document to see outgoing links"});if(t)return i.jsx("div",{className:"ws-rail-loading",children:"Scanning links..."});if(g.length===0)return i.jsx(L,{message:"No outgoing links found"});const y=r.isVisible?g.find((h,v)=>`${h.targetTitle}-${h.chunkIndex}-${v}`===r.targetRef):null;return i.jsxs(i.Fragment,{children:[i.jsx(ne,{items:g,getKey:(h,v)=>`${h.targetTitle}-${h.chunkIndex}-${v}`,renderItem:(h,v)=>{const k=e(h.targetTitle),w=`${h.targetTitle}-${h.chunkIndex}-${v}`,x=[];return h.heading&&x.push(`# ${h.heading}`),h.blockRef&&x.push(`^ ${h.blockRef}`),x.push(`Chunk #${h.chunkIndex}`),i.jsxs("button",{type:"button",className:"ws-rail-item",disabled:!k,onClick:()=>{k&&(f(),o({docId:h.targetTitle,source:"backlink"}))},onMouseEnter:b=>{k&&l(w,b.currentTarget.getBoundingClientRect())},onMouseLeave:c,children:[i.jsx("span",{className:"ws-rail-item-title",children:h.alias??h.targetTitle}),i.jsx("span",{className:"ws-rail-item-meta",children:x.join(" - ")}),i.jsx(oe,{variant:k?"link-explicit":"link-unresolved",children:k?"Resolved":"Unresolved"})]})}}),y&&i.jsx(ie,{docTitle:y.alias??y.targetTitle,excerpt:y.heading?`# ${y.heading}`:void 0,position:r.position,onNavigate:()=>{f(),o({docId:y.targetTitle,source:"backlink"})},onMouseEnter:u,onMouseLeave:m})]})}function hs(n){const o=n.split("/");return(o[o.length-1]??n).replace(/\.[^.]+$/,"")}function fs(){const{selection:n,select:o}=V(),{index:s,isScanning:e,getIncomingLinks:t}=Ge(),r=a.useMemo(()=>n.docId?hs(n.docId):null,[n.docId]),l=a.useMemo(()=>{if(!r)return[];const m=t(r);if(m.length===0)return[];const f=new Map;for(const g of m){const y=f.get(g.sourceDoc);y?y.push(g):f.set(g.sourceDoc,[g])}return Array.from(f.entries()).map(([g,y])=>({sourceDoc:g,edges:y}))},[r,t]),c=a.useMemo(()=>{if(!r||!s)return 0;const m=new Set(t(r).map(g=>g.sourceDoc));let f=0;for(const g of Object.keys(s.outgoing))g!==n.docId&&(m.has(g)||f++);return f},[r,s,n.docId,t]);if(!n.docId)return i.jsx(L,{message:"Select a document to see unlinked mentions"});if(e)return i.jsx("div",{className:"ws-rail-loading",children:"Scanning for mentions..."});if(!s)return i.jsx(L,{message:"Link index not available"});const u=l.length>0;return!u&&c===0?i.jsx(L,{message:"No mentions found for this document"}):i.jsxs("div",{className:"ws-rail-list",children:[u&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"ws-rail-item-meta",style:{padding:"0.5rem 0.75rem"},children:["Linked mentions",i.jsx(oe,{variant:"success",count:l.length,style:{marginLeft:"0.5rem"},children:"linked"})]}),i.jsx(ne,{items:l,getKey:m=>m.sourceDoc,renderItem:m=>{const f=m.sourceDoc.split("/").pop()??m.sourceDoc,g=m.edges.map(y=>`#${y.chunkIndex}`).join(", ");return i.jsxs("button",{type:"button",className:"ws-rail-item",onClick:()=>{o({docId:m.sourceDoc,source:"backlink"})},children:[i.jsx("span",{className:"ws-rail-item-title",children:f}),i.jsxs("span",{className:"ws-rail-item-meta",children:[m.edges.length," link",m.edges.length!==1?"s":""," - Chunks"," ",g]})]})}})]}),c>0&&i.jsxs("div",{className:"ws-rail-item-meta",style:{padding:"0.5rem 0.75rem",marginTop:u?"0.75rem":0},children:[i.jsx(oe,{variant:"info",count:c,style:{marginRight:"0.5rem"},children:"unlinked"}),c," document",c!==1?"s":"",' scanned without a link to "',r,'".',i.jsx("p",{className:"ws-rail-item-excerpt",style:{marginTop:"0.375rem"},children:"Full text scanning for unlinked mentions requires fetching all document chunks and is planned for a future update."})]})]})}const Je={nodeRadius:8,activeNodeRadius:12,currentNodeColor:"#3b82f6",defaultNodeColor:"#9ca3af",pinnedNodeColor:"#10b981",edgeWidth:1.5,pinnedEdgeColor:"#3b82f6",semanticEdgeColor:"#d1d5db",backlinkEdgeColor:"#8b5cf6",repulsionStrength:150,attractionStrength:.3,centerGravity:.05,velocityDecay:.4,maxNodes:150,neighborsToShow:10};function gs({graphData:n,config:o,width:s,height:e,enabled:t=!0}){const r=a.useMemo(()=>({...Je,...o}),[o]),[l,c]=a.useState([]),[u,m]=a.useState(!1),f=a.useRef(null),g=a.useRef(0);a.useEffect(()=>{const k=s/2,w=e/2,x=n.nodes.map((b,d)=>{const p=l.find(A=>A.id===b.id);if(p&&p.x!==void 0&&p.y!==void 0)return{...b,x:p.x,y:p.y,vx:0,vy:0};const S=d/n.nodes.length*Math.PI*2,E=Math.min(s,e)*.3;return{...b,x:k+Math.cos(S)*E+(Math.random()-.5)*50,y:w+Math.sin(S)*E+(Math.random()-.5)*50,vx:0,vy:0}});c(x),m(!1),g.current=0},[n.nodes.length,s,e,n.nodes.map,l.find]);const y=a.useRef(new Map);a.useEffect(()=>{const k=new Map;for(const w of n.edges){const x=k.get(w.source)||[];x.push(w.target),k.set(w.source,x);const b=k.get(w.target)||[];b.push(w.source),k.set(w.target,b)}y.current=k},[n.edges]);const h=a.useCallback(()=>{if(!t||l.length===0)return!1;const k=s/2,w=e/2;let x=0;const b=l.map(d=>{let p=0,S=0;if(d.fx!==void 0&&d.fx!==null&&d.fy!==void 0&&d.fy!==null)return{...d,x:d.fx,y:d.fy};for(const I of l){if(I.id===d.id)continue;const N=(d.x??0)-(I.x??0),j=(d.y??0)-(I.y??0),P=Math.sqrt(N*N+j*j)||1,O=r.repulsionStrength/(P*P);p+=N/P*O,S+=j/P*O}const E=y.current.get(d.id)||[];for(const I of E){const N=l.find(O=>O.id===I);if(!N)continue;const j=(N.x??0)-(d.x??0),P=(N.y??0)-(d.y??0);p+=j*r.attractionStrength,S+=P*r.attractionStrength}p+=(k-(d.x??0))*r.centerGravity,S+=(w-(d.y??0))*r.centerGravity;const A=((d.vx??0)+p)*(1-r.velocityDecay),M=((d.vy??0)+S)*(1-r.velocityDecay),z=(d.x??0)+A,W=(d.y??0)+M,U=40,R=Math.max(U,Math.min(s-U,z)),T=Math.max(U,Math.min(e-U,W)),C=Math.sqrt(A*A+M*M);return x=Math.max(x,C),{...d,x:R,y:T,vx:A,vy:M}});return c(b),g.current++,x>.5&&g.current<300},[l,t,s,e,r]);a.useEffect(()=>{if(!t){f.current&&cancelAnimationFrame(f.current);return}const k=()=>{h()?f.current=requestAnimationFrame(k):m(!0)};return f.current=requestAnimationFrame(k),()=>{f.current&&cancelAnimationFrame(f.current)}},[h,t]);const v=a.useCallback(()=>{m(!1),g.current=0,c(k=>k.map(w=>({...w,vx:(Math.random()-.5)*10,vy:(Math.random()-.5)*10})))},[]);return{nodes:l,isStable:u,reheat:v}}function ms({graphData:n,currentNodeId:o,pinnedNodeIds:s,onNodeClick:e,config:t}){const r=a.useRef(null),l=a.useRef(null),[c,u]=a.useState({width:600,height:300}),[m,f]=a.useState(null),[g,y]=a.useState(null),[h,v]=a.useState({x:0,y:0}),[k,w]=a.useState(1),x=a.useRef(!1),b=a.useRef({x:0,y:0}),d=a.useMemo(()=>({...Je,...t}),[t]),{nodes:p,isStable:S}=gs({graphData:n,config:t,width:c.width,height:c.height,enabled:n.nodes.length>0});a.useEffect(()=>{const C=l.current;if(!C)return;const I=new ResizeObserver(N=>{const j=N[0];j&&u({width:j.contentRect.width,height:j.contentRect.height})});return I.observe(C),()=>I.disconnect()},[]);const E=a.useCallback((C,I)=>{const N=r.current;if(!N)return{x:0,y:0};const j=N.getBoundingClientRect(),P=(C-j.left-h.x)/k,O=(I-j.top-h.y)/k;return{x:P,y:O}},[h,k]),A=a.useCallback((C,I)=>{for(const N of p){if(N.x===void 0||N.y===void 0)continue;const j=C-N.x,P=I-N.y,O=N.id===o?d.activeNodeRadius:d.nodeRadius;if(j*j+P*P<=O*O*1.5)return N}return null},[p,o,d.nodeRadius,d.activeNodeRadius]),M=a.useCallback(C=>{x.current=!0,b.current={x:C.clientX,y:C.clientY}},[]),z=a.useCallback(()=>{x.current=!1},[]),W=a.useCallback(C=>{if(x.current){const P=C.clientX-b.current.x,O=C.clientY-b.current.y;v($=>({x:$.x+P,y:$.y+O})),b.current={x:C.clientX,y:C.clientY};return}const{x:I,y:N}=E(C.clientX,C.clientY),j=A(I,N);if(f(j),j){const P=r.current;if(P){const O=P.getBoundingClientRect();y({x:C.clientX-O.left,y:C.clientY-O.top,node:j})}}else y(null)},[E,A]),U=a.useCallback(C=>{const{x:I,y:N}=E(C.clientX,C.clientY),j=A(I,N);j&&e&&e(j)},[E,A,e]),R=a.useCallback(C=>{C.preventDefault();const I=C.deltaY>0?.9:1.1;w(N=>Math.max(.3,Math.min(3,N*I)))},[]);a.useEffect(()=>{const C=r.current;if(!C)return;const I=C.getContext("2d");if(!I)return;C.width=c.width*window.devicePixelRatio,C.height=c.height*window.devicePixelRatio,I.scale(window.devicePixelRatio,window.devicePixelRatio),I.clearRect(0,0,c.width,c.height),I.save(),I.translate(h.x,h.y),I.scale(k,k);const N=new Map;for(const j of p)j.x!==void 0&&j.y!==void 0&&N.set(j.id,{x:j.x,y:j.y});for(const j of n.edges){const P=N.get(j.source),O=N.get(j.target);!P||!O||(I.beginPath(),I.moveTo(P.x,P.y),I.lineTo(O.x,O.y),I.strokeStyle=j.type==="pinned"?d.pinnedEdgeColor:j.type==="backlink"?d.backlinkEdgeColor:d.semanticEdgeColor,I.lineWidth=j.type==="pinned"?d.edgeWidth*1.5:d.edgeWidth,j.type==="semantic"?I.setLineDash([4,4]):I.setLineDash([]),I.stroke())}I.setLineDash([]);for(const j of p){if(j.x===void 0||j.y===void 0)continue;const P=j.id===o,O=s.has(j.id),$=m?.id===j.id,Y=P?d.activeNodeRadius:d.nodeRadius,Xe=P?d.currentNodeColor:O?d.pinnedNodeColor:d.defaultNodeColor;I.beginPath(),I.arc(j.x,j.y,$?Y*1.3:Y,0,Math.PI*2),I.fillStyle=Xe,I.fill(),I.strokeStyle=$?"#fff":"rgba(0,0,0,0.2)",I.lineWidth=$?2:1,I.stroke(),P&&(I.font="10px sans-serif",I.fillStyle="#fff",I.textAlign="center",I.textBaseline="middle",I.fillText("●",j.x,j.y))}I.restore()},[p,n.edges,c,h,k,o,s,m,d]);const T=C=>{const I=C.split(/[/\\]/);return I[I.length-1]||C};return i.jsxs("div",{ref:l,className:"w-full h-full relative rounded-lg overflow-hidden",style:{background:"var(--ws-surface-1)"},children:[i.jsx("canvas",{ref:r,className:"w-full h-full cursor-grab active:cursor-grabbing",style:{width:c.width,height:c.height},onMouseDown:M,onMouseUp:z,onMouseMove:W,onMouseLeave:()=>{f(null),y(null),x.current=!1},onClick:U,onWheel:R}),g&&i.jsxs("div",{className:"absolute pointer-events-none z-10 max-w-xs px-3 py-2 text-xs rounded-lg shadow-lg",style:{background:"var(--ws-surface-0)",color:"var(--ws-text)",left:Math.min(g.x+10,c.width-200),top:Math.min(g.y+10,c.height-60)},children:[i.jsx("p",{className:"font-medium truncate",children:T(g.node.filePath)}),i.jsxs("p",{style:{color:"var(--ws-text-faint)"},children:["Chunk #",g.node.chunkIndex]}),i.jsx("p",{className:"mt-1 line-clamp-2",style:{color:"var(--ws-text-muted)"},children:g.node.text})]}),i.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1",children:[i.jsx("button",{type:"button",onClick:()=>w(C=>Math.min(3,C*1.2)),className:"p-1.5 rounded shadow",style:{background:"var(--ws-surface-raised)",color:"var(--ws-text-secondary)"},title:"Zoom in",children:i.jsx(ps,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>w(C=>Math.max(.3,C*.8)),className:"p-1.5 rounded shadow",style:{background:"var(--ws-surface-raised)",color:"var(--ws-text-secondary)"},title:"Zoom out",children:i.jsx(bs,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>{v({x:0,y:0}),w(1)},className:"p-1.5 rounded shadow",style:{background:"var(--ws-surface-raised)",color:"var(--ws-text-secondary)"},title:"Reset view",children:i.jsx(xs,{className:"w-4 h-4"})}),!S&&i.jsx("span",{className:"p-1.5 text-xs",style:{color:"var(--ws-text-muted)"},children:"Simulating..."})]}),i.jsxs("div",{className:"absolute top-2 left-2 text-xs px-2 py-1 rounded",style:{color:"var(--ws-text-secondary)",background:"var(--ws-surface-raised)"},children:[i.jsxs("span",{className:"inline-flex items-center gap-1",children:[i.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:d.currentNodeColor}}),"Current"]}),i.jsxs("span",{className:"inline-flex items-center gap-1 ml-3",children:[i.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:d.pinnedNodeColor}}),"Pinned"]}),i.jsxs("span",{className:"inline-flex items-center gap-1 ml-3",children:[i.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:d.defaultNodeColor}}),"Related"]})]})]})}function ps({className:n}){return i.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function bs({className:n}){return i.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}function xs({className:n}){return i.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function ys(){const{selection:n,select:o}=V(),s=n.docId??null,e=n.chunkIndex??null,{related:t,isLoading:r}=_e(s,e),{pins:l}=wn(),{graphData:c,currentNodeId:u}=Pn({filePath:s??"",activeChunkIndex:e,relatedChunks:t,pins:l}),m=a.useMemo(()=>{const g=new Set;for(const y of l)g.add(`${y.sourceKey.filePath}:${y.sourceKey.chunkIndex}`),g.add(`${y.targetKey.filePath}:${y.targetKey.chunkIndex}`);return g},[l]),f=g=>{o({docId:g.filePath,chunkIndex:g.chunkIndex,source:"graph"})};return s?r?i.jsx("div",{className:"ws-rail-loading",children:"Loading graph..."}):c.nodes.length===0?i.jsx(L,{message:"No graph data available"}):i.jsx("div",{style:{height:"100%",minHeight:300},children:i.jsx(ms,{graphData:c,currentNodeId:u,pinnedNodeIds:m,onNodeClick:f})}):i.jsx(L,{message:"Select a document to see its graph"})}const ws=[{id:"backlinks",label:"Backlinks"},{id:"outgoing",label:"Outgoing"},{id:"related",label:"Related"},{id:"mentions",label:"Mentions"},{id:"outline",label:"Outline"},{id:"graph",label:"Graph"}],ks={backlinks:He,outgoing:us,related:is,mentions:fs,outline:ls,graph:ys};function vs({collapsed:n,onToggle:o,width:s}){const[e,t]=F("ws-right-rail-tab","backlinks");if(n)return i.jsx("aside",{className:"ws-right-rail ws-right-rail--collapsed",children:i.jsx("button",{type:"button",className:"ws-rail-toggle",onClick:o,"aria-label":"Toggle right rail",children:"‹"})});const r=ks[e]??He;return i.jsxs("aside",{className:"ws-right-rail",style:{width:s},children:[i.jsxs("div",{className:"ws-right-rail-header",children:[i.jsx(Fe,{tabs:ws,activeId:e,onSelect:l=>t(l),variant:"pill",className:"ws-right-rail-tabs"}),i.jsx("button",{type:"button",className:"ws-rail-toggle",onClick:o,"aria-label":"Toggle right rail",children:"›"})]}),i.jsx("div",{className:"ws-right-rail-content",children:i.jsx(r,{})})]})}function Ss(){const n=ue({storageKey:"left-rail",defaultWidth:220,min:180,max:320}),o=ue({storageKey:"right-rail",defaultWidth:300,min:240,max:420}),{selection:s,select:e}=V(),t=dt(),r=a.useRef(!1);a.useEffect(()=>{if(r.current){r.current=!1;return}s.docId&&t.push(s.docId,s.chunkIndex)},[s.docId,s.chunkIndex]);const l=a.useCallback(()=>{const u=t.goBack();u&&(r.current=!0,e({docId:u.docId,chunkIndex:u.chunkIndex,source:"backlink"}))},[t,e]),c=a.useCallback(()=>{const u=t.goForward();u&&(r.current=!0,e({docId:u.docId,chunkIndex:u.chunkIndex,source:"backlink"}))},[t,e]);return ut({onToggleLeftRail:n.toggleCollapsed,onToggleRightRail:o.toggleCollapsed,onNavigateBack:l,onNavigateForward:c}),i.jsxs("div",{className:"ws-shell",children:[i.jsx(Nt,{}),i.jsx(qn,{collapsed:n.collapsed,onToggle:n.toggleCollapsed,width:n.width}),!n.collapsed&&i.jsx(Se,{direction:"left",onResize:u=>n.setWidth(n.width+u)}),i.jsx(Gt,{}),!o.collapsed&&i.jsx(Se,{direction:"right",onResize:u=>o.setWidth(o.width+u)}),i.jsx(vs,{collapsed:o.collapsed,onToggle:o.toggleCollapsed,width:o.width})]})}function Cs(){return i.jsx(lt,{children:i.jsx(Ss,{})})}const Is=a.createContext(null);function Es({children:n,vaultId:o="default"}){const s=`rag-vault-reading-mode-${o}`,[e,t]=F(s,"full"),r=a.useCallback(u=>{t(u)},[t]),l=a.useCallback(()=>{t(u=>u==="skim"?"full":"skim")},[t]),c=a.useMemo(()=>({mode:e,setMode:r,toggleMode:l,isSkimMode:e==="skim",isFullMode:e==="full"}),[e,r,l]);return i.jsx(Is.Provider,{value:c,children:n})}const js=new Ye({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}}),Qe=document.getElementById("root");if(!Qe)throw new Error('Root element not found. Ensure index.html has <div id="root"></div>');it.createRoot(Qe).render(i.jsx(a.StrictMode,{children:i.jsx(Ze,{client:js,children:i.jsx(rt,{children:i.jsx(Xt,{children:i.jsx(Et,{children:i.jsx(ct,{children:i.jsx(Mt,{dbId:"default",children:i.jsx(yn,{children:i.jsx(ds,{children:i.jsx(Rn,{children:i.jsx(On,{children:i.jsx(Fn,{children:i.jsx(_n,{children:i.jsx(Es,{children:i.jsx(Wn,{children:i.jsx(Cs,{})})})})})})})})})})})})})})})}));export{Fs as A,Ks as B,Zs as C,$s as D,_s as E,zs as F,Ws as G,Bs as H,ms as K,xt as S,Xs as T,Fe as W,F as a,Qs as b,Pn as c,bn as d,Tn as e,wn as f,Os as g,Rs as h,Ps as i,jt as j,to as k,Ys as l,eo as m,Ms as n,Ds as o,qs as p,Us as q,Hs as r,Ns as s,Vs as t,ze as u,K as v,Gs as w,Js as x,pn as y,Ls as z};
|