@diagc/cli 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,18 +13,7 @@ Needs Node ≥ 22.
13
13
  ## Quickstart
14
14
 
15
15
  ```bash
16
- mkdir -p .diagrams/src
17
- cat > .diagrams/src/acme.diagram.ts <<'EOF'
18
- import { model } from '@diagc/core';
19
-
20
- const m = model('acme', { name: 'Acme platform' });
21
- const web = m.node('web', { name: 'Web app', type: 'service' });
22
- const db = m.node('db', { name: 'Postgres', type: 'database' });
23
- m.relate(web, db, { kind: 'reads' });
24
-
25
- export default m;
26
- EOF
27
-
16
+ diagc init shop # a starter diagram in .diagrams/src/, the .gitignore lines, compiled
28
17
  diagc studio # opens the editor, recompiling as you edit
29
18
  ```
30
19
 
@@ -34,6 +23,7 @@ diagc studio # opens the editor, recompiling as you edit
34
23
 
35
24
  | Command | What it does |
36
25
  | --- | --- |
26
+ | `diagc init` | Set a repository up: a starter diagram (`--type c4` for a C4 one), the `.gitignore` lines, and with `--agents` a pointer to the guide for coding agents. |
37
27
  | `diagc compile` | Compile `.diagrams/src/**/*.diagram.{ts,json}` into validated artifacts under `.diagrams/.artifacts/`. The default command. |
38
28
  | `diagc watch` | The same, recompiling on change. |
39
29
  | `diagc studio` | Serve the visual editor against the current directory (default `http://127.0.0.1:5173`). Diagrams drawn here are saved back as `.diagram.json`. |
@@ -106,4 +106,4 @@ ${this.parser.parse(e)}</blockquote>
106
106
  ${e}</tr>
107
107
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
108
108
  `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${QT(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=$T(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+QT(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=$T(e);if(i===null)return QT(n);e=i;let a=`<img src="${e}" alt="${QT(n)}"`;return t&&(a+=` title="${QT(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:QT(e.text)}},cE=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},lE=class e{options;renderer;textRenderer;constructor(e){this.options=e||aT,this.options.renderer=this.options.renderer||new sE,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new cE}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},uE=class{options;block;constructor(e){this.options=e||aT}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?oE.lex:oE.lexInline}provideParser(e=this.block){return e?lE.parse:lE.parseInline}},dE=new class{defaults=iT();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=lE;Renderer=sE;TextRenderer=cE;Lexer=oE;Tokenizer=aE;Hooks=uE;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new sE(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new aE(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new uE;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];uE.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&uE.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return oE.lex(e,t??this.defaults)}parser(e,t){return lE.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?oE.lex:oE.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?lE.parse:lE.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?oE.lex:oE.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?lE.parse:lE.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
