@loomcycle/explorer 0.12.0 → 0.13.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.
@@ -0,0 +1,14 @@
1
+ import type { BrowseScope, DocScope } from "../types";
2
+ import type { ExplorerDataLayer } from "../lib/dataLayer";
3
+ import { type TransferRequest, type TransferResult } from "../lib/transfer";
4
+ export interface TransferModalProps {
5
+ data: ExplorerDataLayer;
6
+ scope: DocScope;
7
+ browse?: BrowseScope;
8
+ documentId?: string;
9
+ underPath?: string;
10
+ fromPath: string;
11
+ onClose: () => void;
12
+ onDone: (req: TransferRequest, res: TransferResult) => void;
13
+ }
14
+ export default function TransferModal({ data, scope, browse, documentId, underPath, fromPath, onClose, onDone, }: TransferModalProps): import("react").JSX.Element;
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=require("react/jsx-runtime"),u=require("@loomcycle/client"),d=require("react-markdown");d=s(d,1);let f=require("remark-gfm");f=s(f,1);var p=`loomcycle.explorer.navigator`;function m(e){try{return e?.getItem(`loomcycle.explorer.navigator`)===`stars`?`stars`:`tree`}catch{return`tree`}}function h(e,t){try{e?.setItem(p,t)}catch{}}function g(e){return!!e&&!e.parent_id&&!!e.entity?.natural_key}function _(e){let t=e?.classes;if(!Array.isArray(t))return[];let n=new Set;for(let e of t){let{name:t,kind:r}=e??{};typeof t==`string`&&t!==``&&r!==`document`&&n.add(t)}return[...n].sort((e,t)=>e.localeCompare(t))}function v(e,t){let n=t??``;return n===``||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[n,...e]}var y=4,b=5e3;function x(e,t,n){return{...S(e,n),pathLs:(t,n,r,i,a)=>e.path({op:`ls`,path:t,scope:n,recursive:r,...a?.limit?{limit:a.limit}:{},...a?.cursor?{cursor:a.cursor}:{}},i),pathIsStored:(t,n,r)=>e.path({op:`stat`,path:t,scope:n},r).then(()=>!0,e=>{if(e?.name===`SubstrateToolRefusedError`)return!1;throw e}),documentPath:async(t,n,r)=>{let i;for(let a=0;a<y;a++){let a=await e.path({op:`ls`,path:`/`,scope:n,recursive:!0,kind_filter:`document`,limit:b,...i?{cursor:i}:{}},r),o=(a.entries??[]).find(e=>e.resource_ref?.document_id===t);if(o)return o.full_path;if(i=a.next_cursor||void 0,!i)return}},pathMkdir:(t,n,r)=>e.path({op:`mkdir`,path:t,scope:n},r),pathMv:(t,n,r,i)=>e.path({op:`mv`,path:t,to:n,scope:r},i),pathRm:(t,n,r,i)=>e.path({op:`rm`,path:t,scope:n,recursive:r},i),documentCreate:(t,n,r,i)=>e.document({op:`create_document`,title:t,path:n,scope:r},i),documentDelete:(t,n,r)=>e.document({op:`delete_document`,id:t,scope:n},r),documentGet:(t,n,r)=>e.document({op:`get_document`,id:t,scope:n},r),documentsSummary:(t,n,r)=>e.document({op:`documents_summary`,scope:n,...t.documentIds?{document_ids:t.documentIds}:{},...t.underPath?{under_path:t.underPath}:{}},r),documentQueryChunks:(t,n,r)=>e.document({op:`query_chunks`,document_id:t,scope:n,limit:1e3},r),documentGetChunk:(t,n,r)=>e.document({op:`get_chunk`,id:t,scope:n},r),documentCreateChunk:(t,n,r,i,a,o)=>e.document({op:`create_chunk`,document_id:t,parent_id:n,scope:i,...o?{after_id:o}:{},...r},a),documentReorderChunk:(t,n,r,i)=>e.document({op:`reorder_chunk`,id:t,direction:n,scope:r},i),documentDeleteChunk:(t,n,r)=>e.document({op:`delete_chunk`,id:t,scope:n},r),documentSetAsset:(t,n,r,i,a,o)=>e.document({op:`set_asset`,id:t,media_type:n,data:r,...i?{filename:i}:{},scope:a},o),documentGetEdges:(t,n,r,i)=>e.document({op:`get_edges`,document_id:t,scope:n,...i?.after?{after:i.after}:{}},r),documentGetEdge:(t,n,r)=>e.document({op:`get_edge`,id:t,scope:n},r),documentAcceptStatement:(t,n,r,i)=>e.document({op:`accept_statement`,id:t,scope:n,...i?{reason:i}:{}},r),documentRejectStatement:(t,n,r,i)=>e.document({op:`reject_statement`,id:t,reason:n,scope:r},i),documentListStatements:(t,n,r)=>e.document({op:`list_statements`,scope:t,...r?.status?{status:r.status}:{},...r?.kind?{kind:r.kind}:{},...r?.limit?{limit:r.limit}:{},...r?.after?{after:r.after}:{}},n),documentClassify:(t,n,r,i)=>e.document({op:`classify`,document_id:t,write:n,scope:r},i),documentEntityTypes:(t,n)=>e.document({op:`describe_ontology`,scope:t},n).then(_),documentAcceptClassification:(t,n,r)=>e.document({op:`accept_classification`,document_id:t,scope:n},r),documentUpdateChunk:(t,n,r,i,a)=>e.document({op:`update_chunk`,id:t,revision:n,scope:i,...r},a),documentExportMd:(t,n,r,i)=>e.document({op:`export_md`,document_id:t,scope:n,include_metadata:r},i),documentBacklinks:(t,n,r)=>e.document({op:`backlinks`,id:t,scope:n},r),documentRelated:(t,n,r,i)=>e.document({op:`related`,id:t,scope:n,...i?{limit:i}:{}},r),documentUnlinkedMentions:(t,n,r,i)=>e.document({op:`unlinked_mentions`,id:t,scope:n,...i?{limit:i}:{}},r),documentHistory:(t,n,r,i)=>e.document({op:`history`,id:t,scope:n,...i?{limit:i}:{}},r),documentGetVersion:(t,n,r,i)=>e.document({op:`get_version`,id:t,revision:n,scope:r},i),documentDiff:(t,n,r,i,a)=>e.document({op:`diff`,id:t,from_revision:n,to_revision:r,scope:i},a),documentExportCanvas:(t,n,r)=>e.document({op:`export_canvas`,document_id:t,scope:n},r),...t?{documentAssetObjectUrl:async(e,n,r)=>{let i=new URLSearchParams({scope:n});r?.scopeId&&i.set(`scope_id`,r.scopeId),r?.tenant&&i.set(`tenant`,r.tenant);let a=await t(`/v1/_document/asset/${encodeURIComponent(e)}?${i.toString()}`);if(!a.ok)throw Error(`asset fetch failed: ${a.status}`);let o=await a.blob();return URL.createObjectURL(o)}}:{}}}function S(e,t){let n=e,r=e=>e?.tenant?`?tenant=${encodeURIComponent(e.tenant)}`:``,i={};typeof n.ruleStatements==`function`?i.documentRuleStatements=(e,t)=>n.ruleStatements(e.action,e.ids?{ids:e.ids}:{filter:e.filter},{reason:e.reason,dryRun:e.dry_run,expectCount:e.expect_count,max:e.max,scope:e.scope,scopeId:e.scope_id,tenant:t?.tenant}):t&&(i.documentRuleStatements=(e,n)=>t(`/v1/_statements/rule${r(n)}`,e));let a=(e,t)=>e===`user`&&t?.scopeId?t.scopeId:void 0;return typeof n.revertRuling==`function`?i.documentRevertRuling=(e,t,r)=>n.revertRuling(e,{scope:t,scopeId:a(t,r),tenant:r?.tenant}):t&&(i.documentRevertRuling=(e,n,i)=>{let o=a(n,i);return t(`/v1/_statements/revert${r(i)}`,{ruling_id:e,scope:n,...o?{scope_id:o}:{}})}),i}var C=(0,c.createContext)(null);function w({value:e,children:t}){return(0,l.jsx)(C.Provider,{value:e,children:t})}function T(){let e=(0,c.useContext)(C);if(!e)throw Error(`useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)`);return e}var E=5e3;function D(e){return e===``?`/`:e}function O(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function k(e){let t=[``],n=e.split(`/`).filter(Boolean),r=``;for(let e=0;e<n.length-1;e++)r=`${r}/${n[e]}`,t.push(r);return t}function A(e){return e instanceof Error?e.message:String(e)}function j(e,t){return{entries:[...t,...e.entries??[]],nextCursor:e.next_cursor||void 0,loaded:!0,loading:!1}}var ee=class{data;scope;browse;pageLimit;dirs=new Map;snapshot=new Map;listeners=new Set;inflight=new Map;epoch=new Map;constructor(e,t,n,r=500){this.data=e,this.scope=t,this.browse=n,this.pageLimit=r}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});publish(){this.snapshot=new Map(this.dirs),this.listeners.forEach(e=>e())}set(e,t){this.dirs.set(e,t),this.publish()}track(e,t){let n=t.finally(()=>{this.inflight.get(e)===n&&this.inflight.delete(e)});return this.inflight.set(e,n),n}loadDir(e){return this.inflight.get(e)||(this.dirs.get(e)?.loaded?Promise.resolve():this.fetchFirst(e,this.pageLimit))}reload(e){let t=this.dirs.get(e),n=t?.entries.length??0,r=t?.loaded&&!t.nextCursor?n+this.pageLimit:n;return this.fetchFirst(e,Math.min(E,Math.max(this.pageLimit,r)))}fetchFirst(e,t){let n=(this.epoch.get(e)??0)+1;this.epoch.set(e,n);let r=this.dirs.get(e);this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!0});let i=this.data.pathLs(D(e),this.scope,!1,this.browse,{limit:t}).then(t=>{this.epoch.get(e)===n&&this.set(e,j(t,[]))},t=>{throw this.epoch.get(e)===n&&this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!1,error:A(t)}),t});return this.track(e,i)}loadMore(e){let t=this.inflight.get(e);if(t)return t;let n=this.dirs.get(e);if(!n?.nextCursor)return Promise.resolve();let r=this.epoch.get(e)??0;this.set(e,{...n,loading:!0,error:void 0});let i=this.data.pathLs(D(e),this.scope,!1,this.browse,{limit:this.pageLimit,cursor:n.nextCursor}).then(t=>{this.epoch.get(e)===r&&this.set(e,j(t,n.entries))},t=>{throw this.epoch.get(e)===r&&this.set(e,{...n,loading:!1,error:A(t)}),t});return this.track(e,i)}async reveal(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){for(await this.loadDir(n);;){let t=this.dirs.get(n);if(!t)return!1;if(t.entries.some(t=>t.name===e))break;let r=t.entries[t.entries.length-1];if(!t.nextCursor||r&&r.name>e)return!1;let i=t.nextCursor;if(await this.loadMore(n),this.dirs.get(n)?.nextCursor===i)return!1}n=`${n}/${e}`}return!0}async invalidate(e,t){if(t?.dropSubtree){for(let t of[...this.dirs.keys()])(t===e||t.startsWith(`${e}/`))&&(this.dirs.delete(t),this.epoch.set(t,(this.epoch.get(t)??0)+1),this.inflight.delete(t));this.publish()}let n=k(e).filter(e=>this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}async refresh(e){let t=new Set(e);t.add(``);for(let e of[...this.dirs.keys()])t.has(e)||(this.dirs.delete(e),this.epoch.set(e,(this.epoch.get(e)??0)+1),this.inflight.delete(e));this.publish();let n=[...t].filter(e=>e===``||this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}};async function te(e,t,n,r){let i=[],a;for(;;){let o=await e.pathLs(D(t),n,!0,r,{limit:E,cursor:a});i.push(...o.entries??[]);let s=o.next_cursor||void 0;if(!s||s===a)return i;a=s}}function ne(e){let t=[];for(let n of e){if(n.kind!==`document`)continue;let e=n.resource_ref?.document_id;e&&t.push(e)}return t}function M(e){let t=e.fetch;return new u.LoomcycleClient({baseUrl:e.baseUrl,authToken:e.token||void 0,fetch:(e,n)=>t?t(e,n):fetch(e,n)})}function re(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return t=>{let r={};return e.token&&(r.Authorization=`Bearer ${e.token}`),n(e.baseUrl+t,{headers:r})}}var N=class extends Error{status;code;constructor(e,t,n){super(e),this.name=`RequestError`,this.status=t,this.code=n}};function P(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return async(t,r)=>{let i={"Content-Type":`application/json`,Accept:`application/json`};e.token&&(i.Authorization=`Bearer ${e.token}`);let a=await n(e.baseUrl+t,{method:`POST`,headers:i,body:JSON.stringify(r)}),o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!a.ok){let e=s&&typeof s==`object`?s:{};throw new N(typeof e.error==`string`&&e.error?e.error:`${a.status} ${a.statusText}`.trim(),a.status,typeof e.code==`string`?e.code:void 0)}return s}}function F(e){let{dataLayer:t,client:n,connection:r}=e;return(0,c.useMemo)(()=>t||(n?x(n):r?x(M(r),re(r),P(r)):null),[t,n,r?.baseUrl,r?.token,r?.fetch])}function I({theme:e,dataLayer:t,children:n}){let r=e?{"data-theme":e}:{};return t?(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsx)(w,{value:t,children:n})}):(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsxs)(`div`,{className:`error-banner`,children:[`@loomcycle/explorer: provide a `,(0,l.jsx)(`code`,{children:`connection`}),`, `,(0,l.jsx)(`code`,{children:`client`}),`, or`,` `,(0,l.jsx)(`code`,{children:`dataLayer`}),` prop.`]})})}function L(e,t,n){let r=e[e.length-1];return[...r&&r.documentId===t.documentId?[...e.slice(0,-1),{...r,...R(t)}]:[...e,t],n]}function ie(e,t){return t<0||t>=e.length-1?e:e.slice(0,t+1)}function ae(e,t,n){let r=e[e.length-1];if(!r||r.documentId!==t)return e;let i={...r,...R(n)};return i.title===r.title&&i.path===r.path?e:[...e.slice(0,-1),i]}function R(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function z(e){return e.title?e.title:e.path?e.path.slice(e.path.lastIndexOf(`/`)+1)||e.path:e.documentId.slice(0,8)}function B(e,t=4){let n=Array.from({length:e},(e,t)=>({kind:`crumb`,index:t}));if(e<=t||t<3)return n;let r=t-1,i=Array.from({length:e-1-r},(e,t)=>t+1);return[n[0],{kind:`gap`,hidden:i},...n.slice(e-r)]}function oe(e,t){for(let n of e.values()){let e=n.entries.find(e=>V(e)===t);if(e)return e.full_path}}function V(e){if(e.kind===`document`)return e.resource_ref?.document_id||void 0}function se(e,t){return t&&e.some(e=>e.id===t)?t:e.find(e=>!e.parent_id)?.id}function ce({trail:e,onJump:t}){let[n,r]=(0,c.useState)(!1);if(e.length<2)return null;let i=e.length-1,a=e[i-1],o=B(e.length,n?e.length:void 0);return(0,l.jsxs)(`nav`,{className:`doc-trail`,"aria-label":`Documents you came through`,children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-back`,onClick:()=>t(i-1),title:`Back to ${z(a)}`,children:`← Back`}),(0,l.jsx)(`ol`,{className:`doc-trail-list`,children:o.map(n=>n.kind===`gap`?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-gap`,onClick:()=>r(!0),title:`Show ${n.hidden.length} more: ${n.hidden.map(t=>z(e[t])).join(` › `)}`,"aria-label":`Show ${n.hidden.length} hidden documents`,children:`…`})},`gap`):n.index===i?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`page`,title:z(e[i]),children:z(e[i])})},n.index):(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>t(n.index),title:z(e[n.index]),children:z(e[n.index])})},n.index))})]})}var H=6;function le({children:e,defaultLeftWidth:t=380,minLeftWidth:n=180,minRightWidth:r=240,storageKey:i,className:a,hideRight:o=!1}){let s=()=>{if(i){let e=localStorage.getItem(i),t=e?parseInt(e,10):NaN;if(Number.isFinite(t)&&t>=n)return t}return t},[u,d]=(0,c.useState)(s),[f,p]=(0,c.useState)(i);f!==i&&(p(i),d(s()));let m=(0,c.useRef)(null),[h,g]=(0,c.useState)(!1);(0,c.useEffect)(()=>{i&&!h&&f===i&&localStorage.setItem(i,String(Math.round(u)))},[i,f,u,h]);let _=(0,c.useCallback)(e=>{e.preventDefault(),g(!0),e.target.setPointerCapture(e.pointerId)},[]),v=(0,c.useCallback)(e=>{if(!h||!m.current)return;let t=m.current.getBoundingClientRect(),i=e.clientX-t.left,a=t.width-r-H;d(Math.max(n,Math.min(i,a)))},[h,n,r]),y=(0,c.useCallback)(e=>{g(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:m,className:`splitter ${a??``} ${h?`dragging`:``}`,style:{gridTemplateColumns:o?`1fr 0 0`:`min(${u}px, calc(100% - ${r+H}px)) ${H}px 1fr`},children:[(0,l.jsx)(`div`,{className:`splitter-pane splitter-left`,children:e[0]}),(0,l.jsx)(`div`,{hidden:o,className:`splitter-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-valuenow":Math.round(u),onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:y}),(0,l.jsx)(`div`,{className:`splitter-pane splitter-right`,hidden:o,children:e[1]})]})}var ue=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`];function U(e){return ue.includes(e)}function de(e){return new Promise((t,n)=>{if(!U(e.type)){n(Error(`unsupported image type "${e.type||`unknown`}" (png, jpeg, gif, webp only)`));return}let r=new FileReader;r.onerror=()=>n(r.error??Error(`failed to read file`)),r.onload=()=>{let i=String(r.result??``),a=i.indexOf(`,`);a<0?n(Error(`could not decode image data`)):t({mediaType:e.type,data:i.slice(a+1)})},r.readAsDataURL(e)})}function fe(e){if(!e)return null;for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`file`&&U(n.type)){let e=n.getAsFile();if(e)return e}}return null}var pe=20;async function me(e,t,n,r,i=20){let a=[],o;for(let s=0;s<i;s++){let i=await e.documentGetEdges(t,n,r,o?{after:o}:void 0);if(o&&i.next_cursor===o)return{edges:a,incomplete:!0};if(a.push(...i.edges??[]),!i.truncated)return{edges:a,incomplete:!1};if(!i.next_cursor)return{edges:a,incomplete:!0};o=i.next_cursor}return{edges:a,incomplete:!0}}function he(e,t){if(!t)return[];let n=new Map(e.map(e=>[e.id,e])),r=new Set([t]),i=[],a=n.get(t)?.parent_id;for(;a&&!r.has(a);){let e=n.get(a);if(!e)break;r.add(a),i.push(e),a=e.parent_id}return i.reverse()}var ge=new Set([`manual`,`wikilink`]),_e=280;function W(e){return e.status&&e.status!==`asserted`?e.status:void 0}function ve(e){return e.method&&!ge.has(e.method)?e.method:void 0}function ye(e){return e.status===`proposed`&&!!e.id}function G(e){return new Date(Math.floor(e/1e6)).toISOString().slice(0,10)}function be(e){let t=e.valid_at==null?void 0:G(e.valid_at),n=e.invalid_at==null?void 0:G(e.invalid_at);if(t&&n)return`valid ${t} → ${n}`;if(t)return`valid from ${t}`;if(n)return`valid until ${n}`}function xe(e){if(e.judged_at==null)return;let t=`judged by ${e.judged_by||`a judge`} on ${G(e.judged_at)}`;return e.judge_reason?`${t}: ${e.judge_reason}`:t}function Se(e,t=3){let n=(e.evidence??[]).slice(0,t),r=Math.max(e.evidence_count??0,e.evidence?.length??0);return{rows:n,more:Math.max(0,r-n.length)}}function Ce(e,t=_e){let n=e.replace(/\s+/g,` `).trim();return n.length>t?n.slice(0,t-1)+`…`:n}var we=1e3,Te=3,K=1e3;function Ee(e){return!!e&&typeof e==`object`&&e.code===`queue_changed`}async function De(e,t,n={}){let r={action:t.action,...t.ids?{ids:t.ids}:{filter:t.filter??{}},...t.reason?{reason:t.reason}:{},...t.scope&&t.scope!==`tenant`?{scope:t.scope}:{},...t.scope===`user`&&t.scopeId?{scope_id:t.scopeId}:{}},i={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[]},a=async()=>{let t=await e.rule({...r,dry_run:!0});return i.skipped=t.skipped,t},o=async(e,t)=>!n.confirm||await n.confirm(e,t)?(i.total=i.ruled+e.matched,!0):(i.cancelled=!0,!1),s;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`first`))return i;let c=0;for(let t=0;t<K&&s.to_rule!==0;t++){let t;try{t=await e.rule({...r,dry_run:!1,expect_count:s.matched})}catch(e){if(!Ee(e)||c>=3)return i.error=e,i;c++;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`queue_changed`))return i;continue}t.ruling_id&&i.rulingIds.push(t.ruling_id),i.ruled+=t.ruled,i.failed+=t.failed;for(let e of t.items??[])e.error&&i.failures.push(e);if(n.onProgress?.({ruled:i.ruled,failed:i.failed,total:i.total,chunks:i.rulingIds.length}),t.ruled===0||t.matched<=t.selected)break;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0)break;if(s.matched>i.total-i.ruled&&!await o(s,`grew`))return i}return i}async function q(e,t){let n={reverted:0,changed:0,errors:[]};for(let r of[...t].reverse())try{let t=await e(r);n.reverted+=t.reverted,n.changed+=t.changed}catch(e){n.errors.push(e instanceof Error?e.message:String(e))}return n}function J(e){return Math.max(1,Math.ceil(e/we))}function Y(e){return e===`tenant`||e===`user`?e:void 0}function Oe(e,t){return e.documentRuleStatements?Y(t):void 0}function ke(e,t){return e.filter(e=>ye(e)&&!!e.id&&e.from_document_id===t)}function Ae(e,t,n,r){return e?{proposals:t,scope:e,incomplete:n,onChanged:r}:void 0}function X(e,t,n){return e.documentRuleStatements?De({rule:n=>e.documentRuleStatements(n,t.browse)},{action:t.action,...t.ids&&t.ids.length>0?{ids:t.ids}:{filter:{from_document_id:t.documentId}},...t.reason?{reason:t.reason}:{},scope:t.scope,...t.scope===`user`&&t.browse?.scopeId?{scopeId:t.browse.scopeId}:{}},n):Promise.reject(Error(`this data layer cannot rule in bulk`))}function Z(e,t){let n=e=>e.toLocaleString(`en-US`),r=[`${e===`accept`?`Accepted`:`Rejected`} ${n(t.ruled)} statement${t.ruled===1?``:`s`}`];return t.failed>0&&r.push(`${n(t.failed)} did not take the ruling`),t.skipped>0&&r.push(`${n(t.skipped)} skipped: not yours to rule`),r.join(`; `)+`.`}var Q={"doc.rfc.draft":`#c99a3a`,"doc.rfc.review":`#6a7bd6`,"doc.rfc.confirmed":`#3a9ad6`,"doc.rfc.done":`#3aa06a`,"doc.plan.draft":`#c99a3a`,"doc.plan.review":`#6a7bd6`,"doc.plan.confirmed":`#3a9ad6`,"doc.plan.done":`#3aa06a`,"doc.document.done":`#3aa06a`,"doc.research.done":`#8a6ad6`,"doc.publication.draft":`#c99a3a`,"chunk.draft":`#c99a3a`,"chunk.review":`#6a7bd6`,"chunk.confirmed":`#3a9ad6`,"chunk.done":`#3aa06a`,"chunk.backlog":`#8a8f98`,"chunk.implementation":`#d1863a`,"chunk.merged":`#3aa06a`},je=.16;function Me(e){return e&&Object.keys(e).length>0?e:Q}function Ne(e,t,n){let r=e??``,i=t??``;if(r&&i&&n[`doc.${r}.${i}`])return n[`doc.${r}.${i}`];if(r&&n[`doc.${r}`])return n[`doc.${r}`]}function Pe(e,t){let n=e??``;return n?t[`chunk.${n}`]:void 0}function Fe(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!t)return;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`rgba(${parseInt(n.slice(0,2),16)}, ${parseInt(n.slice(2,4),16)}, ${parseInt(n.slice(4,6),16)}, ${je})`}function $(e){if(!e)return;let t=Fe(e);if(t)return{background:t,borderLeft:`3px solid ${e}`}}async function Ie(e){try{return typeof navigator>`u`||!navigator.clipboard?!1:(await navigator.clipboard.writeText(e),!0)}catch{return!1}}function Le({value:e,label:t,compact:n,title:r}){let[i,a]=(0,c.useState)(`idle`),o=async t=>{t.stopPropagation(),t.preventDefault();let n=await Ie(e);a(n?`copied`:`error`),window.setTimeout(()=>a(`idle`),n?1200:1500)},s=i===`copied`?`✓`:i===`error`?`✗`:`⎘`,u=r??`Copy ${t??`id`}: ${e}`,d=(0,l.jsx)(`button`,{type:`button`,className:`id-copy-btn id-copy-${i}`,onClick:o,title:u,"aria-label":u,children:s});return n?d:(0,l.jsxs)(`span`,{className:`id-copy`,children:[t&&(0,l.jsx)(`span`,{className:`id-copy-label`,children:t}),(0,l.jsx)(`code`,{className:`id-copy-value`,title:e,children:e}),d]})}function Re(e){let t=new Map;e.forEach(e=>t.set(e.id,{row:e,children:[]}));let n=[];e.forEach(e=>{let r=t.get(e.id);e.parent_id&&t.has(e.parent_id)?t.get(e.parent_id).children.push(r):n.push(r)});let r=e=>{e.sort((e,t)=>e.row.position-t.row.position),e.forEach(e=>r(e.children))};return r(n),n}function ze(e){return e===`image`?`🖼`:e===`mermaid`?`📊`:``}function Be(e,t){for(let n of e){if(n.row.id===t)return n;let e=Be(n.children,t);if(e)return e}}function Ve({tree:e,selectedId:t,onSelect:n,colorEnabled:r,scheme:i,linkedIds:a}){let[o,s]=(0,c.useState)(()=>new Map),u=(0,c.useCallback)(e=>{s(t=>{let n=new Map(t);return n.set(e,t.get(e)===!1),n})},[]);(0,c.useEffect)(()=>{if(!t)return;let n=He(e,t);n.length!==0&&s(e=>{let t=!1,r=new Map(e);for(let e of n)r.get(e)===!1&&(r.set(e,!0),t=!0);return t?r:e})},[e,t]);let d=r?Me(i):null;return e.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`No chunks.`})}):(0,l.jsx)(`ul`,{className:`tree chunk-tree`,children:e.map(e=>(0,l.jsx)(Ue,{node:e,expanded:o,toggle:u,selectedId:t,onSelect:n,tintScheme:d,linkedIds:a},e.row.id))})}function He(e,t){let n=[],r=(e,i)=>{for(let a of e){if(a.row.id===t)return n.push(...i),!0;if(r(a.children,[...i,a.row.id]))return!0}return!1};return r(e,[]),n}function Ue({node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,linkedIds:o}){let s=e.children.length>0,c=t.get(e.row.id)!==!1,u=r===e.row.id,d=a?$(Pe(e.row.status,a)):void 0,f=o?.has(e.row.id);return(0,l.jsxs)(`li`,{className:`node chunk-node ${u?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row chunk-row`,style:d,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":c?`collapse`:`expand`,disabled:!s,onClick:t=>{t.stopPropagation(),s&&n(e.row.id)},children:s?c?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`chunk-link`,onClick:()=>i(e),title:e.row.title,children:[ze(e.row.type)&&(0,l.jsx)(`span`,{className:`chunk-type-icon`,"aria-hidden":!0,children:ze(e.row.type)}),(0,l.jsx)(`span`,{className:`chunk-title`,children:e.row.title||`(untitled)`}),e.row.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:e.row.type}),e.row.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:e.row.status}),f&&(0,l.jsx)(`span`,{className:`chunk-link-badge`,title:`Has cross-reference links`,"aria-label":`linked`,children:`🔗`})]}),(0,l.jsx)(Le,{value:e.row.id,compact:!0,title:`Copy chunk id: ${e.row.id}`})]}),s&&c&&(0,l.jsx)(`ul`,{className:`children chunk-children`,children:e.children.map(e=>(0,l.jsx)(Ue,{node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,linkedIds:o},e.row.id))})]})}var We=0;function Ge(e){let t=e?.closest(`g.node`);return t?/flowchart-(.+)-\d+$/.exec(t.id)?.[1]:void 0}function Ke({code:e,onNodeClick:t}){let n=(0,c.useRef)(null),[r,i]=(0,c.useState)({});return(0,c.useEffect)(()=>{let t=!1;return(async()=>{try{let r=(await import(`mermaid`)).default,a=n.current?.closest(`[data-theme]`)?.getAttribute(`data-theme`),o=!a||a===`dark`;r.initialize({startOnLoad:!1,theme:o?`dark`:`default`,securityLevel:`strict`});let{svg:s}=await r.render(`lc-mmd-${We++}`,e);t||i({svg:s})}catch{t||i({err:!0})}})(),()=>{t=!0}},[e]),r.err?(0,l.jsx)(`pre`,{className:`md-pre md-mermaid-error`,title:`diagram failed to render`,children:(0,l.jsx)(`code`,{children:e})}):r.svg?(0,l.jsx)(`div`,{ref:n,className:t?`md-mermaid md-mermaid-nav`:`md-mermaid`,onClick:t&&(e=>{let n=Ge(e.target);n&&t(n)}),dangerouslySetInnerHTML:{__html:r.svg}}):(0,l.jsx)(`div`,{ref:n,className:`md-mermaid md-mermaid-loading`,children:`rendering diagram…`})}function qe({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=T(),[o,s]=(0,c.useState)(e.title),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(e.status??``),[m,h]=(0,c.useState)(e.body??``),[g,_]=(0,c.useState)(e.fields?JSON.stringify(e.fields,null,2):``),[v,y]=(0,c.useState)((e.tags??[]).join(`, `)),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,E]=(0,c.useState)(!1),D=u===`mermaid`,O=u===`image`||!!e.asset,[k,A]=(0,c.useState)(m);(0,c.useEffect)(()=>{if(!D)return;let e=setTimeout(()=>A(m),400);return()=>clearTimeout(e)},[m,D]);let j=async o=>{C(null),x(!0);try{let{mediaType:s,data:c}=await de(o);i(await a.documentSetAsset(e.id,s,c,o.name,t,n)),r()}catch(e){C(e instanceof Error?e.message:String(e)),x(!1)}},ee=D?`Mermaid source`:O?`Caption (optional)`:`Body (Markdown)`;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal chunk-editor`,onClick:e=>e.stopPropagation(),onSubmit:async s=>{s.preventDefault(),C(null),E(!1);let c={body:m,title:o,type:u,status:f,tags:v.split(`,`).map(e=>e.trim()).filter(e=>e!==``)};if(g.trim()!==``)try{c.fields=JSON.parse(g)}catch{C(`fields must be valid JSON`);return}x(!0);try{i(await a.documentUpdateChunk(e.id,e.revision,c,t,n)),r()}catch(e){let t=e instanceof Error?e.message:String(e);C(t),E(/revision conflict/i.test(t)),x(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:`Edit chunk`}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:b,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:b,children:b?`saving…`:`save`})]})]}),S&&(0,l.jsxs)(`div`,{className:`modal-err`,children:[S,w&&` — reopen the chunk to load the latest, then reapply your edit.`]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Title`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:o,onChange:e=>s(e.target.value)})]}),(0,l.jsxs)(`div`,{className:`chunk-editor-row`,children:[(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:u,placeholder:`(none)`,onChange:e=>d(e.target.value)})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Status`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:f,placeholder:`(none)`,onChange:e=>p(e.target.value)})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Tags`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:v,placeholder:`comma-separated, nest with a slash: area/sub, priority/high`,onChange:e=>y(e.target.value)})]}),O&&(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Replace image`}),(0,l.jsx)(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:b,onChange:e=>{let t=e.target.files?.[0];t&&j(t)}})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:ee}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-body-input`,rows:D?8:12,value:m,onChange:e=>h(e.target.value)})]}),D&&(0,l.jsxs)(`div`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Preview`}),(0,l.jsx)(`div`,{className:`chunk-mermaid-preview`,children:k.trim()?(0,l.jsx)(Ke,{code:k}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(enter Mermaid source above)`})})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Fields (JSON, optional)`}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-fields-input`,rows:4,value:g,placeholder:`{}`,onChange:e=>_(e.target.value)})]})]})})}function Je({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=T(),[o,s]=(0,c.useState)(null),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(null);(0,c.useEffect)(()=>{let e=!1;return a.documentEntityTypes?.(t,n).then(t=>{e||s(t)}).catch(t=>{e||h(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[a,t,n]);let y=o?v(o,e.type):[],b=u.toLowerCase()===(e.type??``).toLowerCase();return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async o=>{if(o.preventDefault(),!(b||f)){h(null),p(!0);try{let o=await a.documentUpdateChunk(e.id,e.revision,{type:u},t,n);if(i(o),o.not_announced){_(o.not_announced),p(!1);return}r()}catch(e){h(e instanceof Error?e.message:String(e)),p(!1)}}},children:[(0,l.jsx)(`h3`,{children:`Change type`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`“`,e.title||`(untitled)`,`” is a subject (`,(0,l.jsx)(`code`,{children:e.entity?.natural_key}),`). Its key stays as it is; relations about it are re-checked against the new type.`]}),m&&(0,l.jsx)(`div`,{className:`modal-err`,children:m}),g?(0,l.jsxs)(`div`,{className:`modal-err`,children:[`The type was changed, but subscribers were not told: `,g]}):(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),o===null?(0,l.jsx)(`span`,{className:`doc-empty-body`,children:m?``:`loading types…`}):(0,l.jsx)(`select`,{className:`path-modal-input`,value:u,disabled:f,onChange:e=>d(e.target.value),children:y.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:f,children:g?`close`:`cancel`}),!g&&(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:f||b||o===null,children:f?`saving…`:`change type`})]})]})})}function Ye(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Xe(e){if(!e||typeof e!=`object`)return;let t=e.classification;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t,r={};return typeof n.by==`string`&&(r.by=n.by),typeof n.at==`number`&&(r.at=n.at),typeof n.applied_type==`string`&&n.applied_type&&(r.applied_type=n.applied_type),typeof n.proposed_type==`string`&&n.proposed_type&&(r.proposed_type=n.proposed_type),n.proposed_fields&&typeof n.proposed_fields==`object`&&!Array.isArray(n.proposed_fields)&&(r.proposed_fields=n.proposed_fields),Ye(n.proposed_tags)&&(r.proposed_tags=n.proposed_tags),Ye(n.statements)&&(r.statements=n.statements),r}function Ze(e){let t=Xe(e);if(!t)return;let n=t.proposed_tags??[],r=t.statements?.length??0;if(t.proposed_type||n.length!==0||r!==0)return{proposedType:t.proposed_type,proposedTags:n,statementCount:r}}function Qe(e){let t=e.write===`report`;switch(e.result){case`classified`:return t?`would be classified`:`classified`;case`proposed`:return t?`would be proposed for review`:`proposed — waits for review`;case`kept`:return`kept — the type was set by hand`;case`unclassified`:return`unclassified — nothing decided`;default:return String(e.result)}}function $e(e){if(!e.class)return;if(e.result===`kept`)return`not applied`;let t=e.write===`report`;return e.live?t?`would be applied`:`applied`:t?`would be proposed`:`proposed`}function et(e){return e.write===`report`?e.result===`classified`||e.result===`proposed`||(e.concepts?.length??0)>0||(e.issued_by?.length??0)>0:!1}function tt(e){return e==null||!Number.isFinite(e)?``:`${Math.round(e*100)}%`}var nt={rules:`Rules`,vote:`Neighbourhood vote`,model:`Model`};function rt(e){return nt[e]??e}function it(e){let t=[];e.quote&&t.push(e.from?`“${e.quote}” (${e.from})`:`“${e.quote}”`),e.votes!=null&&t.push(`${e.votes} vote${e.votes===1?``:`s`}`);let n=tt(e.share);return n&&t.push(n),t.join(` · `)}function at(e){return{label:rt(e.step),...e.chosen?{chosen:e.chosen}:{},...e.method?{method:e.method}:{},...e.neighbours?{neighbours:e.neighbours}:{},...e.reason?{reason:e.reason}:{},candidates:(e.candidates??[]).map(e=>({class:e.class,detail:it(e)}))}}function ot(e){let t=[];e.type&&t.push(`type ${e.type}`);let n=e.accepted_statements?.length??0;n>0&&t.push(`${n} statement${n===1?``:`s`}`),e.tags&&e.tags.length>0&&t.push(`tags ${e.tags.join(`, `)}`);let r=[];e.type_pending&&r.push(`The proposed class stays pending: another document already holds its identity.`),e.skipped_type&&r.push(`Class ${e.skipped_type} was not applied: it is not a declared document class.`);let i=e.skipped_statements?.length??0;return i>0&&r.push(`${i} statement${i===1?` was`:`s were`} skipped (already ruled on, or not this document's proposal).`),e.skipped_tags&&e.skipped_tags.length>0&&r.push(`Tags not applied (not concepts of the ontology): ${e.skipped_tags.join(`, `)}.`),r.push(...e.warnings??[]),{applied:t.length>0?`Accepted ${t.join(`, `)}.`:`Nothing was accepted.`,notices:r}}function st(e){let t=e instanceof Error?e.message:String(e);return t.includes(`nothing_pending`)?`Nothing is pending for this document — it may already have been accepted.`:t}function ct({documentId:e,scope:t,browse:n,rootFields:r,requestKey:i,onClose:a,onChanged:o}){let s=T(),[u,d]=(0,c.useState)(null),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(!1),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),S=(0,c.useMemo)(()=>s.documentAcceptClassification?Ze(r):void 0,[s,r]);(0,c.useEffect)(()=>{if(i===0||!s.documentClassify)return;let r=!1;return p(!0),h(null),d(null),s.documentClassify(e,`report`,t,n).then(e=>!r&&d(e)).catch(e=>!r&&h(st(e))).finally(()=>!r&&p(!1)),()=>{r=!0}},[s,e,t,n,i]);let C=async()=>{if(s.documentClassify){p(!0),h(null);try{d(await s.documentClassify(e,`propose`,t,n)),o()}catch(e){h(st(e))}finally{p(!1)}}},w=async()=>{if(s.documentAcceptClassification){_(!0),y(null);try{x(await s.documentAcceptClassification(e,t,n)),o()}catch(e){y(st(e))}finally{_(!1)}}},E=i>0;if(!E&&!S&&!b&&!v)return null;let D=b?ot(b):void 0;return(0,l.jsxs)(`div`,{className:`doc-classify`,children:[S&&(0,l.jsxs)(`div`,{className:`doc-classify-pending`,children:[(0,l.jsx)(`span`,{className:`doc-classify-label`,children:`Pending classification`}),S.proposedType&&(0,l.jsxs)(`span`,{children:[`class `,(0,l.jsx)(`strong`,{children:S.proposedType})]}),S.proposedTags.length>0&&(0,l.jsxs)(`span`,{children:[`tags`,` `,S.proposedTags.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e))]}),S.statementCount>0&&(0,l.jsxs)(`span`,{children:[S.statementCount,` proposed statement`,S.statementCount===1?``:`s`]}),(0,l.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>void w(),children:g?`Accepting…`:`Accept`})]}),v&&(0,l.jsxs)(`div`,{className:`doc-classify-err`,role:`alert`,children:[v,(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>y(null),"aria-label":`Dismiss`,children:`×`})]}),D&&(0,l.jsxs)(`div`,{className:`doc-classify-notice`,role:`status`,children:[(0,l.jsx)(`span`,{children:D.applied}),D.notices.map((e,t)=>(0,l.jsx)(`span`,{className:`doc-classify-warn`,children:e},t)),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>x(null),"aria-label":`Dismiss`,children:`×`})]}),E&&(0,l.jsxs)(`div`,{className:`doc-classify-panel`,children:[(0,l.jsxs)(`div`,{className:`doc-classify-head`,children:[(0,l.jsx)(`h4`,{children:`Classify`}),u&&(0,l.jsx)(`span`,{className:`doc-classify-result ${u.result}`,children:Qe(u)}),u?.write===`report`&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:`report only — nothing written`}),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:a,"aria-label":`Close`,children:`×`})]}),!u&&!m&&(0,l.jsx)(`p`,{className:`doc-classify-hint`,children:`Classifying…`}),m&&(0,l.jsx)(`p`,{className:`doc-classify-err`,role:`alert`,children:m}),u&&(0,l.jsx)(lt,{answer:u}),u&&et(u)&&(0,l.jsx)(`div`,{className:`doc-classify-actions`,children:(0,l.jsx)(`button`,{type:`button`,disabled:f,onClick:()=>void C(),title:`Apply a unique rule match to the document; file everything else for review`,children:f?`Applying…`:`Apply`})})]})]})}function lt({answer:e}){let t=$e(e),n=Object.entries(e.fields??{}),r=e.issued_by??[],i=e.concepts??[],a=(e.steps??[]).map(at),o=e.statements?.length??0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`dl`,{className:`doc-classify-rows`,children:[e.class&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`class`}),(0,l.jsxs)(`dd`,{children:[(0,l.jsx)(`strong`,{children:e.class}),t&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` (`,t,`)`]})]})]}),e.work_key&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`work key`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:e.work_key})]}),n.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`fields`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:n.map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`).join(` · `)})]}),r.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`issued by`}),(0,l.jsx)(`dd`,{children:r.map((e,t)=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.quote,children:[e.instance,e.quote&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` “`,e.quote,`”`]})]},`${e.instance}-${t}`))})]}),i.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`concepts`}),(0,l.jsx)(`dd`,{children:i.map(e=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.tag,children:[e.concept,(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,tt(e.share)]})]},e.tag))})]}),o>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`statements`}),(0,l.jsxs)(`dd`,{children:[o,` written`,e.statements.some(e=>e.status===`proposed`)&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` (proposed ones wait for review)`})]})]})]}),a.length>0&&(0,l.jsx)(`ol`,{className:`doc-classify-steps`,children:a.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`span`,{className:`doc-classify-step`,children:e.label}),e.method&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` [`,e.method,`]`]}),e.chosen?(0,l.jsxs)(l.Fragment,{children:[` → `,(0,l.jsx)(`strong`,{children:e.chosen})]}):(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` no choice`}),e.neighbours!=null&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` · `,e.neighbours,` neighbours`]}),e.reason&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` — `,e.reason]}),e.candidates.length>0&&(0,l.jsxs)(`details`,{className:`doc-classify-candidates`,children:[(0,l.jsxs)(`summary`,{children:[e.candidates.length,` candidate`,e.candidates.length===1?``:`s`]}),(0,l.jsx)(`ul`,{children:e.candidates.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`strong`,{children:e.class}),e.detail&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,e.detail]})]},`${e.class}-${t}`))})]})]},`${e.label}-${t}`))}),e.warnings&&e.warnings.length>0&&(0,l.jsx)(`ul`,{className:`doc-classify-warnings`,children:e.warnings.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-classify-warn`,children:e},t))})]})}function ut(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((e??``).trim());if(!t)return`#888888`;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`#`+n.toLowerCase()}function dt({documentId:e,rootChunkId:t,docType:n,docStatus:r,chunkStatuses:i,scope:a,browse:o,onClose:s,onSaved:u}){let d=T(),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(!1),[g,_]=(0,c.useState)({}),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),w=(0,c.useMemo)(()=>{let e=new Set(Object.keys(Q));n&&e.add(`doc.${n}.${r||`draft`}`);for(let t of i)t&&e.add(`chunk.${t}`);return[...e].sort()},[n,r,i]);(0,c.useEffect)(()=>{let e=!1;return d.documentGetChunk(t,a,o).then(t=>{if(e)return;p(t);let n=t.fields??{};h(n.color_enabled===!0);let r=n.color_scheme??{};_({...Q,...r})}).catch(t=>!e&&C(t instanceof Error?t.message:String(t))),()=>{e=!0}},[d,t,a,o]);let E=(e,t)=>_(n=>({...n,[e]:t})),D=e=>({...e??{},color_enabled:m,color_scheme:g}),O=async()=>{if(f){y(!0),C(null),x(null);try{await d.documentUpdateChunk(t,f.revision,{fields:D(f.fields)},a,o),u(),s()}catch(e){C(e instanceof Error?e.message:String(e)),y(!1)}}},k=async()=>{if(!n)C(`this document has no type to match`);else{y(!0),C(null),x(null);try{let{documents:t}=await d.documentsSummary({underPath:`/`},a,o),r=(t??[]).filter(t=>t.type===n&&t.document_id!==e&&t.root_chunk_id),i=0;for(let e of r)try{let t=await d.documentGetChunk(e.root_chunk_id,a,o);await d.documentUpdateChunk(e.root_chunk_id,t.revision,{fields:D(t.fields)},a,o),i++}catch{}x(`Applied to ${i} other ${n} document(s).`),u()}catch(e){C(e instanceof Error?e.message:String(e))}finally{y(!1)}}},A=w.filter(e=>e.startsWith(`doc.`)),j=w.filter(e=>e.startsWith(`chunk.`));return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:s,children:(0,l.jsxs)(`div`,{className:`modal scheme-editor`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`scheme-editor-head`,children:[(0,l.jsx)(`h3`,{children:`Document colors`}),(0,l.jsxs)(`div`,{className:`scheme-editor-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:s,disabled:v,children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`primary`,onClick:()=>void O(),disabled:v||!f,children:v?`saving…`:`save`})]})]}),S&&(0,l.jsx)(`div`,{className:`modal-err`,children:S}),f?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`label`,{className:`scheme-toggle`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked)}),(0,l.jsx)(`span`,{children:`Enable coloring for this document`})]}),(0,l.jsx)(`p`,{className:`modal-context`,children:`Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable.`}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Document (type · status)`}),A.map(e=>(0,l.jsx)(ft,{label:e.slice(4),value:g[e],onChange:t=>E(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Chunks (status)`}),j.map(e=>(0,l.jsx)(ft,{label:e.slice(6),value:g[e],onChange:t=>E(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-editor-foot`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>void k(),disabled:v||!n,title:n?`Apply this palette to every other ${n} document`:`This document has no type`,children:[`copy to all `,n||`same-type`,` documents`]}),b&&(0,l.jsx)(`span`,{className:`scheme-status`,children:b})]})]}):(0,l.jsx)(`p`,{className:`modal-context`,children:`Loading…`})]})})}function ft({label:e,value:t,onChange:n}){let r=ut(t);return(0,l.jsxs)(`label`,{className:`scheme-row`,children:[(0,l.jsx)(`input`,{type:`color`,value:r,onChange:e=>n(e.target.value)}),(0,l.jsx)(`span`,{className:`scheme-key`,children:e}),(0,l.jsx)(`code`,{className:`scheme-hex`,children:r})]})}function pt({id:e,title:t,targetDocumentId:n,documentId:r,onSelectChunk:i,onOpenDocument:a}){let o=t||e.slice(0,8);return!n||n===r?(0,l.jsx)(`button`,{type:`button`,className:`doc-ref-target`,onClick:()=>i(e),children:o}):a?(0,l.jsxs)(`button`,{type:`button`,className:`doc-ref-target external`,title:`In another document — opens it at this chunk`,onClick:()=>a(n,e,t),children:[o,` ↗`]}):(0,l.jsxs)(`span`,{className:`doc-ref-target external`,title:`In another document`,children:[o,` ↗`]})}function mt({statement:e}){let t=W(e),n=ve(e),r=xe(e),i=be(e),{rows:a,more:o}=Se(e);return(0,l.jsxs)(l.Fragment,{children:[t&&(0,l.jsx)(`span`,{className:`doc-stmt-status ${t}`,children:t}),n&&(0,l.jsx)(`span`,{className:`doc-stmt-method`,title:`how this relation was made`,children:n}),r&&(0,l.jsx)(`span`,{className:`doc-stmt-verdict`,title:r,children:`judged`}),i&&(0,l.jsx)(`span`,{className:`doc-stmt-valid`,children:i}),a.length>0&&(0,l.jsxs)(`ul`,{className:`doc-stmt-evidence`,children:[a.map(e=>(0,l.jsxs)(`li`,{title:e.quote,children:[`“`,Ce(e.quote),`”`,e.stale&&(0,l.jsx)(`span`,{className:`doc-stmt-stale`,children:` (source changed)`})]},e.id)),o>0&&(0,l.jsxs)(`li`,{className:`doc-stmt-more`,children:[`+`,o,` more`]})]})]})}function ht({id:e,onRule:t}){let[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=async n=>{s(!0),d(null);try{await t(e,n,n?void 0:i.trim()),r(!1),a(``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{s(!1)}};return(0,l.jsxs)(`span`,{className:`doc-stmt-review`,children:[n?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:i,disabled:o,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i.trim()&&f(!1),e.key===`Escape`&&r(!1)},autoFocus:!0}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:o||!i.trim(),onClick:()=>void f(!1),children:`Reject`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!1),children:`Cancel`})]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>void f(!0),children:`Accept`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!0),children:`Reject…`})]}),u&&(0,l.jsx)(`span`,{className:`doc-stmt-err`,role:`alert`,children:u})]})}var gt=3;function _t({documentId:e,proposals:t,incomplete:n,scope:r,browse:i,onChanged:a,onSelectChunk:o,onOpenDocument:s}){let u=T(),[d,f]=(0,c.useState)(new Set),[p,m]=(0,c.useState)({kind:`idle`}),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useRef)(null),S=new Set(t.map(e=>e.id)),C=[...d].filter(e=>S.has(e)),w=p.kind!==`idle`&&p.kind!==`reason`,E=(e,t)=>{v(null),b(null),e===`reject`?m({kind:`reason`,action:e,all:t}):D(e,t,``)},D=async(t,n,o)=>{m({kind:`counting`,action:t,all:n});let s;try{s=await X(u,{documentId:e,action:t,ids:n?void 0:C,reason:o.trim()||void 0,scope:r,browse:i},{confirm:(e,r)=>new Promise(i=>{x.current=i,m({kind:`confirm`,action:t,all:n,dry:e,changed:r!==`first`})}),onProgress:e=>m({kind:`ruling`,action:t,ruled:e.ruled,total:e.total})})}catch(e){s={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[],error:e}}x.current=null,m({kind:`idle`}),g(``),s.rulingIds.length>0?(f(new Set),b({text:Z(t,s),rulingIds:s.rulingIds}),a()):s.error===void 0&&!s.cancelled&&b({text:`Nothing to rule: no proposals match.`,rulingIds:[]}),s.error!==void 0&&v(s.error instanceof Error?s.error.message:String(s.error))},O=e=>{e&&p.kind===`confirm`&&m({kind:`ruling`,action:p.action}),x.current?.(e)},k=async()=>{if(!y||!u.documentRevertRuling)return;let e=y,t=await q(e=>u.documentRevertRuling(e,r,i),e.rulingIds),n=[`${t.reverted} came back to review`];t.changed>0&&n.push(`${t.changed} changed since and left as ruled`),t.errors.length>0&&n.push(`not undone: ${t.errors.join(`; `)}`),b({...e,undone:!0,text:n.join(`; `)+`.`}),a()},A=e=>f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),j=t.length>0&&C.length===t.length,ee=t.length===0&&!n;return(0,l.jsxs)(`div`,{className:`doc-conn-group doc-bulk`,children:[(0,l.jsxs)(`h5`,{children:[`Proposals from this document (`,t.length,`)`]}),(0,l.jsxs)(`div`,{className:`doc-bulk-bar`,children:[(0,l.jsxs)(`label`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select every proposal shown`,checked:j,disabled:w||t.length===0,onChange:()=>f(j?new Set:new Set(S))}),` `,`all shown`]}),(0,l.jsxs)(`button`,{type:`button`,disabled:w||C.length===0,onClick:()=>E(`accept`,!1),children:[`Accept selected (`,C.length,`)`]}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||C.length===0,onClick:()=>E(`reject`,!1),children:`Reject selected…`}),(0,l.jsx)(`button`,{type:`button`,disabled:w||ee,onClick:()=>E(`accept`,!0),children:`Accept all from this document`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||ee,onClick:()=>E(`reject`,!0),children:`Reject all…`})]}),p.kind===`reason`&&(0,l.jsxs)(`form`,{className:`doc-bulk-step`,onSubmit:e=>{e.preventDefault(),h.trim()&&D(p.action,p.all,h)},children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:h,onChange:e=>g(e.target.value),autoFocus:!0}),(0,l.jsx)(`button`,{type:`submit`,className:`danger`,disabled:!h.trim(),children:`Count`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>m({kind:`idle`}),children:`Cancel`})]}),p.kind===`counting`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`counting…`}),p.kind===`confirm`&&(0,l.jsx)(vt,{step:p,onAnswer:O}),p.kind===`ruling`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:p.total?`ruled ${p.ruled??0} of ${p.total}…`:`ruling…`}),_&&(0,l.jsx)(`p`,{className:`doc-stmt-err`,role:`alert`,children:_}),y&&(0,l.jsxs)(`p`,{className:`doc-bulk-result`,role:`status`,children:[y.text,y.rulingIds.length>0&&!y.undone&&u.documentRevertRuling&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>void k(),children:`Undo`})]}),t.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:t.map(t=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select ${t.from_title??t.from_id} ${t.kind} ${t.to_title??t.to_id}`,checked:d.has(t.id),disabled:w,onChange:()=>A(t.id)}),(0,l.jsx)(pt,{id:t.from_id,title:t.from_title,targetDocumentId:t.from_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:t.kind}),(0,l.jsx)(pt,{id:t.to_id,title:t.to_title,targetDocumentId:t.to_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(mt,{statement:t})]},t.id))})]})}function vt({step:e,onAnswer:t}){let{dry:n}=e,r=e.action===`accept`?`Accept`:`Reject`,i=J(n.matched);return(0,l.jsxs)(`div`,{className:`doc-bulk-step doc-bulk-confirm`,children:[e.changed&&(0,l.jsx)(`p`,{className:`doc-bulk-warn`,children:`The proposals changed since the last count; counted again.`}),(0,l.jsxs)(`p`,{children:[r,` `,n.matched,` statement`,n.matched===1?``:`s`,e.all?` filed from this document`:``,i>1?`, in ${i} rulings of up to 1,000`:``,`?`,n.skipped>0&&` ${n.skipped} of them are not yours to rule and will be skipped.`]}),(n.sample??[]).length>0&&(0,l.jsx)(`ul`,{className:`doc-bulk-sample`,children:(n.sample??[]).slice(0,gt).map(e=>(0,l.jsxs)(`li`,{children:[e.from_title||e.from_id,` `,(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),` `,e.to_title||e.to_id]},e.id))}),(0,l.jsxs)(`button`,{type:`button`,className:e.action===`reject`?`danger`:void 0,onClick:()=>t(!0),children:[r,` `,n.matched]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>t(!1),children:`Cancel`})]})}var yt=8,bt=20;function xt(e){return/embedder|embedding|vector|semantic|not configured/i.test(e)}function St({documentId:e,selectedId:t,scope:n,browse:r,onSelectChunk:i,onOpenDocument:a,refreshKey:o,review:s}){let u=T(),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(void 0),[_,v]=(0,c.useState)([]),[y,b]=(0,c.useState)([]),[x,S]=(0,c.useState)(null),[C,w]=(0,c.useState)([]),[E,D]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(!d||!t)return;let e=t,i=!1;return m(!0),Promise.allSettled([u.documentBacklinks(e,n,r),u.documentRelated(e,n,r,yt),u.documentUnlinkedMentions(e,n,r,bt)]).then(([t,n,r])=>{if(!i){if(v(t.status===`fulfilled`?t.value.backlinks??[]:[]),n.status===`fulfilled`)b(n.value.related??[]),S(null);else{b([]);let e=n.reason instanceof Error?n.reason.message:String(n.reason);S(xt(e)?`semantic search not configured`:e)}r.status===`fulfilled`?(w(r.value.unlinked_mentions??[]),D(!!r.value.truncated)):(w([]),D(!1)),g(e),m(!1)}}),()=>{i=!0}},[u,d,t,n,r,o]);let O=(t,n,r)=>(0,l.jsx)(pt,{id:t,title:n,targetDocumentId:r,documentId:e,onSelectChunk:i,onOpenDocument:a}),k=!!(d&&t&&!p&&h===t);return(0,l.jsxs)(`div`,{className:`doc-conn`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-conn-toggle`,onClick:()=>f(e=>!e),children:[d?`▼`:`▶`,` Connections`]}),d&&(0,l.jsxs)(`div`,{className:`doc-conn-body`,children:[s&&(0,l.jsx)(_t,{documentId:e,proposals:s.proposals,incomplete:s.incomplete,scope:s.scope,browse:r,onChanged:s.onChanged,onSelectChunk:i,onOpenDocument:a}),t?k?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Backlinks`}),_.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:_.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[O(e.from_id,e.from_title,e.from_document_id),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),e.auto&&(0,l.jsx)(`span`,{className:`doc-conn-auto`,title:`Auto-linked from a [[wikilink]]`,children:`auto`}),(0,l.jsx)(mt,{statement:e})]},`${e.from_id}-${e.kind}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Related`}),x?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:x}):y.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:y.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[O(e.chunk_id,e.title,e.document_id),(0,l.jsx)(`span`,{className:`doc-conn-score`,title:`similarity score`,children:e.score.toFixed(2)})]},`${e.chunk_id}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Unlinked mentions`}),C.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsxs)(`ul`,{className:`doc-conn-list`,children:[C.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-conn-row`,children:O(e.chunk_id,e.title,e.document_id)},`${e.chunk_id}-${t}`)),E&&(0,l.jsx)(`li`,{className:`doc-conn-more`,"aria-hidden":!0,children:`(more…)`})]})]})]}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`loading…`}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`Select a chunk.`})]})]})}var Ct=24;function wt({edges:e,documentId:t,selectedId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a,incomplete:o}){let[s,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(!1);if(e.length===0)return null;let p=n?e.filter(e=>e.from_id===n||e.to_id===n):[],m=d?e:e.slice(0,Ct),h=Et(m);return(0,l.jsxs)(`div`,{className:`doc-refs`,children:[o&&(0,l.jsxs)(`p`,{className:`doc-refs-incomplete`,children:[`Showing the first `,e.length,` links of this document; it has more, which are not shown here or in the graph.`]}),n&&(0,l.jsxs)(`div`,{className:`doc-refs-list-wrap`,children:[(0,l.jsx)(`h4`,{children:`References`}),p.length===0?(0,l.jsx)(`p`,{className:`doc-refs-empty`,children:`This chunk has no links.`}):(0,l.jsx)(`ul`,{className:`doc-refs-list`,children:p.map((e,o)=>(0,l.jsx)(Tt,{edge:e,selectedId:n,documentId:t,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a},`${e.from_id}-${e.to_id}-${e.kind}-${o}`))})]}),(0,l.jsxs)(`div`,{className:`doc-graph`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-graph-toggle`,onClick:()=>u(e=>!e),children:[s?`▼`:`▶`,` relationship graph (`,e.length,`)`]}),s&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Ke,{code:h,onNodeClick:e=>{let n=Dt(m,e);n&&(!n.documentId||n.documentId===t?r(n.id):i?.(n.documentId,n.id,n.title))}}),e.length>Ct&&(0,l.jsx)(`button`,{type:`button`,className:`doc-graph-more`,onClick:()=>f(e=>!e),children:d?`show top ${Ct}`:`show all ${e.length}`})]})]})]})}function Tt({edge:e,selectedId:t,documentId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a}){let o=e.from_id===t,s=o?e.to_id:e.from_id,c=o?e.to_title:e.from_title,u=o?e.to_document_id:e.from_document_id;return(0,l.jsxs)(`li`,{className:`doc-ref`,children:[(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),(0,l.jsx)(`span`,{className:`doc-ref-arrow`,"aria-hidden":!0,children:o?`→`:`←`}),(0,l.jsx)(pt,{id:s,title:c,targetDocumentId:u,documentId:n,onSelectChunk:r,onOpenDocument:i}),(0,l.jsx)(mt,{statement:e}),a&&ye(e)&&(0,l.jsx)(ht,{id:e.id,onRule:a})]})}function Et(e){let t=[`graph LR`];for(let n of e){let e=`${Ot(n.from_id)}["${kt(n.from_title,n.from_id)}"]`,r=`${Ot(n.to_id)}["${kt(n.to_title,n.to_id)}"]`,i=(n.kind||`link`).replace(/[|"]/g,` `),a=n.status===`proposed`?`-.->`:`-->`;t.push(` ${e} ${a}|${i}| ${r}`)}return t.join(`
2
- `)}function Dt(e,t){for(let n of e){if(Ot(n.from_id)===t)return{id:n.from_id,documentId:n.from_document_id,title:n.from_title};if(Ot(n.to_id)===t)return{id:n.to_id,documentId:n.to_document_id,title:n.to_title}}}function Ot(e){return`n`+e.replace(/[^a-zA-Z0-9]/g,``)}function kt(e,t){let n=(e??``).replace(/["[\]{}|<>]/g,` `).replace(/\s+/g,` `).trim()||t.slice(0,6);return n.length>30?n.slice(0,29)+`…`:n}function At({documentId:e,scope:t,detail:n}){return(0,l.jsxs)(`div`,{className:`doc-unavailable`,role:`alert`,children:[(0,l.jsx)(`p`,{className:`doc-unavailable-lead`,children:`This document can’t be opened.`}),(0,l.jsxs)(`p`,{children:[`It may have been deleted, live in a scope other than `,(0,l.jsx)(`code`,{children:t}),`, or not be yours to read.`]}),(0,l.jsxs)(`p`,{className:`doc-unavailable-detail`,children:[(0,l.jsx)(`code`,{children:e}),n&&(0,l.jsxs)(l.Fragment,{children:[` — `,n]})]})]})}function jt(e){let t=typeof e==`number`?e/1e6:Date.parse(String(e));return!Number.isFinite(t)||t<=0?String(e??``):new Date(t).toLocaleString()}function Mt({chunkId:e,chunkTitle:t,scope:n,browse:r,onClose:i}){let a=T(),[o,s]=(0,c.useState)([]),[u,d]=(0,c.useState)(!0),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(`none`),[g,_]=(0,c.useState)(null),[v,y]=(0,c.useState)(``),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,E]=(0,c.useState)(null),[D,O]=(0,c.useState)(``);(0,c.useEffect)(()=>{let t=!1;return d(!0),p(null),a.documentHistory(e,n,r).then(e=>{if(t)return;let n=e.revisions??[];if(s(n),n.length>=2){let e=n.map(e=>e.revision);C(Math.min(...e)),E(Math.max(...e))}}).catch(e=>!t&&p(e instanceof Error?e.message:String(e))).finally(()=>!t&&d(!1)),()=>{t=!0}},[a,e,n,r]);let k=async t=>{p(null),x(!0),_(t),h(`version`);try{let i=await a.documentGetVersion(e,t,n,r);y(i.body??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}},A=async()=>{if(S!==null&&w!==null){p(null),x(!0),h(`diff`);try{let t=await a.documentDiff(e,S,w,n,r);O(t.diff??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}}};return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:i,children:(0,l.jsxs)(`div`,{className:`modal history-modal`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`History`,t?` — ${t}`:``]}),(0,l.jsx)(`div`,{className:`modal-buttons modal-buttons-top`,children:(0,l.jsx)(`button`,{type:`button`,onClick:i,children:`close`})})]}),f&&(0,l.jsx)(`div`,{className:`modal-err`,children:f}),u?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):o.length===0?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`No history recorded for this chunk.`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`div`,{className:`doc-hist-revs`,children:o.map(e=>(0,l.jsxs)(`button`,{type:`button`,className:`doc-hist-rev`+(m===`version`&&g===e.revision?` active`:``),onClick:()=>void k(e.revision),children:[(0,l.jsxs)(`span`,{className:`doc-hist-rev-num`,children:[`rev `,e.revision]}),(0,l.jsx)(`span`,{className:`doc-hist-rev-time`,children:jt(e.created_at)}),(0,l.jsx)(`span`,{className:`doc-hist-rev-actor`,children:e.actor||`unknown`})]},e.revision))}),o.length>=2&&(0,l.jsxs)(`div`,{className:`doc-hist-diffbar`,children:[(0,l.jsx)(`span`,{children:`Compare`}),(0,l.jsx)(`select`,{value:S??``,onChange:e=>C(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff from revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`span`,{"aria-hidden":!0,children:`→`}),(0,l.jsx)(`select`,{value:w??``,onChange:e=>E(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff to revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void A(),disabled:b||S===null||w===null,children:`diff`})]}),(0,l.jsx)(`div`,{className:`doc-hist-output`,children:b?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):m===`diff`?(0,l.jsx)(Nt,{text:D}):m===`version`?(0,l.jsx)(`pre`,{className:`md-pre doc-hist-version`,children:(0,l.jsx)(`code`,{children:v||`(empty)`})}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Select a revision to view it, or compare two.`})})]})]})})}function Nt({text:e}){if(!e.trim())return(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(no differences)`});let t=e.split(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=require("react/jsx-runtime"),u=require("@loomcycle/client"),d=require("react-markdown");d=s(d,1);let f=require("remark-gfm");f=s(f,1);var p=`loomcycle.explorer.navigator`;function m(e){try{return e?.getItem(`loomcycle.explorer.navigator`)===`stars`?`stars`:`tree`}catch{return`tree`}}function h(e,t){try{e?.setItem(p,t)}catch{}}function g(e){return!!e&&!e.parent_id&&!!e.entity?.natural_key}function _(e){let t=e?.classes;if(!Array.isArray(t))return[];let n=new Set;for(let e of t){let{name:t,kind:r}=e??{};typeof t==`string`&&t!==``&&r!==`document`&&n.add(t)}return[...n].sort((e,t)=>e.localeCompare(t))}function v(e,t){let n=t??``;return n===``||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[n,...e]}function y(e){let t={op:e.op===`copy`?`copy_documents`:`move_documents`,scope:e.scope,to_scope:e.toScope,dry_run:e.dryRun};e.documentId&&(t.document_ids=[e.documentId]),e.underPath&&(t.under_path=e.underPath);let n=C(e.from),r=C(e.to);return n&&r&&n!==r&&(t.path_map={[n]:r}),e.op===`move`&&(e.dropDangling&&(t.dangling=`drop`),e.dryRun||(t.expect_count=e.expectCount??0)),t}function b(e){let t=e.to.trim();return t.startsWith(`/`)?e.op===`move`&&e.toScope===e.scope?`a move goes to another scope; to rename within this one, use rename / move`:e.op===`copy`&&e.toScope===e.scope&&C(t)===C(e.from)?`a copy into the same scope needs a new path`:null:`the new path must start with /`}function x(e,t){let n=t.counts??{},r=n.documents??0,i=e===`copy`?`copied`:`moved`,a=[],o=`${n.chunks??0} parts, ${n.revisions??0} revisions, ${n.statements??0} relations, ${n.assets??0} images`;if(t.dry_run)a.push(`${r} ${w(r,`document`)} would be ${i}: ${o}.`),t.to_finish?.length&&a.push(`${t.to_finish.length} ${w(t.to_finish.length,`document`)} left by an earlier interrupted move will be finished.`);else if(e===`move`){let e=t.moved?.length??0;a.push(`${e} ${w(e,`document`)} moved: ${o}.`)}else a.push(`${r} ${w(r,`document`)} copied: ${o}.`);let s=t.refused_count??t.refused?.length??0;if(s>0){a.push(`${s} ${w(s,`document`)} refused:`);for(let e of t.refused??[])a.push(` ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}`)}if(t.dangling_count>0){e===`copy`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set stay behind.`):t.dropped===void 0?t.blocked_by===`dangling_relations`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} join these documents to ones outside the set. A relation cannot span two scopes: include the other documents, or drop these relations.`):a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set will be dropped.`):a.push(`${t.dropped} ${w(t.dropped,`relation`)} to documents outside the set were dropped.`);for(let e of t.dangling??[])a.push(` ${e.kind}: ${e.from} → ${e.to} (outside: ${e.outside})`)}for(let e of t.unfinished??[])a.push(`not finished: ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}. Run the move again.`);for(let e of t.name_failures??[])a.push(`no name ${e.path} for ${e.document_id}: ${e.error}`);return t.body_failures&&a.push(`${t.body_failures} ${w(t.body_failures,`body`,`bodies`)} could not be written.`),t.statements_failed&&a.push(`${t.statements_failed} ${w(t.statements_failed,`relation`)} could not be written${t.statement_error?`: ${t.statement_error}`:``}.`),a}function S(e,t,n){return e===`move`&&t.dangling_count>0&&!n||(t.counts?.documents??0)===0&&!(t.to_finish?.length??0)}function C(e){let t=e.trim(),n=t.length;for(;n>1&&t[n-1]===`/`;)n--;return t.slice(0,n)}function w(e,t,n=t+`s`){return e===1?t:n}var T=4,E=5e3;function D(e,t,n){return{...O(e,n),pathLs:(t,n,r,i,a)=>e.path({op:`ls`,path:t,scope:n,recursive:r,...a?.limit?{limit:a.limit}:{},...a?.cursor?{cursor:a.cursor}:{}},i),pathIsStored:(t,n,r)=>e.path({op:`stat`,path:t,scope:n},r).then(()=>!0,e=>{if(e?.name===`SubstrateToolRefusedError`)return!1;throw e}),documentPath:async(t,n,r)=>{let i;for(let a=0;a<T;a++){let a=await e.path({op:`ls`,path:`/`,scope:n,recursive:!0,kind_filter:`document`,limit:E,...i?{cursor:i}:{}},r),o=(a.entries??[]).find(e=>e.resource_ref?.document_id===t);if(o)return o.full_path;if(i=a.next_cursor||void 0,!i)return}},pathMkdir:(t,n,r)=>e.path({op:`mkdir`,path:t,scope:n},r),pathMv:(t,n,r,i)=>e.path({op:`mv`,path:t,to:n,scope:r},i),pathRm:(t,n,r,i)=>e.path({op:`rm`,path:t,scope:n,recursive:r},i),documentCreate:(t,n,r,i)=>e.document({op:`create_document`,title:t,path:n,scope:r},i),documentDelete:(t,n,r)=>e.document({op:`delete_document`,id:t,scope:n},r),documentsTransfer:(t,n)=>e.document(y(t),n),documentGet:(t,n,r)=>e.document({op:`get_document`,id:t,scope:n},r),documentsSummary:(t,n,r)=>e.document({op:`documents_summary`,scope:n,...t.documentIds?{document_ids:t.documentIds}:{},...t.underPath?{under_path:t.underPath}:{}},r),documentQueryChunks:(t,n,r)=>e.document({op:`query_chunks`,document_id:t,scope:n,limit:1e3},r),documentGetChunk:(t,n,r)=>e.document({op:`get_chunk`,id:t,scope:n},r),documentCreateChunk:(t,n,r,i,a,o)=>e.document({op:`create_chunk`,document_id:t,parent_id:n,scope:i,...o?{after_id:o}:{},...r},a),documentReorderChunk:(t,n,r,i)=>e.document({op:`reorder_chunk`,id:t,direction:n,scope:r},i),documentDeleteChunk:(t,n,r)=>e.document({op:`delete_chunk`,id:t,scope:n},r),documentSetAsset:(t,n,r,i,a,o)=>e.document({op:`set_asset`,id:t,media_type:n,data:r,...i?{filename:i}:{},scope:a},o),documentGetEdges:(t,n,r,i)=>e.document({op:`get_edges`,document_id:t,scope:n,...i?.after?{after:i.after}:{}},r),documentGetEdge:(t,n,r)=>e.document({op:`get_edge`,id:t,scope:n},r),documentAcceptStatement:(t,n,r,i)=>e.document({op:`accept_statement`,id:t,scope:n,...i?{reason:i}:{}},r),documentRejectStatement:(t,n,r,i)=>e.document({op:`reject_statement`,id:t,reason:n,scope:r},i),documentListStatements:(t,n,r)=>e.document({op:`list_statements`,scope:t,...r?.status?{status:r.status}:{},...r?.kind?{kind:r.kind}:{},...r?.limit?{limit:r.limit}:{},...r?.after?{after:r.after}:{}},n),documentClassify:(t,n,r,i)=>e.document({op:`classify`,document_id:t,write:n,scope:r},i),documentEntityTypes:(t,n)=>e.document({op:`describe_ontology`,scope:t},n).then(_),documentAcceptClassification:(t,n,r)=>e.document({op:`accept_classification`,document_id:t,scope:n},r),documentUpdateChunk:(t,n,r,i,a)=>e.document({op:`update_chunk`,id:t,revision:n,scope:i,...r},a),documentExportMd:(t,n,r,i)=>e.document({op:`export_md`,document_id:t,scope:n,include_metadata:r},i),documentBacklinks:(t,n,r)=>e.document({op:`backlinks`,id:t,scope:n},r),documentRelated:(t,n,r,i)=>e.document({op:`related`,id:t,scope:n,...i?{limit:i}:{}},r),documentUnlinkedMentions:(t,n,r,i)=>e.document({op:`unlinked_mentions`,id:t,scope:n,...i?{limit:i}:{}},r),documentHistory:(t,n,r,i)=>e.document({op:`history`,id:t,scope:n,...i?{limit:i}:{}},r),documentGetVersion:(t,n,r,i)=>e.document({op:`get_version`,id:t,revision:n,scope:r},i),documentDiff:(t,n,r,i,a)=>e.document({op:`diff`,id:t,from_revision:n,to_revision:r,scope:i},a),documentExportCanvas:(t,n,r)=>e.document({op:`export_canvas`,document_id:t,scope:n},r),...t?{documentAssetObjectUrl:async(e,n,r)=>{let i=new URLSearchParams({scope:n});r?.scopeId&&i.set(`scope_id`,r.scopeId),r?.tenant&&i.set(`tenant`,r.tenant);let a=await t(`/v1/_document/asset/${encodeURIComponent(e)}?${i.toString()}`);if(!a.ok)throw Error(`asset fetch failed: ${a.status}`);let o=await a.blob();return URL.createObjectURL(o)}}:{}}}function O(e,t){let n=e,r=e=>e?.tenant?`?tenant=${encodeURIComponent(e.tenant)}`:``,i={};typeof n.ruleStatements==`function`?i.documentRuleStatements=(e,t)=>n.ruleStatements(e.action,e.ids?{ids:e.ids}:{filter:e.filter},{reason:e.reason,dryRun:e.dry_run,expectCount:e.expect_count,max:e.max,scope:e.scope,scopeId:e.scope_id,tenant:t?.tenant}):t&&(i.documentRuleStatements=(e,n)=>t(`/v1/_statements/rule${r(n)}`,e));let a=(e,t)=>e===`user`&&t?.scopeId?t.scopeId:void 0;return typeof n.revertRuling==`function`?i.documentRevertRuling=(e,t,r)=>n.revertRuling(e,{scope:t,scopeId:a(t,r),tenant:r?.tenant}):t&&(i.documentRevertRuling=(e,n,i)=>{let o=a(n,i);return t(`/v1/_statements/revert${r(i)}`,{ruling_id:e,scope:n,...o?{scope_id:o}:{}})}),i}var k=(0,c.createContext)(null);function A({value:e,children:t}){return(0,l.jsx)(k.Provider,{value:e,children:t})}function j(){let e=(0,c.useContext)(k);if(!e)throw Error(`useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)`);return e}var M=5e3;function N(e){return e===``?`/`:e}function ee(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function te(e){let t=[``],n=e.split(`/`).filter(Boolean),r=``;for(let e=0;e<n.length-1;e++)r=`${r}/${n[e]}`,t.push(r);return t}function P(e){return e instanceof Error?e.message:String(e)}function F(e,t){return{entries:[...t,...e.entries??[]],nextCursor:e.next_cursor||void 0,loaded:!0,loading:!1}}var ne=class{data;scope;browse;pageLimit;dirs=new Map;snapshot=new Map;listeners=new Set;inflight=new Map;epoch=new Map;constructor(e,t,n,r=500){this.data=e,this.scope=t,this.browse=n,this.pageLimit=r}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});publish(){this.snapshot=new Map(this.dirs),this.listeners.forEach(e=>e())}set(e,t){this.dirs.set(e,t),this.publish()}track(e,t){let n=t.finally(()=>{this.inflight.get(e)===n&&this.inflight.delete(e)});return this.inflight.set(e,n),n}loadDir(e){return this.inflight.get(e)||(this.dirs.get(e)?.loaded?Promise.resolve():this.fetchFirst(e,this.pageLimit))}reload(e){let t=this.dirs.get(e),n=t?.entries.length??0,r=t?.loaded&&!t.nextCursor?n+this.pageLimit:n;return this.fetchFirst(e,Math.min(M,Math.max(this.pageLimit,r)))}fetchFirst(e,t){let n=(this.epoch.get(e)??0)+1;this.epoch.set(e,n);let r=this.dirs.get(e);this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!0});let i=this.data.pathLs(N(e),this.scope,!1,this.browse,{limit:t}).then(t=>{this.epoch.get(e)===n&&this.set(e,F(t,[]))},t=>{throw this.epoch.get(e)===n&&this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!1,error:P(t)}),t});return this.track(e,i)}loadMore(e){let t=this.inflight.get(e);if(t)return t;let n=this.dirs.get(e);if(!n?.nextCursor)return Promise.resolve();let r=this.epoch.get(e)??0;this.set(e,{...n,loading:!0,error:void 0});let i=this.data.pathLs(N(e),this.scope,!1,this.browse,{limit:this.pageLimit,cursor:n.nextCursor}).then(t=>{this.epoch.get(e)===r&&this.set(e,F(t,n.entries))},t=>{throw this.epoch.get(e)===r&&this.set(e,{...n,loading:!1,error:P(t)}),t});return this.track(e,i)}async reveal(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){for(await this.loadDir(n);;){let t=this.dirs.get(n);if(!t)return!1;if(t.entries.some(t=>t.name===e))break;let r=t.entries[t.entries.length-1];if(!t.nextCursor||r&&r.name>e)return!1;let i=t.nextCursor;if(await this.loadMore(n),this.dirs.get(n)?.nextCursor===i)return!1}n=`${n}/${e}`}return!0}async invalidate(e,t){if(t?.dropSubtree){for(let t of[...this.dirs.keys()])(t===e||t.startsWith(`${e}/`))&&(this.dirs.delete(t),this.epoch.set(t,(this.epoch.get(t)??0)+1),this.inflight.delete(t));this.publish()}let n=te(e).filter(e=>this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}async refresh(e){let t=new Set(e);t.add(``);for(let e of[...this.dirs.keys()])t.has(e)||(this.dirs.delete(e),this.epoch.set(e,(this.epoch.get(e)??0)+1),this.inflight.delete(e));this.publish();let n=[...t].filter(e=>e===``||this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}};async function re(e,t,n,r){let i=[],a;for(;;){let o=await e.pathLs(N(t),n,!0,r,{limit:M,cursor:a});i.push(...o.entries??[]);let s=o.next_cursor||void 0;if(!s||s===a)return i;a=s}}function ie(e){let t=[];for(let n of e){if(n.kind!==`document`)continue;let e=n.resource_ref?.document_id;e&&t.push(e)}return t}function I(e){let t=e.fetch;return new u.LoomcycleClient({baseUrl:e.baseUrl,authToken:e.token||void 0,fetch:(e,n)=>t?t(e,n):fetch(e,n)})}function L(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return t=>{let r={};return e.token&&(r.Authorization=`Bearer ${e.token}`),n(e.baseUrl+t,{headers:r})}}var R=class extends Error{status;code;constructor(e,t,n){super(e),this.name=`RequestError`,this.status=t,this.code=n}};function z(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return async(t,r)=>{let i={"Content-Type":`application/json`,Accept:`application/json`};e.token&&(i.Authorization=`Bearer ${e.token}`);let a=await n(e.baseUrl+t,{method:`POST`,headers:i,body:JSON.stringify(r)}),o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!a.ok){let e=s&&typeof s==`object`?s:{};throw new R(typeof e.error==`string`&&e.error?e.error:`${a.status} ${a.statusText}`.trim(),a.status,typeof e.code==`string`?e.code:void 0)}return s}}function ae(e){let{dataLayer:t,client:n,connection:r}=e;return(0,c.useMemo)(()=>t||(n?D(n):r?D(I(r),L(r),z(r)):null),[t,n,r?.baseUrl,r?.token,r?.fetch])}function oe({theme:e,dataLayer:t,children:n}){let r=e?{"data-theme":e}:{};return t?(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsx)(A,{value:t,children:n})}):(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsxs)(`div`,{className:`error-banner`,children:[`@loomcycle/explorer: provide a `,(0,l.jsx)(`code`,{children:`connection`}),`, `,(0,l.jsx)(`code`,{children:`client`}),`, or`,` `,(0,l.jsx)(`code`,{children:`dataLayer`}),` prop.`]})})}function se(e,t,n){let r=e[e.length-1];return[...r&&r.documentId===t.documentId?[...e.slice(0,-1),{...r,...V(t)}]:[...e,t],n]}function B(e,t){return t<0||t>=e.length-1?e:e.slice(0,t+1)}function ce(e,t,n){let r=e[e.length-1];if(!r||r.documentId!==t)return e;let i={...r,...V(n)};return i.title===r.title&&i.path===r.path?e:[...e.slice(0,-1),i]}function V(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function le(e){return e.title?e.title:e.path?e.path.slice(e.path.lastIndexOf(`/`)+1)||e.path:e.documentId.slice(0,8)}function H(e,t=4){let n=Array.from({length:e},(e,t)=>({kind:`crumb`,index:t}));if(e<=t||t<3)return n;let r=t-1,i=Array.from({length:e-1-r},(e,t)=>t+1);return[n[0],{kind:`gap`,hidden:i},...n.slice(e-r)]}function ue(e,t){for(let n of e.values()){let e=n.entries.find(e=>de(e)===t);if(e)return e.full_path}}function de(e){if(e.kind===`document`)return e.resource_ref?.document_id||void 0}function fe(e,t){return t&&e.some(e=>e.id===t)?t:e.find(e=>!e.parent_id)?.id}function pe({trail:e,onJump:t}){let[n,r]=(0,c.useState)(!1);if(e.length<2)return null;let i=e.length-1,a=e[i-1],o=H(e.length,n?e.length:void 0);return(0,l.jsxs)(`nav`,{className:`doc-trail`,"aria-label":`Documents you came through`,children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-back`,onClick:()=>t(i-1),title:`Back to ${le(a)}`,children:`← Back`}),(0,l.jsx)(`ol`,{className:`doc-trail-list`,children:o.map(n=>n.kind===`gap`?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-gap`,onClick:()=>r(!0),title:`Show ${n.hidden.length} more: ${n.hidden.map(t=>le(e[t])).join(` › `)}`,"aria-label":`Show ${n.hidden.length} hidden documents`,children:`…`})},`gap`):n.index===i?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`page`,title:le(e[i]),children:le(e[i])})},n.index):(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>t(n.index),title:le(e[n.index]),children:le(e[n.index])})},n.index))})]})}function me({data:e,scope:t,browse:n,documentId:r,underPath:i,fromPath:a,onClose:o,onDone:s}){let[u,d]=(0,c.useState)(`copy`),[f,p]=(0,c.useState)(t===`tenant`?`user`:`tenant`),[m,h]=(0,c.useState)(a),[g,_]=(0,c.useState)(!1),[v,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(!1),[O,k]=(0,c.useState)(null),A=(0,c.useMemo)(()=>({op:u,scope:t,toScope:f,documentId:r,underPath:i,from:a,to:m,dropDangling:g,dryRun:!0}),[u,t,f,r,i,a,m,g]),j=JSON.stringify(y(A)),M=b(A),N=v&&v.key===j?v.res:null,ee=N?S(u,N,g):!1,te=N?u===`move`?(N.counts?.documents??0)+(N.to_finish?.length??0):N.counts?.documents??0:0,P=async t=>{if(t.preventDefault(),w)o();else if(!M&&e.documentsTransfer){D(!0),k(null);try{if(!N)C({key:j,res:await e.documentsTransfer(A,n)});else{let t={...A,dryRun:!1,expectCount:N.counts?.documents??0},r=await e.documentsTransfer(t,n);T(r),s(t,r)}}catch(e){k(e instanceof Error?e.message:String(e))}finally{D(!1)}}},F=w?`close`:E?`working…`:N?`${u} ${te} document${te===1?``:`s`}`:`check`,ne=w??N;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:E?void 0:o,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:P,children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`Copy or move the `,r?`document`:`documents under`,` `,a]}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[!w&&(0,l.jsx)(`button`,{type:`button`,onClick:o,disabled:E,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:N&&u===`move`&&!w?`danger`:`primary`,disabled:E||!w&&(!!M||ee),children:F})]})]}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`A copy gets new ids and leaves the source as it is. A move keeps every id and removes the documents from `,(0,l.jsx)(`code`,{children:t}),`. Relations between the documents go with them.`]}),(0,l.jsx)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Copy or move`,children:[`copy`,`move`].map(e=>(0,l.jsx)(`button`,{type:`button`,"aria-pressed":u===e,className:u===e?`active`:void 0,disabled:E||!!w,onClick:()=>d(e),children:e},e))}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`To scope`}),(0,l.jsxs)(`select`,{value:f,disabled:E||!!w,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`New path`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:m,disabled:E||!!w,onChange:e=>h(e.target.value)})]}),u===`move`&&(0,l.jsx)(`label`,{className:`path-field`,children:(0,l.jsxs)(`span`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:g,disabled:E||!!w,onChange:e=>_(e.target.checked)}),` `,`Drop relations to documents outside the set`]})}),M&&(0,l.jsx)(`div`,{className:`modal-err`,children:M}),ne&&(0,l.jsx)(`div`,{className:`modal-context`,"aria-live":`polite`,children:x(u,ne).map((e,t)=>e.startsWith(` `)?(0,l.jsx)(`div`,{children:(0,l.jsx)(`code`,{children:e.trim()})},t):(0,l.jsx)(`div`,{children:e},t))}),O&&(0,l.jsx)(`div`,{className:`modal-err`,children:O})]})})}var U=6;function he({children:e,defaultLeftWidth:t=380,minLeftWidth:n=180,minRightWidth:r=240,storageKey:i,className:a,hideRight:o=!1}){let s=()=>{if(i){let e=localStorage.getItem(i),t=e?parseInt(e,10):NaN;if(Number.isFinite(t)&&t>=n)return t}return t},[u,d]=(0,c.useState)(s),[f,p]=(0,c.useState)(i);f!==i&&(p(i),d(s()));let m=(0,c.useRef)(null),[h,g]=(0,c.useState)(!1);(0,c.useEffect)(()=>{i&&!h&&f===i&&localStorage.setItem(i,String(Math.round(u)))},[i,f,u,h]);let _=(0,c.useCallback)(e=>{e.preventDefault(),g(!0),e.target.setPointerCapture(e.pointerId)},[]),v=(0,c.useCallback)(e=>{if(!h||!m.current)return;let t=m.current.getBoundingClientRect(),i=e.clientX-t.left,a=t.width-r-U;d(Math.max(n,Math.min(i,a)))},[h,n,r]),y=(0,c.useCallback)(e=>{g(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:m,className:`splitter ${a??``} ${h?`dragging`:``}`,style:{gridTemplateColumns:o?`1fr 0 0`:`min(${u}px, calc(100% - ${r+U}px)) ${U}px 1fr`},children:[(0,l.jsx)(`div`,{className:`splitter-pane splitter-left`,children:e[0]}),(0,l.jsx)(`div`,{hidden:o,className:`splitter-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-valuenow":Math.round(u),onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:y}),(0,l.jsx)(`div`,{className:`splitter-pane splitter-right`,hidden:o,children:e[1]})]})}var ge=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`];function W(e){return ge.includes(e)}function _e(e){return new Promise((t,n)=>{if(!W(e.type)){n(Error(`unsupported image type "${e.type||`unknown`}" (png, jpeg, gif, webp only)`));return}let r=new FileReader;r.onerror=()=>n(r.error??Error(`failed to read file`)),r.onload=()=>{let i=String(r.result??``),a=i.indexOf(`,`);a<0?n(Error(`could not decode image data`)):t({mediaType:e.type,data:i.slice(a+1)})},r.readAsDataURL(e)})}function ve(e){if(!e)return null;for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`file`&&W(n.type)){let e=n.getAsFile();if(e)return e}}return null}var ye=20;async function G(e,t,n,r,i=20){let a=[],o;for(let s=0;s<i;s++){let i=await e.documentGetEdges(t,n,r,o?{after:o}:void 0);if(o&&i.next_cursor===o)return{edges:a,incomplete:!0};if(a.push(...i.edges??[]),!i.truncated)return{edges:a,incomplete:!1};if(!i.next_cursor)return{edges:a,incomplete:!0};o=i.next_cursor}return{edges:a,incomplete:!0}}function be(e,t){if(!t)return[];let n=new Map(e.map(e=>[e.id,e])),r=new Set([t]),i=[],a=n.get(t)?.parent_id;for(;a&&!r.has(a);){let e=n.get(a);if(!e)break;r.add(a),i.push(e),a=e.parent_id}return i.reverse()}var xe=new Set([`manual`,`wikilink`]),Se=280;function Ce(e){return e.status&&e.status!==`asserted`?e.status:void 0}function we(e){return e.method&&!xe.has(e.method)?e.method:void 0}function K(e){return e.status===`proposed`&&!!e.id}function q(e){return new Date(Math.floor(e/1e6)).toISOString().slice(0,10)}function Te(e){let t=e.valid_at==null?void 0:q(e.valid_at),n=e.invalid_at==null?void 0:q(e.invalid_at);if(t&&n)return`valid ${t} → ${n}`;if(t)return`valid from ${t}`;if(n)return`valid until ${n}`}function Ee(e){if(e.judged_at==null)return;let t=`judged by ${e.judged_by||`a judge`} on ${q(e.judged_at)}`;return e.judge_reason?`${t}: ${e.judge_reason}`:t}function De(e,t=3){let n=(e.evidence??[]).slice(0,t),r=Math.max(e.evidence_count??0,e.evidence?.length??0);return{rows:n,more:Math.max(0,r-n.length)}}function J(e,t=Se){let n=e.replace(/\s+/g,` `).trim();return n.length>t?n.slice(0,t-1)+`…`:n}var Y=1e3,X=3,Z=1e3;function Q(e){return!!e&&typeof e==`object`&&e.code===`queue_changed`}async function Oe(e,t,n={}){let r={action:t.action,...t.ids?{ids:t.ids}:{filter:t.filter??{}},...t.reason?{reason:t.reason}:{},...t.scope&&t.scope!==`tenant`?{scope:t.scope}:{},...t.scope===`user`&&t.scopeId?{scope_id:t.scopeId}:{}},i={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[]},a=async()=>{let t=await e.rule({...r,dry_run:!0});return i.skipped=t.skipped,t},o=async(e,t)=>!n.confirm||await n.confirm(e,t)?(i.total=i.ruled+e.matched,!0):(i.cancelled=!0,!1),s;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`first`))return i;let c=0;for(let t=0;t<Z&&s.to_rule!==0;t++){let t;try{t=await e.rule({...r,dry_run:!1,expect_count:s.matched})}catch(e){if(!Q(e)||c>=3)return i.error=e,i;c++;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`queue_changed`))return i;continue}t.ruling_id&&i.rulingIds.push(t.ruling_id),i.ruled+=t.ruled,i.failed+=t.failed;for(let e of t.items??[])e.error&&i.failures.push(e);if(n.onProgress?.({ruled:i.ruled,failed:i.failed,total:i.total,chunks:i.rulingIds.length}),t.ruled===0||t.matched<=t.selected)break;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0)break;if(s.matched>i.total-i.ruled&&!await o(s,`grew`))return i}return i}async function ke(e,t){let n={reverted:0,changed:0,errors:[]};for(let r of[...t].reverse())try{let t=await e(r);n.reverted+=t.reverted,n.changed+=t.changed}catch(e){n.errors.push(e instanceof Error?e.message:String(e))}return n}function Ae(e){return Math.max(1,Math.ceil(e/Y))}function je(e){return e===`tenant`||e===`user`?e:void 0}function Me(e,t){return e.documentRuleStatements?je(t):void 0}function Ne(e,t){return e.filter(e=>K(e)&&!!e.id&&e.from_document_id===t)}function Pe(e,t,n,r){return e?{proposals:t,scope:e,incomplete:n,onChanged:r}:void 0}function Fe(e,t,n){return e.documentRuleStatements?Oe({rule:n=>e.documentRuleStatements(n,t.browse)},{action:t.action,...t.ids&&t.ids.length>0?{ids:t.ids}:{filter:{from_document_id:t.documentId}},...t.reason?{reason:t.reason}:{},scope:t.scope,...t.scope===`user`&&t.browse?.scopeId?{scopeId:t.browse.scopeId}:{}},n):Promise.reject(Error(`this data layer cannot rule in bulk`))}function Ie(e,t){let n=e=>e.toLocaleString(`en-US`),r=[`${e===`accept`?`Accepted`:`Rejected`} ${n(t.ruled)} statement${t.ruled===1?``:`s`}`];return t.failed>0&&r.push(`${n(t.failed)} did not take the ruling`),t.skipped>0&&r.push(`${n(t.skipped)} skipped: not yours to rule`),r.join(`; `)+`.`}var Le={"doc.rfc.draft":`#c99a3a`,"doc.rfc.review":`#6a7bd6`,"doc.rfc.confirmed":`#3a9ad6`,"doc.rfc.done":`#3aa06a`,"doc.plan.draft":`#c99a3a`,"doc.plan.review":`#6a7bd6`,"doc.plan.confirmed":`#3a9ad6`,"doc.plan.done":`#3aa06a`,"doc.document.done":`#3aa06a`,"doc.research.done":`#8a6ad6`,"doc.publication.draft":`#c99a3a`,"chunk.draft":`#c99a3a`,"chunk.review":`#6a7bd6`,"chunk.confirmed":`#3a9ad6`,"chunk.done":`#3aa06a`,"chunk.backlog":`#8a8f98`,"chunk.implementation":`#d1863a`,"chunk.merged":`#3aa06a`},Re=.16;function ze(e){return e&&Object.keys(e).length>0?e:Le}function Be(e,t,n){let r=e??``,i=t??``;if(r&&i&&n[`doc.${r}.${i}`])return n[`doc.${r}.${i}`];if(r&&n[`doc.${r}`])return n[`doc.${r}`]}function Ve(e,t){let n=e??``;return n?t[`chunk.${n}`]:void 0}function $(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!t)return;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`rgba(${parseInt(n.slice(0,2),16)}, ${parseInt(n.slice(2,4),16)}, ${parseInt(n.slice(4,6),16)}, ${Re})`}function He(e){if(!e)return;let t=$(e);if(t)return{background:t,borderLeft:`3px solid ${e}`}}async function Ue(e){try{return typeof navigator>`u`||!navigator.clipboard?!1:(await navigator.clipboard.writeText(e),!0)}catch{return!1}}function We({value:e,label:t,compact:n,title:r}){let[i,a]=(0,c.useState)(`idle`),o=async t=>{t.stopPropagation(),t.preventDefault();let n=await Ue(e);a(n?`copied`:`error`),window.setTimeout(()=>a(`idle`),n?1200:1500)},s=i===`copied`?`✓`:i===`error`?`✗`:`⎘`,u=r??`Copy ${t??`id`}: ${e}`,d=(0,l.jsx)(`button`,{type:`button`,className:`id-copy-btn id-copy-${i}`,onClick:o,title:u,"aria-label":u,children:s});return n?d:(0,l.jsxs)(`span`,{className:`id-copy`,children:[t&&(0,l.jsx)(`span`,{className:`id-copy-label`,children:t}),(0,l.jsx)(`code`,{className:`id-copy-value`,title:e,children:e}),d]})}function Ge(e){let t=new Map;e.forEach(e=>t.set(e.id,{row:e,children:[]}));let n=[];e.forEach(e=>{let r=t.get(e.id);e.parent_id&&t.has(e.parent_id)?t.get(e.parent_id).children.push(r):n.push(r)});let r=e=>{e.sort((e,t)=>e.row.position-t.row.position),e.forEach(e=>r(e.children))};return r(n),n}function Ke(e){return e===`image`?`🖼`:e===`mermaid`?`📊`:``}function qe(e,t){for(let n of e){if(n.row.id===t)return n;let e=qe(n.children,t);if(e)return e}}function Je({tree:e,selectedId:t,onSelect:n,colorEnabled:r,scheme:i,linkedIds:a}){let[o,s]=(0,c.useState)(()=>new Map),u=(0,c.useCallback)(e=>{s(t=>{let n=new Map(t);return n.set(e,t.get(e)===!1),n})},[]);(0,c.useEffect)(()=>{if(!t)return;let n=Ye(e,t);n.length!==0&&s(e=>{let t=!1,r=new Map(e);for(let e of n)r.get(e)===!1&&(r.set(e,!0),t=!0);return t?r:e})},[e,t]);let d=r?ze(i):null;return e.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`No chunks.`})}):(0,l.jsx)(`ul`,{className:`tree chunk-tree`,children:e.map(e=>(0,l.jsx)(Xe,{node:e,expanded:o,toggle:u,selectedId:t,onSelect:n,tintScheme:d,linkedIds:a},e.row.id))})}function Ye(e,t){let n=[],r=(e,i)=>{for(let a of e){if(a.row.id===t)return n.push(...i),!0;if(r(a.children,[...i,a.row.id]))return!0}return!1};return r(e,[]),n}function Xe({node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,linkedIds:o}){let s=e.children.length>0,c=t.get(e.row.id)!==!1,u=r===e.row.id,d=a?He(Ve(e.row.status,a)):void 0,f=o?.has(e.row.id);return(0,l.jsxs)(`li`,{className:`node chunk-node ${u?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row chunk-row`,style:d,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":c?`collapse`:`expand`,disabled:!s,onClick:t=>{t.stopPropagation(),s&&n(e.row.id)},children:s?c?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`chunk-link`,onClick:()=>i(e),title:e.row.title,children:[Ke(e.row.type)&&(0,l.jsx)(`span`,{className:`chunk-type-icon`,"aria-hidden":!0,children:Ke(e.row.type)}),(0,l.jsx)(`span`,{className:`chunk-title`,children:e.row.title||`(untitled)`}),e.row.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:e.row.type}),e.row.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:e.row.status}),f&&(0,l.jsx)(`span`,{className:`chunk-link-badge`,title:`Has cross-reference links`,"aria-label":`linked`,children:`🔗`})]}),(0,l.jsx)(We,{value:e.row.id,compact:!0,title:`Copy chunk id: ${e.row.id}`})]}),s&&c&&(0,l.jsx)(`ul`,{className:`children chunk-children`,children:e.children.map(e=>(0,l.jsx)(Xe,{node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,linkedIds:o},e.row.id))})]})}var Ze=0;function Qe(e){let t=e?.closest(`g.node`);return t?/flowchart-(.+)-\d+$/.exec(t.id)?.[1]:void 0}function $e({code:e,onNodeClick:t}){let n=(0,c.useRef)(null),[r,i]=(0,c.useState)({});return(0,c.useEffect)(()=>{let t=!1;return(async()=>{try{let r=(await import(`mermaid`)).default,a=n.current?.closest(`[data-theme]`)?.getAttribute(`data-theme`),o=!a||a===`dark`;r.initialize({startOnLoad:!1,theme:o?`dark`:`default`,securityLevel:`strict`});let{svg:s}=await r.render(`lc-mmd-${Ze++}`,e);t||i({svg:s})}catch{t||i({err:!0})}})(),()=>{t=!0}},[e]),r.err?(0,l.jsx)(`pre`,{className:`md-pre md-mermaid-error`,title:`diagram failed to render`,children:(0,l.jsx)(`code`,{children:e})}):r.svg?(0,l.jsx)(`div`,{ref:n,className:t?`md-mermaid md-mermaid-nav`:`md-mermaid`,onClick:t&&(e=>{let n=Qe(e.target);n&&t(n)}),dangerouslySetInnerHTML:{__html:r.svg}}):(0,l.jsx)(`div`,{ref:n,className:`md-mermaid md-mermaid-loading`,children:`rendering diagram…`})}function et({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=j(),[o,s]=(0,c.useState)(e.title),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(e.status??``),[m,h]=(0,c.useState)(e.body??``),[g,_]=(0,c.useState)(e.fields?JSON.stringify(e.fields,null,2):``),[v,y]=(0,c.useState)((e.tags??[]).join(`, `)),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(!1),E=u===`mermaid`,D=u===`image`||!!e.asset,[O,k]=(0,c.useState)(m);(0,c.useEffect)(()=>{if(!E)return;let e=setTimeout(()=>k(m),400);return()=>clearTimeout(e)},[m,E]);let A=async o=>{C(null),x(!0);try{let{mediaType:s,data:c}=await _e(o);i(await a.documentSetAsset(e.id,s,c,o.name,t,n)),r()}catch(e){C(e instanceof Error?e.message:String(e)),x(!1)}},M=E?`Mermaid source`:D?`Caption (optional)`:`Body (Markdown)`;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal chunk-editor`,onClick:e=>e.stopPropagation(),onSubmit:async s=>{s.preventDefault(),C(null),T(!1);let c={body:m,title:o,type:u,status:f,tags:v.split(`,`).map(e=>e.trim()).filter(e=>e!==``)};if(g.trim()!==``)try{c.fields=JSON.parse(g)}catch{C(`fields must be valid JSON`);return}x(!0);try{i(await a.documentUpdateChunk(e.id,e.revision,c,t,n)),r()}catch(e){let t=e instanceof Error?e.message:String(e);C(t),T(/revision conflict/i.test(t)),x(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:`Edit chunk`}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:b,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:b,children:b?`saving…`:`save`})]})]}),S&&(0,l.jsxs)(`div`,{className:`modal-err`,children:[S,w&&` — reopen the chunk to load the latest, then reapply your edit.`]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Title`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:o,onChange:e=>s(e.target.value)})]}),(0,l.jsxs)(`div`,{className:`chunk-editor-row`,children:[(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:u,placeholder:`(none)`,onChange:e=>d(e.target.value)})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Status`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:f,placeholder:`(none)`,onChange:e=>p(e.target.value)})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Tags`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:v,placeholder:`comma-separated, nest with a slash: area/sub, priority/high`,onChange:e=>y(e.target.value)})]}),D&&(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Replace image`}),(0,l.jsx)(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:b,onChange:e=>{let t=e.target.files?.[0];t&&A(t)}})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:M}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-body-input`,rows:E?8:12,value:m,onChange:e=>h(e.target.value)})]}),E&&(0,l.jsxs)(`div`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Preview`}),(0,l.jsx)(`div`,{className:`chunk-mermaid-preview`,children:O.trim()?(0,l.jsx)($e,{code:O}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(enter Mermaid source above)`})})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Fields (JSON, optional)`}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-fields-input`,rows:4,value:g,placeholder:`{}`,onChange:e=>_(e.target.value)})]})]})})}function tt({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=j(),[o,s]=(0,c.useState)(null),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(null);(0,c.useEffect)(()=>{let e=!1;return a.documentEntityTypes?.(t,n).then(t=>{e||s(t)}).catch(t=>{e||h(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[a,t,n]);let y=o?v(o,e.type):[],b=u.toLowerCase()===(e.type??``).toLowerCase();return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async o=>{if(o.preventDefault(),!(b||f)){h(null),p(!0);try{let o=await a.documentUpdateChunk(e.id,e.revision,{type:u},t,n);if(i(o),o.not_announced){_(o.not_announced),p(!1);return}r()}catch(e){h(e instanceof Error?e.message:String(e)),p(!1)}}},children:[(0,l.jsx)(`h3`,{children:`Change type`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`“`,e.title||`(untitled)`,`” is a subject (`,(0,l.jsx)(`code`,{children:e.entity?.natural_key}),`). Its key stays as it is; relations about it are re-checked against the new type.`]}),m&&(0,l.jsx)(`div`,{className:`modal-err`,children:m}),g?(0,l.jsxs)(`div`,{className:`modal-err`,children:[`The type was changed, but subscribers were not told: `,g]}):(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),o===null?(0,l.jsx)(`span`,{className:`doc-empty-body`,children:m?``:`loading types…`}):(0,l.jsx)(`select`,{className:`path-modal-input`,value:u,disabled:f,onChange:e=>d(e.target.value),children:y.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:f,children:g?`close`:`cancel`}),!g&&(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:f||b||o===null,children:f?`saving…`:`change type`})]})]})})}function nt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function rt(e){if(!e||typeof e!=`object`)return;let t=e.classification;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t,r={};return typeof n.by==`string`&&(r.by=n.by),typeof n.at==`number`&&(r.at=n.at),typeof n.applied_type==`string`&&n.applied_type&&(r.applied_type=n.applied_type),typeof n.proposed_type==`string`&&n.proposed_type&&(r.proposed_type=n.proposed_type),n.proposed_fields&&typeof n.proposed_fields==`object`&&!Array.isArray(n.proposed_fields)&&(r.proposed_fields=n.proposed_fields),nt(n.proposed_tags)&&(r.proposed_tags=n.proposed_tags),nt(n.statements)&&(r.statements=n.statements),r}function it(e){let t=rt(e);if(!t)return;let n=t.proposed_tags??[],r=t.statements?.length??0;if(t.proposed_type||n.length!==0||r!==0)return{proposedType:t.proposed_type,proposedTags:n,statementCount:r}}function at(e){let t=e.write===`report`;switch(e.result){case`classified`:return t?`would be classified`:`classified`;case`proposed`:return t?`would be proposed for review`:`proposed — waits for review`;case`kept`:return`kept — the type was set by hand`;case`unclassified`:return`unclassified — nothing decided`;default:return String(e.result)}}function ot(e){if(!e.class)return;if(e.result===`kept`)return`not applied`;let t=e.write===`report`;return e.live?t?`would be applied`:`applied`:t?`would be proposed`:`proposed`}function st(e){return e.write===`report`?e.result===`classified`||e.result===`proposed`||(e.concepts?.length??0)>0||(e.issued_by?.length??0)>0:!1}function ct(e){return e==null||!Number.isFinite(e)?``:`${Math.round(e*100)}%`}var lt={rules:`Rules`,vote:`Neighbourhood vote`,model:`Model`};function ut(e){return lt[e]??e}function dt(e){let t=[];e.quote&&t.push(e.from?`“${e.quote}” (${e.from})`:`“${e.quote}”`),e.votes!=null&&t.push(`${e.votes} vote${e.votes===1?``:`s`}`);let n=ct(e.share);return n&&t.push(n),t.join(` · `)}function ft(e){return{label:ut(e.step),...e.chosen?{chosen:e.chosen}:{},...e.method?{method:e.method}:{},...e.neighbours?{neighbours:e.neighbours}:{},...e.reason?{reason:e.reason}:{},candidates:(e.candidates??[]).map(e=>({class:e.class,detail:dt(e)}))}}function pt(e){let t=[];e.type&&t.push(`type ${e.type}`);let n=e.accepted_statements?.length??0;n>0&&t.push(`${n} statement${n===1?``:`s`}`),e.tags&&e.tags.length>0&&t.push(`tags ${e.tags.join(`, `)}`);let r=[];e.type_pending&&r.push(`The proposed class stays pending: another document already holds its identity.`),e.skipped_type&&r.push(`Class ${e.skipped_type} was not applied: it is not a declared document class.`);let i=e.skipped_statements?.length??0;return i>0&&r.push(`${i} statement${i===1?` was`:`s were`} skipped (already ruled on, or not this document's proposal).`),e.skipped_tags&&e.skipped_tags.length>0&&r.push(`Tags not applied (not concepts of the ontology): ${e.skipped_tags.join(`, `)}.`),r.push(...e.warnings??[]),{applied:t.length>0?`Accepted ${t.join(`, `)}.`:`Nothing was accepted.`,notices:r}}function mt(e){let t=e instanceof Error?e.message:String(e);return t.includes(`nothing_pending`)?`Nothing is pending for this document — it may already have been accepted.`:t}function ht({documentId:e,scope:t,browse:n,rootFields:r,requestKey:i,onClose:a,onChanged:o}){let s=j(),[u,d]=(0,c.useState)(null),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(!1),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),S=(0,c.useMemo)(()=>s.documentAcceptClassification?it(r):void 0,[s,r]);(0,c.useEffect)(()=>{if(i===0||!s.documentClassify)return;let r=!1;return p(!0),h(null),d(null),s.documentClassify(e,`report`,t,n).then(e=>!r&&d(e)).catch(e=>!r&&h(mt(e))).finally(()=>!r&&p(!1)),()=>{r=!0}},[s,e,t,n,i]);let C=async()=>{if(s.documentClassify){p(!0),h(null);try{d(await s.documentClassify(e,`propose`,t,n)),o()}catch(e){h(mt(e))}finally{p(!1)}}},w=async()=>{if(s.documentAcceptClassification){_(!0),y(null);try{x(await s.documentAcceptClassification(e,t,n)),o()}catch(e){y(mt(e))}finally{_(!1)}}},T=i>0;if(!T&&!S&&!b&&!v)return null;let E=b?pt(b):void 0;return(0,l.jsxs)(`div`,{className:`doc-classify`,children:[S&&(0,l.jsxs)(`div`,{className:`doc-classify-pending`,children:[(0,l.jsx)(`span`,{className:`doc-classify-label`,children:`Pending classification`}),S.proposedType&&(0,l.jsxs)(`span`,{children:[`class `,(0,l.jsx)(`strong`,{children:S.proposedType})]}),S.proposedTags.length>0&&(0,l.jsxs)(`span`,{children:[`tags`,` `,S.proposedTags.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e))]}),S.statementCount>0&&(0,l.jsxs)(`span`,{children:[S.statementCount,` proposed statement`,S.statementCount===1?``:`s`]}),(0,l.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>void w(),children:g?`Accepting…`:`Accept`})]}),v&&(0,l.jsxs)(`div`,{className:`doc-classify-err`,role:`alert`,children:[v,(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>y(null),"aria-label":`Dismiss`,children:`×`})]}),E&&(0,l.jsxs)(`div`,{className:`doc-classify-notice`,role:`status`,children:[(0,l.jsx)(`span`,{children:E.applied}),E.notices.map((e,t)=>(0,l.jsx)(`span`,{className:`doc-classify-warn`,children:e},t)),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>x(null),"aria-label":`Dismiss`,children:`×`})]}),T&&(0,l.jsxs)(`div`,{className:`doc-classify-panel`,children:[(0,l.jsxs)(`div`,{className:`doc-classify-head`,children:[(0,l.jsx)(`h4`,{children:`Classify`}),u&&(0,l.jsx)(`span`,{className:`doc-classify-result ${u.result}`,children:at(u)}),u?.write===`report`&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:`report only — nothing written`}),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:a,"aria-label":`Close`,children:`×`})]}),!u&&!m&&(0,l.jsx)(`p`,{className:`doc-classify-hint`,children:`Classifying…`}),m&&(0,l.jsx)(`p`,{className:`doc-classify-err`,role:`alert`,children:m}),u&&(0,l.jsx)(gt,{answer:u}),u&&st(u)&&(0,l.jsx)(`div`,{className:`doc-classify-actions`,children:(0,l.jsx)(`button`,{type:`button`,disabled:f,onClick:()=>void C(),title:`Apply a unique rule match to the document; file everything else for review`,children:f?`Applying…`:`Apply`})})]})]})}function gt({answer:e}){let t=ot(e),n=Object.entries(e.fields??{}),r=e.issued_by??[],i=e.concepts??[],a=(e.steps??[]).map(ft),o=e.statements?.length??0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`dl`,{className:`doc-classify-rows`,children:[e.class&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`class`}),(0,l.jsxs)(`dd`,{children:[(0,l.jsx)(`strong`,{children:e.class}),t&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` (`,t,`)`]})]})]}),e.work_key&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`work key`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:e.work_key})]}),n.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`fields`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:n.map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`).join(` · `)})]}),r.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`issued by`}),(0,l.jsx)(`dd`,{children:r.map((e,t)=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.quote,children:[e.instance,e.quote&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` “`,e.quote,`”`]})]},`${e.instance}-${t}`))})]}),i.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`concepts`}),(0,l.jsx)(`dd`,{children:i.map(e=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.tag,children:[e.concept,(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,ct(e.share)]})]},e.tag))})]}),o>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`statements`}),(0,l.jsxs)(`dd`,{children:[o,` written`,e.statements.some(e=>e.status===`proposed`)&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` (proposed ones wait for review)`})]})]})]}),a.length>0&&(0,l.jsx)(`ol`,{className:`doc-classify-steps`,children:a.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`span`,{className:`doc-classify-step`,children:e.label}),e.method&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` [`,e.method,`]`]}),e.chosen?(0,l.jsxs)(l.Fragment,{children:[` → `,(0,l.jsx)(`strong`,{children:e.chosen})]}):(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` no choice`}),e.neighbours!=null&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` · `,e.neighbours,` neighbours`]}),e.reason&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` — `,e.reason]}),e.candidates.length>0&&(0,l.jsxs)(`details`,{className:`doc-classify-candidates`,children:[(0,l.jsxs)(`summary`,{children:[e.candidates.length,` candidate`,e.candidates.length===1?``:`s`]}),(0,l.jsx)(`ul`,{children:e.candidates.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`strong`,{children:e.class}),e.detail&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,e.detail]})]},`${e.class}-${t}`))})]})]},`${e.label}-${t}`))}),e.warnings&&e.warnings.length>0&&(0,l.jsx)(`ul`,{className:`doc-classify-warnings`,children:e.warnings.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-classify-warn`,children:e},t))})]})}function _t(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((e??``).trim());if(!t)return`#888888`;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`#`+n.toLowerCase()}function vt({documentId:e,rootChunkId:t,docType:n,docStatus:r,chunkStatuses:i,scope:a,browse:o,onClose:s,onSaved:u}){let d=j(),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(!1),[g,_]=(0,c.useState)({}),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),w=(0,c.useMemo)(()=>{let e=new Set(Object.keys(Le));n&&e.add(`doc.${n}.${r||`draft`}`);for(let t of i)t&&e.add(`chunk.${t}`);return[...e].sort()},[n,r,i]);(0,c.useEffect)(()=>{let e=!1;return d.documentGetChunk(t,a,o).then(t=>{if(e)return;p(t);let n=t.fields??{};h(n.color_enabled===!0);let r=n.color_scheme??{};_({...Le,...r})}).catch(t=>!e&&C(t instanceof Error?t.message:String(t))),()=>{e=!0}},[d,t,a,o]);let T=(e,t)=>_(n=>({...n,[e]:t})),E=e=>({...e??{},color_enabled:m,color_scheme:g}),D=async()=>{if(f){y(!0),C(null),x(null);try{await d.documentUpdateChunk(t,f.revision,{fields:E(f.fields)},a,o),u(),s()}catch(e){C(e instanceof Error?e.message:String(e)),y(!1)}}},O=async()=>{if(!n)C(`this document has no type to match`);else{y(!0),C(null),x(null);try{let{documents:t}=await d.documentsSummary({underPath:`/`},a,o),r=(t??[]).filter(t=>t.type===n&&t.document_id!==e&&t.root_chunk_id),i=0;for(let e of r)try{let t=await d.documentGetChunk(e.root_chunk_id,a,o);await d.documentUpdateChunk(e.root_chunk_id,t.revision,{fields:E(t.fields)},a,o),i++}catch{}x(`Applied to ${i} other ${n} document(s).`),u()}catch(e){C(e instanceof Error?e.message:String(e))}finally{y(!1)}}},k=w.filter(e=>e.startsWith(`doc.`)),A=w.filter(e=>e.startsWith(`chunk.`));return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:s,children:(0,l.jsxs)(`div`,{className:`modal scheme-editor`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`scheme-editor-head`,children:[(0,l.jsx)(`h3`,{children:`Document colors`}),(0,l.jsxs)(`div`,{className:`scheme-editor-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:s,disabled:v,children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`primary`,onClick:()=>void D(),disabled:v||!f,children:v?`saving…`:`save`})]})]}),S&&(0,l.jsx)(`div`,{className:`modal-err`,children:S}),f?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`label`,{className:`scheme-toggle`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked)}),(0,l.jsx)(`span`,{children:`Enable coloring for this document`})]}),(0,l.jsx)(`p`,{className:`modal-context`,children:`Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable.`}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Document (type · status)`}),k.map(e=>(0,l.jsx)(yt,{label:e.slice(4),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Chunks (status)`}),A.map(e=>(0,l.jsx)(yt,{label:e.slice(6),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-editor-foot`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>void O(),disabled:v||!n,title:n?`Apply this palette to every other ${n} document`:`This document has no type`,children:[`copy to all `,n||`same-type`,` documents`]}),b&&(0,l.jsx)(`span`,{className:`scheme-status`,children:b})]})]}):(0,l.jsx)(`p`,{className:`modal-context`,children:`Loading…`})]})})}function yt({label:e,value:t,onChange:n}){let r=_t(t);return(0,l.jsxs)(`label`,{className:`scheme-row`,children:[(0,l.jsx)(`input`,{type:`color`,value:r,onChange:e=>n(e.target.value)}),(0,l.jsx)(`span`,{className:`scheme-key`,children:e}),(0,l.jsx)(`code`,{className:`scheme-hex`,children:r})]})}function bt({id:e,title:t,targetDocumentId:n,documentId:r,onSelectChunk:i,onOpenDocument:a}){let o=t||e.slice(0,8);return!n||n===r?(0,l.jsx)(`button`,{type:`button`,className:`doc-ref-target`,onClick:()=>i(e),children:o}):a?(0,l.jsxs)(`button`,{type:`button`,className:`doc-ref-target external`,title:`In another document — opens it at this chunk`,onClick:()=>a(n,e,t),children:[o,` ↗`]}):(0,l.jsxs)(`span`,{className:`doc-ref-target external`,title:`In another document`,children:[o,` ↗`]})}function xt({statement:e}){let t=Ce(e),n=we(e),r=Ee(e),i=Te(e),{rows:a,more:o}=De(e);return(0,l.jsxs)(l.Fragment,{children:[t&&(0,l.jsx)(`span`,{className:`doc-stmt-status ${t}`,children:t}),n&&(0,l.jsx)(`span`,{className:`doc-stmt-method`,title:`how this relation was made`,children:n}),r&&(0,l.jsx)(`span`,{className:`doc-stmt-verdict`,title:r,children:`judged`}),i&&(0,l.jsx)(`span`,{className:`doc-stmt-valid`,children:i}),a.length>0&&(0,l.jsxs)(`ul`,{className:`doc-stmt-evidence`,children:[a.map(e=>(0,l.jsxs)(`li`,{title:e.quote,children:[`“`,J(e.quote),`”`,e.stale&&(0,l.jsx)(`span`,{className:`doc-stmt-stale`,children:` (source changed)`})]},e.id)),o>0&&(0,l.jsxs)(`li`,{className:`doc-stmt-more`,children:[`+`,o,` more`]})]})]})}function St({id:e,onRule:t}){let[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=async n=>{s(!0),d(null);try{await t(e,n,n?void 0:i.trim()),r(!1),a(``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{s(!1)}};return(0,l.jsxs)(`span`,{className:`doc-stmt-review`,children:[n?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:i,disabled:o,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i.trim()&&f(!1),e.key===`Escape`&&r(!1)},autoFocus:!0}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:o||!i.trim(),onClick:()=>void f(!1),children:`Reject`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!1),children:`Cancel`})]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>void f(!0),children:`Accept`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!0),children:`Reject…`})]}),u&&(0,l.jsx)(`span`,{className:`doc-stmt-err`,role:`alert`,children:u})]})}var Ct=3;function wt({documentId:e,proposals:t,incomplete:n,scope:r,browse:i,onChanged:a,onSelectChunk:o,onOpenDocument:s}){let u=j(),[d,f]=(0,c.useState)(new Set),[p,m]=(0,c.useState)({kind:`idle`}),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useRef)(null),S=new Set(t.map(e=>e.id)),C=[...d].filter(e=>S.has(e)),w=p.kind!==`idle`&&p.kind!==`reason`,T=(e,t)=>{v(null),b(null),e===`reject`?m({kind:`reason`,action:e,all:t}):E(e,t,``)},E=async(t,n,o)=>{m({kind:`counting`,action:t,all:n});let s;try{s=await Fe(u,{documentId:e,action:t,ids:n?void 0:C,reason:o.trim()||void 0,scope:r,browse:i},{confirm:(e,r)=>new Promise(i=>{x.current=i,m({kind:`confirm`,action:t,all:n,dry:e,changed:r!==`first`})}),onProgress:e=>m({kind:`ruling`,action:t,ruled:e.ruled,total:e.total})})}catch(e){s={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[],error:e}}x.current=null,m({kind:`idle`}),g(``),s.rulingIds.length>0?(f(new Set),b({text:Ie(t,s),rulingIds:s.rulingIds}),a()):s.error===void 0&&!s.cancelled&&b({text:`Nothing to rule: no proposals match.`,rulingIds:[]}),s.error!==void 0&&v(s.error instanceof Error?s.error.message:String(s.error))},D=e=>{e&&p.kind===`confirm`&&m({kind:`ruling`,action:p.action}),x.current?.(e)},O=async()=>{if(!y||!u.documentRevertRuling)return;let e=y,t=await ke(e=>u.documentRevertRuling(e,r,i),e.rulingIds),n=[`${t.reverted} came back to review`];t.changed>0&&n.push(`${t.changed} changed since and left as ruled`),t.errors.length>0&&n.push(`not undone: ${t.errors.join(`; `)}`),b({...e,undone:!0,text:n.join(`; `)+`.`}),a()},k=e=>f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),A=t.length>0&&C.length===t.length,M=t.length===0&&!n;return(0,l.jsxs)(`div`,{className:`doc-conn-group doc-bulk`,children:[(0,l.jsxs)(`h5`,{children:[`Proposals from this document (`,t.length,`)`]}),(0,l.jsxs)(`div`,{className:`doc-bulk-bar`,children:[(0,l.jsxs)(`label`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select every proposal shown`,checked:A,disabled:w||t.length===0,onChange:()=>f(A?new Set:new Set(S))}),` `,`all shown`]}),(0,l.jsxs)(`button`,{type:`button`,disabled:w||C.length===0,onClick:()=>T(`accept`,!1),children:[`Accept selected (`,C.length,`)`]}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||C.length===0,onClick:()=>T(`reject`,!1),children:`Reject selected…`}),(0,l.jsx)(`button`,{type:`button`,disabled:w||M,onClick:()=>T(`accept`,!0),children:`Accept all from this document`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||M,onClick:()=>T(`reject`,!0),children:`Reject all…`})]}),p.kind===`reason`&&(0,l.jsxs)(`form`,{className:`doc-bulk-step`,onSubmit:e=>{e.preventDefault(),h.trim()&&E(p.action,p.all,h)},children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:h,onChange:e=>g(e.target.value),autoFocus:!0}),(0,l.jsx)(`button`,{type:`submit`,className:`danger`,disabled:!h.trim(),children:`Count`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>m({kind:`idle`}),children:`Cancel`})]}),p.kind===`counting`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`counting…`}),p.kind===`confirm`&&(0,l.jsx)(Tt,{step:p,onAnswer:D}),p.kind===`ruling`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:p.total?`ruled ${p.ruled??0} of ${p.total}…`:`ruling…`}),_&&(0,l.jsx)(`p`,{className:`doc-stmt-err`,role:`alert`,children:_}),y&&(0,l.jsxs)(`p`,{className:`doc-bulk-result`,role:`status`,children:[y.text,y.rulingIds.length>0&&!y.undone&&u.documentRevertRuling&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>void O(),children:`Undo`})]}),t.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:t.map(t=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select ${t.from_title??t.from_id} ${t.kind} ${t.to_title??t.to_id}`,checked:d.has(t.id),disabled:w,onChange:()=>k(t.id)}),(0,l.jsx)(bt,{id:t.from_id,title:t.from_title,targetDocumentId:t.from_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:t.kind}),(0,l.jsx)(bt,{id:t.to_id,title:t.to_title,targetDocumentId:t.to_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(xt,{statement:t})]},t.id))})]})}function Tt({step:e,onAnswer:t}){let{dry:n}=e,r=e.action===`accept`?`Accept`:`Reject`,i=Ae(n.matched);return(0,l.jsxs)(`div`,{className:`doc-bulk-step doc-bulk-confirm`,children:[e.changed&&(0,l.jsx)(`p`,{className:`doc-bulk-warn`,children:`The proposals changed since the last count; counted again.`}),(0,l.jsxs)(`p`,{children:[r,` `,n.matched,` statement`,n.matched===1?``:`s`,e.all?` filed from this document`:``,i>1?`, in ${i} rulings of up to 1,000`:``,`?`,n.skipped>0&&` ${n.skipped} of them are not yours to rule and will be skipped.`]}),(n.sample??[]).length>0&&(0,l.jsx)(`ul`,{className:`doc-bulk-sample`,children:(n.sample??[]).slice(0,Ct).map(e=>(0,l.jsxs)(`li`,{children:[e.from_title||e.from_id,` `,(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),` `,e.to_title||e.to_id]},e.id))}),(0,l.jsxs)(`button`,{type:`button`,className:e.action===`reject`?`danger`:void 0,onClick:()=>t(!0),children:[r,` `,n.matched]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>t(!1),children:`Cancel`})]})}var Et=8,Dt=20;function Ot(e){return/embedder|embedding|vector|semantic|not configured/i.test(e)}function kt({documentId:e,selectedId:t,scope:n,browse:r,onSelectChunk:i,onOpenDocument:a,refreshKey:o,review:s}){let u=j(),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(void 0),[_,v]=(0,c.useState)([]),[y,b]=(0,c.useState)([]),[x,S]=(0,c.useState)(null),[C,w]=(0,c.useState)([]),[T,E]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(!d||!t)return;let e=t,i=!1;return m(!0),Promise.allSettled([u.documentBacklinks(e,n,r),u.documentRelated(e,n,r,Et),u.documentUnlinkedMentions(e,n,r,Dt)]).then(([t,n,r])=>{if(!i){if(v(t.status===`fulfilled`?t.value.backlinks??[]:[]),n.status===`fulfilled`)b(n.value.related??[]),S(null);else{b([]);let e=n.reason instanceof Error?n.reason.message:String(n.reason);S(Ot(e)?`semantic search not configured`:e)}r.status===`fulfilled`?(w(r.value.unlinked_mentions??[]),E(!!r.value.truncated)):(w([]),E(!1)),g(e),m(!1)}}),()=>{i=!0}},[u,d,t,n,r,o]);let D=(t,n,r)=>(0,l.jsx)(bt,{id:t,title:n,targetDocumentId:r,documentId:e,onSelectChunk:i,onOpenDocument:a}),O=!!(d&&t&&!p&&h===t);return(0,l.jsxs)(`div`,{className:`doc-conn`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-conn-toggle`,onClick:()=>f(e=>!e),children:[d?`▼`:`▶`,` Connections`]}),d&&(0,l.jsxs)(`div`,{className:`doc-conn-body`,children:[s&&(0,l.jsx)(wt,{documentId:e,proposals:s.proposals,incomplete:s.incomplete,scope:s.scope,browse:r,onChanged:s.onChanged,onSelectChunk:i,onOpenDocument:a}),t?O?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Backlinks`}),_.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:_.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.from_id,e.from_title,e.from_document_id),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),e.auto&&(0,l.jsx)(`span`,{className:`doc-conn-auto`,title:`Auto-linked from a [[wikilink]]`,children:`auto`}),(0,l.jsx)(xt,{statement:e})]},`${e.from_id}-${e.kind}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Related`}),x?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:x}):y.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:y.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.chunk_id,e.title,e.document_id),(0,l.jsx)(`span`,{className:`doc-conn-score`,title:`similarity score`,children:e.score.toFixed(2)})]},`${e.chunk_id}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Unlinked mentions`}),C.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsxs)(`ul`,{className:`doc-conn-list`,children:[C.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-conn-row`,children:D(e.chunk_id,e.title,e.document_id)},`${e.chunk_id}-${t}`)),T&&(0,l.jsx)(`li`,{className:`doc-conn-more`,"aria-hidden":!0,children:`(more…)`})]})]})]}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`loading…`}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`Select a chunk.`})]})]})}var At=24;function jt({edges:e,documentId:t,selectedId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a,incomplete:o}){let[s,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(!1);if(e.length===0)return null;let p=n?e.filter(e=>e.from_id===n||e.to_id===n):[],m=d?e:e.slice(0,At),h=Nt(m);return(0,l.jsxs)(`div`,{className:`doc-refs`,children:[o&&(0,l.jsxs)(`p`,{className:`doc-refs-incomplete`,children:[`Showing the first `,e.length,` links of this document; it has more, which are not shown here or in the graph.`]}),n&&(0,l.jsxs)(`div`,{className:`doc-refs-list-wrap`,children:[(0,l.jsx)(`h4`,{children:`References`}),p.length===0?(0,l.jsx)(`p`,{className:`doc-refs-empty`,children:`This chunk has no links.`}):(0,l.jsx)(`ul`,{className:`doc-refs-list`,children:p.map((e,o)=>(0,l.jsx)(Mt,{edge:e,selectedId:n,documentId:t,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a},`${e.from_id}-${e.to_id}-${e.kind}-${o}`))})]}),(0,l.jsxs)(`div`,{className:`doc-graph`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-graph-toggle`,onClick:()=>u(e=>!e),children:[s?`▼`:`▶`,` relationship graph (`,e.length,`)`]}),s&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)($e,{code:h,onNodeClick:e=>{let n=Pt(m,e);n&&(!n.documentId||n.documentId===t?r(n.id):i?.(n.documentId,n.id,n.title))}}),e.length>At&&(0,l.jsx)(`button`,{type:`button`,className:`doc-graph-more`,onClick:()=>f(e=>!e),children:d?`show top ${At}`:`show all ${e.length}`})]})]})]})}function Mt({edge:e,selectedId:t,documentId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a}){let o=e.from_id===t,s=o?e.to_id:e.from_id,c=o?e.to_title:e.from_title,u=o?e.to_document_id:e.from_document_id;return(0,l.jsxs)(`li`,{className:`doc-ref`,children:[(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),(0,l.jsx)(`span`,{className:`doc-ref-arrow`,"aria-hidden":!0,children:o?`→`:`←`}),(0,l.jsx)(bt,{id:s,title:c,targetDocumentId:u,documentId:n,onSelectChunk:r,onOpenDocument:i}),(0,l.jsx)(xt,{statement:e}),a&&K(e)&&(0,l.jsx)(St,{id:e.id,onRule:a})]})}function Nt(e){let t=[`graph LR`];for(let n of e){let e=`${Ft(n.from_id)}["${It(n.from_title,n.from_id)}"]`,r=`${Ft(n.to_id)}["${It(n.to_title,n.to_id)}"]`,i=(n.kind||`link`).replace(/[|"]/g,` `),a=n.status===`proposed`?`-.->`:`-->`;t.push(` ${e} ${a}|${i}| ${r}`)}return t.join(`
2
+ `)}function Pt(e,t){for(let n of e){if(Ft(n.from_id)===t)return{id:n.from_id,documentId:n.from_document_id,title:n.from_title};if(Ft(n.to_id)===t)return{id:n.to_id,documentId:n.to_document_id,title:n.to_title}}}function Ft(e){return`n`+e.replace(/[^a-zA-Z0-9]/g,``)}function It(e,t){let n=(e??``).replace(/["[\]{}|<>]/g,` `).replace(/\s+/g,` `).trim()||t.slice(0,6);return n.length>30?n.slice(0,29)+`…`:n}function Lt({documentId:e,scope:t,detail:n}){return(0,l.jsxs)(`div`,{className:`doc-unavailable`,role:`alert`,children:[(0,l.jsx)(`p`,{className:`doc-unavailable-lead`,children:`This document can’t be opened.`}),(0,l.jsxs)(`p`,{children:[`It may have been deleted, live in a scope other than `,(0,l.jsx)(`code`,{children:t}),`, or not be yours to read.`]}),(0,l.jsxs)(`p`,{className:`doc-unavailable-detail`,children:[(0,l.jsx)(`code`,{children:e}),n&&(0,l.jsxs)(l.Fragment,{children:[` — `,n]})]})]})}function Rt(e){let t=typeof e==`number`?e/1e6:Date.parse(String(e));return!Number.isFinite(t)||t<=0?String(e??``):new Date(t).toLocaleString()}function zt({chunkId:e,chunkTitle:t,scope:n,browse:r,onClose:i}){let a=j(),[o,s]=(0,c.useState)([]),[u,d]=(0,c.useState)(!0),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(`none`),[g,_]=(0,c.useState)(null),[v,y]=(0,c.useState)(``),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(``);(0,c.useEffect)(()=>{let t=!1;return d(!0),p(null),a.documentHistory(e,n,r).then(e=>{if(t)return;let n=e.revisions??[];if(s(n),n.length>=2){let e=n.map(e=>e.revision);C(Math.min(...e)),T(Math.max(...e))}}).catch(e=>!t&&p(e instanceof Error?e.message:String(e))).finally(()=>!t&&d(!1)),()=>{t=!0}},[a,e,n,r]);let O=async t=>{p(null),x(!0),_(t),h(`version`);try{let i=await a.documentGetVersion(e,t,n,r);y(i.body??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}},k=async()=>{if(S!==null&&w!==null){p(null),x(!0),h(`diff`);try{let t=await a.documentDiff(e,S,w,n,r);D(t.diff??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}}};return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:i,children:(0,l.jsxs)(`div`,{className:`modal history-modal`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`History`,t?` — ${t}`:``]}),(0,l.jsx)(`div`,{className:`modal-buttons modal-buttons-top`,children:(0,l.jsx)(`button`,{type:`button`,onClick:i,children:`close`})})]}),f&&(0,l.jsx)(`div`,{className:`modal-err`,children:f}),u?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):o.length===0?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`No history recorded for this chunk.`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`div`,{className:`doc-hist-revs`,children:o.map(e=>(0,l.jsxs)(`button`,{type:`button`,className:`doc-hist-rev`+(m===`version`&&g===e.revision?` active`:``),onClick:()=>void O(e.revision),children:[(0,l.jsxs)(`span`,{className:`doc-hist-rev-num`,children:[`rev `,e.revision]}),(0,l.jsx)(`span`,{className:`doc-hist-rev-time`,children:Rt(e.created_at)}),(0,l.jsx)(`span`,{className:`doc-hist-rev-actor`,children:e.actor||`unknown`})]},e.revision))}),o.length>=2&&(0,l.jsxs)(`div`,{className:`doc-hist-diffbar`,children:[(0,l.jsx)(`span`,{children:`Compare`}),(0,l.jsx)(`select`,{value:S??``,onChange:e=>C(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff from revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`span`,{"aria-hidden":!0,children:`→`}),(0,l.jsx)(`select`,{value:w??``,onChange:e=>T(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff to revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void k(),disabled:b||S===null||w===null,children:`diff`})]}),(0,l.jsx)(`div`,{className:`doc-hist-output`,children:b?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):m===`diff`?(0,l.jsx)(Bt,{text:E}):m===`version`?(0,l.jsx)(`pre`,{className:`md-pre doc-hist-version`,children:(0,l.jsx)(`code`,{children:v||`(empty)`})}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Select a revision to view it, or compare two.`})})]})]})})}function Bt({text:e}){if(!e.trim())return(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(no differences)`});let t=e.split(`
3
3
  `);return(0,l.jsx)(`pre`,{className:`md-pre doc-hist-diff`,children:t.map((e,t)=>{let n=e.startsWith(`+`)&&!e.startsWith(`+++`)?`diff-add`:e.startsWith(`-`)&&!e.startsWith(`---`)?`diff-del`:e.startsWith(`@@`)?`diff-hunk`:``;return(0,l.jsxs)(`span`,{className:n,children:[e,`
4
- `]},t)})})}function Pt({source:e}){return(0,l.jsx)(`div`,{className:`md`,children:(0,l.jsx)(d.default,{remarkPlugins:[f.default],components:Ft,children:e})})}var Ft={a({href:e,children:t}){let n=e??``,r=/^https?:\/\//i.test(n);return(0,l.jsx)(`a`,{href:n,target:r?`_blank`:void 0,rel:r?`noopener noreferrer`:void 0,children:t})},pre({children:e}){return(0,l.jsx)(l.Fragment,{children:e})},code({className:e,children:t}){let n=/language-(\w+)/.exec(e??``)?.[1],r=String(t??``);return n===`mermaid`?(0,l.jsx)(Ke,{code:r.replace(/\n$/,``)}):n||r.includes(`
5
- `)?(0,l.jsx)(`pre`,{className:`md-pre`,children:(0,l.jsx)(`code`,{className:e,children:t})}):(0,l.jsx)(`code`,{children:t})}};function It(e){let t=e.fields??{};return typeof t.alt==`string`&&t.alt.trim()!==``?t.alt:e.title||`image`}function Lt({documentId:e,scope:t,titleHint:n,browse:r,principal:i,renderAssistant:a,initialChunkId:o,onOpenDocument:s,onTitle:u,onChunkSelect:d,focusChunk:f}){let p=T(),m=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),[h,_]=(0,c.useState)([]),[v,y]=(0,c.useState)(void 0),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(`chunks`),[w,E]=(0,c.useState)(null),[D,O]=(0,c.useState)(null),[k,A]=(0,c.useState)(null),j=(0,c.useRef)(null),[ee,te]=(0,c.useState)(null),[ne,M]=(0,c.useState)(null),[re,N]=(0,c.useState)(!1),[P,F]=(0,c.useState)(!1),[I,L]=(0,c.useState)(null),[ie,ae]=(0,c.useState)(!1),[R,z]=(0,c.useState)(void 0),[B,oe]=(0,c.useState)(null),[V,ce]=(0,c.useState)(0),[H,ue]=(0,c.useState)(!1),[U,pe]=(0,c.useState)(null),[ge,_e]=(0,c.useState)(!1),[W,ve]=(0,c.useState)([]),[ye,G]=(0,c.useState)(!1),[be,xe]=(0,c.useState)(0),[Se,Ce]=(0,c.useState)(0),[we,Te]=(0,c.useState)(void 0),K=(0,c.useCallback)(()=>ce(e=>e+1),[]),Ee=(0,c.useRef)(o);Ee.current=o;let De=(0,c.useRef)(u);De.current=u;let q=(0,c.useMemo)(()=>Re(h),[h]),J=(0,c.useMemo)(()=>h.find(e=>!e.parent_id)?.title||n||`document`,[h,n]),Y=(0,c.useMemo)(()=>!!b&&!b.parent_id,[b]),X=(0,c.useMemo)(()=>he(h,b?.id),[h,b]),Z=(0,c.useMemo)(()=>U?.root_chunk_id??h.find(e=>!e.parent_id)?.id,[U,h]),Q=(0,c.useRef)(d);Q.current=d,(0,c.useEffect)(()=>{v&&Q.current?.(v===Z?void 0:v)},[v,Z]);let je=(0,c.useMemo)(()=>[...new Set(h.map(e=>e.status).filter(e=>!!e))],[h]),Pe=!!U?.color_enabled,Fe=(0,c.useMemo)(()=>{let e=new Set;for(let t of W)e.add(t.from_id),e.add(t.to_id);return e},[W]),Ie=(0,c.useMemo)(()=>Pe?$(Ne(U?.type,U?.status,Me(U?.color_scheme))):void 0,[Pe,U?.type,U?.status,U?.color_scheme]);(0,c.useEffect)(()=>{let n=!1;return ae(!0),L(null),oe(null),p.documentQueryChunks(e,t,m).then(r=>{if(n)return;let i=r.chunks??[];_(i),z(`${t}:${e}`),y(e=>e??se(i,Ee.current))}).catch(e=>{n||(_([]),oe(e instanceof Error?e.message:String(e)))}).finally(()=>!n&&ae(!1)),()=>{n=!0}},[p,e,t,V,m]);let ze=!ie&&(B!==null||R===`${t}:${e}`&&h.length===0),He=(0,c.useMemo)(()=>h.find(t=>!t.parent_id&&t.document_id===e)?.title,[h,e]);(0,c.useEffect)(()=>{He&&De.current?.(e,He)},[e,He]),(0,c.useEffect)(()=>{let n=!1;return p.documentGet(e,t,m).then(e=>!n&&pe(e)).catch(()=>!n&&pe(null)),()=>{n=!0}},[p,e,t,V,m]),(0,c.useEffect)(()=>{let n=!1;return me(p,e,t,m).then(e=>{n||(ve(e.edges),G(e.incomplete))}).catch(()=>{n||(ve([]),G(!1))}),()=>{n=!0}},[p,e,t,V,m,be]),(0,c.useEffect)(()=>{if(!Z||!p.documentAcceptClassification){Te(void 0);return}let n=!1;return p.documentGetChunk(Z,t,m).then(t=>!n&&Te(t.document_id===e?t.fields:void 0)).catch(()=>!n&&Te(void 0)),()=>{n=!0}},[p,e,Z,t,V,m]);let Ue=(0,c.useMemo)(()=>{if(p.documentAcceptStatement&&p.documentRejectStatement)return async(e,n,r)=>{n?await p.documentAcceptStatement(e,t,m,r):await p.documentRejectStatement(e,r??``,t,m),xe(e=>e+1)}},[p,t,m]),We=(0,c.useMemo)(()=>Oe(p,t),[p,t]),Ge=(0,c.useMemo)(()=>ke(W,e),[W,e]),Ye=(0,c.useCallback)(()=>xe(e=>e+1),[]),Xe=(0,c.useMemo)(()=>Ae(We,Ge,ye,Ye),[We,Ge,ye,Ye]),Ze=f?.seq,Qe=(0,c.useRef)(f);Qe.current=f;let $e=(0,c.useRef)(Z);$e.current=Z,(0,c.useEffect)(()=>{if(Ze===void 0)return;let e=Qe.current?.chunkId??$e.current;e&&y(e)},[Ze]),(0,c.useEffect)(()=>{y(void 0),x(null),E(null),C(`chunks`),pe(null),ve([]),G(!1),Ce(0),Te(void 0)},[e,t]),(0,c.useEffect)(()=>{if(!v){x(null);return}let e=!1;return p.documentGetChunk(v,t,m).then(t=>!e&&x(t)).catch(t=>!e&&L(t instanceof Error?t.message:String(t))),()=>{e=!0}},[p,v,t,V,m]),(0,c.useEffect)(()=>{let e=b?.type===`image`||!!b?.asset;if(!b||!e||!p.documentAssetObjectUrl){O(null),A(null);return}let n=!1,r=null;return A(null),p.documentAssetObjectUrl(b.id,t,m).then(e=>{n?URL.revokeObjectURL(e):(r=e,O(e))}).catch(e=>!n&&A(e instanceof Error?e.message:String(e))),()=>{n=!0,r&&URL.revokeObjectURL(r)}},[p,b,t,m]),(0,c.useEffect)(()=>{if(S!==`markdown`||!v){E(null);return}let e=Be(q,v);if(!e)return;let n=!1,r=[],i=(e,t)=>{r.push({node:e,depth:t}),e.children.forEach(e=>i(e,t+1))};return i(e,0),Promise.all(r.map(e=>p.documentGetChunk(e.node.row.id,t,m))).then(e=>{if(n)return;let t=r.map((t,n)=>{let r=Math.min(t.depth+1,6),i=e[n],a=`#`.repeat(r)+` `+t.node.row.title;if(i.type===`mermaid`&&i.body)return a+`
4
+ `]},t)})})}function Vt({source:e}){return(0,l.jsx)(`div`,{className:`md`,children:(0,l.jsx)(d.default,{remarkPlugins:[f.default],components:Ht,children:e})})}var Ht={a({href:e,children:t}){let n=e??``,r=/^https?:\/\//i.test(n);return(0,l.jsx)(`a`,{href:n,target:r?`_blank`:void 0,rel:r?`noopener noreferrer`:void 0,children:t})},pre({children:e}){return(0,l.jsx)(l.Fragment,{children:e})},code({className:e,children:t}){let n=/language-(\w+)/.exec(e??``)?.[1],r=String(t??``);return n===`mermaid`?(0,l.jsx)($e,{code:r.replace(/\n$/,``)}):n||r.includes(`
5
+ `)?(0,l.jsx)(`pre`,{className:`md-pre`,children:(0,l.jsx)(`code`,{className:e,children:t})}):(0,l.jsx)(`code`,{children:t})}};function Ut(e){let t=e.fields??{};return typeof t.alt==`string`&&t.alt.trim()!==``?t.alt:e.title||`image`}function Wt({documentId:e,scope:t,titleHint:n,browse:r,principal:i,renderAssistant:a,initialChunkId:o,onOpenDocument:s,onTitle:u,onChunkSelect:d,focusChunk:f}){let p=j(),m=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),[h,_]=(0,c.useState)([]),[v,y]=(0,c.useState)(void 0),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(`chunks`),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(null),[O,k]=(0,c.useState)(null),A=(0,c.useRef)(null),[M,N]=(0,c.useState)(null),[ee,te]=(0,c.useState)(null),[P,F]=(0,c.useState)(!1),[ne,re]=(0,c.useState)(!1),[ie,I]=(0,c.useState)(null),[L,R]=(0,c.useState)(!1),[z,ae]=(0,c.useState)(void 0),[oe,se]=(0,c.useState)(null),[B,ce]=(0,c.useState)(0),[V,le]=(0,c.useState)(!1),[H,ue]=(0,c.useState)(null),[de,pe]=(0,c.useState)(!1),[me,U]=(0,c.useState)([]),[ge,W]=(0,c.useState)(!1),[ye,xe]=(0,c.useState)(0),[Se,Ce]=(0,c.useState)(0),[we,K]=(0,c.useState)(void 0),q=(0,c.useCallback)(()=>ce(e=>e+1),[]),Te=(0,c.useRef)(o);Te.current=o;let Ee=(0,c.useRef)(u);Ee.current=u;let De=(0,c.useMemo)(()=>Ge(h),[h]),J=(0,c.useMemo)(()=>h.find(e=>!e.parent_id)?.title||n||`document`,[h,n]),Y=(0,c.useMemo)(()=>!!b&&!b.parent_id,[b]),X=(0,c.useMemo)(()=>be(h,b?.id),[h,b]),Z=(0,c.useMemo)(()=>H?.root_chunk_id??h.find(e=>!e.parent_id)?.id,[H,h]),Q=(0,c.useRef)(d);Q.current=d,(0,c.useEffect)(()=>{v&&Q.current?.(v===Z?void 0:v)},[v,Z]);let Oe=(0,c.useMemo)(()=>[...new Set(h.map(e=>e.status).filter(e=>!!e))],[h]),ke=!!H?.color_enabled,Ae=(0,c.useMemo)(()=>{let e=new Set;for(let t of me)e.add(t.from_id),e.add(t.to_id);return e},[me]),je=(0,c.useMemo)(()=>ke?He(Be(H?.type,H?.status,ze(H?.color_scheme))):void 0,[ke,H?.type,H?.status,H?.color_scheme]);(0,c.useEffect)(()=>{let n=!1;return R(!0),I(null),se(null),p.documentQueryChunks(e,t,m).then(r=>{if(n)return;let i=r.chunks??[];_(i),ae(`${t}:${e}`),y(e=>e??fe(i,Te.current))}).catch(e=>{n||(_([]),se(e instanceof Error?e.message:String(e)))}).finally(()=>!n&&R(!1)),()=>{n=!0}},[p,e,t,B,m]);let Fe=!L&&(oe!==null||z===`${t}:${e}`&&h.length===0),Ie=(0,c.useMemo)(()=>h.find(t=>!t.parent_id&&t.document_id===e)?.title,[h,e]);(0,c.useEffect)(()=>{Ie&&Ee.current?.(e,Ie)},[e,Ie]),(0,c.useEffect)(()=>{let n=!1;return p.documentGet(e,t,m).then(e=>!n&&ue(e)).catch(()=>!n&&ue(null)),()=>{n=!0}},[p,e,t,B,m]),(0,c.useEffect)(()=>{let n=!1;return G(p,e,t,m).then(e=>{n||(U(e.edges),W(e.incomplete))}).catch(()=>{n||(U([]),W(!1))}),()=>{n=!0}},[p,e,t,B,m,ye]),(0,c.useEffect)(()=>{if(!Z||!p.documentAcceptClassification){K(void 0);return}let n=!1;return p.documentGetChunk(Z,t,m).then(t=>!n&&K(t.document_id===e?t.fields:void 0)).catch(()=>!n&&K(void 0)),()=>{n=!0}},[p,e,Z,t,B,m]);let Le=(0,c.useMemo)(()=>{if(p.documentAcceptStatement&&p.documentRejectStatement)return async(e,n,r)=>{n?await p.documentAcceptStatement(e,t,m,r):await p.documentRejectStatement(e,r??``,t,m),xe(e=>e+1)}},[p,t,m]),Re=(0,c.useMemo)(()=>Me(p,t),[p,t]),Ve=(0,c.useMemo)(()=>Ne(me,e),[me,e]),$=(0,c.useCallback)(()=>xe(e=>e+1),[]),Ue=(0,c.useMemo)(()=>Pe(Re,Ve,ge,$),[Re,Ve,ge,$]),Ke=f?.seq,Ye=(0,c.useRef)(f);Ye.current=f;let Xe=(0,c.useRef)(Z);Xe.current=Z,(0,c.useEffect)(()=>{if(Ke===void 0)return;let e=Ye.current?.chunkId??Xe.current;e&&y(e)},[Ke]),(0,c.useEffect)(()=>{y(void 0),x(null),T(null),C(`chunks`),ue(null),U([]),W(!1),Ce(0),K(void 0)},[e,t]),(0,c.useEffect)(()=>{if(!v){x(null);return}let e=!1;return p.documentGetChunk(v,t,m).then(t=>!e&&x(t)).catch(t=>!e&&I(t instanceof Error?t.message:String(t))),()=>{e=!0}},[p,v,t,B,m]),(0,c.useEffect)(()=>{let e=b?.type===`image`||!!b?.asset;if(!b||!e||!p.documentAssetObjectUrl){D(null),k(null);return}let n=!1,r=null;return k(null),p.documentAssetObjectUrl(b.id,t,m).then(e=>{n?URL.revokeObjectURL(e):(r=e,D(e))}).catch(e=>!n&&k(e instanceof Error?e.message:String(e))),()=>{n=!0,r&&URL.revokeObjectURL(r)}},[p,b,t,m]),(0,c.useEffect)(()=>{if(S!==`markdown`||!v){T(null);return}let e=qe(De,v);if(!e)return;let n=!1,r=[],i=(e,t)=>{r.push({node:e,depth:t}),e.children.forEach(e=>i(e,t+1))};return i(e,0),Promise.all(r.map(e=>p.documentGetChunk(e.node.row.id,t,m))).then(e=>{if(n)return;let t=r.map((t,n)=>{let r=Math.min(t.depth+1,6),i=e[n],a=`#`.repeat(r)+` `+t.node.row.title;if(i.type===`mermaid`&&i.body)return a+`
6
6
 
7
7
  \`\`\`mermaid
8
8
  `+i.body+"\n```\n";if(i.type===`image`||i.asset){let e=i.body?` — `+i.body:``;return a+`
@@ -12,6 +12,6 @@ _🖼 image chunk_`+e+`
12
12
 
13
13
  `+i.body:``)+`
14
14
  `}).join(`
15
- `);E(t)}).catch(e=>!n&&L(e instanceof Error?e.message:String(e))),()=>{n=!0}},[p,S,v,q,t,V,m]);let et=(0,c.useCallback)(e=>y(e.row.id),[]),tt=(0,c.useCallback)((t,n,r)=>s?.({documentId:t,chunkId:n,title:r},{documentId:e,chunkId:v,title:J}),[s,e,v,J]),nt=(0,c.useCallback)(async()=>{try{let n=await p.documentExportMd(e,t,!0,m),r=new Blob([n.markdown],{type:`text/markdown`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=(n.title||`document`).replace(/[^\w.-]+/g,`_`)+`.md`,a.click(),URL.revokeObjectURL(i)}catch(e){L(e instanceof Error?e.message:String(e))}},[p,e,t,m]),rt=(0,c.useCallback)(async()=>{try{let n=await p.documentExportCanvas(e,t,m),r=new Blob([JSON.stringify(n.canvas,null,2)],{type:`application/json`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=(J||`document`).replace(/[^\w.-]+/g,`_`)+`.canvas`,a.click(),URL.revokeObjectURL(i)}catch(e){L(e instanceof Error?e.message:String(e))}},[p,e,t,m,J]),it=!!p.documentCreateChunk&&!!Z,at=(0,c.useCallback)(async n=>{if(!p.documentCreateChunk||!p.documentSetAsset)return;let r=v||Z;if(r){L(null);try{let{mediaType:i,data:a}=await de(n),o=await p.documentCreateChunk(e,r,{title:n.name||`image`,type:`image`},t,m);await p.documentSetAsset(o.id,i,a,n.name,t,m),K(),y(o.id)}catch(e){L(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Z,K]),ot=(0,c.useCallback)(async()=>{if(!p.documentCreateChunk)return;let n=v||Z;if(n){L(null);try{let r=await p.documentCreateChunk(e,n,{title:`Diagram`,type:`mermaid`,body:`graph TD
16
- A[Start] --> B[End]`},t,m);K(),y(r.id),te(r)}catch(e){L(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Z,K]),st=(0,c.useCallback)(async()=>{if(!p.documentCreateChunk)return;let n=v&&!Y?v:void 0,r=v||Z;if(r){L(null);try{let i=await p.documentCreateChunk(e,n?``:r,{title:`Text`,body:``},t,m,n);K(),y(i.id),te(i)}catch(e){L(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Y,Z,K]),lt=(0,c.useCallback)(async()=>{if(p.documentCreateChunk&&v){L(null);try{let n=await p.documentCreateChunk(e,v,{title:`Text`,body:``},t,m);K(),y(n.id),te(n)}catch(e){L(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,K]),ut=(0,c.useMemo)(()=>{if(!b||Y)return{canUp:!1,canDown:!1};let e=b.parent_id??``,t=h.filter(t=>(t.parent_id??``)===e).sort((e,t)=>e.position-t.position||e.id.localeCompare(t.id)),n=t.findIndex(e=>e.id===b.id);return{canUp:n>0,canDown:n>=0&&n<t.length-1}},[h,b,Y]),ft=(0,c.useCallback)(async e=>{if(p.documentReorderChunk&&v){L(null);try{await p.documentReorderChunk(v,e,t,m),K()}catch(e){L(e instanceof Error?e.message:String(e))}}},[p,v,t,m,K]),pt=(0,c.useCallback)(async()=>{if(!p.documentDeleteChunk||!b)return;L(null);let e=b.parent_id;try{await p.documentDeleteChunk(b.id,t,m),F(!1),y(e||Z),K()}catch(e){L(e instanceof Error?e.message:String(e)),F(!1)}},[p,b,t,m,Z,K]);return(0,c.useEffect)(()=>{if(!it)return;let e=e=>{if(ee||ge)return;let t=document.activeElement,n=t?.tagName;if(n===`INPUT`||n===`TEXTAREA`||t?.isContentEditable)return;let r=fe(e.clipboardData?.items);r&&(e.preventDefault(),at(r))};return window.addEventListener(`paste`,e),()=>window.removeEventListener(`paste`,e)},[it,ee,ge,at]),(0,l.jsxs)(`div`,{className:`doc-viewer`,children:[(0,l.jsx)(`input`,{ref:j,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&at(t)}}),(0,l.jsxs)(`div`,{className:`doc-toolbar`,style:Ie,children:[(0,l.jsx)(`strong`,{className:`doc-title`,title:J,children:J}),(0,l.jsx)(Le,{value:e,label:`doc`}),(0,l.jsxs)(`div`,{className:`doc-toolbar-actions`,children:[it&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void st(),title:`Add a text chunk AFTER the selected chunk, at the same level`,children:`+ text`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void lt(),disabled:!v,title:v?`Add a chunk NESTED UNDER the selected chunk (in the ontology, a child is a subclass)`:`Select a chunk first — this nests a new chunk under it`,children:`+ child`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>j.current?.click(),title:`Add an image chunk (upload — or paste a screenshot into the view)`,children:`+ image`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ot(),title:`Add a Mermaid diagram chunk`,children:`+ diagram`})]}),(0,l.jsx)(`button`,{type:`button`,className:Pe?`active`:``,onClick:()=>_e(!0),disabled:!Z,title:`Colors — tint chunk tiles + the Path tree by type/status`,children:`colors`}),p.documentClassify&&(0,l.jsx)(`button`,{type:`button`,className:Se>0?`active`:``,onClick:()=>Ce(e=>e>0?0:1),title:`Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)`,children:`classify`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void nt(),title:`Download the whole document as Markdown (.md)`,children:`↓ .md`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void rt(),title:`Download the whole document as a node/edge canvas graph (.canvas)`,children:`↓ .canvas`}),a&&(0,l.jsx)(`button`,{type:`button`,className:H?`active`:``,onClick:()=>ue(e=>!e),title:`Document Assistant — instruct an agent to restructure/import/link chunks`,children:`assistant`}),(0,l.jsx)(`button`,{type:`button`,onClick:K,title:`Reload`,children:`↻`})]})]}),I&&(0,l.jsx)(`div`,{className:`paths-err`,children:I}),!ze&&(0,l.jsx)(ct,{documentId:e,scope:t,browse:m,rootFields:we,requestKey:Se,onClose:()=>Ce(0),onChanged:K},`${t}:${e}`),ze?(0,l.jsx)(At,{documentId:e,scope:t,detail:B??void 0}):(0,l.jsxs)(le,{className:`doc-split`,defaultLeftWidth:320,minLeftWidth:160,minRightWidth:320,storageKey:`loomcycle.explorer.split.doc`,children:[(0,l.jsx)(`div`,{className:`doc-chunktree`,children:ie&&h.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):(0,l.jsx)(Ve,{tree:q,selectedId:v,onSelect:et,colorEnabled:Pe,scheme:U?.color_scheme,linkedIds:Fe})}),(0,l.jsx)(`div`,{className:`doc-content`,children:b?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-content-head`,children:[X.length>0&&(0,l.jsxs)(`nav`,{className:`chunk-ancestry`,"aria-label":`Chunks above this one`,children:[(0,l.jsx)(`button`,{type:`button`,className:`chunk-ancestry-up`,onClick:()=>y(X[X.length-1].id),title:`Up to ${X[X.length-1].title||`(untitled)`}`,children:`↰ Up`}),(0,l.jsxs)(`ol`,{className:`doc-trail-list`,children:[X.map(e=>(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>y(e.id),title:e.title||`(untitled)`,children:e.title||`(untitled)`})},e.id)),(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`location`,title:b.title||`(untitled)`,children:b.title||`(untitled)`})})]})]}),(0,l.jsx)(`h3`,{children:b.title||`(untitled)`}),(0,l.jsxs)(`div`,{className:`doc-content-meta`,children:[b.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:b.type}),b.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:b.status}),(0,l.jsxs)(`span`,{className:`chunk-rev`,children:[`rev `,b.revision]}),b.tags?.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e)),(0,l.jsx)(Le,{value:b.id,label:`chunk`})]}),(0,l.jsxs)(`div`,{className:`doc-content-controls`,children:[(0,l.jsxs)(`div`,{className:`doc-mode-toggle`,children:[(0,l.jsx)(`button`,{type:`button`,className:S===`chunks`?`active`:``,onClick:()=>C(`chunks`),title:`This chunk's own content`,children:`chunk`}),(0,l.jsx)(`button`,{type:`button`,className:S===`markdown`?`active`:``,onClick:()=>C(`markdown`),title:Y?`Whole document as Markdown`:`This chunk + its sub-chunks as Markdown`,children:`markdown`})]}),(0,l.jsx)(`button`,{type:`button`,className:`chunk-edit`,onClick:()=>te(b),children:`edit`}),p.documentEntityTypes&&g(b)&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>M(b),title:`Change this subject's type to another type in force`,children:`change type`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>N(!0),title:`View this chunk's edit history + diffs`,children:`history`}),!Y&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ft(`up`),disabled:!ut.canUp,title:`Move this chunk up within its level`,children:`↑`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ft(`down`),disabled:!ut.canDown,title:`Move this chunk down within its level`,children:`↓`})]}),!Y&&(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>F(!0),title:`Delete this chunk and its sub-chunks`,children:`delete`})]})]}),(0,l.jsx)(`div`,{className:`doc-content-body`,children:b.type===`mermaid`?b.body?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Ke,{code:b.body}),S===`markdown`&&(0,l.jsx)(`pre`,{className:`md-pre doc-mermaid-source`,children:(0,l.jsx)(`code`,{children:b.body})})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty diagram)`}):b.type===`image`||b.asset?k?(0,l.jsxs)(`p`,{className:`doc-empty-body`,children:[`Image failed to load: `,k]}):D?(0,l.jsxs)(`figure`,{className:`doc-image`,children:[(0,l.jsx)(`img`,{src:D,alt:It(b)}),b.body&&(0,l.jsx)(`figcaption`,{children:b.body})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Loading image…`}):S===`markdown`?w===null?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Assembling Markdown…`}):(0,l.jsx)(Pt,{source:w}):b.body?(0,l.jsx)(Pt,{source:b.body}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty chunk)`})}),(0,l.jsx)(wt,{edges:W,incomplete:ye,documentId:e,selectedId:v,onSelectChunk:y,onOpenDocument:s?tt:void 0,onRuleStatement:Ue}),(0,l.jsx)(St,{documentId:e,selectedId:v,scope:t,browse:m,onSelectChunk:y,onOpenDocument:s?tt:void 0,refreshKey:be,review:Xe})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a chunk on the left.`})})})]}),H&&a&&(0,l.jsx)(`div`,{className:`doc-assistant`,children:a({documentId:e,scope:t,subject:i?.subject,onChanged:K})}),ee&&(0,l.jsx)(qe,{chunk:ee,scope:t,browse:m,onClose:()=>te(null),onSaved:K}),ne&&(0,l.jsx)(Je,{chunk:ne,scope:t,browse:m,onClose:()=>M(null),onSaved:K}),re&&b&&(0,l.jsx)(Mt,{chunkId:b.id,chunkTitle:b.title,scope:t,browse:m,onClose:()=>N(!1)}),ge&&Z&&(0,l.jsx)(dt,{documentId:e,rootChunkId:Z,docType:U?.type,docStatus:U?.status,chunkStatuses:je,scope:t,browse:m,onClose:()=>_e(!1),onSaved:K}),P&&b&&(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:()=>F(!1),children:(0,l.jsxs)(`div`,{className:`modal chunk-delete-confirm`,onClick:e=>e.stopPropagation(),children:[(0,l.jsx)(`h3`,{children:`Delete chunk`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`Delete “`,b.title||`(untitled)`,`” and all of its sub-chunks? This cannot be undone.`]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>F(!1),children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>void pt(),children:`delete`})]})]})})]})}function Rt(e,t=``){let n=e.get(t);if(!n)return[];let r=n.entries.map(n=>{let r=n.kind===`directory`&&n.full_path.startsWith(`${t}/`);return{name:n.name,fullPath:n.full_path,kind:n.kind,resourceRef:n.resource_ref,listing:r?e.get(n.full_path):void 0,children:r?Rt(e,n.full_path):[]}});return r.sort((e,t)=>{let n=e.kind===`directory`;return n===(t.kind===`directory`)?e.name.localeCompare(t.name):n?-1:1}),r}var zt={directory:`📁`,document:`📄`,volume_mount:`💾`,memory_entry:`🧠`};function Bt(e){let{tree:t,root:n}=e;return!n||!n.loaded&&n.loading?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):n.loaded&&t.length===0&&!n.nextCursor?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`This tree is empty. Create a folder or document to begin.`})}):(0,l.jsxs)(`ul`,{className:`tree path-tree`,children:[t.map(t=>(0,l.jsx)(Ut,{node:t,...e},t.fullPath)),(0,l.jsx)(Vt,{dir:``,listing:n,...e})]})}function Vt({dir:e,listing:t,onLoadMore:n,onRetry:r}){let i=[];return!t||t.loading&&t.entries.length===0?i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`loading…`})},`status`)):t.error?i.push((0,l.jsxs)(`li`,{className:`node path-status`,children:[e!==``&&(0,l.jsxs)(`span`,{className:`path-err`,children:[`failed to load: `,t.error]}),` `,(0,l.jsx)(`button`,{type:`button`,className:`path-more`,onClick:()=>r(e),children:`retry`})]},`status`)):t.loaded&&t.entries.length===0&&e!==``&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`empty`})},`status`)),t?.nextCursor&&!t.error&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`button`,{type:`button`,className:`path-more`,disabled:t.loading,onClick:()=>n(e),children:t.loading?`loading…`:`Load more (${t.entries.length} shown)`})},`more`)),(0,l.jsx)(l.Fragment,{children:i})}function Ht(e,t){if(e.kind!==`document`||!t)return;let n=e.resourceRef;return n?.document_id?t.get(n.document_id):void 0}function Ut(e){let{node:t,expanded:n,onToggle:r,selectedPath:i,onSelect:a,summaries:o}=e,s=t.kind===`directory`,c=s&&n.has(t.fullPath),u=i===t.fullPath,d=Ht(t,o),f=d&&d.color_enabled?$(Ne(d.type,d.status,Me(d.color_scheme))):void 0;return(0,l.jsxs)(`li`,{className:`node path-node kind-${t.kind} ${u?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row path-row`,style:f,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":c?`collapse`:`expand`,"aria-expanded":s?c:void 0,disabled:!s,onClick:e=>{e.stopPropagation(),s&&r(t.fullPath)},children:s?c?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`path-link`,onClick:()=>a(t),title:t.fullPath,children:[(0,l.jsx)(`span`,{className:`path-kind-icon`,"aria-hidden":!0,children:zt[t.kind]??`•`}),(0,l.jsx)(`span`,{className:`path-name`,children:t.name}),d?.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:d.type}),d?.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:d.status})]})]}),c&&(0,l.jsxs)(`ul`,{className:`children path-children`,children:[t.children.map(t=>(0,l.jsx)(Ut,{...e,node:t},t.fullPath)),(0,l.jsx)(Vt,{...e,dir:t.fullPath,listing:t.listing})]})]})}var Wt=/^[A-Za-z0-9._-]+$/;function Gt(e,t){return`${e}/${t}`}function Kt(e,t){for(let n of e){if(n.fullPath===t)return n;let e=Kt(n.children,t);if(e)return e}}function qt(e){let{theme:t,defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d}=e,f=F(e);return(0,l.jsx)(I,{theme:t,dataLayer:f,children:(0,l.jsx)(Jt,{defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d})})}function Jt({defaultScope:e,path:t,onPathChange:n,browse:r,principal:i,renderAssistant:a,renderNavigator:o,navigator:s,onError:u}){let d=T(),[f,p]=(0,c.useState)(e??`user`),[g,_]=(0,c.useState)(void 0),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(()=>new Set),w=t===void 0?g:t,E=(0,c.useRef)(n);(0,c.useEffect)(()=>{E.current=n},[n]);let D=(0,c.useRef)(u);(0,c.useEffect)(()=>{D.current=u},[u]);let[A,j]=(0,c.useState)([]),M=(0,c.useRef)(0),re=(0,c.useRef)(void 0),N=(0,c.useCallback)(e=>{re.current=e,E.current?.(e),_(e)},[]),P=(0,c.useCallback)(e=>{M.current++,j(e=>e.length>0?[]:e),N(e)},[N]);(0,c.useEffect)(()=>{t!==void 0&&t!==re.current&&(M.current++,j(e=>e.length>0?[]:e))},[t]);let F=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),I=(0,c.useMemo)(()=>new ee(d,f,F),[d,f,F]),R=(0,c.useSyncExternalStore)(I.subscribe,I.getSnapshot),B=(0,c.useCallback)(e=>{D.current?.(e)},[]),[V,se]=(0,c.useState)(()=>o?m(globalThis.localStorage):`tree`),H=!!o&&V===`stars`,ue=(0,c.useCallback)(e=>{se(e),h(globalThis.localStorage,e),e===`tree`&&de(!1)},[]),[U,de]=(0,c.useState)(!1),[fe,pe]=(0,c.useState)(0);(0,c.useEffect)(()=>{o&&s&&ue(s)},[s]);let[me,he]=(0,c.useState)(),[ge,_e]=(0,c.useState)(),W=(0,c.useCallback)((e,t)=>(pe(e=>e+1),I.invalidate(e,t)),[I]),[ve,ye]=(0,c.useState)(()=>new Map),G=(0,c.useRef)(new Set),be=(0,c.useRef)(0),xe=(0,c.useCallback)(()=>{be.current++,G.current=new Set,ye(new Map)},[]),Se=(0,c.useRef)(!0);(0,c.useEffect)(()=>{Se.current?Se.current=!1:(P(void 0),y(null),C(new Set),xe()),I.loadDir(``).catch(B)},[I,P,xe,B]),(0,c.useEffect)(()=>{for(let e of S)R.has(e)||I.loadDir(e).catch(B)},[I,S,R,B]);let Ce=(0,c.useRef)(null);(0,c.useEffect)(()=>{let e=Ce.current!==null&&Ce.current!==I;if(Ce.current=I,!w||e)return;let t=k(w).filter(e=>e!==``);C(e=>{if(t.every(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.add(e)),n}),I.reveal(w).catch(B)},[I,w,B]),(0,c.useEffect)(()=>{if(f===`tenant`)return;let e=[];for(let t of R.values())for(let n of ne(t.entries))G.current.has(n)||(G.current.add(n),e.push(n));let t=be.current;for(let n=0;n<e.length;n+=500)d.documentsSummary({documentIds:e.slice(n,n+500)},f,F).then(e=>{be.current===t&&ye(t=>{let n=new Map(t);for(let t of e.documents??[])n.set(t.document_id,t);return n})}).catch(()=>{})},[d,R,f,F]);let we=(0,c.useMemo)(()=>Rt(R),[R]),Te=(0,c.useCallback)(async()=>{y(null),xe(),pe(e=>e+1),await I.refresh(S).catch(B),w&&await I.reveal(w).catch(B)},[I,S,w,xe,B]),K=(0,c.useCallback)(e=>{C(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ee=(0,c.useCallback)(e=>I.loadMore(e).catch(B),[I,B]),De=(0,c.useCallback)(e=>{(I.getSnapshot().get(e)?.loaded?I.loadMore(e):I.loadDir(e)).catch(B)},[I,B]),q=(0,c.useMemo)(()=>w?Kt(we,w):void 0,[we,w]),J=R.get(``)?.error,Y=q?.kind===`directory`?q.fullPath:void 0,[Oe,ke]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!Y||!d.pathIsStored)return;let e=!1;return d.pathIsStored(Y,f,F).then(t=>{e||ke({path:Y,explicit:t})},()=>{}),()=>{e=!0}},[d,Y,f,F]);let Ae=q?q.kind===`directory`?Oe?.path===q.fullPath?Oe.explicit?`yes`:`implicit (no entry)`:void 0:`yes`:void 0,X=(0,c.useMemo)(()=>q?q.kind===`directory`?q.fullPath:O(q.fullPath):``,[q]),Z=X||`/`,Q=f!==`tenant`,je=(0,c.useCallback)(()=>{x({title:`New folder in ${Z}`,fields:[{key:`name`,label:`Folder name`,placeholder:`e.g. launches`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!Wt.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=Gt(X,t);await d.pathMkdir(n,f,F),await W(n).catch(B),P(n)}})},[d,I,X,Z,f,F,B,P]),Me=(0,c.useCallback)(()=>{x({title:`New document in ${Z}`,fields:[{key:`name`,label:`Path name`,placeholder:`e.g. launch-plan`},{key:`title`,label:`Title`,placeholder:`e.g. Launch Plan`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!Wt.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=e.title.trim()||t,r=Gt(X,t);await d.documentCreate(n,r,f,F),await W(r).catch(B),P(r)}})},[d,I,X,Z,f,F,B,P]),Ne=(0,c.useCallback)(()=>{q&&x({title:`Rename / move ${q.fullPath}`,fields:[{key:`to`,label:`New path`,value:q.fullPath}],submitLabel:`Move`,onSubmit:async e=>{let t=e.to.trim();if(!t.startsWith(`/`))throw Error(`path must start with /`);await d.pathMv(q.fullPath,t,f,F),await Promise.all([W(q.fullPath,{dropSubtree:!0}),W(t)]).catch(B),P(t)}})},[d,I,q,f,F,B,P]),Pe=(0,c.useCallback)(()=>{if(!q)return;if(q.kind===`document`){let e=q.resourceRef?.document_id;x({title:`Delete document ${q.fullPath}`,message:`This deletes the document, all its chunks, and its path entry. This cannot be undone.`,fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{if(!e)throw Error(`this document dirent has no document_id`);await d.documentDelete(e,f,F),await W(q.fullPath).catch(B),P(void 0)}});return}let e=q;y(null),(async()=>{let t;try{t=await te(d,e.fullPath,f,F)}catch(t){y(`could not list ${e.fullPath} for delete: ${t instanceof Error?t.message:String(t)}`);return}let n=f===`tenant`?[]:ne(t);x({title:`Delete branch ${e.fullPath}`,message:t.length===0?`This removes the (empty) folder.`:`This removes the folder and everything under it`+(n.length>0?` — including ${n.length} document(s), whose chunks are deleted.`:`.`),fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{for(let e of n)await d.documentDelete(e,f,F);await d.pathRm(e.fullPath,f,!0,F),await W(e.fullPath,{dropSubtree:!0}).catch(B),P(void 0)}})})()},[d,I,q,f,F,B,P]),Fe=q&&(q.kind===`directory`||q.kind===`document`),$=(0,c.useMemo)(()=>{if(A.length>0)return A[A.length-1];if(q?.kind===`document`)return{documentId:q.resourceRef?.document_id??``,path:q.fullPath,title:q.name}},[A,q]),Ie=(0,c.useCallback)((e,t)=>{let n=++M.current,r=oe(I.getSnapshot(),e.documentId);j(L(A,{...t,path:$?.path},{...e,path:r})),N(r),!r&&d.documentPath&&d.documentPath(e.documentId,f,F).then(t=>{t&&M.current===n&&(j(n=>ae(n,e.documentId,{path:t})),N(t))},()=>{})},[d,I,A,$?.path,f,F,N]),Le=(0,c.useCallback)(e=>{let t=ie(A,e);t!==A&&(M.current++,j(t),N(t[t.length-1].path))},[A,N]),Re=(0,c.useCallback)((e,t)=>j(n=>ae(n,e,{title:t})),[]),ze=(0,c.useCallback)(e=>{_e(t=>({documentId:e.documentId,chunkId:e.chunkId,seq:(t?.seq??0)+1})),$?.documentId!==e.documentId&&(e.path?P(e.path):(M.current++,j([{documentId:e.documentId,chunkId:e.chunkId}]),N(void 0)))},[$?.documentId,P,N]),Be=(0,c.useMemo)(()=>({scope:f,browse:F,selection:{documentId:$?.documentId,chunkId:me&&me.documentId===$?.documentId?me.chunkId:void 0,path:$?.path},onSelect:ze,reloadToken:fe,maximized:U,onToggleMaximize:()=>de(e=>!e),subject:i?.subject}),[f,F,$?.documentId,$?.path,me,ze,fe,U,i?.subject]),Ve=ge&&$&&ge.documentId===$.documentId?ge:void 0,He=!!$?.path&&q?.kind===`document`&&q.fullPath===$.path;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(le,{className:H?`paths-view paths-view--stars`:`paths-view`,defaultLeftWidth:H?720:420,minLeftWidth:280,minRightWidth:300,storageKey:H?`loomcycle.explorer.split.stars`:`loomcycle.explorer.split.paths`,hideRight:H&&U,children:[(0,l.jsxs)(`div`,{className:`left`,children:[(0,l.jsxs)(`div`,{className:`paths-toolbar`,children:[(0,l.jsxs)(`label`,{className:`paths-scope`,children:[(0,l.jsx)(`span`,{children:`scope`}),(0,l.jsxs)(`select`,{value:f,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),o&&(0,l.jsxs)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Navigator`,children:[(0,l.jsx)(`button`,{type:`button`,"aria-pressed":!H,className:H?void 0:`active`,onClick:()=>ue(`tree`),title:`Browse the Path tree`,children:`tree`}),(0,l.jsx)(`button`,{type:`button`,"aria-pressed":H,className:H?`active`:void 0,onClick:()=>ue(`stars`),title:`Browse the scope as a 3D star map`,children:`stars`})]}),(0,l.jsxs)(`div`,{className:`paths-toolbar-actions`,children:[!H&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:je,title:`New folder in ${Z}`,children:`+ folder`}),(0,l.jsx)(`button`,{type:`button`,onClick:Me,disabled:!Q,title:Q?`New document in ${Z}`:`Documents are agent/user scope only`,children:`+ document`})]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void Te(),title:`Reload the tree`,children:`↻`})]})]}),!H&&(0,l.jsxs)(`p`,{className:`paths-context`,children:[`new items → `,(0,l.jsx)(`code`,{children:Z}),F?.scopeId&&(0,l.jsxs)(l.Fragment,{children:[` · `,`subject `,(0,l.jsx)(`code`,{children:F.scopeId})]}),F?.tenant&&(0,l.jsxs)(l.Fragment,{children:[` · `,`tenant `,(0,l.jsx)(`code`,{children:F.tenant})]})]}),(v||J)&&(0,l.jsx)(`div`,{className:`paths-err`,children:v||J}),H&&o?(0,l.jsx)(`div`,{className:`paths-navigator`,children:o(Be)}):(0,l.jsx)(Bt,{tree:we,root:R.get(``),expanded:S,onToggle:K,onLoadMore:Ee,onRetry:De,selectedPath:w,onSelect:e=>P(e.fullPath),summaries:ve})]}),(0,l.jsx)(`div`,{className:`right`,children:$?(0,l.jsxs)(`div`,{className:`paths-doc`,children:[(0,l.jsx)(ce,{trail:A,onJump:Le}),(0,l.jsxs)(`div`,{className:`paths-doc-head`,children:[$.path?(0,l.jsx)(`code`,{className:`paths-doc-path`,children:$.path}):(0,l.jsxs)(`span`,{className:`paths-doc-path paths-doc-unfiled`,title:`Opened by id — no entry for this document was found in the Path tree`,children:[z($),` `,(0,l.jsx)(`em`,{children:`· opened by id, not in the tree`})]}),He&&(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Ne,children:`rename / move`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Pe,children:`delete`})]})]}),(0,l.jsx)(Lt,{documentId:$.documentId,scope:f,titleHint:$.title,browse:F,principal:i,renderAssistant:a,initialChunkId:$.chunkId??Ve?.chunkId,onOpenDocument:Ie,onTitle:Re,onChunkSelect:e=>he({documentId:$.documentId,chunkId:e}),focusChunk:Ve},A.length)]}):q?(0,l.jsxs)(`div`,{className:`paths-detail`,children:[(0,l.jsxs)(`h2`,{children:[(0,l.jsx)(`span`,{className:`paths-detail-kind`,children:q.kind}),(0,l.jsx)(`code`,{children:q.fullPath})]}),(0,l.jsxs)(`dl`,{className:`paths-detail-meta`,children:[(0,l.jsx)(`dt`,{children:`scope`}),(0,l.jsx)(`dd`,{children:f}),Ae&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`stored`}),(0,l.jsx)(`dd`,{children:Ae})]})]}),Fe?(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Ne,children:`rename / move`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Pe,children:`delete`})]}):(0,l.jsxs)(`p`,{className:`paths-readonly`,children:[`Read-only — `,q.kind,` entries are managed by their own tool.`]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a path on the left, or create a folder / document.`})})})]}),b&&(0,l.jsx)(Yt,{state:b,onClose:()=>x(null)})]})}function Yt({state:e,onClose:t}){let[n,r]=(0,c.useState)(()=>Object.fromEntries(e.fields.map(e=>[e.key,e.value??``]))),[i,a]=(0,c.useState)(!1),[o,s]=(0,c.useState)(null);return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:t,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async r=>{r.preventDefault(),a(!0),s(null);try{await e.onSubmit(n),t()}catch(e){s(e instanceof Error?e.message:String(e)),a(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:e.title}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:t,disabled:i,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:e.danger?`danger`:`primary`,disabled:i,children:i?`working…`:e.submitLabel})]})]}),e.message&&(0,l.jsx)(`p`,{className:`modal-context`,children:e.message}),e.fields.map((e,t)=>(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:e.label}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:n[e.key],placeholder:e.placeholder,autoFocus:t===0,onChange:t=>r(n=>({...n,[e.key]:t.target.value}))})]},e.key)),o&&(0,l.jsx)(`div`,{className:`modal-err`,children:o})]})})}function Xt(e){let{documentId:t,scope:n,browse:r,theme:i}=e,a=F(e);return(0,l.jsx)(I,{theme:i,dataLayer:a,children:(0,l.jsx)(Zt,{...e},`${n}:${t}:${r?.scopeId??``}:${r?.tenant??``}`)})}function Zt({documentId:e,scope:t,titleHint:n,browse:r,principal:i,renderAssistant:a,onOpenDocument:o}){let[s,u]=(0,c.useState)([]),d=s[s.length-1],f=(0,c.useCallback)((e,t)=>{o?o(e,t):u(n=>L(n,t,e))},[o]),p=(0,c.useCallback)(e=>u(t=>ie(t,e)),[]),m=(0,c.useCallback)((e,t)=>u(n=>ae(n,e,{title:t})),[]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(ce,{trail:s,onJump:p}),(0,l.jsx)(Lt,{documentId:d?.documentId??e,scope:t,titleHint:d?d.title:n,browse:r,principal:i,renderAssistant:a,initialChunkId:d?.chunkId,onOpenDocument:f,onTitle:m},s.length)]})}exports.DEFAULT_SCHEME=Q,exports.DocumentViewer=Xt,exports.EDGE_PAGE_CAP=pe,exports.PathExplorer=qt,exports.QUEUE_CHANGED_RETRIES=Te,exports.RULING_CHUNK=we,exports.RequestError=N,exports.assetFetchFromConnection=re,exports.chunkColor=Pe,exports.chunkCount=J,exports.createLoomcycleClient=M,exports.dataLayerFromClient=x,exports.docColor=Ne,exports.effectiveScheme=Me,exports.hexToTint=Fe,exports.isQueueChanged=Ee,exports.jsonPostFromConnection=P,exports.loadDocumentEdges=me,exports.runRuling=De,exports.tintStyle=$,exports.undoRulings=q;
15
+ `);T(t)}).catch(e=>!n&&I(e instanceof Error?e.message:String(e))),()=>{n=!0}},[p,S,v,De,t,B,m]);let Ze=(0,c.useCallback)(e=>y(e.row.id),[]),Qe=(0,c.useCallback)((t,n,r)=>s?.({documentId:t,chunkId:n,title:r},{documentId:e,chunkId:v,title:J}),[s,e,v,J]),nt=(0,c.useCallback)(async()=>{try{let n=await p.documentExportMd(e,t,!0,m),r=new Blob([n.markdown],{type:`text/markdown`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=(n.title||`document`).replace(/[^\w.-]+/g,`_`)+`.md`,a.click(),URL.revokeObjectURL(i)}catch(e){I(e instanceof Error?e.message:String(e))}},[p,e,t,m]),rt=(0,c.useCallback)(async()=>{try{let n=await p.documentExportCanvas(e,t,m),r=new Blob([JSON.stringify(n.canvas,null,2)],{type:`application/json`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=(J||`document`).replace(/[^\w.-]+/g,`_`)+`.canvas`,a.click(),URL.revokeObjectURL(i)}catch(e){I(e instanceof Error?e.message:String(e))}},[p,e,t,m,J]),it=!!p.documentCreateChunk&&!!Z,at=(0,c.useCallback)(async n=>{if(!p.documentCreateChunk||!p.documentSetAsset)return;let r=v||Z;if(r){I(null);try{let{mediaType:i,data:a}=await _e(n),o=await p.documentCreateChunk(e,r,{title:n.name||`image`,type:`image`},t,m);await p.documentSetAsset(o.id,i,a,n.name,t,m),q(),y(o.id)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Z,q]),ot=(0,c.useCallback)(async()=>{if(!p.documentCreateChunk)return;let n=v||Z;if(n){I(null);try{let r=await p.documentCreateChunk(e,n,{title:`Diagram`,type:`mermaid`,body:`graph TD
16
+ A[Start] --> B[End]`},t,m);q(),y(r.id),N(r)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Z,q]),st=(0,c.useCallback)(async()=>{if(!p.documentCreateChunk)return;let n=v&&!Y?v:void 0,r=v||Z;if(r){I(null);try{let i=await p.documentCreateChunk(e,n?``:r,{title:`Text`,body:``},t,m,n);q(),y(i.id),N(i)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Y,Z,q]),ct=(0,c.useCallback)(async()=>{if(p.documentCreateChunk&&v){I(null);try{let n=await p.documentCreateChunk(e,v,{title:`Text`,body:``},t,m);q(),y(n.id),N(n)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,q]),lt=(0,c.useMemo)(()=>{if(!b||Y)return{canUp:!1,canDown:!1};let e=b.parent_id??``,t=h.filter(t=>(t.parent_id??``)===e).sort((e,t)=>e.position-t.position||e.id.localeCompare(t.id)),n=t.findIndex(e=>e.id===b.id);return{canUp:n>0,canDown:n>=0&&n<t.length-1}},[h,b,Y]),ut=(0,c.useCallback)(async e=>{if(p.documentReorderChunk&&v){I(null);try{await p.documentReorderChunk(v,e,t,m),q()}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,v,t,m,q]),dt=(0,c.useCallback)(async()=>{if(!p.documentDeleteChunk||!b)return;I(null);let e=b.parent_id;try{await p.documentDeleteChunk(b.id,t,m),re(!1),y(e||Z),q()}catch(e){I(e instanceof Error?e.message:String(e)),re(!1)}},[p,b,t,m,Z,q]);return(0,c.useEffect)(()=>{if(!it)return;let e=e=>{if(M||de)return;let t=document.activeElement,n=t?.tagName;if(n===`INPUT`||n===`TEXTAREA`||t?.isContentEditable)return;let r=ve(e.clipboardData?.items);r&&(e.preventDefault(),at(r))};return window.addEventListener(`paste`,e),()=>window.removeEventListener(`paste`,e)},[it,M,de,at]),(0,l.jsxs)(`div`,{className:`doc-viewer`,children:[(0,l.jsx)(`input`,{ref:A,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&at(t)}}),(0,l.jsxs)(`div`,{className:`doc-toolbar`,style:je,children:[(0,l.jsx)(`strong`,{className:`doc-title`,title:J,children:J}),(0,l.jsx)(We,{value:e,label:`doc`}),(0,l.jsxs)(`div`,{className:`doc-toolbar-actions`,children:[it&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void st(),title:`Add a text chunk AFTER the selected chunk, at the same level`,children:`+ text`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ct(),disabled:!v,title:v?`Add a chunk NESTED UNDER the selected chunk (in the ontology, a child is a subclass)`:`Select a chunk first — this nests a new chunk under it`,children:`+ child`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>A.current?.click(),title:`Add an image chunk (upload — or paste a screenshot into the view)`,children:`+ image`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ot(),title:`Add a Mermaid diagram chunk`,children:`+ diagram`})]}),(0,l.jsx)(`button`,{type:`button`,className:ke?`active`:``,onClick:()=>pe(!0),disabled:!Z,title:`Colors — tint chunk tiles + the Path tree by type/status`,children:`colors`}),p.documentClassify&&(0,l.jsx)(`button`,{type:`button`,className:Se>0?`active`:``,onClick:()=>Ce(e=>e>0?0:1),title:`Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)`,children:`classify`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void nt(),title:`Download the whole document as Markdown (.md)`,children:`↓ .md`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void rt(),title:`Download the whole document as a node/edge canvas graph (.canvas)`,children:`↓ .canvas`}),a&&(0,l.jsx)(`button`,{type:`button`,className:V?`active`:``,onClick:()=>le(e=>!e),title:`Document Assistant — instruct an agent to restructure/import/link chunks`,children:`assistant`}),(0,l.jsx)(`button`,{type:`button`,onClick:q,title:`Reload`,children:`↻`})]})]}),ie&&(0,l.jsx)(`div`,{className:`paths-err`,children:ie}),!Fe&&(0,l.jsx)(ht,{documentId:e,scope:t,browse:m,rootFields:we,requestKey:Se,onClose:()=>Ce(0),onChanged:q},`${t}:${e}`),Fe?(0,l.jsx)(Lt,{documentId:e,scope:t,detail:oe??void 0}):(0,l.jsxs)(he,{className:`doc-split`,defaultLeftWidth:320,minLeftWidth:160,minRightWidth:320,storageKey:`loomcycle.explorer.split.doc`,children:[(0,l.jsx)(`div`,{className:`doc-chunktree`,children:L&&h.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):(0,l.jsx)(Je,{tree:De,selectedId:v,onSelect:Ze,colorEnabled:ke,scheme:H?.color_scheme,linkedIds:Ae})}),(0,l.jsx)(`div`,{className:`doc-content`,children:b?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-content-head`,children:[X.length>0&&(0,l.jsxs)(`nav`,{className:`chunk-ancestry`,"aria-label":`Chunks above this one`,children:[(0,l.jsx)(`button`,{type:`button`,className:`chunk-ancestry-up`,onClick:()=>y(X[X.length-1].id),title:`Up to ${X[X.length-1].title||`(untitled)`}`,children:`↰ Up`}),(0,l.jsxs)(`ol`,{className:`doc-trail-list`,children:[X.map(e=>(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>y(e.id),title:e.title||`(untitled)`,children:e.title||`(untitled)`})},e.id)),(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`location`,title:b.title||`(untitled)`,children:b.title||`(untitled)`})})]})]}),(0,l.jsx)(`h3`,{children:b.title||`(untitled)`}),(0,l.jsxs)(`div`,{className:`doc-content-meta`,children:[b.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:b.type}),b.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:b.status}),(0,l.jsxs)(`span`,{className:`chunk-rev`,children:[`rev `,b.revision]}),b.tags?.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e)),(0,l.jsx)(We,{value:b.id,label:`chunk`})]}),(0,l.jsxs)(`div`,{className:`doc-content-controls`,children:[(0,l.jsxs)(`div`,{className:`doc-mode-toggle`,children:[(0,l.jsx)(`button`,{type:`button`,className:S===`chunks`?`active`:``,onClick:()=>C(`chunks`),title:`This chunk's own content`,children:`chunk`}),(0,l.jsx)(`button`,{type:`button`,className:S===`markdown`?`active`:``,onClick:()=>C(`markdown`),title:Y?`Whole document as Markdown`:`This chunk + its sub-chunks as Markdown`,children:`markdown`})]}),(0,l.jsx)(`button`,{type:`button`,className:`chunk-edit`,onClick:()=>N(b),children:`edit`}),p.documentEntityTypes&&g(b)&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>te(b),title:`Change this subject's type to another type in force`,children:`change type`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>F(!0),title:`View this chunk's edit history + diffs`,children:`history`}),!Y&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ut(`up`),disabled:!lt.canUp,title:`Move this chunk up within its level`,children:`↑`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ut(`down`),disabled:!lt.canDown,title:`Move this chunk down within its level`,children:`↓`})]}),!Y&&(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>re(!0),title:`Delete this chunk and its sub-chunks`,children:`delete`})]})]}),(0,l.jsx)(`div`,{className:`doc-content-body`,children:b.type===`mermaid`?b.body?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)($e,{code:b.body}),S===`markdown`&&(0,l.jsx)(`pre`,{className:`md-pre doc-mermaid-source`,children:(0,l.jsx)(`code`,{children:b.body})})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty diagram)`}):b.type===`image`||b.asset?O?(0,l.jsxs)(`p`,{className:`doc-empty-body`,children:[`Image failed to load: `,O]}):E?(0,l.jsxs)(`figure`,{className:`doc-image`,children:[(0,l.jsx)(`img`,{src:E,alt:Ut(b)}),b.body&&(0,l.jsx)(`figcaption`,{children:b.body})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Loading image…`}):S===`markdown`?w===null?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Assembling Markdown…`}):(0,l.jsx)(Vt,{source:w}):b.body?(0,l.jsx)(Vt,{source:b.body}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty chunk)`})}),(0,l.jsx)(jt,{edges:me,incomplete:ge,documentId:e,selectedId:v,onSelectChunk:y,onOpenDocument:s?Qe:void 0,onRuleStatement:Le}),(0,l.jsx)(kt,{documentId:e,selectedId:v,scope:t,browse:m,onSelectChunk:y,onOpenDocument:s?Qe:void 0,refreshKey:ye,review:Ue})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a chunk on the left.`})})})]}),V&&a&&(0,l.jsx)(`div`,{className:`doc-assistant`,children:a({documentId:e,scope:t,subject:i?.subject,onChanged:q})}),M&&(0,l.jsx)(et,{chunk:M,scope:t,browse:m,onClose:()=>N(null),onSaved:q}),ee&&(0,l.jsx)(tt,{chunk:ee,scope:t,browse:m,onClose:()=>te(null),onSaved:q}),P&&b&&(0,l.jsx)(zt,{chunkId:b.id,chunkTitle:b.title,scope:t,browse:m,onClose:()=>F(!1)}),de&&Z&&(0,l.jsx)(vt,{documentId:e,rootChunkId:Z,docType:H?.type,docStatus:H?.status,chunkStatuses:Oe,scope:t,browse:m,onClose:()=>pe(!1),onSaved:q}),ne&&b&&(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:()=>re(!1),children:(0,l.jsxs)(`div`,{className:`modal chunk-delete-confirm`,onClick:e=>e.stopPropagation(),children:[(0,l.jsx)(`h3`,{children:`Delete chunk`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`Delete “`,b.title||`(untitled)`,`” and all of its sub-chunks? This cannot be undone.`]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>re(!1),children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>void dt(),children:`delete`})]})]})})]})}function Gt(e,t=``){let n=e.get(t);if(!n)return[];let r=n.entries.map(n=>{let r=n.kind===`directory`&&n.full_path.startsWith(`${t}/`);return{name:n.name,fullPath:n.full_path,kind:n.kind,resourceRef:n.resource_ref,listing:r?e.get(n.full_path):void 0,children:r?Gt(e,n.full_path):[]}});return r.sort((e,t)=>{let n=e.kind===`directory`;return n===(t.kind===`directory`)?e.name.localeCompare(t.name):n?-1:1}),r}var Kt={directory:`📁`,document:`📄`,volume_mount:`💾`,memory_entry:`🧠`};function qt(e){let{tree:t,root:n}=e;return!n||!n.loaded&&n.loading?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):n.loaded&&t.length===0&&!n.nextCursor?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`This tree is empty. Create a folder or document to begin.`})}):(0,l.jsxs)(`ul`,{className:`tree path-tree`,children:[t.map(t=>(0,l.jsx)(Xt,{node:t,...e},t.fullPath)),(0,l.jsx)(Jt,{dir:``,listing:n,...e})]})}function Jt({dir:e,listing:t,onLoadMore:n,onRetry:r}){let i=[];return!t||t.loading&&t.entries.length===0?i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`loading…`})},`status`)):t.error?i.push((0,l.jsxs)(`li`,{className:`node path-status`,children:[e!==``&&(0,l.jsxs)(`span`,{className:`path-err`,children:[`failed to load: `,t.error]}),` `,(0,l.jsx)(`button`,{type:`button`,className:`path-more`,onClick:()=>r(e),children:`retry`})]},`status`)):t.loaded&&t.entries.length===0&&e!==``&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`empty`})},`status`)),t?.nextCursor&&!t.error&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`button`,{type:`button`,className:`path-more`,disabled:t.loading,onClick:()=>n(e),children:t.loading?`loading…`:`Load more (${t.entries.length} shown)`})},`more`)),(0,l.jsx)(l.Fragment,{children:i})}function Yt(e,t){if(e.kind!==`document`||!t)return;let n=e.resourceRef;return n?.document_id?t.get(n.document_id):void 0}function Xt(e){let{node:t,expanded:n,onToggle:r,selectedPath:i,onSelect:a,summaries:o}=e,s=t.kind===`directory`,c=s&&n.has(t.fullPath),u=i===t.fullPath,d=Yt(t,o),f=d&&d.color_enabled?He(Be(d.type,d.status,ze(d.color_scheme))):void 0;return(0,l.jsxs)(`li`,{className:`node path-node kind-${t.kind} ${u?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row path-row`,style:f,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":c?`collapse`:`expand`,"aria-expanded":s?c:void 0,disabled:!s,onClick:e=>{e.stopPropagation(),s&&r(t.fullPath)},children:s?c?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`path-link`,onClick:()=>a(t),title:t.fullPath,children:[(0,l.jsx)(`span`,{className:`path-kind-icon`,"aria-hidden":!0,children:Kt[t.kind]??`•`}),(0,l.jsx)(`span`,{className:`path-name`,children:t.name}),d?.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:d.type}),d?.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:d.status})]})]}),c&&(0,l.jsxs)(`ul`,{className:`children path-children`,children:[t.children.map(t=>(0,l.jsx)(Xt,{...e,node:t},t.fullPath)),(0,l.jsx)(Jt,{...e,dir:t.fullPath,listing:t.listing})]})]})}var Zt=/^[A-Za-z0-9._-]+$/;function Qt(e,t){return`${e}/${t}`}function $t(e,t){for(let n of e){if(n.fullPath===t)return n;let e=$t(n.children,t);if(e)return e}}function en(e){let{theme:t,defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d}=e,f=ae(e);return(0,l.jsx)(oe,{theme:t,dataLayer:f,children:(0,l.jsx)(tn,{defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d})})}function tn({defaultScope:e,path:t,onPathChange:n,browse:r,principal:i,renderAssistant:a,renderNavigator:o,navigator:s,onError:u}){let d=j(),[f,p]=(0,c.useState)(e??`user`),[g,_]=(0,c.useState)(void 0),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(()=>new Set),E=t===void 0?g:t,D=(0,c.useRef)(n);(0,c.useEffect)(()=>{D.current=n},[n]);let O=(0,c.useRef)(u);(0,c.useEffect)(()=>{O.current=u},[u]);let[k,A]=(0,c.useState)([]),M=(0,c.useRef)(0),N=(0,c.useRef)(void 0),P=(0,c.useCallback)(e=>{N.current=e,D.current?.(e),_(e)},[]),F=(0,c.useCallback)(e=>{M.current++,A(e=>e.length>0?[]:e),P(e)},[P]);(0,c.useEffect)(()=>{t!==void 0&&t!==N.current&&(M.current++,A(e=>e.length>0?[]:e))},[t]);let I=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),L=(0,c.useMemo)(()=>new ne(d,f,I),[d,f,I]),R=(0,c.useSyncExternalStore)(L.subscribe,L.getSnapshot),z=(0,c.useCallback)(e=>{O.current?.(e)},[]),[ae,oe]=(0,c.useState)(()=>o?m(globalThis.localStorage):`tree`),V=!!o&&ae===`stars`,H=(0,c.useCallback)(e=>{oe(e),h(globalThis.localStorage,e),e===`tree`&&fe(!1)},[]),[de,fe]=(0,c.useState)(!1),[U,ge]=(0,c.useState)(0);(0,c.useEffect)(()=>{o&&s&&H(s)},[s]);let[W,_e]=(0,c.useState)(),[ve,ye]=(0,c.useState)(),G=(0,c.useCallback)((e,t)=>(ge(e=>e+1),L.invalidate(e,t)),[L]),[be,xe]=(0,c.useState)(()=>new Map),Se=(0,c.useRef)(new Set),Ce=(0,c.useRef)(0),we=(0,c.useCallback)(()=>{Ce.current++,Se.current=new Set,xe(new Map)},[]),K=(0,c.useRef)(!0);(0,c.useEffect)(()=>{K.current?K.current=!1:(F(void 0),y(null),T(new Set),we()),L.loadDir(``).catch(z)},[L,F,we,z]),(0,c.useEffect)(()=>{for(let e of w)R.has(e)||L.loadDir(e).catch(z)},[L,w,R,z]);let q=(0,c.useRef)(null);(0,c.useEffect)(()=>{let e=q.current!==null&&q.current!==L;if(q.current=L,!E||e)return;let t=te(E).filter(e=>e!==``);T(e=>{if(t.every(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.add(e)),n}),L.reveal(E).catch(z)},[L,E,z]),(0,c.useEffect)(()=>{if(f===`tenant`)return;let e=[];for(let t of R.values())for(let n of ie(t.entries))Se.current.has(n)||(Se.current.add(n),e.push(n));let t=Ce.current;for(let n=0;n<e.length;n+=500)d.documentsSummary({documentIds:e.slice(n,n+500)},f,I).then(e=>{Ce.current===t&&xe(t=>{let n=new Map(t);for(let t of e.documents??[])n.set(t.document_id,t);return n})}).catch(()=>{})},[d,R,f,I]);let Te=(0,c.useMemo)(()=>Gt(R),[R]),Ee=(0,c.useCallback)(async()=>{y(null),we(),ge(e=>e+1),await L.refresh(w).catch(z),E&&await L.reveal(E).catch(z)},[L,w,E,we,z]),De=(0,c.useCallback)(e=>{T(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),J=(0,c.useCallback)(e=>L.loadMore(e).catch(z),[L,z]),Y=(0,c.useCallback)(e=>{(L.getSnapshot().get(e)?.loaded?L.loadMore(e):L.loadDir(e)).catch(z)},[L,z]),X=(0,c.useMemo)(()=>E?$t(Te,E):void 0,[Te,E]),Z=R.get(``)?.error,Q=X?.kind===`directory`?X.fullPath:void 0,[Oe,ke]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!Q||!d.pathIsStored)return;let e=!1;return d.pathIsStored(Q,f,I).then(t=>{e||ke({path:Q,explicit:t})},()=>{}),()=>{e=!0}},[d,Q,f,I]);let Ae=X?X.kind===`directory`?Oe?.path===X.fullPath?Oe.explicit?`yes`:`implicit (no entry)`:void 0:`yes`:void 0,je=(0,c.useMemo)(()=>X?X.kind===`directory`?X.fullPath:ee(X.fullPath):``,[X]),Me=je||`/`,Ne=f!==`tenant`,Pe=(0,c.useCallback)(()=>{x({title:`New folder in ${Me}`,fields:[{key:`name`,label:`Folder name`,placeholder:`e.g. launches`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!Zt.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=Qt(je,t);await d.pathMkdir(n,f,I),await G(n).catch(z),F(n)}})},[d,L,je,Me,f,I,z,F]),Fe=(0,c.useCallback)(()=>{x({title:`New document in ${Me}`,fields:[{key:`name`,label:`Path name`,placeholder:`e.g. launch-plan`},{key:`title`,label:`Title`,placeholder:`e.g. Launch Plan`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!Zt.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=e.title.trim()||t,r=Qt(je,t);await d.documentCreate(n,r,f,I),await G(r).catch(z),F(r)}})},[d,L,je,Me,f,I,z,F]),Ie=(0,c.useCallback)(()=>{X&&x({title:`Rename / move ${X.fullPath}`,fields:[{key:`to`,label:`New path`,value:X.fullPath}],submitLabel:`Move`,onSubmit:async e=>{let t=e.to.trim();if(!t.startsWith(`/`))throw Error(`path must start with /`);await d.pathMv(X.fullPath,t,f,I),await Promise.all([G(X.fullPath,{dropSubtree:!0}),G(t)]).catch(z),F(t)}})},[d,L,X,f,I,z,F]),Le=(0,c.useCallback)(()=>{if(!X)return;if(X.kind===`document`){let e=X.resourceRef?.document_id;x({title:`Delete document ${X.fullPath}`,message:`This deletes the document, all its chunks, and its path entry. This cannot be undone.`,fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{if(!e)throw Error(`this document dirent has no document_id`);await d.documentDelete(e,f,I),await G(X.fullPath).catch(z),F(void 0)}});return}let e=X;y(null),(async()=>{let t;try{t=await re(d,e.fullPath,f,I)}catch(t){y(`could not list ${e.fullPath} for delete: ${t instanceof Error?t.message:String(t)}`);return}let n=f===`tenant`?[]:ie(t);x({title:`Delete branch ${e.fullPath}`,message:t.length===0?`This removes the (empty) folder.`:`This removes the folder and everything under it`+(n.length>0?` — including ${n.length} document(s), whose chunks are deleted.`:`.`),fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{for(let e of n)await d.documentDelete(e,f,I);await d.pathRm(e.fullPath,f,!0,I),await G(e.fullPath,{dropSubtree:!0}).catch(z),F(void 0)}})})()},[d,L,X,f,I,z,F]),Re=X&&(X.kind===`directory`||X.kind===`document`),ze=!!d.documentsTransfer&&!!Re,Be=(0,c.useCallback)(()=>{if(X){if(X.kind===`document`){let e=X.resourceRef?.document_id;if(!e){y(`this document entry has no document_id`);return}C({documentId:e,fromPath:X.fullPath})}else C({underPath:X.fullPath,fromPath:X.fullPath})}},[X]),Ve=(0,c.useCallback)(e=>{e.op===`move`?(G(e.from,{dropSubtree:!0}).catch(z),A([]),F(void 0)):e.toScope===f&&G(e.to).catch(z)},[G,z,f,F]),$=(0,c.useMemo)(()=>{if(k.length>0)return k[k.length-1];if(X?.kind===`document`)return{documentId:X.resourceRef?.document_id??``,path:X.fullPath,title:X.name}},[k,X]),He=(0,c.useCallback)((e,t)=>{let n=++M.current,r=ue(L.getSnapshot(),e.documentId);A(se(k,{...t,path:$?.path},{...e,path:r})),P(r),!r&&d.documentPath&&d.documentPath(e.documentId,f,I).then(t=>{t&&M.current===n&&(A(n=>ce(n,e.documentId,{path:t})),P(t))},()=>{})},[d,L,k,$?.path,f,I,P]),Ue=(0,c.useCallback)(e=>{let t=B(k,e);t!==k&&(M.current++,A(t),P(t[t.length-1].path))},[k,P]),We=(0,c.useCallback)((e,t)=>A(n=>ce(n,e,{title:t})),[]),Ge=(0,c.useCallback)(e=>{ye(t=>({documentId:e.documentId,chunkId:e.chunkId,seq:(t?.seq??0)+1})),$?.documentId!==e.documentId&&(e.path?F(e.path):(M.current++,A([{documentId:e.documentId,chunkId:e.chunkId}]),P(void 0)))},[$?.documentId,F,P]),Ke=(0,c.useMemo)(()=>({scope:f,browse:I,selection:{documentId:$?.documentId,chunkId:W&&W.documentId===$?.documentId?W.chunkId:void 0,path:$?.path},onSelect:Ge,reloadToken:U,maximized:de,onToggleMaximize:()=>fe(e=>!e),subject:i?.subject}),[f,I,$?.documentId,$?.path,W,Ge,U,de,i?.subject]),qe=ve&&$&&ve.documentId===$.documentId?ve:void 0,Je=!!$?.path&&X?.kind===`document`&&X.fullPath===$.path;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(he,{className:V?`paths-view paths-view--stars`:`paths-view`,defaultLeftWidth:V?720:420,minLeftWidth:280,minRightWidth:300,storageKey:V?`loomcycle.explorer.split.stars`:`loomcycle.explorer.split.paths`,hideRight:V&&de,children:[(0,l.jsxs)(`div`,{className:`left`,children:[(0,l.jsxs)(`div`,{className:`paths-toolbar`,children:[(0,l.jsxs)(`label`,{className:`paths-scope`,children:[(0,l.jsx)(`span`,{children:`scope`}),(0,l.jsxs)(`select`,{value:f,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),o&&(0,l.jsxs)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Navigator`,children:[(0,l.jsx)(`button`,{type:`button`,"aria-pressed":!V,className:V?void 0:`active`,onClick:()=>H(`tree`),title:`Browse the Path tree`,children:`tree`}),(0,l.jsx)(`button`,{type:`button`,"aria-pressed":V,className:V?`active`:void 0,onClick:()=>H(`stars`),title:`Browse the scope as a 3D star map`,children:`stars`})]}),(0,l.jsxs)(`div`,{className:`paths-toolbar-actions`,children:[!V&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:Pe,title:`New folder in ${Me}`,children:`+ folder`}),(0,l.jsx)(`button`,{type:`button`,onClick:Fe,disabled:!Ne,title:Ne?`New document in ${Me}`:`Documents are agent/user scope only`,children:`+ document`})]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void Ee(),title:`Reload the tree`,children:`↻`})]})]}),!V&&(0,l.jsxs)(`p`,{className:`paths-context`,children:[`new items → `,(0,l.jsx)(`code`,{children:Me}),I?.scopeId&&(0,l.jsxs)(l.Fragment,{children:[` · `,`subject `,(0,l.jsx)(`code`,{children:I.scopeId})]}),I?.tenant&&(0,l.jsxs)(l.Fragment,{children:[` · `,`tenant `,(0,l.jsx)(`code`,{children:I.tenant})]})]}),(v||Z)&&(0,l.jsx)(`div`,{className:`paths-err`,children:v||Z}),V&&o?(0,l.jsx)(`div`,{className:`paths-navigator`,children:o(Ke)}):(0,l.jsx)(qt,{tree:Te,root:R.get(``),expanded:w,onToggle:De,onLoadMore:J,onRetry:Y,selectedPath:E,onSelect:e=>F(e.fullPath),summaries:be})]}),(0,l.jsx)(`div`,{className:`right`,children:$?(0,l.jsxs)(`div`,{className:`paths-doc`,children:[(0,l.jsx)(pe,{trail:k,onJump:Ue}),(0,l.jsxs)(`div`,{className:`paths-doc-head`,children:[$.path?(0,l.jsx)(`code`,{className:`paths-doc-path`,children:$.path}):(0,l.jsxs)(`span`,{className:`paths-doc-path paths-doc-unfiled`,title:`Opened by id — no entry for this document was found in the Path tree`,children:[le($),` `,(0,l.jsx)(`em`,{children:`· opened by id, not in the tree`})]}),Je&&(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Ie,children:`rename / move`}),ze&&(0,l.jsx)(`button`,{type:`button`,onClick:Be,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Le,children:`delete`})]})]}),(0,l.jsx)(Wt,{documentId:$.documentId,scope:f,titleHint:$.title,browse:I,principal:i,renderAssistant:a,initialChunkId:$.chunkId??qe?.chunkId,onOpenDocument:He,onTitle:We,onChunkSelect:e=>_e({documentId:$.documentId,chunkId:e}),focusChunk:qe},k.length)]}):X?(0,l.jsxs)(`div`,{className:`paths-detail`,children:[(0,l.jsxs)(`h2`,{children:[(0,l.jsx)(`span`,{className:`paths-detail-kind`,children:X.kind}),(0,l.jsx)(`code`,{children:X.fullPath})]}),(0,l.jsxs)(`dl`,{className:`paths-detail-meta`,children:[(0,l.jsx)(`dt`,{children:`scope`}),(0,l.jsx)(`dd`,{children:f}),Ae&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`stored`}),(0,l.jsx)(`dd`,{children:Ae})]})]}),Re?(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Ie,children:`rename / move`}),ze&&(0,l.jsx)(`button`,{type:`button`,onClick:Be,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Le,children:`delete`})]}):(0,l.jsxs)(`p`,{className:`paths-readonly`,children:[`Read-only — `,X.kind,` entries are managed by their own tool.`]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a path on the left, or create a folder / document.`})})})]}),b&&(0,l.jsx)(nn,{state:b,onClose:()=>x(null)}),S&&(0,l.jsx)(me,{data:d,scope:f,browse:I,documentId:S.documentId,underPath:S.underPath,fromPath:S.fromPath,onClose:()=>C(null),onDone:Ve})]})}function nn({state:e,onClose:t}){let[n,r]=(0,c.useState)(()=>Object.fromEntries(e.fields.map(e=>[e.key,e.value??``]))),[i,a]=(0,c.useState)(!1),[o,s]=(0,c.useState)(null);return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:t,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async r=>{r.preventDefault(),a(!0),s(null);try{await e.onSubmit(n),t()}catch(e){s(e instanceof Error?e.message:String(e)),a(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:e.title}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:t,disabled:i,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:e.danger?`danger`:`primary`,disabled:i,children:i?`working…`:e.submitLabel})]})]}),e.message&&(0,l.jsx)(`p`,{className:`modal-context`,children:e.message}),e.fields.map((e,t)=>(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:e.label}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:n[e.key],placeholder:e.placeholder,autoFocus:t===0,onChange:t=>r(n=>({...n,[e.key]:t.target.value}))})]},e.key)),o&&(0,l.jsx)(`div`,{className:`modal-err`,children:o})]})})}function rn(e){let{documentId:t,scope:n,browse:r,theme:i}=e,a=ae(e);return(0,l.jsx)(oe,{theme:i,dataLayer:a,children:(0,l.jsx)(an,{...e},`${n}:${t}:${r?.scopeId??``}:${r?.tenant??``}`)})}function an({documentId:e,scope:t,titleHint:n,browse:r,principal:i,renderAssistant:a,onOpenDocument:o}){let[s,u]=(0,c.useState)([]),d=s[s.length-1],f=(0,c.useCallback)((e,t)=>{o?o(e,t):u(n=>se(n,t,e))},[o]),p=(0,c.useCallback)(e=>u(t=>B(t,e)),[]),m=(0,c.useCallback)((e,t)=>u(n=>ce(n,e,{title:t})),[]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(pe,{trail:s,onJump:p}),(0,l.jsx)(Wt,{documentId:d?.documentId??e,scope:t,titleHint:d?d.title:n,browse:r,principal:i,renderAssistant:a,initialChunkId:d?.chunkId,onOpenDocument:f,onTitle:m},s.length)]})}exports.DEFAULT_SCHEME=Le,exports.DocumentViewer=rn,exports.EDGE_PAGE_CAP=ye,exports.PathExplorer=en,exports.QUEUE_CHANGED_RETRIES=X,exports.RULING_CHUNK=Y,exports.RequestError=R,exports.assetFetchFromConnection=L,exports.chunkColor=Ve,exports.chunkCount=Ae,exports.createLoomcycleClient=I,exports.dataLayerFromClient=D,exports.docColor=Be,exports.effectiveScheme=ze,exports.hexToTint=$,exports.isQueueChanged=Q,exports.jsonPostFromConnection=z,exports.loadDocumentEdges=G,exports.runRuling=Oe,exports.tintStyle=He,exports.transferInput=y,exports.undoRulings=ke;
17
17
  //# sourceMappingURL=index.cjs.map