109
- Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+QT(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function fE(e,t){return dE.parse(e,t)}fE.options=fE.setOptions=function(e){return dE.setOptions(e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.getDefaults=iT,fE.defaults=aT,fE.use=function(...e){return dE.use(...e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.walkTokens=function(e,t){return dE.walkTokens(e,t)},fE.parseInline=dE.parseInline,fE.Parser=lE,fE.parser=lE.parse,fE.Renderer=sE,fE.TextRenderer=cE,fE.Lexer=oE,fE.lexer=oE.lex,fE.Tokenizer=aE,fE.Hooks=uE,fE.parse=fE,fE.options,fE.setOptions,fE.use,fE.walkTokens,fE.parseInline,lE.parse,oE.lex;function Qle({metadata:e}){let t=Object.entries(e);return t.length===0?null:(0,D.jsx)(`dl`,{className:`meta`,children:t.map(([e,t])=>(0,D.jsxs)(`div`,{className:`meta-row`,children:[(0,D.jsx)(`dt`,{children:e}),(0,D.jsx)(`dd`,{children:typeof t==`string`&&/^https?:\/\//.test(t)?(0,D.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,children:t}):String(t)})]},e))})}function $le({model:e,selection:t}){if(t===null)return(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Select a node or edge for details.`});if(t.kind===`node`){let n=e.nodes.find(e=>e.id===t.id);return n?(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsx)(`h2`,{children:n.name}),(0,D.jsxs)(`p`,{className:`muted`,children:[n.type,` · `,(0,D.jsx)(`code`,{children:n.id})]}),n.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(n.description)}}),n.metadata!==void 0&&(0,D.jsx)(Qle,{metadata:n.metadata})]}):(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Aggregate node (zoom in for details).`})}let[n]=t.id.split(`:`),[r,i]=(n??``).split(`=>`),a=new Set(t.constituentIds??[]),o=e.relations.filter(e=>a.has(e.id));return(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsxs)(`h2`,{children:[r,` → `,i]}),o.length===0?(0,D.jsx)(`p`,{className:`muted`,children:`No relation details available.`}):(0,D.jsx)(`ul`,{children:o.map(e=>(0,D.jsxs)(`li`,{children:[(0,D.jsx)(`code`,{children:e.from}),` → `,(0,D.jsx)(`code`,{children:e.to}),` `,(0,D.jsx)(`b`,{children:e.kind}),e.label===void 0?``:` — ${e.label}`,e.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(e.description)}})]},e.id))})]})}var pE=xi(),eue=Ty(),tue={query:``,toggled:{},groupToggled:{}},mE=(e,t)=>{let{libraryBase:n}=Kx();return n!==void 0&&t.startsWith(`/library/`)?`${n}${t.slice(9)}`:t.startsWith(`/`)||/^https?:/.test(t)?t:`${e}${t}`},nue=16,rue=64;function iue(e){let t=[],n=new Map;for(let r of e){if(r.group===void 0){t.push({cats:[r]});continue}let e=n.get(r.group);e===void 0&&(e={group:r.group,cats:[]},n.set(r.group,e),t.push(e)),e.cats.push(r)}return t}function hE({entry:e,assetBase:t}){if(e.template.image!==void 0)return(0,D.jsx)(`img`,{className:`lib-thumb`,src:mE(t,e.template.image),alt:e.name,draggable:!1});if(e.template.shape!==void 0){let n=`url("${mE(t,e.template.shape)}")`;return(0,D.jsx)(`span`,{className:`lib-thumb lib-shape-thumb`,"aria-hidden":`true`,style:{WebkitMaskImage:n,maskImage:n,background:e.template.color??`var(--dg-text-muted)`}})}let n=e.template.color??`var(--dg-border)`,r=e.template.type===void 0?void 0:pE.resolve(e.template.type),i=r?.icon===void 0?void 0:eue.resolve(r.icon),a=r?.outline===!0||r?.dashed===!0;return(0,D.jsx)(`span`,{className:`lib-swatch lib-swatch-${r?.shape??`box`}${a?` lib-swatch-outline`:``}`,style:a?{border:`1.5px ${r?.dashed===!0?`dashed`:`solid`} ${n}`,color:n}:{background:n},children:i!==void 0&&(0,D.jsx)(i,{size:14,className:`lib-swatch-icon`})})}function aue({library:e,onPlace:t,onApply:n,applyTarget:r,onAddNode:i,onAddImages:a,onAddCategory:o,onDeleteCategory:s,onImportIcon:c,onImportShape:l,assetBase:u=`/api/assets/`,viewState:d}){let f=(0,v.useState)(tue),[{query:p,toggled:m,groupToggled:h},g]=d??f,_=e=>g(t=>({...t,query:e})),[y,b]=(0,v.useState)(``),[x,S]=(0,v.useState)(`place`),C=(0,v.useMemo)(()=>nce(e,p),[e,p]),w=(0,v.useMemo)(()=>{let e=new Map;for(let t of C){let n=e.get(t.category);n===void 0?e.set(t.category,[t]):n.push(t)}return e},[C]),T=p.trim()!==``,E=(0,v.useMemo)(()=>iue(e.categories),[e.categories]),ee=r!==void 0&&n!==void 0,te=ee&&x===`apply`;(0,v.useEffect)(()=>{S(`place`)},[r?.id]);let ne=()=>{let e=y.trim();e===``||o===void 0||(o(e),b(``))};return(0,D.jsxs)(`aside`,{className:`sidebar lib-panel`,children:[(0,D.jsx)(`div`,{className:`panel-head`,children:(0,D.jsx)(`h3`,{children:`Library`})}),(i!==void 0||a!==void 0)&&(0,D.jsxs)(`div`,{className:`lib-actions`,children:[i!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:i,children:`Add node`}),a!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Add image`,children:[`Add image`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,multiple:!0,hidden:!0,"aria-label":`Add image`,onChange:e=>{let t=[...e.target.files??[]];t.length>0&&a(t),e.target.value=``}})]})]}),ee&&(0,D.jsxs)(`div`,{className:`lib-apply-toggle`,role:`group`,"aria-label":`Card click action`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip${te?``:` active`}`,"aria-pressed":!te,title:`Clicking a card adds a new node`,onClick:()=>S(`place`),children:`Place new`}),(0,D.jsxs)(`button`,{type:`button`,className:`chip${te?` active`:``}`,"aria-pressed":te,title:`Clicking a card restyles ${r.name} to match it`,onClick:()=>S(`apply`),children:[`Apply to `,r.name]})]}),(0,D.jsx)(`input`,{className:`lib-search`,type:`search`,"aria-label":`Search library`,placeholder:`Search nodes…`,value:p,onChange:e=>_(e.target.value)}),E.map(e=>{let i=e=>{let i=w.get(e.id)??[];if(i.length===0&&(T||e.builtin===!0))return null;let a=m[e.id]??(T||i.length<=nue);return(0,D.jsxs)(`section`,{className:`lib-category`,children:[(0,D.jsxs)(`div`,{className:`lib-cat-head`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":e.name,"aria-expanded":a,title:`${a?`Collapse`:`Expand`} ${e.name}`,onClick:()=>g(t=>({...t,toggled:{...t.toggled,[e.id]:!a}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:a?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:e.name}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:i.length})]})}),e.builtin!==!0&&(0,D.jsxs)(`span`,{className:`lib-cat-actions`,children:[c!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import icon into ${e.name}`,children:[`Icon`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,hidden:!0,"aria-label":`Import icon into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&c(e.id,n),t.target.value=``}})]}),l!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import shape into ${e.name}`,children:[`Shape`,(0,D.jsx)(`input`,{type:`file`,accept:`.svg,image/svg+xml`,hidden:!0,"aria-label":`Import shape into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&l(e.id,n),t.target.value=``}})]}),s!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon-btn`,"aria-label":`Delete category ${e.name}`,title:`Delete category ${e.name}`,onClick:()=>void Kx().confirmDialog(`Delete category '${e.name}' and its imported icons?`).then(t=>{t&&s(e.id)}),children:`✕`})]})]}),a&&(0,D.jsx)(`div`,{className:`lib-grid`,children:i.map(e=>(0,D.jsxs)(`button`,{type:`button`,className:`lib-entry`,"aria-label":te?`Apply ${e.name}`:`Place ${e.name}`,title:te?`Apply ${e.name} to ${r.name}`:`Place ${e.name}`,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`application/x-dg-library-entry`,e.id),t.dataTransfer.effectAllowed=`copy`},onClick:()=>te?n(e):t(e),children:[(0,D.jsx)(hE,{entry:e,assetBase:u}),(0,D.jsx)(`span`,{className:`lib-entry-name`,children:e.name})]},e.id))})]},e.id)};if(e.group===void 0)return i(e.cats[0]);let a=e.group,o=e.cats.reduce((e,t)=>e+(w.get(t.id)??[]).length,0);if(o===0&&T)return null;let d=h[a]??(T||o<=rue);return(0,D.jsxs)(`section`,{className:`lib-group`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name lib-group-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":a,"aria-expanded":d,title:`${d?`Collapse`:`Expand`} ${a}`,onClick:()=>g(e=>({...e,groupToggled:{...e.groupToggled,[a]:!d}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:d?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:a}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:o})]})}),d&&(0,D.jsx)(`div`,{className:`lib-group-body`,children:e.cats.map(i)})]},`group:${a}`)}),o!==void 0&&(0,D.jsxs)(`div`,{className:`add-member`,children:[(0,D.jsx)(`input`,{"aria-label":`New category name`,placeholder:`New category…`,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),ne())}}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Add category`,onClick:ne,children:`+`})]})]})}var gE={categories:[],entries:[]};async function oue(){try{let e=await Kx().apiFetch(`/api/library`);if(!e.ok)return gE;let t=await e.json();return{categories:t.categories??[],entries:t.entries??[]}}catch{return gE}}async function _E(e){let t=await Kx().apiFetch(`/api/library`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.issues?.[0]?.message??`Library save failed (${t.status})`)}}var vE=new Set(ww.categories.map(e=>e.id));function yE(){let[e,t]=(0,v.useState)({categories:[],entries:[]}),n=(0,v.useRef)(e);n.current=e,(0,v.useEffect)(()=>{oue().then(t)},[]);let r=(0,v.useMemo)(()=>LS(ww,e),[e]),i=(0,v.useCallback)(e=>{t(e),_E(e).catch(()=>{})},[]);return{library:r,addCategory:(0,v.useCallback)(e=>{let t=n.current,r=RS(e,new Set(LS(ww,t).categories.map(e=>e.id)),`category`);i({...t,categories:[...t.categories,{id:r,name:e.trim()||r}]})},[i]),deleteCategory:(0,v.useCallback)(e=>{if(vE.has(e))return;let t=n.current;i({categories:t.categories.filter(t=>t.id!==e),entries:t.entries.filter(t=>t.category!==e)})},[i]),addEntry:(0,v.useCallback)(e=>{let t=n.current;i({...t,entries:[...t.entries,e]})},[i])}}function bE(e,t){let n=new Map(e.nodes.map(e=>[e.id,e.type])),r=new Set(e.relations.map(e=>e.id)),i=e=>oe.includes(n.get(e)??``),a=new Set;for(let r of t.nodeIds)if(!(!n.has(r)||!i(r)))for(let t of Fe(e,r))t!==r&&a.add(t);let o=[...t.relationIds.filter(e=>r.has(e)).map(e=>({type:`delete-relation`,id:e})),...t.nodeIds.filter(e=>n.has(e)&&!a.has(e)).map(e=>({type:`delete-node`,id:e,...i(e)?{cascade:!0}:{}}))];return o.length===0?null:o.length===1?o[0]:{type:`batch`,commands:o}}function sue(e,t,n,r,i){let a=e.nodes.find(e=>e.id===t);if(a?.type!==`db-table`||a.columns===void 0)return null;let o=a.columns.find(e=>e.name===r);if(o===void 0)return null;let s=e.nodes.find(e=>e.id===n)?.columns?.find(e=>e.pk===!0)?.name,c=[{type:`add-relation`,from:t,to:n,opts:{kind:`fk`,fromColumn:o.name,...s===void 0?{}:{toColumn:s},...i?.layer===void 0?{}:{layer:i.layer}}}];return o.fk!==!0&&c.push({type:`set-table-columns`,id:t,columns:a.columns.map(e=>e.name===o.name?{...e,fk:!0}:e)}),c}var xE=e=>e.map(e=>oC(e).label).join(`, `),SE=(e,t,n)=>{let r=[...sC(e)[t.id]];return r[t.index]=n,gC(e,t.id,r)};function CE({overrides:e,onChange:t,onClose:n,mac:r=rC()}){let i=(0,v.useMemo)(()=>sC(e),[e]),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(null),p=(0,v.useRef)(null);(0,v.useEffect)(()=>{p.current?.focus()},[]);let m=e=>nC(e,r),h=e=>{f(null),u(null),c(e)},g=a=>{if(s===null){if(a.key!==`Escape`)return;a.stopPropagation(),l===null?n():u(null);return}if(a.preventDefault(),a.stopPropagation(),a.key===`Escape`){c(null);return}let o=QS(a.nativeEvent,r);if(o===null)return;c(null);let d=hC(o);if(d!==null){f(`${m(o)}: ${d}`);return}if(i[s.id].includes(o))return;let p=bce(i,s.id,o);p.length>0?u({...s,chord:o,conflicts:p}):t(SE(e,s,o))},_=()=>{if(l===null)return;let n=e;for(let e of l.conflicts)n=gC(n,e,sC(n)[e].filter(e=>e!==l.chord));t(SE(n,l,l.chord)),u(null)},y=n=>{let r={...e};delete r[n],t(r)},b=async()=>{await Kx().confirmDialog(`Reset every keyboard shortcut to its default?`)&&t({})},x=a.trim().toLowerCase(),S=aC.filter(e=>x===``||e.label.toLowerCase().includes(x)||e.group.toLowerCase().includes(x)||i[e.id].some(e=>m(e).toLowerCase().includes(x))),C=(e,t)=>s?.id===e&&s.index===t;return(0,D.jsx)(`div`,{className:`hotkeys-backdrop`,"data-testid":`hotkeys-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,D.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,className:`hotkeys-dialog`,tabIndex:-1,onKeyDownCapture:g,children:[(0,D.jsxs)(`header`,{className:`hotkeys-head`,children:[(0,D.jsx)(`strong`,{children:`Keyboard shortcuts`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Close`,onClick:n,children:`✕`})]}),(0,D.jsx)(`input`,{ref:p,className:`hotkeys-search`,"aria-label":`Search shortcuts`,placeholder:`search actions…`,value:a,onChange:e=>o(e.target.value)}),l!==null&&(0,D.jsxs)(`div`,{className:`hotkeys-note`,role:`alert`,children:[(0,D.jsxs)(`span`,{children:[m(l.chord),` is already `,xE(l.conflicts),`.`]}),(0,D.jsx)(`button`,{type:`button`,className:`chip primary`,onClick:_,children:`Reassign`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:()=>u(null),children:`Cancel`})]}),d!==null&&(0,D.jsx)(`div`,{className:`hotkeys-note`,role:`alert`,children:d}),(0,D.jsxs)(`div`,{className:`hotkeys-list`,children:[iC.map(n=>{let r=S.filter(e=>e.group===n);return r.length===0?null:(0,D.jsxs)(`section`,{"aria-label":n,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:n}),r.map(n=>{let r=i[n.id];return(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:n.label}),(0,D.jsxs)(`span`,{className:`hotkeys-keys`,children:[r.length===0&&!C(n.id,0)&&(0,D.jsx)(`span`,{className:`hotkeys-unbound`,children:`—`}),r.map((a,o)=>{let s=bce(i,n.id,a);return(0,D.jsxs)(`span`,{className:`hotkeys-key`,children:[(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip`,"aria-label":`Change ${m(a)} for ${n.label}`,...s.length>0?{title:`Also bound to ${xE(s)}`,"data-conflict":``}:{},...C(n.id,o)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:o}),children:C(n.id,o)?`Press a key…`:m(a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Remove ${m(a)} from ${n.label}`,onClick:()=>t(gC(e,n.id,r.filter((e,t)=>t!==o))),children:`×`})]},a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip hotkey-add`,"aria-label":`Add a key for ${n.label}`,...C(n.id,r.length)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:r.length}),children:C(n.id,r.length)?`Press a key…`:`+`}),e[n.id]!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Reset ${n.label}`,title:`Back to the default`,onClick:()=>y(n.id),children:`↺`})]})]},n.id)})]},n)}),x===``&&(0,D.jsxs)(`section`,{"aria-label":`Fixed`,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:`Fixed`}),vce.map(e=>(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:e.label}),(0,D.jsx)(`span`,{className:`hotkeys-keys hotkeys-fixed`,children:e.keys})]},e.label))]})]}),(0,D.jsxs)(`footer`,{className:`hotkeys-foot`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip`,disabled:Object.keys(e).length===0,onClick:()=>void b(),children:`Reset all to defaults`}),(0,D.jsx)(`span`,{className:`hotkeys-hint`,children:`Click a key to change it. Esc cancels.`})]})]})})}var cue=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable===!0||e.closest(`[contenteditable=""], [contenteditable="true"]`)!==null},wE=(e,t)=>e instanceof Element&&e!==document.body&&e!==document.documentElement&&t!==null&&!t.contains(e);function lue({rootRef:e,keymap:t,mode:n,handlersRef:r,suspended:i,mac:a=rC()}){let o=(0,v.useRef)({keymap:t,mode:n,suspended:i});o.current={keymap:t,mode:n,suspended:i};let s=(0,v.useRef)(null);(0,v.useEffect)(()=>{let t=t=>{let{keymap:n,mode:i,suspended:c}=o.current;if(c||t.defaultPrevented||wE(t.target,e.current))return;let l=QS(t,a);if(l===null)return;let u=uC(n,l,i);if(u===void 0)return;let d=oC(u);if(cue(t.target)&&!(d.inFields===!0&&(t.ctrlKey||t.metaKey||t.altKey)))return;if(t.repeat&&d.repeat!==!0){s.current?.chord===l&&s.current.claimed&&t.preventDefault();return}let f=r.current?.[u],p=f!==void 0&&f()!==!1;t.repeat||(s.current={chord:l,claimed:p}),p&&t.preventDefault()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,r,a])}var uue=`diagc.style`,TE=`diagc.snap`,EE=10,DE=`diagc.rightDock`,due=`diagc.leftDock`,fue=`diagc.leftDockWidth`,OE=`diagc.rightDockWidth`,kE=560,AE=220,jE=240,pue=300,ME=320,NE=(e,t,n)=>{if(e===null)return null;let r=Number(e);return Number.isFinite(r)?nT(r,t,n):null},PE=(e,t)=>{if(t?.kind!==`node`)return;let n=e.nodes.find(e=>e.id===t.id);return n===void 0?void 0:{applyTarget:{id:n.id,name:n.name||n.id}}};function mue({initialTheme:e=`dark`}={}){let{artifacts:t,names:n,booted:r,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,canDesign:l}=Jx(),[u,d]=(0,v.useState)(e),[f,p]=Zx(uue,`clean`,e=>e),[m,h]=Zx(TE,!1,e=>e===null?null:e===`true`),[g,_]=Zx(yce,{},Sce,JSON.stringify),y=(0,v.useMemo)(()=>sC(g),[g]),[S,C]=(0,v.useState)(!1),T=(0,v.useMemo)(rC,[]),E=(0,v.useRef)(null),ee=(0,v.useRef)(null),te=(0,v.useRef)(null),ne=(0,v.useRef)(null),re=(0,v.useRef)({}),[ie,ae]=(0,v.useState)(void 0),[oe,se]=(0,v.useState)([]),[ce,le]=(0,v.useState)(null),[ue,de]=(0,v.useState)({}),[fe,pe]=(0,v.useState)({}),[me,he]=(0,v.useState)({}),[ge,_e]=(0,v.useState)({}),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(null),[we,Te]=(0,v.useState)(null),[Ee,De]=(0,v.useState)(void 0),Oe=e=>De(t=>({id:e,nonce:(t?.nonce??0)+1})),[ke,Ae]=(0,v.useState)(void 0),je=(e,t)=>Ae(n=>({target:e,id:t,nonce:(n?.nonce??0)+1})),[Me,Ne]=(0,v.useState)([]),Pe=(0,v.useCallback)(e=>Ne(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e),[]),[Fe,Ie]=(0,v.useState)(null),[Le,Re]=(0,v.useState)([]),ze=(0,v.useCallback)(e=>Re(e),[]),[Be,Ve]=(0,v.useState)(null),[He,Ue]=(0,v.useState)(`properties`),We=(0,v.useState)(tue),[Ge,Ke]=Zx(due,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[qe,Je]=Zx(DE,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[Ye,Xe]=Zx(fue,pue,e=>NE(e,AE,kE)),[Ze,Qe]=Zx(OE,ME,e=>NE(e,jE,kE)),$e=yE(),et=(0,v.useRef)(()=>!0),{selected:tt,setSelected:nt,enteredPath:rt,setEnteredPath:it,handleEnteredPathChange:at}=tS({names:n,booted:r,leaveEditRef:et}),ot=rt.length>0?rt[rt.length-1]:void 0,st=(0,v.useRef)(tt);st.current=tt,(0,v.useEffect)(()=>{xe(!1)},[tt]),(0,v.useEffect)(()=>{pe({})},[tt]);let[ct,lt]=(0,v.useState)(`select`),[ut,dt]=(0,v.useState)(``),[ft,pt]=(0,v.useState)(3),{editing:mt,setEditing:ht,editor:gt,layoutApiRef:vt,saveIssues:yt,setSaveIssues:bt,saving:xt,doSave:St,enterEdit:Ct,leaveEdit:wt}=cS({setDrafts:o,resetInspector:()=>Ue(`properties`),leaveEditRef:et});(0,v.useEffect)(()=>{(!mt||rt.length>0)&&lt(`select`)},[mt,tt,rt]),(0,v.useEffect)(()=>{w(document.documentElement,u===`dark`?x:b),document.documentElement.dataset.theme=u},[u]);let Tt=t[tt],Et=gt.session,Dt=mt?Et?.state.model:Tt?.model,Ot=mt?Et?.state.layout:Tt?.layout,kt=mt?Et?.state.drawings:Tt?.drawings,At=Dt?.style!==void 0&&Ov(Dt.style)?Dt.style:void 0,jt=Dt?.planes??[],Mt=ie,Nt=Hr(jt,Mt,Dt?.notation),Pt=dae(),Ft=Eh(Nt).partitionOf!==void 0,It=jt.find(e=>e.id===Mt)?.containmentOf!==void 0,Lt=(0,v.useRef)(null);(0,v.useEffect)(()=>{if(Dt===void 0||Lt.current===tt)return;Lt.current=tt,se(Vr(Dt.planes,ie));let e=Ot?.export?.collapsed??[];de({...Object.fromEntries(e.map(e=>[e,`collapsed`])),...Xr(Ot,Dt,ie)})},[tt,Dt,ie,Ot]);let Rt=Dt!==void 0&&Ot?.manual?.[Yr(Dt,Mt)]===!0,zt=(0,v.useMemo)(()=>mt?Ot:Pce(Ot,Dt,Mt,fe),[mt,Ot,Dt,Mt,fe]),Bt=(Dt===void 0?void 0:zt?.settings?.[Yr(Dt,Mt)])??{},Vt=ce!==null&&(Dt?.layers??[]).some(e=>e.id===ce)?ce:null,Ht=(e,t,n)=>{let r={...Dt?.relations.find(t=>t.id===e)?.style},i=t===`from`?`fromSide`:`toSide`;return n===null?delete r[i]:r[i]=n,Object.keys(r).length>0?r:null},Ut=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&&gt.dispatch({type:`update-relation`,id:e,patch:{labels:fce(i,t,n,r)}})},Wt=(e,t,n)=>{if(Dt===void 0)return;let r=JS(Dt,e);r!==null&&gt.dispatch({type:`update-relation`,id:e,patch:{labels:pce(r,t,n)}})},Gt=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&&gt.dispatch({type:`update-relation`,id:e,patch:{labels:mce(i,t,n,r)}})},Kt=Et?.lastRelationId;(0,v.useEffect)(()=>{mt&&Kt!==void 0&&(Ce({kind:`edge`,id:Kt}),Te(null))},[mt,Kt]);let qt=qS({editor:gt,model:Dt,selection:Se,groupSel:Me,editing:mt,notation:Nt,activePlane:Mt,activePlaneBorrowsContainment:It,planes:jt,activeLayer:ce,activeLayers:oe,setSelection:Ce,setRenameId:Te,setLeverageFocus:Ve,setCompareId:Ie,setPlane:ae,setPins:de,layout:Ot,pins:ue,setLayoutPreview:pe,setActiveLayers:se,setActiveLayer:le}),{select:Jt,switchPlane:Yt,activateLayer:Xt,toggleLayer:Zt,mergeSelectedLayers:Qt,toggleExpand:$t,resetView:en}=qt;yS({editing:mt,editor:gt,layoutApiRef:vt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,multiSelection:Me,select:Jt});let{compareSelect:tn,groupSelected:nn}=qt,rn={notation:Nt,plane:Mt,borrowsContainment:It,penLayer:Vt},an=(e,t)=>{let n=gt.peek()?.state.model;if(!mt||n===void 0)return!1;let r=Tle(n,e,rn,t);if(r===void 0)return!1;let i=Yr(n,Mt),a=Ot?.sizes?.[e];return gt.dispatch(Ele(r,{pinned:Rt||Ot?.planes[i]?.[e]!==void 0,source:vt.current?.snapshotPositions()[e],width:a?.w??qr.width,...a===void 0?{}:{size:a},plane:Mt})),Jt({kind:`node`,id:r.id}),Oe(r.id),!0},on=Mt===void 0?{}:{plane:Mt},cn=e=>{let t=gt.peek()?.state.model;if(t===void 0)return;let n=ln(t,e);if(n===void 0)return;let r=`node`in e?t.nodes.find(t=>t.id===e.node)?.type:t.relations.find(t=>t.id===e.relation)?.kind,i=un(n);gt.dispatch({type:`batch`,commands:[{type:`add-threat`,target:e,threat:{id:i,category:pn(r)[0]??`S`,title:sn}},{type:`set-note-open`,target:e,open:!0,...on}]}),je(e,i)},dn=(e,t,n)=>{let r=gt.peek()?.state.model,i=r===void 0?void 0:ln(r,e)?.find(e=>e.id===t);if(i!==void 0){if(n===``){i.title===`New threat`&&gt.dispatch({type:`remove-threat`,target:e,id:t});return}n!==i.title&&gt.dispatch({type:`update-threat`,target:e,id:t,patch:{title:n}})}},fn=(e,t,n)=>gt.dispatch({type:`update-threat`,target:e,id:t,patch:{status:n}}),mn=(e,t,n,r)=>{let i=gt.peek()?.state.model,a=i===void 0?void 0:ln(i,e)?.find(e=>e.id===t);a!==void 0&&(a[n]??``)!==r&&gt.dispatch({type:`update-threat`,target:e,id:t,patch:{[n]:r===``?null:r}})},hn=Dt!==void 0&&Ot!==void 0&&Sn(Dt,Ot,Yr(Dt,Mt)),gn=Dt!==void 0&&(Dt.nodes.some(e=>(e.threats?.length??0)>0)||Dt.relations.some(e=>(e.threats?.length??0)>0)),_n=Dt!==void 0&&(Nt===`threat-model`||gn),vn=sce({editing:mt,selected:tt,current:Tt,names:n,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,setSelected:nt,setEnteredPath:it,setEditing:ht,leaveEdit:wt,resetView:en,editor:gt}),{addNode:yn,createAt:bn,placeFromLibrary:xn,applyFromLibrary:Cn,dropLibraryEntry:wn,addImages:Tn}=rce({editor:gt,layoutApiRef:vt,setSelection:Ce,setRenameId:Te,setLeftTab:Ue,requestLabelEdit:Oe,setSaveIssues:bt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,drillRoot:ot,model:Dt,lib:$e,notation:Nt,today:Pt}),En=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`icon`),i=t.name.replace(/\.[^.]*$/,``)||`icon`;$e.addEntry({id:r,category:e,name:i,template:{type:`image`,image:n,width:64,height:64}})}catch(e){bt([{message:Ar(e)}])}},Dn=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`shape`),i=t.name.replace(/\.[^.]*$/,``)||`shape`;$e.addEntry({id:r,category:e,name:i,template:{shape:n}})}catch(e){bt([{message:Ar(e)}])}},On=async()=>{let e=tt;try{let t=await Kx().apiFetch(`/api/diagrams/${e}`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(st.current!==e)return;pe({}),Ct(e,n.model,n.layout??Jr(),n.drawings??Er())}catch(t){if(st.current!==e)return;bt([{message:`Could not load '${e}' for editing: ${Ar(t)}`}])}},kn=()=>{gt.session?.state.model!==void 0&&(Rt?gt.dispatch({type:`set-plane-layout`,manual:!1,...on}):(gt.dispatch({type:`set-positions`,positions:vt.current?.snapshotPositions()??{},...on}),gt.dispatch({type:`set-plane-layout`,manual:!0,...on})))},An=e=>{gt.session?.state.model!==void 0&&gt.dispatch({type:`set-layout-settings`,patch:e,...Mt===void 0?{}:{plane:Mt}})},jn=(0,v.useCallback)(async e=>{ye(!0);try{let t=await Kx().apiFetch(`/api/layouts/${tt}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json();return bt(e.issues??[{message:`Could not save layout`}]),!1}return s(t=>{let n=t[tt];return n===void 0?t:{...t,[tt]:{...n,layout:e}}}),bt(null),!0}finally{ye(!1)}},[tt,s,bt]),Mn=Dt===void 0?``:(Ot?.unfolded?.[Yr(Dt,Mt)]??[]).join(`\0`),Nn=(0,v.useRef)(null);(0,v.useEffect)(()=>{let e=Nn.current;Nn.current=mt?Mn:null,!(!mt||e===null||e===Mn||Dt===void 0)&&de(e=>KS(e).join(`\0`)===Mn?e:Xr(Ot,Dt,Mt))},[mt,Mn]);let Pn=(0,v.useMemo)(()=>KS(ue),[ue]),Fn=Dt!==void 0&&Pn.join(`\0`)!==Mn,In=Object.keys(me).length>0||Object.keys(ge).length>0||Fn,Ln=(0,v.useCallback)(async()=>{Dt===void 0||!In||await jn(lce(Ot,Dt,Mt,me,Pn,ge))&&(he({}),_e({}))},[Dt,me,ge,In,Pn,Ot,Mt,jn]),Rn=(0,v.useCallback)(async()=>{if(Dt===void 0)return;let e=!Rt,t=e?vt.current?.snapshotPositions()??{}:null;await jn(uce(Ot,Dt,Mt,t,e?Pn:void 0,e?ge:{}))&&e&&(he({}),_e({}))},[Dt,Ot,Mt,Rt,vt,jn,Pn,ge]),zn=(0,v.useCallback)(e=>{if(Dt===void 0)return;let t=Yr(Dt,Mt);pe(n=>PC(n,t,e))},[Dt,Mt]),Bn=mt&&Dt!==void 0?YS(Dt,Se,gt.dispatch):null,Vn=Se?.kind===`node`&&Dt!==void 0?Ot?.planes[Yr(Dt,Mt)]?.[Se.id]:void 0,Hn=Se?.kind===`node`&&Dt!==void 0?vt.current?.snapshotPositions()[Se.id]:void 0,Wn=(e,t)=>e?t:void 0,Gn=i.has(tt),Kn=!mt&&Dt!==void 0,qn=Dt!==void 0&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0,Jn=e=>Wn(Dt!==void 0,()=>te.current!==null&&e(te.current)),Yn=e=>()=>rt.length>0?!1:(lt(e),!0);re.current={"diagram.picker":()=>ne.current?.(),"diagram.toggle-edit":Wn(Dt!==void 0&&Gn,()=>void(mt?wt():On())),"diagram.rename":Wn(l&&!mt&&Gn,()=>void vn.renameDiagram()),"diagram.new":Wn(l,()=>void vn.newDiagram()),"diagram.duplicate":Wn(l&&Kn,()=>void vn.duplicateDiagram()),"diagram.eject":Wn(l&&!mt&&Gn,()=>void vn.ejectDiagram()),"edit.add-node":Wn(mt,()=>yn()),"edit.add-child":Wn(mt,()=>Se?.kind===`node`&&an(Se.id)),"edit.undo":Wn(mt,()=>gt.undo()),"edit.redo":Wn(mt,()=>gt.redo()),"edit.save":Wn(mt,()=>void St()),"edit.group":Wn(mt&&Me.length>=2,()=>void nn()),"edit.relayout":Wn(mt,()=>void DC(gt,{autoLayout:!Rt,activePlane:Mt,getAutoPositions:()=>vt.current?.autoPositions()??{}})),"edit.toggle-auto-layout":Wn(mt,kn),"edit.toggle-notes":Wn(mt&&_n&&gn,()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on})),"tool.select":Wn(mt,()=>lt(`select`)),"tool.pen":Wn(mt,Yn(`pen`)),"tool.eraser":Wn(mt,Yn(`eraser`)),"pen.thin":Wn(mt&&ct===`pen`,()=>pt(2)),"pen.medium":Wn(mt&&ct===`pen`,()=>pt(3)),"pen.thick":Wn(mt&&ct===`pen`,()=>pt(6)),"canvas.fit":Jn(e=>e.fitView()),"canvas.zoom-in":Jn(e=>e.zoomIn()),"canvas.zoom-out":Jn(e=>e.zoomOut()),"canvas.laser":Jn(e=>e.toggleLaser()),"canvas.legend":Jn(e=>e.toggleLegend()),"canvas.dim":Jn(e=>e.toggleDim()),"canvas.drawings":Jn(e=>e.toggleDrawings()),"canvas.loops":Jn(e=>e.toggleLoops()),"view.freeze":Wn(Kn&&!ve&&rt.length===0,()=>void Rn()),"view.save-positions":Wn(Kn&&In&&!ve,()=>void Ln()),"view.auto-arrange":Wn(Kn&&qn,()=>xe(e=>!e)),"arrange.align-left":Jn(e=>e.align(`left`)),"arrange.align-center":Jn(e=>e.align(`centerX`)),"arrange.align-right":Jn(e=>e.align(`right`)),"arrange.align-top":Jn(e=>e.align(`top`)),"arrange.align-middle":Jn(e=>e.align(`middle`)),"arrange.align-bottom":Jn(e=>e.align(`bottom`)),"arrange.distribute-x":Jn(e=>e.distribute(`x`)),"arrange.distribute-y":Jn(e=>e.distribute(`y`)),"window.left-dock":Wn(Dt!==void 0,()=>Ke(e=>!e)),"window.right-dock":Wn(Dt!==void 0,()=>Je(e=>!e)),"window.inspector-properties":Wn(mt,()=>{Ue(`properties`),Ke(!1)}),"window.inspector-library":Wn(mt,()=>{Ue(`library`),Ke(!1)}),"window.theme":()=>d(e=>e===`dark`?`light`:`dark`),"window.snap":()=>h(e=>!e),"window.hotkeys":()=>C(!0)},lue({rootRef:E,keymap:y,mode:mt?`edit`:`view`,handlersRef:re,suspended:S,mac:T});let Xn=e=>bC(y,e,T),Zn=[...Gn?[{id:`rename`,label:`Rename`,title:`Rename this diagram${Xn(`diagram.rename`)}`,onSelect:()=>void vn.renameDiagram()}]:[],...Dt===void 0?[]:[{id:`export-png`,label:`Export PNG`,title:`Save the canvas as drawn — folds, layers, theme and drawings — as a PNG image`,onSelect:()=>void Dce(vt.current,tt??``)},{id:`duplicate`,label:`Duplicate`,title:`Copy this diagram — layout and all — to a new editable one and open it${Xn(`diagram.duplicate`)}`,onSelect:()=>void vn.duplicateDiagram()}],...Gn?[{id:`eject`,label:`Eject`,title:`Promote this diagram to a TypeScript source — it becomes read-only here${Xn(`diagram.eject`)}`,onSelect:()=>void vn.ejectDiagram()}]:[]],Qn=(0,v.useMemo)(()=>({keymap:y,mac:T}),[y,T]),$n=(0,v.useMemo)(()=>({laser:yC(y,`canvas.laser`,T),dim:yC(y,`canvas.dim`,T),legend:yC(y,`canvas.legend`,T),drawings:yC(y,`canvas.drawings`,T),loops:yC(y,`canvas.loops`,T)}),[y,T]);return(0,D.jsx)(vC.Provider,{value:Qn,children:(0,D.jsxs)(`div`,{className:`app`,ref:E,children:[(0,D.jsxs)(`header`,{className:`topbar`,children:[(0,D.jsx)(`strong`,{className:`brand`,children:`diagc studio`}),(0,D.jsx)(Tce,{names:n,selected:tt,onSelect:e=>{wt()&&(nt(e),it([]),en())},toggleRef:ne}),l&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":`New diagram`,title:`New diagram${Xn(`diagram.new`)}`,onClick:()=>void vn.newDiagram(),children:`+`}),l&&!mt&&(0,D.jsx)(Nce,{label:`Diagram actions`,items:Zn,children:`⋯`}),Dt!==void 0&&(Gn?!mt&&(0,D.jsx)(`button`,{className:`chip`,onClick:()=>void On(),title:`Edit this diagram${Xn(`diagram.toggle-edit`)}`,children:`Edit`}):(0,D.jsx)(`span`,{className:`chip read-only`,title:`Compiled from TypeScript — edit the source`,children:`read-only`})),(0,D.jsx)(`span`,{className:`spacer`}),!mt&&Dt!==void 0&&In&&(0,D.jsx)(`button`,{className:`chip primary`,disabled:ve,title:`Write the boxes and edge labels you moved, and which groups are open, to this diagram's layout file. Safe on a generated diagram: re-compiling rewrites the model, never the layout.${Xn(`view.save-positions`)}`,onClick:()=>void Ln(),children:ve?`Saving…`:`Save positions`}),mt&&_n&&(0,D.jsx)(`button`,{type:`button`,className:`chip${hn?` active`:``}`,"aria-pressed":hn,disabled:!gn,title:`${hn?`Close all threat notes`:`Open all threat notes`}${Xn(`edit.toggle-notes`)}`,onClick:()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on}),children:`Notes`}),(0,D.jsx)(`span`,{className:`sep`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon${m?` active`:``}`,"aria-label":`Snap to grid`,"aria-pressed":m,title:`${m?`Snapping to a ${EE}px grid. Click to place boxes freely.`:`Snap dragged boxes to a ${EE}px grid; arrow keys step by it too.`}${Xn(`window.snap`)}`,onClick:()=>h(e=>!e),children:`⋮⋮`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":u===`dark`?`Switch to light theme`:`Switch to dark theme`,title:`${u===`dark`?`Light theme`:`Dark theme`}${Xn(`window.theme`)}`,onClick:()=>d(u===`dark`?`light`:`dark`),children:u===`dark`?`☀`:`☾`}),(0,D.jsx)(`button`,{ref:ee,type:`button`,className:`chip icon`,"aria-label":`Keyboard shortcuts`,title:`Keyboard shortcuts${Xn(`window.hotkeys`)}`,onClick:()=>C(!0),children:`⚙`}),(0,D.jsx)(`a`,{className:`chip source-link`,href:kr,target:`_blank`,rel:`noreferrer`,title:`diagc is free software under the AGPL-3.0 — get the source`,children:`source`})]}),mt&&(0,D.jsx)(EC,{editor:gt,onExit:wt,onSave:()=>void St(),saving:xt,saveIssues:yt,selectionColor:Bn,tool:ct,onSetTool:lt,pen:{color:ut,width:ft},onSetPen:e=>{e.color!==void 0&&dt(e.color),e.width!==void 0&&pt(e.width)},drawingDisabled:rt.length>0}),n.length===0&&(0,D.jsx)(`div`,{className:`banner`,children:l?(0,D.jsxs)(D.Fragment,{children:[`No diagrams yet — use `,(0,D.jsx)(`b`,{children:`New diagram`}),` to create one.`]}):(0,D.jsxs)(D.Fragment,{children:[`No artifacts found — run `,(0,D.jsx)(`code`,{children:`pnpm compile`}),` (or `,(0,D.jsx)(`code`,{children:`pnpm compile:watch`}),`) first.`]})}),!mt&&Tt!==void 0&&Tt.issues.length>0&&(0,D.jsxs)(`div`,{className:`banner error`,children:[(0,D.jsx)(`b`,{children:Tt.name}),` failed validation:`,(0,D.jsx)(`ul`,{children:Tt.issues.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})]}),!mt&&yt!==null&&yt.length>0&&(0,D.jsx)(`div`,{className:`banner error`,children:(0,D.jsx)(`ul`,{children:yt.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})}),(0,D.jsx)(`main`,{className:`body`,children:Dt!==void 0&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(rT,{side:`left`,collapsed:Ge,onToggle:()=>Ke(e=>!e),hasContent:mt?!0:Se!==null,width:Ye,minWidth:AE,maxWidth:kE,onWidthChange:Xe,children:mt?(0,D.jsx)(tT,{activeTab:He,onTabChange:Ue,properties:Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(Ow,{model:Dt,nodeId:Se.id,activePlane:Mt,hasPin:Vn!==void 0,...Vn===void 0?{}:{pinned:Vn},...Hn===void 0?{}:{live:Hn},autoFocusName:Se.id===we,...Nt===void 0?{}:{notation:Nt},today:Pt,onCommand:gt.dispatch,onClose:()=>Jt(null),onDeleted:()=>Jt(null)},Se.id):Se?.kind===`edge`?(0,D.jsx)(Mw,{model:Dt,constituentIds:Se.constituentIds??[Se.id],onCommand:gt.dispatch,onClose:()=>Jt(null),...Nt===void 0?{}:{notation:Nt},...Mt===void 0?{}:{activePlane:Mt}},Se.id):(0,D.jsx)($le,{model:Dt,selection:Se}),library:(0,D.jsx)(aue,{library:$e.library,onPlace:xn,onApply:Cn,...PE(Dt,Se)??{},onAddNode:yn,onAddImages:e=>void Tn(e),onAddCategory:$e.addCategory,onDeleteCategory:$e.deleteCategory,onImportIcon:(e,t)=>void En(e,t),onImportShape:(e,t)=>void Dn(e,t),assetBase:Kx().assetBase,viewState:We})}):Nt===`causal-loop`&&Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(sy,{model:Dt,edges:Le,target:Se.id,activeFocusKey:Be?.key??null,onFocus:Ve,onClose:()=>Jt(null),compareId:Fe,onClearCompare:()=>Ie(null)},Se.id):Se===null?(0,D.jsx)(`div`,{className:`sidebar dock-empty`,children:`Select a node or edge for details.`}):(0,D.jsx)($le,{model:Dt,selection:Se})}),(0,D.jsxs)(`div`,{className:`canvas-area`,children:[(0,D.jsx)(Gse,{model:Dt,plane:Mt,today:Pt,activeLayers:oe,onToggleLayer:Zt,pins:ue,onToggleExpand:$t,onSelect:Jt,onMultiSelect:Pe,onEnteredPathChange:at,enteredPath:rt,onCompareSelect:tn,colorMode:u,assetBase:Kx().assetBase,...Kx().libraryBase===void 0?{}:{libraryBase:Kx().libraryBase},onOpenLink:e=>Kx().openLink(e),styleId:At??f,...m?{snapGrid:EE}:{},onCldEdges:ze,onViewPositionsChange:he,onViewLabelMovesChange:_e,layoutApiRef:vt,canvasCommandsRef:te,builtinKeys:!1,keyHints:$n,ignoreSavedPositions:be,externalHighlight:mt?Me.length>=2?{nodes:Me,edges:[]}:null:Be??(Fe!==null&&Se?.kind===`node`?{nodes:[Se.id,Fe],edges:[]}:null),...Nt===void 0?{}:{notation:Nt},...zt===void 0?{}:{layout:zt},...kt===void 0?{}:{drawings:kt},...mt?{mode:`edit`,tool:ct,pen:{...ut===``?{}:{color:ut},width:ft},edit:{...Ee===void 0?{}:{editLabelRequest:Ee},...ke===void 0?{}:{editThreatRequest:ke},onNoteMoved:(e,t)=>gt.dispatch({type:`set-note-offset`,target:e,offset:t,...on}),onToggleNote:(e,t)=>gt.dispatch({type:`set-note-open`,target:e,open:t,...on}),onAddThreat:cn,onRetitleThreat:dn,onSetThreatStatus:fn,onEditThreatText:mn,quickAdd:{label:(e,t)=>Dt===void 0?void 0:wle(Dt,e,rn,t),run:an},onNodesMoved:(e,t)=>{if(Nt===`plan`&&Dt!==void 0){let n=AS(Dt,Mt,e,t);n!==void 0&&gt.dispatch(n);return}gt.dispatch({type:`set-positions`,positions:e,...Mt===void 0?{}:{plane:Mt}})},onDropInto:(e,t,n)=>{if(Nt===`plan`&&Dt!==void 0){let r=$se(Dt,Mt,e,t,n);r!==void 0&&gt.dispatch(r)}},onMoveLane:(e,t,n)=>{let r=Vw(e,t,n,Mt);r!==null&&gt.dispatch(r)},onSetRole:(e,t,n)=>{if(Dt===void 0)return;let r=Zse(Dt,e,t,n);r!==void 0&&gt.dispatch(r)},onCreateAt:e=>bn(e),onImageFiles:(e,t)=>void Tn(e,t),onDropLibraryEntry:wn,onResize:(e,t,n,r)=>{if(Nt===`plan`&&Dt!==void 0){let n=Dt.nodes.find(t=>t.id===e);if(n!==void 0&&Un(n)){let n=jS(Dt,Mt,e,r.x,t);n!==void 0&&gt.dispatch(n);return}}gt.dispatch({type:`set-size`,nodeId:e,w:t,h:n}),gt.dispatch({type:`set-position`,nodeId:e,x:r.x,y:r.y,...Mt===void 0?{}:{plane:Mt}})},onConnect:(e,t,n)=>{let r=gt.session?.state.model,i=r===void 0?null:sue(r,e,t,n,Vt===null?void 0:{layer:Vt});if(i!==null){for(let e of i)gt.dispatch(e);return}gt.dispatch({type:`add-relation`,from:e,to:t,opts:{kind:Xw(Nt,r,e,t),...Vt===null?{}:{layer:Vt}}})},onDeleteSelection:e=>{let t=gt.peek()?.state.model,n=t===void 0?null:bE(t,e);n!==null&&(gt.dispatch(n),Jt(null))},onSetTableColumns:(e,t)=>gt.dispatch({type:`set-table-columns`,id:e,columns:t}),onRenameNode:(e,t)=>gt.dispatch({type:`rename-node`,id:e,name:t}),onSetNodeRich:(e,t)=>gt.dispatch({type:`set-node-rich`,id:e,runs:t}),onAddEdgeLabel:Ut,onEditEdgeLabel:Wt,onMoveEdgeLabel:Gt,onReconnect:(e,t,n,r)=>gt.dispatch({type:`update-relation`,id:e,patch:{from:t,to:n,...r===void 0?{}:{style:Ht(e,r.end,r.side)}}}),onSetEdgeSide:(e,t,n)=>gt.dispatch({type:`update-relation`,id:e,patch:{style:Ht(e,t,n)}}),onAddStroke:e=>{let t=gt.peek()?.state.drawings,n=gt.peek()?.state.model;t===void 0||n===void 0||gt.dispatch({type:`add-stroke`,stroke:{id:Dr(t,Yr(n,Mt)),...e},...Mt===void 0?{}:{plane:Mt}})},onDeleteStroke:e=>gt.dispatch({type:`delete-stroke`,id:e,...Mt===void 0?{}:{plane:Mt}})}}:{}}),mt&&Me.length>=2&&(0,D.jsxs)(`button`,{className:`chip group-action`,title:`Group the selection${Xn(`edit.group`)}`,onClick:()=>void nn(),children:[`⊞ Group `,Me.length]})]}),(0,D.jsxs)(rT,{side:`right`,collapsed:qe,onToggle:()=>Je(e=>!e),hasContent:!0,width:Ze,minWidth:jE,maxWidth:kE,onWidthChange:Qe,children:[mt&&Nt===`git-graph`&&(0,D.jsx)(ule,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),mt&&Nt===`plan`&&(0,D.jsx)(Yw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),today:Pt}),mt&&Nt===`second-order`&&(0,D.jsx)(hle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),mt&&Nt===`fishbone`&&(0,D.jsx)(yle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),Nt===`threat-model`&&(0,D.jsx)(qw,{model:Dt,...Mt===void 0?{}:{plane:Mt},onSelect:Jt}),mt&&(0,D.jsx)(Hw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),(0,D.jsxs)(Mce,{controls:Eh(Nt).layout===void 0?{settings:Bt,onChange:mt?An:zn,defaultDirection:_t(Dt),algorithmLocked:Ft,...Eh(Nt).defaultAlgorithm===void 0?{}:{defaultAlgorithm:Eh(Nt).defaultAlgorithm}}:null,styleControl:mt?(0,D.jsxs)(`select`,{className:`chip-select`,"aria-label":`Diagram style`,title:`Diagram style (saved with the diagram)`,value:At??``,onChange:e=>gt.dispatch({type:`set-diagram-style`,style:e.target.value===``?null:e.target.value}),children:[(0,D.jsx)(`option`,{value:``,children:`(app default)`}),Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))]}):(0,D.jsx)(`select`,{className:`chip-select`,"aria-label":`Style`,title:At===void 0?`Visual style`:`Set by diagram`,value:At??(Ov(f)?f:`clean`),disabled:At!==void 0,onChange:e=>p(e.target.value),children:Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))}),children:[mt&&(0,D.jsx)(OC,{editor:gt,activePlane:Mt,autoLayout:!Rt,onToggleAutoLayout:kn,getAutoPositions:()=>vt.current?.autoPositions()??{}}),!mt&&fe[Yr(Dt,Mt)]!==void 0&&(0,D.jsx)(`button`,{className:`chip`,title:`Drop the preview and go back to this diagram's own layout settings`,onClick:()=>pe(e=>{let t={...e};return delete t[Yr(Dt,Mt)],t}),children:`Reset layout`}),!mt&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0&&(0,D.jsx)(`button`,{type:`button`,className:`chip${be?` active`:``}`,"aria-pressed":be,title:`${be?`Ignoring this diagram’s saved positions, so the layout algorithm arranges every node. Click to put them back.`:`This plane has saved positions, which override the layout algorithm. Click to arrange those nodes automatically instead (nothing is written).`}${Xn(`view.auto-arrange`)}`,onClick:()=>xe(e=>!e),children:`Auto-arrange`}),!mt&&(0,D.jsx)(`button`,{type:`button`,className:`chip${Rt?` active`:``}`,"aria-pressed":Rt,disabled:ve||rt.length>0,title:`${rt.length>0?`Freezing pins the whole plane, but a drilled view only has positions for what it shows — leave the drilled view first.`:Rt?`Positions are pinned. Click to let the layout algorithm arrange this plane again (your positions are kept).`:`Pin every box where it is so the layout algorithm stops moving them. Boxes added to the source later are still placed automatically until you move them.`}${Xn(`view.freeze`)}`,onClick:()=>void Rn(),children:`Freeze layout`})]}),(0,D.jsx)(Bw,{model:Dt,onCommand:gt.dispatch,mode:mt?`edit`:`view`,activeLayer:Vt,onActivateLayer:Xt,activePlane:Mt,onSelectPlane:e=>e===void 0?en():Yt(e),activeLayers:oe,onToggleLayer:Zt,onMergeLayers:Qt})]})]})}),S&&(0,D.jsx)(CE,{overrides:g,onChange:_,onClose:()=>{C(!1),ee.current?.focus()},mac:T})]})})}var hue=document.getElementById(`root`);hue&&(0,y.createRoot)(hue).render((0,D.jsx)(mue,{}));
109
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+QT(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function fE(e,t){return dE.parse(e,t)}fE.options=fE.setOptions=function(e){return dE.setOptions(e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.getDefaults=iT,fE.defaults=aT,fE.use=function(...e){return dE.use(...e),fE.defaults=dE.defaults,oT(fE.defaults),fE},fE.walkTokens=function(e,t){return dE.walkTokens(e,t)},fE.parseInline=dE.parseInline,fE.Parser=lE,fE.parser=lE.parse,fE.Renderer=sE,fE.TextRenderer=cE,fE.Lexer=oE,fE.lexer=oE.lex,fE.Tokenizer=aE,fE.Hooks=uE,fE.parse=fE,fE.options,fE.setOptions,fE.use,fE.walkTokens,fE.parseInline,lE.parse,oE.lex;function Qle({metadata:e}){let t=Object.entries(e);return t.length===0?null:(0,D.jsx)(`dl`,{className:`meta`,children:t.map(([e,t])=>(0,D.jsxs)(`div`,{className:`meta-row`,children:[(0,D.jsx)(`dt`,{children:e}),(0,D.jsx)(`dd`,{children:typeof t==`string`&&/^https?:\/\//.test(t)?(0,D.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,children:t}):String(t)})]},e))})}function $le({model:e,selection:t}){if(t===null)return(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Select a node or edge for details.`});if(t.kind===`node`){let n=e.nodes.find(e=>e.id===t.id);return n?(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsx)(`h2`,{children:n.name}),(0,D.jsxs)(`p`,{className:`muted`,children:[n.type,` · `,(0,D.jsx)(`code`,{children:n.id})]}),n.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(n.description)}}),n.metadata!==void 0&&(0,D.jsx)(Qle,{metadata:n.metadata})]}):(0,D.jsx)(`aside`,{className:`sidebar muted`,children:`Aggregate node (zoom in for details).`})}let[n]=t.id.split(`:`),[r,i]=(n??``).split(`=>`),a=new Set(t.constituentIds??[]),o=e.relations.filter(e=>a.has(e.id));return(0,D.jsxs)(`aside`,{className:`sidebar`,children:[(0,D.jsxs)(`h2`,{children:[r,` → `,i]}),o.length===0?(0,D.jsx)(`p`,{className:`muted`,children:`No relation details available.`}):(0,D.jsx)(`ul`,{children:o.map(e=>(0,D.jsxs)(`li`,{children:[(0,D.jsx)(`code`,{children:e.from}),` → `,(0,D.jsx)(`code`,{children:e.to}),` `,(0,D.jsx)(`b`,{children:e.kind}),e.label===void 0?``:` — ${e.label}`,e.description!==void 0&&(0,D.jsx)(`div`,{dangerouslySetInnerHTML:{__html:fE.parse(e.description)}})]},e.id))})]})}var pE=xi(),eue=Ty(),tue={query:``,toggled:{},groupToggled:{}},mE=(e,t)=>{let{libraryBase:n}=Kx();return n!==void 0&&t.startsWith(`/library/`)?`${n}${t.slice(9)}`:t.startsWith(`/`)||/^https?:/.test(t)?t:`${e}${t}`},nue=16,rue=64;function iue(e){let t=[],n=new Map;for(let r of e){if(r.group===void 0){t.push({cats:[r]});continue}let e=n.get(r.group);e===void 0&&(e={group:r.group,cats:[]},n.set(r.group,e),t.push(e)),e.cats.push(r)}return t}function hE({entry:e,assetBase:t}){if(e.template.image!==void 0)return(0,D.jsx)(`img`,{className:`lib-thumb`,src:mE(t,e.template.image),alt:e.name,draggable:!1});if(e.template.shape!==void 0){let n=`url("${mE(t,e.template.shape)}")`;return(0,D.jsx)(`span`,{className:`lib-thumb lib-shape-thumb`,"aria-hidden":`true`,style:{WebkitMaskImage:n,maskImage:n,background:e.template.color??`var(--dg-text-muted)`}})}let n=e.template.color??`var(--dg-border)`,r=e.template.type===void 0?void 0:pE.resolve(e.template.type),i=r?.icon===void 0?void 0:eue.resolve(r.icon),a=r?.outline===!0||r?.dashed===!0;return(0,D.jsx)(`span`,{className:`lib-swatch lib-swatch-${r?.shape??`box`}${a?` lib-swatch-outline`:``}`,style:a?{border:`1.5px ${r?.dashed===!0?`dashed`:`solid`} ${n}`,color:n}:{background:n},children:i!==void 0&&(0,D.jsx)(i,{size:14,className:`lib-swatch-icon`})})}function aue({library:e,onPlace:t,onApply:n,applyTarget:r,onAddNode:i,onAddImages:a,onAddCategory:o,onDeleteCategory:s,onImportIcon:c,onImportShape:l,assetBase:u=`/api/assets/`,viewState:d}){let f=(0,v.useState)(tue),[{query:p,toggled:m,groupToggled:h},g]=d??f,_=e=>g(t=>({...t,query:e})),[y,b]=(0,v.useState)(``),[x,S]=(0,v.useState)(`place`),C=(0,v.useMemo)(()=>nce(e,p),[e,p]),w=(0,v.useMemo)(()=>{let e=new Map;for(let t of C){let n=e.get(t.category);n===void 0?e.set(t.category,[t]):n.push(t)}return e},[C]),T=p.trim()!==``,E=(0,v.useMemo)(()=>iue(e.categories),[e.categories]),ee=r!==void 0&&n!==void 0,te=ee&&x===`apply`;(0,v.useEffect)(()=>{S(`place`)},[r?.id]);let ne=()=>{let e=y.trim();e===``||o===void 0||(o(e),b(``))};return(0,D.jsxs)(`aside`,{className:`sidebar lib-panel`,children:[(0,D.jsx)(`div`,{className:`panel-head`,children:(0,D.jsx)(`h3`,{children:`Library`})}),(i!==void 0||a!==void 0)&&(0,D.jsxs)(`div`,{className:`lib-actions`,children:[i!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:i,children:`Add node`}),a!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Add image`,children:[`Add image`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,multiple:!0,hidden:!0,"aria-label":`Add image`,onChange:e=>{let t=[...e.target.files??[]];t.length>0&&a(t),e.target.value=``}})]})]}),ee&&(0,D.jsxs)(`div`,{className:`lib-apply-toggle`,role:`group`,"aria-label":`Card click action`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip${te?``:` active`}`,"aria-pressed":!te,title:`Clicking a card adds a new node`,onClick:()=>S(`place`),children:`Place new`}),(0,D.jsxs)(`button`,{type:`button`,className:`chip${te?` active`:``}`,"aria-pressed":te,title:`Clicking a card restyles ${r.name} to match it`,onClick:()=>S(`apply`),children:[`Apply to `,r.name]})]}),(0,D.jsx)(`input`,{className:`lib-search`,type:`search`,"aria-label":`Search library`,placeholder:`Search nodes…`,value:p,onChange:e=>_(e.target.value)}),E.map(e=>{let i=e=>{let i=w.get(e.id)??[];if(i.length===0&&(T||e.builtin===!0))return null;let a=m[e.id]??(T||i.length<=nue);return(0,D.jsxs)(`section`,{className:`lib-category`,children:[(0,D.jsxs)(`div`,{className:`lib-cat-head`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":e.name,"aria-expanded":a,title:`${a?`Collapse`:`Expand`} ${e.name}`,onClick:()=>g(t=>({...t,toggled:{...t.toggled,[e.id]:!a}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:a?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:e.name}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:i.length})]})}),e.builtin!==!0&&(0,D.jsxs)(`span`,{className:`lib-cat-actions`,children:[c!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import icon into ${e.name}`,children:[`Icon`,(0,D.jsx)(`input`,{type:`file`,accept:`image/*`,hidden:!0,"aria-label":`Import icon into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&c(e.id,n),t.target.value=``}})]}),l!==void 0&&(0,D.jsxs)(`label`,{className:`chip icon-btn`,title:`Import shape into ${e.name}`,children:[`Shape`,(0,D.jsx)(`input`,{type:`file`,accept:`.svg,image/svg+xml`,hidden:!0,"aria-label":`Import shape into ${e.name}`,onChange:t=>{let n=t.target.files?.[0];n!==void 0&&l(e.id,n),t.target.value=``}})]}),s!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon-btn`,"aria-label":`Delete category ${e.name}`,title:`Delete category ${e.name}`,onClick:()=>void Kx().confirmDialog(`Delete category '${e.name}' and its imported icons?`).then(t=>{t&&s(e.id)}),children:`✕`})]})]}),a&&(0,D.jsx)(`div`,{className:`lib-grid`,children:i.map(e=>(0,D.jsxs)(`button`,{type:`button`,className:`lib-entry`,"aria-label":te?`Apply ${e.name}`:`Place ${e.name}`,title:te?`Apply ${e.name} to ${r.name}`:`Place ${e.name}`,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`application/x-dg-library-entry`,e.id),t.dataTransfer.effectAllowed=`copy`},onClick:()=>te?n(e):t(e),children:[(0,D.jsx)(hE,{entry:e,assetBase:u}),(0,D.jsx)(`span`,{className:`lib-entry-name`,children:e.name})]},e.id))})]},e.id)};if(e.group===void 0)return i(e.cats[0]);let a=e.group,o=e.cats.reduce((e,t)=>e+(w.get(t.id)??[]).length,0);if(o===0&&T)return null;let d=h[a]??(T||o<=rue);return(0,D.jsxs)(`section`,{className:`lib-group`,children:[(0,D.jsx)(`h4`,{className:`lib-cat-name lib-group-name`,children:(0,D.jsxs)(`button`,{type:`button`,className:`lib-cat-toggle`,"aria-label":a,"aria-expanded":d,title:`${d?`Collapse`:`Expand`} ${a}`,onClick:()=>g(e=>({...e,groupToggled:{...e.groupToggled,[a]:!d}})),children:[(0,D.jsx)(`span`,{className:`lib-cat-caret`,"aria-hidden":`true`,children:d?`▾`:`▸`}),(0,D.jsx)(`span`,{className:`lib-cat-label`,children:a}),(0,D.jsx)(`span`,{className:`lib-cat-count`,children:o})]})}),d&&(0,D.jsx)(`div`,{className:`lib-group-body`,children:e.cats.map(i)})]},`group:${a}`)}),o!==void 0&&(0,D.jsxs)(`div`,{className:`add-member`,children:[(0,D.jsx)(`input`,{"aria-label":`New category name`,placeholder:`New category…`,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),ne())}}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Add category`,onClick:ne,children:`+`})]})]})}var gE={categories:[],entries:[]};async function oue(){try{let e=await Kx().apiFetch(`/api/library`);if(!e.ok)return gE;let t=await e.json();return{categories:t.categories??[],entries:t.entries??[]}}catch{return gE}}async function _E(e){let t=await Kx().apiFetch(`/api/library`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.issues?.[0]?.message??`Library save failed (${t.status})`)}}var vE=new Set(ww.categories.map(e=>e.id));function yE(){let[e,t]=(0,v.useState)({categories:[],entries:[]}),n=(0,v.useRef)(e);n.current=e,(0,v.useEffect)(()=>{oue().then(t)},[]);let r=(0,v.useMemo)(()=>LS(ww,e),[e]),i=(0,v.useCallback)(e=>{t(e),_E(e).catch(()=>{})},[]);return{library:r,addCategory:(0,v.useCallback)(e=>{let t=n.current,r=RS(e,new Set(LS(ww,t).categories.map(e=>e.id)),`category`);i({...t,categories:[...t.categories,{id:r,name:e.trim()||r}]})},[i]),deleteCategory:(0,v.useCallback)(e=>{if(vE.has(e))return;let t=n.current;i({categories:t.categories.filter(t=>t.id!==e),entries:t.entries.filter(t=>t.category!==e)})},[i]),addEntry:(0,v.useCallback)(e=>{let t=n.current;i({...t,entries:[...t.entries,e]})},[i])}}function bE(e,t){let n=new Map(e.nodes.map(e=>[e.id,e.type])),r=new Set(e.relations.map(e=>e.id)),i=e=>oe.includes(n.get(e)??``),a=new Set;for(let r of t.nodeIds)if(!(!n.has(r)||!i(r)))for(let t of Fe(e,r))t!==r&&a.add(t);let o=[...t.relationIds.filter(e=>r.has(e)).map(e=>({type:`delete-relation`,id:e})),...t.nodeIds.filter(e=>n.has(e)&&!a.has(e)).map(e=>({type:`delete-node`,id:e,...i(e)?{cascade:!0}:{}}))];return o.length===0?null:o.length===1?o[0]:{type:`batch`,commands:o}}function sue(e,t,n,r,i){let a=e.nodes.find(e=>e.id===t);if(a?.type!==`db-table`||a.columns===void 0)return null;let o=a.columns.find(e=>e.name===r);if(o===void 0)return null;let s=e.nodes.find(e=>e.id===n)?.columns?.find(e=>e.pk===!0)?.name,c=[{type:`add-relation`,from:t,to:n,opts:{kind:`fk`,fromColumn:o.name,...s===void 0?{}:{toColumn:s},...i?.layer===void 0?{}:{layer:i.layer}}}];return o.fk!==!0&&c.push({type:`set-table-columns`,id:t,columns:a.columns.map(e=>e.name===o.name?{...e,fk:!0}:e)}),c}var xE=e=>e.map(e=>oC(e).label).join(`, `),SE=(e,t,n)=>{let r=[...sC(e)[t.id]];return r[t.index]=n,gC(e,t.id,r)};function CE({overrides:e,onChange:t,onClose:n,mac:r=rC()}){let i=(0,v.useMemo)(()=>sC(e),[e]),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(null),[d,f]=(0,v.useState)(null),p=(0,v.useRef)(null);(0,v.useEffect)(()=>{p.current?.focus()},[]);let m=e=>nC(e,r),h=e=>{f(null),u(null),c(e)},g=a=>{if(s===null){if(a.key!==`Escape`)return;a.stopPropagation(),l===null?n():u(null);return}if(a.preventDefault(),a.stopPropagation(),a.key===`Escape`){c(null);return}let o=QS(a.nativeEvent,r);if(o===null)return;c(null);let d=hC(o);if(d!==null){f(`${m(o)}: ${d}`);return}if(i[s.id].includes(o))return;let p=bce(i,s.id,o);p.length>0?u({...s,chord:o,conflicts:p}):t(SE(e,s,o))},_=()=>{if(l===null)return;let n=e;for(let e of l.conflicts)n=gC(n,e,sC(n)[e].filter(e=>e!==l.chord));t(SE(n,l,l.chord)),u(null)},y=n=>{let r={...e};delete r[n],t(r)},b=async()=>{await Kx().confirmDialog(`Reset every keyboard shortcut to its default?`)&&t({})},x=a.trim().toLowerCase(),S=aC.filter(e=>x===``||e.label.toLowerCase().includes(x)||e.group.toLowerCase().includes(x)||i[e.id].some(e=>m(e).toLowerCase().includes(x))),C=(e,t)=>s?.id===e&&s.index===t;return(0,D.jsx)(`div`,{className:`hotkeys-backdrop`,"data-testid":`hotkeys-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,D.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,className:`hotkeys-dialog`,tabIndex:-1,onKeyDownCapture:g,children:[(0,D.jsxs)(`header`,{className:`hotkeys-head`,children:[(0,D.jsx)(`strong`,{children:`Keyboard shortcuts`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,"aria-label":`Close`,onClick:n,children:`✕`})]}),(0,D.jsx)(`input`,{ref:p,className:`hotkeys-search`,"aria-label":`Search shortcuts`,placeholder:`search actions…`,value:a,onChange:e=>o(e.target.value)}),l!==null&&(0,D.jsxs)(`div`,{className:`hotkeys-note`,role:`alert`,children:[(0,D.jsxs)(`span`,{children:[m(l.chord),` is already `,xE(l.conflicts),`.`]}),(0,D.jsx)(`button`,{type:`button`,className:`chip primary`,onClick:_,children:`Reassign`}),(0,D.jsx)(`button`,{type:`button`,className:`chip`,onClick:()=>u(null),children:`Cancel`})]}),d!==null&&(0,D.jsx)(`div`,{className:`hotkeys-note`,role:`alert`,children:d}),(0,D.jsxs)(`div`,{className:`hotkeys-list`,children:[iC.map(n=>{let r=S.filter(e=>e.group===n);return r.length===0?null:(0,D.jsxs)(`section`,{"aria-label":n,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:n}),r.map(n=>{let r=i[n.id];return(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:n.label}),(0,D.jsxs)(`span`,{className:`hotkeys-keys`,children:[r.length===0&&!C(n.id,0)&&(0,D.jsx)(`span`,{className:`hotkeys-unbound`,children:`—`}),r.map((a,o)=>{let s=bce(i,n.id,a);return(0,D.jsxs)(`span`,{className:`hotkeys-key`,children:[(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip`,"aria-label":`Change ${m(a)} for ${n.label}`,...s.length>0?{title:`Also bound to ${xE(s)}`,"data-conflict":``}:{},...C(n.id,o)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:o}),children:C(n.id,o)?`Press a key…`:m(a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Remove ${m(a)} from ${n.label}`,onClick:()=>t(gC(e,n.id,r.filter((e,t)=>t!==o))),children:`×`})]},a)}),(0,D.jsx)(`button`,{type:`button`,className:`hotkey-chip hotkey-add`,"aria-label":`Add a key for ${n.label}`,...C(n.id,r.length)?{"data-recording":``}:{},onClick:()=>h({id:n.id,index:r.length}),children:C(n.id,r.length)?`Press a key…`:`+`}),e[n.id]!==void 0&&(0,D.jsx)(`button`,{type:`button`,className:`hotkey-x`,"aria-label":`Reset ${n.label}`,title:`Back to the default`,onClick:()=>y(n.id),children:`↺`})]})]},n.id)})]},n)}),x===``&&(0,D.jsxs)(`section`,{"aria-label":`Fixed`,children:[(0,D.jsx)(`h3`,{className:`hotkeys-group`,children:`Fixed`}),vce.map(e=>(0,D.jsxs)(`div`,{className:`hotkeys-row`,children:[(0,D.jsx)(`span`,{className:`hotkeys-label`,children:e.label}),(0,D.jsx)(`span`,{className:`hotkeys-keys hotkeys-fixed`,children:e.keys})]},e.label))]})]}),(0,D.jsxs)(`footer`,{className:`hotkeys-foot`,children:[(0,D.jsx)(`button`,{type:`button`,className:`chip`,disabled:Object.keys(e).length===0,onClick:()=>void b(),children:`Reset all to defaults`}),(0,D.jsx)(`span`,{className:`hotkeys-hint`,children:`Click a key to change it. Esc cancels.`})]})]})})}var cue=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable===!0||e.closest(`[contenteditable=""], [contenteditable="true"]`)!==null},wE=(e,t)=>e instanceof Element&&e!==document.body&&e!==document.documentElement&&t!==null&&!t.contains(e);function lue({rootRef:e,keymap:t,mode:n,handlersRef:r,suspended:i,mac:a=rC()}){let o=(0,v.useRef)({keymap:t,mode:n,suspended:i});o.current={keymap:t,mode:n,suspended:i};let s=(0,v.useRef)(null);(0,v.useEffect)(()=>{let t=t=>{let{keymap:n,mode:i,suspended:c}=o.current;if(c||t.defaultPrevented||wE(t.target,e.current))return;let l=QS(t,a);if(l===null)return;let u=uC(n,l,i);if(u===void 0)return;let d=oC(u);if(cue(t.target)&&!(d.inFields===!0&&(t.ctrlKey||t.metaKey||t.altKey)))return;if(t.repeat&&d.repeat!==!0){s.current?.chord===l&&s.current.claimed&&t.preventDefault();return}let f=r.current?.[u],p=f!==void 0&&f()!==!1;t.repeat||(s.current={chord:l,claimed:p}),p&&t.preventDefault()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,r,a])}var uue=`diagc.style`,TE=`diagc.snap`,EE=10,DE=`diagc.rightDock`,due=`diagc.leftDock`,fue=`diagc.leftDockWidth`,OE=`diagc.rightDockWidth`,kE=560,AE=220,jE=240,pue=300,ME=320,NE=(e,t,n)=>{if(e===null)return null;let r=Number(e);return Number.isFinite(r)?nT(r,t,n):null},PE=(e,t)=>{if(t?.kind!==`node`)return;let n=e.nodes.find(e=>e.id===t.id);return n===void 0?void 0:{applyTarget:{id:n.id,name:n.name||n.id}}};function mue({initialTheme:e=`dark`}={}){let{artifacts:t,names:n,booted:r,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,canDesign:l}=Jx(),[u,d]=(0,v.useState)(e),[f,p]=Zx(uue,`clean`,e=>e),[m,h]=Zx(TE,!1,e=>e===null?null:e===`true`),[g,_]=Zx(yce,{},Sce,JSON.stringify),y=(0,v.useMemo)(()=>sC(g),[g]),[S,C]=(0,v.useState)(!1),T=(0,v.useMemo)(rC,[]),E=(0,v.useRef)(null),ee=(0,v.useRef)(null),te=(0,v.useRef)(null),ne=(0,v.useRef)(null),re=(0,v.useRef)({}),[ie,ae]=(0,v.useState)(void 0),[oe,se]=(0,v.useState)([]),[ce,le]=(0,v.useState)(null),[ue,de]=(0,v.useState)({}),[fe,pe]=(0,v.useState)({}),[me,he]=(0,v.useState)({}),[ge,_e]=(0,v.useState)({}),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(null),[we,Te]=(0,v.useState)(null),[Ee,De]=(0,v.useState)(void 0),Oe=e=>De(t=>({id:e,nonce:(t?.nonce??0)+1})),[ke,Ae]=(0,v.useState)(void 0),je=(e,t)=>Ae(n=>({target:e,id:t,nonce:(n?.nonce??0)+1})),[Me,Ne]=(0,v.useState)([]),Pe=(0,v.useCallback)(e=>Ne(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e),[]),[Fe,Ie]=(0,v.useState)(null),[Le,Re]=(0,v.useState)([]),ze=(0,v.useCallback)(e=>Re(e),[]),[Be,Ve]=(0,v.useState)(null),[He,Ue]=(0,v.useState)(`properties`),We=(0,v.useState)(tue),[Ge,Ke]=Zx(due,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[qe,Je]=Zx(DE,!1,e=>e===`collapsed`,e=>e?`collapsed`:`expanded`),[Ye,Xe]=Zx(fue,pue,e=>NE(e,AE,kE)),[Ze,Qe]=Zx(OE,ME,e=>NE(e,jE,kE)),$e=yE(),et=(0,v.useRef)(()=>!0),{selected:tt,setSelected:nt,enteredPath:rt,setEnteredPath:it,handleEnteredPathChange:at}=tS({names:n,booted:r,leaveEditRef:et}),ot=rt.length>0?rt[rt.length-1]:void 0,st=(0,v.useRef)(tt);st.current=tt,(0,v.useEffect)(()=>{xe(!1)},[tt]),(0,v.useEffect)(()=>{pe({})},[tt]);let[ct,lt]=(0,v.useState)(`select`),[ut,dt]=(0,v.useState)(``),[ft,pt]=(0,v.useState)(3),{editing:mt,setEditing:ht,editor:gt,layoutApiRef:vt,saveIssues:yt,setSaveIssues:bt,saving:xt,doSave:St,enterEdit:Ct,leaveEdit:wt}=cS({setDrafts:o,resetInspector:()=>Ue(`properties`),leaveEditRef:et});(0,v.useEffect)(()=>{(!mt||rt.length>0)&&lt(`select`)},[mt,tt,rt]),(0,v.useEffect)(()=>{w(document.documentElement,u===`dark`?x:b),document.documentElement.dataset.theme=u},[u]);let Tt=t[tt],Et=gt.session,Dt=mt?Et?.state.model:Tt?.model,Ot=mt?Et?.state.layout:Tt?.layout,kt=mt?Et?.state.drawings:Tt?.drawings,At=Dt?.style!==void 0&&Ov(Dt.style)?Dt.style:void 0,jt=Dt?.planes??[],Mt=ie,Nt=Hr(jt,Mt,Dt?.notation),Pt=dae(),Ft=Eh(Nt).partitionOf!==void 0,It=jt.find(e=>e.id===Mt)?.containmentOf!==void 0,Lt=(0,v.useRef)(null);(0,v.useEffect)(()=>{if(Dt===void 0||Lt.current===tt)return;Lt.current=tt,se(Vr(Dt.planes,ie));let e=Ot?.export?.collapsed??[];de({...Object.fromEntries(e.map(e=>[e,`collapsed`])),...Xr(Ot,Dt,ie)})},[tt,Dt,ie,Ot]);let Rt=Dt!==void 0&&Ot?.manual?.[Yr(Dt,Mt)]===!0,zt=(0,v.useMemo)(()=>mt?Ot:Pce(Ot,Dt,Mt,fe),[mt,Ot,Dt,Mt,fe]),Bt=(Dt===void 0?void 0:zt?.settings?.[Yr(Dt,Mt)])??{},Vt=ce!==null&&(Dt?.layers??[]).some(e=>e.id===ce)?ce:null,Ht=(e,t,n)=>{let r={...Dt?.relations.find(t=>t.id===e)?.style},i=t===`from`?`fromSide`:`toSide`;return n===null?delete r[i]:r[i]=n,Object.keys(r).length>0?r:null},Ut=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&&gt.dispatch({type:`update-relation`,id:e,patch:{labels:fce(i,t,n,r)}})},Wt=(e,t,n)=>{if(Dt===void 0)return;let r=JS(Dt,e);r!==null&&gt.dispatch({type:`update-relation`,id:e,patch:{labels:pce(r,t,n)}})},Gt=(e,t,n,r)=>{if(Dt===void 0)return;let i=JS(Dt,e);i!==null&&gt.dispatch({type:`update-relation`,id:e,patch:{labels:mce(i,t,n,r)}})},Kt=Et?.lastRelationId;(0,v.useEffect)(()=>{mt&&Kt!==void 0&&(Ce({kind:`edge`,id:Kt}),Te(null))},[mt,Kt]);let qt=qS({editor:gt,model:Dt,selection:Se,groupSel:Me,editing:mt,notation:Nt,activePlane:Mt,activePlaneBorrowsContainment:It,planes:jt,activeLayer:ce,activeLayers:oe,setSelection:Ce,setRenameId:Te,setLeverageFocus:Ve,setCompareId:Ie,setPlane:ae,setPins:de,layout:Ot,pins:ue,setLayoutPreview:pe,setActiveLayers:se,setActiveLayer:le}),{select:Jt,switchPlane:Yt,activateLayer:Xt,toggleLayer:Zt,mergeSelectedLayers:Qt,toggleExpand:$t,resetView:en}=qt;yS({editing:mt,editor:gt,layoutApiRef:vt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,multiSelection:Me,select:Jt});let{compareSelect:tn,groupSelected:nn}=qt,rn={notation:Nt,plane:Mt,borrowsContainment:It,penLayer:Vt},an=(e,t)=>{let n=gt.peek()?.state.model;if(!mt||n===void 0)return!1;let r=Tle(n,e,rn,t);if(r===void 0)return!1;let i=Yr(n,Mt),a=Ot?.sizes?.[e];return gt.dispatch(Ele(r,{pinned:Rt||Ot?.planes[i]?.[e]!==void 0,source:vt.current?.snapshotPositions()[e],width:a?.w??qr.width,...a===void 0?{}:{size:a},plane:Mt})),Jt({kind:`node`,id:r.id}),Oe(r.id),!0},on=Mt===void 0?{}:{plane:Mt},cn=e=>{let t=gt.peek()?.state.model;if(t===void 0)return;let n=ln(t,e);if(n===void 0)return;let r=`node`in e?t.nodes.find(t=>t.id===e.node)?.type:t.relations.find(t=>t.id===e.relation)?.kind,i=un(n);gt.dispatch({type:`batch`,commands:[{type:`add-threat`,target:e,threat:{id:i,category:pn(r)[0]??`S`,title:sn}},{type:`set-note-open`,target:e,open:!0,...on}]}),je(e,i)},dn=(e,t,n)=>{let r=gt.peek()?.state.model,i=r===void 0?void 0:ln(r,e)?.find(e=>e.id===t);if(i!==void 0){if(n===``){i.title===`New threat`&&gt.dispatch({type:`remove-threat`,target:e,id:t});return}n!==i.title&&gt.dispatch({type:`update-threat`,target:e,id:t,patch:{title:n}})}},fn=(e,t,n)=>gt.dispatch({type:`update-threat`,target:e,id:t,patch:{status:n}}),mn=(e,t,n,r)=>{let i=gt.peek()?.state.model,a=i===void 0?void 0:ln(i,e)?.find(e=>e.id===t);a!==void 0&&(a[n]??``)!==r&&gt.dispatch({type:`update-threat`,target:e,id:t,patch:{[n]:r===``?null:r}})},hn=Dt!==void 0&&Ot!==void 0&&Sn(Dt,Ot,Yr(Dt,Mt)),gn=Dt!==void 0&&(Dt.nodes.some(e=>(e.threats?.length??0)>0)||Dt.relations.some(e=>(e.threats?.length??0)>0)),_n=Dt!==void 0&&(Nt===`threat-model`||gn),vn=sce({editing:mt,selected:tt,current:Tt,names:n,ownedNames:i,setOwnedNames:a,setDrafts:o,setLoaded:s,setSources:c,setSelected:nt,setEnteredPath:it,setEditing:ht,leaveEdit:wt,resetView:en,editor:gt}),{addNode:yn,createAt:bn,placeFromLibrary:xn,applyFromLibrary:Cn,dropLibraryEntry:wn,addImages:Tn}=rce({editor:gt,layoutApiRef:vt,setSelection:Ce,setRenameId:Te,setLeftTab:Ue,requestLabelEdit:Oe,setSaveIssues:bt,activePlane:Mt,activePlaneBorrowsContainment:It,activePlaneManual:Rt,penLayer:Vt,selection:Se,drillRoot:ot,model:Dt,lib:$e,notation:Nt,today:Pt}),En=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`icon`),i=t.name.replace(/\.[^.]*$/,``)||`icon`;$e.addEntry({id:r,category:e,name:i,template:{type:`image`,image:n,width:64,height:64}})}catch(e){bt([{message:Ar(e)}])}},Dn=async(e,t)=>{try{let n=await bS(t),r=RS(t.name,new Set($e.library.entries.map(e=>e.id)),`shape`),i=t.name.replace(/\.[^.]*$/,``)||`shape`;$e.addEntry({id:r,category:e,name:i,template:{shape:n}})}catch(e){bt([{message:Ar(e)}])}},On=async()=>{let e=tt;try{let t=await Kx().apiFetch(`/api/diagrams/${e}`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(st.current!==e)return;pe({}),Ct(e,n.model,n.layout??Jr(),n.drawings??Er())}catch(t){if(st.current!==e)return;bt([{message:`Could not load '${e}' for editing: ${Ar(t)}`}])}},kn=()=>{gt.session?.state.model!==void 0&&(Rt?gt.dispatch({type:`set-plane-layout`,manual:!1,...on}):(gt.dispatch({type:`set-positions`,positions:vt.current?.snapshotPositions()??{},...on}),gt.dispatch({type:`set-plane-layout`,manual:!0,...on})))},An=e=>{gt.session?.state.model!==void 0&&gt.dispatch({type:`set-layout-settings`,patch:e,...Mt===void 0?{}:{plane:Mt}})},jn=(0,v.useCallback)(async e=>{ye(!0);try{let t=await Kx().apiFetch(`/api/layouts/${tt}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json();return bt(e.issues??[{message:`Could not save layout`}]),!1}return s(t=>{let n=t[tt];return n===void 0?t:{...t,[tt]:{...n,layout:e}}}),bt(null),!0}finally{ye(!1)}},[tt,s,bt]),Mn=Dt===void 0?``:(Ot?.unfolded?.[Yr(Dt,Mt)]??[]).join(`\0`),Nn=(0,v.useRef)(null);(0,v.useEffect)(()=>{let e=Nn.current;Nn.current=mt?Mn:null,!(!mt||e===null||e===Mn||Dt===void 0)&&de(e=>KS(e).join(`\0`)===Mn?e:Xr(Ot,Dt,Mt))},[mt,Mn]);let Pn=(0,v.useMemo)(()=>KS(ue),[ue]),Fn=Dt!==void 0&&Pn.join(`\0`)!==Mn,In=Object.keys(me).length>0||Object.keys(ge).length>0||Fn,Ln=(0,v.useCallback)(async()=>{Dt===void 0||!In||await jn(lce(Ot,Dt,Mt,me,Pn,ge))&&(he({}),_e({}))},[Dt,me,ge,In,Pn,Ot,Mt,jn]),Rn=(0,v.useCallback)(async()=>{if(Dt===void 0)return;let e=!Rt,t=e?vt.current?.snapshotPositions()??{}:null;await jn(uce(Ot,Dt,Mt,t,e?Pn:void 0,e?ge:{}))&&e&&(he({}),_e({}))},[Dt,Ot,Mt,Rt,vt,jn,Pn,ge]),zn=(0,v.useCallback)(e=>{if(Dt===void 0)return;let t=Yr(Dt,Mt);pe(n=>PC(n,t,e))},[Dt,Mt]),Bn=mt&&Dt!==void 0?YS(Dt,Se,gt.dispatch):null,Vn=Se?.kind===`node`&&Dt!==void 0?Ot?.planes[Yr(Dt,Mt)]?.[Se.id]:void 0,Hn=Se?.kind===`node`&&Dt!==void 0?vt.current?.snapshotPositions()[Se.id]:void 0,Wn=(e,t)=>e?t:void 0,Gn=i.has(tt),Kn=!mt&&Dt!==void 0,qn=Dt!==void 0&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0,Jn=e=>Wn(Dt!==void 0,()=>te.current!==null&&e(te.current)),Yn=e=>()=>rt.length>0?!1:(lt(e),!0);re.current={"diagram.picker":()=>ne.current?.(),"diagram.toggle-edit":Wn(Dt!==void 0&&Gn,()=>void(mt?wt():On())),"diagram.rename":Wn(l&&!mt&&Gn,()=>void vn.renameDiagram()),"diagram.new":Wn(l,()=>void vn.newDiagram()),"diagram.duplicate":Wn(l&&Kn,()=>void vn.duplicateDiagram()),"diagram.eject":Wn(l&&!mt&&Gn,()=>void vn.ejectDiagram()),"edit.add-node":Wn(mt,()=>yn()),"edit.add-child":Wn(mt,()=>Se?.kind===`node`&&an(Se.id)),"edit.undo":Wn(mt,()=>gt.undo()),"edit.redo":Wn(mt,()=>gt.redo()),"edit.save":Wn(mt,()=>void St()),"edit.group":Wn(mt&&Me.length>=2,()=>void nn()),"edit.relayout":Wn(mt,()=>void DC(gt,{autoLayout:!Rt,activePlane:Mt,getAutoPositions:()=>vt.current?.autoPositions()??{}})),"edit.toggle-auto-layout":Wn(mt,kn),"edit.toggle-notes":Wn(mt&&_n&&gn,()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on})),"tool.select":Wn(mt,()=>lt(`select`)),"tool.pen":Wn(mt,Yn(`pen`)),"tool.eraser":Wn(mt,Yn(`eraser`)),"pen.thin":Wn(mt&&ct===`pen`,()=>pt(2)),"pen.medium":Wn(mt&&ct===`pen`,()=>pt(3)),"pen.thick":Wn(mt&&ct===`pen`,()=>pt(6)),"canvas.fit":Jn(e=>e.fitView()),"canvas.zoom-in":Jn(e=>e.zoomIn()),"canvas.zoom-out":Jn(e=>e.zoomOut()),"canvas.laser":Jn(e=>e.toggleLaser()),"canvas.legend":Jn(e=>e.toggleLegend()),"canvas.dim":Jn(e=>e.toggleDim()),"canvas.drawings":Jn(e=>e.toggleDrawings()),"canvas.loops":Jn(e=>e.toggleLoops()),"view.freeze":Wn(Kn&&!ve&&rt.length===0,()=>void Rn()),"view.save-positions":Wn(Kn&&In&&!ve,()=>void Ln()),"view.auto-arrange":Wn(Kn&&qn,()=>xe(e=>!e)),"arrange.align-left":Jn(e=>e.align(`left`)),"arrange.align-center":Jn(e=>e.align(`centerX`)),"arrange.align-right":Jn(e=>e.align(`right`)),"arrange.align-top":Jn(e=>e.align(`top`)),"arrange.align-middle":Jn(e=>e.align(`middle`)),"arrange.align-bottom":Jn(e=>e.align(`bottom`)),"arrange.distribute-x":Jn(e=>e.distribute(`x`)),"arrange.distribute-y":Jn(e=>e.distribute(`y`)),"window.left-dock":Wn(Dt!==void 0,()=>Ke(e=>!e)),"window.right-dock":Wn(Dt!==void 0,()=>Je(e=>!e)),"window.inspector-properties":Wn(mt,()=>{Ue(`properties`),Ke(!1)}),"window.inspector-library":Wn(mt,()=>{Ue(`library`),Ke(!1)}),"window.theme":()=>d(e=>e===`dark`?`light`:`dark`),"window.snap":()=>h(e=>!e),"window.hotkeys":()=>C(!0)},lue({rootRef:E,keymap:y,mode:mt?`edit`:`view`,handlersRef:re,suspended:S,mac:T});let Xn=e=>bC(y,e,T),Zn=[...Gn?[{id:`rename`,label:`Rename`,title:`Rename this diagram${Xn(`diagram.rename`)}`,onSelect:()=>void vn.renameDiagram()}]:[],...Dt===void 0?[]:[{id:`export-png`,label:`Export PNG`,title:`Save the canvas as drawn — folds, layers, theme and drawings — as a PNG image`,onSelect:()=>void Dce(vt.current,tt??``)},{id:`duplicate`,label:`Duplicate`,title:`Copy this diagram — layout and all — to a new editable one and open it${Xn(`diagram.duplicate`)}`,onSelect:()=>void vn.duplicateDiagram()}],...Gn?[{id:`eject`,label:`Eject`,title:`Promote this diagram to a TypeScript source — it becomes read-only here${Xn(`diagram.eject`)}`,onSelect:()=>void vn.ejectDiagram()}]:[]],Qn=(0,v.useMemo)(()=>({keymap:y,mac:T}),[y,T]),$n=(0,v.useMemo)(()=>({laser:yC(y,`canvas.laser`,T),dim:yC(y,`canvas.dim`,T),legend:yC(y,`canvas.legend`,T),drawings:yC(y,`canvas.drawings`,T),loops:yC(y,`canvas.loops`,T)}),[y,T]);return(0,D.jsx)(vC.Provider,{value:Qn,children:(0,D.jsxs)(`div`,{className:`app`,ref:E,children:[(0,D.jsxs)(`header`,{className:`topbar`,children:[(0,D.jsx)(`strong`,{className:`brand`,children:`diagc studio`}),(0,D.jsx)(Tce,{names:n,selected:tt,onSelect:e=>{wt()&&(nt(e),it([]),en())},toggleRef:ne}),l&&(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":`New diagram`,title:`New diagram${Xn(`diagram.new`)}`,onClick:()=>void vn.newDiagram(),children:`+`}),l&&!mt&&(0,D.jsx)(Nce,{label:`Diagram actions`,items:Zn,children:`⋯`}),Dt!==void 0&&(Gn?!mt&&(0,D.jsx)(`button`,{className:`chip`,onClick:()=>void On(),title:`Edit this diagram${Xn(`diagram.toggle-edit`)}`,children:`Edit`}):(0,D.jsx)(`span`,{className:`chip read-only`,title:`Compiled from TypeScript — edit the source`,children:`read-only`})),(0,D.jsx)(`span`,{className:`spacer`}),!mt&&Dt!==void 0&&In&&(0,D.jsx)(`button`,{className:`chip primary`,disabled:ve,title:`Write the boxes and edge labels you moved, and which groups are open, to this diagram's layout file. Safe on a generated diagram: re-compiling rewrites the model, never the layout.${Xn(`view.save-positions`)}`,onClick:()=>void Ln(),children:ve?`Saving…`:`Save positions`}),mt&&_n&&(0,D.jsx)(`button`,{type:`button`,className:`chip${hn?` active`:``}`,"aria-pressed":hn,disabled:!gn,title:`${hn?`Close all threat notes`:`Open all threat notes`}${Xn(`edit.toggle-notes`)}`,onClick:()=>gt.dispatch({type:`set-notes-open`,open:!hn,...on}),children:`Notes`}),(0,D.jsx)(`span`,{className:`sep`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon${m?` active`:``}`,"aria-label":`Snap to grid`,"aria-pressed":m,title:`${m?`Snapping to a ${EE}px grid. Click to place boxes freely.`:`Snap dragged boxes to a ${EE}px grid; arrow keys step by it too.`}${Xn(`window.snap`)}`,onClick:()=>h(e=>!e),children:`⋮⋮`}),(0,D.jsx)(`button`,{type:`button`,className:`chip icon`,"aria-label":u===`dark`?`Switch to light theme`:`Switch to dark theme`,title:`${u===`dark`?`Light theme`:`Dark theme`}${Xn(`window.theme`)}`,onClick:()=>d(u===`dark`?`light`:`dark`),children:u===`dark`?`☀`:`☾`}),(0,D.jsx)(`button`,{ref:ee,type:`button`,className:`chip icon`,"aria-label":`Keyboard shortcuts`,title:`Keyboard shortcuts${Xn(`window.hotkeys`)}`,onClick:()=>C(!0),children:`⚙`}),(0,D.jsx)(`a`,{className:`chip source-link`,href:kr,target:`_blank`,rel:`noreferrer`,title:`diagc is free software under the AGPL-3.0 — get the source`,children:`source`})]}),mt&&(0,D.jsx)(EC,{editor:gt,onExit:wt,onSave:()=>void St(),saving:xt,saveIssues:yt,selectionColor:Bn,tool:ct,onSetTool:lt,pen:{color:ut,width:ft},onSetPen:e=>{e.color!==void 0&&dt(e.color),e.width!==void 0&&pt(e.width)},drawingDisabled:rt.length>0}),n.length===0&&(0,D.jsx)(`div`,{className:`banner`,children:l?(0,D.jsxs)(D.Fragment,{children:[`No diagrams yet — use `,(0,D.jsx)(`b`,{children:`New diagram`}),` to create one.`]}):(0,D.jsxs)(D.Fragment,{children:[`No artifacts found — run `,(0,D.jsx)(`code`,{children:`diagc compile`}),` (or `,(0,D.jsx)(`code`,{children:`diagc watch`}),`) first.`]})}),!mt&&Tt!==void 0&&Tt.issues.length>0&&(0,D.jsxs)(`div`,{className:`banner error`,children:[(0,D.jsx)(`b`,{children:Tt.name}),` failed validation:`,(0,D.jsx)(`ul`,{children:Tt.issues.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})]}),!mt&&yt!==null&&yt.length>0&&(0,D.jsx)(`div`,{className:`banner error`,children:(0,D.jsx)(`ul`,{children:yt.map((e,t)=>(0,D.jsx)(`li`,{children:e.message},t))})}),(0,D.jsx)(`main`,{className:`body`,children:Dt!==void 0&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(rT,{side:`left`,collapsed:Ge,onToggle:()=>Ke(e=>!e),hasContent:mt?!0:Se!==null,width:Ye,minWidth:AE,maxWidth:kE,onWidthChange:Xe,children:mt?(0,D.jsx)(tT,{activeTab:He,onTabChange:Ue,properties:Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(Ow,{model:Dt,nodeId:Se.id,activePlane:Mt,hasPin:Vn!==void 0,...Vn===void 0?{}:{pinned:Vn},...Hn===void 0?{}:{live:Hn},autoFocusName:Se.id===we,...Nt===void 0?{}:{notation:Nt},today:Pt,onCommand:gt.dispatch,onClose:()=>Jt(null),onDeleted:()=>Jt(null)},Se.id):Se?.kind===`edge`?(0,D.jsx)(Mw,{model:Dt,constituentIds:Se.constituentIds??[Se.id],onCommand:gt.dispatch,onClose:()=>Jt(null),...Nt===void 0?{}:{notation:Nt},...Mt===void 0?{}:{activePlane:Mt}},Se.id):(0,D.jsx)($le,{model:Dt,selection:Se}),library:(0,D.jsx)(aue,{library:$e.library,onPlace:xn,onApply:Cn,...PE(Dt,Se)??{},onAddNode:yn,onAddImages:e=>void Tn(e),onAddCategory:$e.addCategory,onDeleteCategory:$e.deleteCategory,onImportIcon:(e,t)=>void En(e,t),onImportShape:(e,t)=>void Dn(e,t),assetBase:Kx().assetBase,viewState:We})}):Nt===`causal-loop`&&Se?.kind===`node`&&Dt.nodes.some(e=>e.id===Se.id)?(0,D.jsx)(sy,{model:Dt,edges:Le,target:Se.id,activeFocusKey:Be?.key??null,onFocus:Ve,onClose:()=>Jt(null),compareId:Fe,onClearCompare:()=>Ie(null)},Se.id):Se===null?(0,D.jsx)(`div`,{className:`sidebar dock-empty`,children:`Select a node or edge for details.`}):(0,D.jsx)($le,{model:Dt,selection:Se})}),(0,D.jsxs)(`div`,{className:`canvas-area`,children:[(0,D.jsx)(Gse,{model:Dt,plane:Mt,today:Pt,activeLayers:oe,onToggleLayer:Zt,pins:ue,onToggleExpand:$t,onSelect:Jt,onMultiSelect:Pe,onEnteredPathChange:at,enteredPath:rt,onCompareSelect:tn,colorMode:u,assetBase:Kx().assetBase,...Kx().libraryBase===void 0?{}:{libraryBase:Kx().libraryBase},onOpenLink:e=>Kx().openLink(e),styleId:At??f,...m?{snapGrid:EE}:{},onCldEdges:ze,onViewPositionsChange:he,onViewLabelMovesChange:_e,layoutApiRef:vt,canvasCommandsRef:te,builtinKeys:!1,keyHints:$n,ignoreSavedPositions:be,externalHighlight:mt?Me.length>=2?{nodes:Me,edges:[]}:null:Be??(Fe!==null&&Se?.kind===`node`?{nodes:[Se.id,Fe],edges:[]}:null),...Nt===void 0?{}:{notation:Nt},...zt===void 0?{}:{layout:zt},...kt===void 0?{}:{drawings:kt},...mt?{mode:`edit`,tool:ct,pen:{...ut===``?{}:{color:ut},width:ft},edit:{...Ee===void 0?{}:{editLabelRequest:Ee},...ke===void 0?{}:{editThreatRequest:ke},onNoteMoved:(e,t)=>gt.dispatch({type:`set-note-offset`,target:e,offset:t,...on}),onToggleNote:(e,t)=>gt.dispatch({type:`set-note-open`,target:e,open:t,...on}),onAddThreat:cn,onRetitleThreat:dn,onSetThreatStatus:fn,onEditThreatText:mn,quickAdd:{label:(e,t)=>Dt===void 0?void 0:wle(Dt,e,rn,t),run:an},onNodesMoved:(e,t)=>{if(Nt===`plan`&&Dt!==void 0){let n=AS(Dt,Mt,e,t);n!==void 0&&gt.dispatch(n);return}gt.dispatch({type:`set-positions`,positions:e,...Mt===void 0?{}:{plane:Mt}})},onDropInto:(e,t,n)=>{if(Nt===`plan`&&Dt!==void 0){let r=$se(Dt,Mt,e,t,n);r!==void 0&&gt.dispatch(r)}},onMoveLane:(e,t,n)=>{let r=Vw(e,t,n,Mt);r!==null&&gt.dispatch(r)},onSetRole:(e,t,n)=>{if(Dt===void 0)return;let r=Zse(Dt,e,t,n);r!==void 0&&gt.dispatch(r)},onCreateAt:e=>bn(e),onImageFiles:(e,t)=>void Tn(e,t),onDropLibraryEntry:wn,onResize:(e,t,n,r)=>{if(Nt===`plan`&&Dt!==void 0){let n=Dt.nodes.find(t=>t.id===e);if(n!==void 0&&Un(n)){let n=jS(Dt,Mt,e,r.x,t);n!==void 0&&gt.dispatch(n);return}}gt.dispatch({type:`set-size`,nodeId:e,w:t,h:n}),gt.dispatch({type:`set-position`,nodeId:e,x:r.x,y:r.y,...Mt===void 0?{}:{plane:Mt}})},onConnect:(e,t,n)=>{let r=gt.session?.state.model,i=r===void 0?null:sue(r,e,t,n,Vt===null?void 0:{layer:Vt});if(i!==null){for(let e of i)gt.dispatch(e);return}gt.dispatch({type:`add-relation`,from:e,to:t,opts:{kind:Xw(Nt,r,e,t),...Vt===null?{}:{layer:Vt}}})},onDeleteSelection:e=>{let t=gt.peek()?.state.model,n=t===void 0?null:bE(t,e);n!==null&&(gt.dispatch(n),Jt(null))},onSetTableColumns:(e,t)=>gt.dispatch({type:`set-table-columns`,id:e,columns:t}),onRenameNode:(e,t)=>gt.dispatch({type:`rename-node`,id:e,name:t}),onSetNodeRich:(e,t)=>gt.dispatch({type:`set-node-rich`,id:e,runs:t}),onAddEdgeLabel:Ut,onEditEdgeLabel:Wt,onMoveEdgeLabel:Gt,onReconnect:(e,t,n,r)=>gt.dispatch({type:`update-relation`,id:e,patch:{from:t,to:n,...r===void 0?{}:{style:Ht(e,r.end,r.side)}}}),onSetEdgeSide:(e,t,n)=>gt.dispatch({type:`update-relation`,id:e,patch:{style:Ht(e,t,n)}}),onAddStroke:e=>{let t=gt.peek()?.state.drawings,n=gt.peek()?.state.model;t===void 0||n===void 0||gt.dispatch({type:`add-stroke`,stroke:{id:Dr(t,Yr(n,Mt)),...e},...Mt===void 0?{}:{plane:Mt}})},onDeleteStroke:e=>gt.dispatch({type:`delete-stroke`,id:e,...Mt===void 0?{}:{plane:Mt}})}}:{}}),mt&&Me.length>=2&&(0,D.jsxs)(`button`,{className:`chip group-action`,title:`Group the selection${Xn(`edit.group`)}`,onClick:()=>void nn(),children:[`⊞ Group `,Me.length]})]}),(0,D.jsxs)(rT,{side:`right`,collapsed:qe,onToggle:()=>Je(e=>!e),hasContent:!0,width:Ze,minWidth:jE,maxWidth:kE,onWidthChange:Qe,children:[mt&&Nt===`git-graph`&&(0,D.jsx)(ule,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),mt&&Nt===`plan`&&(0,D.jsx)(Yw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),today:Pt}),mt&&Nt===`second-order`&&(0,D.jsx)(hle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),mt&&Nt===`fishbone`&&(0,D.jsx)(yle,{model:Dt,selection:Se,...Mt!==void 0&&!It?{plane:Mt}:{},onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e}),onCreated:Oe}),Nt===`threat-model`&&(0,D.jsx)(qw,{model:Dt,...Mt===void 0?{}:{plane:Mt},onSelect:Jt}),mt&&(0,D.jsx)(Hw,{model:Dt,plane:Mt,selection:Se,onCommand:gt.dispatch,onSelect:e=>Jt({kind:`node`,id:e})}),(0,D.jsxs)(Mce,{controls:Eh(Nt).layout===void 0?{settings:Bt,onChange:mt?An:zn,defaultDirection:_t(Dt),algorithmLocked:Ft,...Eh(Nt).defaultAlgorithm===void 0?{}:{defaultAlgorithm:Eh(Nt).defaultAlgorithm}}:null,styleControl:mt?(0,D.jsxs)(`select`,{className:`chip-select`,"aria-label":`Diagram style`,title:`Diagram style (saved with the diagram)`,value:At??``,onChange:e=>gt.dispatch({type:`set-diagram-style`,style:e.target.value===``?null:e.target.value}),children:[(0,D.jsx)(`option`,{value:``,children:`(app default)`}),Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))]}):(0,D.jsx)(`select`,{className:`chip-select`,"aria-label":`Style`,title:At===void 0?`Visual style`:`Set by diagram`,value:At??(Ov(f)?f:`clean`),disabled:At!==void 0,onChange:e=>p(e.target.value),children:Ev.map(e=>(0,D.jsx)(`option`,{value:e.id,children:e.label},e.id))}),children:[mt&&(0,D.jsx)(OC,{editor:gt,activePlane:Mt,autoLayout:!Rt,onToggleAutoLayout:kn,getAutoPositions:()=>vt.current?.autoPositions()??{}}),!mt&&fe[Yr(Dt,Mt)]!==void 0&&(0,D.jsx)(`button`,{className:`chip`,title:`Drop the preview and go back to this diagram's own layout settings`,onClick:()=>pe(e=>{let t={...e};return delete t[Yr(Dt,Mt)],t}),children:`Reset layout`}),!mt&&Object.keys(Ot?.planes[Yr(Dt,Mt)]??{}).length>0&&(0,D.jsx)(`button`,{type:`button`,className:`chip${be?` active`:``}`,"aria-pressed":be,title:`${be?`Ignoring this diagram’s saved positions, so the layout algorithm arranges every node. Click to put them back.`:`This plane has saved positions, which override the layout algorithm. Click to arrange those nodes automatically instead (nothing is written).`}${Xn(`view.auto-arrange`)}`,onClick:()=>xe(e=>!e),children:`Auto-arrange`}),!mt&&(0,D.jsx)(`button`,{type:`button`,className:`chip${Rt?` active`:``}`,"aria-pressed":Rt,disabled:ve||rt.length>0,title:`${rt.length>0?`Freezing pins the whole plane, but a drilled view only has positions for what it shows — leave the drilled view first.`:Rt?`Positions are pinned. Click to let the layout algorithm arrange this plane again (your positions are kept).`:`Pin every box where it is so the layout algorithm stops moving them. Boxes added to the source later are still placed automatically until you move them.`}${Xn(`view.freeze`)}`,onClick:()=>void Rn(),children:`Freeze layout`})]}),(0,D.jsx)(Bw,{model:Dt,onCommand:gt.dispatch,mode:mt?`edit`:`view`,activeLayer:Vt,onActivateLayer:Xt,activePlane:Mt,onSelectPlane:e=>e===void 0?en():Yt(e),activeLayers:oe,onToggleLayer:Zt,onMergeLayers:Qt})]})]})}),S&&(0,D.jsx)(CE,{overrides:g,onChange:_,onClose:()=>{C(!1),ee.current?.focus()},mac:T})]})})}var hue=document.getElementById(`root`);hue&&(0,y.createRoot)(hue).render((0,D.jsx)(mue,{}));
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>diagc studio</title>
7
- <script type="module" crossorigin src="/assets/index-DL_lrezG.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-C0LPHkb1.js"></script>
8
8
  <link rel="stylesheet" crossorigin href="/assets/index-Csx5rLJC.css">
9
9
  </head>
10
10
  <body>
package/dist/cli.d.ts CHANGED
@@ -14,6 +14,10 @@ interface Args {
14
14
  imageUrl?: string;
15
15
  /** diff `--labels before,after`: names for the two sides in place of the refs */
16
16
  labels?: [string, string];
17
+ /** init `--type`: which starter to copy */
18
+ type?: string;
19
+ /** init `--agents`: write the coding-agent block */
20
+ agents: boolean;
17
21
  }
18
22
  /** Parse argv into command + flags. Unknown flags (anything `--…` that is not
19
23
  * recognized) are an error rather than being silently treated as a file path,
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@
19
19
  *
20
20
  * SPDX-License-Identifier: AGPL-3.0-only
21
21
  */
22
- import { existsSync } from 'node:fs';
22
+ import { existsSync, statSync } from 'node:fs';
23
23
  import path from 'node:path';
24
24
  import { fileURLToPath } from 'node:url';
25
25
  import fg from 'fast-glob';
@@ -31,15 +31,19 @@ import { ejectDiagram } from './eject.js';
31
31
  import { formatLintReport, lintFile } from './lint.js';
32
32
  import { runGuide } from './guide.js';
33
33
  import { cliVersion, findHome, homePaths } from './home.js';
34
+ import { diagramName, runInit } from './init.js';
34
35
  import { resolveInclude } from './includes.js';
35
36
  import { snapshotSession } from './snapshots.js';
36
37
  import { formatCompileEvent, startWatch } from './watch.js';
37
38
  import { galleryLink } from './publish/gallery.js';
38
39
  import { publishDiagrams } from './publish/publish.js';
39
40
  import { runStudio } from './studio.js';
40
- const USAGE = `Usage: diagc <compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
41
+ const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
41
42
 
42
43
  Commands:
44
+ init init [name] [--type <type>] [--agents]: set a repository up — a starter
45
+ diagram under .diagrams/src (compiled), the .gitignore lines, and with
46
+ --agents a pointer to the guide for coding agents (AGENTS.md / CLAUDE.md)
43
47
  compile Compile *.diagram.{ts,json} sources into overlay artifacts once
44
48
  lint Report suspicious diagrams (typos, duplicates, unused or undrawn parts); exit 1 on any
45
49
  watch Recompile — and live-recompile — a directory of sources
@@ -60,6 +64,8 @@ Options:
60
64
  --labels a,b diff: name the two sides (default: the refs)
61
65
  --image-url t diff: summary.md's image links as t, {path} standing for each PNG
62
66
  --update-includes Refetch remote includes and rewrite the snapshot lock
67
+ --type <type> init: the starter to copy (default basic; 'diagc guide' lists the types)
68
+ --agents init: write the coding-agent block into AGENTS.md / CLAUDE.md
63
69
  --help, -h Show this help and exit
64
70
  `;
65
71
  /** Parse argv into command + flags. Unknown flags (anything `--…` that is not
@@ -76,6 +82,8 @@ export function parseArgs(argv) {
76
82
  let link;
77
83
  let imageUrl;
78
84
  let labels;
85
+ let type;
86
+ let agents = false;
79
87
  let commandSeen = false;
80
88
  for (let i = 0; i < argv.length; i++) {
81
89
  const arg = argv[i];
@@ -96,6 +104,19 @@ export function parseArgs(argv) {
96
104
  json = true;
97
105
  continue;
98
106
  }
107
+ if (arg === '--type') {
108
+ // No fallback: a missing value would otherwise swallow the next flag as the type.
109
+ const value = argv[i + 1];
110
+ if (value === undefined || value.startsWith('--'))
111
+ throw new BadFlagValueError('--type', "needs a diagram type, e.g. --type c4 ('diagc guide' lists them)");
112
+ type = value;
113
+ i++;
114
+ continue;
115
+ }
116
+ if (arg === '--agents') {
117
+ agents = true;
118
+ continue;
119
+ }
99
120
  if (arg === '--image-url') {
100
121
  const value = argv[++i] ?? '';
101
122
  if (!value.includes('{path}'))
@@ -145,6 +166,8 @@ export function parseArgs(argv) {
145
166
  images,
146
167
  updateIncludes,
147
168
  json,
169
+ agents,
170
+ ...(type !== undefined ? { type } : {}),
148
171
  ...(link !== undefined ? { link } : {}),
149
172
  ...(imageUrl !== undefined ? { imageUrl } : {}),
150
173
  ...(labels !== undefined ? { labels } : {}),
@@ -173,6 +196,12 @@ export class BadFlagValueError extends Error {
173
196
  this.name = 'BadFlagValueError';
174
197
  }
175
198
  }
199
+ const SOURCES = '.diagrams/src/**/*.diagram.{ts,json}';
200
+ /** The one message a repository with no diagrams gets, on stderr: `lint --json`'s
201
+ * stdout stays an array and the exit codes hold, so CI without diagrams passes. */
202
+ function warnNoSources(dir = '.diagrams/src') {
203
+ console.error(`No diagrams under ${dir} — run 'diagc init' to create one.`);
204
+ }
176
205
  async function main() {
177
206
  let args;
178
207
  try {
@@ -197,7 +226,9 @@ async function main() {
197
226
  // own separate always-locked session below instead of sharing this one.
198
227
  const snap = snapshotSession(resolveInclude, '.diagrams', args.updateIncludes ? 'update' : 'locked');
199
228
  if (args.command === 'compile') {
200
- const files = args.files.length > 0 ? args.files : await fg('.diagrams/src/**/*.diagram.{ts,json}');
229
+ const files = args.files.length > 0 ? args.files : await fg(SOURCES);
230
+ if (args.files.length === 0 && files.length === 0)
231
+ warnNoSources();
201
232
  let failed = false;
202
233
  for (const file of files) {
203
234
  try {
@@ -222,7 +253,9 @@ async function main() {
222
253
  process.exit(failed ? 1 : 0);
223
254
  }
224
255
  else if (args.command === 'lint') {
225
- const files = args.files.length > 0 ? args.files : await fg('.diagrams/src/**/*.diagram.{ts,json}');
256
+ const files = args.files.length > 0 ? args.files : await fg(SOURCES);
257
+ if (args.files.length === 0 && files.length === 0)
258
+ warnNoSources();
226
259
  const reports = [];
227
260
  for (const file of files) {
228
261
  reports.push(...(await lintFile(file, { rootDir: '.diagrams/src', coreEntry: home.coreEntry, resolver: snap.resolver })));
@@ -242,6 +275,8 @@ async function main() {
242
275
  if (args.updateIncludes)
243
276
  console.error('ignoring --update-includes: watch always runs locked');
244
277
  const dir = args.files[0] ?? '.diagrams/src';
278
+ if (existsSync(dir) && statSync(dir).isDirectory() && (await fg('**/*.diagram.{ts,json}', { cwd: dir })).length === 0)
279
+ warnNoSources(dir);
245
280
  const watchSnap = snapshotSession(resolveInclude, '.diagrams', 'locked');
246
281
  startWatch(dir, args.out, {
247
282
  coreEntry: home.coreEntry,
@@ -271,6 +306,8 @@ async function main() {
271
306
  const artifactsDir = '.diagrams/.artifacts';
272
307
  // Compile first so artifacts reflect current sources (TS + include expansion).
273
308
  const sources = await fg('**/*.diagram.{ts,json}', { cwd: srcDir, absolute: true });
309
+ if (sources.length === 0)
310
+ warnNoSources(srcDir);
274
311
  for (const f of sources) {
275
312
  try {
276
313
  await compileFile(f, artifactsDir, { rootDir: srcDir, coreEntry: home.coreEntry, resolver: snap.resolver });
@@ -328,7 +365,7 @@ async function main() {
328
365
  // eject.ts) — same reasoning as watch above.
329
366
  if (args.updateIncludes)
330
367
  console.error('ignoring --update-includes: eject always runs locked');
331
- const name = args.files[0]?.replace(/^\.diagrams\/src\//, '').replace(/\.diagram\.(ts|json)$/, '');
368
+ const name = args.files[0] === undefined ? undefined : diagramName(args.files[0]);
332
369
  if (name === undefined || name === '') {
333
370
  console.error('diagc: eject needs a diagram name.');
334
371
  console.error(USAGE);
@@ -358,6 +395,23 @@ async function main() {
358
395
  });
359
396
  return;
360
397
  }
398
+ else if (args.command === 'init') {
399
+ if (args.files.length > 1) {
400
+ console.error(`diagc: init takes one name, got ${args.files.length} — e.g. diagc init shop --type c4`);
401
+ process.exit(1);
402
+ }
403
+ process.exitCode = await runInit({
404
+ cwd: process.cwd(),
405
+ ...(args.files[0] !== undefined ? { name: args.files[0] } : {}),
406
+ ...(args.type !== undefined ? { type: args.type } : {}),
407
+ agents: args.agents,
408
+ startersDir: home.startersDir,
409
+ version: cliVersion(home.root),
410
+ coreEntry: home.coreEntry,
411
+ resolver: snap.resolver,
412
+ });
413
+ return;
414
+ }
361
415
  else {
362
416
  console.error(`diagc: Unknown command '${args.command}'.`);
363
417
  console.error(USAGE);
package/dist/compile.d.ts CHANGED
@@ -1,4 +1,30 @@
1
1
  import { type DiagramModel, type IncludeResolver } from '@diagc/core';
2
+ /**
3
+ * A source that threw while running — a misspelled method, a builder call that
4
+ * refused — placed at the first stack frame inside that file. V8 writes the file
5
+ * into every frame and jiti keeps the author's lines, so no source map is needed;
6
+ * taking the first frame *in the user's file* also puts a refusal the builder
7
+ * throws at the call that caused it. A transform error has no such frame: then
8
+ * there is no position and the message is left as it was.
9
+ */
10
+ export declare class LoadError extends Error {
11
+ readonly file: string;
12
+ readonly reason: string;
13
+ readonly line: number | undefined;
14
+ readonly column: number | undefined;
15
+ constructor(file: string, reason: string, position?: {
16
+ line: number;
17
+ column: number;
18
+ });
19
+ }
20
+ /** The line and column of the first `at` frame inside `file`. Matched on the
21
+ * basename after a path separator: a frame spells the path as it was imported,
22
+ * which a symlinked temp dir would not equal; the message line is skipped because
23
+ * a transform error quotes `file:line:col` there and that is not a frame. */
24
+ export declare function positionIn(stack: string | undefined, file: string): {
25
+ line: number;
26
+ column: number;
27
+ } | undefined;
2
28
  /**
3
29
  * Execute a `.diagram.ts` through jiti (core pinned to `coreEntry`) and return
4
30
  * its model — shape-guarded but not validated; callers own validation.
package/dist/compile.js CHANGED
@@ -2,7 +2,7 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import { createRequire } from 'node:module';
3
3
  import path from 'node:path';
4
4
  import { createJiti } from 'jiti';
5
- import { composeIncludes, DiagramValidationError, diagramWarnings, validate, } from '@diagc/core';
5
+ import { composeIncludes, DiagramValidationError, diagramWarnings, errMessage, validate, } from '@diagc/core';
6
6
  import { resolveInclude } from './includes.js';
7
7
  import { snapshotSession } from './snapshots.js';
8
8
  /**
@@ -18,6 +18,44 @@ function assertDiagramShape(model, file) {
18
18
  throw new Error(`${file}: no default export or not a diagram model`);
19
19
  }
20
20
  }
21
+ /**
22
+ * A source that threw while running — a misspelled method, a builder call that
23
+ * refused — placed at the first stack frame inside that file. V8 writes the file
24
+ * into every frame and jiti keeps the author's lines, so no source map is needed;
25
+ * taking the first frame *in the user's file* also puts a refusal the builder
26
+ * throws at the call that caused it. A transform error has no such frame: then
27
+ * there is no position and the message is left as it was.
28
+ */
29
+ export class LoadError extends Error {
30
+ file;
31
+ reason;
32
+ line;
33
+ column;
34
+ constructor(file, reason, position) {
35
+ super(position !== undefined ? `${file}:${position.line}:${position.column}: ${reason}` : reason);
36
+ this.file = file;
37
+ this.reason = reason;
38
+ this.name = 'LoadError';
39
+ this.line = position?.line;
40
+ this.column = position?.column;
41
+ }
42
+ }
43
+ /** The line and column of the first `at` frame inside `file`. Matched on the
44
+ * basename after a path separator: a frame spells the path as it was imported,
45
+ * which a symlinked temp dir would not equal; the message line is skipped because
46
+ * a transform error quotes `file:line:col` there and that is not a frame. */
47
+ export function positionIn(stack, file) {
48
+ const base = path.basename(file).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
49
+ const frame = new RegExp(`[\\\\/]${base}:(\\d+):(\\d+)`);
50
+ for (const line of (stack ?? '').split('\n')) {
51
+ if (!line.trimStart().startsWith('at '))
52
+ continue;
53
+ const m = frame.exec(line);
54
+ if (m !== null)
55
+ return { line: Number(m[1]), column: Number(m[2]) };
56
+ }
57
+ return undefined;
58
+ }
21
59
  /**
22
60
  * Execute a `.diagram.ts` through jiti (core pinned to `coreEntry`) and return
23
61
  * its model — shape-guarded but not validated; callers own validation.
@@ -33,7 +71,17 @@ export async function executeDiagramTs(file, coreEntry) {
33
71
  moduleCache: false,
34
72
  alias: { '@diagc/core': resolvedCoreEntry },
35
73
  });
36
- const def = await jiti.import(path.resolve(file), { default: true });
74
+ let def;
75
+ try {
76
+ def = await jiti.import(path.resolve(file), { default: true });
77
+ }
78
+ catch (e) {
79
+ // A validation error thrown inside the module keeps its shape: lint reads its
80
+ // `issues` by name. Everything else is the source failing to run.
81
+ if (e instanceof Error && e.name === 'DiagramValidationError')
82
+ throw e;
83
+ throw new LoadError(file, errMessage(e), positionIn(e instanceof Error ? e.stack : undefined, file));
84
+ }
37
85
  const hasToJSON = typeof def?.toJSON === 'function';
38
86
  const model = (hasToJSON ? def.toJSON() : def);
39
87
  assertDiagramShape(model, file);
package/dist/init.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { type IncludeResolver } from '@diagc/core';
2
+ /** What `diagc init` works with. `cwd` is the directory being set up — the
3
+ * current directory in the CLI, a temp dir in tests — and every path is built
4
+ * from it, so nothing here reads `process.cwd()`. */
5
+ export interface InitOptions {
6
+ cwd: string;
7
+ /** the diagram's name, folders allowed (`team/app`); `example` when omitted */
8
+ name?: string;
9
+ /** the starter to copy; `basic` when omitted */
10
+ type?: string;
11
+ /** write the coding-agent block into AGENTS.md / CLAUDE.md */
12
+ agents: boolean;
13
+ startersDir: string;
14
+ /** what the `npm i -D @diagc/core@…` hint names */
15
+ version: string;
16
+ coreEntry: string;
17
+ resolver?: IncludeResolver;
18
+ }
19
+ export interface InitIo {
20
+ out(text: string): void;
21
+ err(text: string): void;
22
+ }
23
+ export declare const DEFAULT_NAME = "example";
24
+ export declare const DEFAULT_TYPE = "basic";
25
+ /** build output a repository should not commit; `init` adds what is missing */
26
+ export declare const IGNORED: readonly string[];
27
+ export declare const AGENTS_BEGIN = "<!-- diagc:begin -->";
28
+ export declare const AGENTS_END = "<!-- diagc:end -->";
29
+ /** What `--agents` writes. Commands, not DSL: the guide is where the DSL lives, so
30
+ * this block does not go stale when the DSL grows. The markers let a later run
31
+ * replace it in place. */
32
+ export declare const AGENTS_BLOCK = "<!-- diagc:begin -->\n## Diagrams\n\nDiagrams live in `.diagrams/src/*.diagram.ts` and are built with `diagc`.\n\n- Run `diagc guide` before writing or changing one; `diagc guide <type>` covers one diagram type.\n- Run `diagc lint --json` until it reports nothing.\n- Run `diagc publish <name>` and look at `.diagrams/static/<name>.png` to check the picture.\n<!-- diagc:end -->\n";
33
+ /** `existing` with the block added at the end, or — when both markers are there —
34
+ * with the earlier block replaced where it stands, so a second run never
35
+ * duplicates it and a run after an upgrade refreshes it. */
36
+ export declare function withAgentsBlock(existing: string): {
37
+ text: string;
38
+ replaced: boolean;
39
+ };
40
+ /** A one-line failure on stderr with exit 1. A refusal leaves the tree untouched;
41
+ * a compile failure comes after the writes, so the starter and `.gitignore` stay. */
42
+ export declare class InitError extends Error {
43
+ constructor(message: string);
44
+ }
45
+ /** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
46
+ * applies, so a name copied from a listing is not an "unsafe name". */
47
+ export declare function diagramName(arg: string): string;
48
+ /** Which of `wanted` a `.gitignore` text still lacks. A line counts after trimming,
49
+ * with or without a leading or trailing slash: `/.diagrams/html` already ignores
50
+ * what `.diagrams/html/` would. */
51
+ export declare function missingIgnores(existing: string, wanted?: readonly string[]): string[];
52
+ /** `diagc init`: run the steps in order and return the exit code. A refusal is one
53
+ * line on stderr; anything else is a bug and is left to throw. */
54
+ export declare function runInit(opts: InitOptions, io?: InitIo): Promise<number>;
package/dist/init.js ADDED
@@ -0,0 +1,197 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import fg from 'fast-glob';
5
+ import { errMessage } from '@diagc/core';
6
+ import { isSafeName } from './api/handlers.js';
7
+ import { compileFile } from './compile.js';
8
+ import { readStarter, UnknownStarterError } from './starters.js';
9
+ export const DEFAULT_NAME = 'example';
10
+ export const DEFAULT_TYPE = 'basic';
11
+ const SRC_DIR = '.diagrams/src';
12
+ const ARTIFACTS_DIR = '.diagrams/.artifacts';
13
+ /** build output a repository should not commit; `init` adds what is missing */
14
+ export const IGNORED = ['.diagrams/.artifacts/', '.diagrams/html/', '.diagrams/diff/'];
15
+ export const AGENTS_BEGIN = '<!-- diagc:begin -->';
16
+ export const AGENTS_END = '<!-- diagc:end -->';
17
+ /** What `--agents` writes. Commands, not DSL: the guide is where the DSL lives, so
18
+ * this block does not go stale when the DSL grows. The markers let a later run
19
+ * replace it in place. */
20
+ export const AGENTS_BLOCK = `${AGENTS_BEGIN}
21
+ ## Diagrams
22
+
23
+ Diagrams live in \`.diagrams/src/*.diagram.ts\` and are built with \`diagc\`.
24
+
25
+ - Run \`diagc guide\` before writing or changing one; \`diagc guide <type>\` covers one diagram type.
26
+ - Run \`diagc lint --json\` until it reports nothing.
27
+ - Run \`diagc publish <name>\` and look at \`.diagrams/static/<name>.png\` to check the picture.
28
+ ${AGENTS_END}
29
+ `;
30
+ /** `existing` with the block added at the end, or — when both markers are there —
31
+ * with the earlier block replaced where it stands, so a second run never
32
+ * duplicates it and a run after an upgrade refreshes it. */
33
+ export function withAgentsBlock(existing) {
34
+ const begin = existing.indexOf(AGENTS_BEGIN);
35
+ const end = begin === -1 ? -1 : existing.indexOf(AGENTS_END, begin);
36
+ if (begin !== -1 && end !== -1) {
37
+ let after = end + AGENTS_END.length;
38
+ // The block carries its own closing newline; take the old one with the old block.
39
+ if (existing.startsWith('\n', after))
40
+ after += 1;
41
+ return { text: existing.slice(0, begin) + AGENTS_BLOCK + existing.slice(after), replaced: true };
42
+ }
43
+ if (existing === '')
44
+ return { text: AGENTS_BLOCK, replaced: false };
45
+ const sep = existing.endsWith('\n\n') ? '' : existing.endsWith('\n') ? '\n' : '\n\n';
46
+ return { text: `${existing}${sep}${AGENTS_BLOCK}`, replaced: false };
47
+ }
48
+ const COL = 38;
49
+ const done = (left, right) => `✓ ${left.padEnd(COL)}${right}`;
50
+ const skipped = (left, right) => `· ${left.padEnd(COL)}${right}`;
51
+ /** A one-line failure on stderr with exit 1. A refusal leaves the tree untouched;
52
+ * a compile failure comes after the writes, so the starter and `.gitignore` stay. */
53
+ export class InitError extends Error {
54
+ constructor(message) {
55
+ super(message);
56
+ this.name = 'InitError';
57
+ }
58
+ }
59
+ /** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
60
+ * applies, so a name copied from a listing is not an "unsafe name". */
61
+ export function diagramName(arg) {
62
+ return arg.replace(/^\.diagrams\/src\//, '').replace(/\.diagram\.(ts|json)$/, '');
63
+ }
64
+ /** Which of `wanted` a `.gitignore` text still lacks. A line counts after trimming,
65
+ * with or without a leading or trailing slash: `/.diagrams/html` already ignores
66
+ * what `.diagrams/html/` would. */
67
+ export function missingIgnores(existing, wanted = IGNORED) {
68
+ const norm = (l) => l.trim().replace(/^\//, '').replace(/\/$/, '');
69
+ const have = new Set(existing.split(/\r?\n/).map(norm));
70
+ return wanted.filter((w) => !have.has(norm(w)));
71
+ }
72
+ /** Step 1: the starter. Returns the file it wrote, or nothing when the step was
73
+ * skipped. Every check comes before the write, so a refusal leaves no file. */
74
+ async function starterStep(opts, io) {
75
+ const srcDir = path.join(opts.cwd, SRC_DIR);
76
+ if (opts.name === undefined && opts.type === undefined) {
77
+ // A plain `diagc init` in a repository that already has diagrams is here for
78
+ // the other steps (`--agents` after an upgrade): do not add an `example`.
79
+ const existing = await fg('**/*.diagram.{ts,json}', { cwd: srcDir });
80
+ if (existing.length > 0) {
81
+ io.out(skipped(SRC_DIR, `already has ${existing.length} diagram(s) — starter skipped`));
82
+ return undefined;
83
+ }
84
+ }
85
+ const name = diagramName(opts.name ?? DEFAULT_NAME);
86
+ if (!isSafeName(name) || name.endsWith('/')) {
87
+ throw new InitError(`'${name}' is not a diagram name — use lowercase letters, digits and '-', with '/' for a folder (shop, team/app).`);
88
+ }
89
+ // The type is checked before the name clash: a wrong `--type` is the more useful
90
+ // thing to hear, and it too is checked before anything is written.
91
+ const type = opts.type ?? DEFAULT_TYPE;
92
+ let source;
93
+ try {
94
+ source = readStarter(opts.startersDir, type);
95
+ }
96
+ catch (e) {
97
+ if (!(e instanceof UnknownStarterError))
98
+ throw e;
99
+ // No types at all is not a wrong `--type`: the install lost its files.
100
+ throw new InitError(e.types.length === 0
101
+ ? `starter files missing from this install (${opts.startersDir}) — reinstall diagc.`
102
+ : `${e.message} — e.g. diagc init ${name} --type ${e.types[0]}`);
103
+ }
104
+ for (const ext of ['ts', 'json']) {
105
+ if (existsSync(path.join(srcDir, `${name}.diagram.${ext}`))) {
106
+ throw new InitError(`${SRC_DIR}/${name}.diagram.${ext} already exists — pick another name, or run 'diagc init' with no name and no --type to leave it alone.`);
107
+ }
108
+ }
109
+ const file = path.join(srcDir, `${name}.diagram.ts`);
110
+ await mkdir(path.dirname(file), { recursive: true });
111
+ await writeFile(file, source);
112
+ io.out(done(`${SRC_DIR}/${name}.diagram.ts`, `(${type} starter)`));
113
+ return file;
114
+ }
115
+ /** Step 2: `.gitignore`. Appends the missing lines; creates the file if there is none. */
116
+ async function gitignoreStep(cwd, io) {
117
+ const file = path.join(cwd, '.gitignore');
118
+ const existing = existsSync(file) ? await readFile(file, 'utf8') : '';
119
+ const missing = missingIgnores(existing);
120
+ if (missing.length === 0) {
121
+ io.out(skipped('.gitignore', 'already ignores the build output'));
122
+ return;
123
+ }
124
+ // A file whose last line has no newline gets one first, or the first new entry
125
+ // would be glued onto it.
126
+ const sep = existing === '' || existing.endsWith('\n') ? '' : '\n';
127
+ await writeFile(file, `${existing}${sep}${missing.join('\n')}\n`);
128
+ io.out(done('.gitignore', `(+ ${missing.join(', ')})`));
129
+ }
130
+ /** Step 3: the coding-agent block, only with `--agents`. Into whichever of
131
+ * AGENTS.md and CLAUDE.md exist; into a new AGENTS.md when neither does. */
132
+ async function agentsStep(cwd, io) {
133
+ const targets = ['AGENTS.md', 'CLAUDE.md'].filter((f) => existsSync(path.join(cwd, f)));
134
+ if (targets.length === 0)
135
+ targets.push('AGENTS.md');
136
+ for (const name of targets) {
137
+ const file = path.join(cwd, name);
138
+ const existing = existsSync(file) ? await readFile(file, 'utf8') : '';
139
+ const { text, replaced } = withAgentsBlock(existing);
140
+ await writeFile(file, text);
141
+ io.out(done(name, replaced ? '(diagc block refreshed)' : '(diagc block added)'));
142
+ }
143
+ }
144
+ /** Step 4: compile what was written, so the user starts from a diagram that is
145
+ * known to build and sees where the artifact went. */
146
+ async function compileStep(file, opts, io) {
147
+ let artifact;
148
+ try {
149
+ artifact = await compileFile(file, path.join(opts.cwd, ARTIFACTS_DIR), {
150
+ rootDir: path.join(opts.cwd, SRC_DIR),
151
+ coreEntry: opts.coreEntry,
152
+ ...(opts.resolver !== undefined ? { resolver: opts.resolver } : {}),
153
+ });
154
+ }
155
+ catch (e) {
156
+ throw new InitError(`compile failed — ${errMessage(e)}`);
157
+ }
158
+ io.out(done('compiled', `-> ${path.relative(opts.cwd, artifact).split(path.sep).join('/')}`));
159
+ }
160
+ /** Step 5: what to do now. The `--agents` line goes when `--agents` was given; the
161
+ * install hint only where there is a `package.json` to install into. */
162
+ function nextSteps(opts) {
163
+ const lines = [
164
+ ['diagc studio', 'look at it'],
165
+ ['diagc guide', 'how to write diagrams (for you or your agent)'],
166
+ ];
167
+ if (!opts.agents)
168
+ lines.push(['diagc init --agents', 'point coding agents at the guide (AGENTS.md)']);
169
+ if (existsSync(path.join(opts.cwd, 'package.json')))
170
+ lines.push([`npm i -D @diagc/core@${opts.version}`, 'editor types for .diagram.ts']);
171
+ return `\nNext:\n${lines.map(([cmd, what]) => ` ${cmd.padEnd(COL)}${what}`).join('\n')}`;
172
+ }
173
+ const stdio = {
174
+ out: (text) => console.log(text),
175
+ err: (text) => console.error(text),
176
+ };
177
+ /** `diagc init`: run the steps in order and return the exit code. A refusal is one
178
+ * line on stderr; anything else is a bug and is left to throw. */
179
+ export async function runInit(opts, io = stdio) {
180
+ try {
181
+ const written = await starterStep(opts, io);
182
+ await gitignoreStep(opts.cwd, io);
183
+ if (opts.agents)
184
+ await agentsStep(opts.cwd, io);
185
+ if (written !== undefined)
186
+ await compileStep(written, opts, io);
187
+ io.out(nextSteps(opts));
188
+ return 0;
189
+ }
190
+ catch (e) {
191
+ if (e instanceof InitError) {
192
+ io.err(`diagc: ${e.message}`);
193
+ return 1;
194
+ }
195
+ throw e;
196
+ }
197
+ }
package/dist/lint.d.ts CHANGED
@@ -7,6 +7,9 @@ export interface LintReport {
7
7
  code: string;
8
8
  message: string;
9
9
  ref?: string;
10
+ /** where a `load` finding happened in the source, when the stack placed it */
11
+ line?: number;
12
+ column?: number;
10
13
  }
11
14
  /** Every finding for one source: its validation errors when it does not load,
12
15
  * otherwise its warnings (core's lint included). */
package/dist/lint.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { diagramWarnings, errMessage } from '@diagc/core';
2
- import { loadModel } from './compile.js';
2
+ import { LoadError, loadModel } from './compile.js';
3
3
  const report = (file, severity, i) => ({
4
4
  file,
5
5
  severity,
@@ -19,9 +19,21 @@ export async function lintFile(file, opts) {
19
19
  if (e instanceof Error && e.name === 'DiagramValidationError' && Array.isArray(e.issues)) {
20
20
  return e.issues.map((i) => report(file, 'error', i));
21
21
  }
22
+ if (e instanceof LoadError) {
23
+ return [
24
+ {
25
+ file,
26
+ severity: 'error',
27
+ code: 'load',
28
+ message: e.reason,
29
+ ...(e.line !== undefined && e.column !== undefined ? { line: e.line, column: e.column } : {}),
30
+ },
31
+ ];
32
+ }
22
33
  return [report(file, 'error', { code: 'load', message: errMessage(e) })];
23
34
  }
24
35
  }
25
36
  export function formatLintReport(r) {
26
- return `${r.file}: ${r.severity} ${r.code}: ${r.message}`;
37
+ const where = r.line !== undefined && r.column !== undefined ? `${r.file}:${r.line}:${r.column}` : r.file;
38
+ return `${where}: ${r.severity} ${r.code}: ${r.message}`;
27
39
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagc/cli",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Author software-architecture diagrams as code, compile them to a validated model, edit them in a local studio, and publish pages and images.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Bogdan Frankovskyi",
@@ -44,7 +44,7 @@
44
44
  "fast-glob": "^3.3.0",
45
45
  "jiti": "^2.0.0",
46
46
  "playwright-core": "^1.62.0",
47
- "@diagc/core": "0.11.0"
47
+ "@diagc/core": "0.12.0"
48
48
  },
49
49
  "publishConfig": {
50
50
  "access": "public"