@likec4/mcp 1.59.3 → 1.60.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 +1 -1
- package/dist/app/render-view-client.css +1 -1
- package/dist/app/render-view-client.js +506 -338
- package/dist/chunks/libs/@chevrotain/gast.mjs +27 -0
- package/dist/chunks/libs/@chevrotain/regexp-to-ast.mjs +81 -0
- package/dist/chunks/libs/@logtape/logtape.mjs +6 -0
- package/dist/chunks/libs/@lume/kiwi.mjs +1 -0
- package/dist/chunks/libs/@radix-ui/colors.mjs +1 -0
- package/dist/chunks/libs/@ts-graphviz/ast.mjs +3 -0
- package/dist/chunks/libs/@ts-graphviz/core.mjs +1 -0
- package/dist/chunks/libs/@ungap/structured-clone.mjs +3 -0
- package/dist/chunks/libs/character-entities.mjs +2 -0
- package/dist/chunks/libs/chevrotain-allstar.mjs +2 -0
- package/dist/chunks/libs/chevrotain.mjs +110 -0
- package/dist/chunks/libs/chroma-js.mjs +15 -0
- package/dist/chunks/libs/eventemitter3.mjs +1 -0
- package/dist/chunks/libs/graphology-dag.mjs +1 -0
- package/dist/chunks/libs/graphology.mjs +1 -0
- package/dist/chunks/libs/hast-util-sanitize.mjs +1 -0
- package/dist/chunks/libs/hast-util-to-html.mjs +9 -0
- package/dist/chunks/libs/hastscript.mjs +1 -0
- package/dist/chunks/libs/immer.mjs +1 -0
- package/dist/chunks/libs/json5.mjs +14 -0
- package/dist/chunks/libs/khroma.mjs +1 -0
- package/dist/chunks/libs/langium.mjs +17 -0
- package/dist/chunks/libs/markdown-table.mjs +2 -0
- package/dist/chunks/libs/mdast-util-find-and-replace.mjs +1 -0
- package/dist/chunks/libs/mdast-util-from-markdown.mjs +9 -0
- package/dist/chunks/libs/mdast-util-gfm.mjs +15 -0
- package/dist/chunks/libs/mdast-util-to-hast.mjs +11 -0
- package/dist/chunks/libs/merge-error-cause.mjs +2 -0
- package/dist/chunks/libs/micromark-extension-gfm.mjs +5 -0
- package/dist/chunks/libs/mnemonist.mjs +1 -0
- package/dist/chunks/libs/nano-spawn.mjs +3 -0
- package/dist/chunks/libs/ohash.mjs +1 -0
- package/dist/chunks/libs/p-limit.mjs +1 -0
- package/dist/chunks/libs/p-queue.mjs +1 -0
- package/dist/chunks/libs/parse-entities.mjs +1 -0
- package/dist/chunks/libs/pathe.mjs +1 -0
- package/dist/chunks/libs/pretty-ms.mjs +1 -0
- package/dist/chunks/libs/refractor.mjs +5 -0
- package/dist/chunks/libs/rehype-prism-plus.mjs +4 -0
- package/dist/chunks/libs/remark-github-blockquote-alert.mjs +3 -0
- package/dist/chunks/libs/remark-rehype.mjs +1 -0
- package/dist/chunks/libs/remeda.mjs +1 -0
- package/dist/chunks/libs/ufo.mjs +1 -0
- package/dist/chunks/libs/unified.mjs +1 -0
- package/dist/chunks/libs/unstorage.mjs +1 -0
- package/dist/chunks/libs/which.mjs +1 -0
- package/dist/chunks/rolldown-runtime.mjs +1 -0
- package/dist/chunks/src.mjs +321 -1103
- package/dist/cli.mjs +5 -1
- package/dist/index.mjs +1 -1
- package/package.json +64 -60
package/dist/chunks/src.mjs
CHANGED
|
@@ -1,11 +1,151 @@
|
|
|
1
|
-
import{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import{i as e,r as t,s as r,t as i}from"./rolldown-runtime.mjs";import{t as a}from"./libs/@radix-ui/colors.mjs";import{$ as s,A as c,B as l,C as u,D as p,E as m,F as h,G as g,H as _,I as v,J as y,K as b,L as x,M as S,N as ee,O as te,P as ne,Q as re,R as C,S as ie,T as ae,U as w,V as oe,W as T,X as se,Y as ce,Z as le,_ as ue,_t as de,a as E,at as fe,b as pe,bt as me,c as he,ct as D,d as ge,dt as k,et as _e,f as ve,ft as ye,g as A,gt as be,h as xe,ht as Se,i as Ce,it as we,j,k as Te,l as Ee,lt as M,m as De,mt as Oe,n as ke,nt as Ae,o as je,ot as Me,p as Ne,pt as N,q as Pe,r as Fe,rt as P,s as Ie,st as Le,t as Re,tt as ze,u as Be,ut as Ve,v as He,vt as Ue,w as We,x as F,y as Ge,yt as Ke,z as qe}from"./libs/remeda.mjs";import{t as Je}from"./libs/chroma-js.mjs";import{a as Ye,i as Xe,n as Ze,o as Qe,r as $e,s as et,t as I}from"./libs/mnemonist.mjs";import{n as tt,t as nt}from"./libs/graphology-dag.mjs";import{t as rt}from"./libs/ohash.mjs";import{t as it}from"./libs/hast-util-to-html.mjs";import{c as at,t as ot}from"./libs/mdast-util-from-markdown.mjs";import{n as st,t as ct}from"./libs/mdast-util-gfm.mjs";import{t as lt}from"./libs/rehype-prism-plus.mjs";import{n as ut,t as dt}from"./libs/hast-util-sanitize.mjs";import{t as ft}from"./libs/micromark-extension-gfm.mjs";import{t as pt}from"./libs/remark-github-blockquote-alert.mjs";import{t as mt}from"./libs/remark-rehype.mjs";import{t as ht}from"./libs/unified.mjs";import{n as gt,t as _t}from"./libs/merge-error-cause.mjs";import{n as vt,t as yt}from"./libs/immer.mjs";import{a as bt,i as xt,n as St,o as Ct,r as wt,t as Tt}from"./libs/@logtape/logtape.mjs";import{a as Et,i as Dt,n as Ot,r as kt,t as At}from"./libs/@lume/kiwi.mjs";import{t as jt}from"./libs/@ts-graphviz/core.mjs";import{n as Mt,r as Nt,t as Pt}from"./libs/@ts-graphviz/ast.mjs";import{n as Ft,r as It,t as Lt}from"./libs/khroma.mjs";import{t as Rt}from"./libs/graphology.mjs";import{t as zt}from"./libs/p-limit.mjs";import{t as Bt}from"./libs/p-queue.mjs";import{n as Vt,t as Ht}from"./libs/nano-spawn.mjs";import{t as Ut}from"./libs/which.mjs";import{$ as Wt,A as Gt,B as L,C as Kt,D as qt,E as Jt,F as Yt,G as Xt,H as Zt,I as Qt,J as $t,K as en,L as tn,M as nn,N as rn,O as an,P as on,Q as sn,R as cn,S as ln,T as un,U as dn,V as fn,W as pn,X as mn,Y as hn,Z as gn,_ as _n,a as vn,at as yn,b as bn,c as xn,d as Sn,et as Cn,f as wn,g as Tn,h as En,i as Dn,it as On,j as kn,k as An,l as jn,m as Mn,n as Nn,nt as Pn,o as Fn,p as In,q as Ln,r as Rn,rt as zn,s as Bn,t as Vn,tt as Hn,u as Un,v as Wn,w as Gn,x as Kn,y as qn,z as R}from"./libs/langium.mjs";import{t as Jn}from"./libs/json5.mjs";import{t as Yn}from"./libs/pretty-ms.mjs";import{a as Xn,c as Zn,i as Qn,l as $n,n as er,o as tr,r as nr,s as rr,t as ir,u as ar}from"./libs/ufo.mjs";import{n as or,t as sr}from"./libs/pathe.mjs";import{n as cr,t as lr}from"./libs/unstorage.mjs";import{randomUUID as ur}from"node:crypto";import{basename as dr,dirname as fr,relative as pr,resolve as mr,sep as hr}from"node:path";import{cwd as gr}from"node:process";import{fileURLToPath as _r}from"node:url";import{Graphviz as vr}from"@hpcc-js/wasm-graphviz";import*as yr from"node:fs/promises";import{unlink as br,writeFile as xr}from"node:fs/promises";import{existsSync as Sr,mkdirSync as Cr,readFileSync as wr,statSync as Tr}from"node:fs";import{CancellationToken as Er,DocumentHighlight as Dr,DocumentHighlightKind as Or}from"vscode-languageserver";import{URI as kr}from"vscode-uri";import{CodeAction as Ar,CodeActionKind as jr,CodeActionTriggerKind as Mr,DiagnosticSeverity as Nr,Position as Pr,TextEdit as Fr}from"vscode-languageserver-protocol";import{CompletionItemKind as Ir,DiagnosticSeverity as Lr,InsertTextFormat as Rr,Position as zr,Range as Br,SemanticTokenModifiers as Vr,SemanticTokenTypes as Hr,SymbolKind as Ur,TextEdit as Wr}from"vscode-languageserver-types";import{isColorSupported as Gr,isDevelopment as Kr}from"std-env";import*as z from"zod/v4";import B,{z as qr}from"zod/v4";import{bundleRequire as Jr}from"bundle-require";import{formatMessagesSync as Yr}from"esbuild";import{fdir as Xr}from"fdir";import Zr from"picomatch";import Qr from"chokidar";import V,*as $r from"zod";import{NotificationType as ei,NotificationType0 as ti,RequestType as ni,RequestType0 as ri}from"vscode-jsonrpc";import ii from"tinyrainbow";import{StdioServerTransport as ai}from"@modelcontextprotocol/sdk/server/stdio.js";import{McpServer as oi,ResourceTemplate as si}from"@modelcontextprotocol/sdk/server/mcp.js";import{completable as ci}from"@modelcontextprotocol/sdk/server/completable.js";import*as li from"zod/v3";import{RESOURCE_MIME_TYPE as ui,registerAppResource as di,registerAppTool as fi}from"@modelcontextprotocol/ext-apps/server";import{MemoryEventStore as pi,StreamableHTTPTransport as mi}from"@hono/mcp";import{serve as hi}from"@hono/node-server";import{Hono as gi}from"hono";import{cors as _i}from"hono/cors";const vi={fill:`#3b82f6`,stroke:`#2563eb`,hiContrast:`#eff6ff`,loContrast:`#bfdbfe`},yi={fill:`#0284c7`,stroke:`#0369a1`,hiContrast:`#f0f9ff`,loContrast:`#B6ECF7`},bi={fill:`#64748b`,stroke:`#475569`,hiContrast:`#f8fafc`,loContrast:`#cbd5e1`},xi={primary:vi,blue:vi,secondary:yi,sky:yi,muted:bi,slate:bi,gray:{fill:`#737373`,stroke:`#525252`,hiContrast:`#fafafa`,loContrast:`#d4d4d4`},red:{fill:`#AC4D39`,stroke:`#853A2D`,hiContrast:`#FBD3CB`,loContrast:`#f5b2a3`},green:{fill:`#428a4f`,stroke:`#2d5d39`,hiContrast:`#f8fafc`,loContrast:`#c2f0c2`},amber:{fill:`#A35829`,stroke:`#7E451D`,hiContrast:`#FFE0C2`,loContrast:`#f9b27c`},indigo:{fill:`#6366f1`,stroke:`#4f46e5`,hiContrast:`#eef2ff`,loContrast:`#c7d2fe`}},Si={line:`#8D8D8D`,labelBg:`#18191B`,label:`#C9C9C9`},Ci={line:`#64748b`,labelBg:`#0f172a`,label:`#cbd5e1`},wi={line:`#3b82f6`,labelBg:`#172554`,label:`#eff5fd`},Ti={line:`#0ea5e9`,labelBg:`#082f49`,label:`#d4f2ff`},Ei={amber:{line:`#b45309`,labelBg:`#78350f`,label:`#FFE0C2`},blue:wi,gray:Si,green:{line:`#15803d`,labelBg:`#052e16`,label:`#bbfcd3`},indigo:{line:`#6366f1`,labelBg:`#1e1b4b`,label:`#cbd0fd`},muted:Ci,primary:wi,red:{line:`#AC4D39`,labelBg:`#b91c1c`,label:`#fcd9d2`},secondary:Ti,sky:Ti,slate:Ci},Di={sizes:{xs:{width:180,height:100},sm:{width:240,height:135},md:{width:320,height:180},lg:{width:420,height:234},xl:{width:520,height:290}},spacing:{xs:8,sm:10,md:16,lg:24,xl:32},textSizes:{xs:13.33,sm:16,md:19.2,lg:23.04,xl:27.65},iconSizes:{xs:24,sm:36,md:60,lg:82,xl:90}};var Oi=a();const ki=[`xs`,`sm`,`md`,`lg`,`xl`],Ai=[`left`,`right`,`top`,`bottom`],ji=[`auto`,`fixed`],Mi=[`solid`,`dashed`,`dotted`,`none`],Ni=[`rectangle`,`person`,`browser`,`mobile`,`cylinder`,`storage`,`queue`,`bucket`,`document`,`component`,`agent`],Pi=[`amber`,`blue`,`gray`,`slate`,`green`,`indigo`,`muted`,`primary`,`red`,`secondary`,`sky`],Fi=[`tomato`,`grass`,`blue`,`ruby`,`orange`,`indigo`,`pink`,`teal`,`purple`,`amber`,`crimson`,`red`,`lime`,`yellow`,`violet`],Ii={tomato:Oi.tomato.tomato9,grass:Oi.grass.grass9,blue:Oi.blue.blue9,ruby:Oi.ruby.ruby9,orange:Oi.orange.orange9,indigo:Oi.indigo.indigo9,pink:Oi.pink.pink9,teal:Oi.teal.teal9,purple:Oi.purple.purple9,amber:Oi.amber.amber9,crimson:Oi.crimson.crimson9,red:Oi.red.red9,lime:Oi.lime.lime9,yellow:Oi.yellow.yellow9,violet:Oi.violet.violet9};function isDefaultTagColor(e){return typeof e==`string`&&e in Ii}const Li={colors:Pi.reduce((e,t)=>(e[t]={elements:xi[t],relationships:Ei[t]},e),{}),...Di}
|
|
2
|
+
/*
|
|
3
|
+
* @version 1.4.1
|
|
4
|
+
* @date 2026-09-02
|
|
5
|
+
* @stability 3 - Stable
|
|
6
|
+
* @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
|
|
7
|
+
* @license MIT License
|
|
8
|
+
*/
|
|
9
|
+
;var Ri=/* @__PURE__ */ r((/* @__PURE__ */ i(((e,t)=>{var naturalCompare=function(e,t){var r,i,a=1,s=0,c=0,l=String.alphabet,u=l?l.length:0;function getCode(e,t,i){if(i){for(r=t;i=getCode(e,r),i<76&&i>65;)++r;return+e.slice(t-1,r)}return i=l&&t<e.length?l.indexOf(e.charAt(t)):-1,i>-1?i+76:(i=(i=e.charCodeAt(t)||0,i<45||i>127?i:i<46?65:i<48?i-1:i<58?i+18:i<65?i-11:i<91?i+11:i<97?i-37:i<123?i+5:i-63),i<76?i:i+u)}if((e+=``)!=(t+=``)){for(;a;)if(i=getCode(e,s++),a=getCode(t,c++),i<76&&a<76&&i>66&&a>66&&(i=getCode(e,s,s),a=getCode(t,c,s=r),c=r),i!=a)return i<a?-1:1}return 0};try{t.exports=naturalCompare}catch{String.naturalCompare=naturalCompare}})))(),1);function compareNatural(e,t){return e===t?0:S(e)?S(t)?(0,Ri.default)(e,t):1:S(t)?-1:0}function compareNaturalHierarchically(e=`.`,t=!1){return(r,i)=>{if(r===i)return 0;if(!r)return-1;if(!i)return 1;let a=r.split(e),s=i.split(e),c=Math.min(a.length,s.length);for(let e=0;e<c;e++){let t=a[e],r=s[e],i=(0,Ri.default)(t,r);if(i!==0)return i}let l=a.length-s.length;return t?-1*l:l}}function nonNullable(e,t){if(e===void 0||e==null){let r=typeof t==`function`?t():t;throw Error(r??`Expected defined value, but received ${e}`)}return e}function invariant(e,t){if(!e)throw Error(t??`Invariant failed`)}function nonexhaustive(e){throw Error(`NonExhaustive value: ${e}`)}function assignTagColors(e){let t=[],r=[];for(let[i,a]of M(e))j(a.color)?t.push({tag:i,spec:{color:a.color}}):r.push(i);return N(r,Be(compareNatural),p((e,t)=>({tag:e,spec:{color:nonNullable(Fi[t%Fi.length])}})),Se(t),Be((e,t)=>compareNatural(e.tag,t.tag)),xe(A(`tag`),A(`spec`)))}function commonHead(e,t,r){if(e.length===0||t.length===0)return[];r??=Object.is;let i=[];for(let a=0;a<e.length&&a<t.length&&r(e[a],t[a]);a++)i.push(e[a]);return i}function exact(e){return u(e,e=>e===void 0)}/* @__NO_SIDE_EFFECTS__ */
|
|
10
|
+
function preferSummary(e){return e.summary??e.description}/* @__NO_SIDE_EFFECTS__ */
|
|
11
|
+
function preferDescription(e){return e.description??e.summary}const zi={center({x:e,y:t,width:r,height:i}){return{x:e+r/2,y:t+i/2}},toPoints({x:e,y:t,width:r,height:i}){return[{x:e,y:t},{x:e+r,y:t},{x:e+r,y:t+i},{x:e,y:t+i}]},fromPoints(e){let{x1:t,y1:r,x2:i,y2:a}=Bi.fromPoints(e);return{x:t,y:r,width:i-t,height:a-r}},merge(...e){if(invariant(k(e,1),`No boxes provided`),e.length===1)return e[0];let t=e[0].x,r=e[0].y,i=e[0].x+e[0].width,a=e[0].y+e[0].height;for(let s=1;s<e.length;s++){let c=e[s];t=Math.min(t,c.x),r=Math.min(r,c.y),i=Math.max(i,c.x+c.width),a=Math.max(a,c.y+c.height)}return{x:Math.floor(t),y:Math.floor(r),width:Math.round(i-t),height:Math.round(a-r)}},fromRectBox(e){return{x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)}},toRectBox(e){return{x1:e.x,y1:e.y,x2:e.x+e.width,y2:e.y+e.height}},expand(e,t){return typeof t==`number`?t===0?e:{x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}:{x:e.x-(t.left??0),y:e.y-(t.top??0),width:e.width+(t.left??0)+(t.right??0),height:e.height+(t.top??0)+(t.bottom??0)}},shrink(e,t){return t===0?e:{x:e.x+t,y:e.y+t,width:e.width-t*2,height:e.height-t*2}},includes(e,t){return e===t||e.x<=t.x&&e.y<=t.y&&e.x+e.width>=t.x+t.width&&e.y+e.height>=t.y+t.height},intersects(e,t){return!(e.x+e.width<=t.x||t.x+t.width<=e.x||e.y+e.height<=t.y||t.y+t.height<=e.y)}},Bi={center({x1:e,y1:t,x2:r,y2:i}){return{x:(e+r)/2,y:(t+i)/2}},fromPoints(e){invariant(e.length>0,`At least one point is required`);let t=1/0,r=1/0,i=-1/0,a=-1/0;for(let[s,c]of e)t=Math.min(t,s),r=Math.min(r,c),i=Math.max(i,s),a=Math.max(a,c);return{x1:t,y1:r,x2:i,y2:a}},merge(...e){invariant(e.length>0,`No boxes provided`);let t=1/0,r=1/0,i=-1/0,a=-1/0;for(let s of e)t=Math.min(t,s.x1),r=Math.min(r,s.y1),i=Math.max(i,s.x2),a=Math.max(a,s.y2);return{x1:t,y1:r,x2:i,y2:a}},toBBox(e){return{x:e.x1,y:e.y1,width:e.x2-e.x1,height:e.y2-e.y1}},includes(e,t){return e===t||e.x1<=t.x1&&e.y1<=t.y1&&e.x2>=t.x2&&e.y2>=t.y2}};function nearlyEqual(e,t){return Math.abs(e-t)<=1}function splineToPolyline(e){let t=[];for(let r=0;r<e.length;r+=3){let[i,a]=e[r],s=t.at(-1);(!s||!(nearlyEqual(s.x,i)&&nearlyEqual(s.y,a)))&&t.push({x:i,y:a})}return t}function distanceBetween(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function continuesRun(e,t,r){return nearlyEqual(e[0].x,t.x)&&nearlyEqual(t.x,r.x)&&Math.sign(r.y-t.y)===Math.sign(t.y-e[0].y)||nearlyEqual(e[0].y,t.y)&&nearlyEqual(t.y,r.y)&&Math.sign(r.x-t.x)===Math.sign(t.x-e[0].x)}function polylineToSegments(e){let t=[];for(let r=1;r<e.length;r++){let i=e[r-1],a=e[r];if(nearlyEqual(i.x,a.x)&&nearlyEqual(i.y,a.y))continue;let s=t.at(-1);s&&continuesRun(s,i,a)?s[1]=a:t.push([i,a])}return t}function placeLabelsAlongRoutes(e,t){let r=/* @__PURE__ */ new Map,i=[...t],a=e.flatMap(e=>e.segments);for(let t of e)t.labelBBox&&(t.fixed||t.segments.length===0)&&(r.set(t.id,t.labelBBox),i.push(t.labelBBox));for(let t of[...e].sort(compareIds)){if(!t.labelBBox||r.has(t.id))continue;let e=placeLabelAlongSegments({segments:t.segments,size:t.labelBBox,obstacles:i,routes:a});r.set(t.id,e),i.push(e)}return r}function placeLabelAlongSegments({segments:e,size:t,obstacles:r,routes:i=[]}){let a=[...r.map(e=>zi.expand(e,6)),...i.map(([e,t])=>zi.expand(zi.fromPoints([[e.x,e.y],[t.x,t.y]]),2))],isClear=e=>!a.some(t=>zi.intersects(t,e)),s=e.map((e,t)=>({segment:e,index:t,length:distanceBetween(e[0],e[1])})).sort((e,t)=>t.length-e.length||e.index-t.index),c=null;for(let{segment:[e,r],length:i}of s){let s=Math.abs(r.x-e.x)>=Math.abs(r.y-e.y),l={x:(e.x+r.x)/2,y:(e.y+r.y)/2};c??=labelBeside(l,t,s,!1);let u=i===0?0:(r.x-e.x)/i,p=i===0?0:(r.y-e.y)/i,m=shiftsAlong({origin:s?l.x:l.y,direction:s?u:p,length:i,extent:s?t.width:t.height},a,s);for(let e of m){let r={x:l.x+u*e,y:l.y+p*e};for(let e of[!1,!0]){let i=labelBeside(r,t,s,e);if(isClear(i))return i}}}return c??{x:0,y:0,width:t.width,height:t.height}}function compareIds(e,t){return e.id<t.id?-1:+(e.id>t.id)}function labelBeside(e,t,r,i){return r?{x:Math.round(e.x-t.width/2),y:Math.round(i?e.y+4:e.y-4-t.height),width:t.width,height:t.height}:{x:Math.round(i?e.x-4-t.width:e.x+4),y:Math.round(e.y-t.height/2),width:t.width,height:t.height}}function shiftsAlong({origin:e,direction:t,length:r,extent:i},a,s){let c=/* @__PURE__ */ new Set([0,r/2,-r/2]);if(t!==0)for(let l of a){let a=s?l.x:l.y,u=a+(s?l.width:l.height);for(let s of[Math.floor(a-i)+i/2,Math.ceil(u)+i/2]){let i=(s-e)/t;Math.abs(i)<=r/2&&c.add(i)}}return[...c].sort((e,t)=>Math.abs(e)-Math.abs(t)||t-e)}function isOnStage(e,t){return e[Vi]===t}const Vi=`_stage`,Hi=`_type`,Ui=`_layout`;function ProjectId(e){return e}function MarkdownOrString$1(e){return typeof e==`string`?{txt:e}:e}e(MarkdownOrString$1,`MarkdownOrString`);function flattenMarkdownOrString(e){if(_(e))return null;let t=S(e)?e:e.txt??e.md;return j(t?.trim())?t:null}function Fqn(e,t){return t?t+`.`+e:e}const Wi=`@group`;function isGroupElementKind(e){return e.kind===Wi}function ViewId(e){return e}function GlobalFqn(e,t){return invariant(typeof e==`string`&&e!=``),`@`+e+`.`+t}function isGlobalFqn(e){return e.startsWith(`@`)}function splitGlobalFqn(e){if(!e.startsWith(`@`))return[null,e];let t=e.indexOf(`.`);if(t<2)throw Error(`Invalid global FQN`);return[e.slice(1,t),e.slice(t+1)]}function isStepPath(e){return typeof e==`string`&&e.startsWith(`step-`)}function StepPath(...e){let t=e.filter(e=>e!==void 0&&e!==``).map((e,t)=>Array.isArray(e)&&e.length===2?(invariant(j(e[1]),`StepPath segment kind can not be empty "${e[0]}:${e[1]}"`),`${e[0].toString(10).padStart(2,`0`)}:${e[1]}`):x(e)?e.toString(10).padStart(2,`0`):t>0&&e?.startsWith(`step-`)?e.substring(5):e);invariant(k(t,1),`StepPath must have at least one segment`);let r=t.join(`.`);return r.startsWith(`step-`)?r:`step-${r}`}let H;(function(e){function isElementRef(e){return`model`in e&&!(`project`in e)}e.isElementRef=isElementRef;function isImportRef(e){return`project`in e&&`model`in e}e.isImportRef=isImportRef;function flatten(e){if(S(e))throw Error(`Expected FqnRef, got: "${e}"`);if(isImportRef(e))return GlobalFqn(e.project,e.model);if(isElementRef(e))return e.model;throw Error(`Expected FqnRef.ModelRef or FqnRef.ImportRef`)}e.flatten=flatten;function isModelRef(e){return isElementRef(e)||isImportRef(e)}e.isModelRef=isModelRef;function isInsideInstanceRef(e){return`deployment`in e&&`element`in e}e.isInsideInstanceRef=isInsideInstanceRef;function isDeploymentElementRef(e){return`deployment`in e&&!(`element`in e)}e.isDeploymentElementRef=isDeploymentElementRef;function isDeploymentRef(e){return isDeploymentElementRef(e)||isInsideInstanceRef(e)}e.isDeploymentRef=isDeploymentRef})(H||={});let U;(function(e){function isWildcard(e){return`wildcard`in e&&e.wildcard===!0}e.isWildcard=isWildcard;function isModelRef(e){return`ref`in e&&H.isModelRef(e.ref)}e.isModelRef=isModelRef;function isDeploymentRef(e){return`ref`in e&&H.isDeploymentRef(e.ref)}e.isDeploymentRef=isDeploymentRef;function isElementKindExpr(e){return`elementKind`in e&&`isEqual`in e}e.isElementKindExpr=isElementKindExpr;function isElementTagExpr(e){return`elementTag`in e&&`isEqual`in e}e.isElementTagExpr=isElementTagExpr;function isWhere(e){return`where`in e&&is(e.where.expr)}e.isWhere=isWhere;function isCustom(e){return`custom`in e&&(is(e.custom.expr)||isWhere(e.custom.expr))}e.isCustom=isCustom;function is(e){return isWildcard(e)||isModelRef(e)||isDeploymentRef(e)||isElementKindExpr(e)||isElementTagExpr(e)}e.is=is;function unwrap(e){return isCustom(e)&&(e=e.custom.expr),isWhere(e)&&(e=e.where.expr),e}e.unwrap=unwrap})(U||={});let Gi;(function(e){function isDirect(e){return`source`in e&&`target`in e}e.isDirect=isDirect;function isIncoming(e){return`incoming`in e}e.isIncoming=isIncoming;function isOutgoing(e){return`outgoing`in e}e.isOutgoing=isOutgoing;function isInOut(e){return`inout`in e}e.isInOut=isInOut;function isWhere(e){return`where`in e&&(isDirect(e.where.expr)||isIncoming(e.where.expr)||isOutgoing(e.where.expr)||isInOut(e.where.expr))}e.isWhere=isWhere;function isCustom(e){return`customRelation`in e}e.isCustom=isCustom;function is(e){return isDirect(e)||isIncoming(e)||isOutgoing(e)||isInOut(e)}e.is=is;function unwrap(e){return isCustom(e)&&(e=e.customRelation.expr),isWhere(e)&&(e=e.where.expr),e}e.unwrap=unwrap})(Gi||={});let Ki;(function(e){function isWhere(e){return`where`in e}e.isWhere=isWhere;function isRelationWhere(e){return Gi.isWhere(e)}e.isRelationWhere=isRelationWhere;function isFqnExprWhere(e){return U.isWhere(e)}e.isFqnExprWhere=isFqnExprWhere;function isFqnExpr(e){return U.is(e)||U.isWhere(e)||U.isCustom(e)}e.isFqnExpr=isFqnExpr;function isRelation(e){return Gi.is(e)||Gi.isWhere(e)||Gi.isCustom(e)}e.isRelation=isRelation})(Ki||={});let W;(function(e){function isWildcard(e){return`wildcard`in e&&e.wildcard===!0}e.isWildcard=isWildcard;function isModelRef(e){return`ref`in e&&H.isModelRef(e.ref)}e.isModelRef=isModelRef;function isElementKindExpr(e){return`elementKind`in e&&`isEqual`in e}e.isElementKindExpr=isElementKindExpr;function isElementTagExpr(e){return`elementTag`in e&&`isEqual`in e}e.isElementTagExpr=isElementTagExpr;function isWhere(e){return`where`in e&&is(e.where.expr)}e.isWhere=isWhere;function isCustom(e){return`custom`in e&&(is(e.custom.expr)||isWhere(e.custom.expr))}e.isCustom=isCustom;function is(e){return isWildcard(e)||isModelRef(e)||isElementKindExpr(e)||isElementTagExpr(e)}e.is=is;function unwrap(e){return isCustom(e)&&(e=e.custom.expr),isWhere(e)&&(e=e.where.expr),e}e.unwrap=unwrap})(W||={});let qi;(function(e){function isDirect(e){return`source`in e&&`target`in e}e.isDirect=isDirect;function isIncoming(e){return`incoming`in e}e.isIncoming=isIncoming;function isOutgoing(e){return`outgoing`in e}e.isOutgoing=isOutgoing;function isInOut(e){return`inout`in e}e.isInOut=isInOut;function isWhere(e){return`where`in e&&(isDirect(e.where.expr)||isIncoming(e.where.expr)||isOutgoing(e.where.expr)||isInOut(e.where.expr))}e.isWhere=isWhere;function isCustom(e){return`customRelation`in e}e.isCustom=isCustom;function is(e){return isDirect(e)||isIncoming(e)||isOutgoing(e)||isInOut(e)}e.is=is;function unwrap(e){return isCustom(e)&&(e=e.customRelation.expr),isWhere(e)&&(e=e.where.expr),e}e.unwrap=unwrap})(qi||={});let Ji;(function(e){function isWhere(e){return`where`in e}e.isWhere=isWhere;function isRelationWhere(e){return qi.isWhere(e)}e.isRelationWhere=isRelationWhere;function isFqnExprWhere(e){return W.isWhere(e)}e.isFqnExprWhere=isFqnExprWhere;function isFqnExpr(e){return W.is(e)||W.isWhere(e)||W.isCustom(e)}e.isFqnExpr=isFqnExpr;function isRelationExpr(e){return qi.is(e)||qi.isWhere(e)||qi.isCustom(e)}e.isRelationExpr=isRelationExpr})(Ji||={});function isDeploymentNode$1(e){return j(e.kind)&&!j(e.element)}e(isDeploymentNode$1,`isDeploymentNode`);function isDeployedInstance$1(e){return j(e.element)&&!j(e.kind)}e(isDeployedInstance$1,`isDeployedInstance`);function isPlainObject(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function _defu(e,t,r=`.`,i){if(!isPlainObject(t))return _defu(e,{},r,i);let a={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let s=e[t];s!=null&&(i&&i(a,t,s,r)||(a[t]=Array.isArray(s)&&Array.isArray(a[t])?[...s,...a[t]]:isPlainObject(s)&&isPlainObject(a[t])?_defu(s,a[t],(r?`${r}.`:``)+t.toString(),i):s))}return a}function createDefu(e){return(...t)=>t.reduce((t,r)=>_defu(t,r,``,e),{})}const Yi=createDefu();function computeCompoundColorValues(e,t){let r=t??6;invariant(r>=1,`Depth must be at least 1`);let i=Je(e.fill),a=Je(e.stroke),s=i.luminance()>.8,c=Je.scale(s?[i.darken(.02).desaturate(.05),i.darken(.1).desaturate(.1)]:[i.shade(.12,`lch`).desaturate(.05),i.shade(.35,`lch`).desaturate(.4)]).mode(`oklch`).correctLightness().colors(r,null),l=Je.scale(s?[a.darken(.04).desaturate(.05),a.darken(.12).desaturate(.1)]:[a.shade(.15,`lch`).desaturate(.08),a.shade(.4,`lch`).desaturate(.4)]).mode(`oklch`).correctLightness().colors(r,null),u=N(Re(c,l),p(([t,r])=>({...e,fill:t.hex(),stroke:r.hex()})));return invariant(u.length===r,`Expected ${r} colors, got ${u.length}`),u}const Xi={color:`primary`,size:`md`,opacity:15,shape:`rectangle`,group:{opacity:15,border:`dashed`},relationship:{color:`gray`,line:`dashed`,arrow:`normal`},view:{routing:`spline`}},Zi=1.3;function contentBox({shape:e,width:t,height:r,padding:i}){let a=i+8,s=i+8,c=i,l=i;switch(e){case`queue`:case`mobile`:a=46,s=16;break;case`bucket`:a=s=i+20;break;case`component`:a=i+30;break;case`cylinder`:case`storage`:c=30;break;case`browser`:c=32,l=28}return{width:Math.max(0,t-a-s),height:Math.max(0,r-c-l)}}function countWrappedLines(e,t){let r=Math.max(1,t),i=0;for(let t of e.split(`
|
|
12
|
+
`)){let e=0;i++;for(let a of t.split(/\s+/).filter(Boolean)){let t=a.length;e===0?(i+=Math.ceil(t/r)-1,e=t%r||r):e+1+t<=r?e+=1+t:(i+=Math.ceil(t/r),e=t%r||r)}}return i}function fitNodeContent(e){let{title:t,size:r,hasIcon:i,iconPosition:a}=e,s=contentBox(e),c=r===`xs`||r===`sm`?2:3,l=i&&(a===`left`||a===`right`),u=e.iconSize;i&&(u=l?Math.min(u,s.height,s.width*.3):Math.min(u,s.width,s.height*.35),u=Math.max(0,Math.floor(u)));let p=s.width,m=s.height;i&&(l?p-=u+16:m-=u+16);let h=e.hasTechnology&&r!==`xs`,g=e.hasDescription&&r!==`xs`,reserved=e=>{let t=0;return h&&(t+=e*.635*Zi+8),g&&(t+=e*.74*Zi+8),t},maxcharsFor=e=>Math.max(1,Math.floor(p/(e*.55))),fits=e=>{let r=countWrappedLines(t,maxcharsFor(e));return r<=c&&r*e*1.25+reserved(e)<=m},_=Math.min(e.textSize,Math.max(9,e.textSize*.5)),v=e.textSize;for(;v>_&&!fits(v);)v=Math.max(_,v*.92);return v=Math.round(v*100)/100,{textSize:v,iconSize:u,maxLines:c,maxchars:maxcharsFor(v)}}const Qi={theme:Li,defaults:Xi};var $i=class LikeC4Styles{config;customCss;theme;defaults;static DEFAULT=new LikeC4Styles(Qi);static from(e,t){if(!e&&!t)return this.DEFAULT;let{customCss:r,theme:i,defaults:a}={...e},s=Yi({theme:i},{defaults:{...a}},{theme:{colors:{...t}}},Qi);return _(r?.content)&&ce(s,Qi)?this.DEFAULT:new LikeC4Styles(s,r)}constructor(e,t){this.config=e,this.customCss=t,this.theme=e.theme,this.defaults=e.defaults}get fingerprint(){return memoizeProp(this,`fingerprint`,()=>objectHash({config:this.config,customCss:this.customCss}))}get elementColors(){return this.theme.colors[this.defaults.color].elements}get relationshipColors(){return this.theme.colors[this.defaults.relationship.color].relationships}get groupColors(){let e=this.defaults.group?.color;if(!e)return this.elementColors;if(!this.isThemeColor(e))throw Error(`Default group color not found in theme: ${e}`);return memoizeProp(this,`defaultGroup`,()=>({...this.elementColors,...this.theme.colors[e].elements}))}isDefaultColor(e){return e===this.defaults.color}colors(e){return this.computeFrom(e??this.defaults.color)}compoundColorsCache=new Ze.default(e=>new I.default(t=>computeCompoundColorValues(e,t)));colorsForCompounds(e,t){return this.compoundColorsCache.get(e).get(t??6)}fontSize(e){return e??=this.defaults.text??this.defaults.size,this.theme.textSizes[e]}padding(e){return e??=this.defaults.padding??this.defaults.size,this.theme.spacing[e]}iconSize(e){return e??=this.defaults.size,this.theme.iconSizes[e]}isThemeColor(e){return e in this.theme.colors}nodeSizes(e){let t=Ge(ensureSizes(e,this.defaults.size),[`size`,`textSize`,`padding`,`iconSize`]);return{sizes:t,values:{sizes:this.theme.sizes[t.size],padding:this.padding(t.padding),textSize:this.fontSize(t.textSize),iconSize:this.iconSize(t.iconSize)}}}fitNodeContent(e){let{sizes:t,values:r}=this.nodeSizes(e.style),i=!!e.icon&&e.icon!==`none`;return e.style.sizing===`fixed`?fitNodeContent({title:e.title,shape:e.shape,size:t.size,width:e.width??r.sizes.width,height:e.height??r.sizes.height,padding:r.padding,textSize:r.textSize,iconSize:r.iconSize,hasIcon:i,iconPosition:e.style.iconPosition??this.defaults.iconPosition??`left`,hasTechnology:!!e.technology?.trim(),hasDescription:!!(e.description&&flattenMarkdownOrString(e.description)?.trim())}):{textSize:r.textSize,iconSize:r.iconSize,maxLines:t.size===`xs`||t.size===`sm`?2:3,maxchars:Math.floor(r.sizes.width/(r.textSize*.55))}}computeFrom(e){if(this.isThemeColor(e))return this.theme.colors[e];if(!Je.valid(e))throw Error(`Invalid color value: "${e}" (not a theme color and not a valid CSS color)`);return computeColorValues(e)}equals(e){return e===this||this.constructor===e.constructor&&this.fingerprint===e.fingerprint}tagColor(e){return this.isThemeColor(e)?this.theme.colors[e].elements:isDefaultTagColor(e)?this.computeFrom(Ii[e]).elements:this.computeFrom(e).elements}};function ensureSizes(e,t=Qi.defaults.size){let{size:r,textSize:i,padding:a,iconSize:s}=e;return r??=t,i??=r,a??=r,s??=r,{...e,size:r,padding:a,textSize:i,iconSize:s}}function isTagEqual(e){return`tag`in e}function isKindEqual(e){return`kind`in e}function isMetadataEqual(e){return`metadata`in e}function isParticipantOperator(e){return`participant`in e}function isNotOperator(e){return`not`in e}function isAndOperator(e){return`and`in e}function isOrOperator(e){return`or`in e}function whereOperatorAsPredicate(e){switch(!0){case isParticipantOperator(e):{let t=e.participant;return participantIs(t,whereOperatorAsPredicate(e.operator))}case isTagEqual(e):{if(S(e.tag)||`eq`in e.tag){let t=S(e.tag)?e.tag:e.tag.eq;return e=>Array.isArray(e.tags)&&e.tags.includes(t)}let t=e.tag.neq;return e=>!Array.isArray(e.tags)||!e.tags.includes(t)}case isKindEqual(e):{if(S(e.kind)||`eq`in e.kind){let t=S(e.kind)?e.kind:e.kind.eq;return e=>e.kind===t}let t=e.kind.neq;return e=>C(e.kind)||e.kind!==t}case isMetadataEqual(e):{let{key:t,value:r}=e.metadata;if(r===void 0)return e=>e.metadata!=null&&t in e.metadata&&e.metadata[t]!=null;if(S(r)||`eq`in r){let e=S(r)?r:r.eq;return r=>{if(!r.metadata)return!1;let i=r.metadata[t];return Array.isArray(i)?i.includes(e):i===e}}let i=r.neq;return e=>{if(!e.metadata)return!0;let r=e.metadata[t];return r==null?!0:Array.isArray(r)?!r.includes(i):r!==i}}case isNotOperator(e):{let t=whereOperatorAsPredicate(e.not);return qe(t)}case isAndOperator(e):{let t=e.and.map(whereOperatorAsPredicate);return Ke(t)}case isOrOperator(e):{let t=e.or.map(whereOperatorAsPredicate);return Ue(t)}default:nonexhaustive(e)}}function participantIs(e,t){return r=>{if(!r.source||!r.target)return!1;switch(e){case`source`:return t(r.source);case`target`:return t(r.target)}}}function isViewRulePredicate$1(e){return`include`in e||`exclude`in e}e(isViewRulePredicate$1,`isViewRulePredicate`);function isViewRuleStyle$1(e){return`targets`in e&&`style`in e}e(isViewRuleStyle$1,`isViewRuleStyle`);function isElementView$1(e){return e._type===`element`}e(isElementView$1,`isElementView`);function isExtendsElementView(e){return isElementView$1(e)&&j(e.extends)}function isDeploymentView$1(e){return e._type===`deployment`}e(isDeploymentView$1,`isDeploymentView`);function isDynamicView$1(e){return e._type===`dynamic`}e(isDynamicView$1,`isDynamicView`);function isDynamicViewWithFlow(e){return e._type===`dynamic`&&`flow`in e&&!!e.flow}function isViewRuleGlobalStyle$1(e){return`styleId`in e}e(isViewRuleGlobalStyle$1,`isViewRuleGlobalStyle`);function isViewRuleGlobalPredicateRef$1(e){return`predicateId`in e}e(isViewRuleGlobalPredicateRef$1,`isViewRuleGlobalPredicateRef`);function isViewRuleAutoLayout$1(e){return`direction`in e}e(isViewRuleAutoLayout$1,`isViewRuleAutoLayout`);function isSubFlow(e){return typeof e==`object`&&!!e&&isString(e.id)&&isString(e._type)}function asStepPath(e){return isString(e)?e:e.id}const ea={isStepPath,isSubFlow,isTry:e=>isSubFlow(e)&&e._type===`try`,isTryBlock:e=>isSubFlow(e)&&ea.type.isTryBlock(e._type),isAlt:e=>isSubFlow(e)&&e._type===`alt`,isAltBranch:e=>isSubFlow(e)&&ea.type.isAltBranch(e._type),isTryBranch:e=>isSubFlow(e)&&ea.type.isTryBranch(e._type),isAltOrTry:e=>isSubFlow(e)&&ea.type.isAltOrTry(e._type),isAltOrTryBranch:e=>isSubFlow(e)&&ea.type.isAltOrTryBranch(e._type),type:{isAltOrTry:e=>e===`alt`||e===`try`,isAltBranch:e=>isString(e)&&e.startsWith(`alt-`),isTryBlock:e=>e===`try-block`,isTryBranch:e=>isString(e)&&e.startsWith(`try-`),isAltOrTryBranch:e=>isString(e)&&(e.startsWith(`alt-`)||e.startsWith(`try-`))}};function _includesStep(e,t){let r=asStepPath(e);return asStepPath(t).startsWith(r)}function includes$1(...e){return me(_includesStep,e)}e(includes$1,`includes`);const ta=compareNaturalHierarchically();function _isBefore(e,t){let r=asStepPath(e),i=asStepPath(t);return ta(r,i)<=0}function isBefore(...e){return me(_isBefore,e)}const na={unwindTry:e=>{let[t,r=null,i=null]=e.flow;return!i&&r?._type===`try-finally`&&(i=r,r=null),{tryBlock:t,catchBlock:r?._type===`try-catch`?r:null,finallyBlock:i}},firstStep:e=>{if(isStepPath(e))return e;if(b(e)){for(let t of e){if(isStepPath(t))return t;let e=na.firstStep(t);if(e)return e}return null}return na.firstStep(e.flow)},hasSteps:e=>!!na.firstStep(e),steps:e=>D(e.flow,ea.isStepPath),subflows:e=>D(e.flow,ea.isSubFlow),hasSubflows:e=>e.flow.some(ea.isSubFlow),isBefore,includes:includes$1,extractPath:e=>ea.isStepPath(e)?e:e.id};function parentFlow(e){if(!e)return null;let t=e.lastIndexOf(`.`);if(t===-1)return null;let r=e.slice(0,t);return r.includes(`:`)?r:null}var StopError=class{result;constructor(e){this.result=e}};function walkthroughFlow(...e){if(e.length===1)return t=>walkthroughFlow(t,e[0]);let[t,r]=e;if(!isDynamicViewWithFlow(t))throw Error(`Dynamic view ${t.id} does not have a flow`);let i=1,a=new Map(t.edges.map(e=>[e.id,e])),s=new Map(t.nodes.map(e=>[e.id,e])),visitStep=(e,t,c,l)=>{let u=nonNullable(a.get(e)),p=nonNullable(s.get(u.source)),m=nonNullable(s.get(u.target));r.step?.({step:e,level:c,edge:u,source:p,target:m,stepnum:{index:l,global:i++},parent:t,stopAndReturn:t=>{throw new StopError(t??e)}})},callSubflow=e=>{if(!r.subflow)return;if(oe(r.subflow))return r.subflow(e);let t=r.subflow[e.type]??r.subflow.default;return g(t)?t:oe(t)?t(e):void 0},visitSubflow=(e,t,r,i=0)=>{let a={id:e.id,type:e._type,subflow:e,parent:t,previous:r,level:i,stopAndReturn:t=>{throw new StopError(t??e)}},s=callSubflow(a)??!0;if(s===!1)return!1;let c,l;s===!0?c=e.flow:oe(s)?(l=s,c=e.flow):(c=s.next?N(Array.isArray(s.next)?s.next:[s.next],D(j),p(t=>(invariant(e.flow.includes(t),`Next step must be part of the subflow`),t))):e.flow,l=s.onLeave);let u=walk(c,a,i+1);return l?.(u),!0};function walk(e,t,r=0){let i=1,a=null,s=[];for(let c of e)ea.isStepPath(c)?(s.push(c),a=c,visitStep(c,t,r,i++)):visitSubflow(c,t,a,r)&&(s.push(c),a=c);return{visited:s,lastVisited:a}}try{walk(t.flow,null,0)}catch(e){if(e instanceof StopError)return e.result;throw e}}function onSubflows(e,t){return e=Array.isArray(e)?e:[e],Object.fromEntries(p(e,e=>[e,t]))}walkthroughFlow.onSubflows=onSubflows;function dynamicViewFlow(e){return ra.from(e)}var ra=class DynamicViewFlow{static cache=new Ze.default(e=>new DynamicViewFlow(e));static from(e){if(!isDynamicViewWithFlow(e))throw Error(`Dynamic view "${e.id}" does not have a flow, probably it is a stale snapshot`);return this.cache.get(e)}static guards=ea;static helpers=na;unwindTry=na.unwindTry;isBefore=na.isBefore;includes=na.includes;onSubflows=onSubflows;guards=ea;helpers=na;view;levelById=/* @__PURE__ */ new Map;byId=/* @__PURE__ */ new Map;stepsCount;constructor(e){this.view=e;let t=0;walkthroughFlow(e,{step:({step:e,edge:r,level:i})=>{this.levelById.set(e,i),t++},subflow:({subflow:e,level:t})=>{this.byId.set(e.id,e),this.levelById.set(e.id,t)}}),this.stepsCount=t}get paths(){return Array.from(this.levelById.keys())}level(e){return nonNullable(this.levelById.get(isString(e)?e:e.id))}parent(e){let t=parentFlow(isString(e)?e:e.id);return t?this.lookup(t):void 0}firstStep(e){if(!e)return nonNullable(na.firstStep(this.view.flow),`No steps found in flow`);let t=asStepPath(e);return this.isStep(t)?t:na.firstStep(this.lookup(t))}isStep(e){return!this.byId.has(e)&&this.levelById.has(e)}isSubflow(e){return this.byId.has(e)}steps(e){let t=e?this.lookup(asStepPath(e)).flow:this.view.flow;return D(t,isStepPath)}prevAndNext(e,t){let r={prev:null,next:null},i=!1,a=!1;return walkthroughFlow(this.view,{step:({step:t,stopAndReturn:s})=>{if(t===e)i=!0;else if(!a){if(i)return r.next=t,s();r.prev=t}},subflow:({subflow:r})=>r.id===e?(i=!0,!1):!a&&t?.(r)?(a=!0,()=>{a=!1}):!0}),r}lookup(e,t){let r=nonNullable(this.byId.get(e),`SubFlow "${e}" not found`);if(t&&r._type!==t)throw Error(`SubFlow "${e}" is of type "${r._type}" (expected "${t}")`);return r}subflows(e){return e?(typeof e==`string`?this.lookup(e):e).flow.filter(ea.isSubFlow):this.view.flow.filter(ea.isSubFlow)}hasSubflows(e){return(typeof e==`string`?this.byId.get(e):e)?.flow.some(ea.isSubFlow)??!1}walk(e){return walkthroughFlow(this.view,e)}stepsBefore(e){return stepsBefore(this.view,e)}stepPathsBefore(e){return stepsBefore(this.view,e).map(asStepPath)}stepsAfter(e){return stepsAfter(this.view,e)}};function stepsBefore(e,t){let r=[];return walkthroughFlow(e,{step:({step:e,stopAndReturn:i})=>{if(e===t)return i();r.push(e)},subflow:({subflow:e,stopAndReturn:i})=>e.id===t?i():(r.push(e),!0)}),r}function stepsAfter(e,t){let r=includes$1(t),i;return walkthroughFlow(e,{step:({step:e})=>{e===t?i=[]:i?.push(e)},subflow:({subflow:e})=>e.id===t?(i=[],!1):i?(i.push(e),!0):r(e)}),i??[]}const ia={isStep:e=>!!e&&`source`in e&&`target`in e,isSeries:e=>!!e&&`_type`in e&&e._type===`series`,isParallel:e=>!!e&&`_type`in e&&e._type===`par`,isOpt:e=>!!e&&`_type`in e&&e._type===`opt`,isLoop:e=>!!e&&`_type`in e&&e._type===`loop`,isTry:e=>!!e&&`_type`in e&&e._type===`try`,isAlt:e=>!!e&&`_type`in e&&e._type===`alt`,isBreak:e=>!!e&&`_type`in e&&e._type===`break`};function isViewRuleGroup$1(e){return`title`in e&&`groupRules`in e&&Array.isArray(e.groupRules)}e(isViewRuleGroup$1,`isViewRuleGroup`);function isViewRuleRank$1(e){return`rank`in e&&Array.isArray(e.targets)}e(isViewRuleRank$1,`isViewRuleRank`);const aa=Symbol.for(`text`),oa=Symbol.for(`html`);var sa=class RichText{static mdcache=new Xe.default(500);static txtcache=new Xe.default(500);static getOrCreateFromText(e){if(e=e.trimEnd(),e===``)return RichText.EMPTY;let t=RichText.txtcache.get(e);return t||(t=new RichText({txt:e}),RichText.txtcache.set(e,t),t)}static getOrCreateFromMarkdown(e){if(e=e.trimEnd(),e===``)return RichText.EMPTY;let t=RichText.mdcache.get(e);return t||(t=new RichText({md:e}),RichText.mdcache.set(e,t),t)}static memoize(e,t,r){return memoizeProp(e,t,()=>RichText.from(r))}static from(e){return e==null||e===RichText.EMPTY?RichText.EMPTY:e instanceof RichText?e:typeof e==`string`?this.getOrCreateFromText(e):`isEmpty`in e&&e.isEmpty?RichText.EMPTY:`md`in e?this.getOrCreateFromMarkdown(e.md):this.getOrCreateFromText(e.txt)}static EMPTY=new class extends RichText{isEmpty=!0;nonEmpty=!1;isMarkdown=!1;$source=null;constructor(){super({txt:``})}get text(){return null}get md(){return null}get html(){return null}};$source;isEmpty;nonEmpty;isMarkdown;constructor(e){this.isMarkdown=!1,typeof e==`string`?(this.$source={txt:e},this.isEmpty=e.trim()===``):(this.$source=e,this.isEmpty=!0,`md`in e?(this.isEmpty=e.md===``,this.isMarkdown=!0):this.isEmpty=e.txt===``),this.nonEmpty=!this.isEmpty}get text(){if(this.isEmpty||this.$source===null)return``;let e=this.$source;return`txt`in e?e.txt:memoizeProp(this,aa,()=>markdownToText(e.md))}get md(){if(this.isEmpty||this.$source===null)return``;let e=this.$source;if(`md`in e)return e.md;if(`txt`in e)return e.txt;nonexhaustive(e)}get html(){if(this.isEmpty||this.$source===null)return``;let e=this.$source;return`txt`in e?e.txt:memoizeProp(this,oa,()=>markdownToHtml(e.md))}equals(e){return this===e?!0:e instanceof RichText?this.isEmpty&&e.isEmpty?!0:this.isEmpty!==e.isEmpty||this.isMarkdown!==e.isMarkdown?!1:this.isMarkdown?this.$source?.md===e.$source?.md:this.$source?.txt===e.$source?.txt:!1}};function isString(e){return e!=null&&typeof e==`string`}function isNonEmptyArray(e){return!!e&&Array.isArray(e)&&e.length>0}function _hasProp(e,t){return invariant(typeof t==`string`,`Path must be string`),typeof e==`object`&&!!e&&Object.hasOwn(e,t)&&e[t]!=null}function hasPropCurried(e){return t=>_hasProp(t,e)}function hasProp(...e){if(e.length===1&&typeof e[0]==`string`)return hasPropCurried(e[0]);let[t,r]=e;return _hasProp(t,r)}function isAnyOf(...e){return(t=>e.some(e=>e(t)))}function parentFqn(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):null}function nameFromFqn(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(t+1):e}const asString=e=>isString(e)?e:e.id;function isAncestor(e,t){let r=asString(e);return t?asString(t).startsWith(r+`.`):e=>{let t=asString(e);return r.startsWith(t+`.`)}}function isSameHierarchy(e,t){if(!t)return t=>isSameHierarchy(e,t);let r=asString(e),i=asString(t);return r===i||i.startsWith(r+`.`)||r.startsWith(i+`.`)}function isDescendantOf(e,t){return t?isAncestor(t,e):t=>isAncestor(e,t)}function hierarchyLevel(e){return(isString(e)?e:e.id).split(`.`).length}function hierarchyDistance(e,t){let r=isString(e)?e:e.id,i=isString(t)?t:t.id;if(r===i)return 0;let a=hierarchyLevel(r),s=hierarchyLevel(i);if(isSameHierarchy(r,i))return Math.abs(a-s);let c=commonPrefix(r,i).length;return a+s-(2*c+1)}function commonPrefix(e,t){let r=[],i=e.split(`.`);if(i.length<=1)return r;let a=t.split(`.`);if(a.length<=1)return r;for(let e=0;e<Math.min(i.length,a.length)-1&&i[e]===a[e];e++)r.push(i[e]);return r}function commonAncestor(e,t){let r=commonPrefix(e,t);return r.length===0||r.length===1&&r[0].startsWith(`@`)?null:r.join(`.`)}function ancestorsFqn(e){let t=e.split(`.`);if(t.pop(),!k(t,2))return t;for(let e=1;e<t.length;e++)t[e]=t[e-1]+`.`+t[e];return t.reverse()}function compareFqnHierarchically(e,t){let r=e.split(`.`).length,i=t.split(`.`).length;switch(!0){case r>i:return 1;case r<i:return-1;default:return 0}}function compareByFqnHierarchically(e,t){return compareFqnHierarchically(e.id,t.id)}function sortByFqnHierarchically(e){return e.map(e=>({item:e,fqn:e.id.split(`.`)})).sort((e,t)=>e.fqn.length-t.fqn.length).map(({item:e})=>e)}function findTopAncestor(e,t){let r=t;for(let t of e)t!==r&&isAncestor(t,r)&&(r=t);return r===t?null:r}function sortParentsFirst(e){let t=[],r=[...e],i;for(;i=r.shift();){let e;for(;e=findTopAncestor(r,i);)t.push(...r.splice(r.indexOf(e),1));t.push(i)}return t}function sortNaturalByFqn(e,t){if(!e||isString(e)){let t=e??`asc`;return e=>sortNaturalByFqn(e,t)}let r=t===`desc`?-1:1;return e.map(e=>({item:e,fqn:e.id.split(`.`)})).sort((e,t)=>{if(e.fqn.length!==t.fqn.length)return(e.fqn.length-t.fqn.length)*r;for(let r=0;r<e.fqn.length;r++){let i=compareNatural(e.fqn[r],t.fqn[r]);if(i!==0)return i}return 0}).map(({item:e})=>e)}function getOrCreate(e,t,r){let i=e.get(t);return i||(i=r(t),e.set(t,i)),i}function isIterable(e){return typeof e==`object`&&!!e&&Symbol.iterator in e}function ifilter(e,t){let r=t??e;invariant(oe(r));function*_filter(e){for(let t of e)r(t)&&(yield t)}return t?_filter(e):_filter}function ifind(e,t){let r=t??e;invariant(oe(r));function _find(e){for(let t of e)if(r(t))return t}return t?_find(e):_find}function iflat(e){return e?_iflat(e):_iflat}function*_iflat(e){for(let t of e)yield*t}function ihead(e){return e?_head(e):_head}function _head(e){let{value:t}=e[Symbol.iterator]().next();return t}function imap(e,t){let r=t??e;invariant(oe(r));function*_map(e){for(let t of e)yield r(t)}return t?_map(e):_map}function isome(e,t){let r=t??e;invariant(oe(r));function _some(e){for(let t of e)if(r(t))return!0;return!1}return t?_some(e):_some}function toArray(e){return e?Array.from(e):e=>Array.from(e)}function toSet(e){return e?new Set(e):e=>new Set(e)}function iunique(e){return e?_iunique(e):_iunique}function*_iunique(e){let t=/* @__PURE__ */ new Set;for(let r of e)t.has(r)||(t.add(r),yield r)}function memoizeProp(e,t,r){let i=typeof t==`symbol`?t:Symbol.for(t);if(!e.hasOwnProperty(i)){let t=r();Object.defineProperty(e,i,{enumerable:!1,writable:!1,value:t})}return e[i]}function delay(...e){let t=100;return e.length===2?t=De(e[0],e[1]):e.length===1&&(t=e[0]),new Promise(e=>{setTimeout(()=>{e(`LIKEC4_DELAY`)},t??100)})}function promiseNextTick(){return Promise.resolve().then(()=>void 0)}function onNextTick(e){promiseNextTick().then(e)}const compareRelations=(e,t)=>{let r=commonAncestor(e.source.id,e.target.id),i=commonAncestor(t.source.id,t.target.id);if(r&&!i)return 1;if(!r&&i)return-1;let a=r&&i?compareFqnHierarchically(r,i):0;if(a!==0)return a;let s=compareFqnHierarchically(e.source.id,t.source.id);return s===0?compareFqnHierarchically(e.target.id,t.target.id):s},ca=Qe.intersection,la=Qe.symmetricDifference;function union(...e){let t=/* @__PURE__ */ new Set;for(let r of e)for(let e of r)t.add(e);return t}function intersection(e,...t){let r=/* @__PURE__ */ new Set;if(e.size===0)return r;let i=k(t,2)?ca(...t):t[0];if(i.size===0)return r;for(let t of e)i.has(t)&&r.add(t);return r}function difference(e,t){if(e.size===0)return/* @__PURE__ */ new Set;if(t.size===0)return new Set(e);let r=/* @__PURE__ */ new Set;for(let i of e)t.has(i)||r.add(i);return r}function equals(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function symmetricDifference(e,t){return la(e,t)}function hasIntersection(e,t){if(e.size===0||t.size===0)return!1;t.size<e.size&&([e,t]=[t,e]);for(let r of e)if(t.has(r))return!0;return!1}function objectHash(e){return invariant(typeof e==`object`&&l(e),`objectHash: value must be an object`),rt(e)}function stringHash$1(e){let t=5381,r=e.length;invariant(r>0,`stringHash: empty string`);for(let i=0;i<r;i++)t=t*33^e.charCodeAt(i);return(t>>>0).toString(36)}e(stringHash$1,`stringHash`);function rehypeSanitize(e){return function(t){return dt(t,e)}}function rehypeStringify(e){let t=this,r={...t.data(`settings`),...e};t.compiler=compiler;function compiler(e){return it(e,r)}}const ua={};function remarkGfm(e){let t=this,r=e||ua,i=t.data(),a=i.micromarkExtensions||=[],s=i.fromMarkdownExtensions||=[],c=i.toMarkdownExtensions||=[];a.push(ft(r)),s.push(ct()),c.push(st(r))}function remarkParse(e){let t=this;t.parser=parser;function parser(r){return ot(r,{...t.data(`settings`),...e,extensions:t.data(`micromarkExtensions`)||[],mdastExtensions:t.data(`fromMarkdownExtensions`)||[]})}}function parser(){return ht().use(remarkParse).use(remarkGfm).use(pt).use(mt,{allowDangerousHtml:!0}).use(lt,{ignoreMissing:!0}).use(rehypeSanitize,Yi({attributes:{"*":[`className`],svg:[`width`,`height`,`viewBox`,`fill`,`ariaHidden`],path:[`d`,`fill`,`stroke`,`strokeWidth`,`strokeLinecap`,`strokeLinejoin`]},tagNames:[`svg`,`g`,`path`,`div`],protocols:{src:[`data`]}},ut)).use(rehypeStringify,{allowDangerousHtml:!0})}function markdownToHtml(e){return(``+parser().processSync(e)).trim()}function markdownToText(e){return at(ot(e),{includeHtml:!1,includeImageAlt:!1})}function adjustToneRgb(e,t){return t=Math.max(-1,Math.min(1,t)),e.map(e=>{let r=t>0?e+(255-e)*t:e*(1+t);return Math.round(Math.max(0,Math.min(255,r)))})}function adjustToneHex(e,t){return Je(adjustToneRgb(Je(e).rgb(),t)).hex()}function computeColorValues(e){invariant(Je.valid(e),`Invalid color: ${e}`);let t=e.trim(),r=getColorPalette(t.startsWith(`#`)?t:Je(t).hex());return{elements:{fill:r.el_main,stroke:r.el_secondary,hiContrast:r.el_hiContrast,loContrast:r.el_loContrast},relationships:{line:r.rel_secondary,label:r.rel_hiContrast,labelBg:r.rel_main}}}function getColorPalette(e){let t=e,r=Je(t).darken(.8).hex(),i=getContrastedColorsAPCA(t),a=i.hiContrast,s=i.loContrast,c=t;return{el_main:t,el_secondary:r,el_hiContrast:a,el_loContrast:s,rel_main:c,rel_secondary:adjustToneHex(t,-.25),rel_hiContrast:getContrastedColorsAPCA(c).hiContrast}}function getContrastedColorsAPCA(e){let t=Je(e),r=t.brighten(2),i=t.darken(2),a,s,c,l;do a=r,s=i,r=r.brighten(1),i=i.darken(1),c=Je.contrastAPCA(t,r),l=Je.contrastAPCA(t,i);while(Math.abs(c)<60&&Math.abs(l)<60&&(!ce(r,a)||!ce(i,s)));return Math.abs(c)>Math.abs(l)?{hiContrast:Je(r.brighten(.4)).hex(),loContrast:r.hex()}:{hiContrast:Je(i.darken(.4)).hex(),loContrast:i.hex()}}const da=[`dashed`,`solid`,`dotted`],fa=[`none`,`normal`,`onormal`,`dot`,`odot`,`diamond`,`odiamond`,`crow`,`open`,`vee`];function applyCachedLayout(e,t){let{nodes:r,edges:i,hasManualLayout:a,...s}=e,c=new Map(r.map(e=>[e.id,e])),l=new Map(i.map(e=>[e.id,e])),u=t.nodes.map(e=>{let t=c.get(e.id);return t?{...t,x:e.x,y:e.y,width:e.width,height:e.height,labelBBox:e.labelBBox}:e}),p=t.edges.map(e=>{let t=l.get(e.id);return t?{...t,points:e.points,label:e.label,labelBBox:e.labelBBox,...e.controlPoints!=null&&{controlPoints:e.controlPoints},...e.isLabelCustomized!=null&&{isLabelCustomized:e.isLabelCustomized}}:e}),m={...t,...s,[Vi]:`layouted`,bounds:{...t.bounds},nodes:u,edges:p};return a?m[Ui]=`auto`:delete m[Ui],m}function buildElementNotations(e){return N(e,D(e=>!!e.notation),le(A(`notation`)),ae(ue(le(A(`shape`)),ae(ue(le(A(`color`)),ae(ue(p(A(`kind`)),E())),M(),p(([e,t])=>({kinds:t,color:e})))),M(),P(([e,t])=>t.map(({color:t,kinds:r})=>({shape:e,color:t,kinds:r}))))),M(),P(([e,t])=>t.map(({shape:t,color:r,kinds:i})=>({title:e,shape:t,color:r,kinds:i}))),Ee(A(`shape`),A(`title`),[e=>e.kinds.length,`desc`]))}const changed=(e,t)=>e===t||C(e)&&C(t)?!1:!ce(e,t);function autoApplyMetaAndStyles(e,t){e.color=t.color,e.kind=t.kind,e.navigateTo=t.navigateTo??null,e.links=t.links?[...t.links]:null,e.tags=[...t.tags],C(t.style.border)?delete e.style.border:e.style.border=t.style.border,x(t.style.opacity)?e.style.opacity=t.style.opacity:delete e.style.opacity,C(t.style.multiple)?delete e.style.multiple:e.style.multiple=t.style.multiple}function autoApplyIcon(e,t,r){if(changed(t.icon??`none`,e.icon??`none`)){let i=j(e.icon)&&e.icon!==`none`;switch(!0){case i&&j(t.icon)&&t.icon!==`none`:return e.icon=t.icon,!0;case i&&(C(t.icon)||t.icon===`none`):return e.icon=`none`,!0;case!i&&j(t.icon)&&t.icon!==`none`:return r?(e.icon=t.icon,!0):!1}}return!0}function autoApplyIconStyles(e,t,r){let i=!0;return changed(e.style.iconColor,t.style.iconColor)&&(C(t.style.iconColor)?delete e.style.iconColor:e.style.iconColor=t.style.iconColor),changed(e.style.iconSize,t.style.iconSize)&&(r?C(t.style.iconSize)?delete e.style.iconSize:e.style.iconSize=t.style.iconSize:i=!1),changed(e.style.iconPosition,t.style.iconPosition)&&(r?C(t.style.iconPosition)?delete e.style.iconPosition:e.style.iconPosition=t.style.iconPosition:i=!1),i}function patchMarkdownOrString(e,t){return e?`md`in t?(e.md=t.md,delete e.txt,e):(`txt`in t&&(e.txt=t.txt,delete e.md),e):t}function autoApplyLabelsToLeaf(e,t,r){let i=!0;return changed(e.title,t.title)&&(r?e.title=t.title:i=!1),changed(e.description,t.description)&&(C(t.description)?delete e.description:r?e.description=patchMarkdownOrString(e.description,t.description):i=!1),changed(e.technology,t.technology)&&(C(t.technology)?delete e.technology:r?e.technology=t.technology:i=!1),i}function autoApplyLabelsToCompound(e,t,r){return e.title=t.title,C(t.description)?delete e.description:e.description=patchMarkdownOrString(e.description,t.description),C(t.technology)?delete e.technology:e.technology=t.technology,!0}function applyManualLayout(e,t){invariant(e.id===t.id,`applyManualLayout: view ids do not match`),invariant(e._stage===`layouted`,`applyManualLayout: expected layouted view`),invariant(t._stage===`layouted`,`applyManualLayout: expected layouted snapshot`),invariant(e._layout!==`manual`,`applyManualLayout: expected auto-layouted view`);let r=/* @__PURE__ */ new Set;e._type!==t._type&&r.add(`type-changed`);let i=applyNodesManualLayout(t.nodes,e.nodes,r),a=applyEdgesManualLayout(t.edges,e.edges,r),s=buildElementNotations(i);return vt(t,c=>{c.title=e.title??t.title,c.description=e.description??t.description,c.tags=e.tags?[...e.tags]:null,c.links=e.links?[...e.links]:null,c.sourcePath=e.sourcePath,c[Ui]=`manual`,s&&s.length>0?c.notation={nodes:s}:delete c.notation,c.nodes=yt(i),c.edges=yt(a),isDynamicView$1(e)&&c._type===`dynamic`&&(c.variant=e.variant),e.routing?c.routing=e.routing:delete c.routing,isElementView$1(e)&&c._type===`element`&&(e.viewOf?c.viewOf=e.viewOf:delete c.viewOf,e.extends?c.extends=e.extends:delete c.extends);let l=[...r];k(l,1)?c.drifts=l:(c.hash=e.hash,delete c.drifts)})}function applyNodesManualLayout(e,t,r){let i=new Map(t.map(e=>[e.id,e])),a=e.map(e=>{let t=i.get(e.id);return t?(i.delete(t.id),vt(e,i=>{autoApplyMetaAndStyles(i,t);let a=/* @__PURE__ */ new Set,s=e.children.length>0,c=t.children.length>0;(changed(e.modelRef,t.modelRef)||changed(e.deploymentRef,t.deploymentRef))&&a.add(`modelRef-changed`),c&&!s&&a.add(`became-compound`),!c&&s&&a.add(`became-leaf`),changed(e.parent,t.parent)&&a.add(`parent-changed`);let l=e.width+5>=t.width&&e.height+5>=t.height;changed(e.shape,t.shape)&&(l?i.shape=t.shape:a.add(`shape-changed`)),autoApplyIconStyles(i,t,l)||a.add(`label-changed`),changed(e.style.sizing,t.style.sizing)&&(l?C(t.style.sizing)?delete i.style.sizing:i.style.sizing=t.style.sizing:a.add(`label-changed`)),autoApplyIcon(i,t,l&&c===s)||a.add(`label-changed`),(s?autoApplyLabelsToCompound:autoApplyLabelsToLeaf)(i,t,l)||a.add(`label-changed`),changed(i.notes,t.notes)&&(C(t.notes)?delete i.notes:i.notes=patchMarkdownOrString(i.notes,t.notes)),changed(e.notation,t.notation)&&(i.notation=t.notation??null),s&&c&&symmetricDifference(new Set(e.children),new Set(t.children)).size>0&&a.add(`children-changed`);let u=[...a];k(u,1)?(r.add(`nodes-drift`),i.drifts=u):delete i.drifts})):(r.add(`nodes-removed`),{...e,drifts:[`removed`]})});return i.size>0&&r.add(`nodes-added`),a}function applyEdgesManualLayout(e,t,r){let i=new Map(t.map(e=>[e.id,e])),a=e.map(e=>{let t=i.get(e.id)??N(i.values(),ifilter(t=>t.source===e.source&&t.target===e.target),ihead());return t&&i.delete(t.id),vt(e,i=>{if(!t){i.drifts=[`removed`],r.add(`edges-removed`);return}let a=/* @__PURE__ */ new Set,s=e.id===t.id;switch(!0){case s&&e.source==t.source&&e.target==t.target:changed(i.dir??`forward`,t.dir??`forward`)&&a.add(`direction-changed`);break;case s&&e.source==t.target&&e.target==t.source:e.source!==e.target&&a.add(`direction-changed`);break;case s:e.source!=t.source&&a.add(`source-changed`),e.target!=t.target&&a.add(`target-changed`);break;default:invariant(e.id!=t.id,`Unexpected case in edge drift detection, ids should not match`),invariant(e.source==t.source,`Unexpected case in edge drift detection, sources should match`),invariant(e.target==t.target,`Unexpected case in edge drift detection, targets should match`),changed(i.dir??`forward`,t.dir??`forward`)&&a.add(`direction-changed`)}i.color=t.color,i.line=t.line,t.head!==void 0&&(i.head=t.head),t.tail!==void 0&&(i.tail=t.tail),t.kind!==void 0&&(i.kind=t.kind),i.navigateTo=t.navigateTo??null,i.tags=t.tags?[...t.tags]:null,i.relations=[...t.relations],changed(e.notes,t.notes)&&(C(e.notes)!==C(t.notes)&&a.add(`notes-changed`),i.notes=t.notes??e.notes),t.astPath?i.astPath=t.astPath:delete i.astPath;let c=Ge(e,[`label`,`description`,`technology`,`labelBBox`]),l=Ge(t,[`label`,`description`,`technology`,`labelBBox`]);if(changed(c,l))switch(!0){case t.labelBBox&&!e.labelBBox:a.add(`label-added`);break;case e.labelBBox&&!t.labelBBox:a.add(`label-removed`);break;case!!e.labelBBox&&!!t.labelBBox:t.labelBBox.width*t.labelBBox.height>(e.labelBBox.width+5)*(e.labelBBox.height+5)&&(i.labelBBox.width=Math.round(t.labelBBox.width),i.labelBBox.height=Math.round(t.labelBBox.height)),changed(e.label,t.label)&&(C(t.label)!==C(e.label)&&a.add(`label-changed`),i.label=t.label??e.label),changed(e.description,t.description)&&(C(t.description)!==C(e.description)&&a.add(`label-changed`),t.description&&(i.description=patchMarkdownOrString(i.description,t.description))),changed(e.technology,t.technology)&&(C(t.technology)!==C(e.technology)&&a.add(`label-changed`),i.technology=t.technology??e.technology??null);break;default:invariant(!e.labelBBox,`Unexpected case in edge labelBBox drift detection`),invariant(!t.labelBBox,`Unexpected case in next labelBBox drift detection`)}let u=[...a];k(u,1)?(r.add(`edges-drift`),i.drifts=u):delete i.drifts})});return i.size>0&&r.add(`edges-added`),a}function calcDriftsFromSnapshot(e,t){let{drifts:r,...i}=applyManualLayout(e,t);if(!r||r.length===0)return vt(e,e=>{delete e.drifts,e[Ui]=`auto`});let a=/* @__PURE__ */ new Set;r.includes(`type-changed`)&&a.add(`type-changed`);let s=new Map(i.nodes.map(e=>[e.id,e])),c=new Map(i.edges.map(e=>[e.id,e])),l=e.nodes.map(e=>{let t=s.get(e.id);return t&&s.delete(t.id),vt(e,e=>{t?t.drifts?(a.add(`nodes-drift`),e.drifts=[...t.drifts]):delete e.drifts:(a.add(`nodes-added`),e.drifts=[`added`])})});s.size>0&&a.add(`nodes-removed`);let u=e.edges.map(e=>{let t=c.get(e.id)??N(c.values(),ifilter(t=>t.source===e.source&&t.target===e.target),ihead());return t&&c.delete(t.id),vt(e,e=>{t?t.drifts?(a.add(`edges-drift`),e.drifts=[...t.drifts]):delete e.drifts:(a.add(`edges-added`),e.drifts=[`added`])})});c.size>0&&a.add(`edges-removed`);let p=[...a];return vt(e,e=>{k(p,1)?e.drifts=p:delete e.drifts,e.nodes=yt(l),e.edges=yt(u),e[Ui]=`auto`})}function serializeValue(e,t,r,i){if(typeof e?.toJSON==`function`&&(e=e.toJSON()),!(typeof e==`object`&&e))return e;if(t.has(e)){if(!r)return`[Circular]`;let i=t.get(e);return`[Circular ${i===``?`*`:`*${i}`}]`}t.set(e,i);let a=Array.isArray(e)?[]:{};for(let[s,c]of Object.entries(e))a[s]=serializeValue(c,t,r,i===``?s:`${i}.${s}`);return t.delete(e),a}function safeStringify(e,{indentation:t,trace:r}={}){let i=serializeValue(e,/* @__PURE__ */ new WeakMap,r,``);return JSON.stringify(i,void 0,t)}const parseStack=e=>e.split(`
|
|
13
|
+
`).map(e=>e.trimEnd().replace(`file://`,``).replace(/[A-Za-z]:\\Users\\[^\\]+\\/i,`@vscode\\`).replace(/\/Users\/[^/]+\//,`@vscode/`));function indent$1(e,t=2){e=Array.isArray(e)?e:e.split(`
|
|
14
|
+
`);let r=typeof t==`string`?t:` `.repeat(t);return e.map(e=>`${r}${e}`).join(`
|
|
15
|
+
`)}e(indent$1,`indent`);function loggable(e){if(typeof e==`string`)return e;if(isError$1(e)){let t=_t(e);if(t.stack){let e=parseStack(t.stack);return t.message+`
|
|
16
|
+
`+indent$1(e.slice(1),` `)}return t.message}return safeStringify(e,{indentation:` `})}function wrapError(e,t){return gt(e,t)}function isError$1(e){return e instanceof Error}e(isError$1,`isError`);function getErrorFromLogRecord(e){let t=Object.entries(e.properties).flatMap(([e,t])=>{if(t instanceof Error){let e=_t(t);return e.stack&&=parseStack(e.stack).join(`
|
|
17
|
+
`),[e]}return e===`error`||e===`err`?[Error(loggable(t))]:[]});return t.length===0?null:t.length===1?t[0]:AggregateError(t)}function errorFromLogRecord(e){let t=getErrorFromLogRecord(e);return t&&typeof e.rawMessage==`string`?gt(t,e.rawMessage+`
|
|
18
|
+
`):t}function appendErrorToMessage(e,t=!1){let r=getErrorFromLogRecord(e.record);if(r){let i=`
|
|
19
|
+
`+indent$1(r.stack||r.message,` `);return t&&(i=`${ma}${ha.red}${i}${ma}`),{...e,message:e.message+i}}return e}const pa={trace:`TRACE`,debug:`DEBUG`,info:`INFO `,warning:`WARN `,error:`ERROR`,fatal:`FATAL`};function getMessageOnlyFormatter(){return getTextFormatter({format:({message:e})=>e})}const level=e=>pa[e];function getTextFormatter(e){let t=e?.format??(({timestamp:e,level:t,category:r,message:i})=>`${e} ${t} ${r} ${i}`);return bt({timestamp:`time`,level,category:`.`,...e,format:e=>t(appendErrorToMessage(e))})}const ma=`\x1B[0m`,ha={red:`\x1B[31m`};function getAnsiColorFormatter(e){let t=e?.format??(({timestamp:e,level:t,category:r,message:i})=>`${e} ${t} ${r} ${i}`);return xt({timestamp:`time`,level,categoryStyle:`bold`,categoryColor:`cyan`,category:`.`,levelColors:{trace:`black`,debug:`blue`,info:`green`,warning:`yellow`,error:`red`,fatal:`magenta`},...e,format:e=>t(appendErrorToMessage(e,!0))})}function getConsoleFormatter(e){let t=e?.messageFormatter;return t?e=>{let{properties:r}=e;return r&&Object.keys(r).length>0?[t(e),r]:[t(e)]}:wt}function getConsoleSink(e){return St({formatter:getConsoleFormatter(),...e})}function getConsoleStderrSink(e){let t=e?.formatter??getConsoleFormatter();return e=>{let r=t(e);if(typeof r==`string`){let e=r.replace(/\r?\n$/,``);console.error(e)}else console.error(...r)}}const ga=Ct(`likec4`);function createLogger(e){return ga.getChild(e)}function configureLogger$1(e){try{let{sinks:t={},loggers:r,...i}=e??{},a={console:getConsoleSink(),...t};Tt({reset:!0,...i,sinks:a,loggers:[{category:[`logtape`,`meta`],sinks:[`console`],lowestLevel:`warning`},...e?.loggers??[{category:`likec4`,sinks:[`console`],lowestLevel:`debug`}]]})}catch(e){console.error(e)}}e(configureLogger$1,`configureLogger`);const paddingFromNumber=e=>({left:e,right:e,top:e,bottom:e});function normalizeSpacing(e=16){return typeof e==`number`?paddingFromNumber(e):{left:e?.left??e?.x??0,right:e?.right??e?.x??0,top:e?.top??e?.y??0,bottom:e?.bottom??e?.y??0}}function rectFromSteps(e){return invariant(e.length>0),e.reduce((e,t)=>{let r=[t.from.column,t.to.column],i=[t.from.row,t.to.row];return e.min.column=Math.min(e.min.column,...r),e.min.row=Math.min(e.min.row,...i),e.max.column=Math.max(e.max.column,...r),e.max.row=Math.max(e.max.row,...i),e},{min:{column:1/0,row:1/0},max:{column:-1/0,row:-1/0}})}function buildCompounds(e,t){if(e.length===0||e.length===t.length)return[];let getNode=e=>t.find(t=>t.id===e);function parentsLookup(e){let t=e.parent&&getNode(e.parent);return t?[t,...parentsLookup(t)]:[]}let r=new et.default,i=[];return e.forEach(e=>{let t=parentsLookup(e);if(t.length===0){r.clear();return}let a,s=t[0];for(;a=r.peek()?.node;){if(!s||a.id===s.id){t.length=0;break}if(!isAncestor(a.id,s.id))r.pop();else break}for(;a=t.pop();){let t=r.peek();if(t&&(isAncestor(a.id,t.node.id)||a.id===t.node.id))continue;let s={node:a,from:e,to:e,nested:[]};t?t.nested.push(s):i.push(s),r.push(s)}r.forEach(t=>t.to=e)}),i}const G={required:Dt.required,strong:Dt.strong,medium:Dt.medium,soft:Dt.create(0,.8,1),weak:Dt.weak};var SequenceViewLayouter=class{#e;#t=new At;#n;#r=[];#i;#a;#o;#s=[];#c=/* @__PURE__ */ new Map;constructor({actors:e,steps:t,compounds:r,flow:i,collapsedFlows:a}){this.#t.maxIterations=2e3,this.#e=i;let s=Math.max(...e.map(e=>e.height))+30;this.#o=this.newVar(s),this.constraint(this.#o,`==`,s,G.soft),this.constraint(this.#o,`>=`,s,G.weak),this.#i=this.newVar(0),this.#a=this.newVar(0),this.#n=this.addActors(e);for(let e of r){let t=this.addCompound(e),r=t[0];this.constraint(r.y1,`==`,0,G.strong),this.put(this.#o,G.strong).after(r.y2),this.#r.push(...t)}let[c,...l]=this.#n;this.constraint(c.offset.left,`==`,0,G.strong);let u=l.reduce((e,t)=>(this.put(t.x).after(e.right,80),this.put(e.offset.right,G.strong).before(t.offset.left,50),this.constraint(t.centerY,`==`,e.centerY,G.strong),t),c);for(let e of t)this.addStep(e);this.createSubflowAreas(t,new Set(a)),this.constraint(this.#i,`==`,u.offset.right);let p=te(this.#s)?.inner.bottom??this.#o;if(this.put(this.#a,G.strong).after(p,16),r.length>0)for(let e of this.#r){let t=e.from.column,r=e.to.column,i=Math.max(e.from.maxRow,e.to.maxRow);for(let e=t+1;e<r;e++){let t=this.actorBox(e);i=Math.max(i,t.maxRow)}let a=nonNullable(this.#s[i],`row ${i} not found`);this.put(e.bottom,G.strong).after(a.inner.bottom,10)}this.#t.updateVariables()}getSubflowAreas(){return[...this.#c.entries()].map(([e,{x1:t,y1:r,x2:i,y2:a}])=>({id:e,x:t.value(),y:r.value(),width:i.value()-t.value(),height:a.value()-r.value()}))}getActorBox(e){let t=this.actorBox(e);return{x:t.x.value(),y:t.y.value(),width:t.width,height:t.height}}getCompoundBoxes(){return this.#r.map(({node:e,depth:t,x1:r,y1:i,x2:a,bottom:s})=>({node:e,depth:t,x:r.value(),y:i.value(),width:a.value()-r.value(),height:s.value()-i.value()}))}getPortCenter(e,t){let{column:r,row:i}=t===`source`?e.from:e.to,a=this.actorBox(r).centerX,{rowTop:s}=nonNullable(this.#s[i]);return e.isSelfLoop&&t===`target`?{cx:a.value(),cy:s.value(),height:24}:{cx:a.value(),cy:s.value()+40+e.offset,height:t===`source`?40:24}}isStepCollapsed(e){if(e.from.row===e.to.row)return this.#s[e.from.row]?.collapsed??!1;let t=Math.min(e.from.row,e.to.row),r=Math.min(e.from.row,e.to.row),i=!0;for(let e=t;e<=r&&(i&&=this.#s[e]?.collapsed??!1,i);e++);return i}getViewBounds(){return{x:0,y:0,width:this.#i.value(),height:this.#a.value()}}actorBox(e){if(typeof e!=`number`){let t=typeof e==`string`?e:e.id;e=this.#n.findIndex(e=>e.actor.id===t),invariant(e>=0,`actor ${t} not found`)}return nonNullable(this.#n[e],`actor at index ${e} not found`)}addActors(e){let t=0;return p(e,(e,r)=>{let i=this.newVar(t);t+=e.width+80;let a=this.newVar(0),s={column:r,actor:e,x:i,y:a,centerX:i.plus(Math.round(e.width/2)),centerY:a.plus(Math.round(e.height/2)),width:e.width,height:e.height,right:i.plus(e.width),bottom:a.plus(e.height),minRow:1/0,maxRow:-1/0},c=this.newVar(0),l=this.newVar(0),u=this.newVar(0),p=this.newVar(0);return this.put(a,G.strong).after(c),this.put(i,G.strong).after(l),this.put(s.right,G.strong).before(u),this.put(s.bottom,G.strong).before(p),{...s,offset:{top:c,left:l,right:u,bottom:p}}})}addStep(e){let t=this.actorBox(e.source),r=this.actorBox(e.target);t.minRow=Math.min(t.minRow,e.from.row),t.maxRow=Math.max(t.maxRow,e.from.row),r.minRow=Math.min(r.minRow,e.to.row),r.maxRow=Math.max(r.maxRow,e.to.row);let[i,a]=t.column<=r.column?[t,r]:[r,t],s=(e.label?.width??100)+50;Math.abs(r.column-t.column)<=1&&(i===a?this.constraint(i.centerX.plus(s),`<=`,i.offset.right):this.constraint(i.centerX.plus(s),`<=`,a.centerX));let c=e.label?.height?e.label.height+50+24:100;return c=Math.max(c,100)+e.offset,this.ensureRow(e.from.row,c),e.to.row!==e.from.row&&this.ensureRow(e.to.row,24),this}addCompound(e){let t=[],r=e.nested.flatMap(e=>{let r=this.addCompound(e);return t.push(r[0]),r}),i=Math.max(...r.map(e=>e.depth+1),0),a=this.actorBox(e.from),s=this.actorBox(e.to),c=a.offset.left.minus(32);a.offset.left=c;let l=s.offset.right.plus(32);s.offset.right=l;let u=this.newVar(0),p=F(t),m,h;switch(!0){case!!p:m=p.y1.minus(40),h=p.y2.plus(32),this.put(p.bottom).before(u,32);break;case s===a:m=this.newVar(0),h=this.newVar(0),this.put(m).before(a.offset.top,52),this.put(a.offset.bottom).before(h,32),this.put(h).before(u);break;case t.length>0:m=this.newVar(0),h=this.newVar(0);for(let e of t)this.put(m).before(e.y1,32),this.put(e.y2).before(h,32),this.put(e.bottom).before(u,32);break;default:m=this.newVar(0),h=this.newVar(0);for(var g=a.column;g<=s.column;g++){let e=this.actorBox(g).offset;this.put(m).before(e.top,52),this.put(e.bottom).before(h,32)}this.put(h).before(u)}for(var g=a.column;g<=s.column;g++){let e=this.actorBox(g).offset;e.top=m,e.bottom=h}return[{node:e.node,depth:i,from:a,to:s,x1:c,y1:m,x2:l,y2:h,bottom:u},...r]}ensureRow(e,t){for(;e>=this.#s.length;){let r=te(this.#s)?.outer.bottom||this.#o,i=this.newVar(r.value());this.put(i).after(r);let a=t;e!==this.#s.length&&(a=100);let s=new Et;s.setValue(a),this.#t.addEditVariable(s,G.strong),this.#t.suggestValue(s,a);let c=this.newVar(i.value()+a);this.require(c).after(i),this.constraint(c.minus(i),`==`,s,G.strong);let l=this.newVar(c.value());this.put(l).after(c),this.#s.push({inner:{top:i,bottom:c},rowTop:i,outer:{top:r,bottom:l},height:s})}let r=nonNullable(this.#s[e]);return t>r.height.value()&&(r.height.setValue(t),this.#t.suggestValue(r.height,t)),r}collapseRect({min:e,max:t}){for(let r=e.row;r<=t.row;r++){let e=nonNullable(this.#s[r],`Row ${r} not found`);e.collapsed=!0,e.height.setValue(0),this.#t.suggestValue(e.height,0)}}getRectBounds({min:e,max:t}){let r=this.#s[e.row],i=this.#s[t.row];return invariant(r&&i,`Subflow box invalid minRow=${e.row} maxRow=${t.row}`),{x1:this.actorBox(e.column).centerX,x2:this.actorBox(t.column).centerX,get top(){return r.inner.top},set top(e){r.inner.top=e},get bottom(){return i.inner.bottom},set bottom(e){i.inner.bottom=e},minY:r.outer.top,maxY:i.outer.bottom}}wrapAroundRect(e,t){let r=normalizeSpacing(t??16),i=this.getRectBounds(e),a=this.newVar(0);this.put(a).before(i.x1,r.left);let s=this.newVar(0);this.put(s).after(i.x2,r.right);let c=this.newVar(i.minY.value());this.require(c).after(i.minY),this.put(c).before(i.top,r.top);let l=this.newVar(i.maxY.value());return this.put(l).after(i.bottom,r.bottom),this.require(l).before(i.maxY),i.top=c,i.bottom=l,{x1:a,y1:c,x2:s,y2:l}}createSubflowAreas(e,t){let selectSteps=t=>D(e,e=>e.id.startsWith(t)),r={top:30,right:40,bottom:10,left:90},fitSubflows=({area:e,visited:t,stretch:i=!1,padding:a})=>{let s=N(t,D(ea.isSubFlow),P(e=>this.#c.get(e.id)??[]));if(!k(s,1))return;let c=Yi(a,r),l=fe(s),u=te(s);l.min.row==e.min.row&&this.require(e.y1).before(l.y1,c.top),u.max.row==e.max.row&&this.require(u.y2).before(e.y2,c.bottom);for(let t of s)this.require(t.x1).after(e.x1,c.left),this.require(t.x2).before(e.x2,c.right),i&&(t.x1=c.left>0?e.x1.plus(c.left):e.x1,t.x2=c.right>0?e.x2.minus(c.right):e.x2)},createSubflowArea=e=>{let i=rectFromSteps(selectSteps(e.id)),a;switch(!0){case ea.isAltOrTry(e):a=0;break;case t.has(e.id)&&ea.isAltOrTryBranch(e):a={...r,top:36,bottom:0};break;case t.has(e.id):a={...r,top:24,bottom:0};break;default:a=r}let s={...this.wrapAroundRect(i,a),...i};return this.#c.set(e.id,s),s};this.#e.walk({subflow:({subflow:e,previous:r,parent:i})=>({next:t.has(e.id)?[]:e.flow,onLeave:({visited:a})=>{let s=createSubflowArea(e),c=ea.isSubFlow(r)&&this.#c.get(r.id);switch(!ea.isAltOrTryBranch(e)&&c&&this.put(c.y2).before(s.y1,32),!i&&s.min.column>0&&this.require(this.actorBox(s.min.column-1).centerX).before(s.x1,100),!0){case t.has(e.id):this.collapseRect(s);return;case ea.isAltOrTry(e):return fitSubflows({area:s,visited:a,padding:{top:30,left:0,right:0},stretch:!0});case ea.isAltOrTryBranch(e):return fitSubflows({area:s,visited:a,padding:{top:50,left:32,bottom:32,right:32}});default:return fitSubflows({area:s,visited:a,padding:{top:40,bottom:12,left:32,right:16}})}}})})}newVar(e){let t=new Et;return this.#t.addEditVariable(t,G.weak),typeof e==`number`&&(t.setValue(e),this.#t.suggestValue(t,e)),t}require(...e){if(e.length==1){let[t]=e;return{before:(e,r=0)=>{let i=r?e.minus(r):e;return this.constraint(t,`<=`,i,G.required)},after:(e,r=0)=>{let i=r?e.plus(r):e;return this.constraint(t,`>=`,i,G.required)}}}let[t,r,i]=e,a=this.constraint(t,r,i,G.required);switch(r){case`<=`:case`>=`:this.constraint(t,`==`,i,G.weak);break;case`<= 0`:case`>= 0`:this.constraint(t,`== 0`,void 0,G.weak)}return a}constraint(e,t,r=void 0,i=G.medium){let a;switch(t){case`==`:a=kt.Eq;break;case`>=`:a=kt.Ge;break;case`<=`:a=kt.Le;break;case`== 0`:a=kt.Eq,r=0;break;case`>= 0`:a=kt.Ge,r=0;break;case`<= 0`:a=kt.Le,r=0;break;default:nonexhaustive(t)}let s=new Ot(e,a,r??0,i);return this.#t.addConstraint(s),s}put(e,t=G.required){let r=t===G.required?G.soft:G.weak;return{before:(i,a)=>{a&&(i=i.minus(a)),this.constraint(e,`<=`,i,t),this.constraint(e,`==`,i,r)},after:(i,a)=>{a&&(i=i.plus(a)),this.constraint(e,`>=`,i,t),this.constraint(e,`==`,i,r)}}}};function calcSequenceLayout(e){let t=dynamicViewFlow(e),r=/* @__PURE__ */ new Set,getNode=t=>nonNullable(e.nodes.find(e=>e.id===t)),i=[];for(let t of e.edges){let e=getNode(t.source),a=getNode(t.target);e.children.length||a.children.length?console.error(`Sequence view does not support nested actors`):(r.add(e),r.add(a),i.push({edge:t,source:e,target:a}))}let a=e.nodes.filter(e=>r.has(e));if(invariant(a.length===r.size,`actors array must match actorNodes size`),i.length===0||!k(a,1))return{actors:[],steps:[],compounds:[],parallelAreas:[],subflows:[],bounds:{x:0,y:0,width:0,height:0}};let s=new I.default(()=>[]),c=[],l=0,u;for(let{edge:e,source:t,target:r}of i){let i=a.indexOf(t),p=a.indexOf(r),m=t===r,h=i>p,g=parentFlow(e.id),_=!1;u&&u.target==t&&u.parent===g&&(_=u.isSelfLoop!==m||u.isBack===h),!_&&u&&l++;let v={id:e.id,from:{column:i,row:l},to:{column:p,row:m?++l:l},edge:e,isSelfLoop:m,isBack:h,parent:g,offset:_?(u?.offset??0)+22:0,source:t,target:r,label:e.labelBBox?{height:e.labelBBox.height+8+(e.navigateTo?20:0),width:e.labelBBox.width+16,text:e.label}:null};c.push(v),s.get(t).push({step:v,row:l,type:`source`,position:h&&!m?`left`:`right`}),s.get(r).push({step:v,row:l,type:`target`,position:h||m?`right`:`left`}),u=v}let m=new SequenceViewLayouter({actors:a,steps:c,compounds:buildCompounds(a,e.nodes),flow:t,collapsedFlows:[]}),h=m.getViewBounds(),g=N(m.getCompoundBoxes(),p(({node:e,...t})=>({...t,id:e.id,origin:e.id})),se(`id`),ae((e,t)=>k(e,2)?p(e,(e,r)=>({...e,id:`${t}-${r+1}`})):e),Fe(),we());return{actors:a.map(e=>toSeqActor({actor:e,ports:s.get(e),layout:m})),compounds:g,steps:p(c,e=>({id:e.id,sourceHandle:e.id+`_source`,targetHandle:e.id+`_target`,...e.label&&{labelBBox:{width:e.label.width,height:e.label.height}}})),parallelAreas:[],subflows:m.getSubflowAreas(),bounds:h}}function toSeqActor({actor:e,ports:t,layout:r}){let{x:i,y:a,width:s,height:c}=r.getActorBox(e);return{id:e.id,x:i,y:a,width:s,height:c,ports:t.map(e=>{let t=r.getPortCenter(e.step,e.type);return{id:`${e.step.id}_${e.type}`,cx:t.cx-i,cy:t.cy-a,height:t.height,type:e.type,position:e.position}})}}const K=new Proxy(Object.freeze({}),{get:(e,t)=>t});function f(e,t){return(...r)=>{let i=e?this.Digraph:this.Graph,a=r.find(e=>typeof e==`string`),s=r.find(e=>typeof e==`object`),c=r.find(e=>typeof e==`function`),l=new i(a,t,s);return l.with(this),typeof c==`function`&&c(l),l}}function n(e,t=Nt){return Object.freeze({digraph:f.call(t,!0,e),graph:f.call(t,!1,e)})}const _a=n(!1),va=_a.digraph;_a.graph,n(!0);function O(e,t){let r=Pt(e,t?.convert);return Mt(r,t?.print)}jt()
|
|
20
|
+
/*!
|
|
21
|
+
* word-wrap <https://github.com/jonschlinkert/word-wrap>
|
|
22
|
+
*
|
|
23
|
+
* Copyright (c) 2014-2023, Jon Schlinkert.
|
|
24
|
+
* Released under the MIT License.
|
|
25
|
+
*/
|
|
26
|
+
;var ya=/* @__PURE__ */ r((/* @__PURE__ */ i(((e,t)=>{function trimEnd(e){let t=e.length-1,r=e[t];for(;r===` `||r===` `;)r=e[--t];return e.substring(0,t+1)}function trimTabAndSpaces(e){return e.split(`
|
|
27
|
+
`).map(e=>trimEnd(e)).join(`
|
|
28
|
+
`)}t.exports=function(e,t){if(t||={},e==null)return e;var r=t.width||50,i=typeof t.indent==`string`?t.indent:` `,a=t.newline||`
|
|
29
|
+
`+i,s=typeof t.escape==`function`?t.escape:identity,c=`.{1,`+r+`}`;t.cut!==!0&&(c+=`([\\s]+|$)|[^\\s]+?([\\s]+|$)`);var l=new RegExp(c,`g`),u=i+(e.match(l)||[]).map(function(e){return e.slice(-1)===`
|
|
30
|
+
`&&(e=e.slice(0,e.length-1)),s(e)}).join(a);return t.trim===!0&&(u=trimTabAndSpaces(u)),u};function identity(e){return e}})))(),1);function isCompound(e){return e.children.length>0}function toArrowType(e){switch(e){case`open`:return`vee`;default:return e}}function pointToPx(e){return Array.isArray(e)?[pointToPx(e[0]),pointToPx(e[1])]:(invariant(isFinite(e),`Invalid not finite point value ${e}`),Math.round(e))}const inchToPx=e=>(invariant(isFinite(e),`Invalid not finite inch value ${e}`),Math.floor(e*72)),pxToInch=e=>Math.ceil(e/72*1e3)/1e3,pxToPoints=e=>Math.ceil(e);pxToPoints(40).toString();function compoundColor(e,t){return It(Lt(e,{l:-35-5*t,s:-15-5*t}))}function compoundLabelColor(e){return It(Ft(e,.3))}function sanitize(e){return e.trim().replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function wrap(e,{maxchars:t,maxLines:r,sanitize:i=y(),cut:a=!1}){let s=(0,ya.default)(e,{width:t,indent:``,escape:i,cut:a}).split(`
|
|
31
|
+
`);return T(r)&&r>0&&s.length>r&&(s=s.slice(0,r)),s}function wrapWithFont({text:e,maxchars:t,fontsize:r,maxLines:i,bold:a,color:s,cut:c}){let l=wrap(e,{maxchars:t,maxLines:i,sanitize,cut:c}).join(`<BR/>`);a&&(l=`<B>${l}</B>`);let u=s?` COLOR="${s}"`:``;return`<FONT POINT-SIZE="${pxToPoints(r)}"${u}>${l}</FONT>`}function maxchars(e){switch(e){case`xs`:case`sm`:return 30;case`md`:return 40;case`lg`:case`xl`:return 55;default:nonexhaustive(e)}}function nodeLabel(e,t){let{sizes:{size:r},values:i}=t.nodeSizes(e.style),a=t.colors(e.color).elements,s=[`sm`,`xs`].includes(r),c=j(e.icon),l=e.style.iconPosition??`left`,u=c&&(l===`left`||l===`right`),p=e.style.sizing===`fixed`,m=p?t.fitNodeContent(e):null,h=m?.textSize??i.textSize,g=m?.iconSize??i.iconSize,_=[wrapWithFont({text:e.title,fontsize:h,maxchars:m?.maxchars??maxchars(r),maxLines:m?.maxLines??(s?1:3),cut:p})],secondaryMaxchars=e=>{let t=Math.ceil(h*e);return p?Math.max(1,Math.floor((m?.maxchars??1)*h/t)):u?35:45};if(r!==`xs`){j(e.technology?.trim())&&_.push(wrapWithFont({text:e.technology,fontsize:Math.ceil(h*.65),maxchars:secondaryMaxchars(.65),maxLines:1,cut:p,color:a.loContrast}));let t=sa.from(e.description).text;t&&_.push(wrapWithFont({text:t,fontsize:Math.ceil(h*.75),maxchars:secondaryMaxchars(.75),maxLines:p?1:s?3:5,cut:p,color:a.loContrast}))}if(_.length===1&&c===!1)return`<${_[0]}>`;let v=u?(t,r,i)=>{let a=`<TD ALIGN="TEXT" BALIGN="LEFT">${t}</TD>`;if(r===0){let t=i.length>1?` ROWSPAN="${i.length}"`:``,r=Math.ceil(g+16);(e.shape===`queue`||e.shape===`mobile`)&&(r+=20),l===`right`?(a=`<TD${t} WIDTH="16"> </TD>${a}`,a=`${a}<TD${t} WIDTH="${r}"> </TD>`):(a=`<TD${t} WIDTH="${r}"> </TD>${a}`,a=`${a}<TD${t} WIDTH="16"> </TD>`)}return`<TR>${a}</TR>`}:e=>`<TR><TD>${e}</TD></TR>`,y=_.map(v).join(``);if(c&&(l===`top`||l===`bottom`)){let e=`<TR><TD HEIGHT="${Math.ceil(g+8)}"> </TD></TR>`;y=l===`top`?`${e}${y}`:`${y}${e}`}return`<<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="4">${y}</TABLE>>`}function compoundLabel(e,t){let r=wrapWithFont({text:e.title.toUpperCase(),maxchars:50,fontsize:11,maxLines:1,bold:!0,color:t});return r.includes(`<BR/>`)?`<<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0"><TR><TD ALIGN="TEXT" BALIGN="LEFT">${r}</TD></TR></TABLE>>`:`<${r}>`}const ba=`BGCOLOR="${$i.DEFAULT.relationshipColors.labelBg}A0"`;function edgelabel({label:e,technology:t}){let r=[];if(j(e?.trim())&&r.push(wrapWithFont({text:e,maxchars:40,fontsize:14,maxLines:5,bold:e===`[...]`})),j(t?.trim())&&r.push(wrapWithFont({text:`[ ${t} ]`,fontsize:12,maxLines:1,maxchars:40})),r.length===0)return null;let i=r.map(e=>`<TR><TD ALIGN="TEXT" BALIGN="LEFT">${e}</TD></TR>`).join(``);return`<<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="0" ${ba}>${i}</TABLE>>`}function stepEdgeLabel(e,t){let r=`<TABLE BORDER="0" CELLPADDING="6" ${ba}><TR><TD WIDTH="20" HEIGHT="20"><FONT POINT-SIZE="${pxToPoints(14)}"><B>${e}</B></FONT></TD></TR></TABLE>`;return j(t?.trim())?`<${[`<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">`,`<TR>`,`<TD>${r}</TD>`,`<TD ${ba} CELLPADDING="3">`,wrapWithFont({text:t,maxchars:40,fontsize:14,maxLines:5}),`</TD>`,`</TR>`,`</TABLE>`].join(``)}>`:`<${r}>`}var xa=tt(),Sa=/* @__PURE__ */ r(nt(),1);const Ca=`Arial`,wa=createLogger(`dot`);var DotPrinter=class{view;styles;ids=/* @__PURE__ */ new Set;subgraphs=/* @__PURE__ */ new Map;nodes=/* @__PURE__ */ new Map;edges=/* @__PURE__ */ new Map;compoundIds;edgesWithCompounds;viewNodes=new I.default(e=>nonNullable(this.view.nodes.find(t=>t.id===e),`Node ${e} not found`));logger=wa;graphology=new Rt({allowSelfLoops:!0,multi:!0,type:`directed`});G;constructor(e,t){this.view=e,this.styles=t,this.compoundIds=new Set(e.nodes.filter(isCompound).map(e=>e.id)),this.edgesWithCompounds=new Set(this.compoundIds.size>0?e.edges.filter(e=>this.compoundIds.has(e.source)||this.compoundIds.has(e.target)).map(e=>e.id):[]);for(let t of e.nodes)this.graphology.addNode(t.id,{origin:t,level:t.level,depth:t.depth??0,modelRef:t.modelRef??null,deploymentRef:t.deploymentRef??null,maxConnectedHierarchyDistance:0});for(let t of e.edges){let e=this.graphology.getNodeAttribute(t.source,`deploymentRef`),r=this.graphology.getNodeAttribute(t.target,`deploymentRef`);(e===null||r===null)&&(e=this.graphology.getNodeAttribute(t.source,`modelRef`),r=this.graphology.getNodeAttribute(t.target,`modelRef`));let i=-1;e!==null&&r!==null&&(i=hierarchyDistance(e,r)),this.graphology.addEdgeWithKey(t.id,t.source,t.target,{origin:t,hierarchyDistance:i,weight:1}),i>this.graphology.getNodeAttribute(t.source,`maxConnectedHierarchyDistance`)&&this.graphology.mergeNodeAttributes(t.source,{maxConnectedHierarchyDistance:i}),i>this.graphology.getNodeAttribute(t.target,`maxConnectedHierarchyDistance`)&&this.graphology.mergeNodeAttributes(t.target,{maxConnectedHierarchyDistance:i})}this.graphology.forEachEdge((e,{hierarchyDistance:t},r,i,a,s)=>{let c=Math.max(a.maxConnectedHierarchyDistance,s.maxConnectedHierarchyDistance);if(c>t)this.graphology.mergeEdgeAttributes(e,{weight:c-t+1});else{let a=this.graphology.directedDegree(r),s=this.graphology.directedDegree(i);a===1&&s===1&&t>1&&this.graphology.mergeEdgeAttributes(e,{weight:t})}});let r=this.G=this.createGraph();this.applyNodeAttributes(r.attributes.node),this.applyEdgeAttributes(r.attributes.edge)}get $defaults(){return this.styles.defaults}get hasEdgesWithCompounds(){return this.edgesWithCompounds.size>0}get defaultRelationshipColors(){let e=this.styles.relationshipColors;return{line:e.line,label:e.label,labelBg:e.labelBg}}postBuild(e){}selectViewNodes(){return this.view.nodes}selectViewEdges(){return this.view.edges}build(){let e=this.G,t=[];for(let r of this.selectViewNodes())if(isCompound(r))C(r.parent)&&t.push(r);else{let t=this.generateGraphvizId(r),i=this.elementToNode(r,e.node(t));this.nodes.set(r.id,i)}let traverseClusters=(e,t)=>{let r=this.generateGraphvizId(e),i=this.elementToSubgraph(e,t.subgraph(r));this.subgraphs.set(e.id,i);for(let t of e.children){let e=this.computedNode(t);if(isCompound(e))traverseClusters(e,i);else{let t=this.getGraphNode(e.id);t&&i.node(t.id)}}};for(let r of t)traverseClusters(r,e);for(let t of this.selectViewEdges()){let r=this.addEdge(t,e);r&&this.edges.set(t.id,r)}return this}print(){return this.build(),this.postBuild(this.G),O(this.G,{print:{indentStyle:`space`,indentSize:2}})}enableNewRankIfNeeded(){return this.G.subgraphs.some(e=>!!e.get(K.rank))&&this.G.set(K.newrank,!0),this}get isOrtho(){return this.view.routing===`ortho`}edgeLabelAttr(e){return e||this.isOrtho?K.xlabel:K.label}createGraph(){let e=this.view.autoLayout,t=e.direction,r=va({[K.likec4_viewId]:this.view.id,[K.bgcolor]:`transparent`,[K.layout]:`dot`,[K.compound]:!0,[K.rankdir]:t,[K.TBbalance]:`min`,[K.splines]:this.isOrtho?`ortho`:`spline`,[K.outputorder]:`nodesfirst`,[K.nodesep]:pxToInch(e.nodeSep??110),[K.ranksep]:pxToInch(e.rankSep??120),[K.pad]:pxToInch(15),[K.fontname]:Ca});return r.attributes.graph.apply({[K.fontsize]:pxToPoints(this.styles.fontSize()),[K.labeljust]:t===`RL`?`r`:`l`,[K.labelloc]:t===`BT`?`b`:`t`,[K.margin]:50.1}),r}applyNodeAttributes(e){let t=this.styles.elementColors;e.apply({[K.fontname]:Ca,[K.shape]:`rect`,[K.fillcolor]:t.fill,[K.fontcolor]:t.hiContrast,[K.color]:t.stroke,[K.style]:`filled`,[K.penwidth]:0})}applyEdgeAttributes(e){let t=this.defaultRelationshipColors;e.apply({[K.arrowsize]:.75,[K.fontname]:Ca,[K.fontsize]:pxToPoints(14),[K.penwidth]:pxToPoints(2),[K.color]:t.line,[K.fontcolor]:t.label,[K.style]:this.$defaults.relationship.line})}reserveNodeId(e,t=!1){return t?e=`cluster_`+e:e.toLowerCase().startsWith(`cluster`)&&(e=`nd_`+e),!this.ids.has(e)&&(this.ids.add(e),e)}generateGraphvizId(e){let t=isCompound(e),r=nameFromFqn(e.id).toLowerCase(),i=this.reserveNodeId(r,t),a=1;for(;i===!1;)i=this.reserveNodeId(r+`_`+a++,t);return i}elementToSubgraph(e,t){invariant(isCompound(e),`node should be compound`),invariant(x(e.depth),`node.depth should be defined`);let r=this.styles.colors(e.color).elements,i=compoundLabelColor(r.loContrast);return t.apply({[K.likec4_id]:e.id,[K.likec4_level]:e.level,[K.likec4_depth]:e.depth,[K.fillcolor]:compoundColor(r.fill,e.depth),[K.color]:compoundColor(r.stroke,e.depth),[K.style]:`filled`,[K.margin]:pxToPoints(e.children.length>1?40:32)}),w(e.title.trim())||t.set(K.label,compoundLabel(e,i)),t}elementToNode(e,t){invariant(!isCompound(e),`node should not be compound`);let r=j(e.icon),{values:{padding:i,sizes:{width:a,height:s}}}=this.styles.nodeSizes(e.style),c=r?8:i;t.attributes.apply({[K.likec4_id]:e.id,[K.likec4_level]:e.level,[K.label]:nodeLabel(e,this.styles),[K.margin]:`${pxToInch(c)},${pxToInch(i)}`}),t.attributes.set(K.width,pxToInch(a)),t.attributes.set(K.height,pxToInch(s));let l=e.style.sizing===`fixed`;if(l&&t.attributes.set(K.fixedsize,!0),!this.styles.isDefaultColor(e.color)){let r=this.styles.colors(e.color).elements;t.attributes.apply({[K.fillcolor]:r.fill,[K.fontcolor]:r.hiContrast,[K.color]:r.stroke})}switch(e.shape){case`cylinder`:case`storage`:t.attributes.apply({[K.margin]:`${pxToInch(c)},${pxToInch(0)}`,[K.penwidth]:pxToPoints(2),[K.shape]:`cylinder`});break;case`browser`:t.attributes.apply({[K.margin]:`${pxToInch(r?c:c+4)},${pxToInch(i+6)}`});break;case`mobile`:t.attributes.apply({[K.margin]:`${pxToInch(r?c:c+4)},${pxToInch(i)}`});break;case`queue`:t.attributes.apply({...!l&&{[K.width]:pxToInch(a),[K.height]:pxToInch(s-8)},[K.margin]:`${pxToInch(r?c:c+4)},${pxToInch(i)}`});break;case`component`:t.attributes.apply({...!l&&{[K.width]:pxToInch(a+10)},[K.margin]:`${pxToInch(c+20)},${pxToInch(i)}`})}return t}leafElements(e){return e===null?D([...this.selectViewNodes()],e=>!isCompound(e)):this.computedNode(e).children.flatMap(e=>{let t=this.computedNode(e);return isCompound(t)?this.leafElements(t.id):[t]})}descendants(e){return e===null?[...this.selectViewNodes()]:this.computedNode(e).children.flatMap(e=>{let t=this.computedNode(e);return[t,...this.descendants(t.id)]})}computedNode(e){return this.viewNodes.get(e)}getGraphNode(e){return this.nodes.get(e)??null}getSubgraph(e){return this.subgraphs.get(e)??null}edgeEndpoint(e,t){let r=this.computedNode(e),i=this.getGraphNode(e),a;return i?[r,i,void 0]:(invariant(isCompound(r),`endpoint node should be compound`),a=this.getSubgraph(e)?.id,invariant(a,`subgraph ${e} not found`),r=nonNullable(t(this.leafElements(e)),`leaf element in ${e} not found`),i=nonNullable(this.getGraphNode(r.id),`source graphviz node ${r.id} not found`),[r,i,a])}findInternalEdges(e){if(e===null)return this.view.edges.slice();let t=this.computedNode(e);return N(this.descendants(e),P(e=>Se(e.inEdges,e.outEdges)),E(),ye(Se(t.inEdges,t.outEdges)),p(e=>this.view.edges.find(t=>t.id===e)),D(j))}assignGroups(){let e=N(this.view.nodes,D(isCompound),p(e=>e.id),Be(compareFqnHierarchically),ge(),p(e=>({id:e,edges:this.findInternalEdges(e).filter(e=>e.source!==e.target&&!this.compoundIds.has(e.source)&&!this.compoundIds.has(e.target))})),D(({edges:e})=>e.length>1&&e.length<8),he(4)),t=/* @__PURE__ */ new Set;for(let r of e){let e=r.edges.filter(e=>!t.has(e.source)&&!t.has(e.target));for(let i of e)try{let e=nonNullable(this.getGraphNode(i.source),`Graphviz Node not found for ${i.source}`),a=nonNullable(this.getGraphNode(i.target),`Graphviz Node not found for ${i.target}`);t.add(i.source),t.add(i.target),e.attributes.set(K.group,r.id),a.attributes.set(K.group,r.id)}catch(e){wa.error(`Failed to assign group to edge ${i.id}`,{error:e})}}return this}},AiLayoutViewPrinter=class extends DotPrinter{aiHints;constructor(e,t,r){super(e,t),this.aiHints=r}createGraph(){let e=super.createGraph();return e.delete(K.TBbalance),e}selectViewNodes(){if(!this.aiHints.nodeOrder)return this.view.nodes;let e=[...this.view.nodes],t=[];for(let r of this.aiHints.nodeOrder){let i=e.findIndex(e=>e.id===r);i!==-1&&t.push(...e.splice(i,1))}return t.push(...e),t}selectViewEdges(){if(!this.aiHints.edgeOrder)return this.view.edges;let e=[...this.view.edges],t=[];for(let r of this.aiHints.edgeOrder){let i=e.findIndex(e=>e.id===r);i!==-1&&t.push(...e.splice(i,1))}return t.push(...e),t}postBuild(e){this.applyNodeRanks().addInvisibleEdges().enableNewRankIfNeeded()}applyNodeRanks(){let e=this.G;for(let t of this.aiHints.ranks){let r=[...new Set(t.nodes)].map(e=>this.getGraphNode(e)).filter(l);if(r.length===0||t.rank===`same`&&r.length===1)continue;let i=e.createSubgraph({[K.rank]:t.rank});for(let e of r)i.node(e.id)}return this}addEdge(e,t){let r=this.aiHints.reverseRank?.includes(e.id)??!1,[i,a]=r?[e.target,e.source]:[e.source,e.target],[,s,c]=this.edgeEndpoint(i,te()),[,u,p]=this.edgeEndpoint(a,fe()),m=t.edge([s,u],{[K.likec4_id]:e.id});e.line&&e.line!==`dashed`&&m.attributes.set(K.style,e.line),p&&m.attributes.set(K.lhead,p),c&&m.attributes.set(K.ltail,c);let h=l(p)||l(c),g=edgelabel(e);if(g&&m.attributes.set(this.edgeLabelAttr(h),g),e.color&&e.color!==this.$defaults.relationship.color){let t=this.styles.colors(e.color).relationships;m.attributes.apply({[K.color]:t.line,[K.fontcolor]:t.label})}let _=this.aiHints.edgeWeight[e.id];_!==void 0&&_!==1&&m.attributes.set(K.weight,_);let v=this.aiHints.edgeMinlen[e.id];return v!==void 0&&v!==1&&m.attributes.set(K.minlen,v),this.aiHints.excludeFromRanking?.includes(e.id)&&m.attributes.set(K.constraint,!1),r&&m.attributes.set(K.dir,`back`),m}addInvisibleEdges(){if(!this.aiHints.invisibleEdges)return this;let e=this.G;for(let{source:t,target:r,...i}of this.aiHints.invisibleEdges){let a=this.getGraphNode(t),s=this.getGraphNode(r);if(!a||!s)continue;let c=`invisible_${t}->${r}`;if(this.edges.has(c)){this.logger.trace`invisible edge ${t} -> ${r} already exists with id ${c}, skipping creation`;continue}this.graphology.addEdgeWithKey(c,t,r,{hierarchyDistance:0,origin:`invisible`,weight:i.weight??1});let l=e.edge([a,s],{[K.style]:`invis`});this.edges.set(c,l),i.minlen!==void 0&&i.minlen!==1&&l.attributes.set(K.minlen,i.minlen),i.weight!==void 0&&i.weight!==1&&l.attributes.set(K.weight,i.weight)}return this}reduceDefaultRankSeparation(){let e=this.view.autoLayout,t=this.G;return x(e.rankSep)||!(M(this.aiHints.edgeMinlen).some(([e,t])=>t>1)||(this.aiHints.invisibleEdges?.some(e=>e.minlen&&e.minlen>1)??!1))||t.set(K.ranksep,pxToInch(80)),this}},DeploymentViewPrinter=class extends DotPrinter{createGraph(){let e=super.createGraph(),t=this.view.autoLayout;return e.delete(K.TBbalance),e.apply({[K.nodesep]:pxToInch(t.nodeSep??130),[K.ranksep]:pxToInch(t.rankSep??130)}),e}postBuild(){let e=this.G;return N(this.view.nodes,p(e=>({node:e,graphvizNode:this.getGraphNode(e.id)})),le(({node:e,graphvizNode:t})=>{if(t!=null)return e.modelRef}),Fe(),p(e=>e),Ae(t=>{t.length<2||e.subgraph({[K.rank]:`same`},e=>{for(let{graphvizNode:r}of t)e.node(nonNullable(r).id)})}),je(()=>{e.set(K.newrank,!0),e.set(K.clusterrank,`global`),e.delete(K.pack),e.delete(K.packmode)})),this}elementToSubgraph(e,t){let r=super.elementToSubgraph(e,t);return e.children.length>1&&r.set(K.margin,pxToPoints(50)),r}addEdge(e,t){let[r,i]=[e.source,e.target],[a,s,c]=this.edgeEndpoint(r,te()),[u,p,m]=this.edgeEndpoint(i,fe()),h=l(m)||l(c),g=t.edge([s,p],{[K.likec4_id]:e.id,[K.style]:e.line??`dashed`});m&&g.attributes.set(K.lhead,m),c&&g.attributes.set(K.ltail,c);let _=this.graphology.getEdgeAttribute(e.id,`weight`);_>1&&!this.graphology.hasDirectedEdge(e.target,e.source)&&g.attributes.set(K.weight,_);let v=edgelabel(e);if(v&&g.attributes.set(this.edgeLabelAttr(h),v),e.color&&e.color!==this.$defaults.relationship.color){let t=this.styles.colors(e.color).relationships;g.attributes.apply({[K.color]:t.line,[K.fontcolor]:t.label})}let[y,b]=[e.head??this.$defaults.relationship.arrow,e.tail??`none`];return y===`none`&&b===`none`?(g.attributes.apply({[K.arrowtail]:`none`,[K.arrowhead]:`none`,[K.dir]:`none`}),g):e.dir===`both`?(g.attributes.apply({[K.arrowhead]:toArrowType(y),[K.arrowtail]:toArrowType(e.tail??y),[K.dir]:`both`}),!h&&a.modelRef!==u.modelRef&&g.attributes.set(K.constraint,!1),g):(y&&g.attributes.set(K.arrowhead,toArrowType(y)),b!==`none`&&g.attributes.set(K.arrowtail,toArrowType(b)),g)}},DynamicViewPrinter=class extends DotPrinter{postBuild(e){e.delete(K.TBbalance),e.set(K.ordering,`in`)}addEdge(e,t){let{nodes:r}=this.view,[i,a]=e.dir===`back`?[e.target,e.source]:[e.source,e.target],[s,c,l]=this.edgeEndpoint(i,te()),[u,p,m]=this.edgeEndpoint(a,fe()),h=t.edge([c,p],{[K.likec4_id]:e.id});if(e.line&&e.line!==this.$defaults.relationship.line&&h.attributes.set(K.style,e.line),m&&h.attributes.set(K.lhead,m),l&&h.attributes.set(K.ltail,l),e.color&&e.color!==this.$defaults.relationship.color){let t=this.styles.colors(e.color).relationships;h.attributes.apply({[K.color]:t.line,[K.fontcolor]:t.label})}let g=[e.label?.trim(),e.technology?.trim()].filter(j).join(`
|
|
32
|
+
`),_=stepEdgeLabel(this.view.edges.indexOf(e),g);h.attributes.set(this.edgeLabelAttr(!1),_);let v=r.findIndex(e=>e.id===i);r.findIndex(e=>e.id===a)<v&&e.dir!==`back`&&h.attributes.apply({[K.minlen]:0});let[y,b]=[e.head??this.$defaults.relationship.arrow,e.tail??`none`];return e.dir===`back`?(h.attributes.apply({[K.arrowtail]:toArrowType(y),[K.dir]:`back`}),b!==`none`&&h.attributes.apply({[K.arrowhead]:toArrowType(b),[K.minlen]:0}),h):y===`none`&&b===`none`||y!==`none`&&b!==`none`?(h.attributes.apply({[K.arrowhead]:toArrowType(y),[K.arrowtail]:toArrowType(b),[K.dir]:`both`}),h):y===`none`?(h.attributes.delete(K.arrowhead),h.attributes.apply({[K.arrowtail]:toArrowType(b),[K.minlen]:0,[K.dir]:`back`}),h):(h.attributes.set(K.arrowhead,toArrowType(y)),h)}};const Ta=createLogger(`dot.rank`);var ElementViewPrinter=class extends DotPrinter{postBuild(){this.assignGroups().tileNodesWithoutEdges().applyExplicitRankBlocks().enableNewRankIfNeeded()}tileNodesWithoutEdges(){let e=/* @__PURE__ */ new Set,t=this.view.nodes.reduce((t,r)=>(isCompound(r)&&(e.add(r.id),t.push(r)),t),[]);for(let e of t){let t=N(e.children,D(e=>!this.compoundIds.has(e)&&this.graphology.degree(e)===0),p(e=>this.computedNode(e)));if(t.length<=2)continue;let r=2;switch(!0){case t.length>11:r=4;break;case t.length>4:r=3}let i=nonNullable(this.getSubgraph(e.id),`Subgraph not found for ${e.id}`),a=null;de(t,r).forEach(e=>{let t=e.length>1?i.createSubgraph({[K.rank]:`same`}):null;e.forEach((e,r)=>{let s=this.getGraphNode(e.id);s&&(t?.node(s.id),r===0&&(a&&i.edge([a,s],{[K.style]:`invis`}),a=s))})})}return this}applyExplicitRankBlocks(){let e=this.view.ranks??[];if(e.length===0)return this;let t=0;for(let r of e){let e=[...new Set(r.nodes)].map(e=>this.getGraphNode(e)).filter(e=>!!e);if(e.length===0)continue;let i=this.G.createSubgraph({[K.rank]:r.type});e.forEach(e=>i.node(e.id)),t+=1,Ta.trace`rank ${r.type} => ${e.map(e=>e.id).join(`, `)}`}return t>0&&this.G.set(`likec4_rankBlocks`,t),this}addEdge(e,t){let[r,i]=e.dir===`back`?[e.target,e.source]:[e.source,e.target],[a,s,c]=this.edgeEndpoint(r,te()),[u,p,m]=this.edgeEndpoint(i,fe()),h=e.parent,g=this.graphology.getEdgeAttributes(e.id),_=t.edge([s,p],{[K.likec4_id]:e.id});e.line&&e.line!==this.$defaults.relationship.line&&_.attributes.set(K.style,e.line),m&&_.attributes.set(K.lhead,m),c&&_.attributes.set(K.ltail,c);let v=l(m)||l(c),y=edgelabel(e);if(y&&_.attributes.set(this.edgeLabelAttr(v),y),e.color&&e.color!==this.$defaults.relationship.color){let t=this.styles.colors(e.color).relationships;_.attributes.apply({[K.color]:t.line,[K.fontcolor]:t.label})}!this.graphology.hasDirectedEdge(e.target,e.source)&&g.weight>1&&_.attributes.set(K.weight,g.weight);let[b,x]=[e.head??this.$defaults.relationship.arrow,e.tail??`none`];if(e.dir===`back`)return _.attributes.apply({[K.arrowtail]:toArrowType(b),[K.dir]:`back`}),x!==`none`&&_.attributes.apply({[K.arrowhead]:toArrowType(x),[K.dir]:`both`,[K.minlen]:0}),_;if(b===`none`&&x===`none`)return _.attributes.apply({[K.arrowtail]:`none`,[K.arrowhead]:`none`,[K.dir]:`none`,[K.minlen]:0,[K.constraint]:!1}),_;if(b!==`none`&&x!==`none`)return _.attributes.apply({[K.arrowhead]:toArrowType(b),[K.arrowtail]:toArrowType(x),[K.dir]:`both`}),_;if(_.attributes.set(K.arrowhead,toArrowType(b)),x!==`none`&&_.attributes.set(K.arrowtail,toArrowType(x)),this.view.edges.length===1)return _;let S;return S=h===null&&a.parent==null&&u.parent==null?this.view.edges.filter(t=>{if(t.id===e.id||t.parent!==null||t.source===e.source&&t.target===e.target||t.source===e.target&&t.target===e.source)return!1;let r=this.computedNode(t.source),i=this.computedNode(t.target);return isCompound(r)||isCompound(i)?!1:r.parent==null&&i.parent==null}):this.findInternalEdges(h).filter(t=>!(t.id===e.id||t.source===e.source&&t.target===e.target||t.source===e.target&&t.target===e.source)),S.length===0&&(h===null||this.leafElements(h).length<=3)&&_.attributes.set(K.minlen,0),_}};function placeEdgeLabels(e,t){let r=placeLabelsAlongRoutes(e.map(e=>({id:e.id,segments:polylineToSegments(splineToPolyline(e.points)),labelBBox:e.labelBBox??null})),t.filter(e=>!isCompound(e)));return e.map(e=>{let t=r.get(e.id);return t?{...e,labelBBox:t}:e})}function parseBB(e){let[t,r,i,a]=e?e.split(`,`).map(e=>pointToPx(+e)):[0,0,0,0],s=Math.round(i-t),c=Math.round(r-a);return{x:Math.round(t),y:Math.round(a),width:s,height:c}}function parsePos(e){try{let[t,r]=e.split(`,`);return{x:pointToPx(parseFloat(t)),y:pointToPx(parseFloat(r))}}catch(t){throw Error(`Failed on parsing pos: ${e}`,{cause:t})}}function parseNode(e){let{x:t,y:r}=parsePos(e.pos),i=inchToPx(parseFloat(e.width)),a=inchToPx(parseFloat(e.height));return{x:t-Math.round(i/2),y:r-Math.round(a/2),width:i,height:a}}function parseLabelBbox(e,[t,r]=[0,0]){if(!e||e.length===0)return null;let i=1/0,a=1/0,s=-1/0,c=-1/0,l=13;try{for(let u of e)if(u.op===`F`)l=pointToPx(u.size);else if(u.op===`T`){let e=pointToPx(u.pt[0])-t,p=pointToPx(u.width);switch(u.align){case`r`:e-=p;break;case`c`:e-=Math.round(p/2)}i=Math.min(i,e),s=Math.max(s,e+p);let m=pointToPx(u.pt[1])-r;a=Math.min(a,Math.round(m-l)),c=Math.max(c,m)}}catch(t){return ga.warn(`Failed on parsing label draw ops:
|
|
33
|
+
{labelDrawOps}`,{e:t,labelDrawOps:e}),null}return i===1/0?null:{x:i-2,y:a-2,width:s-i+4,height:c-a+4}}function parseEdgePoints({_draw_:e,likec4_id:t=`???`},r=`<unknown view>`){try{let i=e.filter(e=>e.op.toLowerCase()===`b`);invariant(k(i,1),`view ${r} edge ${t} should have at least one bezier draw op`),i.length>1&&ga.warn(`view ${r} edge ${t} has more than one bezier draw op, using the first one only`);let a=i[0].points.map(e=>pointToPx(e));return invariant(k(a,2),`view ${r} edge ${t} should have at least two points`),a}catch(i){throw Error(`failed on parsing view ${r} edge ${t} _draw_:\n${JSON.stringify(e,null,2)}`,{cause:i})}}function parseGraphvizEdge(e,{id:t,source:r,target:i,dir:a,label:s,description:c,...l},u){let p=parseLabelBbox(e._ldraw_??e._tldraw_??e._hldraw_),m=e.dir===`back`||a===`back`;return s=s&&p?wrap(s,{maxchars:40,maxLines:5}).join(`
|
|
34
|
+
`):null,{id:t,source:r,target:i,label:s,...j(c)&&{description:c},points:parseEdgePoints(e,u),labelBBox:p,...m?{dir:`back`}:{},...l}}function parseGraphvizJson(e,t){let r=parseBB(e.bb),{nodes:i,edges:a,hasManualLayout:s,...c}=t,l=[],u=[],p;if(p=c._type===`dynamic`?{...c,sequenceLayout:{actors:[],compounds:[],parallelAreas:[],subflows:[],steps:[],bounds:r},[Vi]:`layouted`,bounds:r,nodes:l,edges:u}:{...c,[Vi]:`layouted`,bounds:r,nodes:l,edges:u},s){let e=p;e[Ui]=`auto`}let m=e.objects??[];for(let e of i){let t=m.find(t=>t.likec4_id===e.id);invariant(t,`View ${c.id} node ${e.id} not found in graphviz output`);try{let{x:r,y:i,width:a,height:s}=`bb`in t?parseBB(t.bb):parseNode(t),c=[r,i];l.push({...e,x:r,y:i,width:a,height:s,labelBBox:parseLabelBbox(t._ldraw_,c)??{x:r,y:i,width:a,height:s}})}catch(r){throw Error(`Failed on parsing node ${e.id}:\n${JSON.stringify(t,null,2)}`,{cause:r})}}let h=e.edges??[];for(let e of a){let t=h.find(t=>t.likec4_id===e.id);t?u.push(parseGraphvizEdge(t,e,c.id)):ga.warn`View ${c.id} edge ${e.id} not found in graphviz output, skipping`}if(c.routing===`ortho`){let e=placeEdgeLabels(u,l);p={...p,edges:e,bounds:zi.merge(r,...e.flatMap(e=>e.labelBBox?[e.labelBBox]:[]))}}return p}function parseGraphvizJsonOfProjectsView(e,t){return parseGraphvizJson(e,t)}var Ea=class ProjectsViewPrinter extends DotPrinter{static toDot(e){return new ProjectsViewPrinter(e).print()}constructor(e){super(e,$i.DEFAULT)}createGraph(){let e=super.createGraph();return e.apply({[K.nodesep]:pxToInch(100),[K.ranksep]:pxToInch(100)}),e.delete(K.TBbalance),e}elementToNode(e,t){return t.attributes.apply({[K.likec4_id]:e.id,[K.likec4_project]:e.projectId}),super.elementToNode(e,t)}addEdge(e,t){let r=nonNullable(this.getGraphNode(e.source),`Node not found for ${e.source}`),i=nonNullable(this.getGraphNode(e.target),`Node not found for ${e.target}`),a=this.graphology.getEdgeAttributes(e.id),s=t.edge([r,i],{[K.likec4_id]:e.id,[K.likec4_project]:e.projectId});e.line&&e.line!==this.$defaults.relationship.line&&s.attributes.set(K.style,e.line),!this.graphology.hasDirectedEdge(e.target,e.source)&&a.weight>1&&s.attributes.set(K.weight,a.weight);let c=edgelabel(e);if(c&&s.attributes.set(K.label,c),e.color&&e.color!==this.$defaults.relationship.color){let t=this.styles.colors(e.color).relationships;s.attributes.apply({[K.color]:t.line,[K.fontcolor]:t.label})}return s}};const Da=zt(1);var Oa=class GraphvizWasmAdapter{static opsCount=0;get name(){return`wasm`}get concurrency(){return 1}dispose(){vr.unload()}[Symbol.dispose](){this.dispose()}async attempt(e,t,r){return await Da(async()=>{let i=ga.getChild([`layouter`,`wasm`,e,`_`,Ne(4).toLowerCase()]);try{i.trace`execute`;let e=await r();return++GraphvizWasmAdapter.opsCount>=20&&(GraphvizWasmAdapter.opsCount=0,i.trace`reached 20 operations, unloading wasm`,vr.unload()),e}catch(e){i.trace(`FAILED DOT
|
|
35
|
+
`+t);let r=loggable(e);if(r.includes(`syntax error`))throw e;i.warn(r),GraphvizWasmAdapter.opsCount=0,vr.unload()}return i.warn(`Retrying...`),await delay(30,300),await r()})}async unflatten(e){return await this.attempt(`unflatten`,e,async()=>(await vr.load()).unflatten(e,1,!1,3).replaceAll(/\t\[/g,` [`).replaceAll(/\t/g,` `))}async acyclic(e){return await this.attempt(`acyclic`,e,async()=>{let t=(await vr.load()).acyclic(e,!0);return t.acyclic&&t.outFile||e})}async layoutJson(e){return await this.attempt(`layout`,e,async()=>(await vr.load()).layout(e,`json`,void 0,{yInvert:!0}))}async svg(e){return await this.attempt(`svg`,e,async()=>(await vr.load()).layout(e,`svg`))}};const getPrinter=({view:e,styles:t})=>{switch(!0){case isDynamicView$1(e):return new DynamicViewPrinter(e,t);case isDeploymentView$1(e):return new DeploymentViewPrinter(e,t);case isElementView$1(e):return new ElementViewPrinter(e,t);default:nonexhaustive(e)}},ka=ga.getChild(`layouter`);function normalizeDot(e){return e.split(`
|
|
36
|
+
`).filter(e=>!(e.includes(`margin`)&&e.includes(`50.1`))).join(`
|
|
37
|
+
`)}var GraphvizLayouter=class{graphviz;constructor(e){this.graphviz=e??new Oa,ka.trace`created with port ${this.graphviz.name}`}dispose(){this.graphviz.dispose()}[Symbol.dispose](){this.dispose()}get graphvizPort(){return this.graphviz}changePort(e){this.graphviz.dispose(),this.graphviz=e,ka.trace`change port to ${this.graphviz.name}`}printToDot(e,t){return normalizeDot((t?new AiLayoutViewPrinter(e.view,e.styles,t):getPrinter(e)).print())}newScopedLogger(e){return ka.getChild([e,`_`,Ne(4).toLowerCase()])}async dotToJson(e){let t=this.newScopedLogger(`dotToJson`),r;try{r=await this.graphviz.layoutJson(e)}catch(r){throw t.error(loggable(r)),t.error(`Failed to convert DOT to JSON:
|
|
38
|
+
`+e),r}try{return JSON.parse(r)}catch(i){throw t.error(loggable(i)),t.error`Failed to parse JSON:\n${r}\n. Generated from DOT:\n${e}`,i}}async layout(e){let t=this.newScopedLogger(`layout`);try{t.trace`layouting view ${e.view.id}...`;let r=await this.dot(e),{view:i}=e,a=parseGraphvizJson(await this.dotToJson(r),i);return isDynamicView$1(a)&&Object.assign(a,{sequenceLayout:calcSequenceLayout(a)}),r=normalizeDot(r),t.trace`layouting view ${e.view.id} done`,{dot:r,diagram:a}}catch(r){throw t.warn(loggable(r)),wrapError(r,`Error during layout: ${e.view.id}`)}}async aiLayout({view:e,styles:t},r){let i=this.newScopedLogger(`ai-layout`);try{i.trace`layouting view ${e.id} using AI hints...`;let a=new AiLayoutViewPrinter(e,t,r).print(),s=parseGraphvizJson(await this.dotToJson(a),e);return isDynamicView$1(s)&&Object.assign(s,{sequenceLayout:calcSequenceLayout(s)}),a=normalizeDot(a),i.trace`layouting view ${e.id} done`,{dot:a,diagram:s}}catch(t){throw i.warn(loggable(t)),wrapError(t,`Error during AI layout: ${e.id}`)}}async svg(e){let t=await this.dot(e);return t=normalizeDot(t),{svg:await this.graphviz.svg(t),dot:t}}async dot(e){let t=this.newScopedLogger(`dot`);t.trace`generating dot for view ${e.view.id}`;let r=getPrinter(e).print();if(!isElementView$1(e.view))return normalizeDot(r);try{t.trace`unflattening dot`,r=await this.graphviz.unflatten(r)}catch(r){t.warn(`Error during unflatten: ${e.view.id}`,{error:r})}return normalizeDot(r)}async layoutProjectsView(e){let t=this.newScopedLogger(`layoutProjectsView`);t.debug`layouting projects overview...`;let r=new Ea(e).print();try{r=await this.graphviz.unflatten(r)}catch(e){t.warn(`Error during unflatten of projects view`,{error:e})}let i=await this.dotToJson(r);return t.debug`layouting ${`projects overview`}`,parseGraphvizJsonOfProjectsView(i,e)}},QueueGraphvizLayoter=class extends GraphvizLayouter{queue;isProcessingBatch=!1;#e=ga.getChild([`layouter-queue`]);constructor(e){super(e?.graphviz),this.queue=new Bt({concurrency:e?.concurrency??this.graphvizPort.concurrency,timeout:e?.timeout??2e4,throwOnTimeout:e?.throwOnTimeout??!0})}async runInQueue(e){let t=this.#e.getChild([`run`,Ne(3).toLowerCase()]);return await this.waitForQueueToShrink(this.queue.concurrency,t),t.trace`add task to queue`,await this.queue.add(async()=>(await promiseNextTick(),t.trace`task started`,await e()),{throwOnTimeout:!0})}changePort(e){super.changePort(e),this.queue.concurrency!==e.concurrency&&(this.queue.concurrency=this.graphvizPort.concurrency,this.#e.debug`set queue concurrency to ${this.graphvizPort.concurrency}`)}async layout(e){return await this.runInQueue(()=>super.layout(e))}async layoutProjectsView(e){return await this.runInQueue(()=>super.layoutProjectsView(e))}async batchLayout(e,t=this.#e.getChild([`batch`,Ne(3).toLowerCase()])){if(e.batch.length===0)return t.trace`empty batch`,[];let r=F(e.batch);if(r)return t.trace`only one task in batch, adding to queue`,await this.queue.add(async()=>{await promiseNextTick();try{let t=await super.layout(r);return e.onSuccess?.(r,t),[t]}catch(i){if(t.warn(`layout view ${r.view.id} failed`,{error:i}),e.onError)return e.onError(r,i);throw i}},{throwOnTimeout:!0});if(this.isProcessingBatch)return t.trace`wait for previous layouts to finish`,await this.queue.onIdle(),e.cancelToken?.isCancellationRequested?(t.trace`cancellation requested`,[]):(t.trace`retry`,await this.batchLayout(e));try{this.isProcessingBatch=!0;let r=this.queue.concurrency;await this.waitForQueueToShrink(r,t),t.trace`starting, batch size: ${e.batch.length}, concurrency: ${r}`;let i=[],a=0,s=Math.max(r+1,4),c=s>=e.batch.length?[e.batch]:de(e.batch,s);for(let r of c){a++,c.length>1&&t.trace`processing chunk ${a} of ${c.length} (chunk size: ${r.length})`;let s=AbortSignal.timeout(3e4);await this.queue.addAll(r.map(r=>async({signal:a})=>{if(await promiseNextTick(),a?.aborted)t.warn`layout view ${r.view.id} cancelled due to timeout`,e.onError?.(r,/* @__PURE__ */ Error(`Timeout`));else try{let t=await super.layout(r);return i.push(t),e.onSuccess?.(r,t),t}catch(i){if(t.warn(`layout view ${r.view.id} failed`,{error:i}),e.onError)return e.onError(r,i);throw i}}),{signal:s,throwOnTimeout:!1}),s.throwIfAborted()}return t.trace`batch layout done`,i}catch(e){throw t.error(`Batch layout failed`,{error:e}),e}finally{this.isProcessingBatch=!1}}async waitForQueueToShrink(e=this.queue.concurrency,t=this.#e){this.queue.size>e+2&&(t.trace`limit reached. queue size: ${this.queue.size}, running: ${this.queue.pending}, waiting shrink to ${e}`,await this.queue.onSizeLessThan(e+1))}dispose(){this.queue.clear(),super.dispose()}},ElementModel=class{$model;$element;Aux;id;_literalId;hierarchyLevel;imported;constructor(e,t){this.$model=e,this.$element=t,this.id=this.$element.id,this._literalId=this.$element.id;let[r,i]=splitGlobalFqn(this.id);r?(this.imported={from:r,fqn:i},this.hierarchyLevel=hierarchyLevel(i)):(this.imported=null,this.hierarchyLevel=hierarchyLevel(this.id))}get name(){return nameFromFqn(this.id)}get parent(){return this.$model.parent(this)}get kind(){return this.$element.kind}get shape(){return this.style.shape}get color(){return this.style.color}get icon(){return this.style.icon??null}get tags(){return memoizeProp(this,Symbol.for(`tags`),()=>E([...this.$element.tags??[],...this.$model.specification.elements[this.$element.kind]?.tags??[]]))}get metadata(){return this.$element.metadata??{}}get title(){return this.$element.title}get hasSummary(){return!!this.$element.summary&&!!this.$element.description&&!ee(this.$element.summary,this.$element.description)}get summary(){return sa.memoize(this,`summary`,/* @__PURE__ */ preferSummary(this.$element))}get description(){return sa.memoize(this,`description`,/* @__PURE__ */ preferDescription(this.$element))}get technology(){return this.$element.technology??null}get links(){return this.$element.links??[]}get defaultView(){return memoizeProp(this,Symbol.for(`defaultView`),()=>ihead(this.scopedViews())??null)}get isRoot(){return this.parent===null}get style(){return memoizeProp(this,`style`,()=>exact({shape:this.$model.$styles.defaults.shape,color:this.$model.$styles.defaults.color,border:this.$model.$styles.defaults.border,opacity:this.$model.$styles.defaults.opacity,size:this.$model.$styles.defaults.size,padding:this.$model.$styles.defaults.padding,textSize:this.$model.$styles.defaults.text,iconPosition:this.$model.$styles.defaults.iconPosition,...this.$element.style}))}get projectId(){return this.imported?.from??this.$model.projectId}isAncestorOf(e){return isAncestor(this,e)}isDescendantOf(e){return isAncestor(e,this)}ancestors(){return this.$model.ancestors(this)}commonAncestor(e){let t=commonAncestor(this.id,e.id);return t?this.$model.element(t):null}children(){return this.$model.children(this)}descendants(e){return e?sortNaturalByFqn([...this.$model.descendants(this)],e)[Symbol.iterator]():this.$model.descendants(this)}siblings(){return this.$model.siblings(this)}*ascendingSiblings(){yield*this.siblings();for(let e of this.ancestors())yield*e.siblings()}*descendingSiblings(){for(let e of[...this.ancestors()].reverse())yield*e.siblings();yield*this.siblings()}incoming(e=`all`){return this.$model.incoming(this,e)}*incomers(e=`all`){let t=/* @__PURE__ */ new Set;for(let r of this.incoming(e))t.has(r.source.id)||(t.add(r.source.id),yield r.source)}outgoing(e=`all`){return this.$model.outgoing(this,e)}*outgoers(e=`all`){let t=/* @__PURE__ */ new Set;for(let r of this.outgoing(e))t.has(r.target.id)||(t.add(r.target.id),yield r.target)}get allOutgoing(){return memoizeProp(this,Symbol.for(`allOutgoing`),()=>new Set(this.outgoing()))}get allIncoming(){return memoizeProp(this,Symbol.for(`allIncoming`),()=>new Set(this.incoming()))}views(){return memoizeProp(this,Symbol.for(`views`),()=>{let e=/* @__PURE__ */ new Set;for(let t of this.$model.views())t.includesElement(this.id)&&e.add(t);return e})}scopedViews(){return memoizeProp(this,Symbol.for(`scopedViews`),()=>{let e=/* @__PURE__ */ new Set;for(let t of this.$model.views())t.isScopedElementView()&&t.viewOf.id===this.id&&e.add(t);return e})}isDeployed(){return j(ihead(this.deployments()))}deployments(){return this.$model.deployment.instancesOf(this)}hasMetadata(){return!!this.$element.metadata&&!w(this.$element.metadata)}getMetadata(e){return e?this.$element.metadata?.[e]:this.$element.metadata??{}}isTagged(e){return this.tags.includes(e)}},AbstractDeploymentElementModel=class{Aux;get style(){return memoizeProp(this,`style`,()=>exact({shape:this.$model.$styles.defaults.shape,color:this.$model.$styles.defaults.color,border:this.$model.$styles.defaults.border,opacity:this.$model.$styles.defaults.opacity,size:this.$model.$styles.defaults.size,padding:this.$model.$styles.defaults.padding,textSize:this.$model.$styles.defaults.text,iconPosition:this.$model.$styles.defaults.iconPosition,...this.$node.style}))}get name(){return nameFromFqn(this.id)}get shape(){return this.style.shape}get color(){return this.style.color}get icon(){return this.style.icon??null}get summary(){return sa.memoize(this,`summary`,/* @__PURE__ */ preferSummary(this.$node))}get description(){return sa.memoize(this,`description`,/* @__PURE__ */ preferDescription(this.$node))}get technology(){return this.$node.technology??null}get links(){return this.$node.links??[]}ancestors(){return this.$model.ancestors(this)}commonAncestor(e){let t=commonAncestor(this.id,e.id);return t?this.$model.node(t):null}siblings(){return this.$model.siblings(this)}isSibling(e){return this.parent===e.parent}*ascendingSiblings(){yield*this.siblings();for(let e of this.ancestors())yield*e.siblings()}*descendingSiblings(){for(let e of[...this.ancestors()].reverse())yield*e.siblings();yield*this.siblings()}incoming(e=`all`){return this.$model.incoming(this,e)}outgoing(e=`all`){return this.$model.outgoing(this,e)}*incomers(e=`all`){let t=/* @__PURE__ */ new Set;for(let r of this.incoming(e))t.has(r.source.id)||(t.add(r.source.id),yield r.source)}*outgoers(e=`all`){let t=/* @__PURE__ */ new Set;for(let r of this.outgoing(e))t.has(r.target.id)||(t.add(r.target.id),yield r.target)}*views(){for(let e of this.$model.views())e._type===`deployment`&&e.includesDeployment(this.id)&&(yield e)}isDeploymentNode(){return!1}isInstance(){return!1}get allOutgoing(){return memoizeProp(this,Symbol.for(`allOutgoing`),()=>Aa.from(new Set(this.outgoingModelRelationships()),new Set(this.outgoing())))}get allIncoming(){return memoizeProp(this,Symbol.for(`allIncoming`),()=>Aa.from(new Set(this.incomingModelRelationships()),new Set(this.incoming())))}hasMetadata(){return!!this.$node.metadata&&!w(this.$node.metadata)}getMetadata(e){return e?this.$node.metadata?.[e]:this.$node.metadata??{}}isTagged(e){return this.tags.includes(e)}},DeploymentNodeModel=class extends AbstractDeploymentElementModel{$model;$node;id;_literalId;title;hierarchyLevel;constructor(e,t){super(),this.$model=e,this.$node=t,this.id=t.id,this._literalId=t.id,this.title=t.title,this.hierarchyLevel=hierarchyLevel(t.id)}get parent(){return memoizeProp(this,Symbol.for(`parent`),()=>this.$model.parent(this))}get kind(){return this.$node.kind}get metadata(){return this.$node.metadata??{}}get tags(){return memoizeProp(this,Symbol.for(`tags`),()=>E([...this.$node.tags??[],...this.$model.$model.specification.deployments[this.kind]?.tags??[]]))}children(){return this.$model.children(this)}descendants(e=`desc`){return this.$model.descendants(this,e)}isDeploymentNode(){return!0}*instances(){for(let e of this.descendants(`desc`))e.isInstance()&&(yield e)}onlyOneInstance(){let e=this.children();if(e.size!==1)return null;let t=ihead(e);return t?t.isInstance()?t:t.onlyOneInstance():null}_relationshipsFromInstances=null;relationshipsFromInstances(){if(this._relationshipsFromInstances)return this._relationshipsFromInstances;let{outgoing:e,incoming:t}=this._relationshipsFromInstances={outgoing:/* @__PURE__ */ new Set,incoming:/* @__PURE__ */ new Set};for(let r of this.instances()){for(let t of r.element.outgoing())e.add(t);for(let e of r.element.incoming())t.add(e)}return this._relationshipsFromInstances}outgoingModelRelationships(){return this.relationshipsFromInstances().outgoing.values()}incomingModelRelationships(){return this.relationshipsFromInstances().incoming.values()}internalModelRelationships(){let{outgoing:e,incoming:t}=this.relationshipsFromInstances();return intersection(t,e)}},DeployedInstanceModel=class extends AbstractDeploymentElementModel{$model;$instance;element;id;_literalId;title;hierarchyLevel;constructor(e,t,r){super(),this.$model=e,this.$instance=t,this.element=r,this.id=t.id,this._literalId=t.id,this.title=t.title??r.title,this.hierarchyLevel=hierarchyLevel(t.id)}get $node(){return this.$instance}get parent(){return nonNullable(this.$model.parent(this),`Parent of ${this.id} not found`)}get style(){return memoizeProp(this,`style`,()=>exact({shape:this.$model.$styles.defaults.shape,color:this.$model.$styles.defaults.color,border:this.$model.$styles.defaults.border,opacity:this.$model.$styles.defaults.opacity,size:this.$model.$styles.defaults.size,padding:this.$model.$styles.defaults.padding,textSize:this.$model.$styles.defaults.text,iconPosition:this.$model.$styles.defaults.iconPosition,...this.element.$element.style,...this.$instance.style}))}get tags(){return memoizeProp(this,Symbol.for(`tags`),()=>E([...this.$instance.tags??[],...this.element.tags]))}get kind(){return this.element.kind}get metadata(){return this.$instance.metadata??this.element.metadata??{}}get summary(){return sa.memoize(this,`summary`,/* @__PURE__ */ preferSummary(this.$instance)??/* @__PURE__ */ preferSummary(this.element.$element))}get description(){return sa.memoize(this,`description`,/* @__PURE__ */ preferDescription(this.$instance)??/* @__PURE__ */ preferDescription(this.element.$element))}get technology(){return this.$instance.technology??this.element.technology??null}get links(){return this.$instance.links??this.element.links}isInstance(){return!0}outgoingModelRelationships(){return this.element.outgoing()}incomingModelRelationships(){return this.element.incoming()}*views(){for(let e of this.$model.views())e._type===`deployment`&&(e.includesDeployment(this.id)||e.includesDeployment(this.parent.id)&&this.parent.onlyOneInstance())&&(yield e)}},NestedElementOfDeployedInstanceModel=class{instance;element;constructor(e,t){this.instance=e,this.element=t}get id(){return this.instance.id}get _literalId(){return this.instance.id}get style(){return memoizeProp(this,`style `,()=>({shape:this.element.shape,color:this.element.color,...this.element.$element.style}))}get shape(){return this.element.shape}get color(){return this.element.color}get title(){return this.element.title}get summary(){return this.element.summary}get description(){return this.element.description}get technology(){return this.element.technology}isDeploymentNode(){return!1}isInstance(){return!1}},DeploymentRelationModel=class{$model;$relationship;boundary;source;target;constructor(e,t){this.$model=e,this.$relationship=t,this.source=e.deploymentRef(t.source),this.target=e.deploymentRef(t.target);let r=commonAncestor(this.source.id,this.target.id);this.boundary=r?this.$model.node(r):null}get id(){return this.$relationship.id}get expression(){return`${this.source.id} -> ${this.target.id}`}get title(){return j(this.$relationship.title)?this.$relationship.title:null}get technology(){return _(this.$relationship.technology)?(this.kind&&this.$model.specification.relationships[this.kind])?.technology??null:this.$relationship.technology}get hasSummary(){return!!this.$relationship.summary&&!!this.$relationship.description&&!ee(this.$relationship.summary,this.$relationship.description)}get summary(){return sa.memoize(this,`summary`,/* @__PURE__ */ preferSummary(this.$relationship))}get description(){return sa.memoize(this,`description`,/* @__PURE__ */ preferDescription(this.$relationship))}get tags(){return this.$relationship.tags??[]}get kind(){return this.$relationship.kind??null}get metadata(){return this.$relationship.metadata??{}}get navigateTo(){return this.$relationship.navigateTo?this.$model.$model.view(this.$relationship.navigateTo):null}get links(){return this.$relationship.links??[]}get color(){return this.$relationship.color??this.$model.$styles.defaults.relationship.color}get line(){return this.$relationship.line??this.$model.$styles.defaults.relationship.line}get head(){return this.$relationship.head??this.$model.$styles.defaults.relationship.arrow}get tail(){return this.$relationship.tail}get isBidirectional(){return this.$relationship.isBidirectional===!0}*views(){for(let e of this.$model.views())e.includesRelation(this.id)&&(yield e)}isDeploymentRelation(){return!0}isModelRelation(){return!1}hasMetadata(){return!!this.$relationship.metadata&&!w(this.$relationship.metadata)}getMetadata(e){return e?this.$relationship.metadata?.[e]:this.$relationship.metadata??{}}isTagged(e){return this.tags.includes(e)}},Aa=class RelationshipsAccum{model;deployment;static empty(){return new RelationshipsAccum}static from(e,t){return new RelationshipsAccum(new Set(e),new Set(t))}constructor(e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Set){this.model=e,this.deployment=t}get isEmpty(){return this.model.size===0&&this.deployment.size===0}get nonEmpty(){return this.model.size>0||this.deployment.size>0}get size(){return this.model.size+this.deployment.size}intersect(e){return RelationshipsAccum.from(intersection(this.model,e.model),intersection(this.deployment,e.deployment))}difference(e){return RelationshipsAccum.from(difference(this.model,e.model),difference(this.deployment,e.deployment))}union(e){return RelationshipsAccum.from(union(this.model,e.model),union(this.deployment,e.deployment))}};const getId=e=>typeof e==`string`?e:e.id,ja=/(?<!\\)\//,Ma=/\\\//g,unescapeViewPathSegment=e=>e.replace(Ma,`/`),splitViewTitle=e=>{if(invariant(!e.includes(`
|
|
39
|
+
`),`View title cannot contain newlines`),ja.test(e)){let t=e.split(ja).map(e=>e.trim()).filter(e=>e.length>0);return k(t,1)?t:[``]}return[e.trim()]},splitViewFolderPath=e=>splitViewTitle(e),normalizeViewPath=e=>splitViewTitle(e).join(`/`),getViewFolderPath=e=>{let t=splitViewTitle(e);return k(t,2)?t.slice(0,-1).join(`/`):null},extractViewTitleFromPath=e=>ja.test(e)?unescapeViewPathSegment(splitViewTitle(e).at(-1)??e):unescapeViewPathSegment(e.trim());var LikeC4DeploymentModel=class{$model;#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Map;#n=new I.default(()=>/* @__PURE__ */ new Set);#r=new I.default(()=>/* @__PURE__ */ new Set);#i=/* @__PURE__ */ new Set;#a=/* @__PURE__ */ new Map;#o=new I.default(()=>/* @__PURE__ */ new Set);#s=new I.default(()=>/* @__PURE__ */ new Set);#c=new I.default(()=>/* @__PURE__ */ new Set);#l=new I.default(()=>/* @__PURE__ */ new Set);#u=/* @__PURE__ */ new Map;$deployments;constructor(e){this.$model=e;let t=this.$deployments=e.$data.deployments,r=Fe(t.elements);for(let e of sortParentsFirst(r)){let t=this.addElement(e);for(let e of t.tags)this.#l.get(e).add(t);t.isInstance()&&this.#r.get(t.element.id).add(t)}for(let e of Fe(t.relations)){let t=this.addRelation(e);for(let e of t.tags)this.#l.get(e).add(t)}}get $styles(){return this.$model.$styles}get projectId(){return this.$model.projectId}get project(){return this.$model.project}get specification(){return this.$model.specification}element(e){if(e instanceof DeploymentNodeModel||e instanceof DeployedInstanceModel)return e;let t=getId(e);return nonNullable(this.#e.get(t),`Element ${t} not found`)}findElement(e){return this.#e.get(e)??null}node(e){let t=this.element(e);return invariant(t.isDeploymentNode(),`Element ${t.id} is not a deployment node`),t}findNode(e){let t=this.findElement(e);return t?(invariant(t.isDeploymentNode(),`Element ${t?.id} is not a deployment node`),t):null}instance(e){let t=this.element(e);return invariant(t.isInstance(),`Element ${t.id} is not a deployed instance`),t}findInstance(e){let t=this.findElement(e);return t?(invariant(t.isInstance(),`Element ${t?.id} is not a deployed instance`),t):null}roots(){return this.#i.values()}elements(){return this.#e.values()}*nodes(){for(let e of this.#e.values())e.isDeploymentNode()&&(yield e)}*nodesOfKind(e){for(let t of this.#e.values())t.isDeploymentNode()&&t.kind===e&&(yield t)}*instances(){for(let e of this.#e.values())e.isInstance()&&(yield e)}*instancesOf(e){let t=getId(e);this.#r.has(t)&&(yield*this.#r.get(t))}deploymentRef(e){if(H.isInsideInstanceRef(e)){let{deployment:t,element:r}=e;return getOrCreate(this.#u,`${t}@${r}`,()=>new NestedElementOfDeployedInstanceModel(this.instance(t),this.$model.element(r)))}return this.element(e.deployment)}relationships(){return this.#a.values()}relationship(e){let t=getId(e);return nonNullable(this.#a.get(t),`DeploymentRelationModel ${t} not found`)}findRelationship(e){return this.#a.get(e)??null}*views(){for(let e of this.$model.views())e.isDeploymentView()&&(yield e)}parent(e){let t=getId(e);return this.#t.get(t)||null}children(e){let t=getId(e);return this.#n.get(t)}*siblings(e){let t=getId(e),r=this.parent(e)?.children()??this.roots();for(let e of r)e.id!==t&&(yield e)}*ancestors(e){let t=getId(e),r;for(;r=this.#t.get(t);)yield r,t=r.id}*descendants(e,t=`desc`){for(let r of this.children(e))t===`asc`?(yield r,yield*this.descendants(r.id)):(yield*this.descendants(r.id),yield r)}*incoming(e,t=`all`){let r=getId(e);for(let e of this.#o.get(r))switch(!0){case t===`all`:case t===`direct`&&e.target.id===r:case t===`to-descendants`&&e.target.id!==r:yield e}}*outgoing(e,t=`all`){let r=getId(e);for(let e of this.#s.get(r))switch(!0){case t===`all`:case t===`direct`&&e.source.id===r:case t===`from-descendants`&&e.source.id!==r:yield e}}addElement(e){if(this.#e.has(e.id))throw Error(`Element ${e.id} already exists`);let t=isDeploymentNode$1(e)?new DeploymentNodeModel(this,Object.freeze(e)):new DeployedInstanceModel(this,Object.freeze(e),this.$model.element(e.element));this.#e.set(t.id,t);let r=parentFqn(t.id);return r?(invariant(this.#e.has(r),`Parent ${r} of ${t.id} not found`),this.#t.set(t.id,this.node(r)),this.#n.get(r).add(t)):(invariant(t.isDeploymentNode(),`Root element ${t.id} is not a deployment node`),this.#i.add(t)),t}addRelation(e){if(this.#a.has(e.id))throw Error(`Relation ${e.id} already exists`);let t=new DeploymentRelationModel(this,Object.freeze(e));this.#a.set(t.id,t),this.#o.get(t.target.id).add(t),this.#s.get(t.source.id).add(t);let r=t.boundary?.id??null;if(r)for(let e of[r,...ancestorsFqn(r)])this.#c.get(e).add(t);for(let e of ancestorsFqn(t.source.id)){if(e===r)break;this.#s.get(e).add(t)}for(let e of ancestorsFqn(t.target.id)){if(e===r)break;this.#o.get(e).add(t)}return t}},RelationshipModel=class{model;$relationship;source;target;boundary;constructor(e,t){this.model=e,this.$relationship=t,this.source=e.element(H.flatten(t.source)),this.target=e.element(H.flatten(t.target));let r=commonAncestor(this.source.id,this.target.id);this.boundary=r?this.model.element(r):null}get id(){return this.$relationship.id}get expression(){return`${this.source.id} -> ${this.target.id}`}get title(){return _(this.$relationship.title)?null:this.$relationship.title}get technology(){return _(this.$relationship.technology)?(this.kind&&this.model.specification.relationships[this.kind])?.technology??null:this.$relationship.technology}get hasSummary(){return!!this.$relationship.summary&&!!this.$relationship.description&&!ee(this.$relationship.summary,this.$relationship.description)}get summary(){return sa.memoize(this,`summary`,/* @__PURE__ */ preferSummary(this.$relationship))}get description(){return sa.memoize(this,`description`,/* @__PURE__ */ preferDescription(this.$relationship))}get navigateTo(){return this.$relationship.navigateTo?this.model.view(this.$relationship.navigateTo):null}get tags(){return this.$relationship.tags??[]}get kind(){return this.$relationship.kind??null}get metadata(){return this.$relationship.metadata??{}}get links(){return this.$relationship.links??[]}get color(){return this.$relationship.color??this.model.$styles.defaults.relationship.color}get line(){return this.$relationship.line??this.model.$styles.defaults.relationship.line}get head(){return this.$relationship.head??this.model.$styles.defaults.relationship.arrow}get tail(){return this.$relationship.tail}get isBidirectional(){return this.$relationship.isBidirectional===!0}*views(){for(let e of this.model.views())e.includesRelation(this.id)&&(yield e)}isDeploymentRelation(){return!1}isModelRelation(){return!0}hasMetadata(){return!!this.$relationship.metadata&&!w(this.$relationship.metadata)}getMetadata(e){return e?this.$relationship.metadata?.[e]:this.$relationship.metadata??{}}isTagged(e){return this.tags.includes(e)}},EdgeModel=class{source;target;Aux;$viewModel;$view;$edge;constructor(e,t,r,i){this.source=r,this.target=i,this.$viewModel=e,this.$view=e.$view,this.$edge=t}get id(){return this.$edge.id}get parent(){return this.$edge.parent?this.$viewModel.node(this.$edge.parent):null}get label(){return this.$edge.label??null}get description(){return sa.memoize(this,`description`,this.$edge.description)}get technology(){return this.$edge.technology??null}hasParent(){return this.$edge.parent!==null}get tags(){return this.$edge.tags??[]}get navigateTo(){return this.$edge.navigateTo?this.$viewModel.$model.view(this.$edge.navigateTo):null}get color(){return this.$edge.color}get line(){return this.$edge.line??this.$viewModel.$styles.defaults.relationship.line}get head(){return this.$edge.head??this.$viewModel.$styles.defaults.relationship.arrow}get tail(){return this.$edge.tail}isStep(){return isStepPath(this.$edge.id)}*relationships(e){for(let t of this.$edge.relations)if(e){let r=this.$viewModel.$model.findRelationship(t,e);r&&(yield r)}else yield this.$viewModel.$model.relationship(t)}includesRelation(e){let t=typeof e==`string`?e:e.id;return this.$edge.relations.includes(t)}isTagged(e){return this.tags.includes(e)}},NodeModel=class{Aux;$viewModel;$view;$node;constructor(e,t){this.$viewModel=e,this.$view=e.$view,this.$node=t}get id(){return this.$node.id}get title(){return this.$node.title}get kind(){return this.$node.kind}get description(){return sa.memoize(this,`description`,this.$node.description)}get technology(){return this.$node.technology??null}get notes(){return sa.memoize(this,`notes`,this.$node.notes)}get parent(){return this.$node.parent?this.$viewModel.node(this.$node.parent):null}get element(){let e=this.$node.modelRef;return e?this.$viewModel.$model.element(e):null}get deployment(){let e=this.$node.deploymentRef;return e?this.$viewModel.$model.deployment.element(e):null}get shape(){return this.$node.shape}get color(){return this.$node.color}get icon(){return this.$node.icon??null}get tags(){return this.$node.tags}get links(){return this.$node.links??[]}get navigateTo(){return this.$node.navigateTo?this.$viewModel.$model.view(this.$node.navigateTo):null}get style(){return this.$node.style}get x(){return`x`in this.$node?this.$node.x:void 0}get y(){return`y`in this.$node?this.$node.y:void 0}get width(){return`width`in this.$node?this.$node.width:void 0}get height(){return`height`in this.$node?this.$node.height:void 0}children(){return memoizeProp(this,`children`,()=>new Set(this.$node.children.map(e=>this.$viewModel.node(e))))}*ancestors(){let e=this.parent;for(;e;)yield e,e=e.parent}*siblings(){let e=this.parent?.children()??this.$viewModel.roots();for(let t of e)t.id!==this.id&&(yield t)}*incoming(e=`all`){for(let t of this.$node.inEdges){let r=this.$viewModel.edge(t);switch(!0){case e===`all`:case e===`direct`&&r.target.id===this.id:case e===`to-descendants`&&r.target.id!==this.id:yield r}}}*incomers(e=`all`){let t=/* @__PURE__ */ new Set;for(let r of this.incoming(e))t.has(r.source.id)||(t.add(r.source.id),yield r.source)}*outgoing(e=`all`){for(let t of this.$node.outEdges){let r=this.$viewModel.edge(t);switch(!0){case e===`all`:case e===`direct`&&r.source.id===this.id:case e===`from-descendants`&&r.source.id!==this.id:yield r}}}*outgoers(e=`all`){let t=/* @__PURE__ */ new Set;for(let r of this.outgoing(e))t.has(r.target.id)||(t.add(r.target.id),yield r.target)}isLayouted(){return`width`in this.$node&&`height`in this.$node}hasChildren(){return this.$node.children.length>0}hasParent(){return this.$node.parent!==null}hasElement(){return j(this.$node.modelRef)}hasDeployment(){return j(this.$node.deploymentRef)}hasDeployedInstance(){return this.hasElement()&&this.hasDeployment()}isGroup(){return isGroupElementKind(this.$node)}isTagged(e){return this.tags.includes(e)}},LikeC4ViewModel=class{Aux;#e;#t=/* @__PURE__ */ new Set;#n=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ new Map;#i=/* @__PURE__ */ new Set;#a=/* @__PURE__ */ new Set;#o=/* @__PURE__ */ new Set;#s=new I.default(e=>/* @__PURE__ */ new Set);#c;id;$model;title;order;folder;viewPath;constructor(e,t,r,i){this.$model=e,this.#e=r,this.id=r.id,this.order=r.order,this.folder=t,this.#c=i;for(let e of this.#e.nodes){let t=new NodeModel(this,Object.freeze(e));this.#n.set(e.id,t),e.parent||this.#t.add(t),e.deploymentRef&&this.#a.add(e.deploymentRef),e.modelRef&&this.#i.add(e.modelRef);for(let e of t.tags)this.#s.get(e).add(t)}for(let e of this.#e.edges){let t=new EdgeModel(this,Object.freeze(e),this.node(e.source),this.node(e.target));for(let e of t.tags)this.#s.get(e).add(t);for(let t of e.relations)this.#o.add(t);this.#r.set(e.id,t)}this.title=r.title?extractViewTitleFromPath(r.title):null,this.viewPath=r.title?normalizeViewPath(r.title):r.id}get $styles(){return this.$model.$styles}get _type(){return this.#e[Hi]}get stage(){return this.#e[Vi]}get bounds(){if(`bounds`in this.#e)return this.#e.bounds;if(this.#c)return this.#c.bounds;throw Error(`View is not layouted`)}get titleOrId(){return this.title??this.viewOf?.title??this.id}get titleOrUntitled(){return this.title??`Untitled`}get breadcrumbs(){return memoizeProp(this,`breadcrumbs`,()=>this.folder.isRoot?[this]:[...this.folder.breadcrumbs,this])}get description(){return sa.memoize(this,`description`,this.#e.description)}get tags(){return this.#e.tags??[]}get links(){return this.#e.links??[]}get viewOf(){if(this.isElementView()){let e=this.#e.viewOf;return e?this.$model.element(e):null}return null}get mode(){return this.isDynamicView()?this.#e.variant??`diagram`:null}get includedTags(){return[...this.#s.keys()]}get $view(){if(!this.isLayouted()||`drifts`in this.#e)return this.#e;let e=this.#c;return e?memoizeProp(this,`withDriftReasons`,()=>calcDriftsFromSnapshot(this.#e,e)):this.#e}get $layouted(){if(!this.isLayouted())throw Error(`View is not layouted`);return this.$manual??this.#e}get hasManualLayout(){return this.#c!==void 0}get hasLayoutDrifts(){if(!this.isLayouted())return!1;let e=this.$manual;return!!e?.drifts&&e.drifts.length>0}get $manual(){if(!this.isLayouted())return null;let e=this.#c;return e?this.#e._layout===`manual`?this.#e:memoizeProp(this,`snapshotWithManualLayout`,()=>applyManualLayout(this.#e,e)):null}get projectId(){return this.$model.projectId}roots(){return this.#t.values()}*compounds(){for(let e of this.#n.values())e.hasChildren()&&(yield e)}node(e){let t=getId(e);return nonNullable(this.#n.get(t),`Node ${t} not found in view ${this.#e.id}`)}findNode(e){return this.#n.get(getId(e))??null}findNodeWithElement(e){let t=getId(e);return this.#i.has(t)?ifind(this.#n.values(),e=>e.hasElement()&&e.element.id===t)??null:null}nodes(){return this.#n.values()}edge(e){let t=getId(e);return nonNullable(this.#r.get(t),`Edge ${t} not found in view ${this.#e.id}`)}findEdge(e){return this.#r.get(getId(e))??null}edges(){return this.#r.values()}*edgesWithRelation(e){for(let t of this.#r.values())t.includesRelation(e)&&(yield t)}*elements(){for(let e of this.#n.values())e.hasElement()&&(yield e)}isTagged(e){return this.tags.includes(e)}includesElement(e){return this.#i.has(getId(e))}includesDeployment(e){return this.#a.has(getId(e))}includesRelation(e){return this.#o.has(getId(e))}isComputed(){return this.#e[Vi]===`computed`}isLayouted(){return this.#e[Vi]===`layouted`}isDiagram(){return this.#e[Vi]===`layouted`}isElementView(){return this.#e[Hi]===`element`}isScopedElementView(){return this.#e._type===`element`&&j(this.#e.viewOf)}isDeploymentView(){return this.#e[Hi]===`deployment`}isDynamicView(){return this.#e[Hi]===`dynamic`}},Na=class LikeC4ViewsFolder{$model;path;title;isRoot;parentPath;defaultViewId;constructor(e,t,r){this.$model=e,this.path=t.join(`/`),this.isRoot=this.path===``,this.title=unescapeViewPathSegment(te(t)),this.parentPath=this.isRoot?void 0:t.slice(0,-1).join(`/`),this.defaultViewId=r}get defaultView(){return this.defaultViewId?this.$model.view(this.defaultViewId):null}get breadcrumbs(){return invariant(!this.isRoot,`Root view folder has no breadcrumbs`),memoizeProp(this,`breadcrumbs`,()=>{let e=this.parent;return e?e.isRoot?[e,this]:[...e.breadcrumbs,this]:[this]})}get parent(){return invariant(!this.isRoot,`Root view folder has no parent`),_(this.parentPath)?null:this.$model.viewFolder(this.parentPath)}get children(){return this.$model.viewFolderItems(this.path)}get folders(){return memoizeProp(this,`folders`,()=>{let e=[];for(let t of this.children)t instanceof LikeC4ViewsFolder&&e.push(t);return e})}get views(){return memoizeProp(this,`views`,()=>{let e=[];for(let t of this.children)t instanceof LikeC4ViewModel&&e.push(t);return e})}},Pa=class LikeC4Model{Aux;_elements=/* @__PURE__ */ new Map;_parents=/* @__PURE__ */ new Map;_children=new I.default(()=>/* @__PURE__ */ new Set);_rootElements=/* @__PURE__ */ new Set;_relations=/* @__PURE__ */ new Map;_incoming=new I.default(()=>/* @__PURE__ */ new Set);_outgoing=new I.default(()=>/* @__PURE__ */ new Set);_internal=new I.default(()=>/* @__PURE__ */ new Set);_views=/* @__PURE__ */ new Map;_rootViewFolder;_viewFolders=/* @__PURE__ */ new Map;_viewFolderItems=new I.default(()=>/* @__PURE__ */ new Set);_allTags=new I.default(()=>/* @__PURE__ */ new Set);static fromParsed(e){return new LikeC4Model(e)}static instances=/* @__PURE__ */ new WeakMap;static create(e){let t=this.instances.get(e);return t||(t=new LikeC4Model(e),this.instances.set(e,t)),t}static fromDump(e){let{_stage:t=`layouted`,projectId:r=`unknown`,project:i,globals:a,imports:s,deployments:c,views:l,relations:u,elements:p,specification:m}=e;return new LikeC4Model({[Vi]:t,projectId:r,project:i,globals:{predicates:a?.predicates??{},dynamicPredicates:a?.dynamicPredicates??{},styles:a?.styles??{}},imports:s??{},deployments:{elements:c?.elements??{},relations:c?.relations??{}},views:l??{},relations:u??{},elements:p??{},specification:m})}deployment;$data;constructor(e){this.$data=e;for(let[,t]of M(e.elements)){let e=this.addElement(t);for(let t of e.tags)this._allTags.get(t).add(e)}for(let[t,r]of M(e.imports??{}))for(let e of sortParentsFirst(r)){let r=this.addImportedElement(t,e);for(let e of r.tags)this._allTags.get(e).add(r)}for(let t of Fe(e.relations)){let e=this.addRelation(t);for(let t of e.tags)this._allTags.get(t).add(e)}if(this.deployment=new LikeC4DeploymentModel(this),isOnStage(e,`computed`)||isOnStage(e,`layouted`)){let t=compareNaturalHierarchically(`/`),compareViews=(e,r)=>{let i=t(e.folderPath,r.folderPath);if(i!==0)return i;let a=e.view.order,s=r.view.order;return a===s?0:a===void 0?1:s===void 0?-1:a-s},r=N(Fe(e.views),p(e=>({view:e,path:normalizeViewPath(e.title??e.id),folderPath:e.title&&getViewFolderPath(e.title)||``})),Be(compareViews)),getOrCreateFolder=e=>{let t=this._viewFolders.get(e);if(!t){let i=splitViewFolderPath(e);invariant(k(i,1),`View group path "${e}" must have at least one element`);let a;a=e===``?r.find(e=>e.view.id===`index`):r.find(t=>t.path===e),t=new Na(this,i,a?.view.id),this._viewFolders.set(e,t)}return t};this._rootViewFolder=getOrCreateFolder(``);for(let{folderPath:e}of r)this._viewFolders.has(e)||splitViewFolderPath(e).reduce((e,t)=>{let r=e.join(`/`),i=w(r)?t:r+`/`+t,a=getOrCreateFolder(i);return this._viewFolderItems.get(r).add(a),e.push(t),e},[]);for(let{view:t,folderPath:i}of r){let r=new LikeC4ViewModel(this,getOrCreateFolder(i),t,e.manualLayouts?.[t.id]);this._viewFolderItems.get(i).add(r),this._views.set(t.id,r);for(let e of r.tags)this._allTags.get(e).add(r)}}else this._rootViewFolder=new Na(this,[``],void 0),this._viewFolders.set(this._rootViewFolder.path,this._rootViewFolder)}get asParsed(){return this}get asComputed(){return this}get asLayouted(){return this}get $styles(){return memoizeProp(this,`styles`,()=>$i.from(this.project.styles,this.specification.customColors))}isParsed(){return this.stage===`parsed`}isLayouted(){return this.stage===`layouted`}isComputed(){return this.stage===`computed`}get $model(){return this.$data}get stage(){return this.$data[Vi]}get projectId(){return this.$data.projectId??`default`}get project(){return this.$data.project??memoizeProp(this,Symbol.for(`project`),()=>({id:this.projectId,styles:{},manualLayouts:{}}))}get specification(){return this.$data.specification}get globals(){return memoizeProp(this,Symbol.for(`globals`),()=>({predicates:{...this.$data.globals?.predicates},dynamicPredicates:{...this.$data.globals?.dynamicPredicates},styles:{...this.$data.globals?.styles}}))}element(e){if(e instanceof ElementModel)return e;let t=getId(e);return nonNullable(this._elements.get(t),`Element ${t} not found`)}findElement(e){let t=typeof e==`string`?e:e.id;return this._elements.get(t)??null}roots(){return this._rootElements.values()}elements(){return this._elements.values()}relationships(){return this._relations.values()}relationship(e,t){if(t===`deployment`)return this.deployment.relationship(e);let r=getId(e),i=this._relations.get(r)??null;return i||t===`model`?nonNullable(i,`Model relation ${r} not found`):nonNullable(this.deployment.findRelationship(r),`No model/deployment relation ${r} not found`)}findRelationship(e,t){if(t===`deployment`)return this.deployment.findRelationship(e);let r=this._relations.get(getId(e))??null;return r||t===`model`?r:this.deployment.findRelationship(e)}views(){return this._views.values()}view(e){let t=getId(e);return nonNullable(this._views.get(t),`View ${t} not found`)}findView(e){return this._views.get(e)??null}findManualLayout(e){return`manualLayouts`in this.$data?this.$data.manualLayouts?.[e]??null:null}viewFolder(e){return nonNullable(this._viewFolders.get(e),`View folder "${e}" not found`)}findViewFolder(e){return this._viewFolders.get(e)??null}get rootViewFolder(){return this._rootViewFolder}get hasViewFolders(){return this._viewFolders.size>1}viewFolderItems(e){return invariant(this._viewFolders.has(e),`View folder ${e} not found`),this._viewFolderItems.get(e)}parent(e){let t=getId(e);return this._parents.get(t)||null}children(e){let t=getId(e);return this._children.get(t)}*siblings(e){let t=getId(e),r=this._parents.get(t),i=r?this._children.get(r.id).values():this.roots();for(let e of i)e.id!==t&&(yield e)}*ancestors(e){let t=getId(e),r;for(;r=this._parents.get(t);)yield r,t=r.id}*descendants(e){for(let t of this.children(e))yield t,yield*this.descendants(t.id)}*incoming(e,t=`all`){let r=getId(e);for(let e of this._incoming.get(r))switch(!0){case t===`all`:case t===`direct`&&e.target.id===r:case t===`to-descendants`&&e.target.id!==r:yield e}}*outgoing(e,t=`all`){let r=getId(e);for(let e of this._outgoing.get(r))switch(!0){case t===`all`:case t===`direct`&&e.source.id===r:case t===`from-descendants`&&e.source.id!==r:yield e}}get tags(){return memoizeProp(this,`tags`,()=>Be([...this._allTags.keys()],compareNatural))}get tagsFromSpecification(){return memoizeProp(this,`tagsFromSpecification`,()=>N(Te(this.specification.tags),Be(compareNatural)))}get tagsSortedByUsage(){return memoizeProp(this,`tagsSortedByUsage`,()=>N([...this._allTags.entries()],p(([e,t])=>({tag:e,count:t.size,tagged:t})),Be((e,t)=>compareNatural(e.tag,t.tag)),Ee([A(`count`),`desc`])))}findByTag(e,t){return ifilter(this._allTags.get(e),e=>t===`elements`?e instanceof ElementModel:t===`views`?e instanceof LikeC4ViewModel:t!==`relationships`||e instanceof RelationshipModel)}*elementsOfKind(e){for(let t of this._elements.values())t.kind===e&&(yield t)}*elementsWhere(e){let t=whereOperatorAsPredicate(e);for(let e of this._elements.values())t(e)&&(yield e)}*relationshipsWhere(e){let t=whereOperatorAsPredicate(e);for(let e of this._relations.values())t(e)&&(yield e)}addElement(e){if(this._elements.has(e.id))throw Error(`Element ${e.id} already exists`);let t=new ElementModel(this,Object.freeze(e));this._elements.set(t.id,t);let r=parentFqn(t.id);return r?(invariant(this._elements.has(r),`Parent ${r} of ${t.id} not found`),this._parents.set(t.id,this.element(r)),this._children.get(r).add(t)):this._rootElements.add(t),t}addImportedElement(e,t){invariant(!isGlobalFqn(t.id),`Imported element already has global FQN`);let r=GlobalFqn(e,t.id);if(this._elements.has(r))throw Error(`Element ${r} already exists`);let i=new ElementModel(this,Object.freeze({...t,tags:this.onlyExistingTags(t.tags),id:r}));this._elements.set(i.id,i);let a=parentFqn(i.id);for(;a;){if(a.includes(`.`)&&this._elements.has(a))return this._parents.set(i.id,this.element(a)),this._children.get(a).add(i),i;a=parentFqn(a)}return this._rootElements.add(i),i}addRelation(e){if(this._relations.has(e.id))throw Error(`Relation ${e.id} already exists`);let t=new RelationshipModel(this,Object.freeze(e)),{source:r,target:i}=t;this._relations.set(t.id,t),this._incoming.get(i.id).add(t),this._outgoing.get(r.id).add(t);let a=commonAncestor(r.id,i.id);if(a)for(let e of[a,...ancestorsFqn(a)])this._internal.get(e).add(t);for(let e of ancestorsFqn(r.id)){if(e===a)break;this._outgoing.get(e).add(t)}for(let e of ancestorsFqn(i.id)){if(e===a)break;this._incoming.get(e).add(t)}return t}onlyExistingTags(e){return!e||e.length===0?[]:e.filter(e=>e in this.$data.specification.tags)}};(function(e){e.EMPTY=new Pa({_stage:`computed`,projectId:`default`,project:{id:`default`},specification:{elements:{},relationships:{},deployments:{},tags:{}},globals:{predicates:{},dynamicPredicates:{},styles:{}},deployments:{elements:{},relations:{}},elements:{},relations:{},views:{},imports:{}})})(Pa||={});let Fa;(function(e){e.isInside=e=>t=>isAncestor(e,t.source.id)&&isAncestor(e,t.target.id);let t=e.isDirectedBetween=(e,t)=>r=>(r.source.id===e||isAncestor(e,r.source.id))&&(r.target.id===t||isAncestor(t,r.target.id));e.isAnyBetween=(e,r)=>{let i=t(e,r),a=t(r,e);return e=>i(e)||a(e)};let r=e.isIncoming=e=>t=>(t.target.id===e||isAncestor(e,t.target.id))&&!isAncestor(e,t.source.id),i=e.isOutgoing=e=>t=>(t.source.id===e||isAncestor(e,t.source.id))&&!isAncestor(e,t.target.id);e.isAnyInOut=e=>{let t=r(e),a=i(e);return e=>t(e)||a(e)}})(Fa||={});const Ia=Symbol.for(`nodejs.util.inspect.custom`);var La=class DeploymentConnectionModel{source;target;relations;id;constructor(e,t,r){this.source=e,this.target=t,this.relations=r,this.id=stringHash$1(`deployment:${e.id}:${t.id}`)}get expression(){return`${this.source.id} -> ${this.target.id}`}_boundary;get boundary(){return this._boundary??=this.source.commonAncestor(this.target),this._boundary}nonEmpty(){return this.relations.nonEmpty}[Ia](e,t,r){let i=this.toString();return Object.defineProperty(i,"constructor",{value:DeploymentConnectionModel,enumerable:!1}),i}toString(){let e=[...this.relations.model].map(e=>` `+e.expression);e.length?e.unshift(` model:`):e.unshift(` model: []`);let t=[...this.relations.deployment].map(e=>` `+e.expression);return t.length?t.unshift(` deployment:`):t.unshift(` deployment: []`),[this.expression,...e,...t].join(`
|
|
40
|
+
`)}hasDirectDeploymentRelation(){for(let e of this.relations.deployment)if(e.source.id===this.source.id||e.target.id===this.target.id)return!0;return!1}*values(){yield*this.relations.model,yield*this.relations.deployment}mergeWith(e){return Array.isArray(e)?e.reduce((e,t)=>e.mergeWith(t),this):(invariant(this.source.id===e.source.id,`Cannot merge connections with different sources`),invariant(this.target.id===e.target.id,`Cannot merge connections with different targets`),new DeploymentConnectionModel(this.source,this.target,this.relations.union(e.relations)))}difference(e){return new DeploymentConnectionModel(this.source,this.target,this.relations.difference(e.relations))}intersect(e){return new DeploymentConnectionModel(this.source,this.target,this.relations.intersect(e.relations))}equals(e){return invariant(e instanceof DeploymentConnectionModel,`Other should ne DeploymentConnectionModel`),this.id===e.id&&this.source.id===e.source.id&&this.target.id===e.target.id&&equals(this.relations.model,e.relations.model)&&equals(this.relations.deployment,e.relations.deployment)}update(e){return e&&={model:this.relations.model,deployment:this.relations.deployment,...e},new DeploymentConnectionModel(this.source,this.target,e?new Aa(e.model??/* @__PURE__ */ new Set,e.deployment??/* @__PURE__ */ new Set):this.relations)}};function isNestedConnection(e,t){if(!t){let t=e;return e=>isNestedConnection(e,t)}let r=e.source===t.source,i=e.target===t.target;if(r&&i)return!1;let a=isAncestor(t.source.id,e.source.id),s=isAncestor(t.target.id,e.target.id);return a&&s||r&&s||i&&a}function findDeepestNestedConnection(e,t){let r=t;for(let t of e)isNestedConnection(t,r)&&(r=t);return r===t?null:r}function boundaryHierarchy(e){return e.boundary?.id?`.${e.boundary.id}`:``}function sortConnectionsByBoundaryHierarchy(e,t){if(!e||isString(e)){let t=e??`asc`;return e=>_sortByBoundary(e,t)}return _sortByBoundary(e,t??`asc`)}function _sortByBoundary(e,t){return N(e,p(e=>({id:boundaryHierarchy(e),conn:e})),sortNaturalByFqn(t),p(e=>e.conn))}function findAscendingConnections(e,t){return e.filter(e=>isNestedConnection(t,e))}function findDescendantConnections(e,t){return e.filter(isNestedConnection(t))}function mergeConnections(e){let t=/* @__PURE__ */ new Map;for(let r of e){let e=t.get(r.id);e?t.set(r.id,r.mergeWith(e)):t.set(r.id,r)}return[...t.values()]}function differenceConnections(e,t){let r=new Map([...t].map(e=>[e.id,e]));return[...e].reduce((e,t)=>{let i=r.get(t.id);if(!i)return e.push(t),e;let a=t.difference(i);return a.nonEmpty()&&e.push(a),e},[])}function hasSameSourceTarget(e,t){return t?e.source===t.source&&e.target===t.target:t=>e.source===t.source&&e.target===t.target}function isOutgoing(e,t){if(!t){let t=e;return e=>isOutgoing(e,t)}let r=e;return isDescendantOf(r.source,t)&&!isDescendantOf(r.target,t)}function isIncoming(e,t){if(!t){let t=e;return e=>isIncoming(e,t)}let r=e;return isDescendantOf(r.target,t)&&!isDescendantOf(r.source,t)}function isAnyInOut(e,t){if(!t){let t=e;return e=>isAnyInOut(e,t)}let r=e;return isDescendantOf(r.source,t)!==isDescendantOf(r.target,t)}var Ra=class ConnectionModel{source;target;relations;id;constructor(e,t,r=/* @__PURE__ */ new Set){this.source=e,this.target=t,this.relations=r,this.id=stringHash$1(`model:${e.id}:${t.id}`)}_boundary;get boundary(){return this._boundary??=this.source.commonAncestor(this.target)}get expression(){return`${this.source.id} -> ${this.target.id}`}get isDirect(){return this.nonEmpty()&&!this.isImplicit}get isImplicit(){return this.nonEmpty()&&isome(this.relations,qe(hasSameSourceTarget(this)))}get directRelations(){return new Set(ifilter(this.relations,hasSameSourceTarget(this)))}nonEmpty(){return this.relations.size>0}mergeWith(e){return invariant(this.source.id===e.source.id,`Cannot merge connections with different sources`),invariant(this.target.id===e.target.id,`Cannot merge connections with different targets`),new ConnectionModel(this.source,this.target,union(this.relations,e.relations))}difference(e){return new ConnectionModel(this.source,this.target,difference(this.relations,e.relations))}intersect(e){return invariant(e instanceof ConnectionModel,`Cannot intersect connection with different type`),new ConnectionModel(this.source,this.target,intersection(this.relations,e.relations))}equals(e){invariant(e instanceof ConnectionModel,`Cannot merge connection with different type`);let t=e;return this.id===t.id&&this.source.id===t.source.id&&this.target.id===t.target.id&&equals(this.relations,t.relations)}update(e){return new ConnectionModel(this.source,this.target,e)}[Ia](e,t,r){let i=this.toString();return Object.defineProperty(i,"constructor",{value:ConnectionModel,enumerable:!1}),i}toString(){return[this.expression,this.relations.size?` relations:`:` relations: [ ]`,...[...this.relations].map(e=>` `+e.expression)].join(`
|
|
41
|
+
`)}reversed(){return new ConnectionModel(this.target,this.source)}},za=/* @__PURE__ */ t({findConnection:()=>findConnection$4,findConnectionsBetween:()=>findConnectionsBetween$4,findConnectionsWithin:()=>findConnectionsWithin$3});function findConnection$4(e,t,r=`directed`){if(e===t||isSameHierarchy(e,t))return[];let i=e.allOutgoing.intersect(t.allIncoming),a=i.nonEmpty?[new La(e,t,i)]:[];return r===`directed`?a:[...a,...findConnection$4(t,e,`directed`)]}e(findConnection$4,`findConnection`);function findConnectionsBetween$4(e,t,r=`both`){if(e.allIncoming.isEmpty&&e.allOutgoing.isEmpty)return[];let i=[],a=[];for(let s of t)if(e!==s)for(let t of findConnection$4(e,s,r))t.source===e?i.push(t):a.push(t);return[...i,...a]}e(findConnectionsBetween$4,`findConnectionsBetween`);function findConnectionsWithin$3(e){return[...e].reduce((e,t,r,i)=>(r===i.length-1||e.push(...findConnectionsBetween$4(t,i.slice(r+1),`both`)),e),[])}e(findConnectionsWithin$3,`findConnectionsWithin`);var Ba=/* @__PURE__ */ t({findConnection:()=>findConnection$3,findConnectionsBetween:()=>findConnectionsBetween$3,findConnectionsWithin:()=>findConnectionsWithin$2});function findConnection$3(e,t,r=`directed`){if(e===t||isSameHierarchy(e,t))return[];let i=intersection(e.allOutgoing,t.allIncoming),a=i.size>0?new Ra(e,t,i):null;if(r===`directed`)return a?[a]:[];let s=intersection(e.allIncoming,t.allOutgoing),c=s.size>0?new Ra(t,e,s):null;return a&&c?[a,c]:a?[a]:c?[c]:[]}e(findConnection$3,`findConnection`);function findConnectionsBetween$3(e,t,r=`both`){if(e.allIncoming.size===0&&e.allOutgoing.size===0)return[];let i=[],a=[];for(let s of t)if(e!==s)for(let t of findConnection$3(e,s,r))t.source===e?i.push(t):a.push(t);return[...i,...a]}e(findConnectionsBetween$3,`findConnectionsBetween`);function findConnectionsWithin$2(e){return[...e].reduce((e,t,r,i)=>(r===i.length-1||e.push(...findConnectionsBetween$3(t,i.slice(r+1),`both`)),e),[])}e(findConnectionsWithin$2,`findConnectionsWithin`);function isDeploymentNodeModel(e){return e instanceof DeploymentNodeModel}function isDeployedInstanceModel(e){return e instanceof DeployedInstanceModel}function isDeploymentElementModel(e){return isDeploymentNodeModel(e)||isDeployedInstanceModel(e)}function isNestedElementOfDeployedInstanceModel(e){return e instanceof NestedElementOfDeployedInstanceModel}function isElementModel(e){return e instanceof ElementModel}var Va=/* @__PURE__ */ r(Ut(),1);const Ha=ga.getChild([`graphviz`,`binary`]);var GraphvizBinaryAdapter=class{_dotpath;_unflattenpath;concurrency=4;constructor(e,t){this._dotpath=e,this._unflattenpath=t}get name(){return`binary`}dispose(){}[Symbol.dispose](){}get dotpath(){return this._dotpath??memoizeProp(this,`_dotpath`,()=>{let e=Va.default.sync(`dot`);return Ha.debug`Found ${e}`,e})}get unflattenpath(){return this._unflattenpath??memoizeProp(this,`_unflattenpath`,()=>{let e=Va.default.sync(`unflatten`);return Ha.debug`Found ${e}`,e})}async unflatten(e){let t,r=Ha.getChild([`unflatten`,Ne(4)]);try{let i=await Ht(this.unflattenpath,[`-l`,`1`,`-c`,`3`],{timeout:1e4,stdin:{string:e}});t=i.stdout,w(i.stderr)?r.trace(`{command} succeeded in {durationMs}ms`,{command:i.command,durationMs:Math.round(i.durationMs)}):r.warn(`{command} has stderr:
|
|
42
|
+
`+i.stderr,{command:i.command})}catch(i){r.debug(`FAILED DOT`,{dot:e}),r.error(loggable(i)),i instanceof Vt&&!w(i.stdout)&&(r.warn(`{command} returned result but failed with exitcode {exitCode}:
|
|
43
|
+
{stderr}`,{command:i.command,exitCode:i.exitCode,stderr:i.stderr}),t=i.stdout)}return t&&(e=t.replaceAll(/\t\[/g,` [`).replaceAll(/\t/g,` `)),e}async layoutJson(e){let t=Ha.getChild([`layoutJson`,Ne(4)]),r;try{let i=await Ht(this.dotpath,[`-Tjson`,`-y`],{timeout:1e4,stdin:{string:e}});r=i.stdout,w(i.stderr)?t.trace(`{command} succeeded in {durationMs}ms`,{command:i.command,durationMs:Math.round(i.durationMs)}):t.warn(`{command} has stderr:
|
|
44
|
+
`+i.stderr,{command:i.command})}catch(i){if(t.debug(`FAILED DOT`,{dot:e}),t.error(loggable(i)),i instanceof Vt&&!w(i.stdout))t.warn(`{command} returned result but failed with exitcode {exitCode}:
|
|
45
|
+
{stderr}`,{command:i.command,exitCode:i.exitCode,stderr:i.stderr}),r=i.stdout;else throw i}return r}async acyclic(e){return Promise.reject(/* @__PURE__ */ Error(`Method not implemented.`))}async svg(e){let t=Ha.getChild([`svg`,Ne(4)]),r;try{let i=await Ht(this.dotpath,[`-Tsvg`,`-y`],{timeout:1e4,stdin:{string:e}});r=i.stdout,w(i.stderr)?t.trace(`{command} succeeded in {durationMs}ms`,{command:i.command,durationMs:Math.round(i.durationMs)}):t.warn(`{command} has stderr:
|
|
46
|
+
`+i.stderr,{command:i.command})}catch(i){if(t.debug(`FAILED DOT`,{dot:e}),t.error(loggable(i)),i instanceof Vt&&!w(i.stdout))t.warn(`{command} returned result but failed with exitcode {exitCode}:
|
|
47
|
+
{stderr}`,{command:i.command,exitCode:i.exitCode,stderr:i.stderr}),r=i.stdout;else throw i}return r}};const q=ga.getChild(`server`);function logWarnError(e){q.warn(loggable(e))}function getTelemetrySink(e){let t=getMessageOnlyFormatter();return r=>{try{switch(r.level){case`error`:case`fatal`:{let i=r.category.join(`.`);if(i===`likec4.config`)break;let a=errorFromLogRecord(r);a?e.telemetry.logEvent({eventName:`error`,message:`${a.name}: ${a.message}`,category:i,...a.stack&&{stack:a.stack}}):e.telemetry.logEvent({eventName:`error`,message:t(r),category:i});break}}}catch(e){console.error(`Error while logging to LSP connection:`,e)}}}function configureLanguageServerLogger({lspConnection:e,enableTelemetry:t=!!e,useStdErr:r=!1,logLevel:i=Kr?`debug`:`warning`,nonBlocking:a=!1,colors:s=Gr}={}){let c=!!e&&t&&!Kr;configureLogger$1({reset:!0,sinks:{console:r?getConsoleStderrSink():getConsoleSink({formatter:s?getAnsiColorFormatter():getTextFormatter(),nonBlocking:a}),...c&&{telemetry:getTelemetrySink(e)}},loggers:[{category:[`likec4`],sinks:[`console`,...c?[`telemetry`]:[]],lowestLevel:i}]}),q.trace(`logger configured`)}var Ua=/* @__PURE__ */ r(Jn(),1);const Wa=/^@[A-Za-z0-9_-]*$/,Ga=/^(?!\/|[A-Za-z]:[\\\/])(?!.*:\/\/).*$/,Ka=B.string().min(1,`Image alias key cannot be empty`).regex(Wa,`Image alias key must match /^@\\w+$/`),qa=B.string().min(1,`Image alias value cannot be empty`).regex(Ga,`Image alias value must be a relative path (no leading slash or protocol)`),Ja=B.record(Ka,qa).meta({id:`ImageAliases`,description:`Map of image alias prefixes to relative paths (keys must match /^@\\w+$/; values must be relative paths without protocol or leading slash).`}),Ya=B.string().min(1,`Include path cannot be empty`).regex(/^(?!\/|[A-Za-z]:[\\\/])(?!.*:\/\/).*$/,`Include path must be a relative path (no leading slash, drive letter, or protocol)`),Xa=B.strictObject({paths:B.array(Ya).meta({description:[`Additional relative directory paths to include LikeC4 source files from, searched recursively.`,`Paths are relative to the project folder (the folder containing this config file).`,`Example: ["../shared", "../common/specs"]`].join(`
|
|
48
|
+
`)}),maxDepth:B.number().int().min(1).max(20).default(3).meta({description:[`Maximum directory depth to scan when searching for .c4 files in include paths.`,`Prevents excessive scanning of deeply nested directories.`,`Default: 3`].join(`
|
|
49
|
+
`)}),fileThreshold:B.number().int().min(1).max(1e4).default(30).meta({description:[`Maximum number of files to load from include paths before warning.`,`Helps identify performance issues from accidentally including large directories.`,`Default: 30`].join(`
|
|
50
|
+
`)})}).meta({id:`include-config`,description:[`Configuration for including additional LikeC4 source files from other directories.`,`Example: { "paths": ["../shared", "../common/specs"], "maxDepth": 5, "fileThreshold": 50 }`].join(`
|
|
51
|
+
`)}),Za=B.int().min(0,`Opacity must be between 0 and 100`).max(100,`Opacity must be between 0 and 100`).meta({id:`Opacity`,description:`Opacity 0-100%`}),Qa=B.enum(Ni).meta({id:`ElementShape`}),$a=B.enum(Mi).meta({id:`BorderStyle`}),eo=B.enum(ki).meta({id:`ElementSize`}),to=B.enum(Ai).meta({id:`IconPosition`}),no=B.enum(fa).meta({id:`ArrowType`}),ro=B.enum([`dashed`,`solid`,`dotted`]).meta({id:`LineType`}),io=B.enum([`spline`,`ortho`]).meta({id:`EdgeRouting`}),ao=B.enum(Pi).meta({id:`ThemeColorName`}),oo=B.custom().refine(e=>typeof e==`string`,`Custom color name must be a string`).transform(e=>e).meta({id:`CustomColorName`}),so=ao.or(oo).transform(e=>e).meta({id:`ColorName`}),co=B.string().min(1,`Color value cannot be empty`).meta({id:`ColorLiteral`}),lo=B.strictObject({fill:co.meta({description:`Background color`}),stroke:co.meta({description:`Stroke color (border, paths above background)`}),hiContrast:co.meta({description:`High contrast text color (title)`}),loContrast:co.meta({description:`Low contrast text color (description)`})}).meta({id:`ElementColorValues`}).transform(e=>e),uo=B.strictObject({line:co.meta({description:`Line color`}),label:co.meta({description:`Label text color`}),labelBg:co.optional().default(`rgba(0, 0, 0, 0.5)`).meta({description:`Label background color`})}).meta({id:`RelationshipColorValues`}).transform(e=>e),fo=B.strictObject({elements:lo.or(co.transform(e=>computeColorValues(e).elements)).meta({description:`Exact color value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color values`}),relationships:uo.or(co.transform(e=>computeColorValues(e).relationships)).meta({description:`Exact color value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color values`})}).transform(e=>e).meta({id:`StrictThemeColorValues`,description:`Exact color value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color value`}).or(co.transform(e=>computeColorValues(e))).transform(e=>e).meta({id:`ThemeColorValues`,description:`Exact value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color values`}),po=B.partialRecord(so,fo).transform(e=>e),mo=B.strictObject({width:B.number().min(50),height:B.number().min(50)}).meta({id:`Dimensions`,description:`Defines dimensions for theme size`}),ho=B.partialRecord(eo,mo),go=B.strictObject({colors:po.optional().meta({description:`Override theme colors`}),sizes:ho.optional().meta({description:`Override theme sizes`})}).meta({id:`ThemeCustomization`,description:`Customize theme colors and sizes`}).transform(({colors:e,sizes:t})=>exact({colors:e?exact(e):void 0,sizes:t?exact(t):void 0})),_o=B.strictObject({color:so.optional().meta({description:`Default color for groups
|
|
52
|
+
(must be a valid color name from the theme)`}),opacity:Za.optional().meta({description:`Default opacity for groups`}),border:$a.optional().meta({description:`Default border for groups`})}).meta({id:`GroupDefaultStyleValues`}),vo=B.strictObject({color:so.optional().meta({description:`Default color for relationships
|
|
53
|
+
(must be a valid color name from the theme)`}),line:ro.optional().meta({description:`Default line style for relationships`}),arrow:no.optional().meta({description:`Default arrow style for relationships`})}).meta({id:`RelationshipDefaultStyleValues`,description:`Override default values for relationship style properties
|
|
54
|
+
These values will be used if such property is not defined`}),yo=B.strictObject({routing:io.optional().meta({description:"Default edge routing: `spline` for curves or `ortho` for right-angle bends.\nA view can override this default with its `routing` property or `autoLayout` routing parameter."})}).meta({id:`ViewDefaultValues`,description:`Default view settings.
|
|
55
|
+
Explicit settings in a view override these defaults.`}),bo=B.strictObject({color:so.optional().meta({description:`Default color for elements
|
|
56
|
+
(must be a valid color name from the theme)`}),opacity:Za.optional().meta({description:`Default opacity (0-100%) for elements when displayed as a group (like a container)`}),border:$a.optional().meta({description:`Default border style for elements when displayed as a group (like a container)`}),size:eo.optional().meta({description:`Default size for elements`}),shape:Qa.optional().meta({description:`Default shape for elements`}),iconPosition:to.optional().meta({description:`Default icon position for elements`}),group:_o.optional().meta({description:`Override default values for group style properties
|
|
57
|
+
These values will be used if such property is not defined`}),relationship:vo.optional().meta({description:`Override default values for relationship style properties
|
|
58
|
+
These values will be used if such property is not defined`}),view:yo.optional().meta({description:`Default view settings.
|
|
59
|
+
Explicit settings in a view override these defaults.`})}).meta({id:`DefaultStyleValues`}),xo=B.union([B.string().min(1,`Custom CSS file path cannot be empty`),B.array(B.string().min(1,`Custom CSS file path cannot be empty`))]).meta({id:`CustomStylesheets`}),So=B.strictObject({theme:go.optional().meta({description:`Project theme customization`}),defaults:bo.optional().meta({description:`Override default values for style properties
|
|
60
|
+
These values will be used if such property is not defined`}),customCss:xo.optional().meta({description:`Custom CSS (or list of CSS files) to be included in the generated diagrams`})}).transform(({theme:e,defaults:t,customCss:r})=>exact({defaults:normalizeDefaults(t),customCss:normalizeStylesheets(r),theme:e}));function normalizeDefaults(e){if(!e)return;let{relationship:t,group:r,view:i,...a}=e;return exact({...a,relationship:t&&exact(t),group:r&&exact(r),view:i&&exact(i)})}function normalizeStylesheets(e){if(!e)return;let t=(Array.isArray(e)?e:[e]).filter(Boolean);if(t.length!==0)return{paths:t,content:``}}const Co=[`png`,`jpg`,`dot`,`d2`,`mmd`,`puml`,`drawio`],wo=B.strictObject({outDir:B.string().default(`.likec4`).meta({description:[`Path to the directory where manual layouts will be stored,`,`relative to the folder containing the project config. `,``,`Defaults to '.likec4'.`].join(`
|
|
61
|
+
`)})}).meta({id:`ManualLayoutsConfig`,description:`Configuration for manual layouts`}),To=B.enum(Co),Eo=B.enum([`global`,`view`]),Do=B.strictObject({defaultScope:Eo.default(`view`)}),Oo=B.strictObject({exportFormats:B.array(To).refine(e=>new Set(e).size===e.length,{message:`Export formats cannot contain duplicates`}).default([...Co]).meta({description:[`Webapp export formats enabled in the generated application.`,`Omit to enable all export formats. Use an empty array to disable webapp exports.`].join(`
|
|
62
|
+
`)}),relationshipsBrowser:Do.optional()}).meta({id:`WebappConfig`,description:`Configuration for the generated web application`}),ko=B.union([B.strictObject({redirect:B.literal(!0)}),B.strictObject({include:B.array(B.string().nonempty().refine(e=>e!==`#`,{message:`selector cannot be "#"`})).nonempty(`include list cannot be empty`)}),B.strictObject({exclude:B.array(B.string().nonempty().refine(e=>e!==`#`,{message:`selector cannot be "#"`})).nonempty(`exclude list cannot be empty`)})]).meta({id:`LandingPageConfig`,description:`Configure the landing page. Use redirect to go to the index view, or include/exclude to filter the view grid.`}),Ao=B.object({name:B.string().nonempty(`Project name cannot be empty`).refine(e=>e!=="default",{abort:!0,error:`Project name cannot be "default"`}).refine(e=>!e.includes(`.`)&&!e.includes(`@`)&&!e.includes(`#`),{abort:!0,error:`Project name cannot contain ".", "@" or "#", try to use A-z, 0-9, _ and -`}).meta({description:`Project name, must be unique in the workspace`}),extends:B.union([B.string().min(1,`Extend path cannot be empty`),B.array(B.string().min(1,`Extend path cannot be empty`)).min(1,`Extend list cannot be empty`)]).optional().meta({description:`Extend styles from other config files`}),title:B.string().nonempty(`Project title cannot be empty if specified`).optional().meta({description:`A human readable title for the project`}),contactPerson:B.string().nonempty(`Contact person cannot be empty if specified`).optional().meta({description:`A person who has been involved in creating or maintaining this project`}),metadata:B.record(B.string(),B.any()).optional().meta({description:`Arbitrary metadata as key-value pairs for custom project information`}),styles:So.optional().meta({description:`Project styles customization`}),imageAliases:Ja.optional(),include:Xa.optional(),exclude:B.array(B.string()).optional().meta({description:`List of file patterns to exclude from the project, default is ["**/node_modules/**"]`}),manualLayouts:wo.optional(),inferTechnologyFromIcon:B.boolean().optional().meta({description:[`Automatically derive element technology from icon name when technology is not set explicitly.`,`Applies to aws:, azure:, gcp:, and tech: icons. Bootstrap icons are excluded.`,`Defaults to true.`].join(`
|
|
63
|
+
`)}),implicitViews:B.boolean().optional().meta({description:`Auto-generate scoped views for elements without explicit views. Defaults to false.`}),landingPage:ko.optional(),webapp:Oo.optional()}).meta({id:`LikeC4ProjectConfig`,description:`LikeC4 Project Configuration`}),jo=B.instanceof(Function),Mo=B.record(B.string(),jo);Ao.extend({generators:Mo.optional()});function validateProjectConfig(e){let t=e.landingPage,r=null;if(t!=null){let e=ko.safeParse(t);if(!e.success)throw Error(`Config validation failed:
|
|
64
|
+
`+B.prettifyError(e.error));r=e.data}let i=Ao.safeParse(e);if(!i.success)throw Error(`Config validation failed:
|
|
65
|
+
`+B.prettifyError(i.error));let a=i.data;r!==null&&(a={...a,landingPage:r});let s=e.generators;if(typeof s==`object`&&s&&!Array.isArray(s)){let e=Mo.safeParse(s);if(!e.success)throw Error(`Config validation failed (generators):
|
|
66
|
+
`+B.prettifyError(e.error));return{...a,generators:e.data}}return a}function parseProjectConfigJSON(e){return validateProjectConfig(Ua.default.parse(e.trim()||`{}`))}const No={parse:parseProjectConfigJSON,validate:validateProjectConfig,normalizeInclude:e=>{let t=Xa.safeParse(e);return t.success?t.data:{paths:[],maxDepth:3,fileThreshold:30}}};function trimTrailingSlashes(e){let t=e.length;for(;t>0&&(e[t-1]===`/`||e[t-1]===`\\`);)t--;return e.slice(0,t)}function splitPath(e){return e.split(`/`).flatMap(e=>e.split(`\\`))}function basename$1(e){let t=trimTrailingSlashes(e),r=splitPath(t);return r[r.length-1]||t}e(basename$1,`basename`);const Po=[`.likec4rc`,`.likec4.config.json`,`likec4.config.json`],Fo=[`likec4.config.js`,`likec4.config.cjs`,`likec4.config.mjs`,`likec4.config.ts`,`likec4.config.cts`,`likec4.config.mts`];[...Po,...Fo];function isLikeC4JsonConfig(e){return Po.includes(basename$1(e))}function isLikeC4NonJsonConfig(e){return Fo.includes(basename$1(e))}function isLikeC4Config(e){return isLikeC4JsonConfig(e)||isLikeC4NonJsonConfig(e)}const Io=Ao.pick({extends:!0,styles:!0}).loose(),normalizeExtends=e=>e?Array.isArray(e)?e:[e]:[],parseJsonConfig=async e=>{let t=await yr.readFile(e,`utf-8`),r;try{r=Ua.default.parse(t.trim()||`{}`)}catch(t){throw wrapError(t,`${e}:`)}if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`${e}: Config must be a JSON object`);let i=Io.safeParse(r);if(!i.success)throw Error(`${e}: Invalid config\n`+B.prettifyError(i.error));return i.data},loadJsonConfigs=async(e,t)=>{if(t.includes(e)){let r=t.indexOf(e),i=[...t.slice(r),e].join(` -> `);throw Error(`Config extends cycle detected: ${i}`)}let r=await parseJsonConfig(e),i=normalizeExtends(r.extends),a=[...t,e],s=[];for(let t of i){let r=mr(fr(e),t);s.push(...await loadJsonConfigs(r,a))}return[...s,r]};async function loadConfig(e){e=typeof e==`string`?e:e.fsPath,ga.getChild(`config`).trace`Loading config: ${pr(gr(),e)}`;let t=fr(e),r=dr(e),i={name:dr(t)};if(isLikeC4JsonConfig(r)){let t=await loadJsonConfigs(mr(e),[]);invariant(k(t,1),`Expect at least one config`);let r=We(te(t),[`extends`,`styles`]),a=t.map(e=>e.styles).filter(l),s=a.length>0?Yi({},...a.reverse()):void 0;return validateProjectConfig({...i,...r,...s?{styles:s}:{}})}invariant(isLikeC4NonJsonConfig(r),`Invalid name for config file: ${e}`);let{mod:a}=await Jr({filepath:e,cwd:t,esbuildOptions:{resolveExtensions:[`.ts`,`.mts`,`.cts`,`.mjs`,`.js`,`.cjs`],plugins:[{name:`likec4-config`,setup(e){e.onResolve({filter:/^@?likec4\/config$/},e=>({path:e.path,namespace:`likec4-config`})),e.onEnd(e=>{let t=Yr(e.errors,{kind:`error`});for(let e of t)ga.error(e)}),e.onLoad({filter:/.*/,namespace:`likec4-config`},e=>({contents:`
|
|
67
|
+
// Mock implementation to allow loading config files without bundling @likec4/config
|
|
68
|
+
function mock(x) { return x }
|
|
69
|
+
export {
|
|
70
|
+
mock as defineConfig,
|
|
71
|
+
mock as defineGenerators,
|
|
72
|
+
mock as defineStyle,
|
|
73
|
+
mock as defineTheme,
|
|
74
|
+
mock as defineThemeColor,
|
|
75
|
+
}`,loader:`js`}))}}]}});return validateProjectConfig(Object.assign(i,a?.default??a))}const Lo={aws:/* @__PURE__ */ `activate.alexa-for-business.amplify.apache-mxnet-on-aws.api-gateway.app-config.app-flow.app-mesh.app-runner.app-stream.app-sync.application-auto-scaling.application-composer.application-cost-profiler.application-discovery-service.application-migration-service.artifact.athena.audit-manager.augmented-ai-a2i.aurora.auto-scaling.backint-agent.backup.batch.billing-conductor.bottlerocket.braket.budgets.certificate-manager.chatbot.chime-sdk.chime-voice-connector.chime.clean-rooms.client-vpn.cloud-control-api.cloud-development-kit.cloud-directory.cloud-formation.cloud-front.cloud-hsm.cloud-map.cloud-search.cloud-shell.cloud-trail.cloud-wan.cloud-watch.cloud9.code-artifact.code-build.code-catalyst.code-commit.code-deploy.code-guru.code-pipeline.code-star.code-whisperer.cognito.command-line-interface.comprehend-medical.comprehend.compute-optimizer.config.connect.console-mobile-application.control-tower.corretto.cost-and-usage-report.cost-explorer.data-exchange.data-pipeline.data-sync.data-zone.database-migration-service.deep-composer.deep-learning-amis.deep-learning-containers.deep-lens.deep-racer.detective.dev-ops-guru.device-farm.direct-connect.directory-service.distro-for-open-telemetry.document-db.dynamo-db.ec2-auto-scaling.ec2-image-builder.ec2.ecs-anywhere.efs.eks-anywhere.eks-cloud.eks-distro.elasti-cache.elastic-beanstalk.elastic-block-store.elastic-container-registry.elastic-container-service.elastic-disaster-recovery.elastic-fabric-adapter.elastic-inference.elastic-kubernetes-service.elastic-load-balancing.elastic-transcoder.elemental-appliances-software.elemental-conductor.elemental-delta.elemental-link.elemental-live.elemental-media-connect.elemental-media-convert.elemental-media-live.elemental-media-package.elemental-media-store.elemental-media-tailor.elemental-server.emr.event-bridge.express-workflows.fargate.fault-injection-simulator.file-cache.fin-space.firewall-manager.forecast.fraud-detector.free-rtos.fsx-for-lustre.fsx-for-net-app-ontap.fsx-for-open-zfs.fsx-for-wfs.fsx.game-kit.game-lift.game-sparks.genomics-cli.global-accelerator.glue-data-brew.glue-elastic-views.glue.ground-station.guard-duty.health-lake.honeycode.iam-identity-center.identity-and-access-management.inspector.interactive-video-service.io-t-1-click.io-t-analytics.io-t-button.io-t-core.io-t-device-defender.io-t-device-management.io-t-edu-kit.io-t-events.io-t-express-link.io-t-fleet-wise.io-t-greengrass.io-t-robo-runner.io-t-site-wise.io-t-things-graph.io-t-twin-maker.iq.kendra.key-management-service.keyspaces.kinesis-data-analytics.kinesis-data-streams.kinesis-firehose.kinesis-video-streams.kinesis.lake-formation.lambda.launch-wizard.lex.license-manager.lightsail.local-zones.location-service.lookout-for-equipment.lookout-for-metrics.lookout-for-vision.lumberyard.macie.mainframe-modernization.managed-blockchain.managed-grafana.managed-service-for-prometheus.managed-services.managed-streaming-for-apache-kafka.managed-workflows-for-apache-airflow.management-console.marketplace-dark.marketplace-light.memory-db-for-redis.migration-evaluator.migration-hub.monitron.mq.neptune.network-firewall.neuron.nice-dcv.nice-engin-frame.nimble-studio.nitro-enclaves.omics.open-3d-engine.open-search-service.ops-works.organizations.outposts-family.outposts-rack.outposts-servers.panorama.parallel-cluster.personal-health-dashboard.personalize.pinpoint-apis.pinpoint.polly.private-5g.private-certificate-authority.private-link.professional-services.proton.quantum-ledger-database.quick-sight.rds-on-vmware.rds.re-post.red-hat-open-shift-service-on-aws.redshift.rekognition.reserved-instance-reporting.resilience-hub.resource-access-manager.resource-explorer.robo-maker.route-53.s3-on-outposts.sage-maker-ground-truth.sage-maker-studio-lab.sage-maker.savings-plans.secrets-manager.security-hub.security-lake.server-migration-service.serverless-application-repository.service-catalog.service-management-connector.shield.signer.sim-space-weaver.simple-email-service.simple-notification-service.simple-queue-service.simple-storage-service-glacier.simple-storage-service.site-to-site-vpn.snowball-edge.snowball.snowcone.snowmobile.step-functions.storage-gateway.sumerian.supply-chain.support.systems-manager.tensor-flow-on-aws.textract.thinkbox-deadline.thinkbox-frost.thinkbox-krakatoa.thinkbox-sequoia.thinkbox-stoke.thinkbox-xmesh.timestream.tools-and-sdks.torch-serve.training-certification.transcribe.transfer-family.transit-gateway.translate.trusted-advisor.verified-access.verified-permissions.virtual-private-cloud.vmware-cloud-on-aws.vpc-lattice.waf.wavelength.well-architected-tool.wickr.work-docs-sdk.work-docs.work-link.work-mail.work-spaces-family.x-ray`.split(`.`),azure:/* @__PURE__ */ `abs-member.active-directory-connect-health.activity-log.administrative-units.advisor.ai-at-edge.ai-studio.aks-automatic.aks-istio.alerts.all-resources.analysis-services.anomaly-detector.api-center.api-connections.api-management-services.api-proxy.app-compliance-automation.app-configuration.app-registrations.app-service-certificates.app-service-domains.app-service-environments.app-service-plans.app-services.app-space-component.app-space.applens.application-gateway-containers.application-gateways.application-group.application-insights.application-security-groups.aquila.arc-data-services.arc-kubernetes.arc-machines.arc-postgre-sql.arc-sql-managed-instance.arc-sql-server.atm-multistack.auto-scale.automanaged-vm.automation-accounts.availability-sets.avs-vm.azure-a.azure-ad-b2c.azure-api-for-fhir.azure-applied-ai-services.azure-arc.azure-attestation.azure-backup-center.azure-blockchain-service.azure-center-for-sap.azure-chaos-studio.azure-cloud-shell.azure-communication-services.azure-communications-gateway.azure-compute-galleries.azure-consumption-commitment.azure-cosmos-db.azure-data-catalog.azure-data-explorer-clusters.azure-database-maria-db-server.azure-database-migration-services.azure-database-my-sql-server.azure-database-postgre-sql-server-group.azure-database-postgre-sql-server.azure-databox-gateway.azure-databricks.azure-deployment-environments.azure-dev-ops.azure-dev-tunnels.azure-edge-hardware-center.azure-experimentation-studio.azure-fileshares.azure-firewall-manager.azure-firewall-policy.azure-hcp-cache.azure-hpc-workbenches.azure-hybrid-center.azure-information-protection.azure-io-t-operations.azure-lighthouse.azure-load-testing.azure-managed-grafana.azure-managed-redis.azure-maps-accounts.azure-media-service.azure-migrate.azure-monitor-dashboard.azure-monitor-pipeline.azure-monitors-for-sap-solutions.azure-net-app-files.azure-network-function-manager-functions.azure-network-function-manager.azure-object-understanding.azure-open-ai.azure-operator-5g-core.azure-operator-insights.azure-operator-nexus.azure-operator-service-manager.azure-orbital.azure-programmable-connectivity.azure-purview-accounts.azure-quotas.azure-red-hat-open-shift.azure-sentinel.azure-service-bus.azure-sphere.azure-spring-apps.azure-sql-edge.azure-sql-server-stretch-databases.azure-sql-vm.azure-sql.azure-stack-edge.azure-stack-hci-sizer.azure-stack.azure-storage-mover.azure-support-center-blue.azure-sustainability.azure-synapse-analytics.azure-token-service.azure-video-indexer.azure-virtual-desktop.azure-vmware-solution.azure-workbooks.azurite.backlog.backup-vault.bare-metal-infrastructure.bastions.batch-accounts.batch-ai.biz-talk.blob-block.blob-page.blockchain-applications.blueprints.bonsai.bot-services.branch.breeze.browser.bug.builds.business-process-tracking.cache-redis.cache.capacity-reservation-groups.capacity.cdn-profiles.central-service-instance-for-sap.ceres.change-analysis.client-apps.cloud-services-classic.cloud-services-extended-support.cloud-test.code-optimization.code.cognitive-search.cognitive-services-decisions.cognitive-services.collaborative-service.commit.community-images.compliance-center.compliance.compute-fleet.computer-vision.conditional-access.confidential-ledgers.connected-cache.connected-vehicle-platform.connections.consortium.container-apps-environments.container-instances.container-registries.container-services-deprecated.content-moderators.content-safety.controls-horizontal.controls.cost-alerts.cost-analysis.cost-budgets.cost-export.cost-management-and-billing.cost-management.counter.cubes.custom-ip-prefix.custom-vision.customer-lockbox-for-microsoft-azure.dashboard-hub.dashboard.data-box.data-collection-rules.data-factories.data-lake-analytics.data-lake-storage-gen1.data-lake-store-gen1.data-share-invitations.data-shares.data-virtualization.database-instance-for-sap.ddo-s-protection-plans.dedicated-hsm.defender-cm-local-manager.defender-dcs-controller.defender-distributer-control-system.defender-engineering-station.defender-external-management.defender-freezer-monitor.defender-historian.defender-hmi.defender-industrial-packaging-system.defender-industrial-printer.defender-industrial-robot.defender-industrial-scale-system.defender-marquee.defender-meter.defender-plc.defender-pneumatic-device.defender-programable-board.defender-relay.defender-robot-controller.defender-rtu.defender-sensor.defender-slot.defender-web-guiding-system.detonation.dev-console.dev-ops-starter.dev-test-labs.device-compliance.device-configuration.device-enrollment.device-provisioning-services.device-security-apple.device-security-google.device-security-windows.device-update-io-t-hub.devices.diagnostics-settings.digital-twins.disk-encryption-sets.disk-pool.disks-classic.disks-snapshots.disks.dns-multistack.dns-private-resolver.dns-security-policy.dns-zones.download.e-books.edge-actions.edge-management.edge-storage-accelerator.education.elastic-job-agents.elastic-san.endpoint-analytics.engage-center-connect.enterprise-applications.entra-connect-health.entra-connect-sync.entra-connect.entra-domain-services.entra-global-secure-access.entra-id-protection.entra-identity-custom-roles.entra-identity-licenses.entra-identity-risky-signins.entra-identity-risky-users.entra-identity-roles-and-administrators.entra-internet-access.entra-managed-identities.entra-private-access.entra-privleged-identity-management.entra-verified-id.error.event-grid-domains.event-grid-subscriptions.event-grid-topics.event-hub-clusters.event-hubs.exchange-access.exchange-on-premises-access.express-route-circuits.express-route-direct.express-route-traffic-collector.extended-security-updates.extensions.external-id-modified.external-id.external-identities.face-apis.feature-previews.fhir-service.fiji.file.files.firewalls.folder-blank.folder-website.form-recognizers.frd-qa.free-services.front-door-and-cdn-profiles.ftp.function-apps.gear.genomics-accounts.genomics.globe-error.globe-success.globe-warning.groups.guide.hd-insight-clusters.hdi-aks-cluster.heart.help-and-support.host-groups.host-pools.hosts.hybrid-connectivity-hub.ic-m-troubleshooting.identity-governance.identity-multi-factor-authentication.identity-secure-score.image-definitions.image-templates.image-versions.image.images.immersive-readers.import-export-jobs.industrial-io-t.information.infrastructure-backup.input-output.instance-pools.integration-accounts.integration-environments.integration-service-environments.internet-analyzer-profiles.intune-app-protection.intune-for-education.intune-trends.intune.io-t-central-applications.io-t-edge.io-t-hub.ip-address-manager.ip-groups.journey-hub.key-vaults.keys.kubernetes-fleet-manager.kubernetes-services.lab-accounts.lab-services.landing-zone.language-understanding.language.launch-portal.learn.load-balancer-hub.load-balancers.load-test.load-testing.local-network-gateways.location.log-analytics-query-pack.log-analytics-workspaces.log-streaming.logic-apps-custom-connector.logic-apps-template.logic-apps.machine-learning-studio-classic-web-services.machine-learning-studio-web-service-plans.machine-learning-studio-workspaces.machine-learning.machines-azure-arc.maintenance-configuration.managed-applications-center.managed-database.managed-desktop.managed-dev-ops-pools.managed-file-shares.managed-identities.managed-instance-apache-cassandra.managed-service-fabric.management-groups.management-portal.marketplace-management.marketplace.med-tech-service.media-file.media.mesh-applications.metrics-advisor.metrics.microsoft-defender-easm.microsoft-defender-for-cloud.microsoft-defender-for-io-t.microsoft-dev-box.mindaro.mission-landing-zone.mobile-engagement.mobile-networks.mobile.modular-data-center.module.monitor-health-models.monitor.multi-tenancy.multifactor-authentication.my-customers.nat.network-foundation-hub.network-interfaces.network-managers.network-security-groups.network-security-hub.network-security-perimeters.network-watcher.notification-hub-namespaces.notification-hubs.offers.on-premises-data-gateways.open-supply-chain-platform.operation-log-classic.oracle-database.os-images-classic.osconfig.outbound-connection.partner-namespace.partner-registration.partner-topic.peering-service.peerings.personalizers.planetary-computer-pro.plans.policy.power-bi-embedded.power-platform.power-up.power.powershell.preview-features.private-endpoints.private-link-service.private-link-services.private-link.process-explorer.production-ready-database.promethus.proximity-placement-groups.public-ip-addresses-classic.public-ip-addresses.public-ip-prefixes.qn-a-makers.quickstart-center.recent.recovery-services-vaults.region-management.relays.remote-rendering.reservations.reserved-capacity.reserved-ip-addresses-classic.resource-explorer.resource-graph-explorer.resource-group-list.resource-groups.resource-guard.resource-linked.resource-management-private-link.resource-mover.resources-provider.restore-points-collections.restore-points.route-filters.route-tables.rtos.savings-plans.scheduler-job-collections.scheduler.scvmm-management-servers.search-grid.search.security-baselines.security.send-grid-accounts.server-farm.serverless-search.service-catalog-mad.service-endpoint-policies.service-fabric-clusters.service-group-relationships.service-groups.service-health.service-providers.shared-image-galleries.signal-r.software-as-a-service.software-updates.solutions.sonic-dash.spatial-anchor-accounts.speech-services.spot-vm.spot-vmss.sql-data-warehouses.sql-database-fleet-manager.sql-database.sql-elastic-pools.sql-managed-instance.sql-server-registries.sql-server.ssd.ssh-keys.ssis-lift-and-shift-ir.stack-hci-premium.static-apps.stor-simple-data-managers.stor-simple-device-managers.storage-accounts-classic.storage-accounts.storage-actions.storage-azure-files.storage-container.storage-explorer.storage-functions.storage-hubs.storage-queue.storage-sync-services.stream-analytics-jobs.subnet.subscriptions.system-topic.table.tag.tags.targets-management.template-specs.templates.tenant-properties.tenant-status.test-base.tfs-vc-repository.time-series-data-sets.time-series-insights-access-policies.time-series-insights-environments.time-series-insights-event-sources.toolbox.toolchain-orchestrator.traffic-manager-profiles.translator-text.troubleshoot.universal-print.update-management-center.updates.user-privacy.user-settings.user-subscriptions.users.verifiable-credentials.verification-as-a-service.versions.video-analyzers.virtual-clusters.virtual-enclaves.virtual-instance-for-sap.virtual-machine.virtual-machines-classic.virtual-network-gateways.virtual-networks-classic.virtual-networks.virtual-router.virtual-visits-builder.virtual-wan-hub.virtual-wans.vm-app-definitions.vm-app-versions.vm-image-version.vm-images-classic.vm-scale-sets.vpnclient-windows.wac-installer.wac.web-app-database.web-application-firewall-policies-waf.web-jobs.web-slots.web-test.website-power.website-staging.windows-notification-services.windows10-core-services.workbooks.worker-container-app.workflow.workload-orchestration.workspace-gateway.workspaces`.split(`.`),gcp:/* @__PURE__ */ `access-context-manager.administration.advanced-agent-modeling.advanced-solutions-lab.agent-assist.ai-hub.ai-platform-unified.ai-platform.analytics-hub.anthos-config-management.anthos-service-mesh.anthos.api-analytics.api-monetization.api.apigee-api-platform.apigee-sense.app-engine.artifact-registry.asset-inventory.assured-workloads.auto-ml-natural-language.auto-ml-tables.auto-ml-translation.auto-ml-video-intelligence.auto-ml-vision.auto-ml.bare-metal-solutions.batch.beyondcorp.big-query.bigtable.billing.binary-authorization.catalog.certificate-authority-service.certificate-manager.cloud-api-gateway.cloud-apis.cloud-armor.cloud-asset-inventory.cloud-audit-logs.cloud-build.cloud-cdn.cloud-code.cloud-composer.cloud-data-fusion.cloud-deploy.cloud-deployment-manager.cloud-dns.cloud-domains.cloud-ekm.cloud-endpoints.cloud-external-ip-addresses.cloud-firewall-rules.cloud-for-marketing.cloud-functions.cloud-generic.cloud-gpu.cloud-healthcare-api.cloud-healthcare-marketplace.cloud-hsm.cloud-ids.cloud-inference-api.cloud-interconnect.cloud-jobs-api.cloud-load-balancing.cloud-logging.cloud-media-edge.cloud-monitoring.cloud-nat.cloud-natural-language-api.cloud-network.cloud-ops.cloud-optimization-ai-fleet-routing-api.cloud-optimization-ai.cloud-router.cloud-routes.cloud-run-for-anthos.cloud-run.cloud-scheduler.cloud-security-scanner.cloud-shell.cloud-spanner.cloud-sql.cloud-storage.cloud-tasks.cloud-test-lab.cloud-tpu.cloud-translation-api.cloud-vision-api.cloud-vpn.compute-engine.configuration-management.connectivity-test.connectors.contact-center-ai.container-optimized-os.container-registry.data-catalog.data-labeling.data-layers.data-loss-prevention-api.data-qn-a.data-studio.data-transfer.database-migration-service.dataflow.datalab.dataplex.datapol.dataprep.dataproc-metastore.dataproc.datashare.datastore.datastream.debugger.developer-portal.dialogflow-cx.dialogflow-insights.dialogflow.document-ai.early-access-center.error-reporting.eventarc.filestore.financial-services-marketplace.firestore.fleet-engine.free-trial.game-servers.gce-systems-management.genomics.gke-on-prem.google-cloud-marketplace.google-kubernetes-engine.google-maps-platform.healthcare-nlp-api.home.identity-and-access-management.identity-aware-proxy.identity-platform.iot-core.iot-edge.key-access-justifications.key-management-service.kuberun.launcher.local-ssd.looker.managed-service-for-microsoft-active-directory.media-translation-api.memorystore.migrate-for-anthos.migrate-for-compute-engine.my-cloud.network-connectivity-center.network-intelligence-center.network-security.network-tiers.network-topology.onboarding.os-configuration-management.os-inventory-management.os-patch-management.partner-interconnect.partner-portal.performance-dashboard.permissions.persistent-disk.phishing-protection.policy-analyzer.premium-network-tier.private-connectivity.private-service-connect.producer-portal.profiler.project.pub-sub.quantum-engine.quotas.real-world-insights.recommendations-ai.release-notes.retail-api.risk-manager.runtime-config.secret-manager.security-command-center.security-health-advisor.security-key-enforcement.security.service-discovery.speech-to-text.stackdriver.standard-network-tier.stream-suite.support.tensorflow-enterprise.text-to-speech.tools-for-powershell.trace.traffic-director.transfer-appliance.transfer.user-preferences.vertex-ai.video-intelligence-api.virtual-private-cloud.visual-inspection.vmware-engine.web-risk.web-security-scanner.workflows.workload-identity-pool`.split(`.`),tech:/* @__PURE__ */ `100tb.500px.aarch64.active-campaign-icon.active-campaign.adobe-after-effects.adobe-animate.adobe-dreamweaver.adobe-icon.adobe-illustrator.adobe-incopy.adobe-indesign.adobe-lightroom.adobe-photoshop.adobe-premiere-pro.adobe-premiere.adobe-xd.adobe.adonis-js.adonisjs-icon.adroll.adyen.aerogear.aerospike-icon.aerospike.after-effects.aha.airbnb-icon.airbnb.airbrake.airflow-icon.airflow.airtable.aix.akamai.akka.alfresco.algolia.alpinejs-icon.alpinejs.altair.amazon-chime.amazon-connect.amazon-web-services.amd.amex-digital.amex.amp-icon.amp.ampersand.amplication-icon.amplication.amplitude-icon.amplitude.anaconda.analog.android-icon.android-studio.android-vertical.android.angellist.angular-icon.angular-js.angular.ansible.ant-design.anthropic-icon.anthropic.apache-camel.apache-cloudstack.apache-flink-icon.apache-flink.apache-spark.apache-superset-icon.apache-superset.apache.apiary.apidog-icon.apidog.apl.apollostack.apostrophe.appbaseio-icon.appbaseio.appcelerator.appcenter-icon.appcenter.appcircle-icon.appcircle.appcode.appdynamics-icon.appdynamics.appium.apple-app-store.apple-pay.apple-safari.apple.applitools-icon.applitools.appsignal-icon.appsignal.apptentive.appveyor.appwrite-icon.appwrite.arangodb-icon.arangodb.arc.architect-icon.architect.archlinux.arduino.argo-icon.argo.argocd.arm.armory-icon.armory.asana-icon.asana.asciidoctor.assembla-icon.assembla.astro-icon.astro.astronomer.async-api-icon.async-api.atlassian.atom-icon.atom.atomic-icon.atomic.atomicojs-icon.atomicojs.aurelia.aurora.auth0-icon.auth0.authy.autodesk-maya.autodesk-shot-grid.autoit.autoprefixer.ava.awesome.awk.aws-amplify.aws-api-gateway.aws-app-mesh.aws-appflow.aws-appsync.aws-athena.aws-aurora.aws-backup.aws-batch.aws-certificate-manager.aws-cloudformation.aws-cloudfront.aws-cloudsearch.aws-cloudtrail.aws-cloudwatch.aws-codebuild.aws-codecommit.aws-codedeploy.aws-codepipeline.aws-codestar.aws-cognito.aws-config.aws-documentdb.aws-dynamodb.aws-ec2.aws-ecs.aws-eks.aws-elastic-beanstalk.aws-elasticache.aws-elb.aws-eventbridge.aws-fargate.aws-glacier.aws-glue.aws-iam.aws-keyspaces.aws-kinesis.aws-kms.aws-lake-formation.aws-lambda.aws-lightsail.aws-mq.aws-msk.aws-neptune.aws-open-search.aws-opsworks.aws-quicksight.aws-rds.aws-redshift.aws-route53.aws-s3.aws-secrets-manager.aws-ses.aws-shield.aws-sns.aws-sqs.aws-step-functions.aws-systems-manager.aws-timestream.aws-vpc.aws-waf.aws-xray.aws.axios.azios.azure-devops.azure-sql-database.azure.babel.backbone-icon.backbone-js.backbone.backerkit.baker-street.balena.ballerina.bamboo.basecamp-icon.basecamp.basekit.baseline.bash-icon.bash.batch.beats.behance.bem-2.bem.bigpanda.bing.biomejs-icon.biomejs.bitbar.bitbucket.bitcoin.bitnami.bitrise-icon.bitrise.blender.blitzjs-icon.blitzjs.blocs.blogger.blossom.blueprint.bluesky.bluetooth.booqable-icon.booqable.bootstrap.bosun.botanalytics.bourbon.bower.box.brackets.brainjs.branch-icon.branch.brandfolder-icon.brandfolder.brave.braze-icon.braze.broadcom-icon.broadcom.broccoli.brotli.browserify-icon.browserify.browserling.browserslist.browserstack.browsersync.brunch.bubble-icon.bubble.buck.buddy.buffer.bugherd-icon.bugherd.bugsee.bugsnag.builder-io-icon.builder-io.buildkite-icon.buildkite.bulma.bun.bunny-net-icon.bunny-net.c.cachet.cairo-graphics.cake-php.cakephp-icon.calibre-icon.calibre.campaignmonitor-icon.campaignmonitor.canjs.canva.capacitor.capacitorjs-icon.capacitorjs.capistrano.carbide.cardano-icon.cardano.cassandra.cent-os.centos-icon.certbot.ceylon.chai.chalk.chargebee-icon.chargebee.chartjs.chef.chevereto.chroma.chromatic-icon.chromatic.chrome-web-store.chrome.cinder.circle-ci.cirrus-ci.cirrus.clarity.claude-icon.claude.clio-lang.clion.cljs.clojure-script.clojure.close.cloud9.cloudacademy-icon.cloudacademy.cloudcraft.cloudflare-icon.cloudflare-workers-icon.cloudflare-workers.cloudflare.cloudinary-icon.cloudinary.cloudlinux.cmake.cobalt.cockpit.cocoapods.coda-icon.coda.codacy.code-igniter.code-pen.codeac.codebase.codebeat.codecademy.codeception.codeclimate-icon.codeclimate.codecov-icon.codecov.codefactor-icon.codefactor.codeigniter-icon.codepen-icon.codersrank-icon.codersrank.coderwall.codesandbox-icon.codesandbox.codesee-icon.codesee.codio.codium-icon.codium.coffee-script.commitizen.compass.componentkit.compose-multiplatform.compose.composer.conan-io.concourse.concretecms-icon.concretecms.conda.confluence.consul.contao.contentful.convox-icon.convox.copyleft-pirate.copyleft.corda.cordova.cosmosdb.couchbase.couchdb-icon.couchdb.coursera.coveralls.cpanel.cplusplus.craftcms.crashlytics.crateio.create-react-app.createjs.crossplane-icon.crossplane.crucible.crystal.csharp.css3-official.css3.cssnext.cube-icon.cube.cucumber.curl.customerio-icon.customerio.cyclejs.cypress-icon.cypress.d3.d3js.dailydev-icon.dailydev.daisy-ui-icon.daisy-ui.danfo.dart.dashlane-icon.dashlane.data-grip.data-spell.data-station.database-labs.datadog-icon.datadog.datasette-icon.datasette.datocms-icon.datocms.dbeaver.dbt-icon.dbt.dcos-icon.dcos.debian.delighted-icon.delighted.deno.dependabot.deployhq-icon.deployhq.derby.descript-icon.descript.designernews.deviantart-icon.deviantart.devicon.dgraph-icon.dgraph.dialogflow.digital-ocean-icon.digital-ocean.dimer.dinersclub.discord-icon.discord-js.discord.discourse-icon.discourse.discover.disqus.django-icon.django-rest.django.dockbit.docker-icon.docker.doctrine.docusaurus.dojo-icon.dojo-toolkit.dojo.dolt.dotnet.dovetail-icon.dovetail.dreamhost.dribbble-icon.dribbble.drift.drip.drizzle-icon.drizzle.drone-icon.drone.drools-icon.drools.dropbox.dropmark.dropwizard.dropzone.drupal-icon.drupal.duckduckgo.dynatrace-icon.dynatrace.dyndns.ebanx.eclipse-ceylon.eclipse-icon.eclipse-ide.eclipse-vert-x.eclipse.ecma.edgedb.edgio-icon.edgio.editorconfig.effect-icon.effect.effector.egghead.elasticbeats.elasticpath-icon.elasticpath.elasticsearch.electron.element.elemental-ui.elementary.eleventy-11ty.eleventy.elixir.ello.elm-classic.elm.elo.emacs-classic.emacs.embedded-c.embedly.ember-js.ember-tomster.ember.emmet.enact.engine-yard-icon.engine-yard.envato.envoy-icon.envoy.envoyer.eraser-icon.eraser.erlang.esbuild.esdoc.eslint-old.eslint.eta-icon.eta.etcd.ethereum-color.ethereum.ethers.ethnio.eventbrite-icon.eventbrite.eventsentry.evergreen-icon.evergreen.expo-icon.expo.express.fabric.facebook.faker.falcor.fast-api.fastapi-icon.fastify-icon.fastify.fastlane.fastly.fauna-icon.fauna.feathers.feathersjs.fedora.fetch.ffmpeg-icon.ffmpeg.figma.file-zilla.firebase-icon.firebase.firefox.flannel.flarum.flask.flat-ui.flattr-icon.flattr.fleep.flickr-icon.flickr.flight.floodio.flow.flowxo.floydhub.flutter.flux.fluxxor.fly-icon.fly.fogbugz-icon.fogbugz.fomo-icon.fomo.font-awesome.forestadmin-icon.forestadmin.forever.formkeep.fortran.foundation.foundationdb-icon.foundationdb.framer.framework7-icon.framework7.freebsd.freedcamp-icon.freedcamp.freedomdefined.fresh.frontapp.fsharp.fuchsia.galliumos.game-analytics-icon.game-analytics.ganache-icon.ganache.gatling.gatsby.gazebo.gcc.geekbot.geetest-icon.geetest.gentoo.getyourguide.ghost.giantswarm.gimp.gin.git-icon.git.gitboard.gitbook.github-actions.github-codespaces.github-copilot.github-icon.github-octocat.github.gitkraken.gitlab-icon.gitlab.gitpod.gitter.gitup.glamorous-icon.glamorous.gleam.glimmerjs.glint.glitch-icon.glitch.gnome-icon.gnome.gnu-emacs.gnu-net.gnu.gnupg-icon.gnupg.go-land.go.gocd.godot-engine.godot-icon.godot.gohorse.google-360suite.google-admob.google-ads.google-adsense.google-analytics.google-bard-icon.google-bard.google-calendar.google-cloud-functions.google-cloud-run.google-cloud.google-data-studio.google-developers.google-domains-icon.google-domains.google-drive.google-fit.google-gemini.google-gmail.google-home.google-icon.google-keep.google-maps.google-marketing-platform.google-meet.google-one.google-optimize.google-palm.google-pay.google-photos.google-play-console-icon.google-play-console.google-play-icon.google-play.google-search-console.google-tag-manager.google-workspace.google.gopher.gradio-icon.gradio.gradle.grafana.grails.grammarly-icon.grammarly.graphene.graphql.grav.gravatar-icon.gravatar.graylog-icon.graylog.greensock-icon.greensock.gridsome-icon.gridsome.grommet.groovehq.groovy.grove.growth-book-icon.growth-book.grpc.grunt.gruntjs.gulp.gulpjs.gunicorn.gunjs.gusto.gwt.hack.hacker-one.hadoop.haiku-icon.haiku.haml.hanami.handlebars.hapi.hardhat-icon.hardhat.harness-icon.harness.harvester.hashicorp-icon.hashicorp-vault.hashicorp.hashnode-icon.hashnode.haskell-icon.haskell.hasura-icon.hasura.haxe.haxl.hbase.hcaptcha-icon.hcaptcha.headlessui-icon.headlessui.heap-icon.heap.helm.helpscout-icon.helpscout.hermes.heroku-icon.heroku-redis.heroku.hexo.hhvm.hibernate.highcharts.hipercard.homebrew.hono.hookstate.hootsuite-icon.hootsuite.hosted-graphite.hostgator-icon.hostgator.hotjar-icon.hotjar.houndci.html5-boilerplate.html5.htmx-icon.htmx.httpie-icon.httpie.hubspot.hugging-face-icon.hugging-face.huggy.hugo.humongous.hyper.hyperapp.ibm-spss-statistics.ibm.ie10.ieee.ietf.ifttt.imagemin.imba-icon.imba.immer-icon.immer.immutable.impala.importio-icon.importio.incident-icon.incident.infer.inferno.influxdb-icon.influxdb.ink.inkscape.insomnia.instagram-icon.instagram.intel.intellij-idea.intercom-icon.intercom.internet-computer-icon.internet-computer.internetexplorer.invision-icon.invision.ionic-icon.ionic.ios.iron-icon.iron.itsalive-icon.itsalive.jade.jaeger.jamstack-icon.jamstack.jasmine.java.javascript.jcb.jeet.jekyll.jenkins.jest.jetbrains-icon.jetbrains-space-icon.jetbrains-space.jetbrains.jfrog.jhipster-icon.jhipster.jira-align.jira.joomla.jotai.jquery-mobile.jquery.jruby.jsbin.jsdelivr.jsdom.jsfiddle.json-ld.json-schema-icon.json-schema.json.jspm.jss.juju.jule.julia.junit.jupyter.jwt-icon.jwt.k3os.k3s.kafka-icon.kafka.kaggle.kaios.kallithea.karate.karma.katalon-icon.katalon.kde.keen.kemal.keras.keycdn-icon.keycdn.keydb-icon.keydb.keystonejs.khan-academy-icon.khan-academy.kibana.kickstarter-icon.kickstarter.kinto-icon.kinto.kirby-icon.kirby.knex-js.knex.knockout.koa.kong-icon.kong.kops.koreio.kotlin-icon.kotlin.kraken.krakenjs.ktor-icon.ktor.kubernetes.kustomer.labview.languagetool.laravel.lastfm.lateral-icon.lateral.latex.launchdarkly-icon.launchdarkly.launchrock.leaflet.leankit-icon.leankit.lerna.less-js.less.lets-cloud.letsencrypt.leveldb.lexical-icon.lexical.liftweb.lighthouse.lightstep-icon.lightstep.lighttpd.linear-icon.linear.linkedin-icon.linkedin.linkerd.linode.linux-mint.linux-tux.linux.liquibase.lit-icon.lit.litmus.livewire.llvm.loader.lodash.logentries.logstash.lookback.looker-icon.looker.loom-icon.loom.loopback-icon.loopback.losant.lua.lucene-net.lucene.lumen.mac-os.madge.maestro.mageia.magento.mailchimp-freddie.mailchimp.maildeveloper.mailgun-icon.mailgun.mailjet-icon.mailjet.malinajs.manjaro.mantine-icon.mantine.mapbox-icon.mapbox.maps-me.mapzen-icon.mapzen.mariadb-icon.mariadb.marionette.markdown.marko.marvel.mastercard.mastodon-icon.mastodon.material-ui.materialize.materializecss.matlab.matomo-icon.matomo.matplotlib-icon.matplotlib.matter-icon.matter.mattermost-icon.mattermost.mautic-icon.mautic.maven.mdn.mdx.medium-icon.medium.medusa-icon.medusa.meilisearch.memcached.memgraph.mention.mercurial.mesos.messenger.meta-icon.meta.metabase.metamask-icon.metamask.meteor-icon.meteor-js.meteor.micro-icon.micro-python.micro.microcosm.micron-icon.micron.microsoft-azure.microsoft-edge.microsoft-icon.microsoft-onedrive.microsoft-power-bi.microsoft-sql-server.microsoft-teams.microsoft-windows-icon.microsoft-windows.microsoft.mida-icon.mida.middleman.midjourney.milligram.million-icon.million.milvus-icon.milvus.mindsdb-icon.mindsdb.minitab.mint-lang.mio.miro-icon.miro.mist.mistral-ai-icon.mistral-ai.mithril.mixmax.mixpanel.mlab.mob-x.mocha.mockflow-icon.mockflow.modernizr.modx-icon.modx.moleculer.momentjs.monday-icon.monday.monero.mongodb-icon.mongodb.mongoose-js.mono.moodle.moon.mootools.morpheus-icon.morpheus.mozilla.mparticle-icon.mparticle.mps-icon.mps.ms-dos.msw-icon.msw.multipass.mysql-icon.mysql.naiveui.namecheap.nano.nanonets.nasm.nativescript.nats-icon.nats.neat.neo4j.neon-icon.neon.neovim.nerog.nestjs.net-core.net.netbeans.netflix-icon.netflix.netlify-icon.netlify.network-x.neverinstall-icon.neverinstall.new-relic-icon.new-relic.new4j.nextjs-icon.nextjs.nginx.ngrok.nhibernate.nhost-icon.nhost.nightwatch.nim-lang.nim.nimble.nix.nocodb.nodal.node-sass.nodebots.nodejs-icon-alt.nodejs-icon.nodejs.nodemon.nodeos.nodewebkit.nomad-icon.nomad.notion-icon.notion.noysi.npm-icon.npm.nuclide.nuget.num-py.nuxt-icon.nuxt-js.nuxt.nvidia.nvm.nx.oauth.objective-c.observablehq.obsidian-icon.obsidian.ocaml.octodns.octopus-deploy.oh-my-zsh.okta-icon.okta.olark.onesignal.open-al.open-api.open-cl.open-cv.open-gl.open-graph.open-stack.open-suse.open-telemetry.open-zeppelin-icon.open-zeppelin.openai-icon.openai.openapi-icon.opencart.opencollective.openframeworks.openjs-foundation-icon.openjs-foundation.openlayers.opensearch-icon.opensearch.openshift.opensource.openstack-icon.opentelemetry-icon.opera.opsgenie.optimizely-icon.optimizely.oracle.oreilly.origami.origin.oshw.osquery.overloop-icon.overloop.p5js.packer.pagekit.pagekite.pagerduty-icon.pagerduty.panda.pandacss-icon.pandacss.pandas-icon.pandas.parcel-icon.parcel.parse.parsehub.partytown-icon.partytown.passbolt-icon.passbolt.passport.patreon.payload.paypal.peer5.pepperoni.percona.percy-icon.percy.perf-rocks.perl.perplexity-icon.perplexity.pf-sense.phalcon.phoenix-framework.phoenix.photon-engine.php-alt.php-storm.php.pinecone-icon.pinecone.pinia.pinterest.pipedream.pipedrive.pipefy.pivotal-tracker.pixijs.pkg.planetscale.planless-icon.planless.plasmic.plastic-scm.platformio.play.playwright.playwrite.ploty.pluralsight-icon.pluralsight.pm2-icon.pm2.pnpm.pocket-base.podman.poeditor.polygon.polymer.portainer.postcss.postgraphile.postgresql.posthog-icon.posthog.postman-icon.postman.pouchdb.powershell.preact.precursor.prerender-icon.prerender.prestashop-icon.prestashop.presto-icon.presto.prettier.prisma.prismic-icon.prismic.processing.processwire-icon.processwire.productboard-icon.productboard.producthunt.progress.prometheus.promises.proofy.protoio.protonet.protractor.prott.pug.pulumi-icon.pulumi.pumpkindb.puppet-icon.puppet.puppeteer.purescript-icon.purescript.pushbullet.pusher-icon.pusher.putty.pwa.pycharm.pypi.pyscript.pytest.python-poetry.python.pytorch-icon.pytorch.pyup.q.qdrant-icon.qdrant.qlik.qodana.qt.qualcomm.quarkus-icon.quarkus.quasar.quay.quobyte.quora.qwik-icon.qwik.r-lang.r.rabbitmq-icon.rabbitmq.rackspace-icon.rackspace.rails.ramda.raml.rancher-icon.rancher.raphael.raspberry-pi.rax.reach.react-bootstrap.react-query-icon.react-query.react-router.react-spring.react-styleguidist.react.reactivex.realm.reapp.reasonml-icon.reasonml.recaptcha.recoil-icon.recoil.red-cube-s-epic-compiler-thingy-programming-re-ct.reddit-icon.reddit.redhat-icon.redhat.redis.redsmin.redux-observable.redux-saga.redux.redwoodjs.reindex.relay.release.remix-icon.remix.ren-py.renovatebot.replay-icon.replay.replit-icon.replit.require.rescript-icon.rescript.rest-li.rethinkdb.retool-icon.retool.riak.rider.riot.risingwave-icon.risingwave.robot-operating-system-ros.rocket-chat-icon.rocket-chat.rocksdb.rocky-linux-icon.rocky-linux.rollbar-icon.rollbar.rollupjs.rome-icon.rome.ros.rsa.rsmq.rspec.rstudio.rubocop.ruby-mine.ruby-on-rails.ruby.rubygems.rum.runscope.rush-icon.rush.rust.rxdb.safari.sagui.sails.salesforce.sameroom.samsung.sanity.sap.sass-doc.sass.saucelabs.scala.scaledrone.scalingo.scribd-icon.scribd.sdl.seaborn-icon.seaborn.section-icon.section.segment-icon.segment.selenium.sema-software.semantic-release.semantic-ui.semaphoreci.sencha.sendgrid-icon.sendgrid.seneca.sensu-icon.sensu.sentry-icon.sentry.sequelize.serverless.sherlock-icon.sherlock.shields.shipit.shogun.shopify.shopware.shortcut-icon.shortcut.sidekiq-icon.sidekiq.signal.sigstore-icon.sigstore.sinatra.singlestore-icon.singlestore.sitepoint.sk-hynix.skaffolder.sketch.skylight.skype.slack-icon.slack.slides.slidev.slim.smartling.smashingmagazine.snap-svg.snaplet-icon.snaplet.snowflake-icon.snowflake.snowpack.snyk.socket-io.solarwinds.solid.solidity.solidjs-icon.solidjs.solr.sonarcloud-icon.sonarcloud.sonarlint-icon.sonarlint.sonarqube.soundcloud.sourcegraph.sourcetree.spark.sparkpost.speakerdeck.speedcurve.spidermonkey-icon.spidermonkey.spinnaker.splunk.spotify-icon.spotify.spree.spring-icon.spring.sql-developer.sqlalchemy.sqlite.square.squarespace.ssh.sst-icon.sst.stability-ai-icon.stability-ai.stackbit-icon.stackbit.stackblitz-icon.stackblitz.stackoverflow-icon.stackoverflow.stackshare.stata.stately-icon.stately.statuspage.stdlib-icon.stdlib.steam.stenciljs-icon.stenciljs.stetho.stickermule.stigg-icon.stigg.stimulus-icon.stimulus.stitch.stoplight.storyblocks-icon.storyblocks.storyblok-icon.storyblok.storybook-icon.storybook.strapi-icon.strapi.streamlit.strider.stripe.struts.styleci.stylefmt.stylelint.stylis.stylus.stytch.sublimetext-icon.sublimetext.subversion.sugarss.supabase-icon.supabase.supertokens-icon.supertokens.surge.surrealdb-icon.surrealdb.survicate-icon.survicate.suse.susy.svelte-icon.svelte-kit.svelte.svg.svgator.swagger.swc.swift.swiftype.swimm.swr.symfony.sysdig-icon.sysdig.t3.tableau-icon.tableau.taiga.tailwindcss-icon.tailwindcss.tapcart-icon.tapcart.taskade-icon.taskade.tastejs.tauri.tealium.teamcity.teamgrid.teamwork-icon.teamwork.telegram.tensorflow.terminal.terraform-icon.terraform.terser-icon.terser.testcafe.testing-library.testlodge.tex.the-algorithms.threejs.thymeleaf-icon.thymeleaf.tidal-icon.tidal.tiktok-icon.tiktok.titanium-sdk.tnw.todoist-icon.todoist.todomvc.tomcat.toml.tor-browser.tor.tortoise-git.tower.traackr.trac.traefik-mesh.traefik-proxy.travis-ci-monochrome.travis-ci.treasuredata-icon.treasuredata.treehouse-icon.treehouse.trello.trpc.truffle-icon.truffle.tsmc.tsnode.tsuru.tumblr-icon.tumblr.tunein.tuple.turbopack-icon.turbopack.turborepo-icon.turborepo.turret.twilio-icon.twilio.twitch.twitter.typeform-icon.typeform.typeorm.typescript-icon-round.typescript-icon.typescript.typesense-icon.typesense.typo3-icon.typo3.ubuntu.udacity-icon.udacity.udemy-icon.udemy.uikit.uml.umu.unbounce-icon.unbounce.undertow.unionpay.unitjs.unito-icon.unito.unity.unix.unjs.unocss.unrealengine-icon.unrealengine.upcase.upstash-icon.upstash.upwork.user-testing-icon.user-testing.uservoice-icon.uservoice.uwsgi.v8-ignition.v8-turbofan.v8.vaadin.vaddy.vagrant-icon.vagrant.vala.vault-icon.vault.vector.vercel-icon.vercel.verdaccio-icon.verdaccio.vernemq.veutify.vim.vimeo-icon.vimeo.visa.visaelectron.visual-studio-code.visual-studio.vite.vitejs.vitess.vitest.vivaldi-icon.vivaldi.vlang.vmware.void.volar.vorejs.vscode.vsphere.vue-storefront.vue.vuetifyjs.vueuse.vulkan.vultr-icon.vultr.vwo.vyper.w3c.waffle-icon.waffle.wagtail.wakatime.walkme.watchman.waypoint-icon.waypoint.wayscript-icon.wayscript.wearos.weave.web-dev-icon.web-dev.web3js.webassembly.webcomponents.webdriverio.webflow.webgpu.webhint-icon.webhint.webhooks.webix-icon.webix.webkit.weblate.webmin.webpack.webplatform.webrtc.websocket.webstorm.webtorrent.weebly.whalar-icon.whalar.whatsapp-icon.whatsapp-monochrome-icon.whatsapp.whatwg.wicket-icon.wicket.wifi.wildfly.windi-css.windows11.windows8.winglang-icon.winglang.wire.wix.wmr.woo-commerce.woocommerce-icon.woopra.wordpress-icon-alt.wordpress-icon.wordpress.workboard.workos-icon.workos.workplace-icon.workplace.wpengine.wufoo.x.xamarin.xampp.xata-icon.xata.xcart.xcode.xero.xml.xray-for-jira.xstate.xtend.xwiki-icon.xwiki.yahoo.yaml.yammer.yandex-ru.yarn.ycombinator.yeoman.yii-framework.yii.youtrack.youtube-icon.youtube.yugabyte-icon.yugabyte.yuno-host.zabbix.zapier.zend-framework.zendesk-icon.zendesk.zenhub-icon.zenhub.zeplin.zeroheight-icon.zeroheight.zig.zod.zoho.zoom-icon.zoom.zorin-os.zsh.zube.zulip-icon.zulip.zwave`.split(`.`),bootstrap:/* @__PURE__ */ `0-circle-fill.0-circle.0-square-fill.0-square.1-circle-fill.1-circle.1-square-fill.1-square.123.2-circle-fill.2-circle.2-square-fill.2-square.3-circle-fill.3-circle.3-square-fill.3-square.4-circle-fill.4-circle.4-square-fill.4-square.5-circle-fill.5-circle.5-square-fill.5-square.6-circle-fill.6-circle.6-square-fill.6-square.7-circle-fill.7-circle.7-square-fill.7-square.8-circle-fill.8-circle.8-square-fill.8-square.9-circle-fill.9-circle.9-square-fill.9-square.activity.airplane-engines-fill.airplane-engines.airplane-fill.airplane.alarm-fill.alarm.alexa.align-bottom.align-center.align-end.align-middle.align-start.align-top.alipay.alphabet-uppercase.alphabet.alt.amazon.amd.android.android2.app-indicator.app.apple.archive-fill.archive.arrow-90deg-down.arrow-90deg-left.arrow-90deg-right.arrow-90deg-up.arrow-bar-down.arrow-bar-left.arrow-bar-right.arrow-bar-up.arrow-clockwise.arrow-counterclockwise.arrow-down-circle-fill.arrow-down-circle.arrow-down-left-circle-fill.arrow-down-left-circle.arrow-down-left-square-fill.arrow-down-left-square.arrow-down-left.arrow-down-right-circle-fill.arrow-down-right-circle.arrow-down-right-square-fill.arrow-down-right-square.arrow-down-right.arrow-down-short.arrow-down-square-fill.arrow-down-square.arrow-down-up.arrow-down.arrow-left-circle-fill.arrow-left-circle.arrow-left-right.arrow-left-short.arrow-left-square-fill.arrow-left-square.arrow-left.arrow-repeat.arrow-return-left.arrow-return-right.arrow-right-circle-fill.arrow-right-circle.arrow-right-short.arrow-right-square-fill.arrow-right-square.arrow-right.arrow-through-heart-fill.arrow-through-heart.arrow-up-circle-fill.arrow-up-circle.arrow-up-left-circle-fill.arrow-up-left-circle.arrow-up-left-square-fill.arrow-up-left-square.arrow-up-left.arrow-up-right-circle-fill.arrow-up-right-circle.arrow-up-right-square-fill.arrow-up-right-square.arrow-up-right.arrow-up-short.arrow-up-square-fill.arrow-up-square.arrow-up.arrows-angle-contract.arrows-angle-expand.arrows-collapse-vertical.arrows-collapse.arrows-expand-vertical.arrows-expand.arrows-fullscreen.arrows-move.arrows-vertical.arrows.aspect-ratio-fill.aspect-ratio.asterisk.at.award-fill.award.back.backpack-fill.backpack.backpack2-fill.backpack2.backpack3-fill.backpack3.backpack4-fill.backpack4.backspace-fill.backspace-reverse-fill.backspace-reverse.backspace.badge-3d-fill.badge-3d.badge-4k-fill.badge-4k.badge-8k-fill.badge-8k.badge-ad-fill.badge-ad.badge-ar-fill.badge-ar.badge-cc-fill.badge-cc.badge-hd-fill.badge-hd.badge-sd-fill.badge-sd.badge-tm-fill.badge-tm.badge-vo-fill.badge-vo.badge-vr-fill.badge-vr.badge-wc-fill.badge-wc.bag-check-fill.bag-check.bag-dash-fill.bag-dash.bag-fill.bag-heart-fill.bag-heart.bag-plus-fill.bag-plus.bag-x-fill.bag-x.bag.balloon-fill.balloon-heart-fill.balloon-heart.balloon.ban-fill.ban.bandaid-fill.bandaid.bank.bank2.bar-chart-fill.bar-chart-line-fill.bar-chart-line.bar-chart-steps.bar-chart.basket-fill.basket.basket2-fill.basket2.basket3-fill.basket3.battery-charging.battery-full.battery-half.battery.behance.bell-fill.bell-slash-fill.bell-slash.bell.bezier.bezier2.bicycle.bing.binoculars-fill.binoculars.blockquote-left.blockquote-right.bluetooth.body-text.book-fill.book-half.book.bookmark-check-fill.bookmark-check.bookmark-dash-fill.bookmark-dash.bookmark-fill.bookmark-heart-fill.bookmark-heart.bookmark-plus-fill.bookmark-plus.bookmark-star-fill.bookmark-star.bookmark-x-fill.bookmark-x.bookmark.bookmarks-fill.bookmarks.bookshelf.boombox-fill.boombox.bootstrap-fill.bootstrap-icons.bootstrap-reboot.bootstrap.border-all.border-bottom.border-center.border-inner.border-left.border-middle.border-outer.border-right.border-style.border-top.border-width.border.bounding-box-circles.bounding-box.box-arrow-down-left.box-arrow-down-right.box-arrow-down.box-arrow-in-down-left.box-arrow-in-down-right.box-arrow-in-down.box-arrow-in-left.box-arrow-in-right.box-arrow-in-up-left.box-arrow-in-up-right.box-arrow-in-up.box-arrow-left.box-arrow-right.box-arrow-up-left.box-arrow-up-right.box-arrow-up.box-fill.box-seam-fill.box-seam.box.box2-fill.box2-heart-fill.box2-heart.box2.boxes.braces-asterisk.braces.bricks.briefcase-fill.briefcase.brightness-alt-high-fill.brightness-alt-high.brightness-alt-low-fill.brightness-alt-low.brightness-high-fill.brightness-high.brightness-low-fill.brightness-low.brilliance.broadcast-pin.broadcast.browser-chrome.browser-edge.browser-firefox.browser-safari.brush-fill.brush.bucket-fill.bucket.bug-fill.bug.building-add.building-check.building-dash.building-down.building-exclamation.building-fill-add.building-fill-check.building-fill-dash.building-fill-down.building-fill-exclamation.building-fill-gear.building-fill-lock.building-fill-slash.building-fill-up.building-fill-x.building-fill.building-gear.building-lock.building-slash.building-up.building-x.building.buildings-fill.buildings.bullseye.bus-front-fill.bus-front.c-circle-fill.c-circle.c-square-fill.c-square.cake-fill.cake.cake2-fill.cake2.calculator-fill.calculator.calendar-check-fill.calendar-check.calendar-date-fill.calendar-date.calendar-day-fill.calendar-day.calendar-event-fill.calendar-event.calendar-fill.calendar-heart-fill.calendar-heart.calendar-minus-fill.calendar-minus.calendar-month-fill.calendar-month.calendar-plus-fill.calendar-plus.calendar-range-fill.calendar-range.calendar-week-fill.calendar-week.calendar-x-fill.calendar-x.calendar.calendar2-check-fill.calendar2-check.calendar2-date-fill.calendar2-date.calendar2-day-fill.calendar2-day.calendar2-event-fill.calendar2-event.calendar2-fill.calendar2-heart-fill.calendar2-heart.calendar2-minus-fill.calendar2-minus.calendar2-month-fill.calendar2-month.calendar2-plus-fill.calendar2-plus.calendar2-range-fill.calendar2-range.calendar2-week-fill.calendar2-week.calendar2-x-fill.calendar2-x.calendar2.calendar3-event-fill.calendar3-event.calendar3-fill.calendar3-range-fill.calendar3-range.calendar3-week-fill.calendar3-week.calendar3.calendar4-event.calendar4-range.calendar4-week.calendar4.camera-fill.camera-reels-fill.camera-reels.camera-video-fill.camera-video-off-fill.camera-video-off.camera-video.camera.camera2.capslock-fill.capslock.capsule-pill.capsule.car-front-fill.car-front.card-checklist.card-heading.card-image.card-list.card-text.caret-down-fill.caret-down-square-fill.caret-down-square.caret-down.caret-left-fill.caret-left-square-fill.caret-left-square.caret-left.caret-right-fill.caret-right-square-fill.caret-right-square.caret-right.caret-up-fill.caret-up-square-fill.caret-up-square.caret-up.cart-check-fill.cart-check.cart-dash-fill.cart-dash.cart-fill.cart-plus-fill.cart-plus.cart-x-fill.cart-x.cart.cart2.cart3.cart4.cash-coin.cash-stack.cash.cassette-fill.cassette.cast.cc-circle-fill.cc-circle.cc-square-fill.cc-square.chat-dots-fill.chat-dots.chat-fill.chat-heart-fill.chat-heart.chat-left-dots-fill.chat-left-dots.chat-left-fill.chat-left-heart-fill.chat-left-heart.chat-left-quote-fill.chat-left-quote.chat-left-text-fill.chat-left-text.chat-left.chat-quote-fill.chat-quote.chat-right-dots-fill.chat-right-dots.chat-right-fill.chat-right-heart-fill.chat-right-heart.chat-right-quote-fill.chat-right-quote.chat-right-text-fill.chat-right-text.chat-right.chat-square-dots-fill.chat-square-dots.chat-square-fill.chat-square-heart-fill.chat-square-heart.chat-square-quote-fill.chat-square-quote.chat-square-text-fill.chat-square-text.chat-square.chat-text-fill.chat-text.chat.check-all.check-circle-fill.check-circle.check-lg.check-square-fill.check-square.check.check2-all.check2-circle.check2-square.check2.chevron-bar-contract.chevron-bar-down.chevron-bar-expand.chevron-bar-left.chevron-bar-right.chevron-bar-up.chevron-compact-down.chevron-compact-left.chevron-compact-right.chevron-compact-up.chevron-contract.chevron-double-down.chevron-double-left.chevron-double-right.chevron-double-up.chevron-down.chevron-expand.chevron-left.chevron-right.chevron-up.circle-fill.circle-half.circle-square.circle.clipboard-check-fill.clipboard-check.clipboard-data-fill.clipboard-data.clipboard-fill.clipboard-heart-fill.clipboard-heart.clipboard-minus-fill.clipboard-minus.clipboard-plus-fill.clipboard-plus.clipboard-pulse.clipboard-x-fill.clipboard-x.clipboard.clipboard2-check-fill.clipboard2-check.clipboard2-data-fill.clipboard2-data.clipboard2-fill.clipboard2-heart-fill.clipboard2-heart.clipboard2-minus-fill.clipboard2-minus.clipboard2-plus-fill.clipboard2-plus.clipboard2-pulse-fill.clipboard2-pulse.clipboard2-x-fill.clipboard2-x.clipboard2.clock-fill.clock-history.clock.cloud-arrow-down-fill.cloud-arrow-down.cloud-arrow-up-fill.cloud-arrow-up.cloud-check-fill.cloud-check.cloud-download-fill.cloud-download.cloud-drizzle-fill.cloud-drizzle.cloud-fill.cloud-fog-fill.cloud-fog.cloud-fog2-fill.cloud-fog2.cloud-hail-fill.cloud-hail.cloud-haze-fill.cloud-haze.cloud-haze2-fill.cloud-haze2.cloud-lightning-fill.cloud-lightning-rain-fill.cloud-lightning-rain.cloud-lightning.cloud-minus-fill.cloud-minus.cloud-moon-fill.cloud-moon.cloud-plus-fill.cloud-plus.cloud-rain-fill.cloud-rain-heavy-fill.cloud-rain-heavy.cloud-rain.cloud-slash-fill.cloud-slash.cloud-sleet-fill.cloud-sleet.cloud-snow-fill.cloud-snow.cloud-sun-fill.cloud-sun.cloud-upload-fill.cloud-upload.cloud.clouds-fill.clouds.cloudy-fill.cloudy.code-slash.code-square.code.coin.collection-fill.collection-play-fill.collection-play.collection.columns-gap.columns.command.compass-fill.compass.cone-striped.cone.controller.cookie.copy.cpu-fill.cpu.credit-card-2-back-fill.credit-card-2-back.credit-card-2-front-fill.credit-card-2-front.credit-card-fill.credit-card.crop.crosshair.crosshair2.cup-fill.cup-hot-fill.cup-hot.cup-straw.cup.currency-bitcoin.currency-dollar.currency-euro.currency-exchange.currency-pound.currency-rupee.currency-yen.cursor-fill.cursor-text.cursor.dash-circle-dotted.dash-circle-fill.dash-circle.dash-lg.dash-square-dotted.dash-square-fill.dash-square.dash.database-add.database-check.database-dash.database-down.database-exclamation.database-fill-add.database-fill-check.database-fill-dash.database-fill-down.database-fill-exclamation.database-fill-gear.database-fill-lock.database-fill-slash.database-fill-up.database-fill-x.database-fill.database-gear.database-lock.database-slash.database-up.database-x.database.device-hdd-fill.device-hdd.device-ssd-fill.device-ssd.diagram-2-fill.diagram-2.diagram-3-fill.diagram-3.diamond-fill.diamond-half.diamond.dice-1-fill.dice-1.dice-2-fill.dice-2.dice-3-fill.dice-3.dice-4-fill.dice-4.dice-5-fill.dice-5.dice-6-fill.dice-6.disc-fill.disc.discord.display-fill.display.displayport-fill.displayport.distribute-horizontal.distribute-vertical.door-closed-fill.door-closed.door-open-fill.door-open.dot.download.dpad-fill.dpad.dribbble.dropbox.droplet-fill.droplet-half.droplet.duffle-fill.duffle.ear-fill.ear.earbuds.easel-fill.easel.easel2-fill.easel2.easel3-fill.easel3.egg-fill.egg-fried.egg.eject-fill.eject.emoji-angry-fill.emoji-angry.emoji-astonished-fill.emoji-astonished.emoji-dizzy-fill.emoji-dizzy.emoji-expressionless-fill.emoji-expressionless.emoji-frown-fill.emoji-frown.emoji-grimace-fill.emoji-grimace.emoji-grin-fill.emoji-grin.emoji-heart-eyes-fill.emoji-heart-eyes.emoji-kiss-fill.emoji-kiss.emoji-laughing-fill.emoji-laughing.emoji-neutral-fill.emoji-neutral.emoji-smile-fill.emoji-smile-upside-down-fill.emoji-smile-upside-down.emoji-smile.emoji-sunglasses-fill.emoji-sunglasses.emoji-surprise-fill.emoji-surprise.emoji-tear-fill.emoji-tear.emoji-wink-fill.emoji-wink.envelope-arrow-down-fill.envelope-arrow-down.envelope-arrow-up-fill.envelope-arrow-up.envelope-at-fill.envelope-at.envelope-check-fill.envelope-check.envelope-dash-fill.envelope-dash.envelope-exclamation-fill.envelope-exclamation.envelope-fill.envelope-heart-fill.envelope-heart.envelope-open-fill.envelope-open-heart-fill.envelope-open-heart.envelope-open.envelope-paper-fill.envelope-paper-heart-fill.envelope-paper-heart.envelope-paper.envelope-plus-fill.envelope-plus.envelope-slash-fill.envelope-slash.envelope-x-fill.envelope-x.envelope.eraser-fill.eraser.escape.ethernet.ev-front-fill.ev-front.ev-station-fill.ev-station.exclamation-circle-fill.exclamation-circle.exclamation-diamond-fill.exclamation-diamond.exclamation-lg.exclamation-octagon-fill.exclamation-octagon.exclamation-square-fill.exclamation-square.exclamation-triangle-fill.exclamation-triangle.exclamation.exclude.explicit-fill.explicit.exposure.eye-fill.eye-slash-fill.eye-slash.eye.eyedropper.eyeglasses.facebook.fan.fast-forward-btn-fill.fast-forward-btn.fast-forward-circle-fill.fast-forward-circle.fast-forward-fill.fast-forward.feather.feather2.file-arrow-down-fill.file-arrow-down.file-arrow-up-fill.file-arrow-up.file-bar-graph-fill.file-bar-graph.file-binary-fill.file-binary.file-break-fill.file-break.file-check-fill.file-check.file-code-fill.file-code.file-diff-fill.file-diff.file-earmark-arrow-down-fill.file-earmark-arrow-down.file-earmark-arrow-up-fill.file-earmark-arrow-up.file-earmark-bar-graph-fill.file-earmark-bar-graph.file-earmark-binary-fill.file-earmark-binary.file-earmark-break-fill.file-earmark-break.file-earmark-check-fill.file-earmark-check.file-earmark-code-fill.file-earmark-code.file-earmark-diff-fill.file-earmark-diff.file-earmark-easel-fill.file-earmark-easel.file-earmark-excel-fill.file-earmark-excel.file-earmark-fill.file-earmark-font-fill.file-earmark-font.file-earmark-image-fill.file-earmark-image.file-earmark-lock-fill.file-earmark-lock.file-earmark-lock2-fill.file-earmark-lock2.file-earmark-medical-fill.file-earmark-medical.file-earmark-minus-fill.file-earmark-minus.file-earmark-music-fill.file-earmark-music.file-earmark-pdf-fill.file-earmark-pdf.file-earmark-person-fill.file-earmark-person.file-earmark-play-fill.file-earmark-play.file-earmark-plus-fill.file-earmark-plus.file-earmark-post-fill.file-earmark-post.file-earmark-ppt-fill.file-earmark-ppt.file-earmark-richtext-fill.file-earmark-richtext.file-earmark-ruled-fill.file-earmark-ruled.file-earmark-slides-fill.file-earmark-slides.file-earmark-spreadsheet-fill.file-earmark-spreadsheet.file-earmark-text-fill.file-earmark-text.file-earmark-word-fill.file-earmark-word.file-earmark-x-fill.file-earmark-x.file-earmark-zip-fill.file-earmark-zip.file-earmark.file-easel-fill.file-easel.file-excel-fill.file-excel.file-fill.file-font-fill.file-font.file-image-fill.file-image.file-lock-fill.file-lock.file-lock2-fill.file-lock2.file-medical-fill.file-medical.file-minus-fill.file-minus.file-music-fill.file-music.file-pdf-fill.file-pdf.file-person-fill.file-person.file-play-fill.file-play.file-plus-fill.file-plus.file-post-fill.file-post.file-ppt-fill.file-ppt.file-richtext-fill.file-richtext.file-ruled-fill.file-ruled.file-slides-fill.file-slides.file-spreadsheet-fill.file-spreadsheet.file-text-fill.file-text.file-word-fill.file-word.file-x-fill.file-x.file-zip-fill.file-zip.file.files-alt.files.filetype-aac.filetype-ai.filetype-bmp.filetype-cs.filetype-css.filetype-csv.filetype-doc.filetype-docx.filetype-exe.filetype-gif.filetype-heic.filetype-html.filetype-java.filetype-jpg.filetype-js.filetype-json.filetype-jsx.filetype-key.filetype-m4p.filetype-md.filetype-mdx.filetype-mov.filetype-mp3.filetype-mp4.filetype-otf.filetype-pdf.filetype-php.filetype-png.filetype-ppt.filetype-pptx.filetype-psd.filetype-py.filetype-raw.filetype-rb.filetype-sass.filetype-scss.filetype-sh.filetype-sql.filetype-svg.filetype-tiff.filetype-tsx.filetype-ttf.filetype-txt.filetype-wav.filetype-woff.filetype-xls.filetype-xlsx.filetype-xml.filetype-yml.film.filter-circle-fill.filter-circle.filter-left.filter-right.filter-square-fill.filter-square.filter.fingerprint.fire.flag-fill.flag.floppy-fill.floppy.floppy2-fill.floppy2.flower1.flower2.flower3.folder-check.folder-fill.folder-minus.folder-plus.folder-symlink-fill.folder-symlink.folder-x.folder.folder2-open.folder2.fonts.forward-fill.forward.front.fuel-pump-diesel-fill.fuel-pump-diesel.fuel-pump-fill.fuel-pump.fullscreen-exit.fullscreen.funnel-fill.funnel.gear-fill.gear-wide-connected.gear-wide.gear.gem.gender-ambiguous.gender-female.gender-male.gender-neuter.gender-trans.geo-alt-fill.geo-alt.geo-fill.geo.gift-fill.gift.git.github.gitlab.globe-americas.globe-asia-australia.globe-central-south-asia.globe-europe-africa.globe.globe2.google-play.google.gpu-card.graph-down-arrow.graph-down.graph-up-arrow.graph-up.grid-1x2-fill.grid-1x2.grid-3x2-gap-fill.grid-3x2-gap.grid-3x2.grid-3x3-gap-fill.grid-3x3-gap.grid-3x3.grid-fill.grid.grip-horizontal.grip-vertical.h-circle-fill.h-circle.h-square-fill.h-square.hammer.hand-index-fill.hand-index-thumb-fill.hand-index-thumb.hand-index.hand-thumbs-down-fill.hand-thumbs-down.hand-thumbs-up-fill.hand-thumbs-up.handbag-fill.handbag.hash.hdd-fill.hdd-network-fill.hdd-network.hdd-rack-fill.hdd-rack.hdd-stack-fill.hdd-stack.hdd.hdmi-fill.hdmi.headphones.headset-vr.headset.heart-arrow.heart-fill.heart-half.heart-pulse-fill.heart-pulse.heart.heartbreak-fill.heartbreak.hearts.heptagon-fill.heptagon-half.heptagon.hexagon-fill.hexagon-half.hexagon.highlighter.highlights.hospital-fill.hospital.hourglass-bottom.hourglass-split.hourglass-top.hourglass.house-add-fill.house-add.house-check-fill.house-check.house-dash-fill.house-dash.house-door-fill.house-door.house-down-fill.house-down.house-exclamation-fill.house-exclamation.house-fill.house-gear-fill.house-gear.house-heart-fill.house-heart.house-lock-fill.house-lock.house-slash-fill.house-slash.house-up-fill.house-up.house-x-fill.house-x.house.houses-fill.houses.hr.hurricane.hypnotize.image-alt.image-fill.image.images.inbox-fill.inbox.inboxes-fill.inboxes.incognito.indent.infinity.info-circle-fill.info-circle.info-lg.info-square-fill.info-square.info.input-cursor-text.input-cursor.instagram.intersect.journal-album.journal-arrow-down.journal-arrow-up.journal-bookmark-fill.journal-bookmark.journal-check.journal-code.journal-medical.journal-minus.journal-plus.journal-richtext.journal-text.journal-x.journal.journals.joystick.justify-left.justify-right.justify.kanban-fill.kanban.key-fill.key.keyboard-fill.keyboard.ladder.lamp-fill.lamp.laptop-fill.laptop.layer-backward.layer-forward.layers-fill.layers-half.layers.layout-sidebar-inset-reverse.layout-sidebar-inset.layout-sidebar-reverse.layout-sidebar.layout-split.layout-text-sidebar-reverse.layout-text-sidebar.layout-text-window-reverse.layout-text-window.layout-three-columns.layout-wtf.life-preserver.lightbulb-fill.lightbulb-off-fill.lightbulb-off.lightbulb.lightning-charge-fill.lightning-charge.lightning-fill.lightning.line.link-45deg.link.linkedin.list-check.list-columns-reverse.list-columns.list-nested.list-ol.list-stars.list-task.list-ul.list.lock-fill.lock.luggage-fill.luggage.lungs-fill.lungs.magic.magnet-fill.magnet.mailbox-flag.mailbox.mailbox2-flag.mailbox2.map-fill.map.markdown-fill.markdown.marker-tip.mask.mastodon.medium.megaphone-fill.megaphone.memory.menu-app-fill.menu-app.menu-button-fill.menu-button-wide-fill.menu-button-wide.menu-button.menu-down.menu-up.messenger.meta.mic-fill.mic-mute-fill.mic-mute.mic.microsoft-teams.microsoft.minecart-loaded.minecart.modem-fill.modem.moisture.moon-fill.moon-stars-fill.moon-stars.moon.mortarboard-fill.mortarboard.motherboard-fill.motherboard.mouse-fill.mouse.mouse2-fill.mouse2.mouse3-fill.mouse3.music-note-beamed.music-note-list.music-note.music-player-fill.music-player.newspaper.nintendo-switch.node-minus-fill.node-minus.node-plus-fill.node-plus.noise-reduction.nut-fill.nut.nvidia.nvme-fill.nvme.octagon-fill.octagon-half.octagon.opencollective.optical-audio-fill.optical-audio.option.outlet.p-circle-fill.p-circle.p-square-fill.p-square.paint-bucket.palette-fill.palette.palette2.paperclip.paragraph.pass-fill.pass.passport-fill.passport.patch-check-fill.patch-check.patch-exclamation-fill.patch-exclamation.patch-minus-fill.patch-minus.patch-plus-fill.patch-plus.patch-question-fill.patch-question.pause-btn-fill.pause-btn.pause-circle-fill.pause-circle.pause-fill.pause.paypal.pc-display-horizontal.pc-display.pc-horizontal.pc.pci-card-network.pci-card-sound.pci-card.peace-fill.peace.pen-fill.pen.pencil-fill.pencil-square.pencil.pentagon-fill.pentagon-half.pentagon.people-fill.people.percent.person-add.person-arms-up.person-badge-fill.person-badge.person-bounding-box.person-check-fill.person-check.person-circle.person-dash-fill.person-dash.person-down.person-exclamation.person-fill-add.person-fill-check.person-fill-dash.person-fill-down.person-fill-exclamation.person-fill-gear.person-fill-lock.person-fill-slash.person-fill-up.person-fill-x.person-fill.person-gear.person-heart.person-hearts.person-lines-fill.person-lock.person-plus-fill.person-plus.person-raised-hand.person-rolodex.person-slash.person-square.person-standing-dress.person-standing.person-up.person-vcard-fill.person-vcard.person-video.person-video2.person-video3.person-walking.person-wheelchair.person-workspace.person-x-fill.person-x.person.phone-fill.phone-flip.phone-landscape-fill.phone-landscape.phone-vibrate-fill.phone-vibrate.phone.pie-chart-fill.pie-chart.piggy-bank-fill.piggy-bank.pin-angle-fill.pin-angle.pin-fill.pin-map-fill.pin-map.pin.pinterest.pip-fill.pip.play-btn-fill.play-btn.play-circle-fill.play-circle.play-fill.play.playstation.plug-fill.plug.plugin.plus-circle-dotted.plus-circle-fill.plus-circle.plus-lg.plus-slash-minus.plus-square-dotted.plus-square-fill.plus-square.plus.postage-fill.postage-heart-fill.postage-heart.postage.postcard-fill.postcard-heart-fill.postcard-heart.postcard.power.prescription.prescription2.printer-fill.printer.projector-fill.projector.puzzle-fill.puzzle.qr-code-scan.qr-code.question-circle-fill.question-circle.question-diamond-fill.question-diamond.question-lg.question-octagon-fill.question-octagon.question-square-fill.question-square.question.quora.quote.r-circle-fill.r-circle.r-square-fill.r-square.radar.radioactive.rainbow.receipt-cutoff.receipt.reception-0.reception-1.reception-2.reception-3.reception-4.record-btn-fill.record-btn.record-circle-fill.record-circle.record-fill.record.record2-fill.record2.recycle.reddit.regex.repeat-1.repeat.reply-all-fill.reply-all.reply-fill.reply.rewind-btn-fill.rewind-btn.rewind-circle-fill.rewind-circle.rewind-fill.rewind.robot.rocket-fill.rocket-takeoff-fill.rocket-takeoff.rocket.router-fill.router.rss-fill.rss.rulers.safe-fill.safe.safe2-fill.safe2.save-fill.save.save2-fill.save2.scissors.scooter.screwdriver.sd-card-fill.sd-card.search-heart-fill.search-heart.search.segmented-nav.send-arrow-down-fill.send-arrow-down.send-arrow-up-fill.send-arrow-up.send-check-fill.send-check.send-dash-fill.send-dash.send-exclamation-fill.send-exclamation.send-fill.send-plus-fill.send-plus.send-slash-fill.send-slash.send-x-fill.send-x.send.server.shadows.share-fill.share.shield-check.shield-exclamation.shield-fill-check.shield-fill-exclamation.shield-fill-minus.shield-fill-plus.shield-fill-x.shield-fill.shield-lock-fill.shield-lock.shield-minus.shield-plus.shield-shaded.shield-slash-fill.shield-slash.shield-x.shield.shift-fill.shift.shop-window.shop.shuffle.sign-dead-end-fill.sign-dead-end.sign-do-not-enter-fill.sign-do-not-enter.sign-intersection-fill.sign-intersection-side-fill.sign-intersection-side.sign-intersection-t-fill.sign-intersection-t.sign-intersection-y-fill.sign-intersection-y.sign-intersection.sign-merge-left-fill.sign-merge-left.sign-merge-right-fill.sign-merge-right.sign-no-left-turn-fill.sign-no-left-turn.sign-no-parking-fill.sign-no-parking.sign-no-right-turn-fill.sign-no-right-turn.sign-railroad-fill.sign-railroad.sign-stop-fill.sign-stop-lights-fill.sign-stop-lights.sign-stop.sign-turn-left-fill.sign-turn-left.sign-turn-right-fill.sign-turn-right.sign-turn-slight-left-fill.sign-turn-slight-left.sign-turn-slight-right-fill.sign-turn-slight-right.sign-yield-fill.sign-yield.signal.signpost-2-fill.signpost-2.signpost-fill.signpost-split-fill.signpost-split.signpost.sim-fill.sim-slash-fill.sim-slash.sim.sina-weibo.skip-backward-btn-fill.skip-backward-btn.skip-backward-circle-fill.skip-backward-circle.skip-backward-fill.skip-backward.skip-end-btn-fill.skip-end-btn.skip-end-circle-fill.skip-end-circle.skip-end-fill.skip-end.skip-forward-btn-fill.skip-forward-btn.skip-forward-circle-fill.skip-forward-circle.skip-forward-fill.skip-forward.skip-start-btn-fill.skip-start-btn.skip-start-circle-fill.skip-start-circle.skip-start-fill.skip-start.skype.slack.slash-circle-fill.slash-circle.slash-lg.slash-square-fill.slash-square.slash.sliders.sliders2-vertical.sliders2.smartwatch.snapchat.snow.snow2.snow3.sort-alpha-down-alt.sort-alpha-down.sort-alpha-up-alt.sort-alpha-up.sort-down-alt.sort-down.sort-numeric-down-alt.sort-numeric-down.sort-numeric-up-alt.sort-numeric-up.sort-up-alt.sort-up.soundwave.sourceforge.speaker-fill.speaker.speedometer.speedometer2.spellcheck.spotify.square-fill.square-half.square.stack-overflow.stack.star-fill.star-half.star.stars.steam.stickies-fill.stickies.sticky-fill.sticky.stop-btn-fill.stop-btn.stop-circle-fill.stop-circle.stop-fill.stop.stoplights-fill.stoplights.stopwatch-fill.stopwatch.strava.stripe.subscript.substack.subtract.suit-club-fill.suit-club.suit-diamond-fill.suit-diamond.suit-heart-fill.suit-heart.suit-spade-fill.suit-spade.suitcase-fill.suitcase-lg-fill.suitcase-lg.suitcase.suitcase2-fill.suitcase2.sun-fill.sun.sunglasses.sunrise-fill.sunrise.sunset-fill.sunset.superscript.symmetry-horizontal.symmetry-vertical.table.tablet-fill.tablet-landscape-fill.tablet-landscape.tablet.tag-fill.tag.tags-fill.tags.taxi-front-fill.taxi-front.telegram.telephone-fill.telephone-forward-fill.telephone-forward.telephone-inbound-fill.telephone-inbound.telephone-minus-fill.telephone-minus.telephone-outbound-fill.telephone-outbound.telephone-plus-fill.telephone-plus.telephone-x-fill.telephone-x.telephone.tencent-qq.terminal-dash.terminal-fill.terminal-plus.terminal-split.terminal-x.terminal.text-center.text-indent-left.text-indent-right.text-left.text-paragraph.text-right.text-wrap.textarea-resize.textarea-t.textarea.thermometer-half.thermometer-high.thermometer-low.thermometer-snow.thermometer-sun.thermometer.threads-fill.threads.three-dots-vertical.three-dots.thunderbolt-fill.thunderbolt.ticket-detailed-fill.ticket-detailed.ticket-fill.ticket-perforated-fill.ticket-perforated.ticket.tiktok.toggle-off.toggle-on.toggle2-off.toggle2-on.toggles.toggles2.tools.tornado.train-freight-front-fill.train-freight-front.train-front-fill.train-front.train-lightrail-front-fill.train-lightrail-front.translate.transparency.trash-fill.trash.trash2-fill.trash2.trash3-fill.trash3.tree-fill.tree.trello.triangle-fill.triangle-half.triangle.trophy-fill.trophy.tropical-storm.truck-flatbed.truck-front-fill.truck-front.truck.tsunami.tv-fill.tv.twitch.twitter-x.twitter.type-bold.type-h1.type-h2.type-h3.type-h4.type-h5.type-h6.type-italic.type-strikethrough.type-underline.type.ubuntu.ui-checks-grid.ui-checks.ui-radios-grid.ui-radios.umbrella-fill.umbrella.unindent.union.unity.universal-access-circle.universal-access.unlock-fill.unlock.upc-scan.upc.upload.usb-c-fill.usb-c.usb-drive-fill.usb-drive.usb-fill.usb-micro-fill.usb-micro.usb-mini-fill.usb-mini.usb-plug-fill.usb-plug.usb-symbol.usb.valentine.valentine2.vector-pen.view-list.view-stacked.vignette.vimeo.vinyl-fill.vinyl.virus.virus2.voicemail.volume-down-fill.volume-down.volume-mute-fill.volume-mute.volume-off-fill.volume-off.volume-up-fill.volume-up.vr.wallet-fill.wallet.wallet2.watch.water.webcam-fill.webcam.wechat.whatsapp.wifi-1.wifi-2.wifi-off.wifi.wikipedia.wind.window-dash.window-desktop.window-dock.window-fullscreen.window-plus.window-sidebar.window-split.window-stack.window-x.window.windows.wordpress.wrench-adjustable-circle-fill.wrench-adjustable-circle.wrench-adjustable.wrench.x-circle-fill.x-circle.x-diamond-fill.x-diamond.x-lg.x-octagon-fill.x-octagon.x-square-fill.x-square.x.xbox.yelp.yin-yang.youtube.zoom-in.zoom-out`.split(`.`)};Object.keys(Lo);const Ro=[`likec4lib {`,` icons {`,...[...Object.entries(Lo)].flatMap(([e,t])=>t.map(t=>e+`:`+t)).map(e=>` `+e),` }`,`}`].join(`
|
|
76
|
+
`),zo=`likec4builtin`,Bo=`${zo}:///likec4/lib/icons.c4`;function isLikeC4Builtin(e){return(`uri`in e?e.uri:e).scheme===zo}function isNotLikeC4Builtin(e){return!isLikeC4Builtin(e)}const Vo=compareNaturalHierarchically(`/`),compareByUri=(e,t)=>Vo(ar(e.uri.path),ar(t.uri.path)),Ho=compareNaturalHierarchically(`/`,!0),compareByUriDeepFirst=(e,t)=>Ho(ar(e.uri.path),ar(t.uri.path));var ADisposable=class{toDispose=[];isDisposed=!1;onDispose(...e){this.toDispose.push(...e)}dispose(){this.throwIfDisposed(),this.isDisposed=!0;let e;for(;e=this.toDispose.pop();)try{e.dispose()}catch(e){logWarnError(e)}}throwIfDisposed(){this.isDisposed&&q.warn(`this has already been disposed`)}};const Uo={$type:`AbstractStep`,custom:`custom`,dotKind:`dotKind`,kind:`kind`,target:`target`,title:`title`},Wo={$type:`AltSteps`,branches:`branches`,title:`title`};function isAltSteps(e){return J.isInstance(e,Wo.$type)}const Go={$type:`AnyProperty`};function isAnyProperty(e){return J.isInstance(e,Go.$type)}const Ko={$type:`ArrowProperty`,key:`key`,value:`value`};function isArrowProperty(e){return J.isInstance(e,Ko.$type)}const qo={$type:`BorderProperty`,key:`key`,value:`value`};function isBorderProperty(e){return J.isInstance(e,qo.$type)}const Jo={$type:`CatchBlock`,catch:`catch`,title:`title`,try:`try`};function isCatchBlock(e){return J.isInstance(e,Jo.$type)}const Yo={$type:`ColorLiteral`};function isColorLiteral(e){return J.isInstance(e,Yo.$type)}const Xo={$type:`ColorProperty`,customColor:`customColor`,key:`key`,themeColor:`themeColor`};function isColorProperty(e){return J.isInstance(e,Xo.$type)}const Zo={$type:`CustomColor`,name:`name`},Qo={$type:`CustomElementProperties`,props:`props`};function isCustomElementProperties(e){return J.isInstance(e,Qo.$type)}const $o={$type:`CustomRelationProperties`,props:`props`};function isCustomRelationProperties(e){return J.isInstance(e,$o.$type)}const es={$type:`DeployedInstance`,body:`body`,name:`name`,summary:`summary`,target:`target`,title:`title`};function isDeployedInstance(e){return J.isInstance(e,es.$type)}const ts={$type:`DeployedInstanceBody`,elements:`elements`,props:`props`,tags:`tags`};function isDeployedInstanceBody(e){return J.isInstance(e,ts.$type)}const ns={$type:`DeploymentElement`};function isDeploymentElement(e){return J.isInstance(e,ns.$type)}const rs={$type:`DeploymentNode`,body:`body`,kind:`kind`,name:`name`,summary:`summary`,title:`title`};function isDeploymentNode(e){return J.isInstance(e,rs.$type)}const as={$type:`DeploymentNodeBody`,elements:`elements`,props:`props`,tags:`tags`};function isDeploymentNodeBody(e){return J.isInstance(e,as.$type)}const os={$type:`DeploymentNodeKind`,name:`name`};function isDeploymentNodeKind(e){return J.isInstance(e,os.$type)}const ss={$type:`DeploymentNodeOrElementKind`},cs={$type:`DeploymentRelation`,body:`body`,description:`description`,dotKind:`dotKind`,isBidirectional:`isBidirectional`,kind:`kind`,source:`source`,tags:`tags`,target:`target`,technology:`technology`,title:`title`};function isDeploymentRelation(e){return J.isInstance(e,cs.$type)}const ls={$type:`DeploymentRelationBody`,props:`props`,tags:`tags`};function isDeploymentRelationBody(e){return J.isInstance(e,ls.$type)}const us={$type:`DeploymentView`,body:`body`,name:`name`};function isDeploymentView(e){return J.isInstance(e,us.$type)}const ds={$type:`DeploymentViewBody`,props:`props`,rules:`rules`,tags:`tags`};function isDeploymentViewBody(e){return J.isInstance(e,ds.$type)}const fs={$type:`DeploymentViewRule`};function isDeploymentViewRule(e){return J.isInstance(e,fs.$type)}const ps={$type:`DeploymentViewRulePredicate`,expr:`expr`,isInclude:`isInclude`};function isDeploymentViewRulePredicate(e){return J.isInstance(e,ps.$type)}const ms={$type:`DeploymentViewRuleStyle`,props:`props`,targets:`targets`};function isDeploymentViewRuleStyle(e){return J.isInstance(e,ms.$type)}const hs={$type:`DirectedRelationExpr`,source:`source`,target:`target`};function isDirectedRelationExpr(e){return J.isInstance(e,hs.$type)}const gs={$type:`DynamicView`,body:`body`,name:`name`};function isDynamicView(e){return J.isInstance(e,gs.$type)}const _s={$type:`DynamicViewBody`,props:`props`,rules:`rules`,steps:`steps`,tags:`tags`};function isDynamicViewBody(e){return J.isInstance(e,_s.$type)}const vs={$type:`DynamicViewDisplayVariantProperty`,key:`key`,value:`value`};function isDynamicViewDisplayVariantProperty(e){return J.isInstance(e,vs.$type)}const ys={$type:`DynamicViewGlobalPredicateRef`,predicate:`predicate`};function isDynamicViewGlobalPredicateRef(e){return J.isInstance(e,ys.$type)}const bs={$type:`DynamicViewIncludePredicate`,exprs:`exprs`};function isDynamicViewIncludePredicate(e){return J.isInstance(e,bs.$type)}const xs={$type:`DynamicViewProperty`},Ss={$type:`DynamicViewRef`,view:`view`},Cs={$type:`DynamicViewRule`};function isDynamicViewRule(e){return J.isInstance(e,Cs.$type)}const ws={$type:`Element`,body:`body`,kind:`kind`,name:`name`,props:`props`};function isElement(e){return J.isInstance(e,ws.$type)}const Ts={$type:`ElementBody`,elements:`elements`,props:`props`,tags:`tags`};function isElementBody(e){return J.isInstance(e,Ts.$type)}const Es={$type:`ElementKind`,name:`name`};function isElementKind(e){return J.isInstance(e,Es.$type)}const Ds={$type:`ElementKindExpression`,isEqual:`isEqual`,kind:`kind`};function isElementKindExpression(e){return J.isInstance(e,Ds.$type)}const Os={$type:`ElementProperty`};function isElementProperty(e){return J.isInstance(e,Os.$type)}const ks={$type:`ElementRef`,modelElement:`modelElement`};function isElementRef(e){return J.isInstance(e,ks.$type)}const As={$type:`ElementStringProperty`,key:`key`,value:`value`};function isElementStringProperty(e){return J.isInstance(e,As.$type)}const js={$type:`ElementStyleProperty`,key:`key`,props:`props`};function isElementStyleProperty(e){return J.isInstance(e,js.$type)}const Ms={$type:`ElementTagExpression`,isEqual:`isEqual`,tag:`tag`};function isElementTagExpression(e){return J.isInstance(e,Ms.$type)}const Ns={$type:`ElementView`,body:`body`,extends:`extends`,name:`name`,viewOf:`viewOf`};function isElementView(e){return J.isInstance(e,Ns.$type)}const Ps={$type:`ElementViewBody`,props:`props`,rules:`rules`,tags:`tags`};function isElementViewBody(e){return J.isInstance(e,Ps.$type)}const Fs={$type:`ElementViewRef`,view:`view`},Is={$type:`Expressions`,prev:`prev`,value:`value`};function isExpressions(e){return J.isInstance(e,Is.$type)}const Ls={$type:`ExpressionV2`};function isExpressionV2(e){return J.isInstance(e,Ls.$type)}const Rs={$type:`ExtendDeployment`,body:`body`,deploymentNode:`deploymentNode`};function isExtendDeployment(e){return J.isInstance(e,Rs.$type)}const zs={$type:`ExtendDeploymentBody`,elements:`elements`,props:`props`,tags:`tags`};function isExtendDeploymentBody(e){return J.isInstance(e,zs.$type)}const Bs={$type:`ExtendElement`,body:`body`,element:`element`};function isExtendElement(e){return J.isInstance(e,Bs.$type)}const Vs={$type:`ExtendElementBody`,elements:`elements`,props:`props`,tags:`tags`};function isExtendElementBody(e){return J.isInstance(e,Vs.$type)}const Hs={$type:`ExtendElementOrRelation`};function isExtendElementOrRelation(e){return J.isInstance(e,Hs.$type)}const Us={$type:`ExtendElementProperty`},Ws={$type:`ExtendRelation`,body:`body`,dotKind:`dotKind`,isBidirectional:`isBidirectional`,kind:`kind`,source:`source`,target:`target`,title:`title`};function isExtendRelation(e){return J.isInstance(e,Ws.$type)}const Gs={$type:`ExtendRelationBody`,props:`props`,tags:`tags`};function isExtendRelationBody(e){return J.isInstance(e,Gs.$type)}const Ks={$type:`ExtendRelationProperty`},qs={$type:`FinallyBlock`,finally:`finally`,title:`title`,tryCatch:`tryCatch`};function isFinallyBlock(e){return J.isInstance(e,qs.$type)}const Js={$type:`FqnExpr`};function isFqnExpr(e){return J.isInstance(e,Js.$type)}const Ys={$type:`FqnExpressions`,prev:`prev`,value:`value`};function isFqnExpressions(e){return J.isInstance(e,Ys.$type)}const Xs={$type:`FqnExprOrWhere`};function isFqnExprOrWhere(e){return J.isInstance(e,Xs.$type)}const Zs={$type:`FqnExprOrWith`};function isFqnExprOrWith(e){return J.isInstance(e,Zs.$type)}const Qs={$type:`FqnExprWhere`,subject:`subject`,where:`where`};function isFqnExprWhere(e){return J.isInstance(e,Qs.$type)}const $s={$type:`FqnExprWith`,custom:`custom`,subject:`subject`};function isFqnExprWith(e){return J.isInstance(e,$s.$type)}const ec={$type:`FqnRef`,parent:`parent`,value:`value`};function isFqnRef(e){return J.isInstance(e,ec.$type)}const tc={$type:`FqnReferenceable`},nc={$type:`FqnRefExpr`,ref:`ref`,selector:`selector`};function isFqnRefExpr(e){return J.isInstance(e,nc.$type)}const rc={$type:`GlobalDynamicPredicateGroup`,name:`name`,predicates:`predicates`};function isGlobalDynamicPredicateGroup(e){return J.isInstance(e,rc.$type)}const ic={$type:`GlobalPredicateGroup`,name:`name`,predicates:`predicates`};function isGlobalPredicateGroup(e){return J.isInstance(e,ic.$type)}const ac={$type:`Globals`,name:`name`,predicates:`predicates`,styles:`styles`};function isGlobals(e){return J.isInstance(e,ac.$type)}const oc={$type:`GlobalStyle`,id:`id`,props:`props`,targets:`targets`};function isGlobalStyle(e){return J.isInstance(e,oc.$type)}const sc={$type:`GlobalStyleGroup`,id:`id`,styles:`styles`};function isGlobalStyleGroup(e){return J.isInstance(e,sc.$type)}const cc={$type:`GlobalStyleId`,name:`name`},lc={$type:`HexColor`,hex:`hex`};function isHexColor(e){return J.isInstance(e,lc.$type)}const uc={$type:`IconColorProperty`,customColor:`customColor`,key:`key`,themeColor:`themeColor`};function isIconColorProperty(e){return J.isInstance(e,uc.$type)}const dc={$type:`IconPositionProperty`,key:`key`,value:`value`};function isIconPositionProperty(e){return J.isInstance(e,dc.$type)}const fc={$type:`IconProperty`,key:`key`,libicon:`libicon`,value:`value`};function isIconProperty(e){return J.isInstance(e,fc.$type)}const pc={$type:`IconSizeProperty`,key:`key`,value:`value`};function isIconSizeProperty(e){return J.isInstance(e,pc.$type)}const mc={$type:`Imported`,imported:`imported`,prev:`prev`};function isImported(e){return J.isInstance(e,mc.$type)}const hc={$type:`ImportsFromPoject`,imports:`imports`,project:`project`};function isImportsFromPoject(e){return J.isInstance(e,hc.$type)}const gc={$type:`IncomingRelationExpr`,to:`to`};function isIncomingRelationExpr(e){return J.isInstance(e,gc.$type)}const _c={$type:`InOutRelationExpr`,inout:`inout`};function isInOutRelationExpr(e){return J.isInstance(e,_c.$type)}const vc={$type:`LibIcon`,name:`name`};function isLibIcon(e){return J.isInstance(e,vc.$type)}const yc={$type:`LikeC4Grammar`,deployments:`deployments`,globals:`globals`,imports:`imports`,likec4lib:`likec4lib`,models:`models`,specifications:`specifications`,views:`views`};function isLikeC4Grammar(e){return J.isInstance(e,yc.$type)}const bc={$type:`LikeC4Lib`,icons:`icons`};function isLikeC4Lib(e){return J.isInstance(e,bc.$type)}const xc={$type:`LikeC4View`};function isLikeC4View(e){return J.isInstance(e,xc.$type)}const Sc={$type:`LineProperty`,key:`key`,value:`value`};function isLineProperty(e){return J.isInstance(e,Sc.$type)}const Cc={$type:`LinkProperty`,key:`key`,title:`title`,value:`value`};function isLinkProperty(e){return J.isInstance(e,Cc.$type)}const wc={$type:`MarkdownOrString`,markdown:`markdown`,text:`text`};function isMarkdownOrString(e){return J.isInstance(e,wc.$type)}const Tc={$type:`MetadataArray`,values:`values`};function isMetadataArray(e){return J.isInstance(e,Tc.$type)}const Ec={$type:`MetadataAttribute`,boolValue:`boolValue`,key:`key`,value:`value`};function isMetadataAttribute(e){return J.isInstance(e,Ec.$type)}const Dc={$type:`MetadataBody`,props:`props`};function isMetadataBody(e){return J.isInstance(e,Dc.$type)}const Oc={$type:`MetadataProperty`};function isMetadataProperty(e){return J.isInstance(e,Oc.$type)}const kc={$type:`MetadataValue`},Ac={$type:`Model`,elements:`elements`,name:`name`};function isModel(e){return J.isInstance(e,Ac.$type)}const jc={$type:`ModelDeployments`,elements:`elements`,name:`name`};function isModelDeployments(e){return J.isInstance(e,jc.$type)}const Mc={$type:`ModelElement`},Nc={$type:`ModelReferenceable`},Pc={$type:`ModelViews`,folder:`folder`,name:`name`,styles:`styles`,views:`views`};function isModelViews(e){return J.isInstance(e,Pc.$type)}const Fc={$type:`MultipleProperty`,key:`key`,value:`value`};function isMultipleProperty(e){return J.isInstance(e,Fc.$type)}const Ic={$type:`NavigateToProperty`,key:`key`,value:`value`};function isNavigateToProperty(e){return J.isInstance(e,Ic.$type)}const Lc={$type:`NotationProperty`,key:`key`,value:`value`};function isNotationProperty(e){return J.isInstance(e,Lc.$type)}const Rc={$type:`NotesProperty`,key:`key`,value:`value`};function isNotesProperty(e){return J.isInstance(e,Rc.$type)}const zc={$type:`OpacityProperty`,key:`key`,value:`value`};function isOpacityProperty(e){return J.isInstance(e,zc.$type)}const Bc={$type:`OutgoingRelationExpr`,dotKind:`dotKind`,from:`from`,isBidirectional:`isBidirectional`,kind:`kind`};function isOutgoingRelationExpr(e){return J.isInstance(e,Bc.$type)}const Vc={$type:`PaddingSizeProperty`,key:`key`,value:`value`};function isPaddingSizeProperty(e){return J.isInstance(e,Vc.$type)}const Hc={$type:`Referenceable`},Uc={$type:`Relation`,body:`body`,description:`description`,dotKind:`dotKind`,isBidirectional:`isBidirectional`,kind:`kind`,source:`source`,tags:`tags`,target:`target`,technology:`technology`,title:`title`};function isRelation(e){return J.isInstance(e,Uc.$type)}const Wc={$type:`RelationBody`,props:`props`,tags:`tags`};function isRelationBody(e){return J.isInstance(e,Wc.$type)}const Gc={$type:`RelationExpr`};function isRelationExpr(e){return J.isInstance(e,Gc.$type)}const Kc={$type:`RelationExprOrWhere`};function isRelationExprOrWhere(e){return J.isInstance(e,Kc.$type)}const qc={$type:`RelationExprOrWith`};function isRelationExprOrWith(e){return J.isInstance(e,qc.$type)}const Jc={$type:`RelationExprWhere`,subject:`subject`,where:`where`};function isRelationExprWhere(e){return J.isInstance(e,Jc.$type)}const Yc={$type:`RelationExprWith`,custom:`custom`,subject:`subject`};function isRelationExprWith(e){return J.isInstance(e,Yc.$type)}const Xc={$type:`RelationKindDotRef`,kind:`kind`};function isRelationKindDotRef(e){return J.isInstance(e,Xc.$type)}const Zc={$type:`RelationNavigateToProperty`,key:`key`,value:`value`};function isRelationNavigateToProperty(e){return J.isInstance(e,Zc.$type)}const Qc={$type:`RelationProperty`},$c={$type:`RelationshipKind`,name:`name`};function isRelationshipKind(e){return J.isInstance(e,$c.$type)}const el={$type:`RelationshipStyleProperty`};function isRelationshipStyleProperty(e){return J.isInstance(e,el.$type)}const tl={$type:`RelationStringProperty`,key:`key`,value:`value`};function isRelationStringProperty(e){return J.isInstance(e,tl.$type)}const nl={$type:`RelationStyleProperty`,key:`key`,props:`props`};function isRelationStyleProperty(e){return J.isInstance(e,nl.$type)}const rl={$type:`RGBAColor`,alpha:`alpha`,blue:`blue`,green:`green`,red:`red`};function isRGBAColor(e){return J.isInstance(e,rl.$type)}const il={$type:`ShapeProperty`,key:`key`,value:`value`};function isShapeProperty(e){return J.isInstance(e,il.$type)}const al={$type:`ShapeSizeProperty`,key:`key`,value:`value`};function isShapeSizeProperty(e){return J.isInstance(e,al.$type)}const ol={$type:`SizeProperty`};function isSizeProperty(e){return J.isInstance(e,ol.$type)}const sl={$type:`SizingProperty`,key:`key`,value:`value`};function isSizingProperty(e){return J.isInstance(e,sl.$type)}const cl={$type:`SpecificationColor`,color:`color`,name:`name`};function isSpecificationColor(e){return J.isInstance(e,cl.$type)}const ll={$type:`SpecificationDeploymentNodeKind`,kind:`kind`,props:`props`,tags:`tags`};function isSpecificationDeploymentNodeKind(e){return J.isInstance(e,ll.$type)}const ul={$type:`SpecificationElementKind`,kind:`kind`,props:`props`,tags:`tags`};function isSpecificationElementKind(e){return J.isInstance(e,ul.$type)}const dl={$type:`SpecificationElementStringProperty`,key:`key`,value:`value`};function isSpecificationElementStringProperty(e){return J.isInstance(e,dl.$type)}const fl={$type:`SpecificationRelationshipKind`,kind:`kind`,props:`props`,tags:`tags`};function isSpecificationRelationshipKind(e){return J.isInstance(e,fl.$type)}const pl={$type:`SpecificationRelationshipStringProperty`,key:`key`,value:`value`};function isSpecificationRelationshipStringProperty(e){return J.isInstance(e,pl.$type)}const ml={$type:`SpecificationRule`,colors:`colors`,deploymentNodes:`deploymentNodes`,elements:`elements`,name:`name`,relationships:`relationships`,tags:`tags`};function isSpecificationRule(e){return J.isInstance(e,ml.$type)}const hl={$type:`SpecificationTag`,color:`color`,customColor:`customColor`,tag:`tag`,themeColor:`themeColor`};function isSpecificationTag(e){return J.isInstance(e,hl.$type)}const gl={$type:`Step`,custom:`custom`,dotKind:`dotKind`,isBackward:`isBackward`,kind:`kind`,source:`source`,target:`target`,title:`title`};function isStep(e){return J.isInstance(e,gl.$type)}const _l={$type:`StepOrSeries`};function isStepOrSeries(e){return J.isInstance(e,_l.$type)}const vl={$type:`StepsBlock`,steps:`steps`};function isStepsBlock(e){return J.isInstance(e,vl.$type)}const yl={$type:`StepSeries`,custom:`custom`,dotKind:`dotKind`,kind:`kind`,source:`source`,target:`target`,title:`title`};function isStepSeries(e){return J.isInstance(e,yl.$type)}const bl={$type:`StepStatement`};function isStepStatement(e){return J.isInstance(e,bl.$type)}const xl={$type:`StrictFqnElementRef`,el:`el`,parent:`parent`};function isStrictFqnElementRef(e){return J.isInstance(e,xl.$type)}const Sl={$type:`StrictFqnRef`,parent:`parent`,value:`value`};function isStrictFqnRef(e){return J.isInstance(e,Sl.$type)}const Cl={$type:`StringProperty`};function isStringProperty(e){return J.isInstance(e,Cl.$type)}const wl={$type:`StyleProperty`};function isStyleProperty(e){return J.isInstance(e,wl.$type)}const Tl={$type:`SubflowStep`,kind:`kind`,steps:`steps`,title:`title`};function isSubflowStep(e){return J.isInstance(e,Tl.$type)}const El={$type:`Tag`,name:`name`};function isTag(e){return J.isInstance(e,El.$type)}const Dl={$type:`TagRef`,tag:`tag`};function isTagRef(e){return J.isInstance(e,Dl.$type)}const Ol={$type:`Tags`,prev:`prev`,values:`values`};function isTags(e){return J.isInstance(e,Ol.$type)}const kl={$type:`TextSizeProperty`,key:`key`,value:`value`};function isTextSizeProperty(e){return J.isInstance(e,kl.$type)}const Al={$type:`TryBlock`,steps:`steps`,title:`title`};function isTryBlock(e){return J.isInstance(e,Al.$type)}const jl={$type:`TryStep`};function isTryStep(e){return J.isInstance(e,jl.$type)}const Ml={$type:`ViewOrderProperty`,key:`key`,value:`value`};function isViewOrderProperty(e){return J.isInstance(e,Ml.$type)}const Nl={$type:`ViewProperty`};function isViewProperty(e){return J.isInstance(e,Nl.$type)}const Pl={$type:`ViewRef`,view:`view`},Fl={$type:`ViewRoutingProperty`,key:`key`,value:`value`};function isViewRoutingProperty(e){return J.isInstance(e,Fl.$type)}const Il={$type:`ViewRule`};function isViewRule(e){return J.isInstance(e,Il.$type)}const Ll={$type:`ViewRuleAncestors`,key:`key`,value:`value`};function isViewRuleAncestors(e){return J.isInstance(e,Ll.$type)}const Rl={$type:`ViewRuleAutoLayout`,direction:`direction`,nodeSep:`nodeSep`,rankSep:`rankSep`,routing:`routing`};function isViewRuleAutoLayout(e){return J.isInstance(e,Rl.$type)}const zl={$type:`ViewRuleGlobalPredicateRef`,predicate:`predicate`};function isViewRuleGlobalPredicateRef(e){return J.isInstance(e,zl.$type)}const Bl={$type:`ViewRuleGlobalStyle`,style:`style`};function isViewRuleGlobalStyle(e){return J.isInstance(e,Bl.$type)}const Vl={$type:`ViewRuleGroup`,groupRules:`groupRules`,props:`props`,title:`title`};function isViewRuleGroup(e){return J.isInstance(e,Vl.$type)}const Hl={$type:`ViewRulePredicate`,exprs:`exprs`,isInclude:`isInclude`};function isViewRulePredicate(e){return J.isInstance(e,Hl.$type)}const Ul={$type:`ViewRuleRank`,targets:`targets`,value:`value`};function isViewRuleRank(e){return J.isInstance(e,Ul.$type)}const Wl={$type:`ViewRuleStyle`,props:`props`,targets:`targets`};function isViewRuleStyle(e){return J.isInstance(e,Wl.$type)}const Gl={$type:`ViewRuleStyleOrGlobalRef`};function isViewRuleStyleOrGlobalRef(e){return J.isInstance(e,Gl.$type)}const Kl={$type:`ViewStringProperty`,key:`key`,value:`value`};function isViewStringProperty(e){return J.isInstance(e,Kl.$type)}const ql={$type:`WhereBinaryExpression`,left:`left`,operator:`operator`,right:`right`};function isWhereBinaryExpression(e){return J.isInstance(e,ql.$type)}const Jl={$type:`WhereElement`};function isWhereElement(e){return J.isInstance(e,Jl.$type)}const Yl={$type:`WhereElementExpression`};function isWhereElementExpression(e){return J.isInstance(e,Yl.$type)}const Xl={$type:`WhereElementKind`,not:`not`,operator:`operator`,value:`value`};function isWhereElementKind(e){return J.isInstance(e,Xl.$type)}const Zl={$type:`WhereElementMetadata`,key:`key`,not:`not`,operator:`operator`,value:`value`};function isWhereElementMetadata(e){return J.isInstance(e,Zl.$type)}const Ql={$type:`WhereElementNegation`,value:`value`};function isWhereElementNegation(e){return J.isInstance(e,Ql.$type)}const $l={$type:`WhereElementTag`,not:`not`,operator:`operator`,value:`value`};function isWhereElementTag(e){return J.isInstance(e,$l.$type)}const eu={$type:`WhereExpression`},tu={$type:`WhereKindEqual`};function isWhereKindEqual(e){return J.isInstance(e,tu.$type)}const nu={$type:`WhereMetadataEqual`};function isWhereMetadataEqual(e){return J.isInstance(e,nu.$type)}const ru={$type:`WhereRelation`};function isWhereRelation(e){return J.isInstance(e,ru.$type)}const iu={$type:`WhereRelationExpression`};function isWhereRelationExpression(e){return J.isInstance(e,iu.$type)}const au={$type:`WhereRelationKind`,not:`not`,operator:`operator`,value:`value`};function isWhereRelationKind(e){return J.isInstance(e,au.$type)}const ou={$type:`WhereRelationMetadata`,key:`key`,not:`not`,operator:`operator`,value:`value`};function isWhereRelationMetadata(e){return J.isInstance(e,ou.$type)}const su={$type:`WhereRelationNegation`,value:`value`};function isWhereRelationNegation(e){return J.isInstance(e,su.$type)}const cu={$type:`WhereRelationParticipantKind`,not:`not`,operator:`operator`,participant:`participant`,value:`value`};function isWhereRelationParticipantKind(e){return J.isInstance(e,cu.$type)}const lu={$type:`WhereRelationParticipantMetadata`,key:`key`,not:`not`,operator:`operator`,participant:`participant`,value:`value`};function isWhereRelationParticipantMetadata(e){return J.isInstance(e,lu.$type)}const uu={$type:`WhereRelationParticipantTag`,not:`not`,operator:`operator`,participant:`participant`,value:`value`};function isWhereRelationParticipantTag(e){return J.isInstance(e,uu.$type)}const du={$type:`WhereRelationTag`,not:`not`,operator:`operator`,value:`value`};function isWhereRelationTag(e){return J.isInstance(e,du.$type)}const fu={$type:`WhereTagEqual`};function isWhereTagEqual(e){return J.isInstance(e,fu.$type)}const pu={$type:`WildcardExpression`,isWildcard:`isWildcard`};function isWildcardExpression(e){return J.isInstance(e,pu.$type)}var LikeC4AstReflection=class extends On{types={AbstractStep:{name:Uo.$type,properties:{custom:{name:Uo.custom,optional:!0},dotKind:{name:Uo.dotKind,optional:!0},kind:{name:Uo.kind,referenceType:$c.$type,optional:!0},target:{name:Uo.target},title:{name:Uo.title,optional:!0}},superTypes:[]},AltSteps:{name:Wo.$type,properties:{branches:{name:Wo.branches,defaultValue:[]},title:{name:Wo.title,optional:!0}},superTypes:[bl.$type]},AnyProperty:{name:Go.$type,properties:{},superTypes:[]},ArrowProperty:{name:Ko.$type,properties:{key:{name:Ko.key},value:{name:Ko.value}},superTypes:[el.$type]},BorderProperty:{name:qo.$type,properties:{key:{name:qo.key},value:{name:qo.value}},superTypes:[wl.$type]},CatchBlock:{name:Jo.$type,properties:{catch:{name:Jo.catch},title:{name:Jo.title,optional:!0},try:{name:Jo.try}},superTypes:[jl.$type]},ColorLiteral:{name:Yo.$type,properties:{},superTypes:[]},ColorProperty:{name:Xo.$type,properties:{customColor:{name:Xo.customColor,referenceType:Zo.$type,optional:!0},key:{name:Xo.key},themeColor:{name:Xo.themeColor,optional:!0}},superTypes:[el.$type,wl.$type]},CustomColor:{name:Zo.$type,properties:{name:{name:Zo.name}},superTypes:[]},CustomElementProperties:{name:Qo.$type,properties:{props:{name:Qo.props,defaultValue:[],optional:!0}},superTypes:[]},CustomRelationProperties:{name:$o.$type,properties:{props:{name:$o.props,defaultValue:[],optional:!0}},superTypes:[]},DeployedInstance:{name:es.$type,properties:{body:{name:es.body,optional:!0},name:{name:es.name,optional:!0},summary:{name:es.summary,optional:!0},target:{name:es.target},title:{name:es.title,optional:!0}},superTypes:[ns.$type,Hc.$type]},DeployedInstanceBody:{name:ts.$type,properties:{elements:{name:ts.elements,defaultValue:[],optional:!0},props:{name:ts.props,defaultValue:[],optional:!0},tags:{name:ts.tags,optional:!0}},superTypes:[]},DeploymentElement:{name:ns.$type,properties:{},superTypes:[]},DeploymentNode:{name:rs.$type,properties:{body:{name:rs.body,optional:!0},kind:{name:rs.kind,referenceType:os.$type},name:{name:rs.name},summary:{name:rs.summary,optional:!0},title:{name:rs.title,optional:!0}},superTypes:[ns.$type,Hc.$type]},DeploymentNodeBody:{name:as.$type,properties:{elements:{name:as.elements,defaultValue:[],optional:!0},props:{name:as.props,defaultValue:[],optional:!0},tags:{name:as.tags,optional:!0}},superTypes:[]},DeploymentNodeKind:{name:os.$type,properties:{name:{name:os.name}},superTypes:[ss.$type]},DeploymentNodeOrElementKind:{name:ss.$type,properties:{},superTypes:[]},DeploymentRelation:{name:cs.$type,properties:{body:{name:cs.body,optional:!0},description:{name:cs.description,optional:!0},dotKind:{name:cs.dotKind,optional:!0},isBidirectional:{name:cs.isBidirectional,defaultValue:!1,optional:!0},kind:{name:cs.kind,referenceType:$c.$type,optional:!0},source:{name:cs.source,optional:!0},tags:{name:cs.tags,optional:!0},target:{name:cs.target},technology:{name:cs.technology,optional:!0},title:{name:cs.title,optional:!0}},superTypes:[]},DeploymentRelationBody:{name:ls.$type,properties:{props:{name:ls.props,defaultValue:[],optional:!0},tags:{name:ls.tags,optional:!0}},superTypes:[]},DeploymentView:{name:us.$type,properties:{body:{name:us.body,optional:!0},name:{name:us.name}},superTypes:[xc.$type]},DeploymentViewBody:{name:ds.$type,properties:{props:{name:ds.props,defaultValue:[],optional:!0},rules:{name:ds.rules,defaultValue:[],optional:!0},tags:{name:ds.tags,optional:!0}},superTypes:[]},DeploymentViewRule:{name:fs.$type,properties:{},superTypes:[]},DeploymentViewRulePredicate:{name:ps.$type,properties:{expr:{name:ps.expr},isInclude:{name:ps.isInclude,defaultValue:!1,optional:!0}},superTypes:[fs.$type]},DeploymentViewRuleStyle:{name:ms.$type,properties:{props:{name:ms.props,defaultValue:[],optional:!0},targets:{name:ms.targets}},superTypes:[fs.$type]},DirectedRelationExpr:{name:hs.$type,properties:{source:{name:hs.source},target:{name:hs.target}},superTypes:[Gc.$type]},DynamicView:{name:gs.$type,properties:{body:{name:gs.body,optional:!0},name:{name:gs.name}},superTypes:[xc.$type]},DynamicViewBody:{name:_s.$type,properties:{props:{name:_s.props,defaultValue:[],optional:!0},rules:{name:_s.rules,defaultValue:[],optional:!0},steps:{name:_s.steps,defaultValue:[],optional:!0},tags:{name:_s.tags,optional:!0}},superTypes:[]},DynamicViewDisplayVariantProperty:{name:vs.$type,properties:{key:{name:vs.key},value:{name:vs.value}},superTypes:[xs.$type]},DynamicViewGlobalPredicateRef:{name:ys.$type,properties:{predicate:{name:ys.predicate,referenceType:rc.$type}},superTypes:[Cs.$type]},DynamicViewIncludePredicate:{name:bs.$type,properties:{exprs:{name:bs.exprs}},superTypes:[Cs.$type]},DynamicViewProperty:{name:xs.$type,properties:{},superTypes:[Go.$type]},DynamicViewRef:{name:Ss.$type,properties:{view:{name:Ss.view,referenceType:gs.$type}},superTypes:[]},DynamicViewRule:{name:Cs.$type,properties:{},superTypes:[]},Element:{name:ws.$type,properties:{body:{name:ws.body,optional:!0},kind:{name:ws.kind,referenceType:Es.$type},name:{name:ws.name},props:{name:ws.props,defaultValue:[],optional:!0}},superTypes:[tc.$type,Mc.$type,Nc.$type,Hc.$type]},ElementBody:{name:Ts.$type,properties:{elements:{name:Ts.elements,defaultValue:[],optional:!0},props:{name:Ts.props,defaultValue:[],optional:!0},tags:{name:Ts.tags,optional:!0}},superTypes:[]},ElementKind:{name:Es.$type,properties:{name:{name:Es.name}},superTypes:[ss.$type]},ElementKindExpression:{name:Ds.$type,properties:{isEqual:{name:Ds.isEqual,defaultValue:!1,optional:!0},kind:{name:Ds.kind,referenceType:Es.$type}},superTypes:[Js.$type]},ElementProperty:{name:Os.$type,properties:{},superTypes:[Go.$type]},ElementRef:{name:ks.$type,properties:{modelElement:{name:ks.modelElement}},superTypes:[]},ElementStringProperty:{name:As.$type,properties:{key:{name:As.key},value:{name:As.value}},superTypes:[Os.$type,Cl.$type]},ElementStyleProperty:{name:js.$type,properties:{key:{name:js.key},props:{name:js.props,defaultValue:[],optional:!0}},superTypes:[Os.$type]},ElementTagExpression:{name:Ms.$type,properties:{isEqual:{name:Ms.isEqual,defaultValue:!1,optional:!0},tag:{name:Ms.tag}},superTypes:[Js.$type]},ElementView:{name:Ns.$type,properties:{body:{name:Ns.body,optional:!0},extends:{name:Ns.extends,optional:!0},name:{name:Ns.name,optional:!0},viewOf:{name:Ns.viewOf,optional:!0}},superTypes:[xc.$type]},ElementViewBody:{name:Ps.$type,properties:{props:{name:Ps.props,defaultValue:[],optional:!0},rules:{name:Ps.rules,defaultValue:[],optional:!0},tags:{name:Ps.tags,optional:!0}},superTypes:[]},ElementViewRef:{name:Fs.$type,properties:{view:{name:Fs.view,referenceType:Ns.$type}},superTypes:[]},ExpressionV2:{name:Ls.$type,properties:{},superTypes:[]},Expressions:{name:Is.$type,properties:{prev:{name:Is.prev,optional:!0},value:{name:Is.value}},superTypes:[]},ExtendDeployment:{name:Rs.$type,properties:{body:{name:Rs.body},deploymentNode:{name:Rs.deploymentNode}},superTypes:[tc.$type]},ExtendDeploymentBody:{name:zs.$type,properties:{elements:{name:zs.elements,defaultValue:[],optional:!0},props:{name:zs.props,defaultValue:[],optional:!0},tags:{name:zs.tags,optional:!0}},superTypes:[]},ExtendElement:{name:Bs.$type,properties:{body:{name:Bs.body},element:{name:Bs.element}},superTypes:[Hs.$type,tc.$type]},ExtendElementBody:{name:Vs.$type,properties:{elements:{name:Vs.elements,defaultValue:[],optional:!0},props:{name:Vs.props,defaultValue:[],optional:!0},tags:{name:Vs.tags,optional:!0}},superTypes:[]},ExtendElementOrRelation:{name:Hs.$type,properties:{},superTypes:[Mc.$type]},ExtendElementProperty:{name:Us.$type,properties:{},superTypes:[]},ExtendRelation:{name:Ws.$type,properties:{body:{name:Ws.body},dotKind:{name:Ws.dotKind,optional:!0},isBidirectional:{name:Ws.isBidirectional,defaultValue:!1,optional:!0},kind:{name:Ws.kind,referenceType:$c.$type,optional:!0},source:{name:Ws.source},target:{name:Ws.target},title:{name:Ws.title,optional:!0}},superTypes:[Hs.$type]},ExtendRelationBody:{name:Gs.$type,properties:{props:{name:Gs.props,defaultValue:[],optional:!0},tags:{name:Gs.tags,optional:!0}},superTypes:[]},ExtendRelationProperty:{name:Ks.$type,properties:{},superTypes:[]},FinallyBlock:{name:qs.$type,properties:{finally:{name:qs.finally},title:{name:qs.title,optional:!0},tryCatch:{name:qs.tryCatch}},superTypes:[jl.$type]},FqnExpr:{name:Js.$type,properties:{},superTypes:[Xs.$type]},FqnExprOrWhere:{name:Xs.$type,properties:{},superTypes:[Zs.$type]},FqnExprOrWith:{name:Zs.$type,properties:{},superTypes:[Ls.$type]},FqnExprWhere:{name:Qs.$type,properties:{subject:{name:Qs.subject},where:{name:Qs.where,optional:!0}},superTypes:[Xs.$type]},FqnExprWith:{name:$s.$type,properties:{custom:{name:$s.custom,optional:!0},subject:{name:$s.subject}},superTypes:[Zs.$type]},FqnExpressions:{name:Ys.$type,properties:{prev:{name:Ys.prev,optional:!0},value:{name:Ys.value}},superTypes:[]},FqnRef:{name:ec.$type,properties:{parent:{name:ec.parent,optional:!0},value:{name:ec.value,referenceType:Hc.$type}},superTypes:[]},FqnRefExpr:{name:nc.$type,properties:{ref:{name:nc.ref},selector:{name:nc.selector,optional:!0}},superTypes:[Js.$type]},FqnReferenceable:{name:tc.$type,properties:{},superTypes:[]},GlobalDynamicPredicateGroup:{name:rc.$type,properties:{name:{name:rc.name},predicates:{name:rc.predicates,defaultValue:[],optional:!0}},superTypes:[]},GlobalPredicateGroup:{name:ic.$type,properties:{name:{name:ic.name},predicates:{name:ic.predicates,defaultValue:[],optional:!0}},superTypes:[]},GlobalStyle:{name:oc.$type,properties:{id:{name:oc.id},props:{name:oc.props,defaultValue:[],optional:!0},targets:{name:oc.targets}},superTypes:[]},GlobalStyleGroup:{name:sc.$type,properties:{id:{name:sc.id},styles:{name:sc.styles,defaultValue:[],optional:!0}},superTypes:[]},GlobalStyleId:{name:cc.$type,properties:{name:{name:cc.name}},superTypes:[]},Globals:{name:ac.$type,properties:{name:{name:ac.name},predicates:{name:ac.predicates,defaultValue:[],optional:!0},styles:{name:ac.styles,defaultValue:[],optional:!0}},superTypes:[]},HexColor:{name:lc.$type,properties:{hex:{name:lc.hex}},superTypes:[Yo.$type]},IconColorProperty:{name:uc.$type,properties:{customColor:{name:uc.customColor,referenceType:Zo.$type,optional:!0},key:{name:uc.key},themeColor:{name:uc.themeColor,optional:!0}},superTypes:[wl.$type]},IconPositionProperty:{name:dc.$type,properties:{key:{name:dc.key},value:{name:dc.value}},superTypes:[wl.$type]},IconProperty:{name:fc.$type,properties:{key:{name:fc.key},libicon:{name:fc.libicon,referenceType:vc.$type,optional:!0},value:{name:fc.value,optional:!0}},superTypes:[Os.$type,wl.$type]},IconSizeProperty:{name:pc.$type,properties:{key:{name:pc.key},value:{name:pc.value}},superTypes:[ol.$type,wl.$type]},Imported:{name:mc.$type,properties:{imported:{name:mc.imported,referenceType:ws.$type},prev:{name:mc.prev,optional:!0}},superTypes:[Nc.$type,Hc.$type]},ImportsFromPoject:{name:hc.$type,properties:{imports:{name:hc.imports},project:{name:hc.project}},superTypes:[]},InOutRelationExpr:{name:_c.$type,properties:{inout:{name:_c.inout}},superTypes:[Gc.$type]},IncomingRelationExpr:{name:gc.$type,properties:{to:{name:gc.to}},superTypes:[Gc.$type]},LibIcon:{name:vc.$type,properties:{name:{name:vc.name}},superTypes:[]},LikeC4Grammar:{name:yc.$type,properties:{deployments:{name:yc.deployments,defaultValue:[],optional:!0},globals:{name:yc.globals,defaultValue:[],optional:!0},imports:{name:yc.imports,defaultValue:[],optional:!0},likec4lib:{name:yc.likec4lib,defaultValue:[],optional:!0},models:{name:yc.models,defaultValue:[],optional:!0},specifications:{name:yc.specifications,defaultValue:[],optional:!0},views:{name:yc.views,defaultValue:[],optional:!0}},superTypes:[]},LikeC4Lib:{name:bc.$type,properties:{icons:{name:bc.icons,defaultValue:[]}},superTypes:[]},LikeC4View:{name:xc.$type,properties:{},superTypes:[]},LineProperty:{name:Sc.$type,properties:{key:{name:Sc.key},value:{name:Sc.value}},superTypes:[el.$type]},LinkProperty:{name:Cc.$type,properties:{key:{name:Cc.key},title:{name:Cc.title,optional:!0},value:{name:Cc.value}},superTypes:[Os.$type,Us.$type,Ks.$type,Qc.$type,Nl.$type]},MarkdownOrString:{name:wc.$type,properties:{markdown:{name:wc.markdown,optional:!0},text:{name:wc.text,optional:!0}},superTypes:[kc.$type]},MetadataArray:{name:Tc.$type,properties:{values:{name:Tc.values,defaultValue:[]}},superTypes:[kc.$type]},MetadataAttribute:{name:Ec.$type,properties:{boolValue:{name:Ec.boolValue,defaultValue:!1,optional:!0},key:{name:Ec.key},value:{name:Ec.value,optional:!0}},superTypes:[Cl.$type]},MetadataBody:{name:Dc.$type,properties:{props:{name:Dc.props,defaultValue:[],optional:!0}},superTypes:[Oc.$type]},MetadataProperty:{name:Oc.$type,properties:{},superTypes:[Os.$type,Us.$type,Ks.$type,Qc.$type]},MetadataValue:{name:kc.$type,properties:{},superTypes:[]},Model:{name:Ac.$type,properties:{elements:{name:Ac.elements,defaultValue:[],optional:!0},name:{name:Ac.name}},superTypes:[]},ModelDeployments:{name:jc.$type,properties:{elements:{name:jc.elements,defaultValue:[],optional:!0},name:{name:jc.name}},superTypes:[]},ModelElement:{name:Mc.$type,properties:{},superTypes:[]},ModelReferenceable:{name:Nc.$type,properties:{},superTypes:[]},ModelViews:{name:Pc.$type,properties:{folder:{name:Pc.folder,optional:!0},name:{name:Pc.name},styles:{name:Pc.styles,defaultValue:[],optional:!0},views:{name:Pc.views,defaultValue:[],optional:!0}},superTypes:[]},MultipleProperty:{name:Fc.$type,properties:{key:{name:Fc.key},value:{name:Fc.value,defaultValue:!1}},superTypes:[wl.$type]},NavigateToProperty:{name:Ic.$type,properties:{key:{name:Ic.key},value:{name:Ic.value}},superTypes:[Go.$type]},NotationProperty:{name:Lc.$type,properties:{key:{name:Lc.key},value:{name:Lc.value}},superTypes:[Cl.$type]},NotesProperty:{name:Rc.$type,properties:{key:{name:Rc.key},value:{name:Rc.value}},superTypes:[Cl.$type]},OpacityProperty:{name:zc.$type,properties:{key:{name:zc.key},value:{name:zc.value}},superTypes:[wl.$type]},OutgoingRelationExpr:{name:Bc.$type,properties:{dotKind:{name:Bc.dotKind,optional:!0},from:{name:Bc.from},isBidirectional:{name:Bc.isBidirectional,defaultValue:!1,optional:!0},kind:{name:Bc.kind,referenceType:$c.$type,optional:!0}},superTypes:[Gc.$type]},PaddingSizeProperty:{name:Vc.$type,properties:{key:{name:Vc.key},value:{name:Vc.value}},superTypes:[ol.$type,wl.$type]},RGBAColor:{name:rl.$type,properties:{alpha:{name:rl.alpha,optional:!0},blue:{name:rl.blue},green:{name:rl.green},red:{name:rl.red}},superTypes:[Yo.$type]},Referenceable:{name:Hc.$type,properties:{},superTypes:[tc.$type]},Relation:{name:Uc.$type,properties:{body:{name:Uc.body,optional:!0},description:{name:Uc.description,optional:!0},dotKind:{name:Uc.dotKind,optional:!0},isBidirectional:{name:Uc.isBidirectional,defaultValue:!1,optional:!0},kind:{name:Uc.kind,referenceType:$c.$type,optional:!0},source:{name:Uc.source,optional:!0},tags:{name:Uc.tags,optional:!0},target:{name:Uc.target},technology:{name:Uc.technology,optional:!0},title:{name:Uc.title,optional:!0}},superTypes:[Mc.$type]},RelationBody:{name:Wc.$type,properties:{props:{name:Wc.props,defaultValue:[],optional:!0},tags:{name:Wc.tags,optional:!0}},superTypes:[]},RelationExpr:{name:Gc.$type,properties:{},superTypes:[Kc.$type]},RelationExprOrWhere:{name:Kc.$type,properties:{},superTypes:[qc.$type]},RelationExprOrWith:{name:qc.$type,properties:{},superTypes:[Ls.$type]},RelationExprWhere:{name:Jc.$type,properties:{subject:{name:Jc.subject},where:{name:Jc.where,optional:!0}},superTypes:[Kc.$type]},RelationExprWith:{name:Yc.$type,properties:{custom:{name:Yc.custom,optional:!0},subject:{name:Yc.subject}},superTypes:[qc.$type]},RelationKindDotRef:{name:Xc.$type,properties:{kind:{name:Xc.kind,referenceType:$c.$type}},superTypes:[]},RelationNavigateToProperty:{name:Zc.$type,properties:{key:{name:Zc.key},value:{name:Zc.value}},superTypes:[Qc.$type]},RelationProperty:{name:Qc.$type,properties:{},superTypes:[Go.$type]},RelationStringProperty:{name:tl.$type,properties:{key:{name:tl.key},value:{name:tl.value}},superTypes:[Qc.$type,Cl.$type]},RelationStyleProperty:{name:nl.$type,properties:{key:{name:nl.key},props:{name:nl.props,defaultValue:[],optional:!0}},superTypes:[Qc.$type]},RelationshipKind:{name:$c.$type,properties:{name:{name:$c.name}},superTypes:[]},RelationshipStyleProperty:{name:el.$type,properties:{},superTypes:[Go.$type]},ShapeProperty:{name:il.$type,properties:{key:{name:il.key},value:{name:il.value}},superTypes:[wl.$type]},ShapeSizeProperty:{name:al.$type,properties:{key:{name:al.key},value:{name:al.value}},superTypes:[ol.$type,wl.$type]},SizeProperty:{name:ol.$type,properties:{},superTypes:[]},SizingProperty:{name:sl.$type,properties:{key:{name:sl.key},value:{name:sl.value}},superTypes:[wl.$type]},SpecificationColor:{name:cl.$type,properties:{color:{name:cl.color},name:{name:cl.name}},superTypes:[]},SpecificationDeploymentNodeKind:{name:ll.$type,properties:{kind:{name:ll.kind},props:{name:ll.props,defaultValue:[],optional:!0},tags:{name:ll.tags,optional:!0}},superTypes:[]},SpecificationElementKind:{name:ul.$type,properties:{kind:{name:ul.kind},props:{name:ul.props,defaultValue:[],optional:!0},tags:{name:ul.tags,optional:!0}},superTypes:[]},SpecificationElementStringProperty:{name:dl.$type,properties:{key:{name:dl.key},value:{name:dl.value}},superTypes:[Cl.$type]},SpecificationRelationshipKind:{name:fl.$type,properties:{kind:{name:fl.kind},props:{name:fl.props,defaultValue:[],optional:!0},tags:{name:fl.tags,optional:!0}},superTypes:[]},SpecificationRelationshipStringProperty:{name:pl.$type,properties:{key:{name:pl.key},value:{name:pl.value}},superTypes:[Cl.$type]},SpecificationRule:{name:ml.$type,properties:{colors:{name:ml.colors,defaultValue:[],optional:!0},deploymentNodes:{name:ml.deploymentNodes,defaultValue:[],optional:!0},elements:{name:ml.elements,defaultValue:[],optional:!0},name:{name:ml.name},relationships:{name:ml.relationships,defaultValue:[],optional:!0},tags:{name:ml.tags,defaultValue:[],optional:!0}},superTypes:[]},SpecificationTag:{name:hl.$type,properties:{color:{name:hl.color,optional:!0},customColor:{name:hl.customColor,referenceType:Zo.$type,optional:!0},tag:{name:hl.tag},themeColor:{name:hl.themeColor,optional:!0}},superTypes:[]},Step:{name:gl.$type,properties:{custom:{name:gl.custom,optional:!0},dotKind:{name:gl.dotKind,optional:!0},isBackward:{name:gl.isBackward,defaultValue:!1,optional:!0},kind:{name:gl.kind,referenceType:$c.$type,optional:!0},source:{name:gl.source},target:{name:gl.target},title:{name:gl.title,optional:!0}},superTypes:[Uo.$type,_l.$type]},StepOrSeries:{name:_l.$type,properties:{},superTypes:[bl.$type]},StepSeries:{name:yl.$type,properties:{custom:{name:yl.custom,optional:!0},dotKind:{name:yl.dotKind,optional:!0},kind:{name:yl.kind,referenceType:$c.$type,optional:!0},source:{name:yl.source},target:{name:yl.target},title:{name:yl.title,optional:!0}},superTypes:[Uo.$type,_l.$type]},StepStatement:{name:bl.$type,properties:{},superTypes:[]},StepsBlock:{name:vl.$type,properties:{steps:{name:vl.steps,defaultValue:[]}},superTypes:[]},StrictFqnElementRef:{name:xl.$type,properties:{el:{name:xl.el,referenceType:ws.$type},parent:{name:xl.parent,optional:!0}},superTypes:[]},StrictFqnRef:{name:Sl.$type,properties:{parent:{name:Sl.parent,optional:!0},value:{name:Sl.value,referenceType:Hc.$type}},superTypes:[]},StringProperty:{name:Cl.$type,properties:{},superTypes:[Go.$type]},StyleProperty:{name:wl.$type,properties:{},superTypes:[Go.$type]},SubflowStep:{name:Tl.$type,properties:{kind:{name:Tl.kind},steps:{name:Tl.steps,defaultValue:[]},title:{name:Tl.title,optional:!0}},superTypes:[vl.$type,bl.$type]},Tag:{name:El.$type,properties:{name:{name:El.name}},superTypes:[]},TagRef:{name:Dl.$type,properties:{tag:{name:Dl.tag,referenceType:El.$type}},superTypes:[]},Tags:{name:Ol.$type,properties:{prev:{name:Ol.prev,optional:!0},values:{name:Ol.values,defaultValue:[]}},superTypes:[]},TextSizeProperty:{name:kl.$type,properties:{key:{name:kl.key},value:{name:kl.value}},superTypes:[ol.$type,wl.$type]},TryBlock:{name:Al.$type,properties:{steps:{name:Al.steps,defaultValue:[]},title:{name:Al.title,optional:!0}},superTypes:[vl.$type,jl.$type]},TryStep:{name:jl.$type,properties:{},superTypes:[bl.$type]},ViewOrderProperty:{name:Ml.$type,properties:{key:{name:Ml.key},value:{name:Ml.value}},superTypes:[Nl.$type]},ViewProperty:{name:Nl.$type,properties:{},superTypes:[Go.$type,xs.$type]},ViewRef:{name:Pl.$type,properties:{view:{name:Pl.view,referenceType:xc.$type}},superTypes:[]},ViewRoutingProperty:{name:Fl.$type,properties:{key:{name:Fl.key},value:{name:Fl.value}},superTypes:[Nl.$type]},ViewRule:{name:Il.$type,properties:{},superTypes:[]},ViewRuleAncestors:{name:Ll.$type,properties:{key:{name:Ll.key},value:{name:Ll.value,defaultValue:!1}},superTypes:[fs.$type]},ViewRuleAutoLayout:{name:Rl.$type,properties:{direction:{name:Rl.direction},nodeSep:{name:Rl.nodeSep,optional:!0},rankSep:{name:Rl.rankSep,optional:!0},routing:{name:Rl.routing,optional:!0}},superTypes:[fs.$type,Cs.$type,Il.$type]},ViewRuleGlobalPredicateRef:{name:zl.$type,properties:{predicate:{name:zl.predicate,referenceType:ic.$type}},superTypes:[Il.$type]},ViewRuleGlobalStyle:{name:Bl.$type,properties:{style:{name:Bl.style,referenceType:cc.$type}},superTypes:[Gl.$type]},ViewRuleGroup:{name:Vl.$type,properties:{groupRules:{name:Vl.groupRules,defaultValue:[],optional:!0},props:{name:Vl.props,defaultValue:[],optional:!0},title:{name:Vl.title,optional:!0}},superTypes:[Il.$type]},ViewRulePredicate:{name:Hl.$type,properties:{exprs:{name:Hl.exprs},isInclude:{name:Hl.isInclude,defaultValue:!1,optional:!0}},superTypes:[Il.$type]},ViewRuleRank:{name:Ul.$type,properties:{targets:{name:Ul.targets},value:{name:Ul.value,optional:!0}},superTypes:[Il.$type]},ViewRuleStyle:{name:Wl.$type,properties:{props:{name:Wl.props,defaultValue:[],optional:!0},targets:{name:Wl.targets}},superTypes:[Gl.$type]},ViewRuleStyleOrGlobalRef:{name:Gl.$type,properties:{},superTypes:[Cs.$type,Il.$type]},ViewStringProperty:{name:Kl.$type,properties:{key:{name:Kl.key},value:{name:Kl.value}},superTypes:[Cl.$type,Nl.$type]},WhereBinaryExpression:{name:ql.$type,properties:{left:{name:ql.left},operator:{name:ql.operator},right:{name:ql.right}},superTypes:[Yl.$type,iu.$type]},WhereElement:{name:Jl.$type,properties:{},superTypes:[Yl.$type]},WhereElementExpression:{name:Yl.$type,properties:{},superTypes:[eu.$type]},WhereElementKind:{name:Xl.$type,properties:{not:{name:Xl.not,defaultValue:!1,optional:!0},operator:{name:Xl.operator},value:{name:Xl.value,referenceType:ss.$type}},superTypes:[Jl.$type,tu.$type]},WhereElementMetadata:{name:Zl.$type,properties:{key:{name:Zl.key},not:{name:Zl.not,defaultValue:!1,optional:!0},operator:{name:Zl.operator,optional:!0},value:{name:Zl.value,optional:!0}},superTypes:[Jl.$type,nu.$type]},WhereElementNegation:{name:Ql.$type,properties:{value:{name:Ql.value}},superTypes:[Yl.$type]},WhereElementTag:{name:$l.$type,properties:{not:{name:$l.not,defaultValue:!1,optional:!0},operator:{name:$l.operator},value:{name:$l.value}},superTypes:[Jl.$type,fu.$type]},WhereExpression:{name:eu.$type,properties:{},superTypes:[]},WhereKindEqual:{name:tu.$type,properties:{},superTypes:[]},WhereMetadataEqual:{name:nu.$type,properties:{},superTypes:[]},WhereRelation:{name:ru.$type,properties:{},superTypes:[iu.$type]},WhereRelationExpression:{name:iu.$type,properties:{},superTypes:[eu.$type]},WhereRelationKind:{name:au.$type,properties:{not:{name:au.not,defaultValue:!1,optional:!0},operator:{name:au.operator},value:{name:au.value,referenceType:$c.$type}},superTypes:[tu.$type,ru.$type]},WhereRelationMetadata:{name:ou.$type,properties:{key:{name:ou.key},not:{name:ou.not,defaultValue:!1,optional:!0},operator:{name:ou.operator,optional:!0},value:{name:ou.value,optional:!0}},superTypes:[nu.$type,ru.$type]},WhereRelationNegation:{name:su.$type,properties:{value:{name:su.value}},superTypes:[iu.$type]},WhereRelationParticipantKind:{name:cu.$type,properties:{not:{name:cu.not,defaultValue:!1,optional:!0},operator:{name:cu.operator},participant:{name:cu.participant},value:{name:cu.value,referenceType:ss.$type}},superTypes:[tu.$type,ru.$type]},WhereRelationParticipantMetadata:{name:lu.$type,properties:{key:{name:lu.key},not:{name:lu.not,defaultValue:!1,optional:!0},operator:{name:lu.operator,optional:!0},participant:{name:lu.participant},value:{name:lu.value,optional:!0}},superTypes:[nu.$type,ru.$type]},WhereRelationParticipantTag:{name:uu.$type,properties:{not:{name:uu.not,defaultValue:!1,optional:!0},operator:{name:uu.operator},participant:{name:uu.participant},value:{name:uu.value}},superTypes:[ru.$type,fu.$type]},WhereRelationTag:{name:du.$type,properties:{not:{name:du.not,defaultValue:!1,optional:!0},operator:{name:du.operator},value:{name:du.value}},superTypes:[ru.$type,fu.$type]},WhereTagEqual:{name:fu.$type,properties:{},superTypes:[]},WildcardExpression:{name:pu.$type,properties:{isWildcard:{name:pu.isWildcard,defaultValue:!1}},superTypes:[Js.$type]}}};const J=new LikeC4AstReflection;let mu;const LikeC4Grammar=()=>mu??=_n(`{"$type":"Grammar","isDeclared":true,"name":"LikeC4","rules":[{"$type":"ParserRule","entry":true,"name":"LikeC4Grammar","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"imports","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Assignment","feature":"specifications","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"models","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Assignment","feature":"views","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@45"},"arguments":[]}},{"$type":"Assignment","feature":"globals","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@136"},"arguments":[]}},{"$type":"Assignment","feature":"deployments","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@121"},"arguments":[]}},{"$type":"Assignment","feature":"likec4lib","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}}],"cardinality":"*"},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"LikeC4Lib","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"likec4lib"},{"$type":"Keyword","value":"{"},{"$type":"Keyword","value":"icons"},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"icons","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},"cardinality":"+"},{"$type":"Keyword","value":"}"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"LibIcon","definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@178"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementKind","definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Tag","definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationshipKind","definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CustomColor","definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@181"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentNodeKind","definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationRule","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"specification"}},{"$type":"Keyword","value":"{"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"relationships","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Assignment","feature":"colors","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"deploymentNodes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationElementKind","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"element"},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@162"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationElementStringProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"title"},{"$type":"Keyword","value":"description"},{"$type":"Keyword","value":"technology"},{"$type":"Keyword","value":"notation"},{"$type":"Keyword","value":"summary"}]}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationDeploymentNodeKind","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"deploymentNode"},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@162"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationTag","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"tag"},{"$type":"Assignment","feature":"tag","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Group","elements":[{"$type":"Keyword","value":"color"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@143"},"arguments":[]},{"$type":"Assignment","feature":"color","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@175"},"arguments":[]}}]}],"cardinality":"?"},{"$type":"Keyword","value":"}"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationColor","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"color"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"color","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@175"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationRelationshipKind","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"relationship"},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@165"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@146"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SpecificationRelationshipStringProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"title"},{"$type":"Keyword","value":"description"},{"$type":"Keyword","value":"technology"},{"$type":"Keyword","value":"notation"}]}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ImportsFromPoject","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"import"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"imports","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Keyword","value":"}"}]},{"$type":"Assignment","feature":"imports","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Keyword","value":"from"},{"$type":"Assignment","feature":"project","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Imported","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"imported","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@21"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Imported"},"feature":"prev","operator":"="},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"imported","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@21"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Tags","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"values","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@166"},"arguments":[]},"cardinality":"+"},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Tags"},"feature":"prev","operator":"="},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"values","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@166"},"arguments":[]},"cardinality":"*"}],"cardinality":"*"},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Model","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"model"}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ModelElement","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[{"$type":"NamedArgument","value":{"$type":"BooleanLiteral","true":true},"calledByName":false}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Element","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@3"},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@201"},"arguments":[]},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@3"},"deprecatedSyntax":false,"isMulti":false}}]}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}],"cardinality":"?"}],"cardinality":"?"},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[{"$type":"NamedArgument","value":{"$type":"BooleanLiteral","true":false},"calledByName":false}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@162"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@147"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@40"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementStringProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"title"},{"$type":"Keyword","value":"description"},{"$type":"Keyword","value":"technology"},{"$type":"Keyword","value":"summary"}]}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExtendElementOrRelation","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"extend"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ExtendRelation"}},{"$type":"Assignment","feature":"source","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ExtendElement"}},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]}}]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExtendElementBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[{"$type":"NamedArgument","value":{"$type":"BooleanLiteral","true":false},"calledByName":false}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExtendElementProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@40"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExtendRelationBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExtendRelationProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@40"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementRef","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Assignment","feature":"modelElement","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"StrictFqnElementRef","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"el","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@21"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Group","elements":[{"$type":"Action","type":{"$ref":"#/interfaces@1"},"feature":"parent","operator":"="},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Assignment","feature":"el","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@21"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FqnRef","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/types@1"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Group","elements":[{"$type":"Action","type":{"$ref":"#/interfaces@2"},"feature":"parent","operator":"="},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/types@1"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"StrictFqnRef","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/types@1"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Group","elements":[{"$type":"Action","type":{"$ref":"#/interfaces@3"},"feature":"parent","operator":"="},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/types@1"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Relation","parameters":[{"$type":"Parameter","name":"isExplicit"}],"definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","guardCondition":{"$type":"ParameterReference","parameter":{"$ref":"#/rules@34/parameters@0"}},"elements":[{"$type":"Assignment","feature":"source","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}}]},{"$type":"Group","guardCondition":{"$type":"Negation","value":{"$type":"ParameterReference","parameter":{"$ref":"#/rules@34/parameters@0"}}},"elements":[{"$type":"Assignment","feature":"source","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]},"cardinality":"?"}]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"description","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Assignment","feature":"technology","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}],"cardinality":"?"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false},{"$type":"ParserRule","fragment":true,"name":"RelationConnector","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"dotKind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@167"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"-["},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@5"},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"isBidirectional","operator":"?=","terminal":{"$type":"Keyword","value":"]<->"}},{"$type":"Keyword","value":"]->"}]}]},{"$type":"Assignment","feature":"isBidirectional","operator":"?=","terminal":{"$type":"Keyword","value":"<->"}},{"$type":"Keyword","value":"->"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"RelationBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@80"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@40"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationStringProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"title"},{"$type":"Keyword","value":"technology"},{"$type":"Keyword","value":"description"}]}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationStyleProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"style"}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@165"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MetadataProperty","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"metadata"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MetadataBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MetadataAttribute","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@43"},"arguments":[]}},{"$type":"Assignment","feature":"boolValue","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@190"},"arguments":[]}}]},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MetadataValue","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MetadataArray","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"values","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"values","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ModelViews","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"views"}},{"$type":"Assignment","feature":"folder","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"views","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@46"},"arguments":[]}},{"$type":"Assignment","feature":"styles","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@73"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"LikeC4ViewRule","returnType":{"$ref":"#/types@2"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@130"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@47"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementView","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"view"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"extends"},{"$type":"Assignment","feature":"extends","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"of"},{"$type":"Assignment","feature":"viewOf","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}}]}],"cardinality":"?"},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicView","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"dynamic"},{"$type":"Keyword","value":"view"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@53"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRef","definition":{"$type":"Assignment","feature":"view","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/types@2"},"deprecatedSyntax":false,"isMulti":false}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementViewRef","definition":{"$type":"Assignment","feature":"view","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@47"},"deprecatedSyntax":false,"isMulti":false}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewRef","definition":{"$type":"Assignment","feature":"view","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@48"},"deprecatedSyntax":false,"isMulti":false}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementViewBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@56"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@62"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@54"},"arguments":[]},"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"steps","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@108"},"arguments":[]}},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@66"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@55"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@56"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewDisplayVariantProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"variant"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@170"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@57"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@58"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@142"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@59"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewStringProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"title"},{"$type":"Keyword","value":"description"}]}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewOrderProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"order"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRoutingProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"routing"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@60"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EdgeRoutingValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"spline"},{"$type":"Keyword","value":"ortho"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewLayoutDirection","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"TopBottom"},{"$type":"Keyword","value":"LeftRight"},{"$type":"Keyword","value":"BottomTop"},{"$type":"Keyword","value":"RightLeft"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRule","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@67"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@68"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@65"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@73"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@74"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@63"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleRank","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"rank"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@64"},"arguments":[]},"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"targets","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@94"},"arguments":[]}},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RankValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"same"},{"$type":"Keyword","value":"min"},{"$type":"Keyword","value":"max"},{"$type":"Keyword","value":"source"},{"$type":"Keyword","value":"sink"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleGroup","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"group"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@144"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@154"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@145"},"arguments":[]}]},"cardinality":"*"},{"$type":"Assignment","feature":"groupRules","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@67"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@68"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@65"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewRule","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@69"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@70"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@73"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@74"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRulePredicate","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"isInclude","operator":"?=","terminal":{"$type":"Keyword","value":"include"}},{"$type":"Keyword","value":"exclude"}]},{"$type":"Assignment","feature":"exprs","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@81"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleGlobalPredicateRef","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"global"},{"$type":"Keyword","value":"predicate"},{"$type":"Assignment","feature":"predicate","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@137"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewIncludePredicate","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"include"},{"$type":"Assignment","feature":"exprs","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@81"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewGlobalPredicateRef","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"global"},{"$type":"Keyword","value":"predicate"},{"$type":"Assignment","feature":"predicate","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@138"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleStyle","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"style"},{"$type":"Assignment","feature":"targets","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@94"},"arguments":[]}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@161"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@75"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleGlobalStyle","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"global"},{"$type":"Keyword","value":"style"},{"$type":"Assignment","feature":"style","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@139"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleStyleOrGlobalRef","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@71"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@72"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleAutoLayout","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"autoLayout"},{"$type":"Assignment","feature":"direction","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@61"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"rankSep","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]}},{"$type":"Assignment","feature":"nodeSep","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"},{"$type":"Assignment","feature":"routing","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@60"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NotationProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"notation"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NotesProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"notes"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@180"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CustomElementProperties","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@79"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@75"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@76"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@161"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CustomRelationProperties","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@80"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@75"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@76"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@165"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@146"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NavigateToProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"navigateTo"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@49"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationNavigateToProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"navigateTo"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Expressions","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@82"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Expressions"},"feature":"prev","operator":"="},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@82"},"arguments":[]},"cardinality":"?"}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExpressionV2","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@85"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@83"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FqnExprOrWith","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@84"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"FqnExprWith"},"feature":"subject","operator":"="},{"$type":"Keyword","value":"with"},{"$type":"Assignment","feature":"custom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@77"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FqnExprOrWhere","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@87"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"FqnExprWhere"},"feature":"subject","operator":"="},{"$type":"Keyword","value":"where"},{"$type":"Assignment","feature":"where","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@95"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationExprOrWith","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@86"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"RelationExprWith"},"feature":"subject","operator":"="},{"$type":"Keyword","value":"with"},{"$type":"Assignment","feature":"custom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@78"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationExprOrWhere","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@89"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"RelationExprWhere"},"feature":"subject","operator":"="},{"$type":"Keyword","value":"where"},{"$type":"Assignment","feature":"where","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@102"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FqnExpr","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WildcardExpression"}},{"$type":"Assignment","feature":"isWildcard","operator":"?=","terminal":{"$type":"Keyword","value":"*"}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ElementTagExpression"}},{"$type":"Keyword","value":"element.tag"},{"$type":"RuleCall","rule":{"$ref":"#/rules@185"},"arguments":[]},{"$type":"Assignment","feature":"tag","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@166"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ElementKindExpression"}},{"$type":"Keyword","value":"element.kind"},{"$type":"RuleCall","rule":{"$ref":"#/rules@185"},"arguments":[]},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@3"},"deprecatedSyntax":false,"isMulti":false}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@88"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FqnRefExpr","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"ref","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}},{"$type":"Assignment","feature":"selector","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@195"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@196"},"arguments":[]}]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationExpr","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@90"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@92"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"InOutRelationExpr","inferredType":{"$type":"InferredType","name":"RelationExpr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@91"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"InOutRelationExpr"},"feature":"inout","operator":"="},{"$type":"Keyword","value":"->"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IncomingRelationExpr","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"->"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@87"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DirectedRelationExpr","inferredType":{"$type":"InferredType","name":"RelationExpr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@93"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"DirectedRelationExpr"},"feature":"source","operator":"="},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@87"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"OutgoingRelationExpr","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@87"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"isBidirectional","operator":"?=","terminal":{"$type":"Keyword","value":"<->"}},{"$type":"Assignment","feature":"dotKind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@167"},"arguments":[]}},{"$type":"Keyword","value":"->"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-["},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@5"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"]->"}]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FqnExpressions","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@87"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"FqnExpressions"},"feature":"prev","operator":"="},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@87"},"arguments":[]},"cardinality":"?"}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereElementExpression","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@96"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereElementOr","inferredType":{"$type":"InferredType","name":"WhereElementExpression"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@97"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereBinaryExpression"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"or"}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@97"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereElementAnd","inferredType":{"$type":"InferredType","name":"WhereElementExpression"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@98"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereBinaryExpression"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"and"}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@98"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereElementPrimary","inferredType":{"$type":"InferredType","name":"WhereElementExpression"},"definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"RuleCall","rule":{"$ref":"#/rules@95"},"arguments":[]},{"$type":"Keyword","value":")"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@99"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereElementNegation","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"not"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@95"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereElement","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereElementMetadata"}},{"$type":"Keyword","value":"metadata"},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@101"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereElementTag"}},{"$type":"Keyword","value":"tag"},{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@166"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereElementKind"}},{"$type":"Keyword","value":"kind"},{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/types@5"},"deprecatedSyntax":false,"isMulti":false}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MetadataFilterValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@190"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereRelationExpression","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@103"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereRelationOr","inferredType":{"$type":"InferredType","name":"WhereRelationExpression"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@104"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereBinaryExpression"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"or"}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@104"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereRelationAnd","inferredType":{"$type":"InferredType","name":"WhereRelationExpression"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@105"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereBinaryExpression"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"and"}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@105"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereRelationPrimary","inferredType":{"$type":"InferredType","name":"WhereRelationExpression"},"definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"RuleCall","rule":{"$ref":"#/rules@102"},"arguments":[]},{"$type":"Keyword","value":")"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@106"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@107"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereRelationNegation","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"not"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@102"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"WhereRelation","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereRelationParticipantMetadata"}},{"$type":"Assignment","feature":"participant","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@174"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Keyword","value":"metadata"},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@101"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereRelationParticipantKind"}},{"$type":"Assignment","feature":"participant","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@174"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Keyword","value":"kind"},{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/types@5"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereRelationParticipantTag"}},{"$type":"Assignment","feature":"participant","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@174"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Keyword","value":"tag"},{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@166"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereRelationMetadata"}},{"$type":"Keyword","value":"metadata"},{"$type":"RuleCall","rule":{"$ref":"#/rules@198"},"arguments":[]},{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@101"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereRelationKind"}},{"$type":"Keyword","value":"kind"},{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@5"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"WhereRelationTag"}},{"$type":"Keyword","value":"tag"},{"$type":"RuleCall","rule":{"$ref":"#/rules@184"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@166"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"StepStatement","returnType":{"$ref":"#/types@10"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@111"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@117"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@113"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@119"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"StepsBlockFragment","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"steps","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@108"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"SubflowKind","returnType":{"$ref":"#/types@11"},"definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"opt"},{"$type":"Keyword","value":"par"},{"$type":"Keyword","value":"parallel"},{"$type":"Keyword","value":"loop"},{"$type":"Keyword","value":"when"},{"$type":"Keyword","value":"if"},{"$type":"Keyword","value":"else"},{"$type":"Keyword","value":"break"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SubflowStep","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@110"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@109"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"StepsBlock","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@109"},"arguments":[]},"entry":false,"fragment":false,"parameters":[],"$comment":"/**\\n * Represents a block of step statements, i.e. { ... }\\n */"},{"$type":"ParserRule","name":"TryStep","returnType":{"$ref":"#/types@12"},"definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@114"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FinallyBlock","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@115"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","type":{"$ref":"#/interfaces@8"},"feature":"tryCatch","operator":"="},{"$type":"Keyword","value":"finally"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"finally","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@112"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CatchBlock","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@116"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","type":{"$ref":"#/interfaces@7"},"feature":"try","operator":"="},{"$type":"Keyword","value":"catch"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"catch","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@112"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"TryBlock","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"try"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@109"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AltSteps","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"alt"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"branches","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@111"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"StepTarget","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"custom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@78"},"arguments":[]},"cardinality":"?"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"StepSeries","returnType":{"$ref":"#/interfaces@12"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@120"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","type":{"$ref":"#/interfaces@12"},"feature":"source","operator":"="},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"dotKind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@167"},"arguments":[]}},{"$type":"Keyword","value":"->"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-["},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@5"},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"]->"}]}]},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"custom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@78"},"arguments":[]},"cardinality":"?"}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Step","returnType":{"$ref":"#/interfaces@11"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"source","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"isBackward","operator":"?=","terminal":{"$type":"Keyword","value":"<-"}},{"$type":"Assignment","feature":"dotKind","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@167"},"arguments":[]}},{"$type":"Keyword","value":"->"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-["},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@5"},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"]->"}]}]},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"custom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@78"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ModelDeployments","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"deployment"}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@122"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[{"$type":"NamedArgument","value":{"$type":"BooleanLiteral","true":true},"calledByName":false}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@126"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentNode","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@7"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@201"},"arguments":[]},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@7"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Assignment","feature":"summary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@123"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentNodeBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@124"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[{"$type":"NamedArgument","value":{"$type":"BooleanLiteral","true":false},"calledByName":false}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@122"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeployedInstance","definition":{"$type":"Group","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@201"},"arguments":[]}],"cardinality":"?"},{"$type":"Keyword","value":"instanceOf"},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Assignment","feature":"summary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@125"},"arguments":[]},"cardinality":"?"},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeployedInstanceBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[{"$type":"NamedArgument","value":{"$type":"BooleanLiteral","true":false},"calledByName":false}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExtendDeployment","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"extend"},{"$type":"Assignment","feature":"deploymentNode","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@33"},"arguments":[]}},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExtendDeploymentBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@124"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[{"$type":"NamedArgument","value":{"$type":"BooleanLiteral","true":true},"calledByName":false}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@122"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentRelation","parameters":[{"$type":"Parameter","name":"isExplicit"}],"definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","guardCondition":{"$type":"ParameterReference","parameter":{"$ref":"#/rules@128/parameters@0"}},"elements":[{"$type":"Assignment","feature":"source","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}}]},{"$type":"Group","guardCondition":{"$type":"Negation","value":{"$type":"ParameterReference","parameter":{"$ref":"#/rules@128/parameters@0"}}},"elements":[{"$type":"Assignment","feature":"source","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]},"cardinality":"?"}]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"description","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}},{"$type":"Assignment","feature":"technology","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}],"cardinality":"?"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@129"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false},{"$type":"ParserRule","name":"DeploymentRelationBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentView","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"deployment"},{"$type":"Keyword","value":"view"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@131"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentViewBody","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"tags","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@56"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@132"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentViewRule","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@134"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@74"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@133"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ViewRuleAncestors","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"includeAncestors"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@190"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentViewRuleStyle","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"style"},{"$type":"Assignment","feature":"targets","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@94"},"arguments":[]}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@161"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@75"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DeploymentViewRulePredicate","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"isInclude","operator":"?=","terminal":{"$type":"Keyword","value":"include"}},{"$type":"Keyword","value":"exclude"}]},{"$type":"Assignment","feature":"expr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@81"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Globals","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"global"}},{"$type":"Keyword","value":"{"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"predicates","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@137"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@138"},"arguments":[]}]}},{"$type":"Assignment","feature":"styles","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@140"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@141"},"arguments":[]}]}}],"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"GlobalPredicateGroup","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"predicateGroup"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"predicates","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@67"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"GlobalDynamicPredicateGroup","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"dynamicPredicateGroup"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"predicates","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@69"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"GlobalStyleId","definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"GlobalStyle","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"style"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@139"},"arguments":[]}},{"$type":"Assignment","feature":"targets","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@94"},"arguments":[]}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@161"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@75"},"arguments":[]}]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"GlobalStyleGroup","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"styleGroup"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@139"},"arguments":[]}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"styles","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@71"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"LinkProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"link"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@179"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]},"cardinality":"?"},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"ColorRef","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"themeColor","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@172"},"arguments":[]}},{"$type":"Assignment","feature":"customColor","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@6"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@181"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"ColorProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"color"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@143"},"arguments":[]},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"OpacityProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"opacity"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@202"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MultipleProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"multiple"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@190"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IconProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"icon"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"libicon","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@2"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@178"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"none"},{"$type":"RuleCall","rule":{"$ref":"#/rules@179"},"arguments":[]}]}}]},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IconColorProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"iconColor"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@143"},"arguments":[]},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IconSizeProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"iconSize"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@155"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IconPositionValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"left"},{"$type":"Keyword","value":"right"},{"$type":"Keyword","value":"top"},{"$type":"Keyword","value":"bottom"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IconPositionProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"iconPosition"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@150"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ShapeProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"shape"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@173"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"BorderStyleValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@168"},"arguments":[]},{"$type":"Keyword","value":"none"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"BorderProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"border"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@153"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SizeValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"xs"},{"$type":"Keyword","value":"sm"},{"$type":"Keyword","value":"md"},{"$type":"Keyword","value":"lg"},{"$type":"Keyword","value":"xl"},{"$type":"Keyword","value":"xsmall"},{"$type":"Keyword","value":"small"},{"$type":"Keyword","value":"medium"},{"$type":"Keyword","value":"large"},{"$type":"Keyword","value":"xlarge"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ShapeSizeProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"size"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@155"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PaddingSizeProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"padding"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@155"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"TextSizeProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"textSize"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@155"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SizingValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"auto"},{"$type":"Keyword","value":"fixed"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"SizingProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"sizing"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@159"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"StyleProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@144"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@152"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@154"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@145"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@147"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@148"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@146"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@156"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@157"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@158"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@149"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@151"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@160"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementStyleProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"style"}},{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"props","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@161"},"arguments":[]},"cardinality":"*"},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"LineProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Keyword","value":"line"}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@168"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ArrowProperty","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"key","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"head"},{"$type":"Keyword","value":"tail"}]}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@169"},"arguments":[]}},{"$type":"Keyword","value":";","cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationshipStyleProperty","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@144"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@163"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@164"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"TagRef","definition":{"$type":"Assignment","feature":"tag","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@4"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@183"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RelationKindDotRef","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@199"},"arguments":[]},{"$type":"Assignment","feature":"kind","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@5"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"LineOptions","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"solid"},{"$type":"Keyword","value":"dashed"},{"$type":"Keyword","value":"dotted"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ArrowType","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"none"},{"$type":"Keyword","value":"normal"},{"$type":"Keyword","value":"onormal"},{"$type":"Keyword","value":"dot"},{"$type":"Keyword","value":"odot"},{"$type":"Keyword","value":"diamond"},{"$type":"Keyword","value":"odiamond"},{"$type":"Keyword","value":"crow"},{"$type":"Keyword","value":"open"},{"$type":"Keyword","value":"vee"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewDisplayVariantValue","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"diagram"},{"$type":"Keyword","value":"sequence"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DynamicViewFlowKeyword","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"alt"},{"$type":"Keyword","value":"opt"},{"$type":"Keyword","value":"par"},{"$type":"Keyword","value":"parallel"},{"$type":"Keyword","value":"loop"},{"$type":"Keyword","value":"when"},{"$type":"Keyword","value":"if"},{"$type":"Keyword","value":"else"},{"$type":"Keyword","value":"break"},{"$type":"Keyword","value":"try"},{"$type":"Keyword","value":"catch"},{"$type":"Keyword","value":"finally"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ThemeColor","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"primary"},{"$type":"Keyword","value":"secondary"},{"$type":"Keyword","value":"muted"},{"$type":"Keyword","value":"slate"},{"$type":"Keyword","value":"blue"},{"$type":"Keyword","value":"indigo"},{"$type":"Keyword","value":"sky"},{"$type":"Keyword","value":"red"},{"$type":"Keyword","value":"gray"},{"$type":"Keyword","value":"green"},{"$type":"Keyword","value":"amber"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElementShape","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"rectangle"},{"$type":"Keyword","value":"component"},{"$type":"Keyword","value":"person"},{"$type":"Keyword","value":"browser"},{"$type":"Keyword","value":"mobile"},{"$type":"Keyword","value":"cylinder"},{"$type":"Keyword","value":"storage"},{"$type":"Keyword","value":"queue"},{"$type":"Keyword","value":"bucket"},{"$type":"Keyword","value":"document"},{"$type":"Keyword","value":"agent"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Participant","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"source"},{"$type":"Keyword","value":"target"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ColorLiteral","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@176"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@177"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RGBAColor","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"rgba"},{"$type":"Keyword","value":"rgb"}]},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"red","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]}},{"$type":"Keyword","value":",","cardinality":"?"},{"$type":"Assignment","feature":"green","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]}},{"$type":"Keyword","value":",","cardinality":"?"},{"$type":"Assignment","feature":"blue","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]}},{"$type":"Keyword","value":",","cardinality":"?"},{"$type":"Assignment","feature":"alpha","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@205"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@202"},"arguments":[]}]},"cardinality":"?"},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"HexColor","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@197"},"arguments":[]},{"$type":"Assignment","feature":"hex","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@208"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@206"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@207"},"arguments":[]}]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IconId","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@191"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Uri","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@192"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@193"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@194"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MarkdownOrString","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"markdown","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@203"},"arguments":[]}},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@204"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CustomColorId","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@207"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@159"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@173"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@169"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@168"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@174"},"arguments":[]},{"$type":"Keyword","value":"element"},{"$type":"Keyword","value":"model"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Id","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@207"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@173"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@172"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@169"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@168"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@174"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@155"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@170"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@171"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@150"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@159"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@64"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@60"},"arguments":[]},{"$type":"Keyword","value":"element"},{"$type":"Keyword","value":"model"},{"$type":"Keyword","value":"group"},{"$type":"Keyword","value":"node"},{"$type":"Keyword","value":"deployment"},{"$type":"Keyword","value":"instance"},{"$type":"Keyword","value":"relationship"},{"$type":"Keyword","value":"routing"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"HashId","dataType":"string","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@197"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@182"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"EqOperator","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@201"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@200"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"is"}},{"$type":"Assignment","feature":"not","operator":"?=","terminal":{"$type":"Keyword","value":"not"},"cardinality":"?"}]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"IsEqual","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"isEqual","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@201"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@200"},"arguments":[]}]},"entry":false,"parameters":[]},{"$type":"TerminalRule","hidden":true,"name":"BLOCK_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\//","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\/[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/[\\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"RegexToken","regex":"/\\\\b(true|false)\\\\b/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LIB_ICON","definition":{"$type":"RegexToken","regex":"/(aws|azure|bootstrap|gcp|tech):[-\\\\w]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"URI_WITH_SCHEMA","definition":{"$type":"RegexToken","regex":"/\\\\w+:\\\\/{2}\\\\S+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"URI_RELATIVE","definition":{"$type":"RegexToken","regex":"/\\\\.{0,2}\\\\/[^\\\\/]\\\\S+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"URI_ALIAS","definition":{"$type":"RegexToken","regex":"/@[a-zA-Z0-9_-]*\\\\/[^\\\\s]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DotUnderscore","definition":{"$type":"RegexToken","regex":"/\\\\b\\\\._(?![_a-zA-Z])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DotWildcard","definition":{"$type":"RegexToken","regex":"/\\\\b\\\\.\\\\*{1,2}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"Hash","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"#"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"StickyDot","definition":{"$type":"RegexToken","regex":"/\\\\b\\\\./","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"Dot","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"."},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NotEqual","definition":{"$type":"RegexToken","regex":"/\\\\!\\\\={1,2}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"Eq","definition":{"$type":"RegexToken","regex":"/\\\\={1,2}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"Percent","definition":{"$type":"RegexToken","regex":"/\\\\b\\\\d+%/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"MarkdownString","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalGroup","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"'''"},"parenthesized":false},{"$type":"UntilToken","terminal":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"'''"},"parenthesized":false},"parenthesized":false}],"parenthesized":false},{"$type":"TerminalGroup","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"\\"\\"\\""},"parenthesized":false},{"$type":"UntilToken","terminal":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"\\"\\"\\""},"parenthesized":false},"parenthesized":false}],"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"String","definition":{"$type":"RegexToken","regex":"/\\"(?:[^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'(?:[^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"Float","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/\\\\b\\\\d+\\\\.\\\\d+\\\\b/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"Number","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/\\\\b\\\\d+\\\\b/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"IdTerminal","definition":{"$type":"RegexToken","regex":"/([a-zA-Z]|_+[a-zA-Z0-9])[-\\\\w]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"Hex","definition":{"$type":"RegexToken","regex":"/[a-fA-F0-9]{3,}(?![-_g-zG-Z])/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"ElementRef","attributes":[{"$type":"TypeAttribute","name":"modelElement","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"StrictFqnElementRef","attributes":[{"$type":"TypeAttribute","name":"parent","isOptional":true,"type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},{"$type":"TypeAttribute","name":"el","type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@21"}},"isMulti":false},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"FqnRef","attributes":[{"$type":"TypeAttribute","name":"parent","isOptional":true,"type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}}},{"$type":"TypeAttribute","name":"value","type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/types@1"}},"isMulti":false},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"StrictFqnRef","attributes":[{"$type":"TypeAttribute","name":"parent","isOptional":true,"type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@3"}}},{"$type":"TypeAttribute","name":"value","type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/types@1"}},"isMulti":false},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"StepsBlock","attributes":[{"$type":"TypeAttribute","name":"steps","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/types@10"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"SubflowStep","superTypes":[{"$ref":"#/interfaces@4"}],"attributes":[{"$type":"TypeAttribute","name":"kind","type":{"$type":"SimpleType","typeRef":{"$ref":"#/types@11"}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}]},{"$type":"Interface","name":"TryBlock","superTypes":[{"$ref":"#/interfaces@4"}],"attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}]},{"$type":"Interface","name":"CatchBlock","attributes":[{"$type":"TypeAttribute","name":"try","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@6"}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"catch","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"FinallyBlock","attributes":[{"$type":"TypeAttribute","name":"tryCatch","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@6"}},{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@7"}}]},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"finally","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AltSteps","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"branches","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbstractStep","attributes":[{"$type":"TypeAttribute","name":"kind","isOptional":true,"type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@5"}},"isMulti":false}},{"$type":"TypeAttribute","name":"dotKind","isOptional":true,"type":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@167"}}},{"$type":"TypeAttribute","name":"target","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@0"}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"custom","isOptional":true,"type":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@78"}}}],"superTypes":[]},{"$type":"Interface","name":"Step","superTypes":[{"$ref":"#/interfaces@10"}],"attributes":[{"$type":"TypeAttribute","name":"source","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@0"}},"isOptional":false},{"$type":"TypeAttribute","name":"isBackward","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"boolean"}}],"$comment":"/**\\n * A single step in a dynamic view flow\\n * source -> target\\n */"},{"$type":"Interface","name":"StepSeries","superTypes":[{"$ref":"#/interfaces@10"}],"attributes":[{"$type":"TypeAttribute","name":"source","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@11"}},{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@12"}}]},"isOptional":false}],"$comment":"/**\\n * A series of steps in a dynamic view flow\\n * source -> target1 -> target2 -> ...\\n */"}],"types":[{"$type":"Type","name":"ModelReferenceable","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@21"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@17"}}]}},{"$type":"Type","name":"Referenceable","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@122"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@124"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@21"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@17"}}]}},{"$type":"Type","name":"LikeC4View","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@47"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@48"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@130"}}]}},{"$type":"Type","name":"StringProperty","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@24"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@57"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@38"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@42"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@10"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@15"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@75"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@76"}}]}},{"$type":"Type","name":"AnyProperty","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/types@3"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@56"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@54"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@23"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@37"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@165"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@79"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@161"}}]}},{"$type":"Type","name":"DeploymentNodeOrElementKind","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@3"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@7"}}]}},{"$type":"Type","name":"WhereTagEqual","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@100/definition/elements@1/elements@0/inferredType"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@107/definition/elements@5/elements@0/inferredType"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@107/definition/elements@2/elements@0/inferredType"}}]}},{"$type":"Type","name":"WhereKindEqual","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@100/definition/elements@2/elements@0/inferredType"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@107/definition/elements@4/elements@0/inferredType"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@107/definition/elements@1/elements@0/inferredType"}}]}},{"$type":"Type","name":"WhereMetadataEqual","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@100/definition/elements@0/elements@0/inferredType"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@107/definition/elements@3/elements@0/inferredType"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@107/definition/elements@0/elements@0/inferredType"}}]}},{"$type":"Type","name":"WhereExpression","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@95"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@102"}}]}},{"$type":"Type","name":"StepStatement","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/types@13"}},{"$type":"SimpleType","typeRef":{"$ref":"#/types@12"}},{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@9"}},{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}}]}},{"$type":"Type","name":"SubflowKind","type":{"$type":"UnionType","types":[{"$type":"SimpleType","stringType":"opt"},{"$type":"SimpleType","stringType":"par"},{"$type":"SimpleType","stringType":"parallel"},{"$type":"SimpleType","stringType":"loop"},{"$type":"SimpleType","stringType":"when"},{"$type":"SimpleType","stringType":"if"},{"$type":"SimpleType","stringType":"else"},{"$type":"SimpleType","stringType":"break"}]}},{"$type":"Type","name":"TryStep","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@6"}},{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@7"}},{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@8"}}]}},{"$type":"Type","name":"StepOrSeries","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@11"}},{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@12"}}]}},{"$type":"Type","name":"DeploymentElement","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@122"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@124"}}]}},{"$type":"Type","name":"FqnReferenceable","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/types@1"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@21"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@25/definition/elements@1/elements@1/elements@0/inferredType"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@126"}}]}},{"$type":"Type","name":"SizeProperty","type":{"$type":"UnionType","types":[{"$type":"SimpleType","typeRef":{"$ref":"#/rules@156"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@157"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@158"}},{"$type":"SimpleType","typeRef":{"$ref":"#/rules@149"}}]}}],"imports":[]}`),hu={languageId:`likec4`,fileExtensions:[`.c4`,`.likec4`,`.like-c4`],caseInsensitive:!1,mode:`production`},gu={skipValidations:!0,recoveryEnabled:!0,nodeLocationTracking:`full`},_u={AstReflection:()=>new LikeC4AstReflection},vu={Grammar:()=>LikeC4Grammar(),LanguageMetaData:()=>hu,parser:{ParserConfig:()=>gu}},yu=Symbol.for(`idattr`),bu={writeId(e,t){return e[yu]=t,e},readId(e){return e[yu]}},xu={writeId(e,t){return C(t)?e[yu]=void 0:e[yu]=t,e},readId(e){return e[yu]}};function isLikeC4LangiumDocument(e){return e?.textDocument.languageId===hu.languageId}function isLikeC4UserDocument(e){return isLikeC4LangiumDocument(e)&&isNotLikeC4Builtin(e)}function parseMarkdownAsString(e){return e?.markdown||e?.text}function parseAstPercent(e){let t=parseFloat(e);return isNaN(t)?100:be(t,{min:0,max:100})}function parseAstOpacityProperty({value:e}){return parseAstPercent(e)}function parseAstSizeValue({value:e}){switch(e){case`xs`:case`sm`:case`md`:case`lg`:case`xl`:return e;case`xsmall`:return`xs`;case`small`:return`sm`;case`medium`:return`md`;case`large`:return`lg`;case`xlarge`:return`xl`;default:nonexhaustive(e)}}function parseAstIconPositionValue({value:e}){switch(e){case`left`:case`right`:case`top`:case`bottom`:return e;default:nonexhaustive(e)}}function parseAstSizingValue({value:e}){switch(e){case`auto`:case`fixed`:return e;default:nonexhaustive(e)}}function toRelationshipStyle(e,t){let r={};if(!e||e.length===0)return r;for(let i of e)if(t(i))switch(!0){case isColorProperty(i):{let e=toColor(i);j(e)&&(r.color=e);break}case isLineProperty(i):r.line=i.value;break;case isArrowProperty(i):switch(i.key){case`head`:r.head=i.value;break;case`tail`:r.tail=i.value;break;default:nonexhaustive(i)}break;default:nonexhaustive(i)}return r}function toColor(e){return e?.themeColor??e?.customColor?.$refText}function toAutoLayout(e){let t=e.rankSep,r=e.nodeSep,i;switch(e.direction){case`TopBottom`:i=`TB`;break;case`BottomTop`:i=`BT`;break;case`LeftRight`:i=`LR`;break;case`RightLeft`:i=`RL`;break;default:nonexhaustive(e.direction)}return{direction:i,...r&&{nodeSep:r},...t&&{rankSep:t}}}function getViewRulePredicateContainer(e){return Ln(e,e=>isViewRulePredicate(e)||isDeploymentViewRulePredicate(e)||isDynamicViewIncludePredicate(e))}const _isModel=e=>isModel(e)||isElementBody(e)||isExtendElementBody(e)||isElementViewBody(e)||isDynamicViewBody(e)||isElementRef(e),Su=/* @__PURE__ */ e(e=>isModelDeployments(e)||isDeploymentViewBody(e)||isDeploymentNodeBody(e)||isExtendDeploymentBody(e)||isDeployedInstanceBody(e),`_isDeployment`);function isFqnRefInsideGlobals(e){for(;;){if(Su(e)||_isModel(e))return!1;if(isGlobals(e)||isModelViews(e))return!0;if(e.$container)e=e.$container;else return!1}}function isFqnRefInsideModel(e){for(;;){if(Su(e))return!1;if(_isModel(e))return!0;if(e.$container)e=e.$container;else return!1}}function isFqnRefInsideDeployment(e){for(;;){if(_isModel(e))return!1;if(Su(e))return!0;if(e.$container)e=e.$container;else return!1}}function elementRef(e){try{let t=isStrictFqnElementRef(e)?e.el.ref:e.modelElement.value.ref;return t?.$type===`Imported`&&(t=t.imported.ref),t?.$type===`Element`?t:void 0}catch{return}}function readStrictFqn(e){let t=[e.$type===`StrictFqnRef`?e.value.$refText:e.el.$refText],r=e.parent;for(;r;)t.push(r.$type===`StrictFqnRef`?r.value.$refText:r.el.$refText),r=r.parent;return t.length===1?t[0]:t.reverse().join(`.`)}function referenceableParent(e){for(;e.parent;)e=e.parent;return e.value.ref??null}function instanceRef(e){let t;for(;t=e.value?.ref;){if(isDeploymentNode(t))return null;if(isDeployedInstance(t))return t;if(C(e.parent))return null;e=e.parent}return null}function importsRef(e){let t=referenceableParent(e);return t?.$type===`Imported`?t:null}function isReferenceToDeploymentModel(e){let t;for(;t=e.value?.ref;){if(isDeploymentElement(t))return!0;if(C(e.parent))return!1;e=e.parent}return!1}var IndexManager=class extends Tn{services;constructor(e){super(e),this.services=e}async updateContent(e,t){e.likec4ProjectId=this.services.workspace.ProjectsManager.ownerProjectId(e),await super.updateContent(e,t)}projectElements(e,t,r){let i=this.services.workspace.ProjectsManager;return Cn(this.symbolIndex.keys()).filter(t=>r&&!r.has(t)?!1:i.isIncluded(e,t)).flatMap(e=>this.getFileDescriptions(e,t))}},LangiumDocuments=class extends nn{services;constructor(e){super(e),this.services=e}get projectsManager(){return this.services.workspace.ProjectsManager}sortedDocuments=null;get sorted(){return this.sortedDocuments??=this.documentTrie.all().sort(compareByUri)}addDocument(e){isLikeC4UserDocument(e)&&(e.likec4ProjectId=this.projectsManager.ownerProjectId(e)),super.addDocument(e),this.sortedDocuments=null}deleteDocument(e){return this.sortedDocuments=null,super.deleteDocument(e)}deleteDocuments(e){return this.sortedDocuments=null,super.deleteDocuments(e)}getDocument(e){let t=super.getDocument(e);return isLikeC4UserDocument(t)&&(t.likec4ProjectId=this.projectsManager.ownerProjectId(t)),t}get userDocuments(){return Cn(this.sorted).filter(e=>isLikeC4UserDocument(e)&&!this.projectsManager.isExcluded(e))}get all(){return Cn(this.sorted).map(e=>(isLikeC4UserDocument(e)&&(e.likec4ProjectId=this.projectsManager.ownerProjectId(e)),e))}projectDocuments(e){let t=this.services.workspace.ProjectsManager;return Cn(this.sorted).filter(r=>isLikeC4UserDocument(r)&&t.isIncluded(e,r)?(r.likec4ProjectId=e,!0):!1)}groupedByProject(){let e=this.services.workspace.ProjectsManager;return N(this.userDocuments.toArray(),p(t=>(t.likec4ProjectId=e.ownerProjectId(t),t)),le(A(`likec4ProjectId`)))}resetProjectIds(){let e=[];for(let t of this.sorted)delete t.likec4ProjectId,isLikeC4UserDocument(t)&&!this.projectsManager.isExcluded(t)&&e.push(t.uri);return e}};const Y=q.getChild(`projects`);function isLangiumDocument(e){return typeof e==`object`&&`uri`in e&&`textDocument`in e}function normalizeUri(e){return isLangiumDocument(e)?e.uri.toString():typeof e==`string`?nr(e,{acceptRelative:!1,strict:!0})?e:R.file(e).toString():e.toString()}const Cu=/^\/?([A-Za-z]):(?=\/|$)/;function normalizeWindowsDrivePath(e){return e.replace(Cu,(e,t)=>`/${t.toLowerCase()}:`)}function uriPathForMatcher(e){return R.isUri(e)?normalizeWindowsDrivePath(e.path):normalizeWindowsDrivePath(R.parse(e).path)}const wu=compareNaturalHierarchically(`/`,!0),compareUri=(e,t)=>wu(ar(e.path),ar(t.path));function isParentFolderFor(e){return t=>e.startsWith(isString(t)?t:t.folder)}function _overlaps(e,t){let r=isString(e)?e:e.folder,i=isString(t)?t:t.folder;return r===i||r.startsWith(i)||i.startsWith(r)}function sameFolder(e,t){return(isString(e)?e:e.folder)===(isString(t)?t:t.folder)}function hasAmbiguousIncludePathOverlap(e,t){return _overlaps(e,t)&&!sameFolder(e,t)}function overlaps(...e){return me(_overlaps,e)}function _includes(e,t){return t.startsWith(e.folder)||e.includePaths?.some(isParentFolderFor(t))?!_excludes(e,t):!1}function _isInScope(e,t){return t.startsWith(e.folder)||(e.includePaths?.some(isParentFolderFor(t))??!1)}function _excludes(e,t){return e.exclude?.(uriPathForMatcher(t))??!1}function includes(...e){return me(_includes,e)}function isInScope(...e){return me(_isInScope,e)}function excludes(...e){return me(_excludes,e)}function ProjectFolder(e){return e=normalizeUri(e),rr(e)}const compareProjectByFolder=(e,t)=>compareUri(e.folderUri,t.folderUri);function ensureProjectsOrder(e){return e.length<=1?e:Be(e,compareProjectByFolder)}const Tu={id:`default`,config:{name:`default`,exclude:[`**/node_modules/**`]},exclude:Zr(`**/node_modules/**`,{dot:!0}),includeConfig:{paths:[],maxDepth:3,fileThreshold:30}};function isExcludedByDefault(e){return Tu.exclude(uriPathForMatcher(e))}function parseRegisterOptions(e){if(`configUri`in e){invariant(!_(e.configUri),`configUri is emptyish`);let t=R.isUri(e.configUri)?e.configUri:R.parse(normalizeUri(e.configUri)),r=ProjectFolder(L.dirname(t));return{configUri:t,folder:r,folderUri:R.parse(r)}}invariant(!_(e.folderUri),`folderUri is emptyish`);let t=ProjectFolder(e.folderUri),r=R.parse(t);return{configUri:L.joinPath(r,`likec4.config.json`),folder:t,folderUri:r}}var Eu=class ProjectsManager extends ADisposable{services;static DefaultProjectId=Tu.id;#e=[];#t=void 0;#n=void 0;#r=[];#i=new I.default(e=>{if(e===ProjectsManager.DefaultProjectId){let t=this.getWorkspaceFolder(),r=L.joinPath(t,`likec4.config.json`),i=ProjectFolder(t);return{id:e,config:Tu.config,folder:i,folderUri:R.parse(i),configUri:r,exclude:Tu.exclude,includeConfig:{...Tu.includeConfig}}}return nonNullable(this.#r.find(t=>t.id===e),`Project ${e} not found`)});#a=new I.default(e=>{if(this.isExcludedByWorkspace(e))return!0;let t=this.findOwnerProject(e);return t?excludes(t,e)?!this.#r.some(includes(e)):!1:this.#r.some(isInScope(e))?!this.#r.some(includes(e)):isExcludedByDefault(e)});#o=new I.default(e=>this.findOwnerProject(e)??null);constructor(e){super(),this.services=e,this.onDispose(Wn.create(()=>{this.#e.length=0})),Y.trace`created`}isExcludedByWorkspace(e){return this.#n?(R.isUri(e)&&(e=normalizeUri(e)),this.#n(uriPathForMatcher(e))):!1}setWorkspaceExcludePatterns(e){try{if(!Array.isArray(e)){this.#n=void 0;return}let t=N(e,D(j),p(e=>(e=normalizeWindowsDrivePath(e),!or(e)&&!e.startsWith(`**`)&&(e=tr(`**`,e)),e)));if(!k(t,1)){this.#n=void 0;return}Y.debug`set workspace exclude patterns: ${t}`,this.#n=Zr(t,{dot:!0}),this.clearCaches()}catch(e){Y.warn(`Failed to set workspace exclude patterns`,{error:e}),this.#n=void 0}}get defaultProjectId(){if(this.#t)return this.#t;if(!(this.#r.length>1))return k(this.#r,1)?this.#r[0].id:ProjectsManager.DefaultProjectId}set defaultProjectId(e){e!==this.#t&&(this.#t=void 0,!e||e===ProjectsManager.DefaultProjectId?Y.debug`reset default project ID`:(invariant(this.#r.find(t=>t.id===e),`Project "${e}" not found`),Y.debug`set default project ID to ${e}`,this.#t=e))}get default(){return this.#i.get(this.defaultProjectId??ProjectsManager.DefaultProjectId)}get all(){if(k(this.#r,1)){let e=[...p(this.#r,A(`id`)),Tu.id];if(this.#t){let t=e.findIndex(e=>e===this.#t);t>0&&(e.splice(t,1),e.unshift(this.#t))}return e}return[Tu.id]}getProject(e){let t=typeof e==`string`?e:this.ownerProjectId(e);return this.#i.get(t)}findOverlaped(e){if(this.#r.length===0)return[];let t=overlaps(ProjectFolder(e)),isInsideOrIncludes=e=>t(e)||!!e.includePaths&&!!Le(e.includePaths,t);return this.#r.filter(isInsideOrIncludes)}ensureProjectId(e){return e===ProjectsManager.DefaultProjectId?this.defaultProjectId??ProjectsManager.DefaultProjectId:e?(invariant(this.#r.some(t=>e===t.id),`Project ID ${e} is not registered`),e):nonNullable(this.defaultProjectId,()=>`Specify exact project, known: [${p(this.#r,A(`id`)).join(`, `)}]`)}ensureProject(e){return e=this.ensureProjectId(e),this.getProject(e)}hasMultipleProjects(){return this.#r.length>1}isExcluded(...e){let t=e.length===1?e[0]:e[1];return isLangiumDocument(t)&&isLikeC4Builtin(t)?!0:e.length===1?this.#a.get(normalizeUri(t)):excludes(this.#i.get(e[0]),normalizeUri(t))}isIncluded(e,t){let r=normalizeUri(t);return this.isExcludedByWorkspace(r)?!1:k(this.#r,1)?e===ProjectsManager.DefaultProjectId?!this.#o.get(r)&&!this.#a.get(r):includes(this.#i.get(e),r):!isExcludedByDefault(r)}async registerConfigFile(e,t){if(this.isExcludedByWorkspace(e))throw Error(`Skipping project config, path ${e.fsPath} is excluded by editor settings`);if(isExcludedByDefault(normalizeUri(e)))throw Error(`Failed to register project config, path ${e.fsPath} is excluded by default: ${Tu.config.exclude.map(e=>`"${e}"`).join(`, `)}`);try{let r=await this.services.workspace.FileSystemProvider.loadProjectConfig(e);return await this.registerProject({config:r,configUri:e},t)}catch(t){if(!Qt(t))throw wrapError(t,`Failed to register project config ${e.fsPath}:\n`);return Promise.reject(t)}}async registerProject(e,t){let r=No.validate(e.config),{configUri:i,folder:a,folderUri:s}=parseRegisterOptions(e),c=No.normalizeInclude(r.include),l=this.#r.find(e=>e.folder===a);return l?(l.config.name!==r.name&&(Y.info`project name changed from ${l.config.name} to ${r.name}`,Y.info`remove ${l.id}`,l.id=this.uniqueProjectId(r.name),Y.info`add ${l.id}`),this.warnIfConfigOverride(l,i),l.config=r,l.folder=a,l.folderUri=s,l.configUri=i,l.includeConfig=c):(l={id:this.uniqueProjectId(r.name),config:r,folder:a,configUri:i,folderUri:s,includeConfig:c},this.#r=ensureProjectsOrder([...this.#r,l]),Y.info`add ${l.id}`),safeCall(()=>this.updateIncludesExcludes(l)),this.isInitiatingOrReloading||(this.clearCaches(),this.notifyListeners(),await this.rebuildProject(l.id,t).catch(e=>Qt(e)?Promise.reject(e):(Y.warn(`Failed to rebuild project {projectId} after config change`,{projectId:l.id,error:e}),Promise.resolve()))),l}ownerProjectId(e){return this.#o.get(normalizeUri(e))?.id??this.#t??ProjectsManager.DefaultProjectId}findOwnerProject(e){if(this.#r.length===0)return;let t=isParentFolderFor(e);return this.#r.find(t)??this.#r.find(includes(e))??void 0}relativePath(e){let t=normalizeUri(e),r=this.#o.get(t);return r?L.relative(r.folderUri,R.parse(t)):t}get isInitiatingOrReloading(){return!!this.#s||!this.services.workspace.WorkspaceManager.isReady}#s=null;async reloadProjects(e){return this.#s?(Y.debug`reload projects is already in progress, waiting`,await this.#s.catch(()=>{})):(Y.debug`schedule reload projects`,this.#s=Promise.resolve().then(()=>this._reloadProjects(e)).catch(e=>(Qt(e)||Y.warn(`Failed to reload projects`,{error:e}),Promise.reject(e))).finally(()=>{this.#s=null}),await this.#s)}async _reloadProjects(e){let t=this.services.workspace.WorkspaceManager.workspaceFolders;if(!t||t.length===0){Y.warn(`Failed to reloadProjects, no workspace folders found`);return}Y.debug`start reload projects`;let r=[];for(let e of t){let t=R.parse(e.uri);Y.debug`scan projects in ${t.fsPath}`;try{let e=await this.services.workspace.FileSystemProvider.scanProjectFiles(t);for(let i of e)Y.debug`found config ${L.relative(t,i.uri)}`,r.push(i.uri)}catch(e){Y.warn(`Failed on scanProjectFiles in {folder}`,{folder:t.fsPath,error:e})}}if(r.length===0){if(this.#r.length===0){Y.warning(`No config files found`);return}Y.warning(`no config files found, but {count} projects were registered before`,{count:this.#r.length}),Y.warning(`reset`)}r.sort(compareUri);let i=new Map(this.#r.map(e=>[e.configUri.toString(),e]));this.#r=[],this.#i.clear();for(let e of r)try{await this.registerConfigFile(e)}catch(t){Y.warn(loggable(t));let r=i.get(e.toString());r&&(Y.debug`Update failed, restore project ${r.id}`,await this.registerProject(r).catch(e=>{Y.warn(`fail to restore project ${r.id}, ignoring`,{error:e})}))}this.clearCaches(),this.notifyListeners(),await this.services.workspace.WorkspaceManager.rebuildAll(e)}uniqueProjectId(e){let t=new Set(p(this.#r,A(`id`))),r=e;if(!t.has(r))return r;Y.warn`Project "${e}" already exists, generating unique ID`;let i=1;for(;t.has(r);)r=`${e}-${i++}`;return r}clearCaches(){Y.trace(`clearCaches`),this.#t&&!this.#r.some(e=>e.id===this.#t)&&(this.#t=void 0),this.#i.clear(),this.#o.clear(),this.#a.clear()}async rebuildProject(e,t){let r=this.#r.find(t=>t.id===e);if(!r)return e===ProjectsManager.DefaultProjectId?Y.info`Rebuilding all documents `:Y.warn`Project ${e} not found, rebuilding all`,await this.services.workspace.WorkspaceManager.rebuildAll(t);let i=Y.getChild(r.id),_includes=e=>includes(r,normalizeUri(e)),a=this.services.workspace.LangiumDocuments.userDocuments.filter(_includes).map(e=>e.uri).toArray();a.length===0?i.trace`no documents found for project ${r.id}, skipping rebuild`:(i.info`rebuild project documents: ${a.length}`,this.clearCaches(),await this.services.workspace.DocumentBuilder.update(a,[],t).catch(e=>{i.warn(`Failed to rebuild project`,{error:e})}))}getAllIncludePaths(){let e=[];for(let t of this.#r)if(t.includePaths)for(let r of t.includePaths)e.push({projectId:t.id,includePath:r.uri,includeConfig:t.includeConfig});return e}onProjectsUpdate(e){return this.#e.push(e),Wn.create(()=>{let t=this.#e.indexOf(e);t>=0&&this.#e.splice(t,1)})}getWorkspaceFolder(){try{return this.services.workspace.WorkspaceManager.workspaceUri}catch(e){return Y.warn(`Failed to get workspace URI, using default folder`,{error:e}),R.file(`/`)}}notifyListeners(){let e=[...this.#e];for(let t of e)try{t()}catch(e){Y.warn(loggable(e))}}updateIncludesExcludes(e){let t=e.config;delete e.includePaths,delete e.exclude;let r=e.includeConfig.paths;k(r,1)&&(e.includePaths=p(r,t=>{let r=L.resolvePath(e.folderUri,t);return{uri:r,folder:ProjectFolder(r)}}),Y.debug`project ${e.id} include paths: ${e.includePaths.map(e=>e.uri.fsPath).join(`, `)}`);let i=t.exclude;if(C(i))e.exclude=Tu.exclude;else if(k(i,1)){let t=[e.folderUri,...p(e.includePaths??[],A(`uri`))].flatMap(e=>p(i,t=>(!Qn(t)&&!t.startsWith(`**`)&&(t=tr(`**`,t)),ir(Xn(uriPathForMatcher(e),t)))));e.exclude=Zr(t,{contains:!0,dot:!0})}if(!e.includePaths)return e;for(let t of e.includePaths)for(let r of this.#r)r.id!==e.id&&(overlaps(t,r)&&Y.warn(`Project "{projectId}" include path "{includePath}" overlaps with project "{otherProjectId}" folder. Files in overlapping areas will only belong to one project.`,{projectId:e.id,includePath:t.folder,otherProjectId:r.id}),r.includePaths?.forEach(i=>{hasAmbiguousIncludePathOverlap(t,i)&&Y.warn(`Project "{projectId}" include path "{includePath}" overlaps with project "{otherProjectId}" include path "{otherIncludePath}". Files in overlapping areas will only belong to one project.`,{projectId:e.id,includePath:t.folder,otherProjectId:r.id,otherIncludePath:i.folder})}));return e}warnIfConfigOverride(e,t){try{let[r,i]=p([e.configUri,t],L.basename);r!==i&&Y.warn`config ${i} overrides ${r} in folder ${e.folder}`}catch{}}},Du=class TimeoutError extends Error{name=`TimeoutError`;constructor(e,t){super(e,t),Error.captureStackTrace?.(this,TimeoutError)}};const getAbortedReason=e=>e.reason??new DOMException(`This operation was aborted.`,`AbortError`);function pTimeout(e,t){let{milliseconds:r,fallback:i,message:a,customTimers:s={setTimeout,clearTimeout},signal:c}=t,l,abortHandler,u=new Promise((t,u)=>{if(typeof r!=`number`||Math.sign(r)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(c?.aborted){u(getAbortedReason(c)),e.then(t,u);return}if(c&&(abortHandler=()=>{u(getAbortedReason(c))},c.addEventListener(`abort`,abortHandler,{once:!0})),e.then(t,u),r===1/0)return;let p=new Du;l=s.setTimeout.call(void 0,()=>{if(i)try{t(i())}catch(e){u(e)}else typeof e.cancel==`function`&&e.cancel(),a===!1?t():a instanceof Error?u(a):(p.message=a??`Promise timed out after ${r} milliseconds`,u(p))},r)}).finally(()=>{u.clear(),abortHandler&&c&&c.removeEventListener(`abort`,abortHandler)});return u.clear=()=>{s.clearTimeout.call(void 0,l),l=void 0},u}var LikeC4WorkspaceManager=class extends En{services;fileSystemProvider;#e=q.getChild(`workspace`);#t=!1;#n=[];initialBuildOptions={eagerLinking:!0,validation:!0};constructor(e){super(e),this.services=e,this.fileSystemProvider=e.workspace.FileSystemProvider}get documentFactory(){return this.services.workspace.LangiumDocumentFactory}get isReady(){return this.#t}async performStartup(e){this.#t&&this.#e.error`workspace already initialized, invalid performStartup call`;try{this.#t=!1,await this.readExcludeConfig(),(!this.folders||this.folders.length===0)&&(this.folders=e);let t=e.map(e=>kr.parse(e.uri)),r=[],i=[];for(let e of t){this.#e.debug`scanning folder ${e.fsPath} for likec4`;let t=!1;try{let i=await this.fileSystemProvider.scanProjectFiles(e);t=i.length>0,r.push(...i)}catch(t){this.#e.warn(`Failed to scan workspace folder {folder} for project config files`,{folder:e.fsPath,error:t})}try{let r=await this.fileSystemProvider.readDirectory(e,{recursive:!0});t||=r.length>0,i.push(...r)}catch(t){this.#e.warn(`Failed to read workspace folder {folder} for likec4 files`,{folder:e.fsPath,error:t})}t?this.services.workspace.FileSystemWatcher.watch(e.fsPath):this.#e.trace`no likec4 files found in folder ${e.fsPath}`}let a=this.services.workspace.ProjectsManager,s=0;for(let e of r)try{await a.registerConfigFile(e.uri),s++}catch(t){this.#e.warn(`Failed to register config file {config}`,{config:e.uri.fsPath,error:t})}r.length===s?s>0&&this.#e.info`loaded ${s} projects`:this.#e.warn`loaded ${s} projects out of ${r.length}`,s>0&&i.push(...await this.scanProjectIncludePaths());let c=await this.loadDocuments(i);k(c,1)?this.#e.debug`found ${c.length} likec4 documents`:this.#e.warn(`No likec4 documents found in workspace`),c.push(this.documentFactory.fromString(Ro,kr.parse(Bo)));for(let e of c)this.saveAddDocument(e);return c}finally{this.#t=!0,this._ready.resolve()}}async traverseFolder(e,t){try{let r=await this.fileSystemProvider.readDirectory(e,{recursive:!0});t.push(...N(r,D(e=>e.isFile),p(e=>e.uri)))}catch(t){console.error(`Failure to read directory content of `+e.toString(!0),t)}}async scanProjectIncludePaths(){let e=this.services.workspace.ProjectsManager.getAllIncludePaths();if(!k(e,1))return[];let t=qe(e=>this.services.workspace.ProjectsManager.isExcludedByWorkspace(e.uri)),r=[];for(let{projectId:i,includePath:a,includeConfig:s}of e)try{this.#e.debug`scanning include path ${a.fsPath} for project ${i}`;let e=N(await this.fileSystemProvider.readDirectory(a,{recursive:!0,maxDepth:s.maxDepth}),D(t));r.push(...e),e.length===0?this.#e.trace`no files found in include path ${a.fsPath}`:(this.#e.debug`loaded ${e.length} files from include path ${a.fsPath}`,e.length>s.fileThreshold&&this.#e.warn(`Loaded ${e.length} files from include path ${a.fsPath} (project: ${i}) (threshold: ${s.fileThreshold}).\nLarge include directories may slow workspace initialization. Consider adjusting "include.fileThreshold" or "include.maxDepth" in your project configuration.`))}catch(e){this.#e.warn(`Failed to scan include path ${a.fsPath}`,{error:e})}return r}async loadDocuments(e){let t=N(e,Ce(e=>e.uri.path),Be(compareByUri)),r=[];for(let e of t)try{if(this.langiumDocuments.hasDocument(e.uri)){r.push(this.langiumDocuments.getDocument(e.uri));continue}r.push(await this.documentFactory.fromUri(e.uri))}catch(t){this.#e.warn(`Failed to load document ${e.uri}`,{error:t})}return r}saveAddDocument(e){this.langiumDocuments.hasDocument(e.uri)||this.langiumDocuments.addDocument(e)}workspace(){return this.folders&&k(this.folders,1)?this.folders[0]:null}async rebuildAll(e){let t=this.services.workspace.LangiumDocuments.resetProjectIds();this.#e.info(`invalidate and rebuild all {docs} documents`,{docs:t.length}),this.forceCleanCaches(),await this.documentBuilder.update(t,[],e)}get workspaceUri(){return this.#t?memoizeProp(this,`workspaceUri`,()=>{let e=this.workspace();return invariant(e,`Workspace not initialized`),kr.parse(e.uri)}):(this.#e.warn(`Workspace not initialized, returning empty URI`),kr.parse(`file:///`))}relativePath(e){return this.#t?L.relative(this.workspaceUri,e):(this.#e.warn(`Workspace not initialized, returning empty string`),``)}get workspaceURL(){return this.#t?memoizeProp(this,`workspaceURL`,()=>{let e=this.workspace();return invariant(e,`Workspace not initialized`),new URL(e.uri)}):(this.#e.warn(`Workspace not initialized, returning empty URL`),new URL(`file:///`))}forceCleanCaches(){let e=[...this.#n];for(let t of e)try{t()}catch(e){this.#e.warn(`Error in cache evicter`,{error:e})}this.services.workspace.ProjectsManager.clearCaches(),this.services.workspace.ManualLayouts.clearCaches(),this.services.workspace.Cache.clear()}onForceCleanCache(e){return this.#n.push(e),Wn.create(()=>{let t=this.#n.indexOf(e);t!==-1&&this.#n.splice(t,1)})}async readExcludeConfig(){if(!this.services.lsp.Connection){this.#e.debug`no LSP connection, skipping initial configuration read`;return}let e=this.services.workspace.ConfigurationProvider,wait=e=>pTimeout(e,{milliseconds:1e3,message:!1});try{this.#e.trace`waiting for ConfigurationProvider ready...`,await wait(e.ready),this.#e.trace`ConfigurationProvider ready, reading exclude patterns...`;let t=await wait(e.getConfiguration(`likec4`,`exclude`));t?(this.#e.trace`exclude configuration found ${t}`,this.services.workspace.ProjectsManager.setWorkspaceExcludePatterns(t)):this.#e.trace(`no initial exclude configuration found`)}catch(e){this.#e.warn(`Failed to read initial exclude configuration`,{error:e})}}};function projectIdFrom(e){if(isImported(e)){for(;e.$type===`Imported`&&e.$container;)e=e.$container;invariant(isImportsFromPoject(e))}if(isImportsFromPoject(e))return e.project;let t=yn(e)?$t(e):e;return t.likec4ProjectId?t.likec4ProjectId:(q.warn`Document ${t.uri.fsPath} does not have a project ID assigned, this may lead to unexpected behavior.`,Eu.DefaultProjectId)}function stringHash(...e){return stringHash$1(e.length>1?e.join(`:::`):e[0])}function safeCall(e){try{return e()}catch(e){q.trace(`Safe call failed`,{error:e});return}}function performanceNow(){try{return globalThis.performance.now()}catch{return Date.now()}}function performanceMark(){let e=performanceNow();return{get ms(){return performanceNow()-e},get pretty(){return Yn(performanceNow()-e)}}}const Ou=q.getChild(`manual-layouts`),isManualLayoutFile=e=>e!==`.likec4.snap`&&e.endsWith(`.likec4.snap`);function fileName(e){return`${e}.likec4.snap`}function viewIdFromURI(e){let t=L.basename(e);return isManualLayoutFile(t)?t.slice(0,-12):null}function getManualLayoutsOutDir(e){return L.resolvePath(e.folderUri,e.config.manualLayouts?.outDir??`.likec4`)}const ku={manualLayouts:e=>new DefaultLikeC4ManualLayouts(e)},Au=`file://./`;var DefaultLikeC4ManualLayouts=class extends ADisposable{services;cache;listeners=[];#e=zt(1);constructor(e){super(),this.services=e,this.cache=new Kt,this.onDispose(Wn.create(()=>{this.listeners.length=0,this.cache.clear()})),onNextTick(()=>{this.onDispose(e.workspace.ProjectsManager.onProjectsUpdate(()=>{this.clearCaches()}))})}async handleFileSystemUpdate(e){let t=e.update??e.delete,r=viewIdFromURI(t)??void 0,i=this.services.workspace.ProjectsManager.ownerProjectId(t);if(this.cache.delete(i),`delete`in e)this.triggerUpdate(exact({removed:t,projectId:i,viewId:r}));else{if(!r){let e=this.services.workspace.ProjectsManager.getProject(i),a=await this.readSnapshot(t,e);a?r=a.id:(Ou.error(`Snapshot ${t.fsPath} does not exist or is invalid`),r=`index`)}this.triggerUpdate({updated:t,projectId:i,viewId:r})}}onManualLayoutUpdate(e){return this.listeners.push(e),{dispose:()=>{let t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}}}async readManualLayouts(e){let t=Ou.getChild(e.id),r=this.services.workspace.FileSystemProvider,i=getManualLayoutsOutDir(e),a=[],s=stringHash$1(L.relative(e.folderUri,i));try{let c=await r.scanDirectory(i,isManualLayoutFile);if(c.length===0)return null;c.sort(compareByUri);for(let i of c){let c=this.services.workspace.WorkspaceManager.relativePath(i.uri);try{t.trace`read snapshot ${c}`;let l=await r.readFile(i.uri),u=Ua.default.parse(l);s=stringHash$1(s+c+l);let p=this.resolveIconPathsAfterRead(u,e.folderUri);a.push({...p,_layout:`manual`})}catch(e){t.warn(`Failed to read view snapshot {relativePath}`,{relativePath:c,err:e})}}a.length&&t.trace`loaded ${a.length} manual layouts, hash: ${s}`}catch(r){t.warn(`Failed to read manual layouts for ${e.folderUri.fsPath}`,{err:r})}if(a.length===0)return null;let c=Pe(a,A(`id`));return{hash:s,views:c}}async readSnapshot(e,t){let r=this.services.workspace.FileSystemProvider;try{let i=await r.readFile(e),a=Ua.default.parse(i);if(!t){let r=this.services.workspace.ProjectsManager.ownerProjectId(e);t=this.services.workspace.ProjectsManager.getProject(r)}return{...this.resolveIconPathsAfterRead(a,t.folderUri),_layout:`manual`}}catch(t){return Ou.warn(`Failed to read view snapshot ${e.fsPath}`,{err:t}),null}}async read(e){return await this.#e(async()=>{let t=this.cache.get(e.id);if(t!==void 0)return Ou.trace`cache hit project ${e.id}`,t;let r=await this.readManualLayouts(e);return this.cache.set(e.id,r),r})}async write(e,t){let r=Ou.getChild(e.id),i=getManualLayoutsOutDir(e),a=L.joinPath(i,fileName(t.id)),s=this.services.workspace.WorkspaceManager.relativePath(a);if(`manualLayout`in t){let{manualLayout:e,...r}=t;t=r}let c=Ua.default.stringify(this.normalizeIconPathsForWrite(t,e.folderUri),{space:2,quote:`'`}),l={uri:a.toString(),range:Br.create(zr.create(0,0),zr.create(c.split(`
|
|
77
|
+
`).length-1,1))};r.debug`write snapshot of ${t.id} to ${s}`;let u=this.services.workspace.FileSystemProvider;try{await u.writeFile(a,c+`
|
|
78
|
+
`),this.cache.delete(e.id),this.triggerUpdate({updated:a,projectId:e.id,viewId:t.id})}catch(e){r.warn(`Failed to write snapshot {viewId} to {workspaceRelativePath}`,{viewId:t.id,workspaceRelativePath:s,err:e})}return l}async remove(e,t){let r=Ou.getChild(e.id),i=getManualLayoutsOutDir(e),a=L.joinPath(i,fileName(t)),s=this.services.workspace.WorkspaceManager.relativePath(a);r.debug`delete snapshot of ${t} in project ${e.id}. File: ${a.fsPath}`;let c={uri:a.toString(),range:Br.create(0,0,0,0)};try{if(!await this.services.workspace.FileSystemProvider.deleteFile(a))return r.warn`Snapshot ${t} did not exist at ${a.fsPath}`,null;this.cache.delete(e.id),this.triggerUpdate({removed:a,projectId:e.id,viewId:t})}catch(e){r.warn(`Failed to delete snapshot {viewId} from {workspaceRelativePath}`,{viewId:t,workspaceRelativePath:s,err:e})}return c}clearCaches(){Ou.trace`clear caches`,this.cache.clear()}triggerUpdate(e){let t=[...this.listeners];for(let r of t)safeCall(()=>r(e))}normalizeIconPathsForWrite(e,t){let r=e.nodes.map(e=>{if(!e.icon||typeof e.icon!=`string`)return e;if(e.icon.startsWith(`file://`)){let r=R.parse(e.icon),i=L.relative(t,r);return i.startsWith(`..`)?e:{...e,icon:`${Au}${i}`}}return e});return{...e,nodes:r}}resolveIconPathsAfterRead(e,t){let r=e.nodes.map(e=>{if(!e.icon||typeof e.icon!=`string`)return e;if(e.icon.startsWith(Au)){let r=e.icon.substring(9),i=L.joinPath(t,r);return{...e,icon:i.toString()}}return e});return{...e,nodes:r}}};function hasLikeC4Ext(e){return hu.fileExtensions.some(t=>e!==t&&e.endsWith(t))}const ju=[`node_modules`,`.git`,`.svn`,`.yarn`,`.pnpm`];function isNodeModulesOrRepo(e){return ju.includes(e)}function insideNodeModulesOrRepo(e){for(let t of ju)if(e.includes(t))return!0;return!1}const Mu=q.getChild(`chokidar`),Nu={fileSystemWatcher:e=>new ChokidarFileSystemWatcher(e)},isAnyLikeC4File=e=>{let t=dr(e);return hasLikeC4Ext(t)||isLikeC4Config(t)||isManualLayoutFile(t)};var ChokidarFileSystemWatcher=class{services;watcher;queue=new Bt({concurrency:1,timeout:5e3});constructor(e){this.services=e,Mu.trace`ChokidarFileSystemWatcher created`}watch(e){this.watcher?(Mu.debug`add watching folder: ${e}`,this.watcher.add(e)):this.watcher=this.createWatcher(e)}async dispose(){if(this.watcher){let e=this.watcher;this.watcher=void 0;try{await e.close()}catch{}}}createWatcher(e){Mu.debug`create watcher for folder: ${e}`;let t=Qr.watch(e,{ignored:[e=>insideNodeModulesOrRepo(e),(e,t)=>!!t&&t.isFile()&&!isAnyLikeC4File(e),e=>this.services.workspace.ProjectsManager.isExcluded(R.file(e))],followSymlinks:!0,ignoreInitial:!0}),onAddOrChange=(e,t)=>{t?.isDirectory()||this.enqueueFileOp(`addOrChange: `+e,async()=>{await this.onAddOrChange(e)})},onRemove=(e,t)=>{t?.isDirectory()||this.enqueueFileOp(`remove: `+e,async()=>{await this.onRemove(e)})};return t.on(`add`,onAddOrChange).on(`change`,onAddOrChange).on(`unlink`,onRemove).on(`unlinkDir`,e=>{this.enqueueFileOp(`removeDir: `+e,async()=>{await this.onRemoveDir(e)})}),t}enqueueFileOp(e,t){this.queue.add(async()=>{try{await t()}catch(t){Mu.warn(`Failed on {fileop}`,{fileop:e,error:t})}}).catch(t=>{Mu.error(`Error on {fileop}`,{fileop:e,error:t})})}async onAddOrChange(e){let t=this.services.workspace,r=dr(e),i=R.file(e);switch(!0){case isLikeC4Config(r):Mu.debug`project config changed: ${e}`,t.ManualLayouts.clearCaches(),await t.ProjectsManager.registerConfigFile(i);break;case isManualLayoutFile(r):Mu.debug`manual layout file changed: ${e}`,await t.ManualLayouts.handleFileSystemUpdate({update:i});break;case hasLikeC4Ext(r):Mu.debug`file changed: ${e}`,await t.DocumentBuilder.update([i],[]);break;default:Mu.warn`Unknown file change: ${e}`}}async onRemove(e){let t=this.services.workspace,r=dr(e);switch(!0){case isLikeC4Config(r):Mu.debug`project file removed: ${e}`,t.ManualLayouts.clearCaches(),await t.ProjectsManager.reloadProjects();break;case hasLikeC4Ext(r):Mu.debug`file removed: ${e}`,await t.DocumentBuilder.update([],[R.file(e)]);break;case isManualLayoutFile(r):Mu.debug`manual layout file removed: ${e}`,await t.ManualLayouts.handleFileSystemUpdate({delete:R.file(e)});break;default:Mu.warn`Unknown file removal: ${e}`}}async onRemoveDir(e){Mu.debug`directory removed: ${e}`;let t=this.services.workspace;t.ProjectsManager.findOverlaped(e).length>0&&(t.Cache.clear(),t.ManualLayouts.clearCaches(),await t.ProjectsManager.reloadProjects())}},NoopFileSystemProvider=class{scanProjectFiles(){return Promise.resolve([])}scanDirectory(){return Promise.resolve([])}stat(){throw Error(`No file system is available.`)}statSync(){throw Error(`No file system is available.`)}exists(){return Promise.resolve(!1)}existsSync(){return!1}readBinary(e){throw Error(`No file system is available (${e.toString()})`)}readBinarySync(e){throw Error(`No file system is available (${e.toString()})`)}readFileSync(e){if(isLikeC4Builtin(e))return Ro;throw Error(`No file system is available (${e.toString()})`)}readDirectorySync(){return[]}readFile(e){if(isLikeC4Builtin(e))return Promise.resolve(Ro);throw Error(`No file system is available (${e.toString()})`)}readDirectory(){return Promise.resolve([])}loadProjectConfig(){throw Error(`No file system is available.`)}writeFile(){throw Error(`No file system is available.`)}deleteFile(){throw Error(`No file system is available.`)}},NoopFileSystemWatcher=class{constructor(){q.debug`NoopFileSystemWatcher created`}watch(){}dispose(){return Promise.resolve()}},NoopLikeC4ManualLayouts=class{constructor(){q.debug`NoopLikeC4ManualLayouts created`}handleFileSystemUpdate(){return Promise.resolve()}readSnapshot(){return Promise.resolve(null)}read(){return Promise.resolve(null)}write(){return Promise.reject(/* @__PURE__ */ Error(`NoopLikeC4ManualLayouts: write operation is not supported`))}remove(){return Promise.resolve(null)}clearCaches(){}onManualLayoutUpdate(){return{dispose:()=>{}}}dispose(){}};const Pu={fileSystemWatcher:()=>new NoopFileSystemWatcher},Fu={fileSystemProvider:()=>new NoopFileSystemProvider,...Pu},Iu={manualLayouts:()=>new NoopLikeC4ManualLayouts};function isLikeC4ConfigFile(e,t=!1){return!t&&isLikeC4Config(dr(e))}function isLikeC4File(e,t=!1){return!t&&hasLikeC4Ext(dr(e))}const WithFileSystem=(e=!1)=>({fileSystemProvider:e=>new SymLinkTraversingFileSystemProvider(e),...e?Nu:Pu});var SymLinkTraversingFileSystemProvider=class extends vn{services;#e=q.getChild(`filesystem`);constructor(e){super(),this.services=e}isExcluded(e){return this.services.workspace.ProjectsManager.isExcludedByWorkspace(R.file(e))}excludeDirectory=(e,t)=>isNodeModulesOrRepo(e)||this.isExcluded(t);async readFile(e){if(isLikeC4Builtin(e))return Promise.resolve(Ro);try{return await super.readFile(e)}catch(t){return this.#e.warn(`Failed to read file ${e.fsPath}`,{error:t}),``}}async readDirectory(e,t){if(this.isExcluded(e.fsPath))return[];let r=t?.recursive??!0,i=t?.maxDepth??1/0,a=[];try{let t=new Xr().withSymlinks({resolvePaths:!1}).exclude(this.excludeDirectory).withFullPaths().filter(e=>isLikeC4File(e)&&!this.isExcluded(e));r?i!==1/0&&(t=t.withMaxDepth(i)):t=t.withMaxDepth(1);let s=await t.crawl(e.fsPath).withPromise();for(let e of s)a.push({isFile:!0,isDirectory:!1,uri:R.file(e)});return a.sort(compareByUri)}catch(t){return this.#e.warn(`Failed to read directory ${e.fsPath}`,{error:t}),[]}}async scanProjectFiles(e){let t=await this.scanDirectory(e,isLikeC4ConfigFile);return t.length<=1?t:t.sort(compareByUriDeepFirst)}async scanDirectory(e,t){if(this.isExcluded(e.fsPath))return[];let r=[];try{let i=await new Xr().withSymlinks({resolvePaths:!1}).exclude(this.excludeDirectory).withFullPaths().filter((e,r)=>t(e,r)&&!this.isExcluded(e)).crawl(e.fsPath).withPromise();for(let e of i)r.push({isFile:!0,isDirectory:!1,uri:R.file(e)})}catch(t){this.#e.warn(`Failed to scan directory {path}`,{path:e.fsPath,error:t})}return r}async loadProjectConfig(e){return await loadConfig(e)}async writeFile(e,t){let r=fr(e.fsPath),i=Tr(r,{throwIfNoEntry:!1});if(i?.isFile())throw Error(`Cannot create directory ${r} because a file with the same name exists.`);return i||(this.#e.debug(`creating directory {path}`,{path:r}),Cr(r,{recursive:!0})),this.#e.debug(`writing file {path}`,{path:e.fsPath}),await xr(e.fsPath,t,{encoding:`utf-8`})}async deleteFile(e){try{let t=e.fsPath,r=Tr(t,{throwIfNoEntry:!1});return r?.isFile()||r?.isSymbolicLink()?(await br(t),this.#e.debug(`deleted file {path}`,{path:t}),!0):(this.#e.warn(`deleteFile failed: {path} does not exist, or is not a file`,{path:t}),!1)}catch(t){this.#e.warn(`Failed to delete file ${e.fsPath}`,{error:t})}return!1}},LikeC4DocumentationProvider=class extends qn{parser;locator;projects;constructor(e){super(e),this.parser=e.likec4.ModelParser,this.locator=e.likec4.ModelLocator,this.projects=e.shared.workspace.ProjectsManager}getDocumentation(e){if(!(isDeploymentNode(e)||isDeployedInstance(e)||isElement(e)))return super.getDocumentation(e);let t=$t(e);if(t.state<rn.Linked)return super.getDocumentation(e);try{let r=this.parser.forDocument(t);switch(!0){case isDeploymentNode(e):return`**${r.parseDeploymentNode(e).title}**`;case isDeployedInstance(e):{let i=r.parseDeployedInstance(e),[a,s]=H.isImportRef(i.element)?[i.element.project,i.element.model]:[t.likec4ProjectId??this.projects.ownerProjectId(t),i.element.model],c=a?this.locator.getParsedElement(s,a):this.locator.getParsedElement(s),l=[`_instance of_ \`${s}\``];return c&&l.push(`**${c.element.title}**`),l.join(`
|
|
79
|
+
`)}case isElement(e):{let t=r.parseElement(e);return t?[`**${t.title}**`,`<small>kind: \`${t.kind}\`</small>`].join(`
|
|
80
|
+
`):void 0}default:return e}}catch(t){return q.debug(`Failed to get documentation for node {nodeType}`,{error:t,nodeType:e.$type}),super.getDocumentation(e)}}};function areOverlap(e,t){return[e,t]=compareRanges(e,t)>0?[t,e]:[e,t],isInRagne(e.range,t.range.start)}function compareRanges(e,t){let r=e.range.start.line-t.range.start.line;return r===0?e.range.start.character-t.range.start.character:r}function isInRagne(e,t){return!(t.line<e.start.line||t.line>e.end.line||t.line==e.start.line&&t.character<e.start.character||t.line==e.end.line&&t.character>e.end.character)}function isMultiline(e){return!!e&&e.range.start.line!=e.range.end.line}function isSameLine(e,t){if(!e||!t)return!1;let[r,i]=e.range.start.line<t.range.start.line?[e,t]:[t,e];return r.range.end.line===i.range.start.line}const X={newLine:Bn.newLine({allowMore:!0}),oneSpace:Bn.oneSpace(),noSpace:Bn.noSpace(),indent:Bn.indent({allowMore:!0}),noIndent:Bn.noIndent()};var LikeC4Formatter=class extends Fn{options={quoteStyle:`auto`};extendedFormattingCommands=[];constructor(e){super(),e.shared.workspace.ConfigurationProvider.onConfigurationSectionUpdate(e=>this.onConfigurationUpdate(e.configuration.formatting))}doDocumentFormat(e,t,r){this.extendedFormattingCommands=[];let i=super.doDocumentFormat(e,t,r);return this.doExtendedFormatting(i),i}format(e){this.removeIndentFromTopLevelStatements(e),this.indentContentInBraces(e),this.normalizeQuotes(e),this.formatImports(e),this.formatSpecificationRule(e),this.formatGlobals(e),this.formatElementDeclaration(e),this.formatExtendElement(e),this.formatRelation(e),this.formatMetadataProperty(e),this.formatDeploymentNodeDeclaration(e),this.formatDeployedInstance(e),this.formatDeploymentRelation(e),this.formatExtendDeployment(e),this.formatView(e),this.formatViewRuleGroup(e),this.formatViewRuleGlobalStyle(e),this.formatViewRuleGlobalPredicate(e),this.formatIncludeExcludeExpressions(e),this.formatWhereExpression(e),this.formatWhereRelationExpression(e),this.formatWhereElementExpression(e),this.formatRelationExpression(e),this.formatAutolayoutProperty(e),this.formatWithPredicate(e),this.formatSteps(e),this.formatViewRuleStyle(e),this.formatLeafProperty(e),this.formatLinkProperty(e),this.formatNavigateToProperty(e),this.formatTags(e)}formatTags(e){this.on(e,isTags,(e,t)=>{let r=pn(e.$cstNode,`values`).filter(j).slice(1);t.cst(r).prepend(X.oneSpace),t.keywords(`,`).prepend(X.noSpace).append(X.oneSpace)})}formatDeploymentRelation(e){this.on(e,isDeploymentRelation,(e,t)=>{let r=e?.source?.$cstNode?[e?.source?.$cstNode]:[];t.cst(r).append(X.oneSpace),t.keywords(`]->`).prepend(X.noSpace),t.keywords(`-[`).append(X.noSpace),t.nodes(...D([e.target,e.tags],j)).prepend(X.oneSpace),t.properties(`title`,`description`,`technology`).prepend(X.oneSpace)})}formatExtendDeployment(e){this.on(e,isExtendDeployment,(e,t)=>{t.keywords(`extend`).append(X.oneSpace)})}formatRelation(e){this.on(e,e=>isRelation(e)||isDeploymentRelation(e),(e,t)=>{let r=e?.source?.$cstNode?[e?.source?.$cstNode]:[];t.cst(r).append(X.oneSpace),t.keywords(`]->`,`]<->`).prepend(X.noSpace),t.keywords(`-[`).append(X.noSpace),t.nodes(...D([e.target,e.tags],j)).prepend(X.oneSpace),t.properties(`title`,`description`,`technology`).prepend(X.oneSpace)}),this.on(e,isStepOrSeries,(e,t)=>{t.keywords(`->`,`<-`).surround(X.oneSpace),t.property(`dotKind`).prepend(X.oneSpace).append(X.oneSpace),t.keywords(`]->`).prepend(X.noSpace).append(X.oneSpace),t.keywords(`-[`).prepend(X.oneSpace).append(X.noSpace),t.properties(`title`).prepend(X.oneSpace),(isStepSeries(e)&&isMultiline(e.$cstNode)||isStep(e)&&isStepSeries(e.$container)&&isMultiline(e.$container.$cstNode))&&(t.property(`dotKind`).prepend(Bn.indent({allowLess:!1,allowMore:!0,priority:2})),t.keywords(`->`,`-[`).prepend(Bn.indent({allowLess:!1,allowMore:!0,priority:2})),e.custom?.$cstNode&&isMultiline(e.custom.$cstNode)&&t.property(`custom`).prepend({options:{allowLess:!1,allowMore:!0,priority:2},moves:[{tabs:1}]}))})}removeIndentFromTopLevelStatements(e){isLikeC4Grammar(e.$container)&&this.getNodeFormatter(e).keywords(`specification`,`model`,`views`,`likec4lib`,`global`,`deployments`,`import`).prepend(X.noIndent)}indentContentInBraces(e){if(isLikeC4Lib(e)||isSpecificationRule(e)||isSpecificationElementKind(e)||isSpecificationRelationshipKind(e)||isSpecificationDeploymentNodeKind(e)||isGlobals(e)||isGlobalStyle(e)||isGlobalStyleGroup(e)||isGlobalPredicateGroup(e)||isGlobalDynamicPredicateGroup(e)||isGlobalStyleGroup(e)||isModel(e)||isElementBody(e)||isExtendElementBody(e)||isRelationBody(e)||isRelationStyleProperty(e)||isMetadataBody(e)||isModelViews(e)||isElementViewBody(e)||isDynamicViewBody(e)||isDeploymentViewBody(e)||isViewRuleStyle(e)||isViewRuleGroup(e)||isCustomElementProperties(e)||isCustomRelationProperties(e)||isElementStyleProperty(e)||isStepsBlock(e)||isAltSteps(e)||isModelDeployments(e)||isDeploymentNodeBody(e)||isDeploymentRelationBody(e)||isDeployedInstanceBody(e)||isExtendDeploymentBody(e)){let t=this.getNodeFormatter(e),r=t.keywords(`{`);r.prepend(X.noIndent).prepend(X.oneSpace);let i=isMultiline(e.$cstNode),a=t.keywords(`}`),s=t.interior(r,a),c=null;for(let e of s.nodes)i?((!c||!areOverlap(c,e))&&t.cst([e]).prepend(Bn.newLine({allowMore:!0})).prepend(X.indent),c=e):t.cst([e]).surround(X.oneSpace);i?a.prepend(X.noIndent).prepend(Bn.newLine({allowMore:!0})):a.prepend(Bn.oneSpace({allowLess:!0}))}}appendKeywordsWithSpace(e){this.on(e,isElementKind)?.keywords(`element`).append(X.oneSpace)}formatView(e){this.on(e,isElementView,(e,t)=>{(e.extends||e.viewOf||e.name)&&t.keywords(`view`).append(X.oneSpace),t.keywords(`of`,`extends`).surround(X.oneSpace)}),this.on(e,isDynamicView)?.keywords(`dynamic`,`view`).append(X.oneSpace),this.on(e,isDeploymentView)?.keywords(`deployment`,`view`).append(X.oneSpace)}formatLeafProperty(e){if(isElementStringProperty(e)||isRelationStringProperty(e)||isViewStringProperty(e)||isViewOrderProperty(e)||isViewRoutingProperty(e)||isNotationProperty(e)||isNotesProperty(e)||isSpecificationElementStringProperty(e)||isSpecificationRelationshipStringProperty(e)||isColorProperty(e)||isLineProperty(e)||isArrowProperty(e)||isIconProperty(e)||isShapeProperty(e)||isBorderProperty(e)||isOpacityProperty(e)||isMultipleProperty(e)||isIconColorProperty(e)||isIconSizeProperty(e)||isIconPositionProperty(e)||isShapeSizeProperty(e)||isPaddingSizeProperty(e)||isTextSizeProperty(e)||isSizingProperty(e)){let t=this.getNodeFormatter(e),r=t.keyword(`:`),i=t.keywords(`title`,`description`,`order`,`routing`,`technology`,`summary`,`notation`,`notes`,`color`,`line`,`head`,`tail`,`icon`,`iconColor`,`iconSize`,`iconPosition`,`shape`,`border`,`opacity`,`multiple`,`size`,`padding`,`textSize`,`sizing`);r.nodes.length===0?i.append(X.oneSpace):r.prepend(X.noSpace).append(X.oneSpace),t.keyword(`;`).prepend(X.noSpace).append(X.newLine)}}formatLinkProperty(e){this.on(e,isLinkProperty,(e,t)=>{t.keyword(`link`).append(X.oneSpace),t.property(`value`).append(X.oneSpace),t.keyword(`:`).prepend(X.noSpace).append(X.oneSpace),t.keyword(`;`).prepend(X.noSpace).append(X.newLine)})}formatNavigateToProperty(e){this.on(e,isNavigateToProperty)?.property(`key`).append(X.oneSpace)}formatAutolayoutProperty(e){this.on(e,isViewRuleAutoLayout,(e,t)=>{t.keyword(`autoLayout`).append(X.oneSpace),t.property(`rankSep`).prepend(X.oneSpace),t.property(`nodeSep`).prepend(X.oneSpace),t.property(`routing`).prepend(X.oneSpace)})}formatMetadataProperty(e){this.on(e,isMetadataAttribute,(e,t)=>{t.property(`key`).append(X.oneSpace),t.keyword(`:`).prepend(X.noSpace).append(X.oneSpace),t.keyword(`;`).prepend(X.noSpace).append(X.newLine)})}formatElementDeclaration(e){this.on(e,isElement,(e,t)=>{let r=dn(e.$cstNode,`kind`),i=dn(e.$cstNode,`name`);i&&r&&(compareRanges(i,r)>0?t.cst([r]).append(X.oneSpace):(t.cst([i]).append(X.oneSpace),t.cst([r]).prepend(X.oneSpace))),t.properties(`props`).prepend(X.oneSpace)})}formatExtendElement(e){this.on(e,isExtendElementOrRelation,(e,t)=>{t.keywords(`extend`).append(X.oneSpace)})}formatGlobals(e){this.on(e,isGlobalStyle,(e,t)=>{t.keyword(`style`).append(X.oneSpace),t.property(`id`).append(X.oneSpace)}),this.on(e,isGlobalStyleGroup,(e,t)=>{t.keyword(`styleGroup`).append(X.oneSpace)}),this.on(e,isGlobalPredicateGroup,(e,t)=>{t.keyword(`predicateGroup`).append(X.oneSpace)}),this.on(e,isGlobalDynamicPredicateGroup,(e,t)=>{t.keyword(`dynamicPredicateGroup`).append(X.oneSpace)})}formatImports(e){this.on(e,isImportsFromPoject,(e,t)=>{t.keyword(`import`).append(X.oneSpace),t.keywords(`{`,`}`,`from`).surround(X.oneSpace)}),this.on(e,isImported,(e,t)=>{t.keywords(`,`).prepend(X.noSpace).append(X.oneSpace)})}formatSpecificationRule(e){if((isSpecificationElementKind(e)||isSpecificationRelationshipKind(e)||isSpecificationTag(e)||isSpecificationDeploymentNodeKind(e))&&this.getNodeFormatter(e).keywords(`element`,`relationship`,`tag`,`deploymentNode`).append(X.oneSpace),isSpecificationColor(e)){let t=this.getNodeFormatter(e);t.keyword(`color`).append(X.oneSpace),t.property(`name`).append(X.oneSpace)}}formatWithPredicate(e){(isFqnExprWith(e)||isRelationExprWith(e))&&this.getNodeFormatter(e).keyword(`with`).prepend(X.oneSpace)}formatDeploymentNodeDeclaration(e){this.on(e,isDeploymentNode,(e,t)=>{let r=dn(e.$cstNode,`kind`),i=dn(e.$cstNode,`name`);i&&r&&(compareRanges(i,r)>0?t.cst([r]).append(X.oneSpace):(t.cst([i]).append(X.oneSpace),t.cst([r]).prepend(X.oneSpace))),t.properties(`title`).prepend(X.oneSpace)})}formatDeployedInstance(e){this.on(e,isDeployedInstance,(e,t)=>{let r=e.$cstNode?.content.find(e=>e.text===`=`);r&&t.cst([r]).surround(X.oneSpace),t.keyword(`instanceOf`).append(X.oneSpace),t.property(`title`).prepend(X.oneSpace)})}formatViewRuleGlobalStyle(e){this.on(e,isViewRuleGlobalStyle,(e,t)=>{t.keywords(`global`,`style`).append(X.oneSpace)})}formatViewRuleGlobalPredicate(e){let t=this.getNodeFormatter(e);(isViewRuleGlobalPredicateRef(e)||isDynamicViewGlobalPredicateRef(e))&&t.keywords(`global`,`predicate`).append(X.oneSpace)}formatViewRuleGroup(e){this.on(e,isViewRuleGroup,(e,t)=>{t.keyword(`group`).append(X.oneSpace)})}formatViewRuleStyle(e){this.on(e,isViewRuleStyle)?.keyword(`style`).append(X.oneSpace),this.on(e,isDeploymentViewRuleStyle)?.keyword(`style`).append(X.oneSpace),this.on(e,isExpressions)?.keyword(`,`).prepend(X.noSpace).append(X.oneSpace),this.on(e,isFqnExpressions)?.keyword(`,`).prepend(X.noSpace).append(X.oneSpace)}formatWhereExpression(e){(isRelationExprWhere(e)||isFqnExprWhere(e))&&this.getNodeFormatter(e).keyword(`where`).append(X.oneSpace)}formatWhereRelationExpression(e){if(this.on(e,isWhereRelationExpression,(e,t)=>{t.property(`operator`).surround(X.oneSpace)}),this.on(e,isWhereRelationNegation,(e,t)=>{t.keyword(`not`).append(X.oneSpace)}),isWhereRelation(e)){let t=this.getNodeFormatter(e);t.property(`operator`).surround(X.oneSpace),t.property(`not`).surround(X.oneSpace)}}formatWhereElementExpression(e){if(this.on(e,isWhereElementExpression,(e,t)=>{t.property(`operator`).surround(X.oneSpace)}),this.on(e,isWhereElementNegation,(e,t)=>{t.keyword(`not`).append(X.oneSpace)}),isWhereElement(e)){let t=this.getNodeFormatter(e);t.property(`operator`).surround(X.oneSpace),t.property(`not`).surround(X.oneSpace)}}formatIncludeExcludeExpressions(e){if(isDynamicViewRule(e)||isViewRulePredicate(e)||isDeploymentViewRulePredicate(e)){let t=this.getNodeFormatter(e);(!e.$cstNode||!isMultiline(e.$cstNode))&&t.keywords(`include`,`exclude`).append(X.oneSpace)}if(isExpressions(e)){let t=this.getNodeFormatter(e),r=this.findPredicateExpressionRoot(e),i=r?.$cstNode&&isMultiline(r?.$cstNode);i&&t.property(`value`).prepend(X.indent),t.keyword(`,`).prepend(X.noSpace).append(i?X.newLine:X.oneSpace)}}formatRelationExpression(e){this.on(e,isIncomingRelationExpr,(e,t)=>{t.keyword(`->`).append(X.oneSpace)}),this.on(e,isInOutRelationExpr,(e,t)=>{t.keyword(`->`).prepend(X.oneSpace)}),this.on(e,isOutgoingRelationExpr,(e,t)=>{t.keywords(`->`,`<->`).prepend(X.oneSpace),t.keywords(`-[`).prepend(X.oneSpace).append(X.noSpace),t.keywords(`]->`).prepend(X.noSpace).append(X.oneSpace),t.property(`dotKind`).prepend(X.oneSpace).append(X.oneSpace)}),this.on(e,isDirectedRelationExpr,(e,t)=>{t.property(`target`).prepend(X.oneSpace)})}formatSteps(e){this.on(e,isAnyOf(isAltSteps,isTryBlock,isCatchBlock,isFinallyBlock),(e,t)=>{if(t.keywords(`try`,`alt`).append(X.oneSpace),t.property(`title`).surround(X.oneSpace),isCatchBlock(e)){let r=t.keyword(`catch`);isSameLine(e.try.$cstNode,r.nodes[0])?r.prepend(X.oneSpace):r.prepend(Bn.newLine()),r.append(X.oneSpace)}if(isFinallyBlock(e)){let r=t.keyword(`finally`);isSameLine(e.tryCatch.$cstNode,r.nodes[0])?r.prepend(X.oneSpace):r.prepend(Bn.newLine()),r.append(X.oneSpace)}}),this.on(e,isSubflowStep,(e,t)=>{t.property(`kind`).append(X.oneSpace),t.property(`title`).surround(X.oneSpace)})}findPredicateExpressionRoot(e){let t=e.$container;for(;;){if(!t||isDynamicViewRule(t)||isViewRulePredicate(t)||isDeploymentViewRulePredicate(t))return t;t=t.$container}}on(e,t,r){let i=t(e)?this.getNodeFormatter(e):void 0;try{r&&i&&r(e,i)}catch(t){q.warn(`Error formatting node ${e.$type}`,{error:t})}return i}doExtendedFormatting(e){let t=this.quotesNormalizerFactory(this.extendedFormattingCommands);for(let r of this.extendedFormattingCommands)switch(r.type){case`normalizeQuotes`:t(r,e);break;default:nonexhaustive(r.type)}}normalizeQuotes(e){if(this.options.quoteStyle===`ignore`)return;let t=null;if(isMetadataAttribute(e)){let r=e.value;isMetadataArray(r)?t=this.getNodeFormatter(r).nodes(...r.values):r&&(t=this.getNodeFormatter(e).property(`value`))}else t=this.on(e,isStringProperty)?.property(`value`);t??=this.on(e,isElement)?.properties(`props`),t??=this.on(e,isImportsFromPoject)?.properties(`project`),t??=this.on(e,isRelation)?.properties(`title`,`technology`),t??=this.on(e,isViewRuleGroup)?.properties(`title`),t??=this.on(e,isStepStatement)?.properties(`title`),t??=this.on(e,isDeploymentNode)?.properties(`title`),t??=this.on(e,isDeployedInstance)?.properties(`title`),t??=this.on(e,isDeploymentRelation)?.properties(`title`,`technology`),t??=this.on(e,isLinkProperty)?.properties(`title`),t&&this.extendedFormattingCommands.push({type:`normalizeQuotes`,region:t})}quotesNormalizerFactory(e){let t=this.options.quoteStyle==`auto`?this.getAutoQuoteStyle(e):this.options.quoteStyle;return(e,r)=>{let i=t===`single`?`"`:`'`,a=t===`single`?`'`:`"`,s=a.repeat(3),c=a,l=e.region.nodes.map(e=>{let t=e.text.startsWith(`"""`)||e.text.startsWith(`'''`)?s:c;return{range:e.range,newText:t+this.escapeQuotesInternalQuotes(e.text.slice(t.length,-t.length),i,a)+t}});r.push(...l)}}escapeQuotesInternalQuotes(e,t,r){let i=``,a=0;for(;a>=0;){let t=e.indexOf(r,a);if(t<0){i+=e.slice(a);break}i+=e.slice(a,t),a=t+1;let s=!1;for(;t>0&&e[t-1]==`\\`;)s=!s,t--;i+=s?r:`\\${r}`}return i}getAutoQuoteStyle(e){let t=e.flatMap(e=>e.region.nodes);return t.filter(e=>e.text[0]==`"`).length*2>=t.length?`double`:`single`}onConfigurationUpdate(e){this.options={...this.options,...e??{quoteStyle:`auto`}}}};function ancestorsOfNode(e,t){let r=[],i=e.parent;for(;i;){let e=nonNullable(t.get(i),`Parent node ${i} not found`);r.push(e),i=e.parent}return r}function linkNodesWithEdges(e,t){for(let r of t){let t=e.get(r.source),i=e.get(r.target);invariant(t,`Source node ${r.source} not found`),invariant(i,`Target node ${r.target} not found`),t.outEdges.push(r.id),i.inEdges.push(r.id);let a=ancestorsOfNode(t,e),s=ancestorsOfNode(i,e),c=a.length>0&&s.length>0?te(commonHead(ge(a),ge(s))):null;r.parent=c?c.id:null;for(let e of a){if(e===c)break;e.outEdges.push(r.id)}for(let e of s){if(e===c)break;e.inEdges.push(r.id)}}}function elementExprToPredicate(e){if(W.isCustom(e))return elementExprToPredicate(e.custom.expr);if(W.isWhere(e)){let t=elementExprToPredicate(e.where.expr),r=whereOperatorAsPredicate(e.where.condition);return e=>t(e)&&r(e)}if(W.isElementKindExpr(e))return e.isEqual?t=>t.kind===e.elementKind:t=>t.kind!==e.elementKind;if(W.isElementTagExpr(e))return e.isEqual?({tags:t})=>t.includes(e.elementTag):({tags:t})=>!t.includes(e.elementTag);if(W.isWildcard(e))return()=>!0;if(W.isModelRef(e)){let t=H.flatten(e.ref);if(e.selector===`expanded`)return e=>e.id===t||parentFqn(e.id)===t;if(e.selector===`descendants`||e.selector===`children`){let e=t+`.`;return t=>t.id.startsWith(e)}return e=>e.id===t}nonexhaustive(e)}function createRelationExpressionToPredicates(e){return function relationExpressionToPredicates(t){switch(!0){case qi.isCustom(t):return relationExpressionToPredicates(t.customRelation.expr);case qi.isWhere(t):{let e=relationExpressionToPredicates(t.where.expr),r=whereOperatorAsPredicate(t.where.condition);return t=>e(t)&&r({source:{tags:t.source.tags,kind:t.source.kind,metadata:t.source.metadata},target:{tags:t.target.tags,kind:t.target.kind,metadata:t.target.metadata},...t.tags&&{tags:t.tags},...t.kind&&{kind:t.kind},...t.metadata&&{metadata:t.metadata}})}case qi.isDirect(t):{let r=e(t.source),i=e(t.target);return e=>r(e.source)&&i(e.target)||!!t.isBidirectional&&r(e.target)&&i(e.source)}case qi.isInOut(t):{let r=e(t.inout);return e=>r(e.source)||r(e.target)}case qi.isIncoming(t):{let r=e(t.incoming);return e=>r(e.target)}case qi.isOutgoing(t):{let r=e(t.outgoing);return e=>r(e.source)}default:nonexhaustive(t)}}}const Lu=createRelationExpressionToPredicates(elementExprToPredicate);function ensureParentsFirst(e){let t=[],r=[...e],i;for(;i=r.shift();){let e=i.parent;if(e){let i=[];for(;e;){let t=r.findIndex(t=>t.id===e);if(t<0)break;let[a]=r.splice(t,1);if(!a)throw Error(`Invalid state, should not happen`);i.unshift(a),e=a.parent}t.push(...i)}t.push(i)}return t}function updateChildren(e){return e.forEach(t=>{t.children.length>0&&(t.children=e.reduce((e,r)=>(r.parent===t.id&&e.push(r.id),e),[]))}),e}function topologicalSort$1(e){let t=ensureParentsFirst([...e.nodes.values()]),r=[...e.edges];if(t.length<2||r.length===0)return{nodes:t,edges:r};let getNode=t=>nonNullable(e.nodes.get(t)),i=new Rt({multi:!0,allowSelfLoops:!0,type:`directed`}),a=N(r,p(e=>{let t=getNode(e.source),r=getNode(e.target),i=e.parent?getNode(e.parent):null;return{id:e.id,edge:e,parent:i,source:t,target:r}})),[s,c]=pe(a,({source:e,target:t})=>e.children.length===0&&t.children.length===0),l=[],addEdgeToGraph=e=>{i.mergeNode(e.source),i.mergeNode(e.target),l.push(e),(0,Sa.default)(i,e.source,e.target)||i.mergeDirectedEdge(e.source,e.target)};for(let{edge:t,source:r,target:a}of s)if(addEdgeToGraph(t),a.parent&&a.parent!==t.parent&&N(ancestorsOfNode(a,e.nodes),Ie(e=>e.inEdges.includes(t.id)),Ae(e=>{i.mergeNode(e.id),(0,Sa.default)(i,t.source,e.id)||i.mergeDirectedEdge(t.source,e.id),(0,Sa.default)(i,e.id,t.target)||i.mergeDirectedEdge(e.id,t.target)})),r.parent){let e=getNode(r.parent);i.mergeNode(e.id),(0,Sa.default)(i,e.id,r.id)||i.mergeDirectedEdge(e.id,r.id),a.parent&&a.parent!==r.parent&&((0,Sa.default)(i,e.id,a.parent)||i.mergeDirectedEdge(e.id,a.parent))}for(let{edge:e}of c)addEdgeToGraph(e);invariant(l.length===r.length,`Not all edges were added to the graph`);let u=(0,xa.topologicalSort)(i),m=[],h=t.slice();for(let e of u){let t=h.findIndex(t=>t.id===e);invariant(t>=0,`Node "${e}" not found`),m.push(...h.splice(t,1))}return h.length>0&&m.length>0&&(m=m.flatMap(e=>{if(h.length===0)return e;let r=t.slice(0,t.indexOf(e)).filter(e=>h.includes(e));return r.length>0?(h=h.filter(e=>!r.includes(e)),[...r,e]):e})),m.push(...h),{nodes:updateChildren(ensureParentsFirst(m)),edges:l}}e(topologicalSort$1,`topologicalSort`);function calcViewLayoutHash(e){return e.hash=objectHash({id:e.id,__:e._type??`element`,autoLayout:e.autoLayout,...e.routing&&{routing:e.routing},nodes:N(e.nodes,p(e=>({id:e.id,icon:j(e.icon)&&e.icon!==`none`?`Y`:`N`,title:e.title,description:flattenMarkdownOrString(e.description),technology:e.technology??null,shape:e.shape,size:e.style.size??null,iconSize:e.style.iconSize??null,iconColor:e.style.iconColor??null,iconPosition:e.style.iconPosition??null,border:e.style.border??null,opacity:e.style.opacity??null,multiple:e.style.multiple??null,textSize:e.style.textSize??null,padding:e.style.padding??null,...e.style.sizing&&{sizing:e.style.sizing},children:e.children})),m(({id:e,...t})=>[e,t])),edges:N(e.edges,p(e=>({id:e.id,source:e.source,target:e.target,label:e.label,description:flattenMarkdownOrString(e.description),technology:e.technology??null,dir:e.dir,head:e.head,tail:e.tail,line:e.line})),m(e=>[e.id,{...e}])),...`ranks`in e&&e.ranks&&e.ranks.length>0&&{ranks:e.ranks}}),e}function withResolvedRouting(e,t){let{routing:r,...i}=e,a=r??t;return a===`ortho`?{...i,routing:a}:i}var AbstractMemory=class{state;get Ctx(){throw Error(`Should not be called in runtime`)}constructor(e){this.state=e}get elements(){return this.state.elements}get explicits(){return this.state.explicits}get final(){return this.state.final}get connections(){return this.state.connections}isEmpty(){return this.elements.size===0&&this.connections.length===0&&this.explicits.size===0&&this.final.size===0}},AbstractStageExclude=class{memory;expression;excluded={elements:/* @__PURE__ */ new Set,connections:[]};constructor(e,t){this.memory=e,this.expression=t}markedToMoveExplicitToImplicit=!1;_removeElement(e){this.excluded.elements.add(e)}exclude(e){if(!e)return this;if(isIterable(e)){for(let t of e)this._removeElement(t);return this}return this._removeElement(e),this}_removeConnection(e){this.excluded.connections.push(e)}excludeConnections(e,t){if(g(t)&&(invariant(!this.markedToMoveExplicitToImplicit,`Already marked to move explicits`),this.markedToMoveExplicitToImplicit=t),isIterable(e)){for(let t of e)this._removeConnection(t);return this}return this._removeConnection(e),this}isDirty(){return this.excluded.elements.size>0||this.excluded.connections.length>0}isEmpty(){return!this.isDirty()}filterForMoveToImplicits(e){return this.markedToMoveExplicitToImplicit||this.excluded.elements.size>0?e:/* @__PURE__ */ new Set}moveDisconnectedExplicitsToImplicits(e){let t=difference(new Set(this.memory.connections.flatMap(e=>[e.source,e.target])),new Set(e.connections.flatMap(e=>[e.source,e.target])));return t=intersection(t,e.elements),t=N(t,ifilter(t=>e.explicits.has(t)&&!isome(e.final,isDescendantOf(t))),toSet()),t.size>0&&(t=this.filterForMoveToImplicits(t),e.explicits=difference(e.explicits,t),e.final=difference(e.final,t)),e}removeElements(e){return e.elements=difference(e.elements,this.excluded.elements),e.explicits=difference(e.explicits,this.excluded.elements),e.final=difference(e.final,this.excluded.elements),e}removeConnections(e){let t=this.excluded.connections.reduce((e,t)=>{let r=e.get(t.id);return r?e.set(t.id,r.mergeWith(t)):e.set(t.id,t),e},/* @__PURE__ */ new Map),r=/* @__PURE__ */ new Set;e.connections=e.connections.reduce((e,i)=>{let a=t.get(i.id);if(a){r.add(i.source),r.add(i.target);let t=i.difference(a);t.nonEmpty()&&e.push(t)}else e.push(i);return e},[]);for(let t of e.connections)r.delete(t.source),r.delete(t.target),t.boundary&&e.elements.has(t.boundary)&&r.delete(t.boundary);return r.size===0||(r=difference(r,e.explicits),e.final=difference(e.final,r)),e}precommit(e){return e}postcommit(e){return invariant(difference(e.explicits,e.elements).size===0,`Explicits must be subset of elements`),invariant(difference(e.final,e.elements).size===0,`Final elements must be subset of elements`),e}commit(){let e=this.precommit(this.memory.mutableState());if(this.excluded.elements.size>0){let t=e.connections.filter(e=>this.excluded.elements.has(e.source)||this.excluded.elements.has(e.target)).flatMap(t=>[t,...findAscendingConnections(e.connections,t).map(e=>e.intersect(t))]).filter(e=>e.nonEmpty());this.excludeConnections(t)}return this.excluded.connections.length>0&&(e=this.removeConnections(e)),this.excluded.elements.size>0&&(e=this.removeElements(e)),this.memory.update(this.postcommit(e))}},AbstractStageInclude=class{memory;expression;explicits=/* @__PURE__ */ new Set;implicits=/* @__PURE__ */ new Set;_ordered=/* @__PURE__ */ new Set;_connections=[];constructor(e,t){this.memory=e,this.expression=t}get elements(){return this.explicits}get connections(){return this._connections}mergedConnections(){return mergeConnections([...this.memory.connections,...this._connections])}connectWithExisting(e,t){throw Error(`Method not implements, depends on the model`)}_addExplicit(e){this._ordered.add(e),this.explicits.add(e),this.implicits.delete(e)}addExplicit(e){if(!e)return this;if(isIterable(e)){for(let t of e)this._addExplicit(t);return this}return this._addExplicit(e),this}_addImplicit(e){this.explicits.has(e)||(this._ordered.add(e),this.implicits.add(e))}addImplicit(e){if(!e)return this;if(isIterable(e)){for(let t of e)this._addImplicit(t);return this}return this._addImplicit(e),this}_addConnection(e){this._connections.push(e),this._addImplicit(e.source),this._addImplicit(e.target)}addConnections(e){if(isIterable(e)){for(let t of e)this._addConnection(t);return this}return this._addConnection(e),this}isDirty(){return this.explicits.size>0||this.implicits.size>0||this._connections.length>0}isEmpty(){return!this.isDirty()}precommit(e){return e}postcommit(e){return e}processConnections(e){return e}commit(){let e=this.precommit(this.memory.mutableState()),t=/* @__PURE__ */ new Set;if(this._connections.length>0){let[r,i]=pe(this._connections,t=>e.final.has(t.source));e.connections=this.processConnections(mergeConnections([...e.connections,...r,...i])),t=new Set(e.connections.flatMap(e=>[e.source,e.target]))}return e.elements=union(e.elements,this._ordered,this.explicits,t,this.implicits),e.explicits=intersection(e.elements,union(e.explicits,this.explicits)),e.final=intersection(e.elements,union(e.final,this.explicits,t)),this.memory.update(this.postcommit(e))}};function treeFromMemoryState(e,t=`final`){let r=sortParentsFirst(toArray(t===`final`?e.final:e.elements)),i=new Set(e.connections.flatMap(e=>[e.source,e.target])),a=new Set(r),s=new I.default(()=>null),c=r.reduce((e,t,r,i)=>(e.set(t,i.slice(r+1).filter(e=>isAncestor(t,e)).map(e=>(a.delete(e),e)).reduce((e,r)=>(e.some(e=>isAncestor(e,r))||(e.push(r),s.set(r,t)),e),[])),e),new I.default(()=>[]));return{root:a,connected:i,hasInOut:t=>e.connections.some(Fa.isAnyInOut(t.id)),parent:e=>s.get(e),children:e=>c.get(e)}}var StageExclude$1=class extends AbstractStageExclude{static{e(this,`StageExclude`)}};function applyViewRuleStyle(e,t,r){let{shape:i,color:a,icon:s,...c}=e.style,l=!w(c);N(r,D(qe(isGroupElementKind)),D(t),Ae(t=>{t.shape=i??t.shape,t.color=a??t.color,T(s)&&(t.icon=s),T(e.notation)&&(t.notation=e.notation),l&&(t.style={...t.style,...c})}))}function applyViewRuleStyles(e,t){for(let r of e){if(!isViewRuleStyle$1(r)||r.targets.length===0)continue;let e=r.targets.map(elementExprToPredicate);applyViewRuleStyle(r,Ue(e),t)}return t}var Ru=class NodesGroup{id;viewRule;parent;elements;static kind=Wi;constructor(e,t,r=null,i=/* @__PURE__ */ new Set){this.id=e,this.viewRule=t,this.parent=r,this.elements=i}isEmpty(){return this.elements.size===0}update(e){return new NodesGroup(this.id,this.viewRule,this.parent,e)}clone(){return new NodesGroup(this.id,this.viewRule,this.parent,new Set(this.elements))}},StageExclude=class extends AbstractStageExclude{excludeRelations(e){return N(this.memory.connections,D(t=>hasIntersection(t.relations,e)),Ae(t=>{this.excludeConnections(t.update(intersection(t.relations,e)))})),this}precommit(e){if(this.excluded.elements.size>0){let e=new Set([...this.excluded.elements].flatMap(e=>[...e.incoming(`direct`),...e.outgoing(`direct`)]));this.excludeRelations(e)}return e}postcommit(e){let t=difference(this.memory.explicits,e.explicits);for(let r of t)e.explicitFirstSeenIn.delete(r);let r=difference(this.memory.elements,e.elements);for(let t of r)e.lastSeenIn.delete(t);return e}},ActiveGroupStageExclude=class extends StageExclude{memory;expression;constructor(e,t){super(e,t),this.memory=e,this.expression=t}};const{findConnection:zu,findConnectionsBetween:Bu}=Ba;var StageInclude$1=class extends AbstractStageInclude{static{e(this,`StageInclude`)}connectWithExisting(e,t=`both`){let r=this._connections.length,hasChanged=()=>this._connections.length>r;if(!isIterable(e)){if(t===`in`||t===`both`)for(let t of this.memory.elements)this.addConnections(zu(t,e,`directed`));return(t===`out`||t===`both`)&&this.addConnections(Bu(e,this.memory.elements,`directed`)),hasChanged()}let i=[...e];if(t===`in`||t===`both`)for(let e of this.memory.elements)this.addConnections(Bu(e,i,`directed`));if(t===`out`||t===`both`)for(let e of i)this.addConnections(Bu(e,this.memory.elements,`directed`));return hasChanged()}addImplicitWithinScope(e){e&&(!this.memory.scope||isAncestor(this.memory.scope,e))&&this.addImplicit(e)}processConnections(e){return Ji.isRelationExpr(this.expression)||N(e,Ae(({source:e,target:t,boundary:r})=>{N(Re([...toArray(e.ancestors()).reverse(),e],[...toArray(t.ancestors()).reverse(),t]),Ve(([e,t])=>e===t),he(1),Ae(([i,a])=>{i===e&&a===t?this.addImplicitWithinScope(r):(i!==e&&this.addImplicitWithinScope(i),a!==t&&this.addImplicitWithinScope(a))}))})),e}postcommit(e){let t=difference(e.explicits,this.memory.explicits);for(let r of t)e.explicitFirstSeenIn.set(r,`@root`);return e}},ActiveGroupStageInclude=class extends StageInclude$1{memory;expression;constructor(e,t){super(e,t),this.memory=e,this.expression=t}postcommit(e){let t=difference(e.explicits,this.memory.explicits);for(let r of t)e.explicitFirstSeenIn.set(r,this.memory.activeGroupId);for(let t of[...this.explicits,...this.implicits])e.lastSeenIn.set(t,this.memory.activeGroupId);return e}},Vu=class Memory$1 extends AbstractMemory{static{e(this,`Memory`)}state;scope;static empty(e){return new Memory$1({elements:/* @__PURE__ */ new Set,explicits:/* @__PURE__ */ new Set,final:/* @__PURE__ */ new Set,connections:[],groups:[],explicitFirstSeenIn:/* @__PURE__ */ new Map,lastSeenIn:/* @__PURE__ */ new Map},e)}constructor(e,t){super(e),this.state=e,this.scope=t}get groups(){return this.state.groups}get explicitFirstSeenIn(){return this.state.explicitFirstSeenIn}get lastSeenIn(){return this.state.lastSeenIn}stageInclude(e){return new StageInclude$1(this,e)}stageExclude(e){return new StageExclude(this,e)}mutableState(){return{elements:new Set(this.state.elements),explicits:new Set(this.state.explicits),final:new Set(this.state.final),connections:[...this.state.connections],groups:this.state.groups.map(e=>e.clone()),explicitFirstSeenIn:new Map(this.state.explicitFirstSeenIn),lastSeenIn:new Map(this.state.lastSeenIn)}}update(e){return new Memory$1({...this.state,...e},this.scope)}},Hu=class ActiveGroupMemory extends Vu{state;scope;stack;static enter(e,t){let r=`@gr${e.groups.length+1}`;if(e instanceof ActiveGroupMemory){let i=et.default.from([...e.stack].reverse()),a=e.mutableState();return a.groups.push(new Ru(r,t,e.activeGroupId)),i.push(r),new ActiveGroupMemory(a,e.scope,i)}let i=e.mutableState();i.groups.push(new Ru(r,t,null));let a=et.default.of(r);return new ActiveGroupMemory(i,e.scope,a)}constructor(e,t,r){super(e,t),this.state=e,this.scope=t,this.stack=r}get activeGroupId(){return nonNullable(this.stack.peek(),`Stack must not be empty`)}mutableState(){return{...super.mutableState()}}update(e){let t={...this.state,...e};return new ActiveGroupMemory(t,this.scope,this.stack)}stageInclude(e){return new ActiveGroupStageInclude(this,e)}stageExclude(e){return new ActiveGroupStageExclude(this,e)}leave(){let e=this.mutableState();return this.stack.pop(),this.stack.peek()?new ActiveGroupMemory(e,this.scope,this.stack):new Vu(e,this.scope)}};function updateDepthOfAncestors(e,t){let r;for(;e.parent&&(r=t.get(e.parent));){let t=r.depth??1;if(r.depth=Math.max(t,(e.depth??0)+1),r.depth===t)break;e=r}}function elementModelToNodeSource(e){let{id:t,title:r,...i}=We(e.$element,[`summary`,`description`,`metadata`,`style`,`tags`]),{color:a,icon:s,shape:c,...l}=e.style;return exact({id:t,title:r,modelRef:t,shape:c,color:a,icon:s,style:l,description:/* @__PURE__ */ preferSummary(e.$element),tags:[...e.tags],metadata:e.$element.metadata,...i})}function buildComputedNodes({defaults:e},t,r){let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;r?.forEach(({id:t,parent:r,viewRule:s,elements:c})=>{r&&nonNullable(i.get(r),`Parent group node ${r} not found`).children.push(t),i.set(t,{id:t,parent:r,kind:Wi,title:s.title??``,color:s.color??e.group.color??e.color,shape:`rectangle`,children:[],inEdges:[],outEdges:[],level:0,depth:0,tags:[],style:exact({border:s.border??e.group.border,opacity:s.opacity??e.group.opacity,size:s.size,multiple:s.multiple,padding:s.padding,textSize:s.textSize})});for(let e of c)a.set(e.id,t)}),Array.from(t).sort(compareByFqnHierarchically).forEach(({id:e,...t})=>{let r=parentFqn(e),s=0,c;for(;r&&(c=i.get(r),!c);)r=parentFqn(r);let l=t.modelRef??e;if(!c&&a.has(l)){let e=nonNullable(a.get(l));c=i.get(e),r=e}c&&(c.children.length==0&&(c.depth=1,updateDepthOfAncestors(c,i)),c.children.push(e),s=c.level+1);let u=exact({id:e,parent:r,level:s,children:[],inEdges:[],outEdges:[],...t});i.set(e,u)});let s=/* @__PURE__ */ new Map;return r?.forEach(({id:e})=>{s.set(e,nonNullable(i.get(e)))}),t.forEach(({id:e})=>{s.set(e,nonNullable(i.get(e)))}),s}function isBidirectionalRelation(e){return e.isBidirectional}function pickRelationshipProps(e){let{title:t,description:r=null}=e;return{...t&&{title:t,description:r},...Ge(e,[`color`,`technology`,`head`,`line`,`tail`,`kind`,`navigateTo`])}}function mergePropsFromRelationships(e,t){let r=N(e,ve((e,t)=>(j(t.title)&&!e.title.includes(t.title)&&e.title.push(t.title),j(t.description)&&!e.description.some(ce(t.description))&&e.description.push(t.description),j(t.technology)&&!e.technology.includes(t.technology)&&e.technology.push(t.technology),j(t.kind)&&!e.kind.includes(t.kind)&&e.kind.push(t.kind),j(t.color)&&!e.color.includes(t.color)&&e.color.push(t.color),j(t.line)&&!e.line.includes(t.line)&&e.line.push(t.line),j(t.head)&&!e.head.includes(t.head)&&e.head.push(t.head),j(t.tail)&&!e.tail.includes(t.tail)&&e.tail.push(t.tail),j(t.navigateTo)&&!e.navigateTo.includes(t.navigateTo)&&e.navigateTo.push(t.navigateTo),t.tags&&e.tags.push(...t.tags),e),{title:[],description:[],technology:[],kind:[],head:[],tail:[],color:[],tags:[],line:[],navigateTo:[]})),i=F(r.title)??(r.title.length>1?`[...]`:void 0),a=E(r.tags),s=exact({title:i,description:F(r.description),technology:F(r.technology),kind:F(r.kind),head:F(r.head),tail:F(r.tail),color:F(r.color),line:F(r.line),navigateTo:F(r.navigateTo),...isNonEmptyArray(a)&&{tags:a}});if(t){let e=pickRelationshipProps(t);s=He({...s,...e},j)}return C(s.title)&&j(s.technology)&&(s.title=`[${s.technology}]`,delete s.technology),s}const Uu={include:e=>{let{expr:t,where:r}=e,i=e.model.element(t.ref.deployment);if(isDeployedInstanceModel(i))return applyElementPredicate(i,r)&&(e.stage.addExplicit(i),e.stage.connectWithExisting(i)),e.stage;switch(!0){case t.selector===`expanded`:includeDeployedNodeWithExpanded(i,e);break;case t.selector===`children`:includeDeployedNodeChildren(i,e);break;case t.selector===`descendants`:includeDeployedNodeDescendants(i,e);break;default:applyElementPredicate(i,r)&&(e.stage.addExplicit(i),e.stage.connectWithExisting(i))}return e.stage},exclude:({expr:e,stage:t,memory:r,where:i})=>{let a=deploymentExpressionToPredicate(e),s=N([...r.elements],D(a),applyElementPredicate(i));return t.exclude(s),t}};function includeDeployedNodeChildren(e,{stage:t,where:r}){let i=applyElementPredicate([...e.children()],r);i.length!==0&&(t.addImplicit(e),t.addConnections($u(i)),t.connectWithExisting(i),t.addExplicit(i))}function includeDeployedNodeWithExpanded(e,{memory:t,stage:r,where:i}){r.addImplicit(e),r.connectWithExisting(e);let a=applyElementPredicate([...e.children()],i),s=!1;for(let e of a)if(Qu(e,t.elements).length>0){s=!0;break}s&&(r.connectWithExisting(a,`in`),r.addConnections($u(a)),r.connectWithExisting(a,`out`)),r.addImplicit(a),r.connections.length>0&&r.addExplicit(e)}function includeDeployedNodeDescendants(e,{stage:t,where:r}){let dfs=e=>{let i=[];for(let t of e.children())t.isDeploymentNode()&&i.push(...dfs(t)),applyElementPredicate(t,r)&&i.push(t);return t.connectWithExisting(i,`in`),t.addConnections($u(i)),t.addImplicit(i),i},i=dfs(e);if(i.length===0)return;t.connectWithExisting(i,`out`);let a=findConnectedElements(t);N(i,D(e=>a.has(e)),Ae(e=>t.addExplicit(e)))}function findConnectedElements(e){return N(e.mergedConnections(),cleanCrossBoundary,cleanRedundantRelationships,ve((e,t)=>(e.add(t.source),e.add(t.target),e),/* @__PURE__ */ new Set))}const Wu={include:({expr:e,model:t,memory:r,stage:i})=>{let a=whereOperatorAsPredicate(e.where.condition);return nonNullable(predicateToPatch(`include`,{expr:e.where.expr,model:t,stage:i,memory:r,where:a}))},exclude:({expr:e,model:t,memory:r,stage:i})=>{let a=whereOperatorAsPredicate(e.where.condition);return nonNullable(predicateToPatch(`exclude`,{expr:e.where.expr,model:t,stage:i,memory:r,where:a}))}},Gu={include:({expr:e,model:t,memory:r,stage:i,where:a})=>{let s=[...r.elements];if(U.isWildcard(e.outgoing)){for(let e of s)if(!e.allIncoming.isEmpty)for(let t of resolveAscendingSiblings(e)){let r=applyPredicate(Zu(t,e,`directed`),a);i.addConnections(r)}return i}invariant(U.isDeploymentRef(e.outgoing),`Only deployment refs are supported in include`);let c=resolveElements$1(t,e.outgoing);for(let e of c){let t=applyPredicate(Qu(e,s,`directed`),a);i.addConnections(t)}return i},exclude:({expr:e,model:t,memory:r,stage:i,where:a})=>{if(U.isElementTagExpr(e.outgoing)||U.isElementKindExpr(e.outgoing))throw Error(`element kind and tag expressions are not supported in exclude`);if(U.isModelRef(e.outgoing))return excludeModelRelations(resolveAllOutgoingRelations(t,e.outgoing),{stage:i,memory:r},a);if(U.isWildcard(e.outgoing))return i;let s=filterOutgoingConnections(resolveElements$1(t,e.outgoing)),c=N(r.connections,D(s),applyPredicate(a));return i.excludeConnections(c),i}};function filterOutgoingConnections(e){return Ue(e.map(e=>{let satisfies=t=>t===e||isAncestor(e,t);return e=>satisfies(e.source)&&!satisfies(e.target)}))}function resolveAllOutgoingRelations(e,t){let r=resolveModelElements(e,t);return new Set(r.flatMap(e=>[...e.allOutgoing]))}const Ku={include:({expr:e,model:t,memory:r,stage:i,where:a})=>{let s=[...r.elements];if(U.isWildcard(e.incoming)){for(let e of s){if(e.allOutgoing.isEmpty&&e.allIncoming.isEmpty)continue;let t=applyPredicate(findConnectionsFrom$1(e,[...resolveAscendingSiblings(e)]),a);i.addConnections(t)}return i}invariant(U.isDeploymentRef(e.incoming),`Only deployment refs are supported in include`);let c=resolveElements$1(t,e.incoming);for(let e of s){let t=applyPredicate(findConnectionsFrom$1(e,c),a);i.addConnections(t)}return i},exclude:({expr:e,model:t,memory:r,stage:i,where:a})=>{if(U.isElementTagExpr(e.incoming)||U.isElementKindExpr(e.incoming))throw Error(`element kind and tag expressions are not supported in exclude`);if(U.isModelRef(e.incoming))return excludeModelRelations(resolveAllIncomingRelations(t,e.incoming),{stage:i,memory:r},a);if(U.isWildcard(e.incoming))return i;let s=resolveElements$1(t,e.incoming),c=filterIncomingConnections(s),l=filterOutgoingConnections(s),u=N(r.connections,P(e=>c(e)?[e]:l(e)?narrowToBidirectional(e):[]),applyPredicate(a));return i.excludeConnections(u),i}};function filterIncomingConnections(e){return Ue(e.map(e=>{let satisfies=t=>t===e||isAncestor(e,t);return e=>!satisfies(e.source)&&satisfies(e.target)}))}function resolveAllIncomingRelations(e,t){let r=resolveModelElements(e,t);return new Set(r.flatMap(e=>[...e.allIncoming,...[...e.allOutgoing].filter(isBidirectionalRelation)]))}const qu={include:({expr:{source:e,target:t,isBidirectional:r=!1},model:i,stage:a,where:s})=>{if(U.isElementTagExpr(e)||U.isElementKindExpr(e)||U.isElementTagExpr(t)||U.isElementKindExpr(t))throw Error(`element kind and tag expressions are not supported in include`);invariant(!U.isModelRef(e),`Invalid source model ref in direct relation`),invariant(!U.isModelRef(t),`Invalid target model ref in direct relation`);let c=U.isWildcard(e),u=U.isWildcard(t),m=r?`both`:`directed`,h;switch(!0){case c&&u:h=N($u(i.instances()),applyPredicate(s),p(e=>(a.addImplicit(e.boundary),e)));break;case!c&&u:{let t=resolveElements$1(i,e),a=filterOutgoingConnections(t),postFilter=a;if(r){let e=filterIncomingConnections(t);postFilter=t=>a(t)!==e(t)}h=N(t,P(e=>{let t=resolveAscendingSiblings(e);return Qu(e,t,m)}),D(postFilter),applyPredicate(s));break}case c&&!u:{let e=resolveElements$1(i,t),a=filterIncomingConnections(e),postFilter=a;if(r){let t=filterOutgoingConnections(e);postFilter=e=>t(e)!==a(e)}h=N(e,P(e=>[...resolveAscendingSiblings(e)].flatMap(t=>Zu(t,e,m))),D(postFilter),applyPredicate(s));break}default:{invariant(!c,`Inference failed - source should be a deployment ref`),invariant(!u,`Inference failed - target should be a deployment ref`);let r=resolveElements$1(i,e),a=resolveElements$1(i,t),l=filterOutgoingConnections(r),p=filterIncomingConnections(a);h=N(r,P(e=>Qu(e,a,m)),D(e=>l(e)&&p(e)),applyPredicate(s))}}return a.addConnections(h),U.isDeploymentRef(e)&&l(e.selector)&&a.addImplicit(i.element(e.ref.deployment)),U.isDeploymentRef(t)&&l(t.selector)&&a.addImplicit(i.element(t.ref.deployment)),a},exclude:({expr:e,model:t,memory:r,stage:i,where:a})=>{let s=deploymentExpressionToPredicate(e.target),c=deploymentExpressionToPredicate(e.source),l;switch(!0){case U.isWildcard(e.source)&&U.isWildcard(e.target):return i.excludeConnections(applyPredicate(r.connections,a)),i;case U.isModelRef(e.source)&&U.isModelRef(e.target):return l=resolveRelationsBetweenModelElements({source:e.source,target:e.target,expr:e,model:t}),excludeModelRelations(l,{stage:i,memory:r},a);case U.isModelRef(e.source)&&U.isWildcard(e.target):return l=resolveAllOutgoingRelations(t,e.source),excludeModelRelations(l,{stage:i,memory:r},a);case U.isModelRef(e.source):return l=resolveAllOutgoingRelations(t,e.source),excludeModelRelations(l,{stage:i,memory:r},a,e=>s(e.target));case U.isModelRef(e.target):return l=resolveAllIncomingRelations(t,e.target),excludeModelRelations(l,{stage:i,memory:r},a,e=>c(e.source));default:let satisfies=t=>c(t.source)&&s(t.target)||e.isBidirectional===!0&&c(t.target)&&s(t.source),u=N(r.connections,D(satisfies),applyPredicate(a));return u.length===0||i.excludeConnections(u),i}}};function resolveRelationsBetweenModelElements({source:e,target:t,expr:r,model:i}){let a=resolveModelElements(i,e),s=resolveModelElements(i,t),c=r.isBidirectional?`both`:`directed`,l=[];for(let e of a)l.push(...findConnectionsBetween$3(e,s,c));return new Set(l.flatMap(e=>[...e.relations]))}const Ju={include:({expr:e,model:t,memory:r,stage:i,where:a})=>{let s=[...r.elements];if(U.isWildcard(e.inout)){for(let e of s){let t=[...resolveAscendingSiblings(e)],r=matchConnections(Qu(e,t,`both`),a);i.addConnections(r)}return i}invariant(U.isDeploymentRef(e.inout),`Only deployment refs are supported in include`);let c=resolveElements$1(t,e.inout);for(let e of s){let t=matchConnections(Qu(e,c,`both`),a);i.addConnections(t)}return i},exclude:({expr:e,model:t,memory:r,stage:i,where:a})=>{if(U.isElementTagExpr(e.inout)||U.isElementKindExpr(e.inout))throw Error(`element kind and tag expressions are not supported in exclude`);if(U.isModelRef(e.inout)){let s=resolveModelElements(t,e.inout);return s.length===0?i:excludeModelRelations(union(/* @__PURE__ */ new Set,...s.flatMap(e=>[e.allIncoming,e.allOutgoing])),{stage:i,memory:r},a)}if(U.isWildcard(e.inout))return i;let s=resolveElements$1(t,e.inout),c=filterIncomingConnections(s),l=filterOutgoingConnections(s),u=N(r.connections,D(e=>c(e)!==l(e)),applyPredicate(a));return i.excludeConnections(u),i}},Yu={include:({expr:e,model:t,memory:r,stage:i})=>{let a=whereOperatorAsPredicate(e.where.condition);return predicateToPatch(`include`,{expr:e.where.expr,model:t,stage:i,memory:r,where:a})},exclude:({expr:e,model:t,memory:r,stage:i})=>{let a=whereOperatorAsPredicate(e.where.condition);return predicateToPatch(`exclude`,{expr:e.where.expr,model:t,stage:i,memory:r,where:a})}},Xu={include:({model:e,stage:t,where:r})=>{let i=[],a;return a=r?N([...e.elements()],applyElementPredicate(r)):toArray(imap(e.roots(),e=>(e.onlyOneInstance()||i.push(...e.children()),e))),t.addExplicit(a),i.length>1?(t.addConnections($u([...a,...i])),t.connectWithExisting(i)):t.addConnections($u(a)),t.connectWithExisting(a),t},exclude:({stage:e,memory:t,where:r})=>{let i=N([...t.elements],applyElementPredicate(r));return e.exclude(i),e}};function predicateToPatch(e,{expr:t,where:r,...i}){switch(!0){case U.isElementTagExpr(t):case U.isElementKindExpr(t):throw Error(`element kind and tag expressions are not supported in deployment view rules`);case Gi.isCustom(t):return;case U.isCustom(t):return e===`include`&&t.custom.navigateTo!=null?predicateToPatch(e,{...i,expr:t.custom.expr,where:r}):void 0;case U.isModelRef(t):return;case U.isWhere(t):return Wu[e]({...i,expr:t,where:r});case Gi.isWhere(t):return Yu[e]({...i,expr:t,where:r});case U.isDeploymentRef(t):return Uu[e]({...i,expr:t,where:r});case U.isWildcard(t):return Xu[e]({...i,expr:t,where:r});case Gi.isDirect(t):return qu[e]({...i,expr:t,where:r});case Gi.isInOut(t):return Ju[e]({...i,expr:t,where:r});case Gi.isOutgoing(t):return Gu[e]({...i,expr:t,where:r});case Gi.isIncoming(t):return Ku[e]({...i,expr:t,where:r});default:nonexhaustive(t)}}function excludeModelRelations(e,{stage:t,memory:r},i,a=()=>!0){if(e.size===0)return t;let s=N(r.connections,D(e=>a(e)),D(t=>hasIntersection(t.relations.model,e)),p(t=>t.update({deployment:null,model:intersection(t.relations.model,e)})),applyPredicate(i),D(e=>e.nonEmpty()));return s.length===0?t:t.excludeConnections(s)}function matchConnection(e,t){return applyPredicate(e,t).nonEmpty()}function applyPredicate(...e){if(e.length===1)return t=>applyPredicate(t,e[0]);let[t,r]=e;return r===null?t:b(t)?t.map(e=>applyPredicate(e,r)).filter(e=>e.nonEmpty()):t.update({model:new Set([...t.relations.model.values()].filter(e=>r(toFilterableRelation(t)(e)))),deployment:new Set([...t.relations.deployment.values()].filter(e=>r(toFilterableRelation(t)(e))))})}function applyElementPredicate(...e){if(e.length===1){let t=e[0];return t==null?e=>e:e=>e.filter(e=>t(toFilterable(e,e)))}let[t,r]=e;return b(t)?r==null?t:t.filter(e=>r(toFilterable(e,e))):r?.(toFilterable(t,t))??!0}function matchConnections(e,t){return t?N(e,D(e=>matchConnection(e,t))):e}function toFilterable(e,t){if(isElementModel(e)){let r=isDeploymentElementModel(t)&&isDeployedInstanceModel(t)?t:null;return{kind:e.kind,tags:[...e.tags,...r?.tags??[]],metadata:r?.metadata??e.metadata}}if(isNestedElementOfDeployedInstanceModel(e))return Ge(e.element,[`tags`,`kind`,`metadata`]);if(isDeployedInstanceModel(e))return{kind:e.element.kind,tags:[...e.tags,...e.element.tags],metadata:e.metadata};if(isDeploymentNodeModel(e))return Ge(e,[`tags`,`kind`,`metadata`]);nonexhaustive(e)}function toFilterableRelation(e){return t=>({tags:t.tags,kind:t.kind,metadata:t.metadata,source:toFilterable(t.source,e.source),target:toFilterable(t.target,e.target)})}function resolveAscendingSiblings(e){let t=/* @__PURE__ */ new Set;for(let r of e.descendingSiblings())t.add(r);return t}const{findConnection:Zu,findConnectionsBetween:Qu,findConnectionsWithin:$u}=za;function findConnectionsFrom$1(e,t){return Qu(e,t,`both`).flatMap(t=>t.source===e?[t]:narrowToBidirectional(t))}e(findConnectionsFrom$1,`findConnectionsFrom`);function narrowToBidirectional(e){let t=new Set([...e.relations.model].filter(isBidirectionalRelation)),r=new Set([...e.relations.deployment].filter(isBidirectionalRelation));return t.size===0&&r.size===0?[]:[e.update({model:t,deployment:r})]}function resolveElements$1(e,t){let r=e.element(t.ref.deployment);if(r.isDeploymentNode()){if(t.selector===`children`)return[...r.children()];if(t.selector===`expanded`)return[r,...r.children()];if(t.selector===`descendants`)return[...r.descendants()]}return[r]}e(resolveElements$1,`resolveElements`);function resolveModelElements(e,t){let r=e.$model.element(t.ref.model);return t.selector===`children`?[...r.children()]:t.selector===`expanded`?[r,...r.children()]:t.selector===`descendants`?[...r.descendants()]:[r]}function deploymentExpressionToPredicate(e){if(U.isWildcard(e))return()=>!0;if(U.isElementTagExpr(e)||U.isElementKindExpr(e))throw Error(`element kind and tag expressions are not supported in deployment view rules`);if(U.isDeploymentRef(e)){let t=e.ref.deployment;if(e.selector===`expanded`){let e=t+`.`;return r=>r.id===t||r.id.startsWith(e)}if(e.selector===`descendants`){let e=t+`.`;return t=>t.id.startsWith(e)}return e.selector===`children`?e=>parentFqn(e.id)===t:e=>e.id===t}if(U.isModelRef(e)){let t=e.ref.model;if(e.selector===`expanded`){let e=t+`.`;return r=>{let i=r.modelRef??null;return!i||i===t||i.startsWith(e)}}if(e.selector===`descendants`){let e=t+`.`;return t=>{let r=t.modelRef??null;return!r||r.startsWith(e)}}return e.selector===`children`?e=>{let r=e.modelRef??null;return!r||parentFqn(r)===t}:e=>{let r=e.modelRef??null;return!r||r===t}}nonexhaustive(e)}function instanceSummary(e){return/* @__PURE__ */ preferSummary(e.$instance)??/* @__PURE__ */ preferSummary(e.element.$element)}function deploymentNodeToNodeSource(e){let t=e.id,r=e.onlyOneInstance();return exact({id:t,deploymentRef:t,title:e.title,kind:e.kind,technology:e.technology??void 0,links:k(e.links,1)?[...e.links]:void 0,notation:e.$node.notation??void 0,color:e.color,shape:e.shape,modelRef:r?.element.id,icon:e.style.icon,description:/* @__PURE__ */ preferSummary(e.$node)??void 0,tags:[...e.tags],style:We(e.style,[`icon`,`shape`,`color`])})}function instanceToNodeSource(e){let t=e.$instance,r=e.element,{icon:i,color:a,shape:s,...c}=e.style,l=[...r.links,...t.links??[]];return exact({id:e.id,kind:`instance`,title:e.title,description:instanceSummary(e)??void 0,technology:e.technology??void 0,tags:[...e.tags],links:k(l,1)?l:void 0,icon:i,color:a,shape:s,style:c,deploymentRef:t.id,modelRef:r.id,notation:t.notation})}function toNodeSource(e){return e.isInstance()?instanceToNodeSource(e):deploymentNodeToNodeSource(e)}const ed=/* @__PURE__ */ e((e,t,r)=>stringHash$1(`model:${e}:${t}:${r}`),`hashEdgeId`);function mergeBidirectionalEdges(e){let t=/* @__PURE__ */ new Set;for(let r=0;r<e.length;r++){if(t.has(r))continue;let i=e[r];for(let a=r+1;a<e.length;a++){if(t.has(a))continue;let r=e[a];if(i.source===r.target&&i.target===r.source&&i.label===r.label){i.dir=`both`;let e=i.head??r.head;e&&(i.head||=e,i.tail||=e),r.color&&(i.color||=r.color),r.line&&(i.line||=r.line),t.add(a);break}}}return t.size>0?e.filter((e,r)=>!t.has(r)):e}function toComputedEdges$1(e,t){let r=[],i=[];for(let a of e){let e=[...a.relations.model,...a.relations.deployment];invariant(k(e,1),`Edge must have at least one relation`);let s=a.source.$model.$styles.defaults,c=a.source.id,l=a.target.id;if(t&&e.length>1){let[u,p]=N(e,pe(e=>t(e,a)));if(u.length>0){for(let e of u){let{title:t,color:i=s.relationship.color,line:u=s.relationship.line,head:p=s.relationship.arrow,...m}=mergePropsFromRelationships([e.$relationship],e.$relationship);r.push({id:ed(c,l,e.id),parent:a.boundary?.id??null,source:c,target:l,label:t??null,relations:[e.id],color:i,line:u,head:p,...m})}if(p.length>0){let e=F(D(p,e=>e.source.id===c&&e.target.id===l)),{title:t,color:r=s.relationship.color,line:u=s.relationship.line,head:m=s.relationship.arrow,...h}=mergePropsFromRelationships(p.map(e=>e.$relationship),e?.$relationship);i.push({id:a.id,parent:a.boundary?.id??null,source:c,target:l,label:t??null,relations:p.map(e=>e.id),color:r,line:u,head:m,...h})}continue}}let{title:u,color:p=s.relationship.color,line:m=s.relationship.line,head:h=s.relationship.arrow,...g}=mergePropsFromRelationships(e.map(e=>e.$relationship)),_=exact({id:a.id,parent:a.boundary?.id??null,source:c,target:l,label:u??null,relations:e.map(e=>e.id),color:p,line:m,head:h,...g});i.push(_)}return[...r,...mergeBidirectionalEdges(i)]}e(toComputedEdges$1,`toComputedEdges`);function buildNodes$1(e,t){let r=buildComputedNodes(e.$styles,[...t.final].map(toNodeSource));for(let t of r.values()){if(!t.deploymentRef||!t.modelRef||t.children.length>0)continue;let r=e.deployment.element(t.deploymentRef),i=r.isDeploymentNode()&&r.onlyOneInstance();if(!i)continue;t.title===r.name&&(t.title=i.title),t.description??=instanceSummary(i)??null,t.technology??=i.technology,w(t.tags)&&(t.tags=[...i.tags]),(!t.links||w(t.links))&&k(i.links,1)&&(t.links=[...i.links]);let a=e.$styles.defaults;t.shape===a.shape&&t.shape!==i.shape&&(t.shape=i.shape,t.notation=null),t.color===a.color&&t.color!==i.color&&(t.color=i.color,t.notation=null),!t.icon&&i.icon&&(t.icon=i.icon)}return r}e(buildNodes$1,`buildNodes`);function applyDeploymentViewRuleStyles(e,t){for(let r of e){if(!isViewRuleStyle$1(r)||r.targets.length===0)continue;let e=r.targets.map(deploymentExpressionToPredicate);applyViewRuleStyle(r,Ue(e),t)}return t}function applyDeploymentNavigateTo(e,t,r){for(let i of t)for(let t of i.include??[]){if(!U.isCustom(t)||t.custom.navigateTo==null)continue;let{expr:i,navigateTo:a}=t.custom,s=U.unwrap(i),c=U.isWhere(i)?whereOperatorAsPredicate(i.where.condition):null,l;switch(!0){case U.isDeploymentRef(s):l=resolveElements$1(e,s);break;case U.isWildcard(s):l=[...e.elements()];break;default:continue}let u=new Set(applyElementPredicate(l,c).map(e=>e.id));r=r.map(e=>e.deploymentRef&&u.has(e.deploymentRef)?{...e,navigateTo:a,isCustomized:!0}:e)}return r}function findCrossBoundarySameSourceOrTarget(e){let t=new I.default(()=>[]);for(let r of e)for(let e of r.relations.model)t.get(e).push(r);let r=new I.default(()=>/* @__PURE__ */ new Set);for(let[e,i]of t)k(i,2)&&N(i,P(e=>[{group:`$source-${e.source.id}`,conn:e},{group:`$target-${e.target.id}`,conn:e}]),le(A(`group`)),Fe(),D(k(2)),Ae(ue(p(A(`conn`)),sortConnectionsByBoundaryHierarchy(`desc`),Ve((e,t,r)=>t===0||e.boundary===r[t-1].boundary),Ae(t=>{r.get(t).add(e)}))));return r}function findCrossBoundaryConnections(e){e=mergeConnections(e);let t=findCrossBoundarySameSourceOrTarget(e);for(let r of e){let{source:e,target:i}=r,a=r.relations.model;if(e.isDeploymentNode()!==i.isDeploymentNode()){let i=e.isDeploymentNode()?e:r.target;invariant(i.isDeploymentNode());let s=intersection(a,i.internalModelRelationships());for(let e of s)t.get(r).add(e)}else if(e.isDeploymentNode()&&i.isDeploymentNode()){let a=union(intersection(r.relations.model,e.internalModelRelationships()),intersection(r.relations.model,i.internalModelRelationships()));for(let e of a)t.get(r).add(e)}}return N(t.entries(),imap(([e,t])=>e.update({model:t,deployment:null})),toArray())}function cleanCrossBoundary(e){return differenceConnections(e,findCrossBoundaryConnections(e))}function findRedundantConnections$1(e){return N(e,mergeConnections,ve((t,r)=>{let{source:i,target:a,relations:s}=r;if(i.isInstance()&&a.isInstance())return t;let c=Aa.empty();if(i.isDeploymentNode()&&a.isDeploymentNode()){let[e]=Zu(a,i,`directed`);e&&(c=s.intersect(e.relations))}for(let t of e)isNestedConnection(t,r)&&(c=c.union(s.intersect(t.relations)));return c.nonEmpty&&t.push(new La(i,a,c)),t},[]))}e(findRedundantConnections$1,`findRedundantConnections`);function cleanRedundantRelationships(e){return differenceConnections(e,findRedundantConnections$1(e))}var StageInclude=class extends AbstractStageInclude{connectWithExisting(e,t=`both`){let r=this._connections.length,hasChanged=()=>this._connections.length>r;if(!isIterable(e)){if(t===`in`||t===`both`)for(let t of this.memory.elements)this.addConnections(Zu(t,e,`directed`));return(t===`out`||t===`both`)&&this.addConnections(Qu(e,this.memory.elements,`directed`)),hasChanged()}let i=[...e];if(t===`in`||t===`both`)for(let e of this.memory.elements)this.addConnections(Qu(e,i,`directed`));if(t===`out`||t===`both`)for(let e of i)this.addConnections(Qu(e,this.memory.elements,`directed`));return hasChanged()}processConnections(e){let t=N(e,cleanCrossBoundary,cleanRedundantRelationships);return N(t,Ae(({source:e,target:t,boundary:r})=>{N(Re([...toArray(e.ancestors()).reverse(),e],[...toArray(t.ancestors()).reverse(),t]),Ve(([e,t])=>e===t),he(1),Ae(([i,a])=>{e===i&&t===a?this.addImplicit(r):(i!==e&&i.isDeploymentNode()&&!i.onlyOneInstance()&&this.addImplicit(i),a!==t&&a.isDeploymentNode()&&!a.onlyOneInstance()&&this.addImplicit(a))}))})),t}},td=class Memory extends AbstractMemory{static empty(){return new Memory({elements:/* @__PURE__ */ new Set,explicits:/* @__PURE__ */ new Set,final:/* @__PURE__ */ new Set,connections:[]})}stageInclude(e){return new StageInclude(this,e)}stageExclude(e){return new StageExclude$1(this,e)}mutableState(){return{elements:new Set(this.state.elements),explicits:new Set(this.state.explicits),final:new Set(this.state.final),connections:[...this.state.connections]}}update(e){return new Memory({...this.state,...e})}equals(e){return e instanceof Memory&&ce(this.state,e.state)}diff(e){return{added:{elements:toArray(difference(e.elements,this.elements)),explicits:toArray(difference(e.explicits,this.explicits)),final:toArray(difference(e.final,this.final)),connections:toArray(differenceConnections(e.connections,this.connections))},removed:{elements:toArray(difference(this.elements,e.elements)),explicits:toArray(difference(this.explicits,e.explicits)),final:toArray(difference(this.final,e.final)),connections:differenceConnections(this.connections,e.connections)}}}toString(){return[`final:`,...[...this.final].map(e=>` `+e.id),`connections:`,...this.connections.map(e=>` `+e.expression)].join(`
|
|
81
|
+
`)}[Ia](e,t,r){return this.toString()}},nd=class StageFinal$1{static{e(this,`StageFinal`)}memory;includeAncestors;static for(e,t){return new StageFinal$1(e,t)}constructor(e,t){this.memory=e,this.includeAncestors=t}step1CleanConnections(e){if(e.connections.length<2)return e;let t=N(e.connections,cleanCrossBoundary,cleanRedundantRelationships),r=differenceConnections(e.connections,t);if(r.length===0)return e;let i=e.stageExclude({});return i.excludeConnections(r,!0),i.commit()}step2ProcessImplicits(e){let t=union(this.memory.elements,e.elements),r=union(e.final,this.memory.explicits),i=new I.default(()=>/* @__PURE__ */ new Set);for(let t of e.connections)if(t.boundary)for(let e of t.relations.model)i.get(e).add(t.boundary);for(let[e,a]of i)if(!(a.size<2))for(let e of a)t.delete(e)&&r.add(e);let a=new Set(r),isFinalOrHasIncludedDescendant=e=>{for(let t of a)if(e===t||isAncestor(e,t))return!0;return!1};return N(difference(t,a),ifilter(e=>e.isDeploymentNode()),toArray(),sortByFqnHierarchically,Ae(e=>{let t=[...e.children()].filter(isFinalOrHasIncludedDescendant).length;(t>=2||t===1&&isome(e.siblings(),isFinalOrHasIncludedDescendant))&&r.add(e)})),e.update({final:r})}step3ProcessBoundaries(e){let t=/* @__PURE__ */ new Set;for(let r of e.connections)r.boundary&&t.add(r.boundary);let r=treeFromMemoryState(e,`final`),i=e.stageExclude({}),isRemovable=i=>!(t.has(i)||e.explicits.has(i)||r.hasInOut(i)||r.root.has(i)),a=F([...r.root]);a&&!e.explicits.has(a)&&i.exclude(a);for(let t of e.final){let e=F(r.children(t));e&&!r.hasInOut(e)&&isRemovable(t)&&i.exclude(t)}return i.isDirty()?i.commit():e}step4AddAncestor(e){let t=/* @__PURE__ */ new Set;for(let r of e.final)for(let e of r.ancestors())t.add(e);if(t.size>0){let r=union(e.final,t);return e.update({final:r})}return e}commit(){let e=this.step1CleanConnections(this.memory),t=this.step2ProcessImplicits(e),r=this.step3ProcessBoundaries(t);return this.includeAncestors===!0?this.step4AddAncestor(r):r}};const rd=createRelationExpressionToPredicates(deploymentExpressionToPredicate);function buildExpandPredicate$1(e,t){let r=[],i=[];for(let e of t)if(isViewRulePredicate$1(e)&&`include`in e)for(let t of e.include)Gi.isCustom(t)&&(t.customRelation.multiple===!0?r.push(t):t.customRelation.multiple===!1&&i.push(t));let a=/* @__PURE__ */ new Set,s=e.specification.relationships;for(let e of Object.keys(s)){let t=s[e];(t?.style??t)?.multiple&&a.add(e)}if(r.length===0&&i.length===0&&a.size===0)return;let c=r.map(e=>({pred:rd(e.customRelation.expr)})),l=i.map(e=>({pred:rd(e.customRelation.expr)}));return(e,t)=>{let resolveEndpoint=e=>{if(e&&typeof e==`object`){if(`tags`in e&&`kind`in e&&`metadata`in e)return e;if(e.instance&&e.element)return{id:e.id,tags:e.instance.tags,kind:e.element.kind,metadata:e.instance.metadata}}return e??{}},r=resolveEndpoint(t?.source??e.source),i=resolveEndpoint(t?.target??e.target);if(l.length>0){for(let{pred:t}of l)if(t({source:r,target:i,kind:e.kind,tags:e.tags,metadata:e.metadata}))return!1}if(a.size>0){let t=e.kind;if(t&&a.has(t))return!0}if(c.length>0){for(let{pred:t}of c)if(t({source:r,target:i,kind:e.kind,tags:e.tags,metadata:e.metadata}))return!0}return!1}}e(buildExpandPredicate$1,`buildExpandPredicate`);function processPredicates$1(e,t){let r=td.empty(),i=!1;for(let a of t){if(isViewRulePredicate$1(a)){let t=`include`in a?`include`:`exclude`,i=a.include??a.exclude;for(let a of i){let i=t===`include`?r.stageInclude(a):r.stageExclude(a);i=predicateToPatch(t,{expr:a,model:e,stage:i,memory:r,where:null})??i,r=i.commit()}}`includeAncestors`in a&&(i=a.includeAncestors)}return nd.for(r,i).commit()}e(processPredicates$1,`processPredicates`);function computeDeploymentView(e,{docUri:t,rules:r,...i}){let a=processPredicates$1(e.deployment,r),s=buildNodes$1(e,a),c=buildExpandPredicate$1(e,r),l=toComputedEdges$1(a.connections,c);linkNodesWithEdges(s,l);let u=topologicalSort$1({nodes:s,edges:l}),m=applyDeploymentNavigateTo(e.deployment,r,applyDeploymentViewRuleStyles(r,u.nodes)),h=Me(r,isViewRuleAutoLayout$1),g=buildElementNotations(m);return calcViewLayoutHash({...withResolvedRouting(i,e.$styles.defaults.view.routing),[Vi]:`computed`,[Hi]:`deployment`,autoLayout:{direction:h?.direction??`TB`,...h?.nodeSep&&{nodeSep:h.nodeSep},...h?.rankSep&&{rankSep:h.rankSep}},edges:u.edges,nodes:p(m,e=>(e.icon===`none`&&delete e.icon,e)),...g.length>0&&{notation:{nodes:g}}})}function flattenGroupRules(e){return t=>isViewRuleGroup$1(t)?t.groupRules.flatMap(flattenGroupRules(e)):isViewRulePredicate$1(t)&&`include`in t?t.include.filter(e):[]}function applyCustomElementProperties(e,t){let r=e.flatMap(flattenGroupRules(W.isCustom));if(r.length===0)return t;let i=[...t];for(let{custom:{expr:e,...t}}of r){let{border:r,opacity:a,multiple:s,iconColor:c,iconSize:l,iconPosition:p,padding:m,size:h,textSize:g,sizing:v,...y}=u(t,C),b=exact({border:r,opacity:a,multiple:s,iconColor:c,iconSize:l,iconPosition:p,padding:m,size:h,textSize:g,sizing:v}),x=!_(b),S=!_(y),ee=elementExprToPredicate(e);i.forEach((e,t)=>{!isGroupElementKind(e)&&ee(e)&&(S&&(e={...e,...y,isCustomized:!0}),x&&(e={...e,isCustomized:!0,style:{...e.style,...b}}),i[t]=e)})}return i}function resolveGlobalRulesInElementView(e,t){return e.reduce((e,r)=>{if(isViewRuleGlobalPredicateRef$1(r)){let i=t.predicates[r.predicateId];return C(i)?e:e.concat(i)}if(isViewRuleGlobalStyle$1(r)){let i=t.styles[r.styleId];return C(i)?e:e.concat(i)}return isViewRuleGroup$1(r)?(e.push({...r,groupRules:resolveGlobalRulesInGroup(r.groupRules,t)}),e):(e.push(r),e)},[])}function resolveGlobalRulesInGroup(e,t){return e.reduce((e,r)=>{if(isViewRuleGlobalPredicateRef$1(r)){let i=t.predicates[r.predicateId];return C(i)?e:e.concat(i)}return isViewRuleGroup$1(r)?(e.push({...r,groupRules:resolveGlobalRulesInGroup(r.groupRules,t)}),e):(e.push(r),e)},[])}function resolveGlobalRulesInDynamicView(e,t){return e.reduce((e,r)=>{if(isViewRuleGlobalPredicateRef$1(r)){let i=t.dynamicPredicates[r.predicateId];return C(i)?e:e.concat(i)}if(isViewRuleGlobalStyle$1(r)){let i=t.styles[r.styleId];return C(i)?e:e.concat(i)}return e.push(r),e},[])}function elementsFromIncludeProperties(e,t){let r=/* @__PURE__ */ new Set;for(let i of t)if(isViewRulePredicate$1(i))for(let t of i.include){let i=elementExprToPredicate(t);for(let t of e.elements())i(t)&&r.add(t)}return r}const flattenSteps=e=>{switch(!0){case ia.isStep(e):return[e];case ia.isParallel(e):{let t=[],r=[];for(let i of e.steps){let[e,...a]=flattenSteps(i);e&&t.push(e),r.push(...a)}return[...t,...r]}case ia.isSeries(e):return[...e.steps];case ia.isBreak(e):case ia.isLoop(e):case ia.isOpt(e):return P(e.steps,flattenSteps);case ia.isAlt(e):case ia.isTry(e):{let t=[],r=[],i=e._type===`try`?[e.try,e.catch,e.finally]:[...e.branches];for(let e of i){if(!e)continue;let[i,...a]=P(e.steps,flattenSteps);i&&(t.push(i),r.push(...a))}return[...t,...r]}default:nonexhaustive(e)}};function elementsFromSteps(e,t){let r=[],addActor=(...[e,t])=>{if(!r.includes(e)){let i=r.indexOf(t);if(i>0){r.splice(i,0,e);return}r.push(e)}r.includes(t)||r.push(t)};for(let i of P(t,flattenSteps)){let t=e.element(i.source),a=e.element(i.target),s=r.indexOf(t),c=r.indexOf(a);s>=0&&c>=0||(i.isBackward?addActor(a,t):addActor(t,a))}return new Set(r)}function findRelations(e,t,r){let i=findConnection$3(e,t,`directed`).flatMap(e=>[...e.relations]).sort(compareRelations);if(!isNonEmptyArray(i))return{};let specificationOf=t=>t?e.$model.specification.relationships[t]:void 0;if(i.length===1){let e=i[0],t=specificationOf(e.kind);return exact({title:e.title??void 0,kind:e.kind??void 0,tags:e.tags,relations:[e.id],navigateTo:e.$relationship.navigateTo,color:e.$relationship.color??t?.color,line:e.$relationship.line??t?.line,head:e.$relationship.head??t?.head,tail:e.$relationship.tail??t?.tail,technology:e.technology??void 0,description:e.$relationship.description??void 0})}let a=N(i,P(e=>e.tags),E()),s=k(a,1)?a:void 0,c=p(i,e=>e.id),l=fe(i).$relationship.navigateTo;l===r&&(l=void 0),l||=N(i,P(e=>e.$relationship.navigateTo&&e.$relationship.navigateTo!==r?e.$relationship.navigateTo:[]),E(),F());let u=N(i,ve((e,{title:t,technology:r,kind:i,$relationship:a})=>{let s=specificationOf(i),c=a.color??s?.color,l=a.line??s?.line,u=a.head??s?.head,p=a.tail??s?.tail;return j(t)&&e.title.add(t),j(c)&&e.color.add(c),j(l)&&e.line.add(l),j(u)&&e.head.add(u),j(p)&&e.tail.add(p),j(i)&&e.kind.add(i),j(r)&&e.technology.add(r),j(a.description)&&!e.description.some(ce(a.description))&&e.description.push(a.description),e},{kind:/* @__PURE__ */ new Set,color:/* @__PURE__ */ new Set,line:/* @__PURE__ */ new Set,head:/* @__PURE__ */ new Set,tail:/* @__PURE__ */ new Set,title:/* @__PURE__ */ new Set,technology:/* @__PURE__ */ new Set,description:[]}));return exact({tags:s??void 0,relations:c,navigateTo:l,kind:F([...u.kind]),title:F([...u.title]),color:F([...u.color]),line:F([...u.line]),head:F([...u.head]),tail:F([...u.tail]),technology:F([...u.technology]),description:F(u.description)})}var DynamicViewCompute=class{model;view;steps=[];constructor(e,t){this.model=e,this.view=t}compute(){let{docUri:e,rules:t,steps:r,...i}=this.view,a=resolveGlobalRulesInDynamicView(t,this.model.globals),s=elementsFromIncludeProperties(this.model,a),c=elementsFromSteps(this.model,r),l=N(union(intersection(s,c),c,s),toArray(),sortParentsFirst),u={actors:/* @__PURE__ */ new Set,flow:[],id:null,_type:null},m=new et.default;m.push(u);let flowStackHead=()=>m.peek()??u,addToFlow=e=>(flowStackHead().flow.push(e),e),addActorToFlow=e=>{flowStackHead().actors.add(e)},newFlow=e=>({actors:/* @__PURE__ */ new Set,flow:[],...e}),pushFlow=e=>(m.push(e),e),popFlow=()=>{let e=m.pop();return e&&e!==u&&e.flow.length>0&&addToFlow(e),e},processSteps=({steps:e,newflow:t,prefix:r})=>{pushFlow(t),r??=t.id,ve(e,(e,t)=>processStep(t,e,r),1),popFlow()},flowId=(e,t,r)=>StepPath(e,[t,r]),processTryStep=(e,t)=>{let r=1;processSteps({steps:e.try.steps,newflow:newFlow({_type:`try-block`,id:flowId(t,r++,`block`),title:e.try.title})}),e.catch&&processSteps({steps:e.catch.steps,newflow:newFlow({_type:`try-catch`,id:flowId(t,r++,`catch`),title:e.catch.title})}),e.finally&&processSteps({steps:e.finally.steps,newflow:newFlow({_type:`try-finally`,id:flowId(t,r,`finally`),title:e.finally.title})})},processStep=(e,t,r)=>{switch(!0){case ia.isSeries(e):for(let i of e.steps)t=processStep(i,t,r);return t;case ia.isLoop(e):case ia.isOpt(e):case ia.isBreak(e):case ia.isParallel(e):return processSteps({steps:e.steps,newflow:newFlow({_type:e._type,id:flowId(r,t,e._type),title:e.title})}),t+1;case ia.isTry(e):{let{id:i}=pushFlow(newFlow({_type:`try`,id:flowId(r,t,`try`)}));return processTryStep(e,i),popFlow(),t+1}case ia.isAlt(e):{let{id:i}=pushFlow(newFlow({_type:`alt`,id:flowId(r,t,`alt`),title:e.title}));return e.branches.forEach((e,t)=>{processSteps({steps:e.steps,newflow:newFlow({_type:`alt-${e._type}`,id:flowId(i,t+1,e._type),title:e.title})})}),popFlow(),t+1}case ia.isStep(e):{let i=addToFlow(StepPath(r,t)),{source:a,target:s,title:c,isBackward:u,navigateTo:p,notation:m,...h}=e,g=this.model.element(a),_=l.indexOf(g);invariant(_>=0,`Source ${a} not found`);let v=this.model.element(s),y=l.indexOf(v);invariant(y>=0,`Target ${s} not found`),addActorToFlow(g),addActorToFlow(v);let{title:b,relations:x,navigateTo:S,...ee}=findRelations(g,v,this.view.id),te=j(p)&&p!==this.view.id?p:S,ne=e.kind?this.model.specification.relationships[e.kind]:void 0;return this.steps.push(exact({...ee,...!e.technology&&!ee.technology&&ne?.technology&&{technology:ne.technology},...!e.color&&!ee.color&&ne?.color&&{color:ne.color},...!e.line&&!ee.line&&ne?.line&&{line:ne.line},...!e.head&&ne?.head&&{head:ne.head},...!e.tail&&ne?.tail&&{tail:ne.tail},...h,id:i,source:g,target:v,navigateTo:te,title:c??b??ne?.title,relations:x??[],isBackward:y<_})),t+1}default:nonexhaustive(e)}};ve(r,(e,t)=>processStep(t,e),1);let h=buildComputedNodes(this.model.$styles,l.map(elementModelToNodeSource)),g=this.model.$styles.defaults.relationship,_=this.steps.map(({id:e,source:t,target:r,relations:i,title:a,isBackward:s,tags:c,...l})=>{let u=nonNullable(h.get(t.id),`Source node ${t.id} not found`),p=nonNullable(h.get(r.id),`Target node ${r.id} not found`),m={id:e,parent:commonAncestor(t.id,r.id),source:u.id,target:p.id,label:a??null,relations:i,color:g.color,line:g.line,head:g.arrow,tags:c??[],...l};for(s&&(m.dir=`back`);m.parent&&!h.has(m.parent);)m.parent=parentFqn(m.parent);u.outEdges.push(m.id),p.inEdges.push(m.id);for(let e of ancestorsFqn(m.source)){if(e===m.parent)break;h.get(e)?.outEdges.push(m.id)}for(let e of ancestorsFqn(m.target)){if(e===m.parent)break;h.get(e)?.inEdges.push(m.id)}return m}),v=applyCustomElementProperties(a,applyViewRuleStyles(a,l.map(e=>nonNullable(h.get(e.id))))),y=Me(a,isViewRuleAutoLayout$1),b=buildElementNotations(v);return calcViewLayoutHash({...withResolvedRouting(i,this.model.$styles.defaults.view.routing),[Hi]:`dynamic`,[Vi]:`computed`,variant:i.variant??`diagram`,flow:toFlowSteps(u),autoLayout:{direction:y?.direction??`LR`,...y?.nodeSep&&{nodeSep:y.nodeSep},...y?.rankSep&&{rankSep:y.rankSep}},nodes:p(v,e=>(e.icon===`none`&&delete e.icon,e)),edges:_,...b.length>0&&{notation:{nodes:b}}})}};function computeDynamicView(e,t){return new DynamicViewCompute(e,t).compute()}const id=ue(y(),p(e=>S(e)?e:subflow(e)));function subflow(e){let t={id:e.id,...e.title&&{title:e.title}};if(e._type===`try`){let[r,i,a]=id(e.flow);if(C(r)||S(r)||S(i)||S(a))throw Error(`Try block, catch block, and finally block must be subflows`);invariant(r._type===`try-block`,`Try block is required`);let s={_type:e._type,flow:[r],...t};return a?(invariant(a._type===`try-finally`,`3rd party must be a finally block`),invariant(i&&i._type===`try-catch`,`2nd must be a catch block`),s.flow=[r,i,a],s):(i&&(invariant(i._type===`try-catch`||i._type===`try-finally`,`2nd element must be a catch or finally block, it is ${i._type}`),s.flow=[r,i]),s)}return{flow:id(e.flow),_type:e._type,...t}}function toFlowSteps(e){return e.flow.map(e=>{if(S(e))return e;let t=subflow(e);if(t._type===`alt-else`||t._type===`alt-if`||t._type===`alt-when`||t._type===`try-block`||t._type===`try-catch`||t._type===`try-finally`)throw Error(`Unsupported root-level subflow type: ${t._type}`);return t})}function edgeMetadata(e,t){let r=null;for(let i of t.relations){let t=e.findRelationship(i,`model`)?.$relationship.metadata;if(t)for(let[e,i]of Object.entries(t)){if(C(i))continue;r??=Object.create(null);let t=r[e]??=[];for(let e of Array.isArray(i)?i:[i])t.includes(e)||t.push(e)}}return r}function applyCustomRelationProperties(e,t,r,i){let a=e.flatMap(flattenGroupRules(qi.isCustom)),s=Array.from(r);if(a.length===0||s.length===0)return s;let c=s.map(e=>i?edgeMetadata(i,e):null);for(let{customRelation:{expr:e,title:r,description:i,notes:l,multiple:p,...m}}of a){let a=i?{description:MarkdownOrString$1(i)}:{},p=l?{notes:MarkdownOrString$1(l)}:{},h=u(m,C),g=Lu(e);s.forEach((e,i)=>{let l,u;for(let r of t)if(r.id===e.source&&(l=r),r.id===e.target&&(u=r),l&&u)break;l&&u&&g({source:l,target:u,...Ge(e,[`kind`,`tags`]),metadata:c[i]})&&(s[i]={...e,...h,...a,...p,label:r??e.label,isCustomized:!0})})}return s}function findRedundantConnections(e){return N([...e],mergeConnections,ve((e,t,r,i)=>{let a=findDescendantConnections(i,t),s=union(...a.map(A(`relations`))),c=intersection(t.relations,s);if(a.length>0&&(c=union(c,t.directRelations)),findDeepestNestedConnection(i,t.reversed())&&(c=union(c,t.directRelations)),c.size<t.relations.size){let e=i.some(isAnyInOut(t.source)),r=i.some(isAnyInOut(t.target));e&&(c=union(c,toSet(ifilter(t.relations,isOutgoing(t.source))))),r&&(c=union(c,toSet(ifilter(t.relations,isIncoming(t.target)))))}return c.size>0&&e.push(t.update(c)),e},[]))}var ad=class StageFinal{memory;static for(e){return new StageFinal(e)}constructor(e){this.memory=e}step1CleanConnections(e){if(e.connections.length<2)return e;let t=findRedundantConnections(e.connections);if(t.length===0)return e;let r=e.stageExclude({});return r.excludeConnections(t,!0),r.commit()}step2ProcessImplicits(e){let t=union(this.memory.elements,e.elements),r=union(e.final,this.memory.explicits),i=new Set(r),isFinalOrHasIncludedDescendant=e=>{for(let t of i)if(e===t||isAncestor(e,t))return!0;return!1};return N(difference(t,i),toArray(),sortByFqnHierarchically,Ae(e=>{let t=[...e.children()].filter(isFinalOrHasIncludedDescendant).length;(t>=2||t===1&&isome(e.siblings(),isFinalOrHasIncludedDescendant))&&r.add(e)})),e.update({final:r})}step3ProcessBoundaries(e){let t=/* @__PURE__ */ new Set;for(let r of e.connections)r.boundary&&r.boundary!==r.source&&r.boundary!==r.target&&t.add(r.boundary);let r=treeFromMemoryState(e,`final`),i=e.stageExclude({}),isRemovable=i=>!(t.has(i)||e.explicits.has(i)||r.hasInOut(i)||r.root.has(i)),a=F([...r.root]);a&&!e.explicits.has(a)&&i.exclude(a);for(let t of e.final){let e=F(r.children(t));e&&!r.hasInOut(e)&&isRemovable(t)&&i.exclude(t)}return i.isDirty()?i.commit():e}commit(){let e=this.step1CleanConnections(this.memory),t=this.step2ProcessImplicits(e);return this.step3ProcessBoundaries(t)}};const{findConnection:od,findConnectionsBetween:sd,findConnectionsWithin:cd}=Ba;function findConnectionsFrom(e,t){return sd(e,t).flatMap(t=>{if(t.source===e)return[t];let r=new Set([...t.relations].filter(isBidirectionalRelation));return r.size>0?[t.update(r)]:[]})}function resolveElements(e,t){switch(!0){case W.isElementKindExpr(t):return[...ifilter(e.elements(),e=>t.isEqual===(e.kind===t.elementKind))];case W.isElementTagExpr(t):return[...ifilter(e.elements(),e=>t.isEqual===e.tags.includes(t.elementTag))];case t.selector===`expanded`:{let r=e.element(H.flatten(t.ref));return[r,...r.children()]}case t.selector===`children`:case t.selector===`descendants`:{let r=e.element(H.flatten(t.ref)),i=t.selector===`children`?toArray(r.children()):toArray(r.descendants());return i&&i.length>0?i:[r]}case W.isModelRef(t):return[e.element(H.flatten(t.ref))];default:nonexhaustive(t)}}function includeDescendantsFromMemory(e,t){if(t.isEmpty()||e.length===0)return e;let r=Ue(e.map(e=>isDescendantOf(e))),i=toArray(ifilter(t.elements,t=>!e.includes(t)&&r(t)));return[...e,...i]}function resolveAndIncludeFromMemory(e,{memory:t,model:r}){let i=resolveElements(r,e);return W.isModelRef(e)?e.selector===`descendants`?i:includeDescendantsFromMemory(i,t):i}const ld={include:({expr:e,model:t,stage:r,where:i})=>{let a=t.element(H.flatten(e.ref));i(a)&&(r.addExplicit(a),r.connectWithExisting(a));let s=[...a.children()].filter(i),c=[];for(let e of s)r.addImplicit(e),r.connectWithExisting(e)&&c.push(e);return r.addConnections(cd(c)),r},exclude:({expr:e,model:t,stage:r,filterWhere:i})=>{let a=i(resolveElements(t,e));return r.exclude(a),r}},ud={include:({expr:e,model:t,stage:r,filterWhere:i})=>{let a=i(resolveElements(t,e));if(a.length!==0)return r.addExplicit(a),r.connectWithExisting(a),r.addConnections(cd(a)),r},exclude:({expr:e,model:t,stage:r,filterWhere:i})=>{let a=i(resolveElements(t,e));return r.exclude(a),r}},dd={include:({expr:e,model:t,stage:r,filterWhere:i})=>{let a=i(resolveElements(t,e));if(a.length!==0)return r.addExplicit(a),r.connectWithExisting(a),r.addConnections(cd(a)),r},exclude:({expr:e,model:t,stage:r,filterWhere:i})=>{let a=i(resolveElements(t,e));return r.exclude(a),r}},NoWhere=()=>!0,NoFilter=e=>e,hashEdgeId=(e,t,r)=>stringHash$1(`model:${e}:${t}:${r}`);function toComputedEdges(e,t){return e.flatMap(e=>{let r=[...e.relations];invariant(k(r,1),`Edge must have at least one relation`);let i=e.source.$model.$styles.defaults,a=e.source.id,s=e.target.id,c=D(r,e=>e.source.id===a&&e.target.id===s);if(t&&r.length>1){let[c,l]=N(r,pe(r=>t(r,e)));if(c.length>0){let t=c.map(t=>{let{title:r,color:c=i.relationship.color,line:l=i.relationship.line,head:u=i.relationship.arrow,...p}=mergePropsFromRelationships([t.$relationship],t.$relationship);return{id:hashEdgeId(a,s,t.id),parent:e.boundary?.id??null,source:a,target:s,label:r??null,relations:[t.id],color:c,line:l,head:u,...p}});if(l.length>0){let{title:r,color:c=i.relationship.color,line:u=i.relationship.line,head:p=i.relationship.arrow,...m}=mergePropsFromRelationships(l.map(e=>e.$relationship),F(D(l,e=>e.source.id===a&&e.target.id===s))?.$relationship);t.push({id:e.id,parent:e.boundary?.id??null,source:a,target:s,label:r??null,relations:l.map(e=>e.id),color:c,line:u,head:p,...m})}return t}}let{title:l,color:u=i.relationship.color,line:p=i.relationship.line,head:m=i.relationship.arrow,...h}=mergePropsFromRelationships(r.map(e=>e.$relationship),F(c)?.$relationship);return[exact({id:e.id,parent:e.boundary?.id??null,source:a,target:s,label:l??null,relations:r.map(e=>e.id),color:u,line:p,head:m,...h})]})}function buildNodes(e,t){return buildComputedNodes(e.$styles,[...t.final].map(elementModelToNodeSource),t.groups)}const fd=W.isWildcard,isAncestorOrDescendantOf=(e,t)=>e.isAncestorOf(t)||e.isDescendantOf(t),pd={include:({expr:{source:e,target:t,isBidirectional:r=!1},memory:i,model:a,stage:s,where:c,filterWhere:l})=>{let u=fd(e),m=fd(t),h=[];switch(!0){case u&&m&&i.isEmpty()&&c!==NoWhere:{let e=N(a.relationships(),ifilter(c),toArray(),p(e=>new Ra(e.source,e.target,/* @__PURE__ */ new Set([e]))));return s.addConnections(e),s}case u&&m&&!i.isEmpty()&&c!==NoWhere:h.push(...cd(i.elements));break;case u&&m:h.push(...cd(a.roots()));break;case!u&&m&&c!==NoWhere:{let t=resolveElements(a,e),i=N(t,P(e=>N(e,ke(Oe(r===!0),{onTrue:e=>union(e.allIncoming,e.allOutgoing),onFalse:e=>e.allOutgoing}),ifilter(c),iunique(),toArray(),pe(t=>t.source===e),([t,r])=>Se(N(t,D(t=>!isAncestorOrDescendantOf(e,t.target)),p(t=>new Ra(e,t.target,/* @__PURE__ */ new Set([t])))),N(r,D(t=>!isAncestorOrDescendantOf(e,t.source)),p(t=>new Ra(t.source,e,/* @__PURE__ */ new Set([t]))))))));return s.addConnections(i),s}case!u&&m:{let[t,s]=resolveWildcard(e,{memory:i,model:a}),c=r?`both`:`directed`;for(let e of t)h.push(...sd(e,s,c));break}case u&&!m&&c!==NoWhere:{let e=resolveElements(a,t),i=N(e,P(e=>N(e,ke(Oe(r===!0),{onTrue:e=>union(e.allIncoming,e.allOutgoing),onFalse:e=>e.allIncoming}),ifilter(c),toArray(),pe(t=>t.target===e),([t,r])=>Se(N(r,D(t=>!isAncestorOrDescendantOf(e,t.target)),p(t=>new Ra(e,t.target,/* @__PURE__ */ new Set([t])))),N(t,D(t=>!isAncestorOrDescendantOf(e,t.source)),p(t=>new Ra(t.source,e,/* @__PURE__ */ new Set([t]))))))));return s.addConnections(i),s}case u&&!m:{let[e,s]=resolveWildcard(t,{memory:i,model:a}),c=r?`both`:`directed`;for(let t of s)h.push(...sd(t,e,c));break}default:{invariant(!fd(e),`Inference failed - source must be not a wildcard`),invariant(!fd(t),`Inference failed - target must be not a wildcard`);let s=resolveAndIncludeFromMemory(e,{memory:i,model:a}),c=resolveAndIncludeFromMemory(t,{memory:i,model:a}),l=r?`both`:`directed`;for(let e of s)h.push(...sd(e,c,l))}}return s.addConnections(l(h)),s},exclude:({expr:{source:e,target:t,isBidirectional:r},model:i,memory:a,stage:s,where:c})=>{let l=fd(e),u=fd(t),p;switch(!0){case l&&u:p=N(a.connections,P(ue(A(`relations`),ifilter(c),toArray())),toSet());break;case!l&&u:{let t=resolveElements(i,e);p=N(t,P(e=>N(e,ke(Oe(r===!0),{onTrue:e=>union(e.allIncoming,e.allOutgoing),onFalse:e=>e.allOutgoing}),ifilter(c),toArray())),toSet());break}case l&&!u:{let e=resolveElements(i,t);p=N(e,P(e=>N(e,ke(Oe(r===!0),{onTrue:e=>union(e.allIncoming,e.allOutgoing),onFalse:e=>e.allIncoming}),ifilter(c),toArray())),toSet());break}default:{invariant(!fd(e),`Inference failed - source must be not a wildcard`),invariant(!fd(t),`Inference failed - target must be not a wildcard`);let a=resolveElements(i,e),s=resolveElements(i,t),l=/* @__PURE__ */ new Set;for(let e of a)for(let t of s)isSameHierarchy(e,t)||(l=union(l,intersection(e.allOutgoing,t.allIncoming),r?intersection(t.allOutgoing,e.allIncoming):/* @__PURE__ */ new Set));p=toSet(ifilter(l,c))}}return s.excludeRelations(p),s}};function resolveWildcard(e,{memory:t,model:r}){let i=resolveElements(r,e);if(!k(i,1))return[[],[]];if(W.isModelRef(e)){let a=toArray(r.element(H.flatten(e.ref)).ascendingSiblings());return[includeDescendantsFromMemory(i,t),includeDescendantsFromMemory(a,t)]}return[i,N(i,p(e=>e.ascendingSiblings()),iflat(),iunique(),toArray(),e=>includeDescendantsFromMemory(e,t))]}const md={include:({expr:e,scope:t,model:r,memory:i,stage:a,filterWhere:s})=>{let c=e.incoming,l=[];if(W.isWildcard(c)){if(!t)return;for(let e of t.ascendingSiblings())l.push(...findConnectionsFrom(e,[t]))}else{let e=resolveAndIncludeFromMemory(c,{memory:i,model:r}),t=[...i.elements];t.length===0&&t.push(...E(e.flatMap(e=>[...e.ascendingSiblings()])));let a=incomingConnectionPredicate(r,c);for(let r of t)l.push(...findConnectionsFrom(r,e).filter(a))}return a.addConnections(s(l)),a},exclude:({expr:{incoming:e},model:t,scope:r,stage:i,where:a})=>{let s=[];if(W.isWildcard(e)){if(!r)return;s.push(...incomingRelations(r))}else{let r=resolveElements(t,e);s.push(...r.flatMap(incomingRelations))}return i.excludeRelations(new Set(s.filter(a))),i}};function incomingConnectionPredicate(e,t){let isIncomingOrBidirectional=e=>{let t=Fa.isIncoming(e),r=Fa.isOutgoing(e);return e=>t(e)||r(e)&&[...e.relations].some(isBidirectionalRelation)};switch(!0){case W.isElementKindExpr(t):case W.isElementTagExpr(t):{let e=elementExprToPredicate(t);return t=>e(t.target)||e(t.source)&&[...t.relations].some(isBidirectionalRelation)}case W.isModelRef(t)&&t.selector===`children`:{let r=H.flatten(t.ref);return Ue([...e.children(r)].map(e=>isIncomingOrBidirectional(e.id)))}case W.isModelRef(t)&&t.selector===`descendants`:{let r=H.flatten(t.ref);return Ue([Fa.isInside(r),...[...e.children(r)].map(e=>isIncomingOrBidirectional(e.id))])}case W.isModelRef(t)&&t.selector===`expanded`:{let e=H.flatten(t.ref);return Ue([isIncomingOrBidirectional(e),Fa.isInside(e)])}case W.isModelRef(t):return isIncomingOrBidirectional(H.flatten(t.ref));default:nonexhaustive(t)}}function incomingRelations(e){return[...e.allIncoming,...[...e.allOutgoing].filter(isBidirectionalRelation)]}const hd={include:({expr:{inout:e},scope:t,model:r,memory:i,stage:a,filterWhere:s})=>{let c=[];if(W.isWildcard(e)){if(!t)return;c.push(...sd(t,t.ascendingSiblings()))}else{let t=resolveAndIncludeFromMemory(e,{memory:i,model:r}),a=[...i.elements];a.length===0&&(a=E(t.flatMap(e=>toArray(e.ascendingSiblings()))));for(let e of t)c.push(...sd(e,a))}return a.addConnections(s(c)),a},exclude:({expr:{inout:e},model:t,scope:r,stage:i,where:a})=>{let s=[];if(W.isWildcard(e)){if(!r)return;s.push(...r.allOutgoing),s.push(...r.allIncoming)}else{let r=resolveElements(t,e);s.push(...r.flatMap(e=>[...e.allOutgoing,...e.allIncoming]))}return i.excludeRelations(toSet(s.filter(a))),i}},gd={include:({expr:e,scope:t,model:r,memory:i,stage:a,filterWhere:s})=>{let c=e.outgoing,l=[];if(W.isWildcard(c)){if(!t)return;l.push(...sd(t,t.ascendingSiblings(),`directed`))}else{let e=resolveAndIncludeFromMemory(c,{memory:i,model:r}),t=[...i.elements];t.length===0&&t.push(...E(e.flatMap(e=>[...e.ascendingSiblings()])));let a=outgoingConnectionPredicate(r,c);for(let r of e)l.push(...sd(r,t,`directed`).filter(a))}return a.addConnections(s(l)),a},exclude:({expr:{outgoing:e},model:t,scope:r,stage:i,where:a})=>{let s=[];if(W.isWildcard(e)){if(!r)return;s.push(...r.allOutgoing)}else{let r=resolveElements(t,e);s.push(...r.flatMap(e=>[...e.allOutgoing]))}return i.excludeRelations(toSet(s.filter(a))),i}};function outgoingConnectionPredicate(e,t){switch(!0){case W.isElementKindExpr(t):case W.isElementTagExpr(t):{let e=elementExprToPredicate(t);return t=>e(t.source)}case W.isModelRef(t)&&t.selector===`children`:{let r=H.flatten(t.ref);return Ue([...e.children(r)].map(e=>Fa.isOutgoing(e.id)))}case W.isModelRef(t)&&t.selector===`descendants`:{let r=H.flatten(t.ref);return Ue([Fa.isInside(r),...[...e.children(r)].map(e=>Fa.isOutgoing(e.id))])}case W.isModelRef(t)&&t.selector===`expanded`:{let e=H.flatten(t.ref);return Ue([Fa.isOutgoing(e),Fa.isInside(e)])}case W.isModelRef(t):{let e=H.flatten(t.ref);return Fa.isOutgoing(e)}default:nonexhaustive(t)}}const _d={include:({scope:e,model:t,stage:r,memory:i,where:a})=>{if(!e){let e=a===NoWhere?[...t.roots()]:toArray(ifilter(t.elements(),a));if(e.length===0)return;let[i,s]=pe(e,e=>!e.imported);return r.addExplicit(i),r.addImplicit(s),r.addConnections(cd(e)),r.connectWithExisting(e),r}let s=toArray(ifilter(e.children(),a)),c=s.length>0;if(!c){let t=sd(e,e.siblings()),i=e.parent;t.length===0&&i&&r.addExplicit(i),s.push(e)}r.addExplicit(e);let l=toSet([...i.elements,...e.descendingSiblings()]);for(let e of l)r.addConnections(sd(e,s,`directed`));c&&(r.addConnections(cd(s)),r.addExplicit(s));for(let e of s)r.addConnections(sd(e,l,`directed`));return r},exclude:({scope:e,memory:t,stage:r,where:i})=>i===NoWhere?e?(r.exclude([e,...e.descendants()]),r):Vu.empty(t.scope).stageExclude(r.expression):(r.exclude(D([...t.elements],i)),r)};function processElementPredicate(e,t,r){switch(!0){case W.isCustom(e):return t===`include`?processElementPredicate(e.custom.expr,t,r):r.stage;case W.isWhere(e):{let i=whereOperatorAsPredicate(e.where.condition),filterWhere=e=>D(e,i);return processElementPredicate(e.where.expr,t,{...r,where:i,filterWhere})}case W.isModelRef(e)&&e.selector===`expanded`:return ld[t]({...r,expr:e})??r.stage;case W.isWildcard(e):return _d[t]({...r,expr:e})??r.stage;case W.isElementKindExpr(e):case W.isElementTagExpr(e):return ud[t]({...r,expr:e})??r.stage;case W.isModelRef(e):return dd[t]({...r,expr:e})??r.stage;default:nonexhaustive(e)}}function processRelationtPredicate(e,t,r){switch(!0){case qi.isCustom(e):return t===`include`?processRelationtPredicate(e.customRelation.expr,t,r):r.stage;case qi.isWhere(e):{let i=whereOperatorAsPredicate(e.where.condition),filterRelations=e=>new Set(D([...e],i)),filterWhere=e=>N(e,p(e=>new Ra(e.source,e.target,filterRelations(e.relations))),D(e=>e.nonEmpty()));return processRelationtPredicate(e.where.expr,t,{...r,where:i,filterWhere})}case qi.isInOut(e):return hd[t]({...r,expr:e})??r.stage;case qi.isDirect(e):return pd[t]({...r,expr:e})??r.stage;case qi.isOutgoing(e):return gd[t]({...r,expr:e})??r.stage;case qi.isIncoming(e):return md[t]({...r,expr:e})??r.stage;default:nonexhaustive(e)}}function process_predicates(e,t,r){let i={model:e,scope:t.scope,where:NoWhere,filterWhere:NoFilter};for(let a of r)if(isViewRuleGroup$1(a))t=process_predicates(e,Hu.enter(t,a),a.groupRules),invariant(t instanceof Hu,`processPredicates must return ActiveGroupMemory`),t=t.leave();else if(isViewRulePredicate$1(a)){let e=`include`in a?`include`:`exclude`,r=a.include??a.exclude;for(let a of r){let r=e===`include`?t.stageInclude(a):t.stageExclude(a);switch(!0){case Ji.isFqnExpr(a):r=processElementPredicate(a,e,{...i,stage:r,memory:t})??r;break;case Ji.isRelationExpr(a):r=processRelationtPredicate(a,e,{...i,stage:r,memory:t})??r;break;default:nonexhaustive(a)}t=r.commit()}}return t}function processPredicates(e,t,r){return t=process_predicates(e,t,r),ad.for(t).commit()}function buildExpandPredicate(e,t){let r=t.flatMap(flattenGroupRules(qi.isCustom)).filter(e=>e.customRelation.multiple===!0),i=t.flatMap(flattenGroupRules(qi.isCustom)).filter(e=>e.customRelation.multiple===!1),a=/* @__PURE__ */ new Set,s=e.specification.relationships;for(let e of Object.keys(s)){let t=s[e];(t?.style??t)?.multiple&&a.add(e)}if(r.length===0&&i.length===0&&a.size===0)return;let c=r.map(e=>({pred:Lu(e.customRelation.expr)})),l=i.map(e=>({pred:Lu(e.customRelation.expr)}));return(e,t)=>{let r=t?.source??e.source,i=t?.target??e.target;if(l.length>0){for(let{pred:t}of l)if(t({source:r,target:i,kind:e.kind,tags:e.tags,metadata:e.metadata}))return!1}if(a.size>0){let t=e.kind;if(t&&a.has(t))return!0}if(c.length>0){for(let{pred:t}of c)if(t({source:r,target:i,kind:e.kind,tags:e.tags,metadata:e.metadata}))return!0}return!1}}function computeElementView(e,{docUri:t,rules:r,...i}){let a=resolveGlobalRulesInElementView(r,e.globals),s=i.viewOf?e.asComputed.element(i.viewOf):null,c=processPredicates(e,Vu.empty(s),a);c.isEmpty()&&s&&(c=c.update({final:/* @__PURE__ */ new Set([s])})),c=assignElementsToGroups(c);let l=buildNodes(e,c),u=buildExpandPredicate(e,a),m=toComputedEdges(c.connections,u);linkNodesWithEdges(l,m);let h=topologicalSort$1({nodes:l,edges:m}),g=applyCustomElementProperties(a,applyViewRuleStyles(a,h.nodes)),_=Me(a,isViewRuleAutoLayout$1),v=buildElementNotations(g),y=collectRankConstraints(a,g);return calcViewLayoutHash({...withResolvedRouting(i,e.$styles.defaults.view.routing),_stage:`computed`,autoLayout:{direction:_?.direction??`TB`,..._?.nodeSep&&{nodeSep:_.nodeSep},..._?.rankSep&&{rankSep:_.rankSep}},edges:applyCustomRelationProperties(a,g,h.edges,e),nodes:p(g,e=>(e.icon===`none`&&delete e.icon,e)),...v.length>0&&{notation:{nodes:v}},...y.length>0&&{ranks:y}})}function collectRankConstraints(e,t){let r=[];for(let i of e){if(!isViewRuleRank$1(i)||i.targets.length===0)continue;let e=Ue(i.targets.map(elementExprToPredicate)),a=N(t,D(e),p(e=>e.id));k(a,1)&&r.push({type:i.rank,nodes:a})}return r}function assignElementsToGroups(e){if(e.groups.length===0)return e;let t=new I.default(()=>/* @__PURE__ */ new Set),r=/* @__PURE__ */ new Map,isAncestorAssigned=e=>{for(let i of e.ancestors()){let a=r.get(i);if(a)return r.set(e,a),t.get(a).add(e),!0}return!1},isDescendantAssigned=e=>{for(let i of e.descendants(`asc`)){let a=r.get(i);if(a)return r.set(e,a),t.get(a).add(e),!0}return!1};if(N(sortParentsFirst([...e.explicitFirstSeenIn.keys()]),Ae(i=>{if(!isAncestorAssigned(i)){let a=nonNullable(e.explicitFirstSeenIn.get(i));r.set(i,a),t.get(a).add(i)}})),N(sortParentsFirst([...e.lastSeenIn.keys()]),D(e=>!r.has(e)),Ae(i=>{if(isAncestorAssigned(i)||isDescendantAssigned(i))return;let a=nonNullable(e.lastSeenIn.get(i));r.set(i,a),t.get(a).add(i)})),t.size===0)return e;let i=e.groups.map(e=>{let r=t.get(e.id);return r?e.update(r):e});return e.update({groups:i})}function unsafeComputeView(e,t){switch(!0){case isElementView$1(e):return computeElementView(t,e);case isDeploymentView$1(e):return computeDeploymentView(t,e);case isDynamicView$1(e):return computeDynamicView(t,e);default:nonexhaustive(e)}}function computeView(e,t){try{return{isSuccess:!0,view:unsafeComputeView(e,t)}}catch(e){return{isSuccess:!1,error:e instanceof Error?e:/* @__PURE__ */ Error(`Unknown error: ${e}`),view:void 0}}}function computeParsedModelData(e){let t=new Pa(e),{views:r,_stage:i,...a}=e,s=ae(r,e=>unsafeComputeView(e,t));return{[Vi]:`computed`,...a,views:s}}function computeLikeC4Model(e){return new Pa(computeParsedModelData(e))}function resolveRulesExtendedViews(e){let t=new Rt({type:`directed`}),r=[];for(let i of Fe(e))t.addNode(i.id,{view:i}),isExtendsElementView(i)&&r.push(i);if(r.length===0)return e;for(let e of r)t.hasNode(e.extends)?(0,Sa.default)(t,e.id,e.extends)?console.warn(`View "${e.id}" extends from "${e.extends}" which creates a cycle`):t.addDirectedEdge(e.id,e.extends):console.warn(`View "${e.id}" extends from "${e.extends}" which does not exist`);return(0,xa.topologicalSort)(t).reverse().reduce((e,r)=>{let i=t.getNodeAttribute(r,`view`);if(!isExtendsElementView(i))return e[i.id]=i,e;let a=e[i.extends];if(!a||!isElementView$1(a))return e;let s=E([...a.tags??[],...i.tags??[]]),c=[...a.links??[],...i.links??[]],{order:l,...u}=a;return e[i.id]={...u,...i,title:i.title??a.title??null,description:i.description??a.description??null,tags:s,links:isNonEmptyArray(c)?c:null,rules:[...a.rules,...i.rules]},e},{})}const keysCount=e=>Te(e).length,vd=/* @__PURE__ */ e(e=>stringHash$1(e),`nodeId`);function computeProjectsView(e){let t=buildNodesForEachModel(e),key=(e,t)=>`${e}->${t}`,r=new I.default(e=>{let[t,r]=e.split(`->`);return{from:t,to:r,relationships:/* @__PURE__ */ new Set}}),relationshipsFromTo=(e,t)=>r.get(key(e,t)).relationships,processImportedElement=(e,t)=>{let r=t.projectId;invariant(r!==e.projectId,`Imported element must have a different project id`);let i=relationshipsFromTo(e.projectId,r);for(let r of t.incoming(`direct`))r.source.projectId===e.projectId&&i.add(r);let a=relationshipsFromTo(r,e.projectId);for(let r of t.outgoing(`direct`))r.target.projectId===e.projectId&&a.add(r)};for(let t of e)if(!w(t.$data.imports))for(let[e,r]of M(t.$data.imports))for(let i of r){let r=GlobalFqn(e,i.id);processImportedElement(t,nonNullable(t.findElement(r),`Element ${i.id} from project ${e} not found in model ${t.projectId}`))}let i=Array.from(r.entries()).filter(([e,{relationships:t}])=>t.size>0).map(([e,{from:t,to:r,relationships:i}])=>{let a=[...i];invariant(k(a,1),`Relationships set must have at least one relationship`);let s={id:stringHash$1(e),source:vd(t),target:vd(r),projectId:t,relations:p(a,A(`id`)),label:null,color:`gray`,parent:null,line:`solid`,tags:E(P(a,A(`tags`)))},c=F(a);return c&&(s.label=c.title,s.description=/* @__PURE__ */ preferSummary(c.$relationship)??null,s.technology=c.technology,s.color=c.color,s.line=c.line,c.kind&&(s.kind=c.kind),c.$relationship.navigateTo&&(s.navigateTo=c.$relationship.navigateTo)),s});linkNodesWithEdges(t,i);let a=topologicalSort$1({nodes:t,edges:i});return{id:`projects-view`,[Hi]:`projects`,[Vi]:`computed`,title:`Projects`,description:{txt:`Overview of all projects and their relationships`},autoLayout:{direction:`TB`},...a}}function buildNodesForEachModel(e){let t=/* @__PURE__ */ new Map;for(let r of e){let e=ProjectId(r.projectId),i={id:vd(e),kind:`@project`,parent:null,projectId:e,title:r.project.title??r.project.id,description:{txt:[`Elements: ${keysCount(r.$data.elements)}`,`Relationships: ${keysCount(r.$data.relations)}`,`Views: ${keysCount(r.$data.views)}`].join(`
|
|
82
|
+
`)},shape:`rectangle`,children:[],inEdges:[],outEdges:[],color:`primary`,level:0,style:{},tags:[]};t.set(i.id,i)}return t}const asTypedExpr=e=>e;function $expr(e){if(!S(e))return e;if(e===`*`)return asTypedExpr({wildcard:!0});if(e.startsWith(`->`))return e.endsWith(`->`)?asTypedExpr({inout:$expr(e.replace(/->/g,``).trim())}):asTypedExpr({incoming:$expr(e.replace(`-> `,``))});if(e.endsWith(` ->`))return asTypedExpr({outgoing:$expr(e.replace(` ->`,``))});if(e.includes(` <-> `)){let[t,r]=e.split(` <-> `);return asTypedExpr({source:$expr(t),target:$expr(r),isBidirectional:!0})}if(e.includes(` -> `)){let[t,r]=e.split(` -> `);return asTypedExpr({source:$expr(t),target:$expr(r)})}return e.endsWith(`._`)?asTypedExpr({ref:{model:e.replace(`._`,``)},selector:`expanded`}):e.endsWith(`.**`)?asTypedExpr({ref:{model:e.replace(`.**`,``)},selector:`descendants`}):e.endsWith(`.*`)?asTypedExpr({ref:{model:e.replace(`.*`,``)},selector:`children`}):asTypedExpr({ref:{model:e}})}function computeAdhocView(e,t){return{...computeElementView(e,{id:ViewId(`adhoc`),_stage:`parsed`,_type:`element`,rules:t,title:null,description:null}),_type:`adhoc`,_stage:`computed`}}const yd=q.getChild(`LanguageServices`),bd=/* @__PURE__ */ e(e=>e.severity===Lr.Error,`isErrorDiagnostic`);var DefaultLikeC4LanguageServices=class{services;builder;editor;projectsManager;workspaceManager;constructor(e){this.services=e,this.builder=e.likec4.ModelBuilder,this.projectsManager=e.shared.workspace.ProjectsManager,this.workspaceManager=e.shared.workspace.WorkspaceManager,this.editor=e.likec4.ModelChanges}get views(){return this.services.likec4.Views}get workspaceUri(){try{return this.workspaceManager.workspaceUri}catch(e){return yd.warn(`Failed to get workspace URI, using default folder`,{error:e}),R.file(`/`)}}get workspacePath(){return this.workspaceUri.fsPath}projects(){let e=this.services.shared.workspace.ProjectsManager,t=N(this.services.shared.workspace.LangiumDocuments.groupedByProject(),M(),p(([t,r])=>{let i=t,{folderUri:a,config:s}=e.getProject(i);return{id:i,folder:a,path:this.workspaceManager.relativePath(a),title:s.title??s.name,documents:p(r,A(`uri`)),config:s}}));if(k(t,2)&&e.defaultProjectId){let r=t.findIndex(t=>t.id===e.defaultProjectId);if(r>0){let[e]=t.splice(r,1);return[e,...t]}return t}if(k(t,1))return t;let{id:r,folderUri:i,config:a}=e.default;return[{id:r,folder:i,path:this.workspaceManager.relativePath(i),title:a.title??a.name,documents:[],config:a}]}project(e){let{id:t,folderUri:r,config:i}=this.projectsManager.ensureProject(e),a=p(this.services.shared.workspace.LangiumDocuments.projectDocuments(t).toArray(),A(`uri`));return{id:t,folder:r,path:this.workspaceManager.relativePath(r),title:i.title??i.name,documents:a,config:i}}async diagrams(e,t){let r=this.projectsManager.ensureProjectId(e);return await this.views.diagrams(r,t)}async computedModel(e,t){let r=this.projectsManager.ensureProjectId(e);return await this.builder.computeModel(r,t)}async layoutedModel(e,t){let r=this.projectsManager.ensureProjectId(e),i=await this.builder.computeModel(r,t);if(!i)throw Error(`Failed to compute model, empty project?`);let a=await this.views.layoutAllViews(r,t);return Pa.create({...i.$data,_stage:`layouted`,views:N(a,p(A(`diagram`)),Pe(A(`id`)))})}async projectsOverview(e){let t=this.services.shared.workspace.ProjectsManager.all,r=[];for(let i of t){let t=await this.builder.computeModel(i,e);if(e?.isCancellationRequested)throw Error(`Operation cancelled`);t===Pa.EMPTY?yd.debug(`Project ${i} is empty, skipping`):r.push(t)}if(!k(r,1))throw Error(`No models found`);let i=computeProjectsView(r);return await this.views.layouter.layoutProjectsView(i)}getErrors(){return N(this.services.shared.workspace.LangiumDocuments.userDocuments.toArray(),P(e=>N(e.diagnostics??[],D(bd),p(({message:t,range:r})=>({message:typeof t==`string`?t:t.value,line:r.start.line,range:r,sourceFsPath:e.uri.fsPath})))))}locate(e){switch(!0){case`element`in e:return this.services.likec4.ModelLocator.locateElement(e.element,e.projectId);case`relation`in e:return this.services.likec4.ModelLocator.locateRelation(e.relation,e.projectId);case`view`in e:return this.services.likec4.ModelLocator.locateView(e.view,e.projectId);case`deployment`in e:return this.services.likec4.ModelLocator.locateDeploymentElement(e.deployment,e.projectId);default:nonexhaustive(e)}}documentText(e){return this.services.shared.workspace.LangiumDocuments.getDocument(R.parse(e))?.textDocument.getText()}async format(e){let t=this.services.shared.workspace.LangiumDocuments,r=this.services.lsp.Formatter,i=buildFormattingOptions(e),a=this.collectDocumentsToFormat(t,e);a.sort((e,t)=>e.uri.toString().localeCompare(t.uri.toString()));let s=/* @__PURE__ */ new Map;for(let e of a){let t=e.uri.toString(),a=await r.formatDocument(e,{options:i,textDocument:{uri:t}}),c=a.length===0?e.textDocument.getText():on.applyEdits(e.textDocument,a);s.set(t,c)}return s}collectDocumentsToFormat(e,t){let r=t?.projectIds??[],i=t?.documentUris??[],a=/* @__PURE__ */ new Map;if(r.length>0)for(let t of r)for(let r of e.projectDocuments(t))a.set(r.uri.toString(),r);else if(i.length===0)for(let t of this.projectsManager.all)for(let r of e.projectDocuments(t))a.set(r.uri.toString(),r);for(let t of i){if(a.has(t))continue;let r;try{r=e.getDocument(R.parse(t))}catch{yd.warn(`format: skipping unknown document ${t}`);continue}isLikeC4LangiumDocument(r)?a.set(t,r):yd.warn(`format: skipping unknown document ${t}`)}return[...a.values()]}async dispose(){try{yd.debug(`disposing LikeC4LanguageServices`),this.services.likec4.FqnIndex.dispose(),this.services.likec4.DeploymentsIndex.dispose(),this.services.likec4.ModelParser.dispose(),this.services.likec4.ModelBuilder.dispose(),this.services.likec4.Views.dispose(),this.services.likec4.LastSeen.dispose(),this.services.Rpc.dispose(),this.services.shared.workspace.ManualLayouts.dispose(),this.services.shared.workspace.ProjectsManager.dispose(),await this.services.shared.workspace.FileSystemWatcher.dispose()}catch(e){yd.error(loggable(e))}finally{yd.debug(`LikeC4LanguageServices disposed`)}}};function buildFormattingOptions(e){return{tabSize:e?.tabSize??2,insertSpaces:e?.insertSpaces??!0,...e?.trimTrailingWhitespace!=null&&{trimTrailingWhitespace:e.trimTrailingWhitespace},...e?.insertFinalNewline!=null&&{insertFinalNewline:e.insertFinalNewline},...e?.trimFinalNewlines!=null&&{trimFinalNewlines:e.trimFinalNewlines}}}var LikeC4CodeLensProvider=class{services;constructor(e){this.services=e}async provideCodeLens(e,t,r){if(!isLikeC4LangiumDocument(e))return;let i=e.parseResult.value.views.flatMap(e=>e.views);return i.length===0?[]:(r&&await Yt(r),i.flatMap(e=>{let t=bu.readId(e),r=e.$cstNode?.range;if(!r||!t)return[];let i=projectIdFrom(e);return{range:{start:r.start,end:{line:r.start.line,character:r.start.character+4}},command:{command:`likec4.open-preview`,arguments:[t,i],title:`open preview`}}}))}};function isCompletionForPojectName(e,t){return zn(t.feature)&&t.property===`project`&&isImportsFromPoject(e.node)}const xd=`view_\${CURRENT_MINUTE}_\${CURRENT_SECOND} {
|
|
83
|
+
title 'Untitled'
|
|
84
|
+
|
|
85
|
+
include \${0:*}
|
|
86
|
+
}`;var LikeC4CompletionProvider=class extends fn{services;constructor(e){super(e),this.services=e}completionOptions={triggerCharacters:[`.`,`#`],allCommitCharacters:[` `,` `,`
|
|
87
|
+
`]};completionFor(e,t,r){switch(!0){case Pn(t.feature):return this.completionForKeyword(e,t.feature,r);case Hn(t.feature)&&!!e.node:return this.completionForCrossReference(e,t,r);case isCompletionForPojectName(e,t):return this.completionForImportedProject(e,r)}}completionForKeyword(e,t,r){if(!this.filterKeyword(e,t))return;let acceptReplacing=(i,a)=>{let s=this.buildCompletionTextEdit(e,t.value,a);s&&r(e,{label:t.value,insertTextFormat:Rr.Snippet,...i,textEdit:s})},acceptProperty=e=>{acceptReplacing({detail:`Insert ${t.value} property`,kind:Ir.Property},`${t.value} ${e}`)},acceptSnippet=({insertText:e,...r})=>{acceptReplacing({detail:`Insert ${t.value}`,kind:Ir.Snippet,...r},`${t.value} ${e}`)},acceptPropertyAndSuggest=e=>{acceptProperty(`\${1|${e.join(`,`)}|}$0`)};switch(!0){case t.value===`import`:acceptSnippet({insertText:`{ $0 } from '\${1|${this.services.shared.workspace.ProjectsManager.all.join(`,`)}|}'`});break;case t.value===`deployment`&&hn(e.node,isModelViews):acceptSnippet({detail:`Insert deployment view`,kind:Ir.Class,insertText:`view ${xd}`});break;case t.value===`dynamic`&&hn(e.node,isModelViews):acceptSnippet({detail:`Insert dynamic view`,kind:Ir.Class,insertText:`view ${xd}`});break;case t.value===`view`&&hn(e.node,isModelViews):acceptSnippet({detail:`Insert element view`,kind:Ir.Class,insertText:xd});break;case t.value===`opacity`:acceptPropertyAndSuggest([`0%`,`20%`,`60%`,`100%`]);break;case t.value===`shape`:acceptPropertyAndSuggest(Ni);break;case[`color`,`iconColor`].includes(t.value):acceptPropertyAndSuggest(Pi);break;case[`size`,`textSize`,`padding`].includes(t.value):acceptPropertyAndSuggest(ki);break;case t.value===`sizing`:acceptPropertyAndSuggest(ji);break;case t.value===`border`:acceptPropertyAndSuggest(Mi);break;case t.value===`autoLayout`:acceptPropertyAndSuggest([`TopBottom`,`BottomTop`,`LeftRight`,`RightLeft`]);break;case[`title`,`description`,`technology`,`summary`,`notes`,`notation`].includes(t.value):acceptProperty(`'$0'`);break;case t.value===`metadata`:acceptProperty(`{
|
|
88
|
+
$0
|
|
89
|
+
}`);break;case[`views`,`specification`,`model`,`deployment`,`with`].includes(t.value):acceptSnippet({kind:Ir.Module,insertText:`{
|
|
90
|
+
$0
|
|
91
|
+
}`});break;case t.value===`group`:acceptSnippet({kind:Ir.Module,insertText:`'\${1:Title}' {
|
|
92
|
+
$0
|
|
93
|
+
}`});break;case[`par`,`parallel`].includes(t.value):acceptSnippet({detail:`Insert parallel steps`,kind:Ir.Module,insertText:`{
|
|
94
|
+
$0
|
|
95
|
+
}`});break;case t.value===`try`&&hn(e.node,isDynamicViewBody):acceptSnippet({detail:`Insert try-catch flow`,kind:Ir.Module,insertText:[`'critical-path' {`,` $0`,`} catch 'handling' {`,`} finally 'cleanup' {`,`}`].join(`
|
|
96
|
+
`)});break;case t.value===`alt`&&hn(e.node,isDynamicViewBody):acceptSnippet({detail:`Insert alternative flow`,kind:Ir.Module,insertText:[`{`,` when 'condition' {`,` $0`,` }`,`}`].join(`
|
|
97
|
+
`)});break;case t.value===`style`&&e.node&&hn(e.node,isGlobalStyle):acceptSnippet({kind:Ir.Module,insertText:`\${1:name} \${2:*} {
|
|
98
|
+
$0
|
|
99
|
+
}`});break;case t.value===`style`&&e.node&&hn(e.node,Ue([isModelViews,isGlobalStyleGroup])):acceptSnippet({kind:Ir.Module,insertText:`\${1:*} {
|
|
100
|
+
$0
|
|
101
|
+
}`});break;case t.value===`style`:acceptSnippet({kind:Ir.Module,insertText:`{
|
|
102
|
+
$0
|
|
103
|
+
}`});break;case t.value===`extend`:acceptSnippet({detail:`Extend another view`,kind:Ir.Class,insertText:`$1 {
|
|
104
|
+
$0
|
|
105
|
+
}`});break;case t.value===`mode`:acceptPropertyAndSuggest([`sequence`,`diagram`]);break;case[`include`,`exclude`].includes(t.value):acceptReplacing({kind:Ir.Operator,detail:`Insert ${t.value} predicate`,insertTextFormat:Rr.PlainText},`${t.value} `);break;default:r(e,{label:t.value,kind:this.getKeywordCompletionItemKind(t),detail:`Keyword`,sortText:`1`})}}completionForImportedProject(e,t){let r=this.services.shared.workspace.ProjectsManager,i=e.document.textDocument,a={start:i.positionAt(e.tokenOffset),end:i.positionAt(e.tokenEndOffset)},s=i.getText(a),c=w(s)?`'`:s.substring(0,1);for(let i of r.all){let r=c+i+c;t(e,{label:i,kind:Ir.Folder,insertText:r,filterText:r,textEdit:Wr.replace(a,r),detail:`Project`,sortText:`0_`+i})}}},LikeC4DocumentHighlightProvider=class extends In{createDocumentHighlight(e){return Dr.create(e.segment.range,Or.Read)}},LikeC4DocumentLinkProvider=class{services;constructor(e){this.services=e}async getDocumentLinks(e,t,r=Er.None){if(!isLikeC4UserDocument(e)||this.services.shared.workspace.ProjectsManager.isExcluded(e))return[];let i=[];for(let t of mn(e.parseResult.value).filter(isLinkProperty)){await Yt(r);try{let r=dn(t.$cstNode,`value`)?.range,a=r&&this.resolveLink(e,t.value);a&&nr(a)&&i.push({range:r,target:a})}catch(e){logWarnError(e)}}return i}resolveLink(e,t){if(nr(t)||er(t))return t;if(Qn(t))return Xn(e.uri.toString(),`../`,t);let r=this.services.shared.workspace.ProjectsManager.getProject(e).folderUri;return Xn(r.toString(),t)}relativeLink(e,t){if(er(t))return $n(t);if(Qn(t)){let r=this.services.shared.workspace.ProjectsManager.getProject(e).folderUri.toString(),i=new URL(e.uri.toString()),a=new URL(t,i).toString();return $n(Zn(a,r))}return null}},LikeC4DocumentSymbolProvider=class{services;nodeKindProvider;nameProvider;parser;locator;logger=q.getChild(`DocumentSymbolProvider`);constructor(e){this.services=e,this.nodeKindProvider=e.shared.lsp.NodeKindProvider,this.parser=e.likec4.ModelParser,this.locator=e.likec4.ModelLocator,this.nameProvider=e.references.NameProvider}async getSymbols(e,t,r=Er.None){if(!isLikeC4LangiumDocument(e)||this.services.shared.workspace.ProjectsManager.isExcluded(e))return[];let{parseResult:{value:{specifications:i,models:a,deployments:s,views:c,likec4lib:l}}}=e,u=[],p=[...l.map(e=>()=>this.getLikec4LibSymbol(e)),...i.map(e=>()=>this.getSpecSymbol(e)),...a.map(e=>()=>this.getModelSymbol(e)),...s.map(e=>()=>this.getDeploymentModelSymbol(e)),...c.map(e=>()=>this.getModelViewsSymbol(e))];for(let e of p){await Yt(r);try{let t=e();t&&u.push(...t)}catch(e){this.logger.warn(loggable(e))}}return u}getLikec4LibSymbol(e){let t=e?.$cstNode;if(!t)return[];let r=e.icons.map(e=>this.getLibIconSymbol(e)).filter(j);return r.length===0?[]:[{kind:Ur.Namespace,name:`icons`,range:t.range,selectionRange:Zt(t,`icons`)?.range??t.range,children:r}]}getSpecSymbol(e){let t=e?.$cstNode;if(!t)return[];let r=dn(t,`name`);if(!r)return[];let i=N([...e.elements,...e.deploymentNodes,...e.tags,...e.relationships],p(e=>{try{if(isSpecificationElementKind(e)||isSpecificationRelationshipKind(e)||isSpecificationDeploymentNodeKind(e))return this.getKindSymbol(e);if(isSpecificationTag(e))return this.getTagSymbol(e)}catch(e){return this.logger.warn(loggable(e)),null}nonexhaustive(e)}),D(j));return i.length===0?[]:[{kind:Ur.Namespace,name:e.name,range:t.range,selectionRange:r.range,children:i}]}getModelSymbol(e){let t=e.$cstNode;if(!t)return[];let r=dn(t,`name`);return r?[{kind:this.symbolKind(e),name:e.name,range:t.range,selectionRange:r.range,children:e.elements.flatMap(e=>isExtendRelation(e)?[]:this.getElementsSymbol(e))}]:[]}getDeploymentModelSymbol(e){let t=e.$cstNode;if(!t)return[];let r=dn(t,`name`);return r?[{kind:this.symbolKind(e),name:e.name,range:t.range,selectionRange:r.range,children:e.elements.flatMap(e=>this.getDeploymentElementSymbol(e))}]:[]}getElementsSymbol(e,t){try{if(isExtendElement(e))return this.getExtendElementSymbol(e);if(isElement(e))return this.getElementSymbol(e)}catch(e){this.logger.getChild(`getElementsSymbol`).warn(loggable(e))}return[]}getExtendElementSymbol(e){let t=e.$cstNode,r=e.element.$cstNode,i=e.body;return!t||!r?[]:[{kind:this.symbolKind(e),name:readStrictFqn(e.element),range:t.range,selectionRange:r.range,children:i.elements.flatMap(t=>this.getElementsSymbol(t,readStrictFqn(e.element)))}]}getElementSymbol(e){let t=e.$cstNode,r=dn(t,`name`);if(!r||!t)return[];let i=e.name,a=`(${e.kind.$refText})`;return[{kind:this.symbolKind(e),name:i,range:t.range,selectionRange:r.range,detail:a,children:e.body?.elements.flatMap(e=>this.getElementsSymbol(e))??[]}]}getModelViewsSymbol(e){let t=e.$cstNode,r=dn(t,`name`);return!r||!t?[]:[{kind:this.symbolKind(e),name:e.name,range:t.range,selectionRange:r.range,children:e.views.flatMap(e=>this.getViewSymbol(e))}]}getKindSymbol(e){return!e.$cstNode||!e.kind.$cstNode||w(e.kind.name)?null:{kind:this.symbolKind(e),name:e.kind.name,range:e.$cstNode.range,selectionRange:e.kind.$cstNode.range}}getTagSymbol(e){return!e.$cstNode||!e.tag.$cstNode||w(e.tag.name)?null:{kind:this.symbolKind(e),name:`#`+e.tag.name,range:e.$cstNode.range,selectionRange:e.tag.$cstNode.range}}getLibIconSymbol(e){return!e.$cstNode||w(e.name)?null:{kind:this.symbolKind(e),name:e.name,range:e.$cstNode.range,selectionRange:e.$cstNode.range}}getViewSymbol(e){let t=e?.$cstNode;if(!t)return[];let r=e.name?dn(t,`name`):null;return r?[{kind:this.symbolKind(e),name:r.text,range:t.range,selectionRange:r.range,children:[]}]:[]}getDeploymentElementSymbol(e){try{if(isDeploymentNode(e))return this.getDeploymentNodeSymbol(e);if(isDeployedInstance(e))return this.getDeployedInstanceSymbol(e);if(isExtendDeployment(e))return[]}catch(e){this.logger.getChild(`getDeploymentElementSymbol`).warn(loggable(e))}return[]}getDeploymentNodeSymbol(e){let t=e.$cstNode,r=this.nameProvider.getNameNode(e);if(!r||!t)return[];let i=this.nameProvider.getNameStrict(e),a=`(${e.kind.$refText})`;return[{kind:this.symbolKind(e),name:i,range:t.range,selectionRange:r.range,detail:a,children:e.body?.elements.flatMap(e=>this.getDeploymentElementSymbol(e))??[]}]}getDeployedInstanceSymbol(e){let t=e.$cstNode,r=this.nameProvider.getNameNode(e);if(!r||!t)return[];let i=$t(e),a=this.parser.forDocument(i).parseDeployedInstance(e),s=this.nameProvider.getNameStrict(e),c=`instance of `+a.element.model;return[{kind:this.symbolKind(e),name:s,range:t.range,selectionRange:r.range,detail:c,children:[]}]}symbolKind(e){return this.nodeKindProvider.getSymbolKind(e)}};const Sd=`
|
|
106
|
+
---
|
|
107
|
+
`;var LikeC4HoverProvider=class extends wn{services;parser;locator;constructor(e){super(e),this.services=e,this.parser=e.likec4.ModelParser,this.locator=e.likec4.ModelLocator}async getAstNodeHoverContent(e){let t=(await this.getAstNodeHover(e))?.contents;return typeof t==`object`&&`value`in t?t.value:void 0}getAstNodeHover(e){if(isTag(e))return{contents:{kind:`markdown`,value:"tag `"+e.name+"`"}};if(isElementKind(e))return{contents:{kind:`markdown`,value:"element kind `"+e.name+"`"}};if(isDeploymentNodeKind(e))return{contents:{kind:`markdown`,value:"deployment node `"+e.name+"`"}};if(isRelationshipKind(e))return{contents:{kind:`markdown`,value:"relationship kind `"+e.name+"`"}};try{if(isElement(e))return this.getElementHover(e);if(isDeploymentNode(e))return this.getDeploymentNodeHover(e);if(isDeployedInstance(e))return this.getDeployedInstanceHover(e)}catch(e){q.debug(loggable(e))}}getElementHover(e){let t=this.locator.getParsedElement(e);if(!t)return;let r=t.element,i=[`<sup>\`${r.id}\`</sup> `,`### ${r.title} `],a=/* @__PURE__ */ preferSummary(r);a&&i.push(``,(a.md??a.txt).split(`
|
|
108
|
+
`).join(`
|
|
109
|
+
`));let s=this.services.likec4.LastSeen.model(t.projectId)?.findElement(r.id),c=s&&this.getElementModelHover(s,t.projectId);return i.push(c||`
|
|
110
|
+
<small>_Model not processed yet, open any view to trigger_</small> `),{contents:{kind:`markdown`,value:i.join(`
|
|
111
|
+
`)}}}getElementModelHover(e,t){let r=[],i=[...e.incoming(`direct`)].length,a=[...e.outgoing(`direct`)].length;(i>0||a>0)&&r.push(Sd,`<small>**${i}** incoming, **${a}** outgoing relationships</small> `);let printViewLink=e=>{let r=[e.id,t],i=R.parse(`command:likec4.open-preview?${encodeURIComponent(JSON.stringify(r))}`);return` - [${e.titleOrId}](${i})`},s=[...e.scopedViews()].map(printViewLink);s.length>0&&r.push(Sd,`<small>Element views:</small>`,...s);let c=[...e.views()].map(t=>t.isScopedElementView()&&t.viewOf===e?null:printViewLink(t)).filter(l);if(c.length>0){let e=s.length>0?`Also appears in views:`:`Appears in views:`;r.push(s.length>0?``:Sd,`<small>${e}</small>`,...c,` `)}return r.length>0?r.join(`
|
|
112
|
+
`):void 0}getDeploymentNodeHover(e){let t=$t(e),r=this.parser.forDocument(t).parseDeploymentNode(e),i=[r.id+` `];r.title!==e.name&&i.push(`### ${r.title}`),i.push("deployment node `"+r.kind+"` ");let a=/* @__PURE__ */ preferSummary(r);return a&&i.push(``,a.md??a.txt),{contents:{kind:`markdown`,value:i.join(`
|
|
113
|
+
`)}}}getDeployedInstanceHover(e){let t=$t(e),r=this.parser.forDocument(t).parseDeployedInstance(e),[i,a]=H.isImportRef(r.element)?[r.element.project,r.element.model]:[t.likec4ProjectId,r.element.model],s=i?this.locator.getParsedElement(a,i):this.locator.getParsedElement(a),c=[r.id+` `,`instance of \`${H.flatten(r.element)}\``];return s&&c.push(`### ${s.element.title}`,"element kind `"+s.element.kind+"` "),{contents:{kind:`markdown`,value:c.join(`
|
|
114
|
+
`)}}}};function stripIndent(e){let t=e.match(/^[ \t]*(?=\S)/gm);if(!t)return e;let r=1/0;for(let e of t)r=Math.min(r,e.length);return r===0||r===1/0?e:e.replace(RegExp(`^[ \\t]{${r}}`,`gm`),``)}function dedent(e){return stripIndent(e.replace(/^(?:[ \t]*\r?\n)+|(?:\r?\n[ \t]*)+$/g,``))}const{findLeafNodeAtOffset:Cd,getStartlineNode:wd}=gn;var LikeC4CodeActionProvider=class{getCodeActions(e,t,r){let i=e.parseResult.value.$cstNode;if(!i||t.context.triggerKind!==Mr.Invoked)return;let a=e.textDocument.offsetAt(t.range.end),s=Cd(i,a);if(!s||s.hidden||!isMarkdownOrString(s.astNode))return;let c=s.astNode;if(c.text!==void 0){let t=wd(s),r=` `.repeat(t.range.start.character),i=s.text.slice(0,1).repeat(3),a=dedent(c.text).split(`
|
|
115
|
+
`).map(e=>r+` `+e);return[Ar.create(`Convert to Markdown`,{changes:{[e.textDocument.uri]:[Fr.replace(s.range,[i,...a,r+i].join(`
|
|
116
|
+
`))]}},jr.QuickFix)]}return[]}};const Td=q.getChild(`SemanticTokenProvider`),Ed={...Hr},Dd={...Vr};function createSemanticTypeMethods(e){let t=[],r=new Proxy({},{get(i,a){if(a===`modifier`)return e=>(t.push(e),r);if(a in Dd)return t.push(Dd[a]),r;if(a in Ed)return()=>e(Ed[a],t);throw Error(`Unknown semantic token type or modifier: ${a}`)}});return r}const Od=`Stop Highlighting`,stopHighlight=()=>{throw Od};var LikeC4SemanticTokenProvider=class extends Sn{services;rules=[];constructor(e){super(e),this.services=e,this.initRules()}initRules(){this.rules=[];let when=(e,t)=>{let r={predicate:e,highlightFn:t};this.rules.push(r)};when(isRelationshipKind,e=>{e.property(`name`).function()}),when(isAnyOf(isRelation,isOutgoingRelationExpr,isDeploymentRelation),e=>{e.property(`kind`).function()}),when(isLibIcon,e=>{e.property(`name`).definition.function(),stopHighlight()}),when(isAnyOf(isNavigateToProperty,isRelationNavigateToProperty),e=>{e.property(`value`).readonly.definition.interface()}),when(isWildcardExpression,e=>{e.cst().readonly.definition.variable(),stopHighlight()}),when(isFqnRefExpr,e=>{e.node.selector&&(e.node.ref.parent?e.property(`selector`).property():e.property(`selector`).readonly.definition.variable())}),when(isTagRef,e=>{e.cst().type()}),when(isRelationKindDotRef,e=>{e.cst().function()}),when(isWhereRelationKind,e=>{j(e.node.value?.$refText)&&e.property(`value`).function()}),when(isAnyOf(isWhereElementMetadata,isWhereRelationMetadata,isWhereRelationParticipantMetadata),e=>{e.keyword(`metadata`).keyword(),e.property(`key`).property()}),when(isAnyOf(isWhereElementTag,isWhereElementKind,isWhereRelationTag,isWhereRelationKind),e=>{j(e.node.value)&&e.property(`value`).readonly.definition.type()}),when(isAnyOf(isWhereRelationParticipantKind,isWhereRelationParticipantTag,isWhereRelationParticipantMetadata),e=>{e.property(`participant`).keyword()}),when(isElementKindExpression,e=>{j(e.node.kind)&&e.property(`kind`).definition.type()}),when(isAnyOf(isGlobalStyleGroup,isGlobalStyle),e=>{e.property(`id`).readonly.definition.variable()}),when(isViewRuleGlobalStyle,e=>{e.property(`style`).readonly.definition.variable()}),when(isAnyOf(isGlobalPredicateGroup,isGlobalDynamicPredicateGroup),e=>{e.property(`name`).readonly.definition.variable()}),when(isViewRuleGlobalPredicateRef,e=>{e.property(`predicate`).readonly.definition.variable()}),when(isElementTagExpression,e=>{j(e.node.tag)&&e.property(`tag`).definition.type()}),when(isAnyOf(isFqnRef,isStrictFqnRef),e=>{if(e.node.parent){e.property(`value`).property();return}let t=e.node.value.$refText;t!==`this`&&t!==`it`&&e.property(`value`).readonly.definition.variable()}),when(isStrictFqnElementRef,e=>{e.node.parent?e.property(`el`).property():e.property(`el`).readonly.definition.variable()}),when(isSpecificationColor,e=>{e.keyword(`color`).keyword(),e.property(`name`).readonly.declaration.type()}),when(isSpecificationTag,e=>{(j(e.node.color)||j(e.node.themeColor)||j(e.node.customColor))&&e.keyword(`color`).property(),j(e.node.customColor)&&e.property(`customColor`).enum(),j(e.node.themeColor)&&e.property(`themeColor`).enum()}),when(isAnyOf(isSpecificationElementKind,isSpecificationRelationshipKind,isSpecificationDeploymentNodeKind),e=>{e.property(`kind`).readonly.declaration.type()}),when(isTag,e=>{e.property(`name`).definition.type()}),when(isOpacityProperty,e=>{e.property(`value`).number()}),when(isIconProperty,e=>{e.node.libicon||e.node.value===`none`?e.property(e.node.libicon?`libicon`:`value`).defaultLibrary.enum():e.property(`value`).string()}),when(isLinkProperty,e=>{j(e.node.value)&&e.property(`value`).string()}),when(isAnyOf(isColorProperty,isIconColorProperty),e=>{j(e.node.customColor)&&e.property(`customColor`).enum(),j(e.node.themeColor)&&e.property(`themeColor`).enum()}),when(e=>isAnyProperty(e)&&!isAnyOf(isMetadataProperty,isElementStyleProperty,isRelationStyleProperty)(e)&&j(e.key),e=>e.property(`key`).property()),when(isAnyOf(isShapeProperty,isArrowProperty,isLineProperty,isBorderProperty,isSizeProperty,isIconPositionProperty,isIconSizeProperty,isSizingProperty,isDynamicViewDisplayVariantProperty),e=>{j(e.node.value)&&e.property(`value`).enum()})}highlightElement(e,t){if(isAnyOf(isElement,isDeploymentNode,isDeployedInstance)(e))return this.highlightNameAndKind(e);if(isLikeC4View(e))return this.highlightView(e);let r;for(let{predicate:t,highlightFn:i}of this.rules)if(t(e))try{r??=this.mark(e),i(r)}catch(t){if(t===Od)return`prune`;Td.warn(`Error highlighting node of type ${e._type}`,{error:t})}}highlightNameAndKind(e){this.mark(e).property(`name`).declaration.readonly.variable(),isDeployedInstance(e)||this.mark(e).property(`kind`).keyword(),isElement(e)?e.props.length>0&&this.mark(e).property(`props`).string():e.title&&this.mark(e).property(`title`).string()}highlightView(e){e.name&&this.mark(e).property(`name`).modifier(`local`).declaration.readonly.interface()}mark(e){let cst=t=>createSemanticTypeMethods((r,i)=>this.highlightToken({range:nonNullable(t??e.$cstNode,`AST node has no CST node`).range,type:r,modifier:i})),keyword=t=>createSemanticTypeMethods((r,i)=>this.highlightKeyword({node:e,keyword:t,type:r,modifier:i})),property=(t,r)=>createSemanticTypeMethods((i,a)=>this.highlightProperty({node:e,property:t,type:i,modifier:a,...r===void 0?{}:{index:r}}));return{node:e,cst,keyword,property}}};const kd=isAnyOf(isElement,isExtendElement);var FqnIndex=class extends ADisposable{services;projects;langiumDocuments;documentCache;workspaceCache;logger=q.getChild(`fqn-index`);constructor(e){super(),this.services=e,this.langiumDocuments=e.shared.workspace.LangiumDocuments,this.projects=e.shared.workspace.ProjectsManager,this.documentCache=new Ze.default(e=>this.createDocumentIndex(e)),this.workspaceCache=new Gn(e.shared,rn.IndexedContent),this.onDispose(e.shared.workspace.DocumentBuilder.onDocumentPhase(rn.IndexedContent,e=>{isLikeC4UserDocument(e)&&this.documentCache.delete(e)}))}documents(e){return this.langiumDocuments.projectDocuments(e).filter(e=>e.state>=rn.IndexedContent)}get(e){return e.state<rn.IndexedContent&&this.logger.warn(`document {doc} is in state {state}, expected at least IndexedContent ({expect}). This may lead to incorrect FQN resolution.`,{doc:L.basename(e.uri),state:e.state,expect:rn.IndexedContent}),this.documentCache.get(e)}resolve(e){return e.$type===`Imported`?this.getFqn(e.imported.ref):e.$type===`Element`?this.getFqn(e):this.services.likec4.DeploymentsIndex.getFqn(e)}getFqn(e){invariant(isElement(e)||isDeploymentElement(e));let t=xu.readId(e);if(j(t))return t;let r=$t(e);return r.state<rn.IndexedContent&&this.logger.warn(`document {doc} is not yet indexed, creating on the fly to resolve FQN for element {el}`,{el:e.name??e.$type,doc:L.basename(r.uri)}),invariant(isLikeC4LangiumDocument(r)),this.documentCache.get(r),nonNullable(xu.readId(e),`Element fqn must be set, invalid state`)}byFqn(e,t){return Cn(this.workspaceCache.get(`${e}:fqn:${t}`,()=>this.documents(e).flatMap(e=>this.get(e).byFqn(t)).toArray()))}rootElements(e){return Cn(this.workspaceCache.get(`${e}:rootElements`,()=>{let t=new Ye.default;for(let r of this.documents(e))for(let e of this.get(r).rootElements())t.set(e.name,e);return uniqueByName(t)}))}directChildrenOf(e,t){return Cn(this.workspaceCache.get(`${e}:directChildrenOf:${t}`,()=>{let r=new Ye.default;for(let i of this.documents(e))for(let e of this.get(i).children(t))r.set(e.name,e);return uniqueByName(r)}))}uniqueDescedants(e,t){return Cn(this.workspaceCache.get(`${e}:uniqueDescedants:${t}`,()=>{let r=new Ye.default,i=new Ye.default;for(let a of this.documents(e)){let e=this.get(a);for(let i of e.children(t))r.set(i.name,i);for(let r of e.descendants(t))i.set(r.name,r)}let a=uniqueByName(r),s=[...i.associations()].flatMap(([e,t])=>t.length===1&&!r.has(e)?t:[]);return[...a,...sortNaturalByFqn(s)]}))}createDocumentIndex(e){let t=e.parseResult.value.models.flatMap(e=>e.elements.filter(kd));if(t.length===0)return Ad.EMPTY;let r=e.likec4ProjectId??this.projects.ownerProjectId(e),i=[],a=new Ye.default,s=new Ye.default,c=new Ye.default,l=this.services.workspace.AstNodeDescriptionProvider,createAndSaveDescription=(t,i,a)=>{let s=Object.assign(l.createDescription(t,i,e),{id:a,likec4ProjectId:r});return xu.writeId(t,a),c.set(a,s),s};function traverseElement(e,t){let r=Fqn(e.name,t),c=createAndSaveDescription(e,e.name,r);t?a.set(t,c):i.push(c);let l=D(e.body?.elements??[],kd);if(!k(l,1))return[c];let u=P(l,e=>traverseElement(e,r));for(let e of u)s.set(r,e);return[c,...u]}function traverseExtendElement(e){let t=readStrictFqn(e.element),r=N(e.body?.elements??[],D(isElement),P(e=>traverseElement(e,t)));if(r.length!==0)for(let e of[t,...ancestorsFqn(t)])for(let t of r)s.set(e,t)}for(let r of t)try{if(isExtendElement(r)){traverseExtendElement(r);continue}traverseElement(r,null)}catch(t){this.logger.warn(`Error while traversing element {el} in document {doc}`,{el:r.$type,doc:L.basename(e.uri),error:t})}return new Ad(i,a,s,c,r)}};function compareNaturalByName(e,t){return compareNatural(e.name,t.name)}function uniqueByName(e){return[...e.associations()].flatMap(([e,t])=>t.length===1?t:[]).sort(compareNaturalByName)}var Ad=class DocumentFqnIndex{_rootElements;_children;_descendants;_byfqn;projectId;static EMPTY=new DocumentFqnIndex([],new Ye.default,new Ye.default,new Ye.default,Eu.DefaultProjectId);constructor(e,t,r,i,a){this._rootElements=e,this._children=t,this._descendants=r,this._byfqn=i,this.projectId=a}rootElements(){return this._rootElements}byFqn(e){return this._byfqn.get(e)??[]}children(e){return this._children.get(e)??[]}descendants(e){return this._descendants.get(e)??[]}};const jd=isAnyOf(isDeploymentElement,isExtendDeployment);var DeploymentsIndex=class extends FqnIndex{services;Names;logger=q.getChild(`deployments-index`);constructor(e){super(e),this.services=e,this.Names=e.references.NameProvider}createDocumentIndex(e){let t=e.parseResult.value.deployments.flatMap(e=>e.elements.filter(jd));if(t.length===0)return Ad.EMPTY;let r=e.likec4ProjectId??this.projects.ownerProjectId(e),i=[],a=new Ye.default,s=new Ye.default,c=new Ye.default,l=this.Names,u=this.services.workspace.AstNodeDescriptionProvider,createAndSaveDescription=(t,i,a)=>{let s={...u.createDescription(t,i,e),id:a,likec4ProjectId:r};return xu.writeId(t,a),c.set(a,s),s};function traverseElement(e,t){let r=l.getName(e);if(!j(r))return[];let c=Fqn(r,t),u=createAndSaveDescription(e,r,c);if(t?a.set(t,u):i.push(u),isDeployedInstance(e))return[u];let p=D(e.body?.elements??[],jd);if(!k(p,1))return[u];let m=P(p,e=>traverseElement(e,c));for(let e of m)s.set(c,e);return[u,...m]}function traverseExtend(e){let t=readStrictFqn(e.deploymentNode),r=N(e.body?.elements??[],D(jd),P(e=>traverseElement(e,t)));if(r.length!==0)for(let e of[t,...ancestorsFqn(t)])for(let t of r)s.set(e,t)}for(let r of t)try{if(isExtendDeployment(r)){traverseExtend(r);continue}traverseElement(r,null)}catch(t){this.logger.warn(`Error while traversing element {el} in document {doc}`,{el:r.$type,doc:L.basename(e.uri),error:t})}return new Ad(i,a,s,c,r)}};const Md=/^(aws|azure|gcp|tech):(.+)$/;function deriveTechnologyFromIcon(e){if(!e)return;let t=Md.exec(e);if(t)return t[2].replace(/-icon$/,``).split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function applyBidirectional(e,t){return t?{...e,isBidirectional:t,tail:e.tail??e.head??`normal`}:e}var MergedSpecification=class{specs={elements:{},deployments:{},relationships:{},colors:{}};tags;globals={predicates:{},dynamicPredicates:{},styles:{}};imports=new Ye.default(Set);projectId;inferTechFromIcon;constructor(e,t){let r={},i=[];for(let t of e){let{c4Specification:e,c4Globals:a,c4Imports:s}=t,c=t.likec4ProjectId;l(c)&&(i.length===0||i[0]!==c)&&i.push(c),Object.assign(r,e.tags),Object.assign(this.specs.elements,e.elements),Object.assign(this.specs.relationships,e.relationships),Object.assign(this.specs.colors,e.colors),Object.assign(this.specs.deployments,e.deployments),Object.assign(this.globals.predicates,a.predicates),Object.assign(this.globals.dynamicPredicates,a.dynamicPredicates),Object.assign(this.globals.styles,a.styles);for(let[e,t]of s)this.imports.set(e,t)}this.tags=assignTagColors(r),this.projectId=F(i),this.inferTechFromIcon=t?.inferTechFromIcon??!0}toModelElement=({tags:e,links:t,style:r,id:i,kind:a,title:s,description:c,technology:l,summary:u,metadata:p})=>{try{let m=this.specs.elements[a];if(!m)return q.warn`No kind '${a}' found for ${i}`,null;l??=m.technology,c??=m.description,u??=m.summary,t??=m.links,_(s)&&(s=m.title||nameFromFqn(i)),m.tags&&isNonEmptyArray(m.tags)&&(e=e?E([...m.tags,...e]):m.tags);let h=exact({...m.style,...r});return!l&&this.inferTechFromIcon&&(l=deriveTechnologyFromIcon(h.icon)),exact({metadata:p&&!w(p)?p:void 0,notation:m.notation,style:h,links:t,tags:e,summary:u,technology:l,description:c,title:s,kind:a,id:i})}catch(e){logWarnError(e)}return null};toModelRelation=({astPath:e,source:t,target:r,kind:i,links:a,id:s,title:c,tags:u,isBidirectional:p,...m})=>{if(l(i)&&this.specs.relationships[i]){let{multiple:e,tags:l,...h}=this.specs.relationships[i];return l&&isNonEmptyArray(l)&&(u=u?E([...l,...u]):l),applyBidirectional({...h,...m,...a&&{links:a},...u&&{tags:u},title:_(c)?h.title??c:c,source:t,target:r,kind:i,id:s},p)}return applyBidirectional({...a&&{links:a},...m,...u&&{tags:u},source:t,target:r,id:s,title:c},p)};toDeploymentElement=e=>{if(`element`in e&&!(`kind`in e))return{...e,element:H.flatten(e.element)};if(`element`in e)return q.warn`Invalid ParsedAstDeployment ${e.id}, has both element and kind properties`,null;try{let t=this.specs.deployments[e.kind];if(!t)return q.warn`No kind ${e.kind} found for ${e.id}`,null;let{id:r,style:i,title:a,...s}=e;return a=a===nameFromFqn(e.id)&&t.title?t.title:a,exact({...t,...s,title:a,style:exact({...t.style,...i}),id:r})}catch(e){logWarnError(e)}return null};toDeploymentRelation=({astPath:e,source:t,target:r,kind:i,links:a,id:s,tags:c,isBidirectional:u,...p})=>{if(l(i)&&this.specs.relationships[i]){let{multiple:e,tags:l,...m}=this.specs.relationships[i];return l&&isNonEmptyArray(l)&&(c=c?E([...l,...c]):l),applyBidirectional({...m,...p,...a&&{links:a},...c&&{tags:c},source:t,target:r,kind:i,id:s},u)}return applyBidirectional({...a&&{links:a},...p,...c&&{tags:c},source:t,target:r,id:s},u)}},LastSeenArtifacts=class extends ADisposable{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Map;#n=/* @__PURE__ */ new Map;constructor(e){super();let clearCache=()=>{this.#e.clear(),this.#t.clear(),this.#n.clear()};this.onDispose(e.shared.workspace.WorkspaceManager.onForceCleanCache(clearCache),Wn.create(clearCache))}rememberSpecification(e){return e.projectId&&this.#e.set(e.projectId,e),e}rememberModel(e){let t=e.projectId,r=e.$styles,i=this.#t.get(t);return(!i||!i.equals(r))&&this.#t.set(t,r),this.#n.set(t,e),e}specification(e){return this.#e.get(e)}styles(e){return this.#t.get(e)}model(e){return this.#n.get(e)}};function assignNavigateTo(e){let t=/* @__PURE__ */ new Map;for(let r of e)if(isElementView$1(r)&&r.viewOf&&C(r.extends)){let e=t.get(r.viewOf)??[];e.push(r.id),t.set(r.viewOf,e)}for(let{id:r,nodes:i}of e)for(let e of i){let i=e.modelRef;if(e.navigateTo||!i)continue;let a=Le(t.get(i)??[],e=>e!==r);a&&(e.navigateTo=a)}return e}function relationFingerprint({source:e,target:t,kind:r,title:i,isBidirectional:a}){let s=H.flatten(e),c=H.flatten(t);if(a&&c<s){let e=c;c=s,s=e}return stringHash(`extend-relation`,s,c,r??`default`,i??``,a?`bidirectional`:`directed`)}var MergedExtends=class{mergedData=/* @__PURE__ */ new Map;mergeMetadata(e,t){let r={...e};for(let[e,i]of Object.entries(t)){let t=r[e];if(t===void 0){r[e]=i;continue}let a=Array.isArray(t)?t:[t],s=Array.isArray(i)?i:[i],c=E([...a,...s]);r[e]=c.length===1?c[0]:c}return r}merge(e){for(let t of e){let{id:e,links:r,tags:i,metadata:a}=t,s=this.mergedData.get(e)??{links:[],tags:[],metadata:{}};r&&s.links.push(...r),i&&(s.tags=E([...s.tags,...i])),a&&(s.metadata=this.mergeMetadata(s.metadata,a)),this.mergedData.set(e,s)}}applyExtended(e){let t=this.mergedData.get(e.id);if(!t)return e;let r=t.links;e.links&&e.links.length>0&&(r=[...e.links,...r]);let i=t.tags;e.tags&&e.tags.length>0&&(i=E([...e.tags,...i]));let a=t.metadata;return e.metadata&&(a=this.mergeMetadata(e.metadata,t.metadata)),{...e,tags:k(i,1)?i:null,links:k(r,1)?r:null,...!w(a)&&{metadata:a}}}};function buildModelData(e,t,r){let i=new MergedSpecification(r,{inferTechFromIcon:t.config.inferTechnologyFromIcon??!0});i.projectId===t.id&&e.likec4.LastSeen.rememberSpecification(i);let a=ae(i.specs.colors,e=>computeColorValues(e.color)),s=/* @__PURE__ */ new Set,c=new MergedExtends,l=new MergedExtends,m=r.flatMap(e=>e.c4ExtendRelations),h=/* @__PURE__ */ new Set,scanMetadataKeys=e=>{e?.metadata&&Te(e.metadata).forEach(e=>s.add(e))},g=N(r,P(e=>(c.merge(e.c4ExtendElements),p(e.c4Elements,i.toModelElement))),D(j),sortParentsFirst,ve((e,t)=>{let r=parentFqn(t.id);return r&&C(e[r])?(q.debug`No parent found for ${t.id}`,e):(e[t.id]=c.applyExtended(t),scanMetadataKeys(e[t.id]),e)},{})),_=N(r,P(e=>p(e.c4Relations,i.toModelRelation)),D(e=>{if(!e)return!1;let t=H.flatten(e.source),r=H.flatten(e.target);return C(g[t])&&!isGlobalFqn(t)||C(g[r])&&!isGlobalFqn(r)?(q.debug`Invalid relation ${e.id}
|
|
117
|
+
source: ${t} resolved: ${!!g[t]}
|
|
118
|
+
target: ${r} resolved: ${!!g[r]}\n`,!1):!0}),p(e=>{let t=relationFingerprint(e),r=m.filter(e=>e.id===t);if(r.length===0)return e;r.forEach(e=>h.add(e.astPath));let i=e.tags?[...e.tags]:[],a=e.links?[...e.links]:[],s=e.metadata?{...e.metadata}:{};for(let e of r){if(e.tags&&i.push(...e.tags),e.links)for(let t of e.links)a.some(e=>e.url===t.url&&(e.title||``)===(t.title||``))||a.push(t);if(e.metadata)for(let[t,r]of Object.entries(e.metadata)){let e=s[t];if(e===void 0)s[t]=r;else{let i=Array.isArray(e)?e:[e],a=Array.isArray(r)?r:[r],c=E([...i,...a]);s[t]=c.length===1?c[0]:c}}}let c=E(i),l=a;return{...e,...k(c,1)&&{tags:c},...k(l,1)&&{links:l},...!w(s)&&{metadata:s}}}),Ae(scanMetadataKeys),Pe(A(`id`))),v=N(r,P(e=>(l.merge(e.c4ExtendDeployments),p(e.c4Deployments,i.toDeploymentElement))),D(j),sortParentsFirst,ve((e,t)=>{let r=parentFqn(t.id);return r&&C(e[r])?(q.debug`No parent found for deployment element ${t.id}`,e):(e[t.id]=isDeploymentNode$1(t)?l.applyExtended(t):t,scanMetadataKeys(e[t.id]),e)},{})),y=N(r,P(e=>p(e.c4DeploymentRelations,i.toDeploymentRelation)),D(e=>e?C(v[e.source.deployment])||C(v[e.target.deployment])?(q.debug`Invalid deployment relation ${e.id}
|
|
119
|
+
source: ${e.source.deployment} resolved: ${!!v[e.source.deployment]}
|
|
120
|
+
target: ${e.target.deployment} resolved: ${!!v[e.target.deployment]}\n`,!1):!0:!1),ve((e,t)=>T(e[t.id])?(q.debug`Duplicate deployment relation ${t.id}`,e):(scanMetadataKeys(t),e[t.id]=t,e),{}));function toC4View(e){let r=e.uri.toString();return e=>{let{id:i,title:a,description:s,astPath:c,...l}=e;return e._type===`element`&&C(a)&&`viewOf`in e&&(a=g[e.viewOf]?.title??null),C(a)&&i===`index`&&(a=`Landscape view`),{...u(l,e=>e===void 0),[Vi]:`parsed`,sourcePath:L.relative(t.folderUri,r),docUri:r,description:s,title:a,id:i}}}let b=r.flatMap(e=>p(e.c4Views,toC4View(e)));if(b.some(e=>e.id===`index`)||b.unshift({[Vi]:`parsed`,[Hi]:`element`,id:`index`,title:`Landscape view`,description:null,rules:[{include:[{wildcard:!0}]}]}),t.config.implicitViews===!0){let e=/* @__PURE__ */ new Set;for(let t of b)t._type===`element`&&`viewOf`in t&&t.viewOf&&e.add(t.viewOf);let t=new Set(b.map(e=>e.id));for(let r of Te(g)){if(e.has(r)||isGlobalFqn(r))continue;let i=`__`+r.replaceAll(`.`,`_`);t.has(i)||(t.add(i),b.push({[Vi]:`parsed`,[Hi]:`element`,id:i,viewOf:r,title:`Auto / ${(g[r]?.title??r).replaceAll(`
|
|
121
|
+
`,` `)}`,description:null,rules:[{include:[{wildcard:!0}]}]}))}}let x=N(b,Pe(A(`id`)));b.some(isExtendsElementView)&&(x=resolveRulesExtendedViews(x));for(let e of m)h.has(e.astPath)||q.warn(`Relation extend at ${e.astPath} does not match any relation in the model`);let S=ae(g,e=>e.title.includes(`\\/`)?{...e,title:e.title.replaceAll(`\\/`,`/`)}:e);return{data:{[Vi]:`parsed`,projectId:t.id,project:exact({id:t.id,title:t.config.title??t.config.name,styles:t.config.styles,contactPerson:t.config.contactPerson,metadata:t.config.metadata,manualLayouts:t.config.manualLayouts,inferTechnologyFromIcon:t.config.inferTechnologyFromIcon}),specification:{tags:i.tags,elements:i.specs.elements,relationships:ae(i.specs.relationships,({notation:e,technology:t,...r})=>({...e&&{notation:e},...t&&{technology:t},style:r})),deployments:i.specs.deployments,...s.size>0&&{metadataKeys:[...s].sort(compareNatural)},customColors:a},elements:S,relations:_,globals:i.globals,views:x,deployments:{elements:v,relations:y},imports:{}},imports:i.imports}}const Nd=q.getChild(`builder`);function isRequestedImportedElement(e,t){for(let r of e)if(t.id===r||t.id.startsWith(`${r}.`))return!0;return!1}function importedElementTitles(e){let t=/* @__PURE__ */ new Map;for(let[r,i]of M(e))for(let e of i)t.set(GlobalFqn(r,e.id),e.title);return t}function withImportedScopedViewTitles(e,t){let r=importedElementTitles(t);return r.size===0?e:ae(e,e=>{if(e._type===`element`&&e.title===null&&e.viewOf){let t=r.get(e.viewOf);if(t!==void 0)return{...e,title:t}}return e})}var DefaultLikeC4ModelBuilder=class extends ADisposable{services;projects;parser;listeners=[];cache;DocumentBuilder;manualLayouts;mutex;lastSeen;constructor(e){super(),this.services=e,this.projects=e.shared.workspace.ProjectsManager,this.parser=e.likec4.ModelParser,this.DocumentBuilder=e.shared.workspace.DocumentBuilder,this.mutex=e.shared.workspace.WorkspaceLock,this.manualLayouts=e.shared.workspace.ManualLayouts,this.lastSeen=e.likec4.LastSeen,this.cache=new ProjectModelCache(e),this.onDispose(this.cache,Wn.create(()=>{this.listeners.length=0}),this.DocumentBuilder.onUpdate((e,t)=>{t.length>0&&this.notifyListeners(t)}),e.shared.workspace.WorkspaceManager.onForceCleanCache(()=>{this.clearCache()}),this.manualLayouts.onManualLayoutUpdate(({projectId:e})=>{this.notifyListeners(e)}));let t=ue(y(),D(e=>isNotLikeC4Builtin(e)&&!this.projects.isExcluded(e)),p(e=>e.uri));this.onDispose(this.DocumentBuilder.onBuildPhase(rn.Validated,(e,r)=>{let i=t(e);i.length>0&&this.notifyListeners(i)})),Nd.debug`created`}unsafeSyncParseModelData(e){return this.cache.parsedData(e,()=>{let t=Nd.getChild(e);try{let r=this.projects.getProject(e),i=this.documents(e);return i.length===0?(t.trace`unsafeSyncParseModelData: ${`skipped due to no documents`}`,null):buildModelData(this.services,r,i)}catch(r){return t.warn(`unsafeSyncParseModelData failed for project ${e}`,{err:r}),null}})}unsafeSyncJoinedModelData(e){return this.cache.parsedJoinedData(e,()=>{let t=Nd.getChild(e),r=this.unsafeSyncParseModelData(e);if(!r)return null;if(r.imports.size===0)return t.trace(`unsafeSyncJoinedModelData: no imports`),r.data;t.trace(`unsafeSyncJoinedModelData: processing imports`);let i=[...r.imports.associations()].reduce((e,[t,r])=>{if(r.size===0)return e;let i=this.unsafeSyncParseModelData(t);if(i){let a=Fe(i.data.elements).filter(e=>isRequestedImportedElement(r,e));k(a,1)&&(e[t]=structuredClone(a))}return e},{});return{...r.data,imports:i,views:withImportedScopedViewTitles(r.data.views,i)}})}async parseModel(e,t){e=this.projects.ensureProjectId(e);let r=Nd.getChild(e),i=await this.mutex.read(async()=>(t?.isCancellationRequested&&await Yt(t),this.cache.parsedModel(e,()=>this.unsafeSyncJoinedModelData(e))));return i?Pa.create(i):(r.debug`parseModel: returning EMPTY`,Pa.EMPTY.asParsed)}unsafeSyncComputeModel(e,t){let r=this.cache.computedModel(e,t??null,()=>{let r=Nd.getChild(e),i=this.unsafeSyncJoinedModelData(e);if(!i)return e!==Eu.DefaultProjectId&&r.warn`unsafeSyncComputeModel: returning EMPTY`,null;r.debug(`computeModel${t?` with manual layouts`:``}: {status}`,{status:`computing`});let a=performanceMark(),s=Pa.create(i),c=[];for(let e of Fe(i.views)){let i=computeView(e,s);i.isSuccess?(t?.views[e.id]&&Object.assign(i.view,{hasManualLayout:!0}),c.push(i.view)):r.warn(loggable(i.error))}return assignNavigateTo(c),r.debug(`computeModel${t?` with manual layouts`:``}: {status} in ${a.pretty}`,{status:`completed`}),{...i,manualLayouts:{...t?.views},[Vi]:`computed`,views:Pe(c,A(`id`))}});return r?this.lastSeen.rememberModel(Pa.create(r)):Pa.EMPTY.asComputed}async computeModel(e,t){e=this.projects.ensureProjectId(e);let r=Nd.getChild(e);return await this.mutex.read(async()=>{t?.isCancellationRequested&&await Yt(t);let i=this.projects.getProject(e),a=await this.manualLayouts.read(i),s=this.unsafeSyncComputeModel(e,a);return s===Pa.EMPTY&&e!==Eu.DefaultProjectId&&r.warn(`computeModel returned EMPTY`),s})}onModelParsed(e){return this.listeners.push(e),Wn.create(()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)})}clearCache(){Nd.debug(`clear all caches`),this.cache.clear()}documents(e){return this.parser.documents(e).toArray()}notifyListeners(e){if(this.listeners.length===0)return;let t;t=b(e)?N(e,le(e=>this.projects.ownerProjectId(e)),M()):[[e,[]]];let r=this.listeners.slice();for(let e of r)for(let[r,i]of t)try{e(r,i)}catch(e){Nd.warn(loggable(e))}}},ProjectModelCache=class extends ln{constructor(e){super(e=>typeof e==`string`?e:e.id),this.toDispose.push(e.shared.workspace.DocumentBuilder.onDocumentPhase(rn.Validated,t=>{let r=e.shared.workspace.ProjectsManager.ownerProjectId(t);this.clear(r)}),e.shared.workspace.DocumentBuilder.onUpdate((t,r)=>{if(r.length>0){let t=e.shared.workspace.ProjectsManager,i=E(p(r,t.ownerProjectId.bind(t)));if(!k(i,1))return;Nd.trace`clear project caches for: ${i} (on delete ${r.map(e=>e.fsPath)})`;for(let e of i)this.clear(e)}}))}parsedData(e,t){let r=`parsed-data`,i=this.get(e,r);if(i!==void 0)return Nd.trace`cache hit project ${e} key: ${r}`,i;Nd.trace`cache miss project ${e} key: ${r}`;let a=t();return a!==void 0&&this.set(e,r,a),a}parsedJoinedData(e,t){let r=`parsed-joined-data`,i=this.get(e,r);if(i!==void 0)return Nd.trace`cache hit project ${e} key: ${r}`,i;Nd.trace`cache miss project ${e} key: ${r}`;let a=t();return a!==void 0&&this.set(e,r,a),a}parsedModel(e,t){let r=`parsed-model`,i=this.get(e,r);if(i!==void 0)return Nd.trace`cache hit project ${e} key: ${r}`,i;Nd.trace`cache miss project ${e} key: ${r}`;let a=t();return a!==void 0&&this.set(e,r,a),a}computedModel(e,t,r){let i=t?`computed-model-${t.hash}`:`computed-model`,a=this.get(e,i);if(a!==void 0)return Nd.trace`cache hit project ${e} key ${i}`,a;Nd.trace`cache miss project ${e} key ${i}`;let s=r();return s!==void 0&&this.set(e,i,s),s}};const{findNodeForKeyword:Pd,findNodeForProperty:Fd}=Xt,{getDocument:Id,streamAllContents:Ld}=en,Rd=q.getChild(`locator`);var LikeC4ModelLocator=class{services;fqnIndex;deploymentsIndex;langiumDocuments;parser;projects;constructor(e){this.services=e,this.fqnIndex=e.likec4.FqnIndex,this.deploymentsIndex=e.likec4.DeploymentsIndex,this.langiumDocuments=e.shared.workspace.LangiumDocuments,this.parser=e.likec4.ModelParser,this.projects=e.shared.workspace.ProjectsManager}documents(e){return this.parser.documents(e)}getParsedElement(...e){try{let t,r;if(e.length===2?(t=e[0],r=e[1]):(t=e[0],r=S(t)?this.projects.ensureProjectId():projectIdFrom(t)),S(t)){let e=t,i=this.fqnIndex.byFqn(r,e).head();if(!i)return null;let a=this.langiumDocuments.getDocument(i.documentUri),s=this.findParsedElementByFqnIn(e,a);return s&&a?{projectId:r,element:s,document:a}:null}let i=this.fqnIndex.getFqn(t),a=Id(t),s=this.findParsedElementByFqnIn(i,a);return s&&a?{projectId:r,element:s,document:a}:null}catch(e){return Rd.debug(loggable(e)),null}}findParsedElementByFqnIn(e,t){if(t)return this.parser.parse(t).c4Elements.find(t=>t.id===e)}locateElement(e,t){let[r,i]=splitGlobalFqn(e);r??=this.projects.ensureProjectId(t);let a=this.fqnIndex.byFqn(r,i).head(),s=a?.nameSegment??a?.selectionSegment;return!a||!s?null:{uri:a.documentUri.toString(),range:s.range}}locateDeploymentElement(e,t){let r=this.projects.ensureProjectId(t),i=e,a=this.deploymentsIndex.byFqn(r,i).head(),s=a?.nameSegment??a?.selectionSegment;return!a||!s?null:{uri:a.documentUri.toString(),range:s.range}}locateRelation(e,t){let r=this.projects.ensureProjectId(t);for(let t of this.documents(r)){let r=t.c4Relations.find(t=>t.id===e)??t.c4DeploymentRelations.find(t=>t.id===e);if(!r)continue;let i=this.services.workspace.AstNodeLocator.getAstNode(t.parseResult.value,r.astPath);if(!isRelation(i)&&!isDeploymentRelation(i))continue;let a=i.kind?Fd(i.$cstNode,`kind`):void 0;if(a??=i.dotKind?Fd(i.$cstNode,`dotKind`):void 0,a??=Pd(i.$cstNode,`->`),a??=Fd(i.$cstNode,`title`),a??=Fd(i.$cstNode,`target`),a??=i.$cstNode,a)return{uri:t.uri.toString(),range:{start:a.range.start,end:a.range.start}}}return null}locateViewAst(e,t){let r=this.projects.ensureProjectId(t);for(let t of this.documents(r)){let r=t.c4Views.find(t=>t.id===e);if(!r)continue;let i=this.services.workspace.AstNodeLocator.getAstNode(t.parseResult.value,r.astPath);if(isLikeC4View(i))return{doc:t,view:r,viewAst:i}}return null}locateView(e,t){let r=this.locateViewAst(e,t);if(!r)return null;let i=r.viewAst,a=i.name?Fd(i.$cstNode,`name`):void 0;return a??=Pd(i.$cstNode,`view`),a??=i.$cstNode,a?{uri:r.doc.uri.toString(),range:{start:a.range.start,end:a.range.start}}:null}async locateDocumentTags(e,t){let r=this.langiumDocuments.getDocument(e);if(!r||!r.likec4ProjectId)return null;r.state<rn.Linked&&(Rd.debug(`Waiting for document ${r.uri.path} to be Linked`),await this.services.shared.workspace.DocumentBuilder.waitUntil(rn.Linked,r.uri,t));let i=projectIdFrom(r);Rd.trace`locate document tags for ${r.uri.fsPath} in project ${i}`;try{let e=this.services.likec4.LastSeen.specification(i)?.tags,t=this.services.likec4.LastSeen.styles(i)??$i.DEFAULT;if(!e)return Rd.trace(`No specification or styles found for project ${i}, cannot locate tags for document ${r.uri.fsPath}`),null;let a=N(Ld(r.parseResult.value),ifilter(e=>isTag(e)||isTagRef(e)),toArray(),P(r=>{let i,a;try{isTag(r)?(i=r.name,a=r.$cstNode):(i=r.tag.$refText,a=r.tag.$refNode);let s=e[i];return invariant(s,`Tag ${i} not found in merged specification`),invariant(a,`Tag ${i} does not have a $cstNode`),{name:i,color:t.tagColor(s.color).fill,range:a.range,isSpecification:isTag(r)}}catch(e){return Rd.warn(`Fail on tag ${i}`,{err:e}),[]}}));return Rd.debug(`Found ${a.length} tags in document ${r.uri.path}`),a}catch(e){return Rd.warn(loggable(e)),null}}locateDynamicViewStep(e){let{doc:t,viewAst:r}=this.locateViewAst(e.view,e.projectId)??{};if(!t||!r)return null;if(!isDynamicView(r)||!r.body)return Rd.warn(`View ${e.view} is not a dynamic view`),null;let i=this.services.workspace.AstNodeLocator.getAstNodePath(r.body)+e.astPath,a=this.services.workspace.AstNodeLocator.getAstNode(t.parseResult.value,i);if(!a||!isStepOrSeries(a))return Rd.warn(`Failed to locate dynamic view step ${i} in view ${e.view}`),null;let s=a.kind?Fd(a.$cstNode,`kind`):void 0;return s??=a.dotKind?Fd(a.$cstNode,`dotKind`):void 0,s??=Pd(a.$cstNode,`->`),s??=Pd(a.$cstNode,`<-`),s??=Fd(a.$cstNode,`title`),s??=Fd(a.$cstNode,`target`),s??=a.$cstNode,s?{uri:t.uri.toString(),range:{start:s.range.start,end:s.range.start}}:null}};const zd=[`this`,`it`,`self`,`super`,`likec4lib`,`global`];function tryOrLog(e){return async function tryOrLogFn(t,r,i){try{let a=e(t,r,i);ne(a)&&await a;return}catch(e){let i=e instanceof Error?e.message:String(e);r(`error`,`Validation failed: ${i}`,{node:t}),q.debug(`Validation failed: ${i}`,{error:e})}}}const{getDocument:Bd}=en,deploymentNodeChecks=e=>{let t=e.likec4.DeploymentsIndex,r=e.references.NameProvider;return tryOrLog((e,i)=>{let a=r.getName(e);if(!a){i(`error`,`DeploymentNode must be named`,{node:e});return}let s=nonNullable(r.getNameNode(e),`name CstNode not found`).range;zd.includes(a)&&i(`error`,`Reserved word: ${a}`,{node:e,range:s});let c=projectIdFrom(e),l=t.getFqn(e);t.byFqn(c,l).limit(2).toArray().length>1&&i(`error`,`Duplicate node name "${l}"`,{node:e,range:s})})},deployedInstanceChecks=e=>{let t=e.likec4.DeploymentsIndex,r=e.references.NameProvider;return tryOrLog((e,i)=>{let a=r.getName(e);if(!a){i(`error`,`Deployed instance must be named, unique inside node`,{node:e});return}let s=nonNullable(r.getNameNode(e),`name CstNode not found`).range;zd.includes(a)&&i(`error`,`Reserved word: ${a}`,{node:e,range:s});let c=projectIdFrom(e),l=t.getFqn(e);t.byFqn(c,l).limit(2).toArray().length>1&&i(`error`,`Duplicate instance name "${l}"`,{node:e,range:s})})},deploymentRelationChecks=e=>{let t=e.likec4.ModelParser;return tryOrLog((e,r)=>{if(!e.target?.value?.ref){r(`error`,`DeploymentRelation target '${e.target?.$cstNode?.text??``}' not resolved`,{node:e,property:`target`});return}let i=Bd(e),a=t.forDocument(i),s;try{s=a._resolveDeploymentRelationSource(e)}catch(t){q.warn(loggable(t)),r(`error`,`DeploymentRelation source not resolved`,{node:e,property:`source`});return}if(H.isImportRef(s)){r(`error`,`DeploymentRelation cannot refer imported model (not implemented yet)`,{node:e,property:`source`});return}if(H.isModelRef(s)){r(`error`,`DeploymentRelation must refer deployment element`,{node:e,property:`source`});return}let c=a.parseFqnRef(e.target);H.isImportRef(c)?r(`error`,`DeploymentRelation cannot refer imported model (not implemented yet)`,{node:e,property:`target`}):H.isModelRef(c)?r(`error`,`DeploymentRelation must refer deployment element`,{node:e,property:`target`}):isSameHierarchy(s.deployment,c.deployment)&&r(`error`,`Invalid parent-child relationship`,{node:e})})},extendDeploymentChecks=e=>tryOrLog((e,t)=>{let r=e.deploymentNode.value.ref;(!r||!isDeploymentNode(r))&&t(`error`,`ExtendDeployment allows only DeploymentNode`,{node:e,property:`deploymentNode`})}),Vd=/* @__PURE__ */ e(e=>{let t=e.likec4.FqnIndex;return tryOrLog((e,r)=>{let i=elementRef(e.source),a=i&&t.getFqn(i);a||r(`error`,`Source not found (not parsed/indexed yet)`,{node:e,property:`source`});let s=elementRef(e.target),c=s&&t.getFqn(s);c||r(`error`,`Target not found (not parsed/indexed yet)`,{node:e,property:`target`}),a&&c&&isSameHierarchy(a,c)&&a!==c&&r(`error`,`Invalid parent-child relationship`,{node:e})})},`stepSingle`),Hd=/* @__PURE__ */ e(e=>{let t=e.likec4.FqnIndex;return tryOrLog((e,r)=>{let i=e.source;isStep(i)&&i.isBackward&&r(`error`,`Invalid chain after backward step`,{node:e});let a=elementRef(e.target);a&&t.getFqn(a)||r(`error`,`Target not found (not parsed/indexed yet)`,{node:e,property:`target`})})},`stepSeries`),subflowStep=e=>{let isParallel=e=>e.kind===`par`||e.kind===`parallel`,isAltBranch=e=>e.kind===`else`||e.kind===`if`||e.kind===`when`;return tryOrLog((e,t)=>{isParallel(e)&&isSubflowStep(e.$container)&&isParallel(e.$container)&&t(`error`,`Nested parallel blocks are not allowed`,{node:e,property:`kind`}),isAltBranch(e)?isAltSteps(e.$container)||t(`error`,`"${e.kind}" alternative branch must be inside "alt"`,{node:e,property:`kind`}):isAltSteps(e.$container)&&t(`error`,`"${e.kind}" can not be used as an alternative branch, only "if", "when" or "else" are allowed`,{node:e,property:`kind`})})},dynamicViewDisplayVariant=e=>tryOrLog((e,t)=>{w(e.value)||e.value!==`diagram`&&e.value!==`sequence`?t(`error`,`Invalid display variant: "diagram" or "sequence" are allowed`,{node:e,property:`value`}):hn(e,isDynamicViewBody)||t(`error`,`Display mode can be defined only inside dynamic view`,{node:e})}),{getDocument:Ud}=en,checkElement=e=>{let t=e.likec4.FqnIndex,r=e.workspace.AstNodeLocator;return tryOrLog((e,i)=>{let a=t.getFqn(e);if(!a){i(`error`,`Not indexed element`,{node:e,property:`name`});return}zd.includes(e.name)&&i(`error`,`Reserved word: ${e.name}`,{node:e,property:`name`});let s=Ud(e),c=s.uri,l=r.getAstNodePath(e),u=t.byFqn(projectIdFrom(s),a).filter(e=>e.documentUri!==c||e.path!==l).head();if(u){let t=u.documentUri!==c;i(`error`,`Duplicate element name ${e.name===a?e.name:e.name+` (`+a+`)`}`,{node:e,property:`name`,...t&&{relatedInformation:[{location:{range:u.nameSegment?.range??u.selectionSegment?.range,uri:u.documentUri.toString()},message:`conflicting element`}]}})}})},checkElementRef=e=>tryOrLog((e,t)=>{isReferenceToDeploymentModel(e.modelElement)&&t(`error`,`Only model elements allowed here`,{node:e,property:`modelElement`})}),{getDocument:Wd}=en,checkImportsFromPoject=e=>{let t=e.shared.workspace.ProjectsManager;return tryOrLog((e,r)=>{if(!t.all.includes(e.project)){r(`error`,`Imported project not found`,{node:e,property:`project`});return}let i=projectIdFrom(Wd(e));e.project===i&&r(`error`,`Imported project cannot be the same as the current project`,{node:e,property:`project`})})},opacityPropertyRuleChecks=e=>tryOrLog((e,t)=>{let r=parseFloat(e.value);(isNaN(r)||r<0||r>100)&&t(`warning`,`Value ignored, must be between 0% and 100%`,{node:e,property:`value`})}),iconPropertyRuleChecks=e=>(e,t)=>{let r=e.$container;r.props.some(t=>isIconProperty(t)&&t!==e)&&t(`error`,`Icon must be defined once`,{node:e}),isElementStyleProperty(r)&&isElementBody(r.$container)&&r.$container.props.some(e=>isIconProperty(e))&&t(`warning`,`Redundant as icon defined on element`,{node:e}),e.value?.startsWith(`file://`)&&t(`error`,`Icon URI must not start with file://`,{node:e,property:`value`})},colorLiteralRuleChecks=e=>(e,t)=>{if(e.$type===`HexColor`){if(e.hex===void 0||S(e.hex)&&!e.hex.match(/^[a-fA-F0-9]+$/)){t(`error`,`Invalid HEX`,{node:e,property:`hex`});return}let r=x(e.hex)?e.hex.toString().length:e.hex.length;r!==6&&r!==3&&r!==8&&t(`error`,`Invalid value "${e.$cstNode?.text}", must be 3, 6 or 8 characters long`,{node:e,property:`hex`})}else if(e.$type===`RGBAColor`){if((!x(e.red)||e.red<0||e.red>255)&&t(`error`,`Invalid value, must be between 0 and 255`,{node:e,property:`red`}),(!x(e.green)||e.green<0||e.green>255)&&t(`error`,`Invalid value, must be between 0 and 255`,{node:e,property:`green`}),(!x(e.blue)||e.blue<0||e.blue>255)&&t(`error`,`Invalid value, must be between 0 and 255`,{node:e,property:`blue`}),x(e.alpha)&&(e.alpha<0||e.alpha>1)&&t(`error`,`Invalid value, must be between 0 and 1`,{node:e,property:`alpha`}),S(e.alpha)){let r=parseFloat(e.alpha);(r<0||r>100)&&t(`error`,`Invalid value, must be between 0% and 100%`,{node:e,property:`alpha`})}}else nonexhaustive(e)},relationChecks=e=>{let t=e.likec4.ModelParser;return tryOrLog((e,r)=>{let i=t.forDocument($t(e)),a=safeCall(()=>i._resolveRelationSource(e));if(!a){r(`error`,`Source not resolved`,{node:e,property:`source`});return}let s=safeCall(()=>i.parseFqnRef(e.target));s?(H.isImportRef(a)&&(H.isImportRef(s)?r(`warning`,`Relationship between imported elements may not be visible in origin projects`,{node:e}):r(`warning`,`Relationship from imported element to local element may not be visible in origin project`,{node:e,property:`source`})),isSameHierarchy(H.flatten(a),H.flatten(s))&&r(`error`,`Invalid parent-child relationship`,{node:e})):r(`error`,`Target not resolved`,{node:e,property:`target`})})},checkRelationBody=e=>tryOrLog((e,t)=>{e.$container.tags?.values&&e.tags?.values&&t(`error`,`Relation cannot have tags in both header and body`,{node:e.tags})}),extendRelationChecks=e=>{let t=e.likec4.ModelParser,r=new Gn(e.shared,rn.Linked);function getProjectFingerprints(t){return r.get(t,()=>new Set(N(e.shared.workspace.LangiumDocuments.projectDocuments(t).toArray(),P(e=>e.c4Relations??[]),p(e=>relationFingerprint(e)))))}return tryOrLog((e,r)=>{let i=$t(e),a=t.forDocument(i),s=safeCall(()=>a.parseFqnRef(e.source));if(!s){r(`error`,`Source not resolved`,{node:e,property:`source`});return}let c=safeCall(()=>a.parseFqnRef(e.target));if(!c){r(`error`,`Target not resolved`,{node:e,property:`target`});return}if(!H.isModelRef(s)&&!H.isImportRef(s)){r(`error`,`Source must reference a model element`,{node:e,property:`source`});return}if(!H.isModelRef(c)&&!H.isImportRef(c)){r(`error`,`Target must reference a model element`,{node:e,property:`target`});return}let l=projectIdFrom(i),u=(e.kind??e.dotKind?.kind)?.ref?.name??`default`,{title:p=``}=a.parseBaseProps({},{title:e.title}),m=relationFingerprint({source:s,target:c,kind:u,title:p,isBidirectional:e.isBidirectional||void 0});getProjectFingerprints(l).has(m)||r(`warning`,`This extend does not match any relation (by source, kind, target, title, and directionality)`,{node:e})})},checkSpecificationRule=e=>tryOrLog((e,t)=>{e.$containerIndex&&e.$containerIndex>0&&t(`warning`,`Prefer one specification per document`,{node:e,property:`name`})}),checkModel=e=>tryOrLog((e,t)=>{e.$containerIndex&&e.$containerIndex>0&&t(`warning`,`Prefer one model per document`,{node:e,property:`name`})}),checkGlobals=e=>tryOrLog((e,t)=>{e.$containerIndex&&e.$containerIndex>0&&t(`warning`,`Prefer one global block per document`,{node:e,property:`name`})}),checkElementKind=e=>{let t=e.shared.workspace.IndexManager;return tryOrLog((e,r)=>{zd.includes(e.name)&&r(`error`,`Reserved word: ${e.name}`,{node:e,property:`name`});let i=projectIdFrom(e),a=t.projectElements(i,Es.$type).filter(t=>t.name===e.name&&t.node!==e).head();if(a){let t=a.documentUri!==$t(e).uri;r(`error`,`Duplicate element kind '${e.name}'`,{node:e,property:`name`,...t&&{relatedInformation:[{location:{range:a.nameSegment.range,uri:a.documentUri.toString()},message:`conflicting definition`}]}})}})},checkDeploymentNodeKind=e=>{let t=e.shared.workspace.IndexManager;return tryOrLog((e,r)=>{zd.includes(e.name)&&r(`error`,`Reserved word: ${e.name}`,{node:e,property:`name`});let i=projectIdFrom(e),a=t.projectElements(i,os.$type).filter(t=>t.name===e.name&&t.node!==e).head();if(a){let t=a.documentUri!==$t(e).uri;r(`error`,`Duplicate deploymentNode kind '${e.name}'`,{node:e,property:`name`,...t&&{relatedInformation:[{location:{range:a.nameSegment.range,uri:a.documentUri.toString()},message:`conflicting definition`}]}})}})},checkTag=e=>{let t=e.shared.workspace.IndexManager;return tryOrLog((e,r)=>{let i=e.name,a=projectIdFrom(e),s=t.projectElements(a,El.$type).filter(t=>t.name===i&&t.node!==e).head();if(s){let t=s.documentUri!==$t(e).uri;r(`error`,`Duplicate tag '${e.name}'`,{node:e,property:`name`,...t&&{relatedInformation:[{location:{range:s.nameSegment.range,uri:s.documentUri.toString()},message:`conflicting definition`}]}})}})},checkRelationshipKind=e=>{let t=e.shared.workspace.IndexManager;return tryOrLog((e,r)=>{zd.includes(e.name)&&r(`error`,`Reserved word: ${e.name}`,{node:e,property:`name`});let i=projectIdFrom(e);t.projectElements(i,$c.$type).filter(t=>t.name===e.name).limit(2).count()>1&&r(`error`,`Duplicate RelationshipKind '${e.name}'`,{node:e,property:`name`})})},checkGlobalPredicate=e=>{let t=e.shared.workspace.IndexManager;return tryOrLog((e,r)=>{let i=projectIdFrom(e),a=t.projectElements(i,ic.$type),s=t.projectElements(i,rc.$type);a.concat(s).filter(t=>t.name===e.name).limit(2).count()>1&&r(`error`,`Duplicate GlobalPredicateGroup or GlobalDynamicPredicateGroup name '${e.name}'`,{node:e,property:`name`})})},checkGlobalStyleId=e=>{let t=e.shared.workspace.IndexManager;return tryOrLog((e,r)=>{let i=projectIdFrom(e);t.projectElements(i,cc.$type).filter(t=>t.name===e.name).limit(2).count()>1&&r(`error`,`Duplicate GlobalStyleId name '${e.name}'`,{node:e,property:`name`})})},Gd=/@likec4-generated/,viewChecks=e=>{let t=e.shared.workspace.IndexManager;return tryOrLog((e,r)=>{let i=sn(e.$cstNode,[`BLOCK_COMMENT`]);if(i&&Gd.test(i.text)&&r(`warning`,`ManualLayoutV1 is no longer supported; remove this block`,{node:e,range:i.range}),!e.name)return;zd.includes(e.name)&&r(`error`,`Reserved word: ${e.name}`,{node:e,property:`name`});let a=projectIdFrom(e);t.projectElements(a,xc.$type).filter(t=>t.name===e.name).limit(2).count()>1&&r(`error`,`Duplicate view '${e.name}'`,{node:e,property:`name`})})},viewOrderChecks=e=>tryOrLog((e,t)=>{(!Number.isSafeInteger(e.value)||e.value<0)&&t(`error`,`View order must be a non-negative safe integer`,{node:e,property:`value`})}),viewRuleAutoLayoutChecks=e=>tryOrLog((e,t)=>{e.routing&&(Ln(e,isLikeC4View)?.body?.props??[]).some(isViewRoutingProperty)&&t(`warning`,`The view "routing" property overrides this autoLayout routing value.`,{node:e,property:`routing`})});function collectFqnExprs(e){let t=[],r=e;for(;r;)r.value&&t.push(r.value),r=r.prev;return t.reverse()}const viewRuleRankChecks=e=>tryOrLog((e,t)=>{let r=collectFqnExprs(e.targets);r.length<2&&e.value===`same`&&t(`warning`,`Rank rule should have at least 2 targets`,{node:e,property:`targets`});let i=r.filter(isFqnRefExpr),a=i[0]?.ref?.parent;for(let r=1;r<i.length;r++){let s=i[r];e.value===`same`&&!areSame(a,s?.ref?.parent)&&t(`error`,`All targets must have the same parent rank same`,{node:e,property:`targets`})}});function areSame(e,t){return!e&&!t?!0:!e||!t||e.value.ref!==t.value.ref?!1:areSame(e.parent,t.parent)}const checkFqnExprWith=e=>{let t=e.likec4.ModelParser;return tryOrLog((e,r)=>{let i=getViewRulePredicateContainer(e);if(i?.$type!==`DynamicViewIncludePredicate`&&i?.isInclude!==!0){r(`error`,`Invalid usage inside "exclude"`,{node:e});return}let a=i.$type===`DynamicViewIncludePredicate`,s=t.forDocument($t(i)),c=U.unwrap(s.parseFqnExprWith(e).custom.expr);switch(!0){case U.isWildcard(c)&&a:case U.isElementKindExpr(c)&&a:case U.isElementTagExpr(c)&&a:r(`warning`,`Predicate is ignored, as not supported in dynamic views`,{node:e});return;case U.isWildcard(c):case U.isModelRef(c):case U.isDeploymentRef(c):return;case U.isElementKindExpr(c):case U.isElementTagExpr(c):r(`error`,`Invalid target (expect reference to specific element)`,{node:e,property:`subject`});return;default:nonexhaustive(c)}})},checkFqnRefExpr=e=>{let t=e.likec4.ModelParser;return tryOrLog((e,r)=>{let i=t.forDocument($t(e)).parseFqnRefExpr(e),a=getViewRulePredicateContainer(e),s=isFqnRefInsideDeployment(e)&&!hn(e,e=>isDeploymentViewRuleStyle(e)||isViewRuleStyle(e));if(a?.$type===`DeploymentViewRulePredicate`||s){if(!hn(e,isRelationExpr)){if(U.isModelRef(i)){r(`error`,`Deployment view predicate must reference deployment model`,{node:e});return}if(U.isDeploymentRef(i)&&H.isInsideInstanceRef(i.ref)){r(`error`,`Must reference deployment nodes or instances, but not internals`,{node:e});return}}j(e.selector)&&!isDeploymentNode(e.ref.value?.ref)&&r(`warning`,`Selector '${e.selector}' applies to deployment nodes only, ignored here`,{node:e,property:`selector`})}else if(a?.$type===`DynamicViewIncludePredicate`)switch(!0){case U.isElementKindExpr(i):case U.isElementTagExpr(i):case U.isWildcard(i):r(`warning`,`Predicate is ignored, as not supported in dynamic views`,{node:e});return}})},checkIncomingRelationExpr=e=>tryOrLog((e,t)=>{if(e.to.$type===`WildcardExpression`&&!isInOutRelationExpr(e.$container)){let r=Ln(e,isElementView);C(r?.viewOf)&&t(`warning`,`Predicate is ignored as it concerns all relationships`,{node:e})}}),checkOutgoingRelationExpr=e=>tryOrLog((e,t)=>{if(getViewRulePredicateContainer(e)?.$type===`ViewRulePredicate`&&e.$container.$type!==`DirectedRelationExpr`&&e.from.$type===`WildcardExpression`){let r=Ln(e,isElementView);r&&C(r.viewOf)&&t(`warning`,`Predicate is ignored as it concerns all relationships`,{node:e})}}),checkRelationExpr=e=>{let t=e.likec4.ModelParser;return tryOrLog((e,r)=>{let i=Ln(e,isDeploymentViewRulePredicate);if(!i||i.isInclude!==!0)return;let a=$t(e),s=t.forDocument(a),c=Gi.unwrap(s.parseRelationExpr(e)),l=`Model reference is allowed in exclude predicate only`;if(Gi.isDirect(c)){(U.isModelRef(c.source)||U.isModelRef(c.target))&&r(`error`,l,{node:e});return}let u;u=Gi.isIncoming(c)?c.incoming:Gi.isOutgoing(c)?c.outgoing:c.inout,U.isModelRef(u)&&r(`error`,l,{node:e})})},checkRelationExprWith=e=>tryOrLog((e,t)=>{let r=getViewRulePredicateContainer(e);r&&r.$type!=`DynamicViewIncludePredicate`&&(r.isInclude||t(`error`,`Invalid usage inside "exclude"`,{node:e}))});var LikeC4DocumentValidator=class extends Mn{services;constructor(e){super(e),this.services=e}async validateDocument(e,t,r){return this.services.shared.workspace.ProjectsManager.isExcluded(e)?[]:await super.validateDocument(e,t,r)}};const Kd=isAnyOf(isImportsFromPoject,isImported,isGlobals,isGlobalPredicateGroup,isGlobalDynamicPredicateGroup,isGlobalStyle,isGlobalStyleGroup,isFqnExprWith,isRelationExprWith,isFqnExpr,isRelationExpr,isStepStatement,isDeploymentViewRule,isDeploymentViewRulePredicate,isExpressionV2,isRelationExpr,isFqnRefExpr,isViewProperty,isStyleProperty,isTags,isViewRule,isDynamicViewRule,isLikeC4View,isViewRuleStyleOrGlobalRef,isDeployedInstance,isDeploymentNode,isDeploymentRelation,isRelationshipStyleProperty,isDynamicViewDisplayVariantProperty,isMetadataBody,isMetadataProperty,isRelation,isRelationBody,isElementProperty,isStringProperty,isNavigateToProperty,isElement,isElementBody,isElementStyleProperty,isElementRef,isExtendElement,isExtendElementBody,isExtendDeployment,isExtendDeploymentBody,isExtendRelation,isExtendRelationBody,isSpecificationElementKind,isSpecificationRelationshipKind,isSpecificationDeploymentNodeKind,isSpecificationTag,isSpecificationColor,isSpecificationRule,isExpressions,isColorLiteral),findInvalidContainer=e=>{let t=e;for(;t&&!isLikeC4Grammar(t);){if(Kd(t))return t;t=t.$container}};function checksFromDiagnostics(e){let t=e.state>=rn.Validated?e.diagnostics?.filter(e=>e.severity===Lr.Error)??[]:[],r=/* @__PURE__ */ new WeakSet;for(let{node:e}of t)if(!(C(e)||r.has(e))&&(r.add(e),!Kd(e))){let t=findInvalidContainer(e);t&&r.add(t)}let isValid=e=>!r.has(e);return{isValid,invalidNodes:r}}function registerValidationChecks(e){q.debug(`registerValidationChecks`),e.validation.ValidationRegistry.register({DeployedInstance:deployedInstanceChecks(e),DeploymentNodeKind:checkDeploymentNodeKind(e),DeploymentNode:deploymentNodeChecks(e),DeploymentRelation:deploymentRelationChecks(e),ExtendDeployment:extendDeploymentChecks(e),ExtendRelation:extendRelationChecks(e),FqnRefExpr:checkFqnRefExpr(e),RelationExpr:checkRelationExpr(e),OpacityProperty:opacityPropertyRuleChecks(e),IconProperty:iconPropertyRuleChecks(e),SpecificationRule:checkSpecificationRule(e),Model:checkModel(e),Globals:checkGlobals(e),GlobalPredicateGroup:checkGlobalPredicate(e),GlobalDynamicPredicateGroup:checkGlobalPredicate(e),GlobalStyleId:checkGlobalStyleId(e),Step:Vd(e),StepSeries:Hd(e),SubflowStep:subflowStep(e),LikeC4View:viewChecks(e),Element:checkElement(e),ElementRef:checkElementRef(e),ElementKind:checkElementKind(e),Relation:relationChecks(e),RelationBody:checkRelationBody(e),Tag:checkTag(e),FqnExprWith:checkFqnExprWith(e),RelationExprWith:checkRelationExprWith(e),RelationshipKind:checkRelationshipKind(e),IncomingRelationExpr:checkIncomingRelationExpr(e),OutgoingRelationExpr:checkOutgoingRelationExpr(e),ImportsFromPoject:checkImportsFromPoject(e),ColorLiteral:colorLiteralRuleChecks(e),DynamicViewDisplayVariantProperty:dynamicViewDisplayVariant(e),ViewRuleRank:viewRuleRankChecks(e),ViewOrderProperty:viewOrderChecks(e),ViewRuleAutoLayout:viewRuleAutoLayoutChecks(e)});let t=e.shared.lsp.Connection;t&&onNextTick(()=>{e.shared.workspace.DocumentBuilder.onUpdate((e,r)=>{for(let e of r)q.debug(`clear diagnostics for deleted ${e.path}`),t.sendDiagnostics({uri:e.toString(),diagnostics:[]}).catch(e=>q.error(loggable(e)))})})}const qd=q.getChild(`parser`),Jd={b:`\b`,f:`\f`,n:`
|
|
122
|
+
`,r:`\r`,t:` `,v:`\v`,0:`\0`};function unescapeKeepingSlash(e){let t=``;for(let r=1;r<e.length-1;r++){let i=e[r];if(i===`\\`){let i=e[++r]??``;t+=i===`/`?`\\/`:Jd[i]??i}else t+=i}return t}function parseTitleKeepingEscapedSlash(e){if(!e||!S(e.text))return;let t=e.$cstNode?.text;return t?unescapeKeepingSlash(t):e.text}function parseInlineTitleKeepingEscapedSlash(e,t,r=0){let i=dn(e?.$cstNode,t,r)?.text;return i?unescapeKeepingSlash(i):void 0}function toSingleLine(e){if(e==null)return;let t=removeIndent(e);return S(t)?t.split(`
|
|
123
|
+
`).join(` `):`md`in t?{md:t.md.split(`
|
|
124
|
+
`).join(` `)}:{txt:t.txt.split(`
|
|
125
|
+
`).join(` `)}}function removeIndent(e){if(e!=null)switch(!0){case S(e):return dedent(e).trim();case isMarkdownOrString(e)&&S(e.markdown):return{md:dedent(e.markdown).trim()};case isMarkdownOrString(e)&&S(e.text):return{txt:dedent(e.text).trim()};case isMarkdownOrString(e):return{txt:``};default:return}}function parseViewOrder(e){if(e&&!/^\s*order\b\s*-/.test(e.$cstNode?.text??``))return Number.isSafeInteger(e.value)&&e.value>=0?e.value:void 0}function parseViewRouting(e,t){return e.find(isViewRoutingProperty)?.value??Me(t,isViewRuleAutoLayout)?.routing}var BaseParser=class{services;doc;project;isValid;docUri;docPathInProject;constructor(e,t,r){this.services=e,this.doc=t,this.project=r,this.isValid=checksFromDiagnostics(t).isValid,this.docUri=t.uri.toString(),this.docPathInProject=L.relative(r.folderUri,t.uri)}logError(e,t,r){let i=e instanceof Error?e.message:typeof e==`string`?e:String(e);if(yn(t)){let e=this.services.references.NameProvider.getName(t);e=e?`"${e}" (${t.$type})`:`${t.$type}`;let r=t.$cstNode,a=r?`:${r.range.start.line+1}:${r.range.start.character+1}`:``;i+=`\n\tat ${e} (${this.doc.uri.fsPath}${a})`}else t&&`$refText`in t&&(i+=`\n\tat reference "${t.$refText}" (${this.doc.uri.fsPath})`);r&&r!==`base`?qd.getChild(r).debug(i):qd.debug(i)}tryParse(e,t,r){try{return!t||!this.isValid(t)?void 0:r(t)}catch(r){this.logError(r,t,e);return}}tryMap(e,t,r){let i=0;return P(t,t=>{try{if(!t||!this.isValid(t))return[];let e=r(t,i);return e===void 0?[]:(i++,e)}catch(r){return this.logError(r,t,e),[]}})}resolveFqn(e){if(isImported(e)){let t=projectIdFrom(e),r=this.resolveFqn(nonNullable(e.imported.ref,`FqnRef is empty of imported: ${e.$cstNode?.text}`));return this.doc.c4Imports.set(t,r),GlobalFqn(t,r)}return isExtendElement(e)?readStrictFqn(e.element):isExtendDeployment(e)?readStrictFqn(e.deploymentNode):isDeploymentElement(e)?this.services.likec4.DeploymentsIndex.getFqn(e):this.services.likec4.FqnIndex.getFqn(e)}getAstNodePath(e){return this.services.workspace.AstNodeLocator.getAstNodePath(e)}getMetadata(e){if(!e||!this.isValid(e)||w(e.props))return;let extractValues=e=>{if(isMarkdownOrString(e)){let t=removeIndent(e);if(!t)return[];if(typeof t==`string`)return j(t)?[t]:[];{let e=t.md||t.txt;return j(e)?[e]:[]}}return isMetadataArray(e)?e.values.map(e=>removeIndent(e)).map(e=>typeof e==`string`?e:e.md||e.txt).filter(j):[]},t=N(e.props,P(e=>e.value?extractValues(e.value).map(t=>[e.key,t]):[[e.key,String(e.boolValue)]]),D(([e,t])=>j(t)));if(w(t))return;let r=N(t,le(([e])=>e),ae(e=>e.map(([e,t])=>t))),i={};for(let[e,t]of Object.entries(r))t&&t.length>0&&(i[e]=t.length===1?t[0]:t);return w(i)?void 0:i}parseMarkdownOrString(e){if(isMarkdownOrString(e))return removeIndent(e)}convertTags(e){return this.parseTags(e)}parseTags(e){let t=e?.tags;if(!t)return null;let r=[];for(;t;)r.push(...this.tryMap(`base`,t.values,e=>nonNullable(e.tag.ref,`Tag reference is not resolved`).name).filter(j)),t=t.prev;return isNonEmptyArray(r)?E(r):null}convertLinks(e){return this.parseLinks(e)}parseLinks(e){if(!e?.props||e.props.length===0)return;let t=this.tryMap(`base`,D(e.props,isLinkProperty),e=>{let t=e.value;if(_(t))return;let r=j(e.title)?toSingleLine(e.title):void 0,i=this.services.lsp.DocumentLinkProvider.relativeLink(this.doc,t);return exact({url:t,title:r,relative:i&&i!==t?i:void 0})});return isNonEmptyArray(t)?t:void 0}parseIconProperty(e){if(!e||!this.isValid(e))return;let{libicon:t,value:r}=e;switch(!0){case!!t:{let r=t.ref?.name;if(!r){this.logError(`Library icon ${t.$refText} is not a valid library icon`,e);return}return r}case r&&r===`none`:return r;case r&&nr(r):if(r.startsWith(`file:`)){this.logError(`Icon property '${r}' used the 'file' protocol which is not supported`,e);return}return r;case r&&r.startsWith(`@`):return this.parseImageAlias(r);case r&&Qn(r):return Xn(this.doc.uri.toString(),`../`,r);case r&&er(r):return tr(this.project.folderUri.toString(),r);default:this.logError(`Icon property '${r}' is not a valid URL, library icon, image alias or 'none'`,e);return}}parseImageAlias(e){let t=e.indexOf(`/`),r=t>0?e.substring(0,t):e,i=t>0?e.substring(t+1):``,a={"@":`./images`,...this.project.config.imageAliases}[r];if(!a){qd.warn(`Image alias "${r}" not found in project configuration`);return}let s=i?tr(a,i):a;return tr(this.project.folderUri.toString(),s)}parseColorLiteral(e){if(this.isValid(e)){if(isHexColor(e))return`#${e.hex}`;if(isRGBAColor(e)){let t=x(e.alpha)?e.alpha:void 0;return S(e.alpha)&&(t=parseAstPercent(e.alpha)/100),t===void 0?`rgb(${e.red},${e.green},${e.blue})`:`rgba(${e.red},${e.green},${e.blue},${t})`}nonexhaustive(e)}}parseElementStyle(e){if(!e)return{};if(b(e)){let t=this.parseStyleProps(e.find(isElementStyleProperty)?.props);try{let r=this.parseIconProperty(e.find(isIconProperty));r&&(t.icon=r)}catch(e){this.logError(e)}return t}return this.parseStyleProps(e.props)}parseStyleProps(e){let t={};if(!e||e.length===0)return t;for(let r of e)if(this.isValid(r))try{switch(!0){case isBorderProperty(r):j(r.value)&&(t.border=r.value);break;case isColorProperty(r):{let e=toColor(r);j(e)&&(t.color=e);break}case isShapeProperty(r):j(r.value)&&(t.shape=r.value);break;case isIconProperty(r):{let e=this.parseIconProperty(r);j(e)&&(t.icon=e);break}case isIconColorProperty(r):{let e=toColor(r);j(e)&&(t.iconColor=e);break}case isIconSizeProperty(r):j(r.value)&&(t.iconSize=parseAstSizeValue(r));break;case isIconPositionProperty(r):j(r.value)&&(t.iconPosition=parseAstIconPositionValue(r));break;case isOpacityProperty(r):t.opacity=parseAstOpacityProperty(r);break;case isMultipleProperty(r):t.multiple=g(r.value)?r.value:!1;break;case isShapeSizeProperty(r):j(r.value)&&(t.size=parseAstSizeValue(r));break;case isPaddingSizeProperty(r):j(r.value)&&(t.padding=parseAstSizeValue(r));break;case isTextSizeProperty(r):j(r.value)&&(t.textSize=parseAstSizeValue(r));break;case isSizingProperty(r):j(r.value)&&(t.sizing=parseAstSizingValue(r));break;default:nonexhaustive(r)}}catch(e){this.logError(e,r)}return exact(t)}parseBaseProps(e,t){let r=removeIndent(t?.title??parseMarkdownAsString(e.title)),i=t?.description?{txt:removeIndent(t.description)}:this.parseMarkdownOrString(e.description);return exact({title:r,summary:t?.summary?{txt:removeIndent(t.summary)}:this.parseMarkdownOrString(e.summary),description:i,technology:toSingleLine(t?.technology)??removeIndent(parseMarkdownAsString(e.technology))})}};function*streamDeploymentModel(e){let t=$e.default.from(e.parseResult.value.deployments.flatMap(e=>e.elements)),r=[],i;for(;i=t.shift();)if(isDeploymentRelation(i))r.push(i);else{if(i.body&&i.body.elements.length>0)for(let e of i.body.elements)t.push(e);yield i}yield*r}function DeploymentModelParser(e){return class DeploymentModelParser extends e{parseDeployment(){let e=this.doc;for(let t of streamDeploymentModel(e))try{switch(!0){case isDeploymentRelation(t):this.isValid(t)&&e.c4DeploymentRelations.push(this.parseDeploymentRelation(t));break;case isDeployedInstance(t):e.c4Deployments.push(this.parseDeployedInstance(t));break;case isDeploymentNode(t):e.c4Deployments.push(this.parseDeploymentNode(t));break;case isExtendDeployment(t):{let r=this.parseExtendDeployment(t);r&&e.c4ExtendDeployments.push(r);break}default:nonexhaustive(t)}}catch(e){this.logError(e,t,`deployment`)}}parseDeploymentNode(e){let t=this.isValid,r=this.resolveFqn(e),i=nonNullable(e.kind.ref,`DeploymentKind not resolved`).name,a=this.parseTags(e.body)??void 0,s=this.parseLinks(e.body),c=this.parseElementStyle(e.body?.props),l=this.getMetadata(e.body?.props.find(isMetadataProperty)),u=N(e.body?.props??[],D(t),D(isElementStringProperty),m(e=>[e.key,e.value])),{title:p,...h}=this.parseBaseProps(u,{title:e.title,summary:e.summary});return exact({id:r,kind:i,title:p??nameFromFqn(r),...h,tags:a,links:s,style:c,metadata:l})}parseDeployedInstance(e){let t=this.isValid,r=this.resolveFqn(e),i=this.parseFqnRef(e.target.modelElement);invariant(H.isModelRef(i)||H.isImportRef(i),`Target must be a model reference`);let a=this.parseTags(e.body)??void 0,s=this.parseElementStyle(e.body?.props),c=this.getMetadata(e.body?.props.find(isMetadataProperty)),l=N(e.body?.props??[],D(t),D(isElementStringProperty),m(e=>[e.key,e.value])),u=this.parseBaseProps(l,{title:e.title,summary:e.summary});return exact({id:r,element:i,tags:a,links:this.parseLinks(e.body),...u,style:s,metadata:c})}parseExtendDeployment(e){let t=this.parseTags(e.body),r=this.getMetadata(e.body?.props.find(isMetadataProperty)),i=this.parseLinks(e.body);return!t&&w(r??{})&&!i?null:exact({id:this.resolveFqn(e),astPath:this.getAstNodePath(e),metadata:r,tags:t,links:i})}_resolveDeploymentRelationSource(e){if(T(e.source))return this.parseFqnRef(e.source);if(e.$container.$type===`DeploymentNodeBody`||e.$container.$type===`DeployedInstanceBody`)return{deployment:this.resolveFqn(e.$container.$container)};throw Error(`RelationRefError: Invalid container for sourceless relation`)}parseDeploymentRelation(e){let t=this.isValid,r=this.getAstNodePath(e),i=this._resolveDeploymentRelationSource(e);invariant(H.isDeploymentRef(i),`Invalid source for deployment relation`);let a=this.parseFqnRef(e.target);invariant(H.isDeploymentRef(a),`Invalid target for deployment relation`);let s=this.convertTags(e)??this.convertTags(e.body)??void 0,c=this.convertLinks(e.body),l=(e.kind??e.dotKind?.kind)?.ref?.name,u=this.getMetadata(e.body?.props.find(isMetadataProperty)),p=N(e.body?.props??[],D(isRelationStringProperty),D(e=>j(e.value)),m(e=>[e.key,e.value])),h=N(e.body?.props??[],D(isRelationNavigateToProperty),fe())?.value.view.ref?.name,g=this.parseBaseProps(p,{title:e.title}),_=e.body?.props.find(isRelationStyleProperty);return exact({id:stringHash(`deployment`,this.docUri,r,i.deployment,a.deployment),source:i,target:a,isBidirectional:e.isBidirectional||void 0,...g,metadata:u,kind:l,tags:s,links:c,...toRelationshipStyle(_?.props,t),navigateTo:h,astPath:r})}}}function DeploymentViewParser(e){return class DeploymentViewParser extends e{parseDeploymentView(e){let t=e.body;invariant(t,`DynamicElementView body is not defined`);let r=t.props.filter(this.isValid),i=this.getAstNodePath(e),a=e.name;a||=`deployment_`+stringHash(this.doc.uri.toString(),i);let s=N(r,D(isViewStringProperty),m(e=>[e.key,e.value])),{title:c=null,description:l=null}=this.parseBaseProps(s,{title:parseTitleKeepingEscapedSlash(s.title)}),u=this.convertTags(t),p=this.convertLinks(t),h=parseViewOrder(r.find(isViewOrderProperty)),g=parseViewRouting(r,t.rules);return bu.writeId(e,a),{[Hi]:`deployment`,id:a,astPath:i,title:toSingleLine(c)??null,description:l,...h!==void 0&&{order:h},...g&&{routing:g},tags:u,links:isNonEmptyArray(p)?p:null,rules:this.tryMap(`deployment`,t.rules,e=>this.parseDeploymentViewRule(e))}}parseDeploymentViewRule(e){if(isDeploymentViewRulePredicate(e))return this.parseDeploymentViewRulePredicate(e);if(isViewRuleAutoLayout(e))return toAutoLayout(e);if(isViewRuleAncestors(e))return{includeAncestors:e.value};if(isDeploymentViewRuleStyle(e))return this.parseDeploymentViewRuleStyle(e);nonexhaustive(e)}parseDeploymentViewRulePredicate(e){let t=[],r=e.expr;for(;r;){try{let e=r.value;l(e)&&this.isValid(e)&&t.unshift(this.parseExpressionV2(e))}catch(e){logWarnError(e)}r=r.prev}return e.isInclude?{include:t}:{exclude:t}}parseDeploymentViewRuleStyle(e){let t=this.parseStyleProps(e.props.filter(isStyleProperty)),r=removeIndent(parseMarkdownAsString(e.props.find(isNotationProperty)?.value));return{targets:this.parseFqnExpressions(e.targets),style:t,...r&&{notation:r}}}}}const parseMetadataEquals=({operator:e,not:t},r)=>e?.startsWith(`!=`)?{neq:r}:e?.startsWith(`=`)?{eq:r}:t?{neq:r}:{eq:r},parseEquals=({operator:e,not:t},r)=>e.startsWith(`!=`)?{neq:r}:e.startsWith(`=`)?{eq:r}:t?{neq:r}:{eq:r};function parseParticipant(e){return!isWhereRelationParticipantKind(e)&&!isWhereRelationParticipantTag(e)&&!isWhereRelationParticipantMetadata(e)?null:e.participant}function parseWhereClause(e){switch(!0){case isWhereTagEqual(e):{let t=e.value.tag.ref?.name,r=parseParticipant(e);invariant(t,`Expected tag name`);let i={tag:parseEquals(e,t)};return r?{participant:r,operator:i}:i}case isWhereKindEqual(e):{let t=e.value?.ref?.name,r=parseParticipant(e);invariant(t,`Expected kind name`);let i={kind:parseEquals(e,t)};return r?{participant:r,operator:i}:i}case isWhereMetadataEqual(e):{let t=e.key,r=parseParticipant(e);invariant(t,`Expected metadata key`);let i={metadata:{key:t,...e.value==null?{}:{value:parseMetadataEquals(e,String(e.value))}}};return r?{participant:r,operator:i}:i}case isWhereElementNegation(e)||isWhereRelationNegation(e):return{not:parseWhereClause(e.value)};case isWhereBinaryExpression(e):{let t=parseWhereClause(e.left),r=parseWhereClause(e.right);return createBinaryOperator(e.operator.toLowerCase(),t,r)}default:nonexhaustive(e)}}function createBinaryOperator(e,t,r){if(r===null)return t;switch(e){case`and`:{let e=[isAndOperator(t)?t.and:t,isAndOperator(r)?r.and:r].flat();return invariant(isNonEmptyArray(e),`Expected non-empty array`),{and:e}}case`or`:{let e=[isOrOperator(t)?t.or:t,isOrOperator(r)?r.or:r].flat();return invariant(isNonEmptyArray(e),`Expected non-empty array`),{or:e}}default:nonexhaustive(e)}}function ExpressionV2Parser(e){return class ExpressionV2Parser extends e{parseFqnRef(e){let t=nonNullable(e.value?.ref,()=>`Element "${e.$cstNode?.text}" is not resolved`);if(isImported(t)){let e={project:projectIdFrom(t),model:this.resolveFqn(nonNullable(t.imported.ref,`Imported "${t.$cstNode?.text}" is not resolved`))};return this.doc.c4Imports.set(e.project,e.model),e}if(isElement(t)){let r=importsRef(e);if(r){let e={project:projectIdFrom(r),model:this.resolveFqn(t)};return this.doc.c4Imports.set(e.project,e.model),e}let i=instanceRef(e);return i?{deployment:this.resolveFqn(i),element:this.resolveFqn(t)}:{model:this.resolveFqn(t)}}if(isDeploymentElement(t))return{deployment:this.resolveFqn(t)};nonexhaustive(t)}parseExpressionV2(e){if(isFqnExprOrWith(e))return this.parseFqnExprOrWith(e);if(isRelationExprOrWith(e))return this.parseRelationExprOrWith(e);nonexhaustive(e)}parseFqnExprOrWith(e){if(isFqnExprWith(e))return this.parseFqnExprWith(e);if(isFqnExprOrWhere(e))return this.parseFqnExprOrWhere(e);nonexhaustive(e)}parseFqnExprWith(e){let t=this.parseFqnExprOrWhere(e.subject);return(e.custom?.props??[]).reduce((e,t)=>{if(!this.isValid(t))return e;if(isNavigateToProperty(t)){let r=t.value.view.$refText;return j(r)&&(e.custom.navigateTo=r),e}if(isNotesProperty(t)){let r=this.parseMarkdownOrString(t.value);return r&&(e.custom[t.key]=r),e}if(isElementStringProperty(t)){if(t.key===`description`||t.key===`summary`){let r=this.parseMarkdownOrString(t.value);return r&&(e.custom.description=r),e}let r=removeIndent(parseMarkdownAsString(t.value));return T(r)&&(e.custom[t.key]=r),e}if(isIconProperty(t)){let r=this.parseIconProperty(t);return T(r)&&(e.custom[t.key]=r),e}if(isColorProperty(t)){let r=toColor(t);return T(r)&&(e.custom[t.key]=r),e}if(isShapeProperty(t)||isBorderProperty(t))return T(t.value)&&(e.custom[t.key]=t.value),e;if(isOpacityProperty(t))return T(t.value)&&(e.custom[t.key]=parseAstOpacityProperty(t)),e;if(isIconColorProperty(t)){let r=toColor(t);return T(r)&&(e.custom[t.key]=r),e}if(isNotationProperty(t)){let r=j(t.value)?removeIndent(parseMarkdownAsString(t.value)):void 0;return r&&(e.custom[t.key]=r),e}if(isMultipleProperty(t))return g(t.value)&&(e.custom[t.key]=t.value),e;if(isShapeSizeProperty(t)||isTextSizeProperty(t)||isPaddingSizeProperty(t)||isIconSizeProperty(t))return j(t.value)&&(e.custom[t.key]=parseAstSizeValue(t)),e;if(isIconPositionProperty(t))return j(t.value)&&(e.custom[t.key]=t.value),e;if(isSizingProperty(t))return j(t.value)&&(e.custom[t.key]=parseAstSizingValue(t)),e;nonexhaustive(t)},{custom:{expr:t}})}parseFqnExprOrWhere(e){if(isFqnExprWhere(e))return this.parseFqnExprWhere(e);if(isFqnExpr(e))return this.parseFqnExpr(e);nonexhaustive(e)}parseFqnExprWhere(e){return invariant(!isFqnExprWhere(e.subject),`FqnExprWhere is not allowed as subject of FqnExprWhere`),{where:{expr:this.parseFqnExpr(e.subject),condition:e.where?parseWhereClause(e.where):{kind:{neq:`--always-true--`}}}}}parseFqnExpr(e){if(isWildcardExpression(e))return{wildcard:!0};if(isElementKindExpression(e))return invariant(e.kind?.ref,`ElementKind "${e.$cstNode?.text}" is not resolved`),{elementKind:e.kind.ref.name,isEqual:e.isEqual};if(isElementTagExpression(e))return invariant(e.tag.tag.ref,`Tag ${e.$cstNode?.text} is not resolved`),{elementTag:e.tag.tag.ref.name,isEqual:e.isEqual};if(isFqnRefExpr(e))return this.parseFqnRefExpr(e);nonexhaustive(e)}parseFqnRefExpr(e){let t=this.parseFqnRef(e.ref);switch(!0){case e.selector===`._`:return{ref:t,selector:`expanded`};case e.selector===`.**`:return{ref:t,selector:`descendants`};case e.selector===`.*`:return{ref:t,selector:`children`};default:return{ref:t}}}parseFqnExpressions(e){let t=[],r=e;for(;r;){try{l(r.value)&&this.isValid(r.value)&&t.push(this.parseFqnExpr(r.value))}catch(e){this.logError(e,r.value,`fqnref`)}r=r.prev}return t.reverse()}parseRelationExprOrWith(e){if(isRelationExprWith(e))return this.parseRelationExprWith(e);if(isRelationExprOrWhere(e))return this.parseRelationExprOrWhere(e);nonexhaustive(e)}parseRelationExprWith(e){let t=this.parseRelationExprOrWhere(e.subject);return{customRelation:{...this.parseCustomRelationProperties(e.custom),expr:t}}}parseCustomRelationProperties(e){return(e?.props??[]).reduce((e,t)=>{if(isNotesProperty(t)){let r=this.parseMarkdownOrString(t.value);return r&&(e[t.key]=r),e}if(isRelationStringProperty(t)||isNotationProperty(t)){if(t.key===`description`){let r=this.parseMarkdownOrString(t.value);return r&&(e.description=r),e}let r=removeIndent(parseMarkdownAsString(t.value));return T(r)&&(e[t.key]=r),e}if(isArrowProperty(t))return j(t.value)&&(e[t.key]=t.value),e;if(isColorProperty(t)){let r=toColor(t);return j(r)&&(e[t.key]=r),e}if(isLineProperty(t))return j(t.value)&&(e[t.key]=t.value),e;if(isRelationNavigateToProperty(t)){let r=t.value.view.ref?.name;return j(r)&&(e[t.key]=r),e}if(isMultipleProperty(t))return g(t.value)&&(e[t.key]=t.value),e;nonexhaustive(t)},{})}parseRelationExprOrWhere(e){if(isRelationExprWhere(e))return this.parseRelationExprWhere(e);if(isRelationExpr(e))return this.parseRelationExpr(e);nonexhaustive(e)}parseRelationExprWhere(e){invariant(!isRelationExprWhere(e.subject),`RelationExprWhere is not allowed as subject of RelationExprWhere`);let t=this.parseRelationExpr(e.subject),r=t.where?.expr??t,i=t.where?.condition,a=e.where?parseWhereClause(e.where):null,s;return s=a&&i?createBinaryOperator(`and`,i,a):a??i??{kind:{neq:`--always-true--`}},{where:{expr:r,condition:s}}}parseRelationExpr(e){switch(e.$type){case`DirectedRelationExpr`:return this.wrapInWhere({source:this.parseFqnExpr(e.source.from),target:this.parseFqnExpr(e.target),isBidirectional:e.source.isBidirectional},this.parseInlineKindCondition(e.source));case`InOutRelationExpr`:return{inout:this.parseFqnExpr(e.inout.to)};case`OutgoingRelationExpr`:return this.wrapInWhere({outgoing:this.parseFqnExpr(e.from)},this.parseInlineKindCondition(e));case`IncomingRelationExpr`:return{incoming:this.parseFqnExpr(e.to)};default:nonexhaustive(e)}}parseInlineKindCondition(e){let t=e.kind??e.dotKind?.kind;return t?t.ref?{kind:{eq:t.ref?.name}}:(this.logError(`RelationshipKind "${t.$refText}" is not resolved`,e,`fqnref`),null):null}wrapInWhere(e,t){return t?{where:{expr:e,condition:t}}:e}}}function GlobalsParser(e){return class GlobalsParser extends e{parseGlobals(){let{parseResult:e,c4Globals:t}=this.doc,r=this.isValid,i=e.value.globals.filter(r),a=i.flatMap(e=>e.predicates.filter(r));for(let e of a)try{let r=e.name;if(!j(r))continue;if(r in t.predicates){this.logError(`Global predicate named "${r}" is already defined`,e,`globals`);continue}this.parseAndStoreGlobalPredicateGroupOrDynamic(e,r,t)}catch(t){this.logError(t,e,`globals`)}let s=i.flatMap(e=>e.styles.filter(r));for(let e of s)try{let r=e.id.name;if(!j(r))continue;if(r in t.styles){this.logError(`Global style named "${r}" is already defined`,e,`globals`);continue}let i=this.parseGlobalStyleOrGroup(e);k(i,1)&&(t.styles[r]=i)}catch(t){this.logError(t,e,`globals`)}}parseAndStoreGlobalPredicateGroupOrDynamic(e,t,r){if(isGlobalPredicateGroup(e)){let i=this.parseGlobalPredicateGroup(e);k(i,1)&&(r.predicates[t]=i)}else if(isGlobalDynamicPredicateGroup(e)){let i=this.parseGlobalDynamicPredicateGroup(e);k(i,1)&&(r.dynamicPredicates[t]=i)}else nonexhaustive(e)}parseGlobalPredicateGroup(e){return e.predicates.map(e=>this.parseViewRulePredicate(e))}parseGlobalDynamicPredicateGroup(e){return e.predicates.map(e=>this.parseDynamicViewIncludePredicate(e))}parseGlobalStyleOrGroup(e){if(isGlobalStyle(e))return[this.parseViewRuleStyle(e)];if(isGlobalStyleGroup(e))return e.styles.map(e=>this.parseViewRuleStyle(e));nonexhaustive(e)}}}function ImportsParser(e){return class ImportsParser extends e{parseImports(){let e=this.doc.parseResult.value.imports??[];for(let t of e){let e=t.project,r=t.imports;for(;r;){try{this.doc.c4Imports.set(e,this.resolveFqn(nonNullable(r.imported.ref,`ElementRef is empty of imported: ${r.imported.$refText}`)))}catch(e){this.logError(e,r,`imports`)}r=r.prev}}}}}function*streamModel(e){let t=$e.default.from(e.parseResult.value.models.flatMap(e=>e.elements)),r=[],i;for(;i=t.shift();)if(isRelation(i))r.push(i);else if(isExtendRelation(i))r.push(i);else{if(i.body?.elements&&k(i.body.elements,1))for(let e of i.body.elements)t.push(e);yield i}yield*r}function ModelParser(e){return class ModelParser extends e{parseModel(){let e=this.doc;for(let t of streamModel(e))try{if(isElement(t)){e.c4Elements.push(this.parseElement(t));continue}if(isRelation(t)){e.c4Relations.push(this.parseRelation(t));continue}if(isExtendElement(t)){let r=this.parseExtendElement(t);r&&e.c4ExtendElements.push(r);continue}if(isExtendRelation(t)){let r=this.parseExtendRelation(t);r&&e.c4ExtendRelations.push(r);continue}nonexhaustive(t)}catch(e){this.logError(e,t,`model`)}}parseElement(e){let t=this.isValid,r=this.resolveFqn(e),i=nonNullable(e.kind.ref,`Element kind is not resolved`).name,a=this.parseTags(e.body),s=this.parseElementStyle(e.body?.props),c=this.getMetadata(e.body?.props.find(isMetadataProperty)),l=this.getAstNodePath(e),[u,p,h]=e.props??[],g=N(e.body?.props??[],D(t),D(isElementStringProperty),m(e=>[e.key,e.value])),{title:_,...v}=this.parseBaseProps(g,{title:T(u)?parseInlineTitleKeepingEscapedSlash(e,`props`,0)??u:parseTitleKeepingEscapedSlash(g.title),summary:p,technology:h});return exact({id:r,kind:i,astPath:l,title:_,metadata:c,tags:a??void 0,links:this.parseLinks(e.body),...v,style:s})}parseExtendElement(e){let t=this.parseTags(e.body),r=this.getMetadata(e.body?.props.find(isMetadataProperty)),i=this.parseLinks(e.body);if(!t&&_(r)&&!i)return null;let a=this.getAstNodePath(e);return exact({id:this.resolveFqn(e),astPath:a,metadata:r,tags:t,links:i})}parseExtendRelation(e){let t=this.parseFqnRef(e.source),r=this.parseFqnRef(e.target);invariant(H.isModelRef(t)||H.isImportRef(t),`Source must be a model reference`),invariant(H.isModelRef(r)||H.isImportRef(r),`Target must be a model reference`);let i=this.parseTags(e.body),a=this.getMetadata(e.body?.props.find(isMetadataProperty)),s=this.getAstNodePath(e),c=this.parseLinks(e.body);if(!i&&w(a??{})&&!c)return null;let l=(e.kind??e.dotKind?.kind)?.ref?.name,{title:u=``}=this.parseBaseProps({},{title:e.title});return exact({id:relationFingerprint({source:t,target:r,kind:l,title:u,isBidirectional:e.isBidirectional||void 0}),astPath:s,isBidirectional:e.isBidirectional||void 0,metadata:a,tags:i,links:c})}_resolveRelationSource(e){if(T(e.source)){let t=this.parseFqnRef(e.source);return invariant(H.isModelRef(t)||H.isImportRef(t),`Relation source must be a model reference`),t}if(isElementBody(e.$container)||isExtendElementBody(e.$container))return{model:this.resolveFqn(e.$container.$container)};throw Error(`RelationRefError: Invalid container for sourceless relation`)}parseRelation(e){let t=this.isValid,r=this._resolveRelationSource(e),i=this.parseFqnRef(e.target);invariant(H.isModelRef(i)||H.isImportRef(i),`Target must be a model reference`);let a=this.parseTags(e)??this.parseTags(e.body)??void 0,s=this.parseLinks(e.body),c=(e.kind??e.dotKind?.kind)?.ref?.name,l=this.getMetadata(e.body?.props.find(isMetadataProperty)),u=this.getAstNodePath(e),h=N(e.body?.props??[],D(isRelationStringProperty),D(e=>j(e.value)),m(e=>[e.key,e.value])),g=N(e.body?.props??[],D(isRelationNavigateToProperty),p(e=>e.value.view.ref?.name),D(j),fe()),{title:_=``,description:v,technology:y}=this.parseBaseProps(h,{title:e.title,description:e.description,technology:e.technology}),b=e.body?.props.find(isRelationStyleProperty);return exact({id:stringHash(this.docUri,u,H.flatten(r),H.flatten(i)),astPath:u,source:r,target:i,isBidirectional:e.isBidirectional||void 0,title:_,metadata:l,kind:c,tags:a,links:s,navigateTo:g,description:v,technology:y,...toRelationshipStyle(b?.props,t)})}}}function PredicatesParser(e){return class PredicatesParser extends e{parsePredicate(e){return this.parseExpressionV2(e)}parseElementPredicate(e){if(isFqnExprWith(e))return this.parseFqnExprWith(e);if(isFqnExprOrWhere(e))return this.parseFqnExprOrWhere(e);nonexhaustive(e)}parseElementPredicateOrWhere(e){return this.parseFqnExprOrWhere(e)}parseElementExpression(e){return this.parseFqnExpr(e)}parseElementPredicateWhere(e){return this.parseFqnExprWhere(e)}parseElementPredicateWith(e){return this.parseFqnExprWith(e)}parseRelationPredicate(e){return this.parseRelationExprOrWith(e)}parseRelationPredicateOrWhere(e){return this.parseRelationExprOrWhere(e)}parseRelationPredicateWhere(e){return this.parseRelationExprWhere(e)}parseRelationPredicateWith(e){return this.parseRelationExprWith(e)}parseRelationExpression(e){return this.parseRelationExpr(e)}}}function SpecificationParser(e){return class SpecificationParser extends e{parseSpecification(){let{parseResult:{value:{specifications:e}},c4Specification:t}=this.doc,r=this.isValid;for(let i of e.flatMap(e=>e.elements.filter(r)))try{Object.assign(t.elements,this.parseElementSpecificationNode(i))}catch(e){this.logError(e,i,`specification`)}for(let i of e.flatMap(e=>e.deploymentNodes.filter(r)))try{Object.assign(t.deployments,this.parseElementSpecificationNode(i))}catch(e){this.logError(e,i,`specification`)}let i=e.flatMap(e=>e.relationships.filter(this.isValid));for(let e of i){let{kind:r,props:i}=e;try{let a=r.name;if(!j(a))continue;if(a in t.relationships){this.logError(`Relationship kind "${a}" is already defined`,r,`specification`);continue}let s=this.parseTags(e),c=this.parseLinks(e),l=N(i.filter(isSpecificationRelationshipStringProperty)??[],D(e=>this.isValid(e)),m(e=>[e.key,e.value])),{summary:u,...p}=this.parseBaseProps(l),h=removeIndent(parseMarkdownAsString(l.notation)),g=i.filter(isMultipleProperty);g.length>1&&this.logError(`Duplicate 'multiple' property for relationship "${a}", using the first one`,r,`specification`);let _=g[0];t.relationships[a]=exact({...p,notation:h,tags:s??void 0,...c&&isNonEmptyArray(c)&&{links:c},...toRelationshipStyle(i.filter(isRelationshipStyleProperty),this.isValid),..._&&{multiple:_.value}})}catch(e){this.logError(e,r,`specification`)}}let a=e.flatMap(e=>e.tags.filter(this.isValid));for(let e of a)try{let r=e.tag.name,i=this.getAstNodePath(e.tag),a=toColor(e)??(e.color&&this.parseColorLiteral(e.color));if(r in t.tags){this.logError(`Tag ${r} is already defined, skipping duplicate`,e,`specification`);continue}j(r)&&(t.tags[r]={astPath:i,...a?{color:a}:{}})}catch(t){this.logError(t,e,`specification`)}let s=e.flatMap(e=>e.colors.filter(r));for(let{name:e,color:r}of s)try{let i=e.name;if(i in t.colors){this.logError(`Custom color "${i}" is already defined`,e,`specification`);continue}t.colors[i]={color:nonNullable(this.parseColorLiteral(r),`Color "${i}" is not valid`)}}catch(e){this.logError(e,r,`specification`)}}parseElementSpecificationNode(e){let{kind:t,props:r}=e,i=t.name;if(!j(i))throw Error(`DeploymentNodeKind name is not resolved`);let a=this.parseTags(e),s=this.parseElementStyle(r.find(isElementStyleProperty)),c=this.parseLinks(e),l=N(r.filter(isSpecificationElementStringProperty)??[],D(e=>this.isValid(e)),m(e=>[e.key,e.value])),u=this.parseBaseProps(l),p=removeIndent(parseMarkdownAsString(l.notation));return{[i]:exact({...u,notation:p,tags:a??void 0,...c&&isNonEmptyArray(c)&&{links:c},style:s})}}}}function ViewsParser(e){return class ViewsParser extends e{parseViews(){let e=this.isValid;for(let t of this.doc.parseResult.value.views){let r=t.styles.flatMap(t=>{try{return e(t)?this.parseViewRuleStyleOrGlobalRef(t):[]}catch(e){return this.logError(e,t,`views`),[]}}),i=t.folder&&!w(t.folder.trim())?toSingleLine(t.folder):null;for(let a of t.views)try{if(!e(a))continue;switch(!0){case isElementView(a):this.doc.c4Views.push(this.parseElementView(a,r));break;case isDynamicView(a):this.doc.c4Views.push(this.parseDynamicElementView(a,r));break;case isDeploymentView(a):this.doc.c4Views.push(this.parseDeploymentView(a));break;default:nonexhaustive(a)}if(i){let e=this.doc.c4Views.at(-1);e.title=i+` / `+(e.title||e.id)}}catch(e){this.logError(e,a,`views`)}}}parseElementView(e,t){let r=e.body;invariant(r,`ElementView body is not defined`);let i=r.props.filter(this.isValid),a=this.getAstNodePath(e),s=null,c=e.viewOf;if(c){let t=safeCall(()=>this.parseModelElementRef(c,`Invalid reference to viewOf`));if(t)s=t;else{let t=e.name??`unnamed`,r=c.$cstNode?.text??`<unknown>`;this.logError(`viewOf ${t} not resolved ${r}`,c)}}let l=e.name;l||=`view_`+stringHash(this.doc.uri.toString(),a,s??``);let u=N(i,D(isViewStringProperty),m(e=>[e.key,e.value])),{title:p=null,description:h=null}=this.parseBaseProps(u,{title:parseTitleKeepingEscapedSlash(u.title)}),g=this.convertTags(r),_=this.convertLinks(r),v=parseViewOrder(i.find(isViewOrderProperty)),y=parseViewRouting(i,r.rules),b={[Hi]:`element`,id:l,astPath:a,title:toSingleLine(p)??null,description:h,...v!==void 0&&{order:v},...y&&{routing:y},tags:g,links:isNonEmptyArray(_)?_:null,rules:[...t,...this.tryMap(`views`,r.rules,e=>this.parseElementViewRule(e))],...s&&{viewOf:s}};if(bu.writeId(e,b.id),`extends`in e){let t=e.extends.view.ref;return invariant(t?.name,`view extends is not resolved: `+e.$cstNode?.text),Object.assign(b,{extends:t.name})}return b}parseElementViewRule(e){if(isViewRulePredicate(e))return this.parseViewRulePredicate(e);if(isViewRuleGlobalPredicateRef(e))return this.parseViewRuleGlobalPredicateRef(e);if(isViewRuleStyleOrGlobalRef(e))return this.parseViewRuleStyleOrGlobalRef(e);if(isViewRuleAutoLayout(e))return toAutoLayout(e);if(isViewRuleGroup(e))return this.parseViewRuleGroup(e);if(isViewRuleRank(e))return this.parseViewRuleRank(e);nonexhaustive(e)}parseViewRulePredicate(e){let t=[],r=e.exprs;for(;r;){let{value:e,prev:i}=r;if(this.tryParse(`views`,e,()=>{let r=this.parsePredicate(e);t.unshift(r)}),!i)break;r=i}return e.isInclude?{include:t}:{exclude:t}}parseViewRuleGlobalPredicateRef(e){return{predicateId:e.predicate.$refText}}parseViewRuleStyleOrGlobalRef(e){if(isViewRuleStyle(e))return this.parseViewRuleStyle(e);if(isViewRuleGlobalStyle(e))return this.parseViewRuleGlobalStyle(e);nonexhaustive(e)}parseViewRuleGroup(e){let t=[];for(let r of e.groupRules)try{if(!this.isValid(r))continue;if(isViewRulePredicate(r)){t.push(this.parseViewRulePredicate(r));continue}if(isViewRuleGlobalPredicateRef(r)){t.push(this.parseViewRuleGlobalPredicateRef(r));continue}if(isViewRuleGroup(r)){t.push(this.parseViewRuleGroup(r));continue}nonexhaustive(r)}catch(e){this.logError(e,r,`views`)}return{title:toSingleLine(e.title)??null,groupRules:t,...this.parseStyleProps(e.props)}}parseViewRuleRank(e){let t=this.parseFqnExpressions(e.targets).filter(e=>Ji.isFqnExpr(e));return{rank:e.value??`same`,targets:t}}parseViewRuleStyle(e){let t=this.parseFqnExpressions(e.targets).filter(e=>Ji.isFqnExpr(e)),r=this.parseStyleProps(e.props.filter(isStyleProperty)),i=removeIndent(parseMarkdownAsString(e.props.find(isNotationProperty)?.value));return{targets:t,style:r,...i&&{notation:i}}}parseViewRuleGlobalStyle(e){return{styleId:e.style.$refText}}parseDynamicElementView(e,t){let r=e.body;invariant(r,`DynamicElementView body is not defined`);let i=this.isValid,a=r.props.filter(i),s=this.getAstNodePath(e),c=e.name;c||=`dynamic_`+stringHash(this.doc.uri.toString(),s);let l=N(a,D(isViewStringProperty),m(e=>[e.key,e.value])),{title:u=null,description:p=null}=this.parseBaseProps(l,{title:parseTitleKeepingEscapedSlash(l.title)}),h=this.convertTags(r),g=this.convertLinks(r),_=parseViewOrder(a.find(isViewOrderProperty));bu.writeId(e,c);let v=Le(a,isDynamicViewDisplayVariantProperty)?.value,y=parseViewRouting(a,r.rules);return{[Hi]:`dynamic`,id:c,astPath:s,title:toSingleLine(u)??null,description:p,..._!==void 0&&{order:_},...y&&{routing:y},tags:h,links:isNonEmptyArray(g)?g:null,variant:v,rules:[...t,...this.tryMap(`views`,r.rules,e=>this.parseDynamicViewRule(e))],steps:this.parseSteps(r.steps)}}parseDynamicViewRule(e){if(isDynamicViewIncludePredicate(e))return this.parseDynamicViewIncludePredicate(e);if(isDynamicViewGlobalPredicateRef(e))return this.parseViewRuleGlobalPredicateRef(e);if(isViewRuleStyleOrGlobalRef(e))return this.parseViewRuleStyleOrGlobalRef(e);if(isViewRuleAutoLayout(e))return toAutoLayout(e);nonexhaustive(e)}parseDynamicViewIncludePredicate(e){let t=[],r=e.exprs;for(;r;)this.tryParse(`views`,r.value,e=>{if(isFqnExprOrWith(e)){let r=this.parseElementPredicate(e);t.unshift(r)}}),r=r.prev;return{include:t}}parseSteps(e){return this.tryMap(`views`,e,e=>this.parseStepStatement(e))}parseStepStatement(e){switch(!0){case isSubflowStep(e):return this.parseSubflowStep(e);case isTryStep(e):return this.parseTryStep(e);case isAltSteps(e):return this.parseAltSteps(e);case isStepSeries(e):return this.parseStepSeries(e);case isStep(e):return this.parseStep(e);default:nonexhaustive(e)}}parseStepSeries(e){let t=this.recursiveParseStepSeries(e);return invariant(isNonEmptyArray(t),`Dynamic step chain must have at least one step`),{[Hi]:`series`,steps:t}}recursiveParseStepSeries(e,t){if(isStep(e.source)){if(!this.isValid(e.source))return[];let r=this.parseStep(e.source);if(r.isBackward)return[];let i={...this.parseAbstractDynamicStep(e),source:r.target};return i.target===r.source?i.isBackward=!0:t&&(t.push([r.source,r.target]),t.push([i.source,i.target])),[r,i]}t??=[];let r=this.recursiveParseStepSeries(e.source,t);if(!isNonEmptyArray(r)||!this.isValid(e))return[];let i=te(r),a={...this.parseAbstractDynamicStep(e),source:i.target},s=t.findIndex(([e,t])=>e===a.target&&t===a.source);return s===-1?t.push([a.source,a.target]):(a.isBackward=!0,t.splice(s,t.length-s)),[...r,a]}parseStep(e){let t={...this.parseAbstractDynamicStep(e),source:this.parseDynamicStepEndpoint(e.source,`source`)};return e.isBackward&&(t={...t,source:t.target,target:t.source,isBackward:!0}),t}parseAbstractDynamicStep(e){let t=pathInsideDynamicView(e),r={target:this.parseDynamicStepEndpoint(e.target,`target`),astPath:t},i=removeIndent(e.title);i&&(r.title=i);let a=e.kind?.ref?.name??e.dotKind?.kind.ref?.name;a&&(r.kind=a);for(let t of e.custom?.props??[])try{switch(!0){case isRelationNavigateToProperty(t):{let e=t.value.view.ref?.name;j(e)&&(r.navigateTo=e);break}case isRelationStringProperty(t):case isNotationProperty(t):if(T(t.value)){if(t.key===`description`){let e=removeIndent(t.value);e&&(r.description=e)}else r[t.key]=removeIndent(parseMarkdownAsString(t.value))??``}break;case isNotesProperty(t):T(t.value)&&(r[t.key]=removeIndent(t.value));break;case isArrowProperty(t):T(t.value)&&(r[t.key]=t.value);break;case isColorProperty(t):{let e=toColor(t);T(e)&&(r[t.key]=e);break}case isLineProperty(t):T(t.value)&&(r[t.key]=t.value);break;case isMultipleProperty(t):break;default:nonexhaustive(t)}}catch(e){this.logError(e,t,`views`)}return r}parseModelElementRef(e,t){let r=this.parseFqnRef(e.modelElement);if(!H.isModelRef(r))throw Error(t);return H.flatten(r)}parseDynamicStepEndpoint(e,t){return this.parseModelElementRef(e,`Invalid reference to ${t}`)}parseSubflowStep(e){let t=e.kind===`parallel`?`par`:e.kind;switch(t){case`break`:case`loop`:case`opt`:case`par`:{let r=this.parseSteps(e.steps);return invariant(isNonEmptyArray(r),`Parallel steps must have at least one step`),exact({[Hi]:t,title:e.title,steps:r})}case`else`:case`if`:case`when`:throw Error(`Unsupported kind: ${t}`);default:nonexhaustive(t)}}parseTryStep(e){if(invariant(this.isValid(e)),isFinallyBlock(e)){let t=this.parseTryStep(e.tryCatch),r=this.parseSteps(e.finally.steps);return isNonEmptyArray(r)?{...t,finally:exact({title:e.title,steps:r})}:t}if(isCatchBlock(e)){let t=this.parseTryStep(e.try),r=this.parseSteps(e.catch.steps);return isNonEmptyArray(r)?{...t,catch:exact({title:e.title,steps:r})}:t}let t=this.parseSteps(e.steps);return invariant(isNonEmptyArray(t),`Try steps must have at least one step`),{[Hi]:`try`,try:exact({title:e.title,steps:t})}}parseAltSteps(e){let t=this.tryMap(`views`,e.branches,e=>{let t=e.kind;invariant(t===`if`||t===`else`||t===`when`,`Expected "if", "else", or "when", got "${t}"`);let r=this.parseSteps(e.steps);return invariant(isNonEmptyArray(r),`Branch steps must have at least one step`),exact({[Hi]:t,title:e.title,steps:r})});return invariant(isNonEmptyArray(t),`Alt must have at least one branch`),exact({[Hi]:`alt`,title:e.title,branches:t})}}}function pathInsideDynamicView(e){let t=e,r=[];for(;!isDynamicViewBody(t);)x(t.$containerIndex)&&r.unshift(`@${t.$containerIndex}`),r.unshift(`/${t.$containerProperty??`__invalid__`}`),t=t.$container;return r.join(``)}const Yd=N(BaseParser,ExpressionV2Parser,ImportsParser,ModelParser,DeploymentModelParser,DeploymentViewParser,PredicatesParser,SpecificationParser,ViewsParser,GlobalsParser);var DocumentParser=class extends Yd{};const Xd=q.getChild(`parser`),isError=e=>e.severity===Lr.Error;var LikeC4ModelParser=class extends ADisposable{services;cachedParsers=new Ze.default(e=>this.createParser(e));constructor(e){super(),this.services=e,this.onDispose(Wn.create(()=>{this.cachedParsers.clear()}),e.shared.workspace.DocumentBuilder.onDocumentPhase(rn.Linked,async t=>{this.cachedParsers.has(t)&&(Xd.trace(`clear cached parser {doc} on onDocumentPhase Linked`,{doc:e.shared.workspace.WorkspaceManager.relativePath(t.uri)}),this.cachedParsers.delete(t))}),e.shared.workspace.DocumentBuilder.onBuildPhase(rn.Linked,async e=>{for(let t of e)if(isLikeC4UserDocument(t))try{this.parse(t)}catch(e){logWarnError(e)}}),e.shared.workspace.DocumentBuilder.onDocumentPhase(rn.Validated,async e=>{e.diagnostics?.some(isError)&&this.cachedParsers.has(e)&&(Xd.trace(`project {project}, Validated: clear cached parser {doc} because of errors`,{project:e.likec4ProjectId,doc:L.basename(e.uri)}),this.cachedParsers.delete(e))}))}documents(e){return this.services.shared.workspace.LangiumDocuments.projectDocuments(e).map(e=>this.parse(e))}parse(e){return this.forDocument(e).doc}forDocument(e){return this.cachedParsers.get(e)}createParser(e){invariant(isLikeC4LangiumDocument(e),`Document ${e.uri.toString()} is not a LikeC4 document`);let t=this.services.shared.workspace.ProjectsManager.getProject(e),r=L.relative(t.folderUri,e.uri);Xd.trace(`project {project}, create parser {doc}`,{project:t.id,doc:r}),e.state<rn.Linked&&Xd.warn(`document {doc} is not linked, state is {state}`,{doc:r,state:e.state});let i={c4Specification:{tags:{},elements:{},relationships:{},colors:{},deployments:{}},c4Elements:[],c4ExtendElements:[],c4ExtendDeployments:[],c4ExtendRelations:[],c4Relations:[],c4Deployments:[],c4DeploymentRelations:[],c4Globals:{predicates:{},dynamicPredicates:{},styles:{}},c4Views:[],c4Imports:new Ye.default(Set)};e=Object.assign(e,i);let a=new DocumentParser(this.services,e,t);try{a.parseSpecification(),a.parseImports(),a.parseModel(),a.parseDeployment(),a.parseGlobals(),a.parseViews()}catch(e){throw Error(`Error parsing document ${r}`,{cause:e})}return a}},LikeC4ValueConverter=class extends tn{runConverter(e,t,r){return e.name===`MarkdownString`?((t.startsWith(`"""`)&&t.endsWith(`"""`)||t.startsWith(`'''`)&&t.endsWith(`'''`))&&(t=t.slice(2,-2)),cn.convertString(t)):super.runConverter(e,t,r)}};const{findNodeForKeyword:Zd}=Xt,asViewStyleRule=(e,t,r=0)=>{let i=r>0?` `.repeat(r):``;return[i+`style ${e} {`,...M(t).map(([e,t])=>i+` ${e} ${e===`opacity`?t.toString()+`%`:t}`),i+`}`]},isMatchingViewRule=(e,t)=>r=>{if(!isViewRuleStyle(r)&&!isDeploymentViewRuleStyle(r))return!1;let i=r.targets.value;if(!i||j(r.targets.prev)||i.$type!==`FqnRefExpr`||j(i.selector))return!1;let a=i.ref?.value?.ref;return(a?t.resolve(a):null)===e};function changeElementStyle(e,{view:t,viewAst:r,targets:i,style:a}){invariant(r.body,`View ${t.id} has no body`);let s=nonNullable(r.$cstNode,`cant find view cst node`),c=nonNullable(r.body.$cstNode,`cant find view body cst node`),l=nonNullable(Zd(c,`}`),`cant find closing brace`);invariant(l.container,`Closing brace has no container`);let u=l.container.content,p=te(r.body.rules)?.$cstNode??u[u.indexOf(l)-1];invariant(p,`anchor is not defined`);let m=p.range.end,h=l.range.start.line===m.line?`
|
|
126
|
+
`+` `.repeat(s.range.start.character):``,g=s.range.start.character+2,_=[],v=e.likec4.FqnIndex,y=D(r.body.rules,e=>isViewRuleStyle(e)||isDeploymentViewRuleStyle(e)),b=t._type===`element`?t.viewOf??null:null,x=[],S=[];i.forEach(e=>{let t=Me(y,isMatchingViewRule(e,v)),r=b&&isAncestor(b,e)?e.substring(b.length+1):e;t?x.push({fqn:r,rule:t}):S.push({fqn:r})});let ee={start:m,end:m},includeRange=e=>{e.start.line<=ee.start.line&&(e.start.line==ee.start.line?ee.start.character=Math.min(e.start.character,ee.start.character):ee.start=e.start),e.end.line>=ee.end.line&&(e.end.line==ee.end.line?ee.end.character=Math.max(e.end.character,ee.end.character):ee.end=e.end)};if(S.length>0){let e=S.flatMap(({fqn:e})=>asViewStyleRule(e,a,g));_.push(Wr.insert(m,`
|
|
127
|
+
`+e.join(`
|
|
128
|
+
`)+h)),ee.start={line:m.line+1,character:g},ee.end={line:m.line+e.length,character:te(e)?.length??0}}if(x.length>0)for(let{rule:e}of x){let t=e.$cstNode;invariant(t,`RuleCstNode not found`);for(let[r,i]of M(a)){let a=r===`opacity`?i.toString()+`%`:i,s=e.props.find(e=>e.key===r);if(s&&s.$cstNode){let{range:{start:e,end:t}}=s.$cstNode,i=r+` `+a;includeRange({start:e,end:{...t,character:e.character+i.length}}),_.push(Wr.replace({start:e,end:t},i));continue}let c=nonNullable(Zd(t,`}`),`cant find closing brace`).range.start,l=` `.repeat(t.range.start.character)+` `,u=r+` `+a;_.push(Wr.insert({line:c.line,character:0},l+u+`
|
|
129
|
+
`)),includeRange({start:{line:c.line,character:l.length},end:{line:c.line,character:l.length+u.length}})}}return{modifiedRange:ee,edits:_}}const Qd=new Rn(`
|
|
130
|
+
`);function toStringLF(e,t){return Dn(e,t).replaceAll(`\r
|
|
131
|
+
`,`
|
|
132
|
+
`)}function hasContent(e){return typeof e==`string`?e.trimStart().length!==0:e instanceof Nn&&e.contents.some(e=>hasContent(e))}function hasContentOrNewLine(e){return typeof e==`string`?e.trimStart().length!==0:e instanceof Rn?!e.ifNotEmpty:e instanceof Nn&&e.contents.some(e=>hasContentOrNewLine(e))}function fresh(e){return{ctx:e??void 0,out:new Nn}}function materialize(...e){let t,r=2;if(e.length===1){let[r]=e;if(oe(r))return e=>materialize(r,e);if(`op`in r){let{op:e,...t}=r;return r=>materialize(e,r,{indent:2,...t})}t=r}else{let[i,a,s]=e;t=executeOnFresh(a,[i]),r=s?.indent??2}return invariant(S(r)||x(r),`defaultIndentation must be a string or a number`),toStringLF(t.out,r)}function executeOnCtx(e,t,...r){b(t)?(invariant(r.length===0,`When first argument is an array, no additional operations are allowed`),r=t):r=[t,...r];for(let t of r)e=t(e);return e}function executeOnFresh(e,t,...r){return b(t)?executeOnCtx(fresh(e),t):executeOnCtx(fresh(e),[t,...r])}function eachOnFresh(e,t){return t.map(t=>t(fresh(e)))}function operation(e,t){let r=typeof e==`function`?e:t,wrapped=e=>{let t=r(e);return t instanceof Nn?{...e,out:t}:e};return typeof e==`string`&&r.name==``&&Object.defineProperties(wrapped,{name:{value:`wrapped(${e})`}}),wrapped}function isPrintable(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function print$1(e){return operation(function printOp({ctx:t,out:r}){let i=typeof e==`function`?e(t):e??t;C(i)||i===``||(invariant(isPrintable(i),`Value must be a string, number or boolean - got `+typeof i),r.append(String(i)))})}e(print$1,`print`);const space=()=>print$1(` `);function noop(){return e=>e}function lazy(e){return t=>(e()(t),t)}function newline(e){return operation(({out:t})=>{e===`ifNotEmpty`?t.appendNewLineIfNotEmpty():t.appendNewLine()})}function merge(...e){return operation(function merge({ctx:t,out:r}){let i=executeOnFresh(t,e);r.appendIf(hasContent(i.out),i.out)})}function indent(...e){if(e.length===1&&typeof e[0]==`string`){let t=dedent(e[0]);return t.trimStart().length===0?noop():operation(function indent1({out:e}){e.appendNewLineIfNotEmpty().indent({indentEmptyLines:!0,indentedChildren:[Vn(t.split(/\r?\n/),{separator:Qd})]}).appendNewLineIfNotEmpty()})}let t=e;return operation(function indent2({ctx:e,out:r}){let i=executeOnFresh(e,t);hasContent(i.out)&&r.appendNewLineIfNotEmpty().indent({indentEmptyLines:!0,indentedChildren:i.out.contents}).appendNewLineIfNotEmpty()})}function body(...e){let t=F(e);if(S(t))return body(t+` {`,`}`);if(e.length===2&&S(e[0])&&S(e[1])){let[t,r]=e;return(...e)=>operation(function body({ctx:i,out:a}){let s=indent(lines(...e))(fresh(i)).out;a.appendIf(hasContent(s),Vn([t,s,r]))})}let r=e;return body(`{`,`}`)(...r)}function inlineText(e){return operation(({ctx:t,out:r})=>{let i=e??t;if(C(i))return;invariant(S(i),`Value must be a string - got `+typeof i);let a=i.replace(/(\r?\n|\t)+/g,` `).replaceAll(`'`,`\\'`).trim();r.append(`'${a}'`)})}function multilineText(e,t=`'`){return merge(print$1(t),indent(e.replaceAll(`'`,`\\'`)),print$1(t))}function text(e){return operation(function text({ctx:t,out:r}){let i=typeof e==`function`?e(t):e??t;if(!C(i))return invariant(S(i),`Value must be a string - got `+typeof i),i.includes(`
|
|
133
|
+
`)?multilineText(i)({ctx:i,out:r}):inlineText()({ctx:i,out:r})})}const $d=`'`.repeat(3);function markdown(e){return operation(function markdown(t){let r=e??t.ctx;if(!C(r))return invariant(S(r),`Value must be a string - got `+typeof r),multilineText(r,$d)(t)})}function markdownOrString$1(e){return operation(function markdownOrString(t){let r=e??t.ctx;if(!C(r)){if(typeof r==`string`)return text(r)(t);if(`md`in r)return markdown(r.md)(t);if(`txt`in r)return multilineText(r.txt)(t);throw Error(`Invalid MarkdownOrString value: `+r)}})}e(markdownOrString$1,`markdownOrString`);function join(e){return operation(function joinOp({ctx:t,out:r}){let{operations:i,...a}=e,s=Array.isArray(i)?i:[i];invariant(k(s,1),`At least one operation is required`);let c;return c=s.length===1?s[0](fresh(t)).out.contents:N(eachOnFresh(t,s),p(e=>e.out)),c=D(c,hasContentOrNewLine),r.appendIf(c.length>0,Vn(c,a))})}function spaceBetween(...e){return join({operations:e,suffix:(e,t,r)=>!r&&hasContent(e)?` `:void 0})}function lines(...e){let t=F(e);if(x(t)){let e=fresh(void 0);for(let r=0;r<t;r++)e.out.appendNewLine();return(...t)=>join({operations:t,suffix:(t,r,i)=>i?void 0:e.out})}return join({operations:e,appendNewLineIfNotEmpty:!0,skipNewLineAfterLastItem:!0})}function withctx(...e){if(e.length===0)return(...e)=>operation(function withctx1(t){return executeOnCtx(t,e)});let t=e[0];if(e.length===1)return(...e)=>operation(function withctx1({out:r}){return executeOnCtx({ctx:t,out:r},e)});let r=e.slice(1);return operation(function withctx2({out:e}){return executeOnCtx({ctx:t,out:e},r)})}function property(e,t){return operation(function propertyOp({ctx:r,out:i}){let a=v(r)&&hasProp(r,e)?r[e]:void 0;a!=null&&(t?t({ctx:a,out:i}):(invariant(isPrintable(a),`Property ${e} is not printable "${a}"`),i.append(e,` `,String(a))))})}function printProperty(e){return property(e,print$1())}function foreach(...e){let[t,r]=e;if(e.length===2&&!oe(r)){let e=t,i=r;return operation(function foreachSingleOp({ctx:t,out:r}){let a=[];for(let r of t){let t=e(fresh(r)).out;hasContent(t)&&a.push(t)}r.appendIf(a.length>0,Vn(a,i))})}let i=e;return operation(({ctx:e,out:t})=>{for(let r of e)executeOnCtx({ctx:r,out:t},i)})}function separateWith(e){return{separator:e}}function separateNewLine(e=1){if(e>1){let t=fresh(void 0);for(let r=0;r<e;r++)t.out.appendNewLine();return separateWith(t.out)}return separateWith(Qd)}function separateComma(e){return e?{separator:`,`,appendNewLineIfNotEmpty:!0,skipNewLineAfterLastItem:!0}:{separator:`, `}}function foreachNewLine(...e){return operation(function foreachNewLineOp({ctx:t,out:r}){let i=[];for(let r of t){let t=executeOnFresh(r,e).out;hasContent(t)&&i.push(t)}r.appendIf(i.length>0,Vn(i,separateNewLine()))})}function guard(e,...t){return operation(`guard`,({ctx:r,out:i})=>{if(`safeParse`in e){let a=e.safeParse(r);if(a.success)executeOnCtx({ctx:a.data,out:i},t);else throw Error(`Guard failed: ${$r.prettifyError(a.error)}`)}else invariant(typeof e==`function`),e(r)&&executeOnCtx({ctx:r,out:i},t)})}function when(e,...t){return operation(function whenOp({ctx:r,out:i}){e(r)&&executeOnCtx({ctx:r,out:i},t)})}function select(e,...t){return operation(function selectOp({ctx:r,out:i}){let a=e(r);l(a)&&executeOnCtx({ctx:a,out:i},t)})}function execToOut(e){return(t,...r)=>executeOnCtx({ctx:t,out:e},r)}function zodOp(e){return t=>{let zodParseOp=()=>({ctx:r,out:i})=>{let a=$r.safeParse(e,r);if(a.success){let e=t({ctx:a.data,out:i,exec:execToOut(i)});return C(e)?{ctx:r,out:i}:e instanceof Nn?{ctx:r,out:e}:typeof e==`function`?{ctx:r,out:i,...e({ctx:r,out:i})}:hasProp(e,`ctx`)&&hasProp(e,`out`)?e:{ctx:r,out:i}}throw a.error};return zodParseOp.noparse=()=>({ctx:e,out:r})=>{let i=t({ctx:e,out:r,exec:execToOut(r)});return i instanceof Nn?{ctx:e,out:i}:typeof i==`function`?{ctx:e,out:r,...i({ctx:e,out:r})}:{ctx:e,out:r}},zodParseOp}}var ef=/* @__PURE__ */ t({arrow:()=>pf,border:()=>lf,color:()=>Sf,customColor:()=>vf,fqn:()=>rf,icon:()=>cf,iconPosition:()=>df,id:()=>tf,kind:()=>af,line:()=>mf,link:()=>hf,links:()=>gf,markdownOrString:()=>xf,metadata:()=>Tf,metadataValue:()=>wf,opacity:()=>of,props:()=>Ef,shape:()=>sf,size:()=>uf,sizing:()=>ff,style:()=>Cf,tag:()=>yf,tags:()=>bf,themeColor:()=>_f,viewId:()=>nf});const tf=z.string().regex(/^[a-zA-Z0-9_.-]+$/,`id must consist of alphanumeric characters, underscores or hyphens`),nf=tf.transform(e=>e),rf=z.string().regex(/^[a-zA-Z0-9_.-]+$/,`FQN must consist of alphanumeric characters, dots, underscores or hyphens`).transform(e=>e),af=z.string().regex(/^[a-zA-Z0-9_-]+$/,`Kind must consist of alphanumeric characters, underscores or hyphens`).transform(e=>e),of=z.int().min(0,`Opacity must be between 0 and 100`).max(100,`Opacity must be between 0 and 100`),sf=z.enum(Ni),cf=z.string().nonempty(`Icon cannot be empty`).transform(e=>e),lf=z.enum(Mi),uf=z.enum(ki),df=z.enum(Ai),ff=z.enum(ji),pf=z.enum(fa),mf=z.enum(da),hf=z.union([z.string(),z.object({title:z.string().optional(),url:z.string()})]).transform(e=>exact(typeof e==`string`?{url:e}:e)),gf=z.array(hf).readonly(),_f=z.enum(Pi),vf=z.string().nonempty(`Custom color name cannot be empty`).transform(e=>e),yf=z.string().nonempty(`Tag cannot be empty`).transform(e=>e.startsWith(`#`)?e.slice(1):e),bf=z.array(yf).readonly(),xf=z.union([z.string().transform(e=>({txt:e})),z.strictObject({md:z.string()}),z.strictObject({txt:z.string()})]),Sf=_f.or(vf),Cf=z.object({shape:sf,icon:cf,iconColor:Sf,iconSize:uf,iconPosition:df,color:Sf,border:lf,opacity:of,size:uf,padding:uf,textSize:uf,sizing:ff,multiple:z.boolean()}).partial().transform(He(l)),wf=z.union([z.string(),z.boolean(),z.number()]),Tf=z.record(z.string(),wf.or(z.array(wf))),Ef=z.object({tags:bf.nullish(),title:z.string().nullish(),summary:xf.nullish(),description:xf.nullish(),notation:z.string().nullish(),technology:z.string().nullish(),links:gf.nullish(),metadata:Tf.nullish()});var Df=/* @__PURE__ */ t({directRelationExpr:()=>$f,elementKindExpr:()=>Uf,elementTagExpr:()=>Wf,expression:()=>lp,fqnExpr:()=>Gf,fqnExprAny:()=>Qf,fqnExprCustom:()=>Zf,fqnExprOrWhere:()=>qf,fqnRef:()=>Af,incomingRelationExpr:()=>ep,inoutRelationExpr:()=>np,outgoingRelationExpr:()=>tp,refDeployment:()=>kf,refExpr:()=>Hf,refModel:()=>Of,relationExpr:()=>rp,relationExprAny:()=>sp,relationExprCustom:()=>op,relationExprOrWhere:()=>ap,selector:()=>jf,whereAnd:()=>Lf,whereExpr:()=>cp,whereKind:()=>Nf,whereMetadata:()=>Pf,whereNot:()=>Rf,whereOperator:()=>Bf,whereOr:()=>zf,whereParticipant:()=>If,whereTag:()=>Mf,wildcardExpr:()=>Vf});const Of=z.strictObject({model:rf,project:z.string().optional()}),kf=z.strictObject({deployment:rf,element:rf.nullish()}),Af=z.union([Of,kf]),jf=z.enum([`children`,`expanded`,`descendants`,`*`,`_`,`**`]).transform(e=>{switch(e){case`*`:return`children`;case`_`:return`expanded`;case`**`:return`descendants`;default:return e}});function equalOp(e){return z.xor([z.object({eq:e}),z.object({neq:e}),e.transform(e=>({eq:e}))])}const Mf=z.strictObject({tag:equalOp(yf)}),Nf=z.strictObject({kind:equalOp(af)}),Pf=z.strictObject({metadata:z.strictObject({key:z.string(),value:equalOp(z.string()).optional()})}),Ff=z.union([Mf,Nf,Pf]),If=z.strictObject({participant:z.enum([`source`,`target`]),operator:Ff}),Lf=z.object({get and(){return z.array(Bf)}}),Rf=z.object({get not(){return Bf}}),zf=z.object({get or(){return z.array(Bf)}}),Bf=z.union([Mf,Nf,Pf,If,Lf,zf,Rf]),Vf=z.strictObject({wildcard:z.literal(!0)}),Hf=z.object({ref:Af,selector:jf.nullish()}).transform(He(l)),Uf=z.object({elementKind:af,isEqual:z.boolean()}),Wf=z.object({elementTag:yf,isEqual:z.boolean()}),Gf=z.union([Vf,Hf,Uf,Wf]),Kf=z.strictObject({where:z.strictObject({expr:Gf,condition:Bf})}),qf=z.union([Gf,Kf]),Jf=z.object({title:z.string(),description:xf,technology:z.string(),notation:z.string(),notes:xf,navigateTo:nf,color:Sf}),Yf=z.object({...Jf.shape,shape:sf,icon:cf,iconColor:Sf,iconSize:uf,iconPosition:df,border:lf,opacity:of,multiple:z.boolean(),size:uf,padding:uf,textSize:uf,sizing:ff}).partial(),Xf=z.object({...Jf.shape,line:mf,head:pf,tail:pf}).partial(),Zf=z.strictObject({custom:Yf.extend({expr:qf})}),Qf=z.union([qf,Zf]),$f=z.strictObject({source:Gf,target:Gf,isBidirectional:z.boolean().optional()}),ep=z.object({incoming:Gf}),tp=z.object({outgoing:Gf}),np=z.object({inout:Gf}),rp=z.union([$f,ep,tp,np]),ip=z.strictObject({where:z.strictObject({expr:rp,condition:Bf})}),ap=z.union([rp,ip]),op=z.strictObject({customRelation:Xf.extend({expr:ap})}),sp=z.union([ap,op]),cp=z.strictObject({where:z.object({expr:z.xor([Gf,rp]),condition:Bf})}),lp=z.union([Gf,Zf,rp,op,cp]);var up=/* @__PURE__ */ t({element:()=>gp,instance:()=>fp,node:()=>dp,relationship:()=>hp,schema:()=>bp});const dp=Ef.extend({id:rf,kind:af,style:Cf.optional(),shape:sf.optional(),color:Sf.optional(),icon:cf.optional()}).readonly().transform(e=>{let{shape:t,color:r,icon:i,...a}=e;return He(vt(a,e=>{e.style=a.style||{},t&&(e.style.shape=t),r&&(e.style.color=r),i&&(e.style.icon=i)}),l)}),fp=Ef.extend({id:rf,element:rf,style:Cf.optional(),shape:sf.optional(),color:Sf.optional(),icon:cf.optional()}).readonly().transform(e=>{let{shape:t,color:r,icon:i,...a}=e;return He(vt(a,e=>{e.style=a.style||{},t&&(e.style.shape=t),r&&(e.style.color=r),i&&(e.style.icon=i)}),l)}),pp=kf,mp=tf.transform(e=>e),hp=Ef.extend({id:mp.optional(),title:z.string().nullish(),source:pp,target:pp,isBidirectional:z.boolean().nullish(),navigateTo:nf.nullish(),color:Sf.nullish(),kind:af.nullish(),line:mf.nullish(),head:pf.nullish(),tail:pf.nullish()}).readonly().transform(He(l)),gp=z.union([dp,fp]),_p=z.record(rf,gp),vp=z.record(mp,hp),yp=/* @__PURE__ */ e(e=>e.id??Ne(8),`genRelationshipId`),bp=z.object({elements:z.union([_p,z.array(gp)]).transform(e=>b(e)?Pe(e,A(`id`)):e).optional(),relations:z.union([vp,z.array(hp)]).transform(e=>b(e)?Pe(e,yp):e).optional()});var xp=/* @__PURE__ */ t({element:()=>Sp,elements:()=>Ep,relationship:()=>Tp,relationshipEndpoint:()=>Cp,relationshipId:()=>wp,relationships:()=>Dp,schema:()=>Ap});const Sp=z.object({...Ef.shape,id:rf,kind:af,style:Cf.optional(),shape:sf.optional(),color:Sf.optional(),icon:cf.optional()}).transform(e=>{let{shape:t,color:r,icon:i,...a}=e;return(t||r||i)&&(a=vt(a,e=>{e.style=a.style||{},t&&(e.style.shape=t),r&&(e.style.color=r),i&&(e.style.icon=i)})),He(a,l)}).readonly(),Cp=z.union([rf,z.strictObject({model:rf})]).transform(e=>typeof e==`string`?{model:e}:e),wp=tf.transform(e=>e),Tp=z.object({...Ef.shape,id:wp.optional(),title:z.string().nullish(),source:Cp,target:Cp,isBidirectional:z.boolean().nullish(),navigateTo:nf.nullish(),color:Sf.nullish(),kind:af.nullish(),line:mf.nullish(),head:pf.nullish(),tail:pf.nullish()}).transform(He(l)).readonly(),Ep=z.record(rf,Sp),Dp=z.record(wp,Tp),genRelationshipId=e=>e.id??Ne(8),Op=z.union([Ep,z.array(Sp).transform(e=>Pe(e,A(`id`)))]),kp=z.union([Dp,z.array(Tp).transform(e=>Pe(e,genRelationshipId))]),Ap=z.object({elements:Op.optional(),relations:kp.optional()});var jp=/* @__PURE__ */ t({element:()=>Mp,relationship:()=>Np,schema:()=>Fp,tagSpec:()=>Pp});const Mp=z.object({tags:bf.nullable(),title:z.string().nullable(),summary:xf.nullable(),description:xf.nullable(),technology:z.string().nullable(),notation:z.string().nullable(),links:gf.nullable(),style:Cf.nullable()}).partial().transform(He(l)),Np=z.object({technology:z.string().nullable(),notation:z.string().nullable(),color:Sf.nullable(),line:mf.nullable(),head:pf.nullable(),tail:pf.nullable()}).partial().transform(He(l)),Pp=z.object({color:Sf.nullable()}).partial().transform(He(l)),Fp=z.object({elements:z.record(af,Mp),deployments:z.record(af,Mp),relationships:z.record(af,Np),tags:z.union([z.record(yf,Pp),z.array(yf).transform(e=>m(e,e=>[e,{}]))])}).partial();var Ip=/* @__PURE__ */ t({anyView:()=>pm,autoLayoutDirection:()=>Rp,deploymentView:()=>em,deploymentViewRule:()=>$p,deploymentViewRuleIncludeAncestors:()=>Bp,dynamicStep:()=>tm,dynamicStepAlt:()=>sm,dynamicStepAltBranch:()=>om,dynamicStepBlock:()=>im,dynamicStepSeries:()=>rm,dynamicStepTry:()=>am,dynamicView:()=>fm,dynamicViewRule:()=>um,dynamicViewStep:()=>lm,dynamicViewSubflow:()=>cm,dynamicViewVariant:()=>dm,elementView:()=>Qp,elementViewRule:()=>Xp,viewRuleAutoLayout:()=>zp,viewRuleExclude:()=>Hp,viewRuleGlobalPredicate:()=>Kp,viewRuleGlobalStyle:()=>Gp,viewRuleGroup:()=>Yp,viewRuleInclude:()=>Vp,viewRulePredicate:()=>Up,viewRuleRank:()=>Jp,viewRuleStyle:()=>Wp,views:()=>mm});const Lp={TB:`TopBottom`,BT:`BottomTop`,LR:`LeftRight`,RL:`RightLeft`},Rp=V.enum([...Te(Lp),...Fe(Lp)]).transform(e=>Lp[e]??e),zp=V.object({direction:Rp,nodeSep:V.number().nullish(),rankSep:V.number().nullish()}),Bp=V.strictObject({includeAncestors:V.boolean()}),Vp=V.strictObject({include:V.array(lp)}),Hp=V.strictObject({exclude:V.array(lp)}),Up=V.xor([Vp,Hp]),Wp=V.object({targets:V.array(Gf),notation:V.string().optional(),style:Cf}).transform(e=>e),Gp=V.object({styleId:V.string()}).transform(e=>e),Kp=V.object({predicateId:V.string()}).transform(e=>e),qp=V.literal([`max`,`min`,`same`,`sink`,`source`]),Jp=V.object({targets:V.array(Gf),rank:qp}).transform(e=>e),Yp=V.lazy(()=>V.object({groupRules:V.array(V.union([Up,Kp,Yp])),title:V.string().nullable(),color:Sf.optional(),border:lf.optional(),opacity:of.optional(),multiple:V.boolean().optional(),size:uf.nullish(),padding:uf.nullish(),textSize:uf.nullish()}).transform(He(l))),Xp=V.union([Up,zp,Wp,Gp,Kp,Jp,Yp]),Zp=V.object({id:nf,title:V.string().nullish().default(null),description:xf.nullish().default(null),order:V.number().int().nonnegative().optional(),routing:V.literal([`spline`,`ortho`]).optional(),tags:bf.nullish(),links:gf.nullish()});function defineView(e){return V.object({...Zp.shape,...e})}const Qp=defineView({_type:V.literal(`element`),viewOf:rf.nullish(),extends:nf.nullish(),rules:V.array(Xp).optional().default([])}),$p=V.union([Up,zp,Wp,Gp,Kp,Bp]),em=defineView({_type:V.literal(`deployment`),rules:V.array($p).optional().default([])}),tm=V.object({_type:V.never().exactOptional(),source:rf,target:rf,title:V.string().nullish().default(null),kind:V.string().nullish(),description:xf.nullish(),technology:V.string().nullish(),notation:V.string().nullish(),notes:xf.nullish(),color:Sf.optional(),line:mf.optional(),head:pf.optional(),tail:pf.optional(),isBackward:V.boolean().optional(),navigateTo:nf.nullish()}),nm=V.object({title:V.string().optional(),get steps(){return V.array(lm).nonempty(`must have at least one step`)}}),rm=V.object({_type:V.literal(`series`),steps:V.array(tm).nonempty(`must have at least one step`)}),im=nm.extend({_type:V.enum([`par`,`parallel`,`loop`,`opt`,`break`])}),am=V.object({_type:V.literal(`try`),try:nm,catch:nm.optional(),finally:nm.optional()}),om=nm.extend({_type:V.enum([`when`,`if`,`else`])}),sm=V.object({_type:V.literal(`alt`),title:V.string().optional(),branches:V.array(om).nonempty(`alt block must have at least one branch`)}),cm=V.union([sm,rm,im,am]),lm=V.union([tm,cm]),um=V.union([Vp,Kp,Wp,Gp,zp]),dm=V.enum([`diagram`,`sequence`]),fm=defineView({_type:V.literal(`dynamic`),variant:dm.optional(),steps:V.array(lm).optional(),rules:V.array(um).optional()}),pm=V.union([Qp,em,fm]),mm=V.record(nf,pm),hm=z.object({...Ap.shape,views:mm,deployment:bp,deployments:bp,specification:Fp}).partial().transform(normalizeStyles);function normalizeStyles(e){let t=e.specification?.elements;return!_(t)&&!_(e.elements)&&(e={...e,elements:ae(e.elements,e=>normalizeElementStyles(e,t))}),e}function normalizeElementStyles(e,t){let r=t[e.kind];if(!r)return e;let i=r.style??{};return vt(e,t=>{for(let i of[`description`,`technology`,`tags`,`summary`]){let a=r[i],s=e[i];ce(a,s)&&delete t[i]}let a=e.style;if(a)for(let[e,r]of M(i))ce(a[e],r)&&delete t.style[e]})}const Z={common:ef,expr:Df,specification:jp,model:xp,deployment:up,views:Ip,likec4data:hm};function markdownProperty(e,t){return select(t=>t[e],spaceBetween(print$1(t??e),markdownOrString$1()))}const titleProperty=()=>property(`title`,spaceBetween(print$1(`title`),text())),summaryProperty=()=>property(`summary`,spaceBetween(print$1(`summary`),markdownOrString$1())),descriptionProperty=()=>property(`description`,spaceBetween(print$1(`description`),markdownOrString$1())),notesProperty=()=>property(`notes`,spaceBetween(print$1(`notes`),markdownOrString$1())),technologyProperty=()=>property(`technology`,spaceBetween(print$1(`technology`),text())),notationProperty=()=>property(`notation`,spaceBetween(print$1(`notation`),text()));function printMetadataValue(){return operation(({ctx:e,out:t})=>S(e)?text()({ctx:e,out:t}):print$1()({ctx:e,out:t}))}function metadataValue(){return ue(guard(qe(b),printMetadataValue()),guard(b,body(`[`,`]`)(foreach(printMetadataValue(),{appendNewLineIfNotEmpty:!0,suffix(e,t,r){return r?void 0:`,`}}))))}const metadataProperty=()=>select(e=>e.metadata?M(e.metadata):void 0,body(`metadata`)(foreach(spaceBetween(print$1(e=>e[0]),property(`1`,metadataValue())),separateNewLine()))),tagsProperty=()=>property(`tags`,print$1(e=>e.map(e=>`#${e}`).join(`, `)));function linkProperty(){return spaceBetween(select(e=>typeof e==`string`?{url:e}:exact({url:e.url,title:e.title}),print$1(`link`),print$1(e=>e.url),property(`title`,inlineText())))}const linksProperty=()=>property(`links`,foreachNewLine(linkProperty()));function colorProperty(){return property(`color`,spaceBetween(print$1(`color`),print$1()))}function opacityProperty(){return property(`opacity`,spaceBetween(print$1(`opacity`),print$1(e=>`${e}%`)))}function iconProperty(){return property(`icon`,spaceBetween(print$1(`icon`),print$1()))}const gm=zodOp(Cf)(lines(property(`shape`),colorProperty(),iconProperty(),property(`iconColor`),property(`iconSize`),property(`iconPosition`),property(`border`),opacityProperty(),property(`size`),property(`padding`),property(`textSize`),property(`sizing`),property(`multiple`)));function relationConnector(e,t){let r=t?`<->`:`->`;return e?`-[${e}]${r}`:r}function appendSelector(e,t){if(t)switch(t){case`children`:e.append(`.*`);break;case`descendants`:e.append(`.**`);break;case`expanded`:e.append(`._`);break;default:nonexhaustive(t)}return e}const _m=zodOp(Mf)(function whereTagEqualOp({ctx:{tag:e},out:t}){if(`eq`in e)return t.appendTemplate`tag is #${e.eq}`;if(`neq`in e)return t.appendTemplate`tag is not #${e.neq}`;nonexhaustive(e)}),vm=zodOp(Nf)(function whereKindEqualOp({ctx:{kind:e},out:t}){if(`eq`in e)return t.appendTemplate`kind is ${e.eq}`;if(`neq`in e)return t.appendTemplate`kind is not ${e.neq}`;nonexhaustive(e)});function quoteMetadataValue(e){return e===`true`||e===`false`?e:`"${e}"`}const ym=zodOp(Pf)(function whereMetadataEqualOp({ctx:{metadata:e},out:t}){let{key:r,value:i}=e;if(i===void 0)return t.appendTemplate`metadata.${r}`;if(`eq`in i)return t.append(`metadata.${r} is ${quoteMetadataValue(i.eq)}`);if(`neq`in i)return t.append(`metadata.${r} is not ${quoteMetadataValue(i.neq)}`);nonexhaustive(i)}),bm=zodOp(Rf)(property(`not`,spaceBetween(print$1(`not (`),lazy(()=>wm.noparse()),print$1(`)`)))),xm=zodOp(If)(function whereParticipantOp({ctx:{participant:e,operator:t},out:r}){r.append(e,`.`),`tag`in t?_m()({ctx:t,out:r}):`kind`in t?vm()({ctx:t,out:r}):`metadata`in t?ym()({ctx:t,out:r}):nonexhaustive(t)}),Sm=zodOp(Lf)(function whereAndOp({ctx:{and:e},out:t}){let r=p(e,e=>{let{out:t}=executeOnFresh(e,wm.noparse());return`or`in e&&(t=fresh().out.append(`(`,...t.contents,`)`)),t});return t.append(Vn(r,{appendNewLineIfNotEmpty:!0,skipNewLineAfterLastItem:!0,prefix(e,t){return t>0?`and `:void 0}}))}),Cm=zodOp(zf)(({ctx:{or:e},out:t})=>{let r=p(e,e=>{let{out:t}=executeOnFresh(e,wm.noparse());return`and`in e&&(t=fresh().out.append(`(`,...t.contents,`)`)),t});return t.append(Vn(r,{appendNewLineIfNotEmpty:!0,skipNewLineAfterLastItem:!0,prefix(e,t){return t>0?`or `:void 0}}))}),wm=zodOp(Bf)(({ctx:e,exec:t})=>{if(`and`in e)return t(e,Sm.noparse());if(`or`in e)return t(e,Cm.noparse());if(`not`in e)return t(e,bm.noparse());if(`tag`in e)return t(e,_m.noparse());if(`kind`in e)return t(e,vm.noparse());if(`metadata`in e)return t(e,ym.noparse());if(`participant`in e)return t(e,xm.noparse());nonexhaustive(e)}),Tm=zodOp(Af)(({ctx:e,out:t})=>(`model`in e?t.append(e.model):(t.append(e.deployment),e.element&&t.append(`.`,e.element)),t)),Em=zodOp(Gf)(({ctx:e,out:t,exec:r})=>{if(`wildcard`in e)return t.append(`*`);if(`elementKind`in e)return t.append(`element.kind`).append(e.isEqual?` = `:` != `).append(e.elementKind);if(`elementTag`in e)return t.append(`element.tag`).append(e.isEqual?` = `:` != `).append(`#${e.elementTag}`);if(`ref`in e)return r(e.ref,Tm()),appendSelector(t,e.selector),t;nonexhaustive(e)}),Dm=zodOp(Zf)(({ctx:{custom:e},exec:t})=>{t(e.expr,Om());let r=withctx()(body(`with`)(titleProperty(),descriptionProperty(),notationProperty(),notesProperty(),property(`navigateTo`),gm()));return`where`in e.expr?t(e,indent(r)):t(e,space(),r)}),Om=zodOp(qf)(({ctx:e,exec:t})=>{`where`in e?(t(e.where.expr,Em.noparse()),t(e.where.condition,indent(print$1(`where`),indent(wm.noparse())))):t(e,Em.noparse())});zodOp(Qf)(({ctx:e,exec:t})=>`custom`in e?t(e,Dm.noparse()):t(e,Om.noparse()));const km=zodOp($f)(merge(property(`source`,Em.noparse()),print$1(e=>e.isBidirectional?` <-> `:` -> `),property(`target`,Em.noparse()))),Am=zodOp(ep)(merge(print$1(`-> `),property(`incoming`,Em.noparse()))),jm=zodOp(tp)(merge(property(`outgoing`,Em.noparse()),print$1(` ->`))),Mm=zodOp(np)(merge(print$1(`-> `),property(`inout`,Em.noparse()),print$1(` ->`))),Nm=zodOp(rp)(({ctx:e,exec:t})=>{if(`source`in e)return t(e,km.noparse());if(`incoming`in e)return t(e,Am.noparse());if(`outgoing`in e)return t(e,jm.noparse());if(`inout`in e)return t(e,Mm.noparse());nonexhaustive(e)}),Pm=zodOp(ap)(({ctx:e,exec:t})=>{if(`where`in e)t(e.where.expr,Nm.noparse()),t(e.where.condition,indent(print$1(`where`),indent(wm.noparse())));else return t(e,Nm.noparse())}),Fm=zodOp(op)(({ctx:{customRelation:e},exec:t})=>{t(e.expr,Pm.noparse());let r=withctx(e)(body(`with`)(titleProperty(),descriptionProperty(),notationProperty(),markdownProperty(`notes`),property(`navigateTo`),gm(),property(`head`),property(`tail`),property(`line`)));`where`in e.expr?t(e,indent(r)):t(e,space(),r)});zodOp(sp)(({ctx:e,exec:t})=>`customRelation`in e?t(e,Fm.noparse()):t(e,Pm.noparse()));const Im=zodOp(lp)(({ctx:e,exec:t})=>{if(`custom`in e)return t(e,Dm.noparse());if(`customRelation`in e)return t(e,Fm.noparse());if(`wildcard`in e||`ref`in e||`elementKind`in e||`elementTag`in e)return t(e,Em.noparse());if(`source`in e||`incoming`in e||`outgoing`in e||`inout`in e)return t(e,Nm.noparse());if(`where`in e){let{expr:r,condition:i}=e.where;return`source`in r||`incoming`in r||`outgoing`in r||`inout`in r?t({where:{expr:r,condition:i}},Pm.noparse()):t({where:{expr:r,condition:i}},Om.noparse())}nonexhaustive(e)});function buildTree$1(e){let t=/* @__PURE__ */ new Map,r=[],i=N(e,sortParentsFirst);for(let e of i){let i;i=`element`in e?e:{...e,children:[]},t.set(e.id,i);let a=parentFqn(e.id),s=a?t.get(a):void 0;s&&`children`in s?s.children.push(i):r.push(i)}return{roots:r,nodes:t,exists:e=>t.has(e)}}e(buildTree$1,`buildTree`);function hasStyleProps$1(e){return!_(e.style)}e(hasStyleProps$1,`hasStyleProps`);function hasElementProps$1(e){return!!(e.description||e.summary||e.technology||e.notation||e.tags&&e.tags.length>0||e.links&&e.links.length>0||!_(e.metadata)||hasStyleProps$1(e))}e(hasElementProps$1,`hasElementProps`);const Lm=zodOp(Z.deployment.element)(lines(tagsProperty(),technologyProperty(),summaryProperty(),descriptionProperty(),linksProperty(),metadataProperty(),select(e=>hasStyleProps$1(e)?e.style:void 0,body(`style`)(gm())))),Rm=zodOp(Z.deployment.instance)(spaceBetween(when(e=>nameFromFqn(e.id)!==nameFromFqn(e.element),print$1(e=>nameFromFqn(e.id)),print$1(` =`)),print$1(`instanceOf`),printProperty(`element`),when(e=>!!e.title&&e.title!==nameFromFqn(e.id),property(`title`,inlineText())),when(e=>hasElementProps$1(e),body(Lm()))));function node(){return function nodeOp({ctx:e,out:t}){let r=e;if(`element`in r)return Rm()({ctx:r,out:t}),{ctx:e,out:t};invariant(`children`in r,`Node must have children property`);let i=r.children.length>0||hasElementProps$1(r),a=nameFromFqn(r.id),s=[print$1(a),print$1(`=`),print$1(r.kind)];return r.title&&r.title!==a&&s.push(inlineText(r.title)),i&&s.push(body(lines(2)(withctx(r,Lm()),...r.children.map(e=>withctx(e,nodeOp))))),spaceBetween(...s)({ctx:e,out:t})}}function hasRelationStyle$1(e){return!!(e.color||e.line||e.head||e.tail)}e(hasRelationStyle$1,`hasRelationStyle`);function hasRelationProps$1(e){return!!(e.description||e.summary||e.technology||e.tags&&e.tags.length>0||e.links&&e.links.length>0||!_(e.metadata)||hasRelationStyle$1(e)||e.navigateTo)}e(hasRelationProps$1,`hasRelationProps`);const zm=zodOp(Z.deployment.relationship)(spaceBetween(property(`source`,Tm()),print$1(e=>relationConnector(e.kind,e.isBidirectional)),property(`target`,Tm()),property(`title`,inlineText()),when(hasRelationProps$1,body(tagsProperty(),technologyProperty(),summaryProperty(),descriptionProperty(),property(`navigateTo`),linksProperty(),metadataProperty(),when(hasRelationStyle$1,body(`style`)(colorProperty(),property(`line`),property(`head`),property(`tail`))))))),Bm=zodOp(Z.deployment.schema)(body(`deployment`)(lines(2)(select(e=>buildTree$1(e.elements?Fe(e.elements):[]).roots,lines(2)(foreach(node()))),select(e=>e.relations?Fe(e.relations):void 0,lines(2)(foreach(zm()))))));function buildTree(e){let t=/* @__PURE__ */ new Map,r=[],i=N(e,sortParentsFirst);for(let e of i){let i={...e,children:[]};t.set(e.id,i);let a=parentFqn(e.id),s=a?t.get(a):void 0;s?s.children.push(i):r.push(i)}return{roots:r,nodes:t,exists:e=>t.has(e)}}function hasStyleProps(e){return!_(e.style)}function hasElementProps(e){return!!(e.description||e.summary||e.technology||e.notation||e.tags&&e.tags.length>0||e.links&&e.links.length>0||!_(e.metadata)||hasStyleProps(e))}const Vm=zodOp(Z.model.element)(lines(tagsProperty(),technologyProperty(),summaryProperty(),descriptionProperty(),linksProperty(),metadataProperty(),select(e=>hasStyleProps(e)?e.style:void 0,body(`style`)(gm()))));function elementTree(){return function elementTreeNodeOp({ctx:e,out:t}){let r=e,i=(e.children?.length??0)>0||hasElementProps(r),a=nameFromFqn(r.id),s=[print$1(a),print$1(`=`),print$1(r.kind)];return r.title&&r.title!==a&&s.push(inlineText(r.title)),i&&s.push(body(lines(2)(withctx(r,Vm()),...(e.children??[]).map(e=>withctx(e,elementTree()))))),spaceBetween(...s)({ctx:e,out:t})}}function hasRelationStyle(e){return!!(e.color||e.line||e.head||e.tail)}function hasRelationProps(e){return!!(e.description||e.summary||e.technology||e.tags&&e.tags.length>0||e.links&&e.links.length>0||!_(e.metadata)||hasRelationStyle(e)||e.navigateTo)}const Hm=zodOp(Z.model.relationship)(spaceBetween(property(`source`,Tm()),print$1(e=>relationConnector(e.kind,e.isBidirectional)),property(`target`,Tm()),property(`title`,inlineText()),when(hasRelationProps,body(tagsProperty(),technologyProperty(),summaryProperty(),descriptionProperty(),property(`navigateTo`),linksProperty(),metadataProperty(),when(hasRelationStyle,body(`style`)(colorProperty(),property(`line`),property(`head`),property(`tail`)))))));zodOp(Z.model.element)(elementTree());const Um=zodOp(Z.model.schema)(body(`model`)(lines(2)(select(e=>buildTree(e.elements?Fe(e.elements):[]).roots,lines(2)(foreach(elementTree()))),select(e=>e.relations?Fe(e.relations):void 0,lines(2)(foreach(Hm())))))),Wm=zodOp(z.tuple([z.string(),Pp]))(spaceBetween(print$1(`tag`),printProperty(`0`),property(`1`,property(`color`,body(spaceBetween(print$1(`color`),print$1())))))),elementKind=e=>zodOp(z.tuple([z.string(),Mp]))(spaceBetween(print$1(e),printProperty(`0`),property(`1`,body(tagsProperty(),titleProperty(),summaryProperty(),descriptionProperty(),technologyProperty(),notationProperty(),linksProperty(),property(`style`,body(`style`)(gm())))))),Gm=zodOp(z.tuple([z.string(),Np]))(spaceBetween(print$1(`relationship`),printProperty(`0`),property(`1`,body(technologyProperty(),notationProperty(),colorProperty(),property(`line`),property(`head`),property(`tail`))))),Km=zodOp(Fp)(body(`specification`)(lines(2)(select(e=>e.elements&&M(e.elements),foreachNewLine(elementKind(`element`)())),select(e=>e.deployments&&M(e.deployments),foreachNewLine(elementKind(`deploymentNode`)())),select(e=>e.relationships&&M(e.relationships),foreachNewLine(Gm())),select(e=>e.tags&&M(e.tags),foreachNewLine(Wm()))))),viewTitleProperty=()=>property(`title`,spaceBetween(print$1(`title`),inlineText())),viewPredicateOp=e=>operation(`viewPredicateOp`,({ctx:t,out:r})=>{let i=t;if(!k(i,1))return;let a=k(i,2),s=foreach(Im(),separateComma(a));executeOnCtx({ctx:t,out:r},merge(print$1(e),...a?[indent(s)]:[space(),s]))});zodOp(Z.views.viewRuleInclude)(property(`include`,viewPredicateOp(`include`))),zodOp(Z.views.viewRuleExclude)(property(`exclude`,viewPredicateOp(`exclude`))),zodOp(Z.views.viewRulePredicate)(({ctx:e,exec:t})=>{let r,i;return`include`in e?(r=e.include,i=`include`):`exclude`in e&&(r=e.exclude,i=`exclude`),invariant(r&&i,`Invalid view rule predicate`),t(r,viewPredicateOp(i))});const qm=zodOp(Z.views.viewRuleStyle)(spaceBetween(print$1(`style`),property(`targets`,foreach(Im(),separateComma())),body(notationProperty(),property(`style`,gm.noparse())))),Jm=zodOp(Z.views.viewRuleGroup)(({ctx:e,exec:t})=>{throw Error(`not implemented`)}),Ym=zodOp(Z.views.viewRuleGlobalStyle)(({ctx:e,exec:t})=>{throw Error(`not implemented`)}),Xm=zodOp(Z.views.viewRuleGlobalPredicate)(({ctx:e,exec:t})=>{throw Error(`not implemented`)}),Zm=zodOp(Z.views.viewRuleAutoLayout)(spaceBetween(print$1(`autoLayout`),printProperty(`direction`),guard(hasProp(`rankSep`),spaceBetween(printProperty(`rankSep`),printProperty(`nodeSep`))))),Qm=zodOp(Z.views.deploymentViewRuleIncludeAncestors)(spaceBetween(print$1(`includeAncestors`),printProperty(`includeAncestors`))),$m=zodOp(Z.views.viewRuleRank)(({ctx:e,exec:t})=>{throw Error(`not implemented`)}),eh=zodOp(Z.views.elementViewRule)(({ctx:e,exec:t})=>{if(`include`in e)return t(e.include,viewPredicateOp(`include`));if(`exclude`in e)return t(e.exclude,viewPredicateOp(`exclude`));if(`groupRules`in e)return t(e,Jm.noparse());if(`rank`in e)return t(e,$m.noparse());if(`direction`in e)return t(e,Zm.noparse());if(`styleId`in e)return t(e,Ym.noparse());if(`predicateId`in e)return t(e,Xm.noparse());if(`targets`in e&&`style`in e)return t(e,qm.noparse());nonexhaustive(e)}),th=zodOp(Z.views.elementView.partial({_type:!0}))(spaceBetween(print$1(`view`),print$1(e=>e.id),property(`viewOf`,spaceBetween(print$1(`of`),print$1())),body(lines(2)(lines(tagsProperty(),viewTitleProperty(),property(`order`),property(`routing`),descriptionProperty(),linksProperty()),property(`rules`,foreachNewLine(eh.noparse())))))),nh=zodOp(Z.views.deploymentViewRule)(({ctx:e,exec:t})=>{if(`include`in e)return t(e.include,viewPredicateOp(`include`));if(`exclude`in e)return t(e.exclude,viewPredicateOp(`exclude`));if(`includeAncestors`in e)return t(e,Qm.noparse());if(`direction`in e)return t(e,Zm.noparse());if(`styleId`in e)return t(e,Ym.noparse());if(`predicateId`in e)return t(e,Xm.noparse());if(`targets`in e&&`style`in e)return t(e,qm.noparse());nonexhaustive(e)}),rh=zodOp(Z.views.deploymentView.partial({_type:!0}))(spaceBetween(print$1(`deployment view`),print$1(e=>e.id),body(lines(2)(lines(tagsProperty(),viewTitleProperty(),property(`order`),property(`routing`),descriptionProperty(),linksProperty()),property(`rules`,foreachNewLine(nh.noparse())))))),ih=zodOp(Z.views.dynamicStep.partial({source:!0}))(spaceBetween(print$1(e=>e.isBackward?`<-`:e.kind?`-[${e.kind}]->`:`->`),printProperty(`target`),property(`title`,text()),body(lines(technologyProperty(),descriptionProperty(),notesProperty(),property(`navigateTo`),notationProperty(),colorProperty(),property(`line`),property(`head`),property(`tail`))))),ah=zodOp(Z.views.dynamicStep)(spaceBetween(printProperty(`source`),ih.noparse())),bodyWithSteps=()=>property(`steps`,body(foreachNewLine(lazy(()=>fh.noparse())))),oh=zodOp(Z.views.dynamicStepBlock)(spaceBetween(printProperty(`_type`),property(`title`,text()),bodyWithSteps())),sh=zodOp(Z.views.dynamicStepSeries)(merge(select(e=>e.steps[0],printProperty(`source`)),indent(property(`steps`,foreachNewLine(ih.noparse()))))),ch=zodOp(Z.views.dynamicStepTry)(spaceBetween(select(e=>e.try,spaceBetween(print$1(`try`),property(`title`,text()),bodyWithSteps())),select(e=>e.catch,spaceBetween(print$1(`catch`),property(`title`,text()),bodyWithSteps())),select(e=>e.finally,spaceBetween(print$1(`finally`),property(`title`,text()),bodyWithSteps())))),lh=zodOp(Z.views.dynamicStepAltBranch)(spaceBetween(printProperty(`_type`),property(`title`,text()),bodyWithSteps())),uh=zodOp(Z.views.dynamicStepAlt)(spaceBetween(print$1(`alt`),property(`title`,text()),body(property(`branches`,foreachNewLine(lh.noparse()))))),dh=zodOp(Z.views.dynamicViewSubflow)(({ctx:e,exec:t})=>{switch(e._type){case`alt`:return t(e,uh.noparse());case`series`:return t(e,sh.noparse());case`try`:return t(e,ch.noparse());case`par`:case`parallel`:case`loop`:case`opt`:case`break`:return t(e,oh.noparse());default:nonexhaustive(e)}}),fh=zodOp(Z.views.dynamicViewStep)(({ctx:e,exec:t})=>`source`in e&&`target`in e?t(e,ah.noparse()):(invariant(e._type,`Step must have a type`),t(e,dh.noparse()))),ph=Object.assign(ah,{subflow:dh,block:oh,alt:uh,series:sh,try:ch,any:fh}),mh=zodOp(Z.views.dynamicViewRule)(({ctx:e,exec:t})=>{if(`include`in e)return t(e.include,viewPredicateOp(`include`));if(`predicateId`in e)return t(e,Xm.noparse());if(`targets`in e&&`style`in e)return t(e,qm.noparse());if(`styleId`in e)return t(e,Ym.noparse());if(`direction`in e)return t(e,Zm.noparse());nonexhaustive(e)}),hh=zodOp(Z.views.dynamicView.partial({_type:!0}))(spaceBetween(print$1(`dynamic view`),print$1(e=>e.id),body(lines(2)(lines(tagsProperty(),viewTitleProperty(),property(`order`),property(`routing`),descriptionProperty(),linksProperty(),property(`variant`)),property(`steps`,foreachNewLine(ph.any.noparse())),property(`rules`,foreachNewLine(mh.noparse())))))),gh=zodOp(Z.views.anyView)(({ctx:e,exec:t})=>{if(`_type`in e){if(e._type==`element`)return t(e,th.noparse());if(e._type===`deployment`)return t(e,rh.noparse());if(e._type===`dynamic`)return t(e,hh.noparse())}nonexhaustive(e)}),_h=zodOp(Z.views.views)(body(`views`)(select(e=>Fe(e),foreach(gh.noparse(),{separator:new Nn().appendNewLine().appendNewLine(),prefix:(e,t,r)=>t===0&&!r?Qd:void 0})))),vh=zodOp(Z.likec4data)(lines(2)(property(`specification`,Km.noparse()),Um(),property(`deployment`,Bm.noparse()),property(`deployments`,Bm.noparse()),property(`views`,_h.noparse())));function generateLikeC4(e,t){return t={indent:2,...t},materialize(vh(),e,t)}function print(e,t,r){return materialize(e,t??{},r)}const{findNodeForKeyword:yh}=Xt;function changeViewLayout(e,{view:t,viewAst:r,layout:i}){let a=r.$cstNode;invariant(r.body,`View ${t.id} has no body`),invariant(a,`viewCstNode`);let s=Me(r.body.rules,isViewRuleAutoLayout),c=print(Zm(),i);if(s?.routing&&(c+=` ${s.routing}`),s&&s.$cstNode)return Wr.replace(s.$cstNode.range,c);let l=yh(r.body.$cstNode,`}`)?.range;invariant(l,`Closing brace not found`);let u=` `.repeat(l.start.character);return Wr.replace(l,` ${c}\n${u}}`)}const{findNodeForKeyword:bh,findNodeForProperty:xh}=Xt;function changeViewRouting(e,{view:t,viewAst:r,routing:i}){invariant(i===`spline`||i===`ortho`,`Invalid routing: ${i}`),invariant(r.body,`View ${t.id} has no body`);let a=r.body,s=nonNullable(r.$cstNode,`viewCstNode`),c=a.props,l=c.find(isViewRoutingProperty),u=l&&xh(l.$cstNode,`value`);if(u)return Wr.replace(u.range,i);let p=Me(a.rules,isViewRuleAutoLayout);if(p?.$cstNode){let e=p.routing&&xh(p.$cstNode,`routing`);return e?Wr.replace(e.range,i):Wr.insert(p.$cstNode.range.end,` ${i}`)}let m=(c.at(-1)?.$cstNode??a.tags?.$cstNode)?.range.end??nonNullable(bh(a.$cstNode,`{`),`Opening brace not found`).range.end,h=nonNullable(bh(a.$cstNode,`}`),`Closing brace not found`),g=` `.repeat(s.range.start.character+2),_=h.range.start.line===m.line?`
|
|
134
|
+
`+` `.repeat(s.range.start.character):``;return Wr.insert(m,`\n${g}routing ${i}${_}`)}function preparePayload(e,t){let r=t.shared.workspace,{viewId:i,projectId:a,change:s}=e,c=r.ProjectsManager.ensureProject(a),l=t.likec4.ModelLocator.locateViewAst(i,c.id);if(!l)throw Error(`View ${i} not found in project ${c.id}`);return{viewId:i,change:s,services:t,project:c,doc:l.doc,viewAst:l.viewAst,workspace:r}}function viewChangeHandler(e,t){return r=>{if(r.change.op===e)return t(r)}}const Sh=viewChangeHandler(`change-property`,({change:e,viewAst:t})=>{let{title:r,description:i}=e,a=[];return r!==void 0&&a.push(updateViewTitle(t,r)),i!==void 0&&a.push(...updateViewDescription(t,i)),e.tags!==void 0&&a.push(...updateViewTags(t,e.tags)),a});function findExistingViewProperty(e,t){let r=e.body?.props;if(r&&k(r,1))return r.findLast(e=>e.key===t&&e.$cstNode!==void 0)}function findInsertPosition(e,t){let r=t(nonNullable(e.body,`View body is required`));if(!r)return Pr.create(0,0);let{line:i,character:a}=r;return Pr.create(i,a+1)}const doubleIndent=e=>ue(newline(),indent(indent(e)));function updateViewTitle(e,t){let r=findExistingViewProperty(e,`title`),i=splitViewFolderPath(e.$container.folder??``),a=splitViewFolderPath(t);for(;a[0]&&i[0]===a[0];)a.shift(),i.shift();t=a.join(` / `);let s=withctx({title:t})(titleProperty());return r?Fr.replace(r.$cstNode.range,print(s)):Fr.insert(findInsertPosition(e,e=>e.tags?.$cstNode?.range.end??e.$cstNode?.range.start),print(doubleIndent(s)).trimEnd())}function replaceTags(e,t,r){let i=t.tags,a=print$1(r.map(e=>`#${e}`).join(` `));if(i?.$cstNode)return r.length===0?Fr.del({start:findInsertPosition(e,e=>e.$cstNode?.range.start),end:i.$cstNode.range.end}):Fr.replace(i.$cstNode.range,print(a));if(r.length!==0)return Fr.insert(findInsertPosition(e,e=>e.$cstNode?.range.start),print(doubleIndent(a)).trimEnd())}function updateViewTags(e,t){let r=replaceTags(e,nonNullable(e.body,`View body is required`),t);return r?[r]:[]}function updateViewDescription(e,t){let r=findExistingViewProperty(e,`description`),i=withctx({description:t},indent(indent(descriptionProperty())));if(r)return[Fr.replace({start:{line:r.$cstNode.range.start.line,character:0},end:r.$cstNode.range.end},print(i).trimEnd())];let a=findInsertPosition(e,e=>N(e.props,p(e=>e.$cstNode?.range.end),D(j),te())??e.tags?.$cstNode?.range.end??e.$cstNode?.range.start);return[Fr.insert({line:a.line+1,character:0},print(i))]}const Ch=q.getChild(`model-changes`);var LikeC4ModelChanges=class{services;locator;constructor(e){this.services=e,this.locator=e.likec4.ModelLocator}async applyChange(e){let{viewId:t,projectId:r,change:i}=e;if(i.op===`change-property`){let t=preparePayload(e,this.services),r=Sh(t);if(!r)return{success:!1,error:`No changes to apply`};let i=Array.isArray(r)?r:[r];return await this.applyTextEdits(t.doc,i)?{success:!0,location:null}:{success:!1,error:`Failed to apply text edits`}}let a=this.services.shared.workspace;try{let e=a.ProjectsManager.ensureProject(r);Ch.debug`Applying model change ${i.op} to view ${t} in project ${e.id}`;let s=this.locator.locateViewAst(t,e.id);if(!s&&(i.op===`save-view-snapshot`||i.op===`reset-manual-layout`)&&!(await this.services.likec4.ModelBuilder.computeModel(e.id)).findView(t))throw Error(`View ${t} not found in project ${e.id}`);if(i.op===`save-view-snapshot`)return invariant(t===i.layout.id,`View ID does not match, expected `+t+`, got `+i.layout.id),{success:!0,location:await a.ManualLayouts.write(e,i.layout)};if(i.op===`reset-manual-layout`)return{success:!0,location:await a.ManualLayouts.remove(e,t)};if(!s)throw Error(`View ${t} not found in project ${e.id}`);let c={uri:s.doc.textDocument.uri,version:s.doc.textDocument.version},{edits:l,modifiedRange:u}=this.convertToTextEdit({lookup:s,change:i});return l.length?await this.applyTextEdits(s.doc,l)?{success:!0,location:{uri:c.uri,range:u}}:{success:!1,error:`Failed to apply changes`}:{success:!1,error:`No changes to apply`}}catch(t){let r=loggable(wrapError(t,`Failed to apply change ${e.change.op} ${e.viewId}`));return Ch.warn(r),{success:!1,error:r}}}convertToTextEdit({lookup:e,change:t}){switch(t.op){case`change-element-style`:return changeElementStyle(this.services,{...e,targets:t.targets,style:t.style});case`change-autolayout`:{let r=changeViewLayout(this.services,{...e,layout:t.layout});return{modifiedRange:r.range,edits:[r]}}case`change-routing`:{let r=changeViewRouting(this.services,{...e,routing:t.routing});return{modifiedRange:r.range,edits:[r]}}default:nonexhaustive(t)}}async applyTextEdits(e,t){let r=this.services.shared.lsp.Connection,i=this.services.shared.workspace;if(!r){let r=on.applyEdits(e.textDocument,t);return await i.FileSystemProvider.writeFile(e.uri,r),await i.DocumentBuilder.update([e.uri],[]),!0}let a=await r.workspace.applyEdit({label:`LikeC4 - change view`,edit:{changes:{[e.textDocument.uri]:t}}});return a.applied?(await i.DocumentBuilder.update([e.uri],[]),a.applied):(Ch.warn`Failed to apply text edits to document ${e.textDocument.uri}: ${a.failureReason}`,r.window.showErrorMessage(`Failed to apply changes: ${a.failureReason}`),!1)}},LikeC4NameProvider=class extends Gt{services;constructor(e){super(),this.services=e}getNameStrict(e){return nonNullable(this.getName(e),`Failed getName for ${this.services.workspace.AstNodeLocator.getAstNodePath(e)}`)}getName(e){if(kn(e))return e.name;if(isImported(e))return e.imported.$refText;if(isDeployedInstance(e))return e.target.modelElement.value.$refText}getNameNode(e){if(kn(e))return super.getNameNode(e);if(isImported(e))return e.imported.$refNode;if(isDeployedInstance(e))return e.target.modelElement.value.$refNode}};function uniqueDescriptions(e){return N(e,le(e=>`${e.type}.${e.name}`),M(),P(([e,t])=>t.length===1?t:[]))}var LikeC4ScopeComputation=class extends an{constructor(e){super(e)}async collectExportedSymbols(e,t){let r=[];try{let{specifications:t,models:i,views:a,globals:s,likec4lib:c,deployments:l}=e.parseResult.value;this.exportLibrary(c,r,e),this.exportSpecification(t,r,e),this.exportModel(i,r,e),this.exportViews(a,r,e),this.exportGlobals(s,r,e),this.exportDeployments(l,r,e)}catch(e){logWarnError(e)}return r}exportViews(e,t,r){let i=e?.flatMap(e=>e.views);if(!(C(i)||i.length===0))for(let e of i)try{j(e.name)&&t.push(this.descriptions.createDescription(e,e.name,r))}catch(e){logWarnError(e)}}exportGlobals(e,t,r){if(!(C(e)||e.length===0)){for(let i of e.flatMap(e=>e.predicates))try{let e=i;j(e.name)&&t.push(this.descriptions.createDescription(e,e.name,r))}catch(e){logWarnError(e)}for(let i of e.flatMap(e=>e.styles))try{let e=i.id;j(e.name)&&t.push(this.descriptions.createDescription(e,e.name,r))}catch(e){logWarnError(e)}}}exportModel(e,t,r){if(!(C(e)||e.length===0))for(let i of e.flatMap(e=>e.elements))try{isElement(i)&&j(i.name)&&t.push(this.descriptions.createDescription(i,i.name,r))}catch(e){logWarnError(e)}}exportLibrary(e,t,r){if(!C(e))try{for(let i of e.flatMap(e=>e.icons))t.push(this.descriptions.createDescription(i,i.name,r))}catch(e){logWarnError(e)}}exportSpecification(e,t,r){if(!(C(e)||e.length===0))for(let i of e.flatMap(e=>[...e.elements,...e.relationships,...e.deploymentNodes,...e.tags,...e.colors]))try{switch(!0){case isSpecificationDeploymentNodeKind(i):case isSpecificationRelationshipKind(i):case isSpecificationElementKind(i):j(i.kind.name)&&t.push(this.descriptions.createDescription(i.kind,i.kind.name,r));continue;case isSpecificationTag(i):j(i.tag.name)&&t.push(this.descriptions.createDescription(i.tag,i.tag.name,r),this.descriptions.createDescription(i.tag,`#`+i.tag.name,r));continue;case isSpecificationColor(i):j(i.name.name)&&t.push(this.descriptions.createDescription(i.name,i.name.name,r));continue;default:nonexhaustive(i)}}catch(e){logWarnError(e)}}exportDeployments(e,t,r){let i=e?.flatMap(e=>e.elements);if(!(C(i)||i.length===0))for(let e of i)try{isDeploymentNode(e)&&j(e.name)&&t.push(this.descriptions.createDescription(e,e.name,r))}catch(e){logWarnError(e)}}collectLocalSymbols(e,t){return new Promise(t=>{let r=e.parseResult.value,i=[],a=new An;for(let t of r.models)try{i.push(...this.processContainer(t,a,e))}catch(e){logWarnError(e)}for(let t of r.deployments)try{i.push(...this.processDeployments(t,a,e))}catch(e){logWarnError(e)}for(let e of r.imports.flatMap(e=>e.imports))try{let t=e;for(;t;)i.push(this.descriptions.createDescription(t,t.imported.$refText)),t=t.prev}catch(e){logWarnError(e)}uniqueDescriptions(i).forEach(e=>{a.add(r,e)}),t(a)})}processContainer(e,t,r){let i=new An,a=[];for(let s of e.elements){if(isRelation(s))continue;let e;if(isElement(s)?(j(s.name)&&i.add(s.name,this.descriptions.createDescription(s,s.name,r)),e=s.body,e&&(t.add(e,this.descriptions.createDescription(s,`this`,r)),t.add(e,this.descriptions.createDescription(s,`it`,r)))):isExtendElement(s)&&(e=s.body),e&&e.elements.length>0)try{a.push(...this.processContainer(e,t,r))}catch(e){logWarnError(e)}}a.length&&N(a,D(e=>!i.has(e.name)),le(e=>e.name),ze((e,t)=>{e.length===1&&i.add(t,e[0])}));let s=[...i.values()];return t.addAll(e,s),s}processDeployments(e,t,r){let i=new An,a=[];for(let s of e.elements){if(isDeploymentRelation(s))continue;let e=s.body;if(!isExtendDeployment(s)){let a=this.nameProvider.getName(s);if(j(a)){let e=this.descriptions.createDescription(s,a,r);i.add(a,e)}e&&(t.add(e,this.descriptions.createDescription(s,`this`,r)),t.add(e,this.descriptions.createDescription(s,`it`,r)))}if(e)try{a.push(...this.processDeployments(e,t,r))}catch(e){logWarnError(e)}}a.length&&N(a,D(e=>!i.has(e.name)),le(e=>e.name),ze((e,t)=>{e.length===1&&i.add(t,e[0])}));let s=[...i.values()];return t.addAll(e,s),s}};const{getDocument:wh}=en;var LikeC4ScopeProvider=class extends Kn{services;indexManager;constructor(e){super(e),this.services=e,this.indexManager=e.shared.workspace.IndexManager}get fqnIndex(){return this.services.likec4.FqnIndex}get deploymentsIndex(){return this.services.likec4.DeploymentsIndex}getScope(e){try{let t=projectIdFrom(e.container),r=this.reflection.getReferenceType(e);try{let i=e.container;if(isFqnRef(i))return new qt(this.streamForFqnRef(t,i,e));if(isStrictFqnRef(i))return this.getScopeForStrictFqnRef(t,i,e);if(r!==ws.$type)return this.getProjectScope(t,r,e);if(isImported(i)){let e=projectIdFrom(i);return new qt(this.fqnIndex.rootElements(e))}if(isStrictFqnElementRef(i)&&e.property===`el`){let a=i.parent;return a?new qt(this.fqnIndex.directChildrenOf(t,readStrictFqn(a))):this.getProjectScope(t,r,e)}return new qt(Cn(this.computeScope(t,e)))}catch(i){return logWarnError(i),this.getProjectScope(t,r,e)}}catch(e){return logWarnError(e),un}}*genUniqueDescedants(e){if(!e)return;let t=projectIdFrom(e);if(isElement(e)){let r=this.fqnIndex.getFqn(e);yield*this.fqnIndex.uniqueDescedants(t,r)}else if(isDeploymentNode(e)){let r=this.deploymentsIndex.getFqn(e);yield*this.deploymentsIndex.uniqueDescedants(t,r)}}*genScopeExtendElement({element:e}){e.el.$nodeDescription&&(yield e.el.$nodeDescription,yield{...e.el.$nodeDescription,name:`this`},yield{...e.el.$nodeDescription,name:`it`}),yield*this.genUniqueDescedants(elementRef(e))}*genScopeElementView({viewOf:e,extends:t}){if(e)e.modelElement.value.$nodeDescription&&(yield e.modelElement.value.$nodeDescription),yield*this.genUniqueDescedants(elementRef(e));else if(t){let e=t.view.ref;e&&(yield*this.genScopeElementView(e))}}getScopeForStrictFqnRef(e,t,r){let i=t.parent;return i?new qt(this.deploymentsIndex.directChildrenOf(e,readStrictFqn(i)).filter(e=>this.reflection.isSubtype(e.type,rs.$type))):this.getProjectScope(e,rs.$type,r)}*genScopeExtendDeployment({deploymentNode:e}){e.value.$nodeDescription&&(yield e.value.$nodeDescription);let t=e.value.ref;t&&isDeploymentNode(t)&&(yield*this.genUniqueDescedants(t))}streamForFqnRef(e,t,r){let i=t.parent;if(!i)return Cn(this.genScopeForParentlessFqnRef(e,t,r));let a=i.value.ref;if(!a)return Wt;if(isImported(a))return Cn(this.genUniqueDescedants(a.imported.ref));if(isDeploymentNode(a))return Cn(this.genUniqueDescedants(a));if(isDeployedInstance(a)){let e=a.target.modelElement.value.ref,t=isImported(e)?e.imported.ref:isElement(e)?e:void 0;return Cn(this.genUniqueDescedants(t))}return isElement(a)?Cn(this.genUniqueDescedants(a)):nonexhaustive(a)}*genScopeForParentlessFqnRef(e,t,r){hn(t,isElementRef)||isFqnRefInsideModel(t)?yield*this.computeScope(e,r,ws.$type):isFqnRefInsideGlobals(t)?(yield*this.computeScope(e,r,ws.$type),yield*this.computeScope(e,r,rs.$type),yield*this.computeScope(e,r,es.$type)):(yield*this.computeScope(e,r,rs.$type),yield*this.computeScope(e,r,es.$type),hn(t,isDeploymentViewBody)&&(yield*this.computeScope(e,r,ws.$type)));let i=wh(t),a=i.localSymbols;a&&(yield*a.getStream(i.parseResult.value).filter(e=>this.reflection.isSubtype(e.type,mc.$type)))}*computeScope(e,t,r=this.reflection.getReferenceType(t)){let i=this.reflection.isSubtype(r,ws.$type),a=this.reflection.isSubtype(r,ns.$type),s=wh(t.container).localSymbols;if(!s){yield*this.getProjectScope(e,r,t).getAllElements();return}let byReferenceType=e=>this.reflection.isSubtype(e.type,r),c=t.container;for(;c;)yield*s.getStream(c).filter(byReferenceType),a&&isExtendDeploymentBody(c)&&(yield*this.genScopeExtendDeployment(c.$container)),i&&isExtendElementBody(c)&&(yield*this.genScopeExtendElement(c.$container)),i&&isElementViewBody(c)&&(yield*this.genScopeElementView(c.$container)),c=c.$container;yield*this.getProjectScope(e,r,t).getAllElements()}getProjectScope(e,t,r){return t===vc.$type?super.getGlobalScope(t,r):this.globalScopeCache.get(`${e}::${t}`,()=>new Jt(this.indexManager.projectElements(e,t)))}getGlobalScope(e,t){if(e===vc.$type)return super.getGlobalScope(e,t);let r=projectIdFrom(t.container);return this.getProjectScope(r,e,t)}};let Th;(function(e){e.type=new ei(`likec4/onDidChangeModel`)})(Th||={});let Eh;(function(e){e.type=new ti(`likec4/onDidChangeProjects`)})(Eh||={});let Dh;(function(e){let t=e.Method=`likec4/onDidChangeSnapshot`;e.type=new ei(t)})(Dh||={});let Oh;(function(e){e.type=new ei(`likec4/onRequestOpenView`)})(Oh||={});let kh;(function(e){e.req=new ni(`likec4/fetchComputedModel`)})(kh||={});let Ah;(function(e){e.req=new ri(`likec4/fetchViewsFromAllProjects`)})(Ah||={});let jh;(function(e){e.req=new ni(`likec4/fetchLayoutedModel`)})(jh||={});let Mh;(function(e){e.req=new ni(`likec4/layout-view`)})(Mh||={});let Nh;(function(e){e.req=new ni(`likec4/validate-layout`)})(Nh||={});let Ph;(function(e){e.req=new ri(`likec4/reload-projects`)})(Ph||={});let Fh;(function(e){e.req=new ri(`likec4/fetch-projects`)})(Fh||={});let Ih;(function(e){e.req=new ni(`likec4/register-project`)})(Ih||={});let Lh;(function(e){e.req=new ni(`likec4/build`)})(Lh||={});let Rh;(function(e){e.req=new ni(`likec4/locate`)})(Rh||={});let zh;(function(e){e.req=new ni(`likec4/change-view`)})(zh||={});let Bh;(function(e){e.req=new ri(`likec4/metrics`)})(Bh||={});let Vh;(function(e){e.req=new ni(`likec4/document-tags`)})(Vh||={});let Hh;(function(e){e.req=new ri(`likec4/fetch-projects-overview`)})(Hh||={});const Q=q.getChild(`rpc`);var Rpc=class extends ADisposable{services;constructor(e){super(),this.services=e}init=ie(()=>{let e=this.services.shared.lsp.Connection;if(!e){Q.info(`no connection, skip init ServerRpc`);return}Q.info(`init ServerRpc`);let t=this.services.likec4,r=this.services.shared.workspace,i=r.LangiumDocuments,a=r.DocumentBuilder,sendDidChangeModelNotification=t=>{Q.debug`send ${`onDidChangeModel`} for project ${t}`,e.sendNotification(Th.type,{projectId:t}).catch(e=>{Q.warn(`[ServerRpc] error sending onDidChangeModel for project {project}`,{error:e,project:t})})},s=re(e=>{if(typeof e==`string`)sendDidChangeModelNotification(e);else for(let t of e)sendDidChangeModelNotification(t)},{reducer:(e,t)=>!e||e===t?t:e instanceof Set?(e.add(t),e):/* @__PURE__ */ new Set([e,t]),triggerAt:`end`,minQuietPeriodMs:130,maxBurstDurationMs:400}),c=re(t=>{t>1?Q.debug`send ${`DidChangeProjectsNotification`} (${t} batched)`:Q.debug`send ${`DidChangeProjectsNotification`}`,e.sendNotification(Eh.type).catch(e=>{Q.warn(`[ServerRpc] error sending DidChangeProjectsNotification:`,{error:e})})},{reducer:(e,t)=>(e??0)+t,triggerAt:`end`,minQuietPeriodMs:250,maxBurstDurationMs:700}),l=!0;this.onDispose(Wn.create(()=>{s.cancel(),c.cancel()}),t.ModelBuilder.onModelParsed(e=>s.call(e)),r.ProjectsManager.onProjectsUpdate(()=>c.call(1)),e.onRequest(kh.req,async({projectId:e,cleanCaches:i=!1},a)=>{Q.debug`received request ${`fetchComputedModel`} for project ${e}`,i&&(Q.debug`cleanCaches: ${i}`,e?(r.ManualLayouts.clearCaches(),await r.ProjectsManager.rebuildProject(e)):await r.WorkspaceManager.rebuildAll());let s=await t.ModelBuilder.computeModel(e,a);return s===Pa.EMPTY?{model:null}:{model:s.$data}}),e.onNotification(Dh.type,async e=>{let t=R.parse(e.update??e.delete),i=`update`in e?{update:t}:{delete:t};Q.debug`received notification ${`onDidChangeSnapshot`} with ${e}`,await r.ManualLayouts.handleFileSystemUpdate(i)}),e.onRequest(jh.req,async({projectId:e},r)=>{Q.debug`received request ${`fetchLayoutedModel`} for project ${e}`;let i=await t.LanguageServices.layoutedModel(e);if(i===null)return{model:null};let a=await t.Views.diagrams(e,r);return{model:{...i.$data,_stage:`layouted`,views:Pe(a,e=>e.id)}}}),e.onRequest(Mh.req,async({viewId:e,projectId:r,layoutType:i,hints:a},s)=>(Q.debug`received request ${`layoutView`} for ${e} from project ${r} (layout type: ${i??`not set`})`,{result:await t.Views.layoutView({viewId:e,projectId:r,layoutType:i,layoutHints:a,cancelToken:s})})),e.onRequest(Nh.req,async({projectId:e},r)=>(Q.debug`received request ${`validateLayout`} for project ${e}`,{result:reportLayoutDrift((await t.Views.layoutAllViews(e,r)).map(e=>e.diagram))})),e.onRequest(Fh.req,async()=>{Q.debug`received request ${`FetchProjects`}`;let e=i.groupedByProject();return{projects:ae(e,(e,t)=>{let{folderUri:i,config:{name:a,title:s}}=r.ProjectsManager.getProject(t);return{folder:i.toString(),path:r.WorkspaceManager.relativePath(i),config:{name:a,title:s},docs:p(e,e=>e.uri.toString())}})}}),e.onRequest(Ph.req,async e=>{Q.debug`received request ${`ReloadProjects`}`,r.ManualLayouts.clearCaches(),await r.ProjectsManager.reloadProjects(e)}),e.onRequest(Ih.req,async(e,t)=>{Q.debug`received request ${`RegisterProject`}`,r.ManualLayouts.clearCaches();let i;return i=`configUri`in e?await r.ProjectsManager.registerConfigFile(R.parse(e.configUri),t):await r.ProjectsManager.registerProject(e,t),{id:i.id}}),e.onRequest(Ah.req,async e=>{Q.debug`received request ${`FetchViewsFromAllProjects`}`;let i=[];for(let a of r.ProjectsManager.all){await Yt(e);try{let r=await t.Views.computedViews(a,e);i.push(...N(r,p(e=>({id:e.id,title:e.title??e.id,projectId:a})),Be((e,t)=>e.id===`index`?-1:t.id===`index`?1:e.title.localeCompare(t.title))))}catch(e){Q.warn(`Failed to fetch views for project ${a}:`,{error:e})}}return{views:i}}),e.onRequest(Lh.req,async({docs:t},r)=>{let s=t.map(e=>R.parse(e)),isNotChanged=e=>!s.some(t=>L.equals(t,e)),c=i.userDocuments.map(e=>e.uri).filter(isNotChanged).toArray();Q.debug(`[ServerRpc] received request to build:
|
|
135
|
+
changed (total ${s.length}):${t.map(e=>`
|
|
136
|
+
- `+e).join(``)}
|
|
137
|
+
deleted (total ${c.length}):${c.map(e=>`
|
|
138
|
+
- `+e.toString()).join(`
|
|
139
|
+
`)}`),!l&&s.length+c.length>0&&await Promise.allSettled([...s,...c].map(async t=>{let r=t.toString();Q.debug(`clear diagnostics for ${r}`);try{await e.sendDiagnostics({uri:r,diagnostics:[]})}catch(e){Q.warn(`error clearing diagnostics for ${r}: ${e}`)}})),l=!1,await Yt(r),await a.update(s,c,r)}),e.onRequest(Rh.req,e=>{Q.debug`received request ${`locate`}, ${e}`;let r=e.projectId;switch(!0){case`element`in e:return t.ModelLocator.locateElement(e.element,r);case`relation`in e:return t.ModelLocator.locateRelation(e.relation,r);case`astPath`in e:return t.ModelLocator.locateDynamicViewStep({view:e.view,astPath:e.astPath,projectId:r});case`view`in e:return t.ModelLocator.locateView(e.view,r);case`deployment`in e:return t.ModelLocator.locateDeploymentElement(e.deployment,r);default:nonexhaustive(e)}}),e.onRequest(zh.req,async e=>(Q.debug`received request ${`changeView`} of ${e.viewId} from project ${e.projectId}`,await t.ModelChanges.applyChange(e))),e.onRequest(Bh.req,async e=>{let i=null;for(let a of r.ProjectsManager.all)try{let r=await t.ModelBuilder.computeModel(a,e);if(r===Pa.EMPTY)continue;i??={elementKinds:0,deploymentKinds:0,relationshipKinds:0,tags:0,customColors:0,elements:0,deploymentNodes:0,relationships:0,views:0,projects:0},i.elementKinds+=Te(r.specification.elements).length,i.deploymentKinds+=Te(r.specification.deployments).length,i.relationshipKinds+=Te(r.specification.relationships).length,i.tags+=Te(r.specification.tags).length,i.customColors+=Te(r.specification.customColors??{}).length,i.elements+=Te(r.$data.elements).length,i.deploymentNodes+=[...r.deployment.nodes()].length,i.relationships+=Te(r.$data.relations).length,i.views+=Te(r.$data.views).length,i.projects+=1}catch(e){Q.warn(`Error fetching telemetry metrics for project ${a}`,{err:e})}return await Yt(e),{metrics:i}}),e.onRequest(Vh.req,async({documentUri:e},i)=>{let a=R.parse(e);Q.debug`received request ${`GetDocumentTags`} for document ${a}`;let s=await t.ModelLocator.locateDocumentTags(a,i);return{projectId:r.ProjectsManager.ownerProjectId(a),tags:s??[]}}),e.onRequest(Hh.req,async e=>(Q.debug`received request ${`FetchProjectsOverview`}`,{projectsView:await t.LanguageServices.projectsOverview(e)})));function reportLayoutDrift(e){return N(e,D(e=>!!e.hasLayoutDrift),p(e=>{let r=t.ModelLocator.locateView(e.id);return invariant(r,`View ${e.id} not found`),{uri:r.uri,viewId:e.id,severity:Nr.Warning,message:`Layout drift detected for view '${e.id}'`,range:r.range}}))}});async openView(e){let t=this.services.shared.lsp.Connection;t?await t.sendNotification(Oh.type,e):Q.warn(`No LSP connection`)}},NodeKindProvider=class{services;constructor(e){this.services=e}getSymbolKind(e){let t=yn(e)?e.$type:e.type,hasType=(...e)=>e.some(e=>this.services.AstReflection.isSubtype(t,e));switch(!0){case hasType(ws.$type,Bs.$type,rs.$type,es.$type,mc.$type):return Ur.Constructor;case hasType(Ac.$type,Pc.$type,jc.$type,ac.$type,ml.$type):return Ur.Namespace;case hasType(xc.$type):return Ur.Struct;case hasType(El.$type,vc.$type,Zo.$type,hl.$type):return Ur.EnumMember;case hasType($c.$type,fl.$type):return Ur.Event;case hasType(Es.$type,os.$type,ul.$type,ll.$type):return Ur.TypeParameter}return Ur.Field}getCompletionItemKind(e){let t=yn(e)?e.$type:e.type,hasType=(...e)=>e.some(e=>this.services.AstReflection.isSubtype(t,e));switch(!0){case hasType(Zo.$type):return Ir.Color;case hasType(ws.$type,rs.$type,es.$type,Bs.$type,mc.$type):return Ir.Constructor;case hasType(Ac.$type,Pc.$type,jc.$type,ac.$type,ml.$type):return Ir.Module;case hasType(xc.$type):return Ir.Class;case hasType(El.$type,vc.$type,Zo.$type,hl.$type):return Ir.EnumMember;case hasType($c.$type,fl.$type):return Ir.Event;case hasType(Es.$type,ul.$type,os.$type,ll.$type):return Ir.TypeParameter;default:return Ir.Reference}}},WorkspaceSymbolProvider=class extends Un{};const Uh=q.getChild(`views`);var DefaultLikeC4Views=class extends ADisposable{services;#e;#t=new I.default(e=>new ProjectStorage({projectId:e,storage:cr(this.#e,e),layouter:e=>this.layouter.layout(e)}));ModelBuilder;constructor(e){super(),this.services=e,this.ModelBuilder=e.likec4.ModelBuilder,this.#e=lr(),this.onDispose(this.#e,Wn.create(()=>{this.#t.clear()}),e.shared.workspace.WorkspaceManager.onForceCleanCache(()=>{Uh.info`force clean cache`,this.#e.clear()}),e.shared.workspace.ManualLayouts.onManualLayoutUpdate(({projectId:e,viewId:t})=>{this.#t.has(e)&&t&&this.projectStorage(e).clearView(t)}))}get layouter(){return this.services.likec4.Layouter}async computedViews(e,t){let r=await this.ModelBuilder.computeModel(e,t);return Fe(r.$data.views)}async _layoutAllViews(e,t){let r=Fe(e.$data.views);if(r.length===0)return[];let i=e.project.id,a=Uh.getChild(i),s=this.projectStorage(i),c=[],l=e.$styles,u=[];for(let e of r){let t={view:e,styles:l},r=await s.get(t);r?u.push(r):c.push(t)}if(u.length>0&&(c.length>0?a.trace`cached ${u.length} views, still need to layout ${c.length} views`:a.trace`cached all ${u.length} views`),c.length>0){let e=performanceMark();a.debug` -> layouting ${c.length} views`,await this.layouter.batchLayout({batch:c,cancelToken:t,onSuccess:(e,t)=>{u.push(s.remember(e,t))},onError:(e,t)=>{a.warn(`Fail layout view ${e.view.id}`,{error:t})}}),a.debug` <- layouted ${c.length} views in ${e.pretty}`}return t&&await Yt(t),u.length!==r.length&&a.warn`${u.length} of ${r.length} views were layouted`,u}async layoutAllViews(e,t){let r=await this.ModelBuilder.computeModel(e,t);return await this._layoutAllViews(r,t)}async layoutView({viewId:e,layoutType:t,projectId:r,cancelToken:i,layoutHints:a}){let s=await this.ModelBuilder.computeModel(r,i),c=s.findView(e)?.$view;r=s.project.id;let l=Uh.getChild(r);if(a){invariant(c,`View ${e} not found in model`),l.debug`using provided AI layout hints for view ${e}`;let{dot:t,diagram:r}=await this.layouter.aiLayout({view:c,styles:s.$styles},a);return{dot:t,diagram:r}}let u=this.projectStorage(r);if(!c){l.warn`view ${e} not found in model`;let r=s.findManualLayout(e);if(r&&t!==`manual`)return l.warn`view ${e} has manual layout, but requested layout type is ${t}, returning null`,null;if(r){l.info`found manual layout for ${e}`;let t={...r};return t.drifts=[`not-exists`],t._layout=`manual`,{diagram:t,dot:`# manual layout`}}return null}try{let e={view:c,styles:s.$styles},r=await u.getOrExecute(e);return j(t)?{dot:r.dot,diagram:this.withLayoutType(r.diagram,s,t)}:r}catch(e){let t=loggable(e);return l.warn(t),this.reportViewError(c,r,t),Promise.reject(e)}}async diagrams(e,t){let r=await this.ModelBuilder.computeModel(e,t);return(await this._layoutAllViews(r,t)).map(({diagram:e})=>this.withLayoutType(e,r,`manual`))}async viewsAsGraphvizOut(e,t){let r=`All-LayoutedViews-DotWithSvg`,i=this.services.shared.workspace.Cache;if(i.has(r))return await Promise.resolve(i.get(r));let a=await this.ModelBuilder.computeModel(e,t),s=Fe(a.$data.views);if(s.length===0)return[];let c=s.map(async e=>{let{dot:t,svg:r}=await this.layouter.svg({view:e,styles:a.$styles});return{id:e.id,dot:t,svg:r}}),l=[],u=await Promise.allSettled(c);for(let e of u)e.status===`fulfilled`?l.push(e.value):logWarnError(e.reason);return i.set(r,l),l}async openView(e,t){await this.services.Rpc.openView({viewId:e,projectId:t})}async adhocView(e,t){Uh.trace`layouting adhoc view...`;let r=await this.ModelBuilder.computeModel(t),i=computeAdhocView(r,e),{diagram:a}=await this.layouter.layout({view:{...i,hash:``,_type:`element`},styles:r.$styles});return Uh.debug`layouting adhoc view... done`,a}reportViewError(e,t,r){this.projectStorage(t).reportViewError(e,()=>{this.services.shared.lsp.Connection?.window.showErrorMessage(`LikeC4: ${r}`)})}withLayoutType(e,t,r){if(!r)return e;let i=t.findManualLayout(e.id);return i?(e._layout===`manual`&&Uh.error`layouted view ${e.id} has ${e[Ui]} layout, expected auto or none`,r===`manual`?e._layout===`manual`?e:applyManualLayout(e,i):calcDriftsFromSnapshot(e,i)):e}projectStorage(e){return this.#t.get(e)}},ProjectStorage=class{#e;#t;#n;constructor(e){this.#e=Uh.getChild(e.projectId),this.#t=e.storage,this.#n=e.layouter}async get(e){let t=cacheKey(e),r=await this.#t.get(t);if(r)return this.#e.trace`cache hit for ${e.view.id}`,mergeWithCachedLayout(e.view,r);this.#e.trace`cache miss for ${e.view.id}`}async getOrExecute(e){let t=cacheKey(e),r=await this.#t.get(t);if(r)return this.#e.trace`cache hit for ${e.view.id}`,mergeWithCachedLayout(e.view,r);this.#e.trace`cache miss for ${e.view.id}`;let i=performanceMark(),a=await this.#n(e);return this.#e.trace(`layouted {view} in ${i.pretty}`,{view:e.view.id}),await this.#t.set(t,a),this.resetViewError(e.view),a}remember=(e,t)=>{let r=cacheKey(e);return t&&(this.#t.set(r,t).catch(e=>{this.#e.error(e)}),this.resetViewError(e.view)),t};reportViewError(e,t){let r=`error:${e.id}`;this.#t.has(r).then(e=>{e||(this.#t.set(r,`true`),t())})}async clearView(e){this.resetViewError(e);let t=await this.#t.keys(`v:${e}:`);t.length!==0&&(this.#e.trace`clear ${t.length} cached entries for view ${e}`,await Promise.all(t.map(e=>this.#t.remove(e))))}clearAll(){this.#e.trace`clear caches`,this.#t.clear()}resetViewError(e){let t=typeof e==`string`?e:e.id;this.#t.del(`error:${t}`)}};function cacheKey(e){return`v:${e.view.id}:${e.view.hash}:${e.styles.fingerprint}`}function mergeWithCachedLayout(e,t){return{dot:t.dot,diagram:applyCachedLayout(e,t.diagram)}}const Wh={graphviz(){return new Oa}};function WithGraphviz(e){return{graphviz(){return e}}}function createLikeC4SharedModule(e){return{lsp:{NodeKindProvider:e=>new NodeKindProvider(e),WorkspaceSymbolProvider:e=>new WorkspaceSymbolProvider(e)},workspace:{Cache:e=>new Gn(e,rn.Validated),IndexManager:e=>new IndexManager(e),LangiumDocuments:e=>new LangiumDocuments(e),ProjectsManager:e=>new Eu(e),WorkspaceManager:e=>new LikeC4WorkspaceManager(e),FileSystemProvider:t=>e.fileSystemProvider(t),FileSystemWatcher:t=>e.fileSystemWatcher(t),ManualLayouts:t=>e.manualLayouts(t)}}}function bind(e){return t=>new e(t)}function createLikeC4Module(e){return{documentation:{DocumentationProvider:bind(LikeC4DocumentationProvider)},validation:{DocumentValidator:bind(LikeC4DocumentValidator)},Rpc:bind(Rpc),likec4:{LanguageServices:bind(DefaultLikeC4LanguageServices),Graphviz:t=>e.graphviz(t),Layouter:e=>new QueueGraphvizLayoter({graphviz:e.likec4.Graphviz}),Views:bind(DefaultLikeC4Views),DeploymentsIndex:bind(DeploymentsIndex),ModelChanges:bind(LikeC4ModelChanges),FqnIndex:bind(FqnIndex),ModelParser:bind(LikeC4ModelParser),ModelBuilder:bind(DefaultLikeC4ModelBuilder),ModelLocator:bind(LikeC4ModelLocator),LastSeen:bind(LastSeenArtifacts)},lsp:{CompletionProvider:bind(LikeC4CompletionProvider),DocumentHighlightProvider:bind(LikeC4DocumentHighlightProvider),DocumentSymbolProvider:bind(LikeC4DocumentSymbolProvider),SemanticTokenProvider:bind(LikeC4SemanticTokenProvider),HoverProvider:bind(LikeC4HoverProvider),CodeLensProvider:bind(LikeC4CodeLensProvider),DocumentLinkProvider:bind(LikeC4DocumentLinkProvider),Formatter:bind(LikeC4Formatter),CodeActionProvider:bind(LikeC4CodeActionProvider)},references:{NameProvider:bind(LikeC4NameProvider),ScopeComputation:bind(LikeC4ScopeComputation),ScopeProvider:bind(LikeC4ScopeProvider)},parser:{ValueConverter:bind(LikeC4ValueConverter)}}}function createLanguageServices$1(e={},t,r,i){let a=createSharedServices(e),s=[xn({shared:a}),vu,createLikeC4Module({...Fu,...Iu,...Wh,...e}),t,r,i].reduce(_merge,{}),c=bn(s);return a.ServiceRegistry.register(c),registerValidationChecks(c),e.connection?onNextTick(()=>a.workspace.WorkspaceManager.ready.then(()=>c.Rpc.init())):a.workspace.ConfigurationProvider.initialized({}),{shared:a,likec4:c}}e(createLanguageServices$1,`createLanguageServices`);function createSharedServices(e={}){let t={...Fu,...Iu,...e};return bn(jn({...t,fileSystemProvider:()=>new NoopFileSystemProvider}),_u,createLikeC4SharedModule(t))}function _merge(e,t){if(t)for(let[r,i]of Object.entries(t)){if(r===`__proto__`||r===`constructor`||r===`prototype`||i===void 0)continue;let t=Object.hasOwn(e,r),a=e[r];e[r]=t&&a!==null&&i!==null&&typeof a==`object`&&typeof i==`object`?_merge(a,i):i}return e}function parseWhere(e){if(S(e)){let t=e;switch(!0){case t.startsWith(`tag is not #`):return{tag:{neq:t.replace(`tag is not #`,``)}};case t.startsWith(`tag is #`):return{tag:{eq:t.replace(`tag is #`,``)}};case t.startsWith(`kind is not `):return{kind:{neq:t.replace(`kind is not `,``)}};case t.startsWith(`kind is `):return{kind:{eq:t.replace(`kind is `,``)}};case t.startsWith(`source.`):return{operator:parseWhere(t.replace(`source.`,``)),participant:`source`};case t.startsWith(`target.`):return{operator:parseWhere(t.replace(`target.`,``)),participant:`target`};default:throw Error(`Unknown where operator: ${e}`)}}if(e.and)return{and:p(e.and,parseWhere)};if(e.or)return{or:p(e.or,parseWhere)};if(e.not)return{not:parseWhere(e.not)};throw Error(`Unknown where operator: ${e}`)}function $include(...e){return t=>{if(e.length===2&&typeof e[1]!=`string`&&(`where`in e[1]||`with`in e[1])){let r=t.$expr(e[0]),i=e[1].where?parseWhere(e[1].where):void 0;i&&(r={where:{expr:r,condition:i}});let a=e[1].with;return a&&(r=U.is(r)||U.isWhere(r)?{custom:{...a,expr:r}}:{customRelation:{...a,expr:r}}),t.include(r),t}return t.include(...e.map(e=>t.$expr(e))),t}}function $exclude(...e){return t=>{let r=t.$expr(e[0]);if(e.length===2&&e[1].where){let t=parseWhere(e[1].where);r={where:{expr:r,condition:t}}}return t.exclude(r),t}}function $style(e,{notation:t,...r}){return i=>i.style({targets:(b(e)?e:[e]).map(e=>i.$expr(e)),...t?{notation:t}:{},style:{...r}})}function $autoLayout(e,t){return r=>r.autoLayout(e,t)}function $rules(...e){return t=>e.reduce((e,t)=>t(e),t)}function $deploymentExpr(e){if(!S(e))return e;let asTypedDeploymentExpression=e=>e;if(e===`*`)return asTypedDeploymentExpression({wildcard:!0});if(e.startsWith(`->`))return e.endsWith(`->`)?asTypedDeploymentExpression({inout:$deploymentExpr(e.replace(/->/g,``).trim())}):asTypedDeploymentExpression({incoming:$deploymentExpr(e.replace(`-> `,``))});if(e.endsWith(` ->`))return asTypedDeploymentExpression({outgoing:$deploymentExpr(e.replace(` ->`,``))});if(e.includes(` <-> `)){let[t,r]=e.split(` <-> `);return asTypedDeploymentExpression({source:$deploymentExpr(t),target:$deploymentExpr(r),isBidirectional:!0})}if(e.includes(` -> `)){let[t,r]=e.split(` -> `);return asTypedDeploymentExpression({source:$deploymentExpr(t),target:$deploymentExpr(r)})}return e.endsWith(`._`)?asTypedDeploymentExpression({ref:{deployment:e.replace(`._`,``)},selector:`expanded`}):e.endsWith(`.**`)?asTypedDeploymentExpression({ref:{deployment:e.replace(`.**`,``)},selector:`descendants`}):e.endsWith(`.*`)?asTypedDeploymentExpression({ref:{deployment:e.replace(`.*`,``)},selector:`children`}):asTypedDeploymentExpression({ref:{deployment:e}})}function $includeAncestors(e){return t=>t.includeAncestors(e)}function $step(...e){let[t,r,i]=e;if(S(r)){let e;return i!=null&&(e=typeof i==`string`?{title:i}:{...i.title&&{title:i.title},...i.with}),i=>i.step({source:t,target:r,...e})}let[a,s]=t.split(` -> `),c=h(r)?{...r.title&&{title:r.title},...r.with}:{};return e=>e.step({source:a,target:s,...c})}function accumulateSteps(e){let t=[],r={step:e=>(t.push(e),r)};return ve(e,(e,t)=>{if(typeof t==`function`)return t(e);let[r,i]=t.split(` -> `);return e.step({source:r,target:i})},r),invariant(isNonEmptyArray(t),`At least one step is required`),t}$step.series=(...e)=>t=>{let[r,...i]=e,{steps:a}=ve(i,(e,t)=>{let[r,{description:i,...a}]=b(t)?t:[t,{}];return S(i)&&(i={md:i}),e.steps.push({source:e.source,target:r.substring(3),...a,...i?{description:i}:{},astPath:``}),e.source=r.substring(3),e},{source:r,steps:[]});return invariant(isNonEmptyArray(a),`At least one step is required`),t.step({_type:`series`,steps:a})},$step.try=e=>t=>{let r={steps:accumulateSteps(e.try)},i=e.catch?{catch:{steps:accumulateSteps(e.catch)}}:void 0,a=e.finally?{finally:{steps:accumulateSteps(e.finally)}}:void 0;return t.step({_type:`try`,try:r,...i,...a})};function blockBuilder(e){return(...t)=>r=>{if(t.length===1&&typeof t[0]==`object`&&t[0]!==null){let i=t[0],a=accumulateSteps(i.steps);return r.step({_type:e,title:i.title,steps:a})}let i=accumulateSteps(t);return r.step({_type:e,steps:i})}}$step.parallel=blockBuilder(`par`),$step.loop=blockBuilder(`loop`),$step.opt=blockBuilder(`opt`),$step.break=blockBuilder(`break`),$step.alt=(...e)=>t=>{let r=[],i={Types:{},addBranch:e=>(r.push(e),i)};return e.forEach(e=>{e(i)}),invariant(isNonEmptyArray(r),`At least one branch is required`),t.step({_type:`alt`,branches:r})};function branchBuilder(e){return(...t)=>r=>{let i=accumulateSteps(t);return r.addBranch({_type:e,steps:i})}}$step.when=branchBuilder(`when`),$step.if=branchBuilder(`if`),$step.else=branchBuilder(`else`);function mkViewBuilder(e){let t={$expr:e._type===`deployment`?$deploymentExpr:$expr,autoLayout(t,r){return e.rules.push(exact({direction:t,rankSep:r?.rank,nodeSep:r?.node})),this},include(...t){return e.rules.push({include:t}),this},style(t){return e.rules.push(t),this},get Expr(){throw Error(`Expr is not available in runtime`)},get Types(){throw Error(`Types are not available in runtime`)},get ElementExpr(){throw Error(`ElementExpr is not available in runtime`)},get TypedExpr(){throw Error(`TypedExpr is not available in runtime`)}};return e._type===`element`?Object.assign(t,{exclude(...t){return e.rules.push({exclude:t}),this}}):e._type===`deployment`?Object.assign(t,{exclude(...t){return e.rules.push({exclude:t}),this},includeAncestors(t){return e.rules.push({includeAncestors:t}),this}}):e._type===`dynamic`?Object.assign(t,{step(t){return e.steps.push(t),this}}):t}function ensureObj(e){return b(e)?s(e,e=>({})):e}function validateSpec({tags:e,elements:t,deployments:r,relationships:i,...a}){let s={};e&&Object.assign(s,ensureObj(e));let c=ensureObj(t??{});for(let[e,t]of M(c))if(t.tags)for(let r of t.tags)invariant(r in s,`Invalid specification for element kind "${e}": tag "${r}" not found`);let l=ensureObj(r??{});for(let[e,t]of M(l))if(t.tags)for(let r of t.tags)invariant(r in s,`Invalid specification for deployment kind "${e}": tag "${r}" not found`);return{...a,tags:s,elements:c,deployments:l,relationships:ensureObj(i??{})}}const specKeysOf=e=>C(e)?[]:b(e)?e:Object.keys(e);function assertSpecificationCompatible(e,t){let r=[],compare=(e,t,i)=>{for(let a of t)i.has(a)||r.push(`${e} "${a}"`)};if(compare(`element kind`,specKeysOf(e.elements),new Set(specKeysOf(t.elements))),compare(`deployment kind`,specKeysOf(e.deployments),new Set(specKeysOf(t.deployments))),compare(`relationship kind`,specKeysOf(e.relationships),new Set(specKeysOf(t.relationships))),compare(`tag`,specKeysOf(e.tags),new Set(specKeysOf(t.tags))),compare(`metadata key`,e.metadataKeys??[],new Set(t.metadataKeys??[])),r.length>0)throw Error(`Specification mismatch — declared but not present in the loaded model:\n - ${r.join(`
|
|
140
|
+
- `)}`)}function toMarkdownOrString(e){return C(e)?null:typeof e==`string`?{txt:e}:e}function builder(e,t=/* @__PURE__ */ new Map,r=[],i=/* @__PURE__ */ new Map,a={predicates:{},dynamicPredicates:{},styles:{}},s=/* @__PURE__ */ new Map,c=[],l=new I.default(()=>/* @__PURE__ */ new Map),u=`strict`){let h=validateSpec(e),toLikeC4Specification=()=>({elements:structuredClone(h.elements),deployments:structuredClone(h.deployments),relationships:structuredClone(h.relationships),tags:assignTagColors(structuredClone(h.tags)),...h.metadataKeys?{metadataKeys:h.metadataKeys}:{},customColors:{}}),mapLinks=e=>{if(e&&k(e,1))return p(e,e=>typeof e==`string`?{url:e}:e)},createGenericView=(e,t,r)=>{oe(t)&&(r=t,t={}),t??={};let{links:i=[],title:a=null,description:s=null,tags:c=[],...l}=typeof t==`string`?{title:t}:{...t};invariant(l.order===void 0||Number.isInteger(l.order)&&l.order>=0,`View order must be a non-negative integer`);let u=mapLinks(i);return[exact({id:e,title:a,description:toMarkdownOrString(s),tags:c,links:u,_stage:`parsed`,...l}),r]},checkElementExists=e=>{let[r,i]=splitGlobalFqn(e),a=(r?l.get(r):t).get(i);return invariant(a,`Element with id "${e}" not found`),a},parseRelEndpoint=e=>{if(typeof e==`string`){let[t,r]=splitGlobalFqn(e);return t?{project:t,model:r}:{model:r}}return`project`in e||`deployment`in e?e:parseRelEndpoint(e.model)},g={get Types(){throw Error(`Types are not available in runtime`)},specification:e=>{let p=Yi(validateSpec(e),h),m=new I.default(()=>/* @__PURE__ */ new Map);for(let[e,t]of l)m.set(e,structuredClone(t));return builder(p,structuredClone(t),structuredClone(r),structuredClone(i),structuredClone(a),structuredClone(s),structuredClone(c),m,u)},clone:()=>{let e=new I.default(()=>/* @__PURE__ */ new Map);for(let[t,r]of l)e.set(t,structuredClone(r));return builder(structuredClone(h),structuredClone(t),structuredClone(r),structuredClone(i),structuredClone(a),structuredClone(s),structuredClone(c),e,u)},__addElement:e=>{let[r,i]=splitGlobalFqn(e.id),a=parentFqn(i),s=r?l.get(r):t;a&&invariant(s.get(a),`Parent element with id "${a}" not found for element with id "${e.id}"`);let c=s.get(i);if(c){if(u===`strict`)throw Error(`Element with id "${e.id}" already exists`);invariant(c.kind===e.kind,`Element with id "${e.id}" already exists with kind "${c.kind}", cannot redeclare as "${e.kind}"`)}return s.set(i,r?{...e,id:i}:e),g},__addRelation(e){let t=parseRelEndpoint(e.source),i=H.flatten(t),a=parseRelEndpoint(e.target),s=H.flatten(a),c=checkElementExists(i),l=checkElementExists(s);if(isGlobalFqn(i)&&isGlobalFqn(s))throw Error(`Cannot create relationship between global elements`);return!isGlobalFqn(i)&&!isGlobalFqn(s)&&invariant(!isSameHierarchy(c,l),`Cannot create relationship between elements in the same hierarchy`),r.push({id:`rel${r.length+1}`,...e,source:t,target:a}),g},__fqn(e){return invariant(e.trim()!==``,`Id must be non-empty`),e},__deploymentFqn(e){return invariant(e.trim()!==``,`Id must be non-empty`),e},__addSourcelessRelation(){throw Error(`Can be called only in nested model`)},__addView:e=>{if(i.has(e.id)&&u===`strict`)throw Error(`View with id "${e.id}" already exists`);return isElementView$1(e)&&`viewOf`in e&&invariant(t.get(e.viewOf),`Invalid scoped view ${e.id}, wlement with id "${e.viewOf}" not found`),i.set(e.id,e),g},__addDeployment:e=>{if(s.has(e.id))throw Error(`Deployment with id "${e.id}" already exists`);let r=parentFqn(e.id);return r&&invariant(s.get(r),`Parent element with id "${r}" not found for node with id "${e.id}"`),isDeployedInstance$1(e)&&(invariant(r,`Instance ${e.id} of ${e.element} must be deployed under a parent node`),invariant(t.get(e.element),`Instance "${e.id}" references non-existing element "${e.element}"`)),s.set(e.id,e),g},__addDeploymentRelation:e=>(invariant(!isSameHierarchy(e.source.deployment,e.target.deployment),`Cannot create relationship between elements in the same hierarchy`),invariant(s.has(e.source.deployment),`Relation "${e.source.deployment} -> ${e.target.deployment}" references non-existing source`),invariant(s.has(e.target.deployment),`Relation "${e.source.deployment} -> ${e.target.deployment}" references non-existing target`),c.push({id:`deploy_rel${c.length+1}`,...e}),g),build:e=>({[Vi]:`parsed`,projectId:typeof e==`string`?e:e?.id??`from-builder`,project:{id:typeof e==`string`?e:`from-builder`,...typeof e==`object`&&e?e:{}},specification:toLikeC4Specification(),elements:_e(structuredClone(Array.from(t.entries()))),relations:m(r,e=>[e.id,structuredClone(e)]),globals:structuredClone(a),deployments:{elements:_e(structuredClone(Array.from(s.entries()))),relations:m(c,e=>[e.id,structuredClone(e)])},views:_e(structuredClone(Array.from(i.entries()))),imports:N(Array.from(l.entries()),p(([e,t])=>[e,structuredClone([...t.values()])]),D(([e,t])=>t.length>0),_e())}),toLikeC4Model:e=>computeLikeC4Model(g.build(e)),helpers:()=>({model:{model:(...e)=>t=>e.reduce((e,t)=>t(e),t),rel:(e,t,r)=>i=>{let{title:a=``,links:s=[],description:c=null,notes:l=null,...u}=Yi(typeof r==`string`?{title:r}:{...r},{title:null,links:null}),p=mapLinks(s);return i.__addRelation(exact({source:{model:e},target:{model:t},title:a,...c&&{description:toMarkdownOrString(c)},...l&&{notes:toMarkdownOrString(l)},links:p,...u})),i},relTo:(e,t)=>r=>{let{title:i=``,links:a,description:s=null,notes:c=null,...l}=Yi(typeof t==`string`?{title:t}:{...t},{title:null,links:null});return r.__addSourcelessRelation(exact({target:{model:e},title:i,...s&&{description:toMarkdownOrString(s)},...c&&{notes:toMarkdownOrString(c)},links:mapLinks(a),...l})),r},...ae(h.elements,({style:e,...t},r)=>(i,a)=>{let add=(s=>{let{links:c,icon:l,color:u,shape:p,style:m,title:h,description:g,summary:_,...v}=typeof a==`string`?{title:a}:{...a},y=l??e?.icon,b=mapLinks(c),x=s.__fqn(i);return s.__addElement(exact({id:x,kind:r,...t,title:h??t.title??nameFromFqn(x),...g&&{description:toMarkdownOrString(g)},..._&&{summary:toMarkdownOrString(_)},style:exact({icon:y,color:u??e?.color,shape:p??e?.shape,border:e?.border,opacity:e?.opacity,size:e?.size,padding:e?.padding,textSize:e?.textSize,sizing:e?.sizing,...m}),...b&&{links:b},...v})),s});return add.with=(...e)=>t=>{add(t);let{__fqn:r,__addSourcelessRelation:a}=t;try{t.__fqn=e=>`${r(i)}.${e}`,t.__addSourcelessRelation=e=>t.__addRelation({...e,source:{model:r(i)}}),e.reduce((e,t)=>t(e),t)}finally{t.__fqn=r,t.__addSourcelessRelation=a}return t},add})},views:{views:(...e)=>t=>e.reduce((e,t)=>t(e),t),view:(e,t,r)=>{let[i,a]=createGenericView(e,t,r),s={...i,[Hi]:`element`,rules:[]},add=e=>(e.__addView(s),a&&a(mkViewBuilder(s)),e);return add.with=(...e)=>t=>{add(t);let r=mkViewBuilder(s);for(let t of e)t(r);return t},add},viewOf:(e,t,r,i)=>{let[a,s]=createGenericView(e,r,i),c={...a,viewOf:t,[Hi]:`element`,rules:[]},add=e=>(e.__addView(c),s&&s(mkViewBuilder(c)),e);return add.with=(...e)=>t=>{add(t);let r=mkViewBuilder(c);for(let t of e)t(r);return t},add},deploymentView:(e,t,r)=>{let[i,a]=createGenericView(e,t,r),s={...i,[Hi]:`deployment`,rules:[]},add=e=>(e.__addView(s),a&&a(mkViewBuilder(s)),e);return add.with=(...e)=>t=>{add(t);let r=mkViewBuilder(s);for(let t of e)t(r);return t},add},dynamicView:(e,t,r)=>{let[i,a]=createGenericView(e,t,r),s={...i,[Hi]:`dynamic`,rules:[],steps:[]},add=e=>(e.__addView(s),a&&a(mkViewBuilder(s)),e);return add.with=(...e)=>t=>{add(t);let r=mkViewBuilder(s);for(let t of e)t(r);return t},add},$autoLayout,$exclude,$include,$rules,$style,$step,$includeAncestors},deployment:{deployment:(...e)=>t=>e.reduce((e,t)=>t(e),t),instanceOf:(e,t,r)=>i=>{C(t)?(t=e,e=nameFromFqn(e)):typeof t==`string`?r??={}:(r=t,t=e,e=nameFromFqn(e));let{links:a,title:s,description:c,summary:l,icon:u,color:p,shape:m,style:h,...g}=typeof r==`string`?{title:r}:{...r},_=i.__deploymentFqn(e);return i.__addDeployment(exact({id:_,element:t,...s&&{title:s},...l&&{summary:toMarkdownOrString(l)},...c&&{description:toMarkdownOrString(c)},style:exact({icon:u,color:p,shape:m,...h}),links:mapLinks(a),...g})),i},rel:(e,t,r)=>i=>{let{title:a=null,links:s,description:c=null,notes:l=null,...u}=typeof r==`string`?{title:r}:{...r};return i.__addDeploymentRelation(exact({source:{deployment:e},target:{deployment:t},title:a,...c&&{description:toMarkdownOrString(c)},...l&&{notes:toMarkdownOrString(l)},links:mapLinks(s),...u})),i},...ae(h.deployments??{},({style:e,...t},r)=>(i,a)=>{let add=(s=>{let{links:c,icon:l,style:u,title:p,description:m,summary:h,color:g,shape:_,...v}=typeof a==`string`?{title:a}:{...a},y=l??e?.icon,b=mapLinks(c),x=s.__deploymentFqn(i);return s.__addDeployment(exact({id:x,kind:r,...t,title:p??t.title??nameFromFqn(x),...m&&{description:toMarkdownOrString(m)},...h&&{summary:toMarkdownOrString(h)},style:exact({icon:y,color:g??e?.color,shape:_??e?.shape,border:e?.border,opacity:e?.opacity,size:e?.size,padding:e?.padding,textSize:e?.textSize,sizing:e?.sizing,...u}),...b&&{links:b},...v})),s});return add.with=(...e)=>t=>{add(t);let{__deploymentFqn:r}=t;try{t.__deploymentFqn=e=>`${r(i)}.${e}`,e.reduce((e,t)=>t(e),t)}finally{t.__deploymentFqn=r}return t},add})}}),with:(...e)=>{let t=g.clone();return e.reduce((e,t)=>t(e),t)},model:e=>{let t=g.clone(),r=t.helpers().model,i=r.model;return e({...r,_:i},i)(t)},deployment:e=>{let t=g.clone(),r=t.helpers().deployment,i=r.deployment;return e({...r,_:i},i)(t)},views:e=>{let t=g.clone(),r=t.helpers().views;return e({...r,_:r.views},r.views)(t)}};return g}function fromParsedImpl(e,t=`editable`){let{specification:r}=e,i={elements:r.elements,deployments:r.deployments,relationships:r.relationships,tags:r.tags,metadataKeys:r.metadataKeys},a=new Map(Object.entries(structuredClone(e.elements))),s=Object.values(structuredClone(e.relations)),c=new Map(Object.entries(structuredClone(e.views))),l=structuredClone(e.globals),u=new Map(Object.entries(structuredClone(e.deployments.elements))),p=Object.values(structuredClone(e.deployments.relations)),m=new I.default(()=>/* @__PURE__ */ new Map);for(let[t,r]of Object.entries(e.imports??{})){let e=structuredClone(r);m.set(t,new Map(e.map(e=>[e.id,e])))}return builder(i,a,s,c,l,u,p,m,t)}const Gh={forSpecification(e){let t=builder(e);return{...t.helpers(),builder:t}},specification(e){return builder(e)},fromParsed:fromParsedImpl},isErrorDiagnostic=e=>e.severity===1;var LikeC4=class{langium;logger;constructor(e,t=ga){this.langium=e,this.logger=t}get workspace(){return this.langium.shared.workspace.WorkspaceManager.workspaceUri.fsPath}get workspaceURI(){return this.langium.shared.workspace.WorkspaceManager.workspaceUri}get workspaceURL(){return this.langium.shared.workspace.WorkspaceManager.workspaceURL}get languageServices(){return this.langium.likec4.likec4.LanguageServices}get projectsManager(){return this.langium.shared.workspace.ProjectsManager}get viewsService(){return this.langium.likec4.likec4.Views}get modelBuilder(){return this.langium.likec4.likec4.ModelBuilder}get LangiumDocuments(){return this.langium.shared.workspace.LangiumDocuments}ensureSingleProject(){let e=this.languageServices.projects();if(e.length>1)throw this.logger.error(`Multiple projects found:
|
|
141
|
+
${e.map(e=>` - ${e.folder.fsPath}`).join(`
|
|
142
|
+
`)}
|
|
143
|
+
|
|
144
|
+
Please specify a project folder`),Error(`Multiple projects found`)}async diagrams(e){let t=this.projectsManager.ensureProjectId(e);return await this.viewsService.diagrams(t)}syncComputedModel(e){let t=this.projectsManager.ensureProjectId(e);return this.modelBuilder.unsafeSyncComputeModel(t)}async computedModel(e){let t=this.projectsManager.ensureProjectId(e);return await this.modelBuilder.computeModel(t)}async parsedModel(e){let t=this.projectsManager.ensureProjectId(e),r=await this.modelBuilder.parseModel(t);if(!r)throw Error(`Failed to parse model for project "${t}"`);return r}async toBuilder(e=`editable`,t){let r=await this.parsedModel(t);return Gh.fromParsed(r.$data,e)}async toTypedBuilder(e){let{specification:t,mode:r=`editable`,project:i}=e,a=await this.parsedModel(i);return assertSpecificationCompatible(t,a.$data.specification),Gh.fromParsed(a.$data,r)}async toDSL(e){return generateLikeC4((await this.parsedModel(e)).$data)}projects(){return p(this.languageServices.projects(),A(`id`))}async layoutedModel(e){let t=this.projectsManager.ensureProjectId(e);return await this.languageServices.layoutedModel(t)}getErrors(){return[...this.LangiumDocuments.userDocuments].flatMap(e=>(e.diagnostics?.filter(isErrorDiagnostic)??[]).map(({message:t,range:r})=>({message:typeof t==`string`?t:t.value,line:r.start.line,range:r,sourceFsPath:e.uri.fsPath})))}hasErrors(){return this.LangiumDocuments.userDocuments.some(e=>e.diagnostics&&e.diagnostics.some(isErrorDiagnostic))}printErrors(){let e=!1;for(let t of this.LangiumDocuments.userDocuments){let r=t.diagnostics?.filter(isErrorDiagnostic)??[];if(!k(r,1))continue;e=!0;let i=N(r,P(e=>{let t=e.range.start.line,r=(typeof e.message==`string`?e.message:e.message.value).split(`
|
|
145
|
+
`);return r.length>5&&(r.length=5,r.push(`...`)),r.map((e,r)=>r===0?` `+ii.dim(`Line ${t}: `)+ii.red(e):` `.repeat(10)+ii.red(e))}),c(`
|
|
146
|
+
`));this.logger.error(`Invalid ${t.uri.fsPath}\n${i}`)}return e}documentCount(){return[...this.LangiumDocuments.userDocuments].length}documentPaths(){return[...this.LangiumDocuments.userDocuments].map(e=>e.uri.fsPath)}onModelUpdate(e){let t=this.modelBuilder.onModelParsed(t=>e(t));return()=>{t.dispose()}}async format(e){let{projects:t,...r}=e??{},i={...r,...t&&{projectIds:t.map(e=>this.projectsManager.ensureProjectId(e))}};return await this.languageServices.format(i)}async dispose(){await this.languageServices.dispose()}async[Symbol.asyncDispose](){await this.dispose()}};const Kh={printErrors:!0,throwIfInvalid:!1,graphviz:`wasm`,configureLogger:!1,logLevel:void 0},validationErrorsToError=e=>/* @__PURE__ */ Error(`Invalid model:\n${e.getErrors().map(e=>` ${e.sourceFsPath}:${e.line} ${e.message.slice(0,200)}`).join(`
|
|
147
|
+
`)}`);async function handleInitOptions(e,t=ga,r){let i=new LikeC4(e,t),a=r?.throwIfInvalid??Kh.throwIfInvalid,s=r?.printErrors??Kh.printErrors;if((a||s)&&i.hasErrors()){if(a)return await i.dispose(),Promise.reject(validationErrorsToError(i));i.printErrors()}return i}async function createFromSources(e,t,r,i){let a=R.from({scheme:`virtual`,path:`/workspace`}),s={name:`virtual`,uri:a.toString()},c=e.shared.workspace.WorkspaceManager;c.initialize({capabilities:{},processId:null,rootUri:s.uri,workspaceFolders:[s]}),await c.initializeWorkspace([s]);let l=e.shared.ServiceRegistry.all.flatMap(e=>e.LanguageMetaData.fileExtensions),[u,m]=pe(M(r),([e])=>isLikeC4JsonConfig(e));for(let[r,i]of u){let s=L.joinPath(a,r);try{await e.shared.workspace.ProjectsManager.registerProject({configUri:s,config:No.parse(i)})}catch(e){t.error(loggable(e))}}let h=N(m,p(([t,r])=>{l.includes(sr(t))||(t+=`.c4`);let i=L.joinPath(a,t);return e.shared.workspace.LangiumDocuments.createDocument(i,r)}));return await e.shared.workspace.DocumentBuilder.build(h,{validation:!0}),handleInitOptions(e,t,i)}function configureLogger(e){let t=e?.configureLogger??!1;t!==!1&&configureLanguageServerLogger(t===`stderr`?{useStdErr:!0,colors:!1,logLevel:e?.logLevel}:{colors:Gr,logLevel:e?.logLevel})}function createLanguageServices(e){let t=ga.getChild(`lang`),r=Yi(e,{useFileSystem:!0,manualLayouts:!0,watch:!1,graphviz:`wasm`}),i=r.graphviz===`binary`;return t.info(`${ii.dim(`layout`)} ${i?`binary`:`wasm`}`),createLanguageServices$1({...r.useFileSystem?{...WithFileSystem(r.watch),...r.manualLayouts?ku:Iu}:{...Fu,...Iu},...WithGraphviz(i?new GraphvizBinaryAdapter:new Oa)})}async function fromWorkspace(e,t){let r=mr(e),i=R.file(r).toString(),a=rr(i),s=ga.getChild(`lang`),c=Yi(t,{...Kh,useFileSystem:!0,manualLayouts:!0,watch:!1});configureLogger(c);let l=createLanguageServices(c),u={name:dr(r),uri:a},p=l.shared.workspace.WorkspaceManager;s.info(`${ii.dim(`workspace:`)} ${r}`),p.initialize({capabilities:{},processId:null,rootUri:u.uri,workspaceFolders:[u]}),await p.initialized({});let m=l.shared.workspace.LangiumDocuments.userDocuments.toArray();if(m.length===0&&(s.error(`no LikeC4 sources found`),t?.throwIfInvalid))throw await l.likec4.likec4.LanguageServices.dispose(),Error(`no LikeC4 sources found`);return s.info(`${ii.dim(`workspace:`)} found ${m.length} source files`),handleInitOptions(l,ga,t)}async function fromSources(e,t){configureLogger(t);let r=ga.getChild(`lang`);return await createFromSources(createLanguageServices(Yi(t,{...Kh,useFileSystem:!1,watch:!1,manualLayouts:!1})),r,e,t)}function createContext(e={}){let t,r=!1,checkConflict=e=>{if(t&&t!==e)throw Error(`Context conflict`)},i;if(e.asyncContext){let t=e.AsyncLocalStorage||globalThis.AsyncLocalStorage;t?i=new t:console.warn("[unctx] `AsyncLocalStorage` is not provided.")}let _getCurrentInstance=()=>{if(i){let e=i.getStore();if(e!==void 0)return e}return t};return{use:()=>{let e=_getCurrentInstance();if(e===void 0)throw Error(`Context is not available`);return e},tryUse:()=>_getCurrentInstance(),set:(e,i)=>{i||checkConflict(e),t=e,r=!0},unset:()=>{t=void 0,r=!1},call:(e,a)=>{checkConflict(e),t=e;try{return i?i.run(e,a):a()}finally{r||(t=void 0)}},async callAsync(e,a){t=e;let onRestore=()=>{t=e},onLeave=()=>t===e?onRestore:void 0;Xh.add(onLeave);try{let s=i?i.run(e,a):a();return r||(t=void 0),await s}finally{Xh.delete(onLeave)}}}}function createNamespace(e={}){let t={};return{get(r,i={}){return t[r]||(t[r]=createContext({...e,...i})),t[r]}}}const qh=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof global<`u`?global:typeof window<`u`?window:{},Jh=`__unctx__`;qh[Jh]||(qh[Jh]=createNamespace());const Yh=`__unctx_async_handlers__`,Xh=qh[Yh]||(qh[Yh]=/* @__PURE__ */ new Set),Zh=createContext(),Qh=createContext();function useLanguageServices(){return Qh.use()}function setMcpServerCtx(e){return e?Zh.set(e,!0):Zh.unset(),e}function setLanguageServicesCtx(e){return e?Qh.set(e,!0):Qh.unset(),e}const $=ga.getChild(`mcp`);function mcpToolSchema(e){return qr.object(e).meta({$schema:`https://json-schema.org/draft/2020-12/schema`})}function likec4Tool(e){return t=>r=>{let{name:i,description:a,inputSchema:s,outputSchema:c,...l}=e,u=c!==void 0&&!_(c),p={description:a?.trim()??``,...l,...s===void 0?{}:{inputSchema:mcpToolSchema(s)},...c===void 0?{}:{outputSchema:mcpToolSchema(c)}};return r.registerTool(i,p,async(...e)=>{let r=useLanguageServices();$.debug(`Calling tool {name}, args: {args}`,{name:i,args:e});try{let i=await t.apply(null,[r,...e]);return typeof i==`string`?{content:[{type:`text`,text:i}]}:u?{content:[],structuredContent:i}:hasProp(i,`content`)?i:{content:[{type:`text`,text:JSON.stringify(i)}]}}catch(e){return $.error(`Tool ${i} failed`,{err:e}),{content:[{type:`text`,text:loggable(e)}],isError:!0}}}),r}}var $h=`1.60.0`;function applySemanticLayoutPrompt(e){let t=useLanguageServices();return e.registerPrompt(`apply_semantic_layout`,{title:`Prepare prompt for applying semantic layout to a likec4 view`,argsSchema:{projectId:ci(li.string().describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(A(`id`))),viewId:ci(li.string().describe(`View ID`),async(r=``,i)=>{let a=i?.arguments?.projectId??t.projectsManager.default.id,s=await t.computedModel(a);return s?Array.from(s.views()).filter(e=>e.id.startsWith(r)).map(A(`id`)):(await e.sendLoggingMessage({level:`warning`,data:`Completing viewId for project ${a} with input value "${r}", model not found`}),[])})}},async({viewId:e,projectId:t},r)=>({messages:[{role:`user`,content:{type:`text`,text:["Call `apply-semantic-layout` tool from `likec4` MCP with these arguments:","projectId: `"+t+"`","viewId: `"+e+"`"].join(`
|
|
148
|
+
`)}}]})),e}function projectResource(e){let t=useLanguageServices();return e.registerResource(`likec4-project`,new si(`likec4://project/{projectId}`,{list:async()=>({resources:t.projects().map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,name:e.title}))}),complete:{projectId:e=>{if(!e)return t.projects().map(A(`id`));let r=e.toLowerCase();return t.projects().filter(e=>e.id.toLowerCase().includes(r)).map(A(`id`))}}}),{description:`LikeC4 project resource`,mimeType:`application/json`},async(e,{projectId:r})=>{if(!r)return{contents:[]};let i=typeof r==`string`?[r]:r;return{contents:t.projects().filter(e=>i.includes(e.id)).map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,text:JSON.stringify({id:e.id,title:e.title,folder:e.folder.fsPath})}))}}),e}function readDistAsset(e){let t=[new URL(`../dist/${e}`,import.meta.url),new URL(`../../dist/${e}`,import.meta.url)];for(let e of t){let t=_r(e);if(Sr(t))return wr(t,`utf-8`)}throw Error(`Could not locate dist asset '${e}'; tried: ${t.map(String).join(`, `)}`)}function readRenderViewClientBundle(){return readDistAsset(`app/render-view-client.js`)}function readRenderViewClientStyles(){return readDistAsset(`app/render-view-client.css`)}const eg=z.object({name:z.string().describe(`Project identifier`),title:z.string().optional().describe(`Human-readable project title`),contactPerson:z.string().optional().describe(`Maintainer contact information`),metadata:z.record(z.string(),z.unknown()).optional().describe(`Custom project metadata as key-value pairs`),extends:z.union([z.string(),z.array(z.string())]).optional().describe(`Style inheritance paths`),exclude:z.array(z.string()).optional().describe(`File exclusion patterns`),include:z.object({paths:z.array(z.string()).describe(`Include paths`),maxDepth:z.number().describe(`Maximum directory depth`),fileThreshold:z.number().describe(`File threshold`)}).optional().describe(`Include configuration`),manualLayouts:z.object({outDir:z.string().describe(`Output directory for manual layouts`)}).optional().describe(`Manual layouts configuration`),styles:z.object({hasTheme:z.boolean().describe(`Whether theme customization is defined`),hasDefaults:z.boolean().describe(`Whether default style values are defined`),hasCustomCss:z.boolean().describe(`Whether custom CSS is defined`)}).optional().describe(`Simplified styles configuration (boolean flags)`)});function serializeConfig(e){let t={name:e.name};return e.title!=null&&(t.title=e.title),e.contactPerson!=null&&(t.contactPerson=e.contactPerson),e.metadata&&(t.metadata=e.metadata),e.extends&&(t.extends=e.extends),e.exclude&&(t.exclude=e.exclude),e.include&&(t.include={paths:e.include.paths||[],maxDepth:e.include.maxDepth??3,fileThreshold:e.include.fileThreshold??30}),e.manualLayouts&&(t.manualLayouts={outDir:e.manualLayouts.outDir??`.likec4`}),e.styles&&(t.styles={hasTheme:!!e.styles.theme,hasDefaults:!!e.styles.defaults,hasCustomCss:!!e.styles.customCss}),t}const tg=z.object({id:z.string().describe(`Element id (FQN)`),name:z.string().describe(`Element name`),kind:z.string().describe(`Element kind`),title:z.string(),tags:z.array(z.string()),metadata:z.record(z.string(),z.union([z.string(),z.array(z.string())])),includedInViews:z.array(z.object({id:z.string().describe(`View id`),title:z.string().describe(`View title`),type:z.enum([`element`,`deployment`,`dynamic`]).describe(`View type`)})).describe(`Views that include this element`)});function serializeElement(e){return{id:e.id,name:e.name,kind:e.kind,title:e.title,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())}}function traverseGraph(e,t,r,i,a,s){invariant(e.findElement(t),`Element "${t}" not found`);let c=/* @__PURE__ */ new Set,l={},u=0,p=!1,m=[{elementId:t,depth:0}];for(;m.length>0;){let{elementId:t,depth:h}=m.shift();if(h>a||c.has(t))continue;if(c.size>=s){p=!0;break}let g=e.findElement(t);if(!g)continue;c.add(t),u=Math.max(u,h);let _=(r===`incoming`?[...g.incoming(i)]:[...g.outgoing(i)]).map(e=>{let t={elementId:r===`incoming`?e.source.id:e.target.id};return e.title&&(t.relationshipLabel=e.title),e.technology&&(t.technology=e.technology),t});l[t]={...serializeElement(g),neighbors:_,depth:h};for(let e of _)c.has(e.elementId)||m.push({elementId:e.elementId,depth:h+1})}for(let e of Object.values(l))e.neighbors=e.neighbors.filter(e=>e.elementId in l);return{target:t,totalNodes:c.size,maxDepth:u,truncated:p,nodes:l}}const ng=z.object({path:z.string().describe(`Path to the file`),range:z.object({start:z.object({line:z.number(),character:z.number()}),end:z.object({line:z.number(),character:z.number()})}).describe(`Range in the file`)}).nullable(),rg=z.array(z.object({title:z.string().nullable().describe(`Optional link title`),url:z.string().describe(`Link URL`),relative:z.string().nullable().describe(`Relative path (if URL is relative to workspace root)`)})).describe(`External links associated with this element`);function serializeLinks(e){return(e.links??[]).map(e=>({title:e.title??null,url:e.url,relative:e.relative??null}))}const ig=z.string().refine(e=>!0).default(`default`).describe(`Project id (optional, will use "default" if not specified)`),ag=z.array(z.object({id:z.string().describe(`View id`),title:z.string().describe(`View title`),type:z.enum([`element`,`deployment`,`dynamic`]).describe(`View type`)})),includedInViews=e=>[...e].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type})),mkLocate=(e,t)=>r=>{try{let i=e.locate({projectId:t,...r});return i?{path:kr.parse(i.uri).fsPath,range:i.range}:null}catch(e){return $.debug(`Failed to locate {params}`,{error:e,params:r}),null}};function toolError(e){return{isError:!0,content:[{type:`text`,text:e}]}}function pickRecord(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}function buildViewScopedModel(e,t){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,includeElement=t=>{let i=e.element(t);r.add(i.id);for(let e of i.ancestors())r.add(e.id)},includeDeployment=t=>{let r=e.deployment.element(t);i.add(r.id);for(let e of r.ancestors())i.add(e.id);r.isInstance()&&includeElement(r.element.id)},includeDeploymentRef=e=>{includeDeployment(e.deployment),H.isInsideInstanceRef(e)&&includeElement(e.element)};t._type===`element`&&t.viewOf&&includeElement(t.viewOf);for(let e of t.nodes)e.modelRef&&includeElement(e.modelRef),e.deploymentRef&&includeDeployment(e.deploymentRef);for(let r of t.edges)for(let t of r.relations){let r=e.relationship(t);r.isModelRelation()?(a.add(r.id),includeElement(r.source.id),includeElement(r.target.id)):(s.add(r.id),includeDeploymentRef(r.$relationship.source),includeDeploymentRef(r.$relationship.target))}let c=e.$data,l=Object.fromEntries(Object.entries(c.imports).flatMap(([e,t])=>{let i=t.filter(t=>r.has(GlobalFqn(e,t.id)));return i.length>0?[[e,i]]:[]}));return{...c,elements:pickRecord(c.elements,r),imports:l,relations:pickRecord(c.relations,a),deployments:{elements:pickRecord(c.deployments.elements,i),relations:pickRecord(c.deployments.relations,s)},views:{[t.id]:t},manualLayouts:{}}}function inlineLocalSvgIcon(e){if(typeof e!=`string`||!e.startsWith(`file:`)||!e.toLowerCase().split(/[?#]/)[0]?.endsWith(`.svg`))return e;try{return`data:image/svg+xml,${encodeURIComponent(wr(kr.parse(e).fsPath,`utf8`))}`}catch{return null}}function inlineLocalSvgIcons(e){return Array.isArray(e)?e.map(inlineLocalSvgIcons):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,e===`icon`?inlineLocalSvgIcon(t):inlineLocalSvgIcons(t)])):e}function buildRenderPayload(e){let t=e.fullModel?{...e.model.$data,views:{...e.model.$data.views,[e.viewId]:e.layoutedView}}:buildViewScopedModel(e.model,e.layoutedView);return{id:e.viewId,title:e.title,project:e.projectId,view:inlineLocalSvgIcons(e.layoutedView),model:inlineLocalSvgIcons(t)}}const og=`ui://likec4/render-view.html`,sg=z.object({size:z.enum([`compact`,`standard`,`large`]).default(`standard`).describe(`Initial canvas size hint`),fitView:z.boolean().default(!0).describe(`Fit the diagram into the canvas initially`),initialZoom:z.number().min(.05).max(3).optional().describe(`Initial zoom level; overrides fitView`)}).default({size:`standard`,fitView:!0});function renderViewTool(e){return fi(e,`render-view`,{title:`Render View`,description:`Renders a LikeC4 view as an interactive diagram (pan/zoom/fit) inline in the chat. Use it when the user wants to *see* a view; use "read-view" when only the view's structure (nodes/edges) is needed.`,inputSchema:mcpToolSchema({viewId:z.string().describe(`View id (name)`),project:ig,fullModel:z.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`),render:sg}),outputSchema:mcpToolSchema({id:z.string(),title:z.string(),project:z.string(),view:z.record(z.string(),z.unknown()).describe(`Layouted view (nodes, edges, bounds), consumed by the paired render-view UI`),model:z.record(z.string(),z.unknown()).describe(`Layouted model data (specification, elements, relations, deployments), scoped to this view by default; complete when fullModel is true. Consumed by the paired UI to build a LikeC4Model for LikeC4ModelProvider — LikeC4Diagram requires one in context.`),render:sg}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Render view`},_meta:{ui:{resourceUri:og}}},async e=>{let t=useLanguageServices(),r=t.projectsManager.ensureProjectId(e.project),i=await t.layoutedModel(r),a=i.findView(e.viewId);if(!a)return toolError(`View with ID '${e.viewId}' not found in project ${r}`);if(!a.isLayouted())return toolError(`View '${e.viewId}' has no layout`);let s=a.$layouted,c=a.title??a.id;return{content:[{type:`text`,text:`Rendered view "${c}"`}],structuredContent:{...buildRenderPayload({projectId:r,viewId:a.id,title:c,layoutedView:s,model:i,fullModel:e.fullModel}),render:e.render}}}),e}function renderHtml(e,t){return`<!doctype html>
|
|
9
149
|
<html>
|
|
10
150
|
<head>
|
|
11
151
|
<meta charset="utf-8" />
|
|
@@ -19,1120 +159,198 @@ Use this when the user wants to *see* a view. Use "read-view" instead when only
|
|
|
19
159
|
<div id="root"></div>
|
|
20
160
|
<script>${e}<\/script>
|
|
21
161
|
</body>
|
|
22
|
-
</html>`}function renderViewResource(e){return
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
-
|
|
52
|
-
-
|
|
53
|
-
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
-
|
|
57
|
-
-
|
|
58
|
-
-
|
|
59
|
-
-
|
|
60
|
-
-
|
|
61
|
-
|
|
62
|
-
|
|
162
|
+
</html>`}function renderViewResource(e){return di(e,`Render View UI`,og,{description:`Interactive diagram UI for the render-view MCP App tool.`},async()=>({contents:[{uri:og,mimeType:ui,text:renderHtml(readRenderViewClientBundle(),readRenderViewClientStyles())}]})),e}const cg=/* @__PURE__ */ createLogger(`ai-layout`);function truncate(e,t=100){return e=e.replaceAll(/\n/g,` `).trim(),e.length<=t?e:e.slice(0,t-1)+`…`}function mappedEntries(e){let t={};for(let[r,i]of e.entries())t[i]=r;return t}function edgeLabel(e){let t=e.label&&e.label!==`[...]`?e.label:void 0,r=flattenMarkdownOrString(e.description);return r&&(t=t?`${t}\n${r}`:r),t??=e.technology??void 0,t?truncate(t):void 0}function prepareLLMInput(e){let t=1,r=1,i=new I.default(e=>e.children.length===0?`n${r++}`:`c${t++}`),findNodeById=t=>e.nodes.find(e=>e.id===t),nodeId=e=>i.get(findNodeById(e)),a=/* @__PURE__ */ new Set;e.nodes.forEach(e=>{i.get(e),e.children.length===0&&a.add(e.id)});let s=e.edges.find(e=>!a.has(e.source)||!a.has(e.target));if(s)throw cg.error(`Non-leaf edge found in view`,{view:e.id,edge:{source:s.source,target:s.target}}),Error(`Non-leaf edge found in view, this is not supported by the current implementation`);let c=1,l=new I.default(e=>`e${c++}`),u=e.edges.map(e=>{let t=nodeId(e.source),r=nodeId(e.target),i=e.parent?nodeId(e.parent):null;e.dir===`back`&&([t,r]=[r,t]);let a=edgeLabel(e);return{id:l.get(e),...a&&{label:a},...i&&{parent:i},source:t,target:r}}),reduceNodes=(e,t)=>{let{level:r,kind:a,...s}=t,c=i.get(t),l=s.children.length>0,u=s.parent?nodeId(s.parent):void 0,p=truncate(s.title);if(l)return e.compounds.push(exact({id:c,title:p,parent:u,children:s.children.map(nodeId),level:r})),e;let m=s.description?truncate(flattenMarkdownOrString(s.description),200):void 0;return e.nodes.push(exact({id:c,kind:a,title:p,description:m,parent:u,level:r})),e};return{serialized:e.nodes.reduce(reduceNodes,{direction:e.autoLayout.direction,compounds:[],nodes:[],edges:u}),mapping:{nodes:mappedEntries(i),edges:mappedEntries(l)}}}const lg=z.enum([`TB`,`BT`,`LR`,`RL`]),ug=z.string().nonempty().brand(),dg=z.enum([`same`,`source`,`sink`,`min`,`max`]),fg=z.object({rank:dg,nodes:z.array(ug)}),pg={id:z.string().nonempty().brand(),weight:z.coerce.number().int().min(0).max(20),minlen:z.coerce.number().int().min(0).max(4)},mg=z.object({source:ug,target:ug,weight:pg.weight.optional(),minlen:pg.minlen.optional()}),hg=z.object({direction:lg.optional(),ranks:z.array(fg).default([]),edgeWeight:z.record(pg.id,pg.weight).default({}),edgeMinlen:z.record(pg.id,pg.minlen).default({}),reverseRank:z.array(pg.id).default([]),excludeFromRanking:z.array(pg.id).default([]),edgeOrder:z.array(pg.id).default([]),nodeOrder:z.array(ug).default([]),invisibleEdges:z.array(mg).default([]),reasoning:z.string().default(``)}),gg=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/;function extractJson(e){let t=gg.exec(e);if(t&&t[1])return t[1];let r=e.indexOf(`{`),i=e.lastIndexOf(`}`);return r!==-1&&i!==-1&&i>r?e.slice(r,i+1):e.trim()}function parseOutput(e,t){try{let r=extractJson(e),i=Ua.default.parse(r),a=hg.safeParse(i);if(!a.success){cg.warn(`Failed to validate LLM response
|
|
163
|
+
`+z.prettifyError(a.error));return}return restoreIdsAndMapToHints(a.data,t)}catch(t){cg.warn(`Failed to parse LLM response
|
|
164
|
+
{response}`,{error:t,response:e});return}}function restoreIdsAndMapToHints(e,t){let{mapping:r}=t,nodeId=e=>{let t=r.nodes[e]?.id;return t||cg.warn`Unknown node ID ${e} in LLM output, skipping`,t},mapToNodeId=e=>N(e,p(nodeId),D(T)),edgeId=e=>{let t=r.edges[e]?.id;return t||cg.warn`Unknown edge ID ${e} in LLM output, skipping`,t},mapToNonEmpty=(e,t)=>{let r=e.map(t).filter(T);return k(r,1)?r:void 0},i=N(e.excludeFromRanking,p(edgeId),D(T),E(),e=>k(e,1)?e:void 0),a=N(e.reverseRank,p(edgeId),D(T),E(),e=>k(e,1)?e:void 0),s=(()=>{let e=/* @__PURE__ */ new Set;return t=>t.filter(t=>!e.has(t)&&(e.add(t),!0))})(),c=N(e.ranks,p(e=>{let t=s(mapToNodeId(e.nodes));return k(t,1)?{rank:e.rank,nodes:t}:null}),D(j)),l=N(e.invisibleEdges,p(({source:e,target:t,minlen:r=1,weight:i=1})=>{let a=nodeId(e),s=nodeId(t);if(a&&s)return exact({weight:i===1?void 0:i,minlen:r===1?void 0:r,source:a,target:s})}),D(T),le(e=>`${e.source}->${e.target}`),ae(([e,...t])=>N(t,ve((e,t)=>exact({...e,...t,weight:e.weight&&t.weight?Math.max(e.weight,t.weight):e.weight||t.weight,minlen:e.minlen&&t.minlen?Math.max(e.minlen,t.minlen):e.minlen||t.minlen}),e))),Fe(),e=>k(e,1)?e:void 0),u=e.reasoning;u&&(u=u.replaceAll(`][`,`] [`),M(t.mapping.nodes).forEach(([e,t])=>{u=u.replaceAll(RegExp(`\\[${e}\\]`,`g`),"`"+t.id+"`")}),M(t.mapping.edges).forEach(([e,t])=>{u=u.replaceAll(RegExp(`\\[${e}\\]`,`g`),"`"+t.source+` -> `+t.target+"`")}));let safeMapEdgeKeys=e=>{let t={};for(let[r,i]of M(e)){let e=edgeId(r);e&&(t[e]=i)}return t};return exact({direction:e.direction,ranks:c,edgeWeight:safeMapEdgeKeys(e.edgeWeight),edgeMinlen:safeMapEdgeKeys(e.edgeMinlen),excludeFromRanking:i,reverseRank:a,edgeOrder:mapToNonEmpty(e.edgeOrder,edgeId),nodeOrder:mapToNonEmpty(e.nodeOrder,nodeId),invisibleEdges:l,reasoning:u})}const _g={systemPrompt:`You are an advisor specializing in software architecture diagrams and graphviz (DOT) layout optimizations.
|
|
165
|
+
You receive a JSON of Diagram data with:
|
|
166
|
+
- nodes (architectural elements, rendered as leaf boxes)
|
|
167
|
+
- compounds (group of nodes or other compounds, define hierarchy and rendered as boxes around children)
|
|
168
|
+
- edges (directed relationships between nodes, define flow from source to target)
|
|
169
|
+
- direction (preferred layout direction for the diagram, e.g. TB = top to bottom, LR = left to right)
|
|
170
|
+
|
|
171
|
+
Your task: Suggest layout hints to produce readable and visually balanced diagram.
|
|
172
|
+
|
|
173
|
+
<input>
|
|
174
|
+
Diagram (JSON object) fields:
|
|
175
|
+
- compounds: Compound[]
|
|
176
|
+
- nodes: Node[]
|
|
177
|
+
- edges: Edge[]
|
|
178
|
+
- direction: "TB" | "LR" | "BT" | "RL" | "Top
|
|
179
|
+
|
|
180
|
+
Node (JSON object) fields:
|
|
181
|
+
- id: string (starts with "n" followed by a number, e.g. "n1", "n2", etc.)
|
|
182
|
+
- kind: string (semantic type, e.g. "system", "container", "component", "service", "database", etc.)
|
|
183
|
+
- title: string
|
|
184
|
+
- description?: string | undefined - optional description
|
|
185
|
+
- parent?: string (compound ID) | undefined - optional Parent ID, if node is nested inside a compound;
|
|
186
|
+
- level: number - zero-based level in the hierarchy (root level = 0)
|
|
187
|
+
|
|
188
|
+
Compound (JSON object) fields:
|
|
189
|
+
- id: string (starts with "c" followed by a number, e.g. "c1", "c2", etc.)
|
|
190
|
+
- title: string
|
|
191
|
+
- parent?: string (compound ID) | undefined - optional Parent ID, if compound is nested inside another compound;
|
|
192
|
+
- level: number - zero-based level in the hierarchy (root level = 0)
|
|
193
|
+
- children: string[] - IDs of children (compounds or nodes)
|
|
194
|
+
|
|
195
|
+
Edge (JSON object) fields:
|
|
196
|
+
- id: string (starts with "e" followed by a number, e.g. "e1", "e2", etc.)
|
|
197
|
+
- source: string (node ID)
|
|
198
|
+
- target: string (node ID)
|
|
199
|
+
- parent?: string (compound ID) | undefined - optional Parent ID, if edge is inside a compound
|
|
200
|
+
- label?: string | undefined
|
|
201
|
+
</input>
|
|
202
|
+
|
|
203
|
+
<rules>
|
|
204
|
+
|
|
205
|
+
1. Diagram is a hierarchical directed graph, may contain cycles
|
|
206
|
+
2. Compound size and position are determined by its children; Node position is determined by its rank and hierarchy
|
|
207
|
+
3. In vertical direction (TB, BT) rank is a row, in horizontal (LR, RL) rank is a column; rank increases following the direction (i.e from top to bottom for TB)
|
|
208
|
+
4. Edge exists ONLY between nodes
|
|
209
|
+
5. Edge increases rank following its direction, i.e making rank of target higher than rank of source; \`minlen\` controls how many ranks apart they should be
|
|
210
|
+
- by default, all edges have \`minlen=1\`
|
|
211
|
+
- \`minlen=2\` adds extra rank between nodes, pushing target node further away from source (adds more space)
|
|
212
|
+
- \`minlen=0\` does not increase rank, but defines relative order within rank (i.e if rank is a row, source node is on the left, or if rank is a column, source node is on the top)
|
|
213
|
+
- keep \`minlen\` in range 0..4
|
|
214
|
+
6. You can change edge rank direction by adding its ID to the \`reverseRank\` array; this enforces the opposite - rank of source node should be higher than rank of target; It does not change the semantics, and gives more control over ranks. Especially useful to break cycles or swap rank order of source and target
|
|
215
|
+
7. You can exclude edge from calculations by adding its ID to the \`excludeFromRanking\` array; Edge still visible but does not contribute to node ranks (\`constraint=false\` in graphviz)
|
|
216
|
+
8. Edge acts like a "spring" that pulls nodes together; its force controlled by \`weight\`; higher weight means shorter and straighter line;
|
|
217
|
+
- by default, all edges have \`weight=1\`
|
|
218
|
+
- \`weight\` is relative to \`weight\` of other edges
|
|
219
|
+
- same \`weight\` value balances edges equally; only difference in \`weight\` values affects layout
|
|
220
|
+
- keep \`weight\` in range 1..10, to emphasize edge use range 6..10
|
|
221
|
+
9. You can add invisible edges to fine-tune node ranks (and/or order within same rank):
|
|
222
|
+
- invisible edge has same effects as regular edge (changes rank and order), but not visible and does not change semantics
|
|
223
|
+
- to add invisible edge, push an object with \`source\` and \`target\` node IDs to the \`invisibleEdges\` array (\`minlen\` and \`weight\` are optional, but if provided, follow the same rules)
|
|
224
|
+
- you can add edge if only there is no same edge exists, i.e if \`A->B\` exists, you can add \`B->A\`, but not \`A->B\` again
|
|
225
|
+
- invisible edges especially useful to pull semantically related nodes closer, force position of orphan nodes (having only incoming, outgoing, or none edges), move nodes to separate ranks or order nodes strictly in same rank
|
|
226
|
+
10. You can constrain node ranks by using the \`ranks\` array:
|
|
227
|
+
- \`rank="source"\` constrain node(s) at the minimum rank (top/left)
|
|
228
|
+
- \`rank="sink"\` constrain node(s) at the maximum rank (bottom/right)
|
|
229
|
+
- \`rank="same"\` constrain two or more nodes to be on the same rank
|
|
230
|
+
- Node cannot have multiple rank constraints, if you encounter this, pick the most important (prefer \`rank="same"\` when in doubt)
|
|
231
|
+
- Node rank constraint takes precedence over edge-based rank calculations
|
|
232
|
+
11. Vertical layout directions (TB,BT) are good for general flows (like interactions, processes, etc.), horizontal layout (LR,RL) for pipelines, request processing; Keep input layout direction, unless it contradicts the semantics
|
|
233
|
+
12. Node size is 300x200px, rank separation is 200px, spacing within rank is 200px
|
|
234
|
+
13. Avoid node overlapping, compounds order should be aligned with flows crossing their boundaries
|
|
235
|
+
14. Minimize edge crossings; prefer balanced, straighter edges
|
|
236
|
+
|
|
237
|
+
</rules>
|
|
238
|
+
|
|
239
|
+
<workflow>
|
|
240
|
+
|
|
241
|
+
1. Analyze diagram semantics, identify main and auxiliary flows, which nodes are most likely to be sources and which are sinks
|
|
242
|
+
2. If any compound exists, analyze hierarchy and keep parent-child relationships in mind as constraints
|
|
243
|
+
3. Plan node positions and rank constraints
|
|
244
|
+
4. Decide on edges: adjust \`minlen\`, reverse rank direction or exclude from ranking
|
|
245
|
+
5. Consider adding invisible edges to enforce layout
|
|
246
|
+
6. Balance the layout by adjusting edge weights
|
|
247
|
+
7. Output existing edges in semantic order
|
|
248
|
+
8. Output nodes in semantic order
|
|
249
|
+
</workflow>
|
|
250
|
+
|
|
251
|
+
<output>
|
|
252
|
+
Output ONLY a valid JSON object matching the following schema.
|
|
253
|
+
All fields are optional (omit empty, null, undefined).
|
|
254
|
+
Use \`reasoning\` field to explain your decision, be concise.
|
|
255
|
+
Do not include any other text, comments, questions or explanations.
|
|
256
|
+
Do not pretty-print, compact JSON is preferred.
|
|
257
|
+
|
|
258
|
+
\`\`\`json
|
|
63
259
|
{
|
|
64
|
-
"
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
"title": "Frontend",
|
|
70
|
-
"description": "User-facing web app",
|
|
71
|
-
"technology": "React",
|
|
72
|
-
"tags": ["public"],
|
|
73
|
-
"metadata": { "owner": "web-team" },
|
|
74
|
-
"shape": "browser",
|
|
75
|
-
"color": "#2F80ED",
|
|
76
|
-
"children": ["shop.frontend.auth"],
|
|
77
|
-
"incomingCount": 2,
|
|
78
|
-
"outgoingCount": 3,
|
|
79
|
-
"includedInViews": [
|
|
80
|
-
{ "id": "system-overview", "title": "System Overview", "type": "element" }
|
|
81
|
-
]
|
|
82
|
-
}
|
|
260
|
+
// Force ranks for nodes, use "source" for top level, "sink" for bottom level, "same" for nodes that should be on the same rank
|
|
261
|
+
"ranks": [
|
|
262
|
+
{ "rank": "source", "nodes": ["n1", "n2"] },
|
|
263
|
+
{ "rank": "same", "nodes": ["n4", "n5"] },
|
|
264
|
+
{ "rank": "sink", "nodes": ["n3"] }
|
|
83
265
|
],
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
Request:
|
|
90
|
-
- element1Id: string — first element id (FQN)
|
|
91
|
-
- element2Id: string — second element id (FQN)
|
|
92
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
93
|
-
|
|
94
|
-
Response (JSON object):
|
|
95
|
-
- element1: object — snapshot of first element (id, kind, title, description, technology, shape, color)
|
|
96
|
-
- element2: object — snapshot of second element
|
|
97
|
-
- propertyDiffs: Array of { property, element1Value, element2Value } — properties that differ
|
|
98
|
-
- tags: object
|
|
99
|
-
- onlyInElement1: string[] — tags only in element1
|
|
100
|
-
- onlyInElement2: string[] — tags only in element2
|
|
101
|
-
- common: string[] — tags in both
|
|
102
|
-
- metadata: object
|
|
103
|
-
- onlyInElement1: Record — metadata keys only in element1
|
|
104
|
-
- onlyInElement2: Record — metadata keys only in element2
|
|
105
|
-
- different: Array of { key, element1Value, element2Value } — keys present in both but with different values
|
|
106
|
-
- common: Record — metadata keys with identical values in both
|
|
107
|
-
- relationships: object — relationship count comparison
|
|
108
|
-
- incomingOnlyElement1/incomingOnlyElement2/incomingShared
|
|
109
|
-
- outgoingOnlyElement1/outgoingOnlyElement2/outgoingShared
|
|
110
|
-
|
|
111
|
-
Notes:
|
|
112
|
-
- Read-only, idempotent, no side effects.
|
|
113
|
-
- Safe to call repeatedly.
|
|
114
|
-
- Both elements must exist in the same project.
|
|
115
|
-
- Useful for comparing similar nodes to understand why they have different configurations.
|
|
116
|
-
|
|
117
|
-
Example response:
|
|
118
|
-
{
|
|
119
|
-
"element1": { "id": "planner.nodeA", "kind": "cgf-node", "title": "nodeA", ... },
|
|
120
|
-
"element2": { "id": "planner.nodeB", "kind": "cgf-node", "title": "nodeB", ... },
|
|
121
|
-
"propertyDiffs": [
|
|
122
|
-
{ "property": "title", "element1Value": "nodeA :dwNodeTypeA", "element2Value": "nodeB :dwNodeTypeB" }
|
|
123
|
-
],
|
|
124
|
-
"tags": {
|
|
125
|
-
"onlyInElement1": ["target_asil_qm"],
|
|
126
|
-
"onlyInElement2": ["target_asil_asil_b"],
|
|
127
|
-
"common": ["is_in_dag", "process_camera_master"]
|
|
266
|
+
// Edge weight adjustments (only if you want to change from default weight=1)
|
|
267
|
+
"edgeWeight": {
|
|
268
|
+
"e1": 8,
|
|
269
|
+
"e2": 5
|
|
128
270
|
},
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
"
|
|
132
|
-
"
|
|
133
|
-
{ "key": "target_asil", "element1Value": "QM", "element2Value": "ASIL-B" }
|
|
134
|
-
],
|
|
135
|
-
"common": { "host": "machine0" }
|
|
271
|
+
// Edge rank separation adjustments (only if you want to change from default minlen=1)
|
|
272
|
+
"edgeMinlen": {
|
|
273
|
+
"e1": 2, // two ranks between connected nodes
|
|
274
|
+
"e2": 0 // no rank separation
|
|
136
275
|
},
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
"outgoingShared": 2
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Compare two elements`},inputSchema:{element1Id:T.string().describe(`First element id (FQN)`),element2Id:T.string().describe(`Second element id (FQN)`),project:J},outputSchema:se.shape})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.element1Id);m(i,`Element "${t.element1Id}" not found in project "${n}"`);let a=r.findElement(t.element2Id);m(a,`Element "${t.element2Id}" not found in project "${n}"`);let s=[],c=[{name:`kind`,get:e=>e.kind},{name:`title`,get:e=>e.title},{name:`description`,get:e=>e.description.text},{name:`technology`,get:e=>e.technology},{name:`shape`,get:e=>e.shape},{name:`color`,get:e=>e.color}];for(let e of c){let t=e.get(i),n=e.get(a);t!==n&&s.push({property:e.name,element1Value:t,element2Value:n})}let l=new Set(i.tags),u=new Set(a.tags),f=[],p=[],h=[];for(let e of l)u.has(e)?f.push(e):p.push(e);for(let e of u)l.has(e)||h.push(e);let g=i.getMetadata(),_=a.getMetadata(),v=new Set([...Object.keys(g),...Object.keys(_)]),y={},b={},x=[],S={};for(let e of v){let t=g[e],n=_[e];t!==void 0&&n===void 0?y[e]=t:t===void 0&&n!==void 0?b[e]=n:t!==void 0&&n!==void 0&&(JSON.stringify(t)===JSON.stringify(n)?S[e]=t:x.push({key:e,element1Value:t,element2Value:n}))}let C=new Set([...i.incoming()].map(e=>e.source.id)),w=new Set([...a.incoming()].map(e=>e.source.id)),T=new Set([...i.outgoing()].map(e=>e.target.id)),E=new Set([...a.outgoing()].map(e=>e.target.id)),D=0,O=0,k=0;for(let e of C)w.has(e)?D++:O++;for(let e of w)C.has(e)||k++;let A=0,j=0,M=0;for(let e of T)E.has(e)?A++:j++;for(let e of E)T.has(e)||M++;return{element1:{id:i.id,kind:i.kind,title:i.title,description:i.description.text,technology:i.technology,shape:i.shape,color:i.color},element2:{id:a.id,kind:a.kind,title:a.title,description:a.description.text,technology:a.technology,shape:a.shape,color:a.color},propertyDiffs:s,tags:{onlyInElement1:p,onlyInElement2:h,common:f},metadata:{onlyInElement1:y,onlyInElement2:b,different:x,common:S},relationships:{incomingOnlyElement1:O,incomingOnlyElement2:k,incomingShared:D,outgoingOnlyElement1:j,outgoingOnlyElement2:M,outgoingShared:A}}}),le=likec4Tool({name:`find-relationship-paths`,description:`
|
|
147
|
-
Discover all paths (chains of relationships) between two elements, supporting multi-hop traversal.
|
|
148
|
-
|
|
149
|
-
Request:
|
|
150
|
-
- sourceId: string — source element FQN
|
|
151
|
-
- targetId: string — target element FQN
|
|
152
|
-
- maxDepth: number (optional, default: 3, max: 5) — maximum path length (number of hops)
|
|
153
|
-
- includeIndirect: boolean (optional, default: false) — include indirect (implied) relationships through nested elements
|
|
154
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
155
|
-
|
|
156
|
-
Algorithm:
|
|
157
|
-
- Uses breadth-first search (BFS) to find all paths
|
|
158
|
-
- Prevents cycles with visited set per path
|
|
159
|
-
- Paths are sorted by length (shortest first)
|
|
160
|
-
- Limited to 100 paths to avoid overwhelming responses
|
|
161
|
-
|
|
162
|
-
Response (JSON object):
|
|
163
|
-
- paths: Array of path objects, each with:
|
|
164
|
-
- length: number — number of hops in the path
|
|
165
|
-
- steps: Array<Step> — ordered sequence of relationships
|
|
166
|
-
|
|
167
|
-
Step (object) fields:
|
|
168
|
-
- source: string — source element FQN
|
|
169
|
-
- target: string — target element FQN
|
|
170
|
-
- relationship: object
|
|
171
|
-
- kind: string|null — relationship kind
|
|
172
|
-
- title: string|null — relationship title
|
|
173
|
-
- description: string|null — relationship description
|
|
174
|
-
- technology: string|null — relationship technology
|
|
175
|
-
- tags: string[] — relationship tags
|
|
176
|
-
|
|
177
|
-
Notes:
|
|
178
|
-
- Read-only, idempotent, no side effects.
|
|
179
|
-
- Safe to call repeatedly.
|
|
180
|
-
- Returns empty paths array if no paths exist.
|
|
181
|
-
- Rejects if source equals target.
|
|
182
|
-
- includeIndirect=false (default): only follows direct relationships on each element.
|
|
183
|
-
includeIndirect=true: also follows implied relationships through nested elements.
|
|
184
|
-
- maxDepth is capped at 5 to prevent excessive computation.
|
|
185
|
-
- Paths are discovered iteratively and sorted by length.
|
|
186
|
-
|
|
187
|
-
Example response:
|
|
188
|
-
{
|
|
189
|
-
"paths": [
|
|
190
|
-
{
|
|
191
|
-
"length": 1,
|
|
192
|
-
"steps": [
|
|
193
|
-
{
|
|
194
|
-
"source": "shop.frontend",
|
|
195
|
-
"target": "shop.backend",
|
|
196
|
-
"relationship": {
|
|
197
|
-
"kind": "uses",
|
|
198
|
-
"title": "Calls API",
|
|
199
|
-
"description": null,
|
|
200
|
-
"technology": "HTTPS",
|
|
201
|
-
"tags": []
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
]
|
|
205
|
-
},
|
|
206
|
-
{
|
|
207
|
-
"length": 2,
|
|
208
|
-
"steps": [
|
|
209
|
-
{
|
|
210
|
-
"source": "shop.frontend",
|
|
211
|
-
"target": "shop.cache",
|
|
212
|
-
"relationship": {
|
|
213
|
-
"kind": "uses",
|
|
214
|
-
"title": "Reads from",
|
|
215
|
-
"description": null,
|
|
216
|
-
"technology": "Redis",
|
|
217
|
-
"tags": []
|
|
218
|
-
}
|
|
219
|
-
},
|
|
220
|
-
{
|
|
221
|
-
"source": "shop.cache",
|
|
222
|
-
"target": "shop.backend",
|
|
223
|
-
"relationship": {
|
|
224
|
-
"kind": "syncs-with",
|
|
225
|
-
"title": "Updates",
|
|
226
|
-
"description": null,
|
|
227
|
-
"technology": null,
|
|
228
|
-
"tags": []
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
]
|
|
232
|
-
}
|
|
233
|
-
]
|
|
234
|
-
}
|
|
235
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationship paths`},inputSchema:{sourceId:T.string().describe(`Source element FQN`),targetId:T.string().describe(`Target element FQN`),maxDepth:T.number().int().min(1).max(5).optional().default(3).describe(`Maximum path length (default: 3, max: 5)`),includeIndirect:T.boolean().optional().default(!1).describe(`Include indirect (implied) relationships through nested elements (default: false)`),project:J},outputSchema:{paths:T.array(T.object({length:T.number().describe(`Number of hops in the path`),steps:T.array(T.object({source:T.string().describe(`Source element FQN`),target:T.string().describe(`Target element FQN`),relationship:T.object({kind:T.string().nullable().describe(`Relationship kind`),title:T.string().nullable().describe(`Relationship title`),description:T.string().nullable().describe(`Relationship description`),technology:T.string().nullable().describe(`Relationship technology`),tags:T.array(T.string()).describe(`Relationship tags`)})})).describe(`Ordered sequence of relationships in the path`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.sourceId);m(i,`Source element "${t.sourceId}" not found in project "${n}"`);let a=r.findElement(t.targetId);m(a,`Target element "${t.targetId}" not found in project "${n}"`),m(i.id!==a.id,`Source and target must be different elements`);let s=t.maxDepth,c=t.includeIndirect?`all`:`direct`,l=[{elementId:i.id,path:[],visited:new Set([i.id])}],u=[];for(;l.length>0&&u.length<100;){let e=l.shift();if(e.path.length>=s)continue;let t=r.findElement(e.elementId);if(t)for(let n of t.outgoing(c)){let t=n.target.id;if(t===a.id){let t={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};if(u.push({length:e.path.length+1,steps:[...e.path,t]}),u.length>=100)break;continue}if(e.visited.has(t))continue;let r={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};l.push({elementId:t,path:[...e.path,r],visited:new Set([...e.visited,t])})}}return u.sort((e,t)=>e.length-t.length),{paths:u}}),Q=T.object({id:T.string(),title:T.string(),kind:T.string()}),ue=T.object({type:T.enum([`direct`,`indirect`]).describe(`Type of relationship, "direct" for direct relationships, "indirect" for relationships through nested elements`),source:Q,target:Q,kind:T.string().nullable().describe(`Relationship kind`),title:T.string().nullable().describe(`Relationship title`),description:T.string().nullable().describe(`Relationship description`),technology:T.string().nullable().describe(`Relationship technology`),tags:T.array(T.string()).describe(`Relationship tags`),includedInViews:Y.describe(`Views that include this relationship`),sourceLocation:q}),de=likec4Tool({name:`find-relationships`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationships between two elements`},description:`
|
|
236
|
-
Find relationships between two LikeC4 elements within a project.
|
|
237
|
-
|
|
238
|
-
What it does:
|
|
239
|
-
- Finds both direct relationships (element1 ↔ element2) and indirect ones that arise via containment (e.g. via nested elements).
|
|
240
|
-
- Returns rich metadata for each relationship and where it appears in views.
|
|
241
|
-
|
|
242
|
-
Inputs:
|
|
243
|
-
- element1: string — Element ID (FQN)
|
|
244
|
-
- element2: string — Element ID (FQN)
|
|
245
|
-
- project: string (optional, defaults to "default") — Project id
|
|
246
|
-
|
|
247
|
-
Output:
|
|
248
|
-
- found: Relationship[]
|
|
249
|
-
|
|
250
|
-
Relationship (object) fields:
|
|
251
|
-
- type: "direct" | "indirect" — direct is between the specified endpoints; indirect is via nested elements
|
|
252
|
-
- source: Endpoint
|
|
253
|
-
- target: Endpoint
|
|
254
|
-
- kind: string|null — relationship kind from the model
|
|
255
|
-
- title: string|null — relationship title if provided
|
|
256
|
-
- description: string|null — relationship description text
|
|
257
|
-
- technology: string|null — relationship technology
|
|
258
|
-
- tags: string[] — relationship tags
|
|
259
|
-
- includedInViews: View[] — views where this relationship appears
|
|
260
|
-
- sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null
|
|
261
|
-
|
|
262
|
-
Endpoint (object) fields:
|
|
263
|
-
- id: string — Element ID (FQN)
|
|
264
|
-
- title: string — element title
|
|
265
|
-
- kind: string — element kind
|
|
266
|
-
|
|
267
|
-
View (object) fields:
|
|
268
|
-
- id: string — view identifier
|
|
269
|
-
- title: string — view title
|
|
270
|
-
- type: "element" | "deployment" | "dynamic"
|
|
271
|
-
|
|
272
|
-
Notes:
|
|
273
|
-
- Read-only, idempotent; does not mutate the model. May trigger UI navigation in supporting clients.
|
|
274
|
-
- The order of results is not guaranteed.
|
|
275
|
-
|
|
276
|
-
Example:
|
|
277
|
-
Request:
|
|
278
|
-
{
|
|
279
|
-
"element1": "shop.frontend",
|
|
280
|
-
"element2": "shop.backend",
|
|
281
|
-
"project": "default"
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
Response:
|
|
285
|
-
{
|
|
286
|
-
"found": [
|
|
287
|
-
{
|
|
288
|
-
"type": "direct",
|
|
289
|
-
"source": { "id": "shop.frontend", "title": "Frontend", "kind": "component" },
|
|
290
|
-
"target": { "id": "shop.backend", "title": "Backend", "kind": "component" },
|
|
291
|
-
"kind": "sync",
|
|
292
|
-
"title": "Calls",
|
|
293
|
-
"description": "Frontend calls Backend",
|
|
294
|
-
"technology": "HTTP",
|
|
295
|
-
"tags": ["public"],
|
|
296
|
-
"includedInViews": [
|
|
297
|
-
{ "id": "system-overview", "title": "System Overview", "type": "element" }
|
|
298
|
-
],
|
|
299
|
-
"sourceLocation": {
|
|
300
|
-
"path": "/abs/path/project/model.c4",
|
|
301
|
-
"range": { "start": { "line": 12, "character": 0 }, "end": { "line": 14, "character": 0 } }
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
]
|
|
305
|
-
}
|
|
306
|
-
`,inputSchema:{element1:T.string().describe(`Element ID (FQN)`),element2:T.string().describe(`Element ID (FQN)`),project:J},outputSchema:{found:T.array(ue)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project);if(I(t.element1,t.element2))throw Error(`No relationships possible between parent-child`);let r=[],i=await e.computedModel(n),a=i.findElement(t.element1);F(a,`Element "${t.element1}" not found in project "${n}"`);let s=i.findElement(t.element2);F(s,`Element "${t.element2}" not found in project "${n}"`);let c=mkLocate(e,n),l=te.findConnection(a,s,`both`).flatMap(e=>[...e.relations]);for(let e of l){let t=e.source===a&&e.target===s||e.source===s&&e.target===a;r.push({type:t?`direct`:`indirect`,source:{id:e.source.id,title:e.source.title,kind:e.source.kind},target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags],includedInViews:includedInViews(e.views()),sourceLocation:c({relation:e.id})})}return{found:r}}),fe=likec4Tool({name:`list-projects`,description:`
|
|
307
|
-
List LikeC4 projects discoverable in the current workspace.
|
|
308
|
-
|
|
309
|
-
Request:
|
|
310
|
-
- No input parameters.
|
|
311
|
-
|
|
312
|
-
Response (JSON object):
|
|
313
|
-
- projects: Project[]
|
|
314
|
-
|
|
315
|
-
Project (object) fields:
|
|
316
|
-
- id: string — stable project identifier
|
|
317
|
-
- title: string — human-readable project title
|
|
318
|
-
- folder: string — absolute path to the project root
|
|
319
|
-
- sources: string[] — absolute file paths of related documents
|
|
320
|
-
|
|
321
|
-
Notes:
|
|
322
|
-
- Read-only, idempotent, no side effects.
|
|
323
|
-
- Safe to call repeatedly.
|
|
324
|
-
|
|
325
|
-
Example response:
|
|
326
|
-
{
|
|
327
|
-
"projects": [
|
|
328
|
-
{
|
|
329
|
-
"id": "docs",
|
|
330
|
-
"title": "Documentation",
|
|
331
|
-
"folder": "/abs/path/to/workspace/docs",
|
|
332
|
-
"sources": [
|
|
333
|
-
"/abs/path/to/workspace/docs/model/contexts.likec4",
|
|
334
|
-
"/abs/path/to/workspace/docs/model/relations.likec4"
|
|
335
|
-
]
|
|
336
|
-
}
|
|
337
|
-
]
|
|
338
|
-
}
|
|
339
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List projects`},inputSchema:{},outputSchema:{projects:T.array(T.object({id:T.string(),title:T.string(),folder:T.string(),sources:T.array(T.string())}))}})(async e=>({projects:e.projects().map(e=>({id:e.id,title:e.title,folder:e.folder.fsPath,sources:e.documents.map(e=>e.fsPath)}))}));function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}const pe=/^\s*view\s+([A-Za-z_][\w-]*)/;function extractViewId(e){let t=pe.exec(e);return t?t[1]:null}function wrapAsViewsBlock(e){return`views {\n${e}\n}\n`}function toPortablePath(e){return e.split(s).join(`/`)}function toVirtualSourcePath(e,t,n){let r=toPortablePath(i(e,t));return r===``||r.startsWith(`..`)?n:r}function formatDiagnostics(e){return e.map(e=>`- line ${e.range.start.line+1}, column ${e.range.start.character+1}: ${e.message}`).join(`
|
|
340
|
-
`)}function previewViewTool(e){return O(e,`preview-view`,{title:`Preview View`,description:`Renders a preview of a LikeC4 view defined by DSL text, in the context of an existing project's real elements — without saving anything to disk.
|
|
341
|
-
|
|
342
|
-
Request:
|
|
343
|
-
- dsl: string — a single \`view <id> ... { ... }\` definition. It must reference elements that already exist in the target project.
|
|
344
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
345
|
-
|
|
346
|
-
Behavior:
|
|
347
|
-
- The view id must be new (not already present in the project). If the view id matches an existing view, an error is returned — use a different id, or use "render-view" to render an existing view.
|
|
348
|
-
- The view is rendered as a draft alongside the project's real elements.
|
|
349
|
-
|
|
350
|
-
Note: preview styling may not exactly match the real project (custom theme/style extensions aren't applied to the preview). Only \`view <id> ...\` (element view) declarations are recognized for id-detection — a \`dynamic view <id> {...}\` or \`deployment view <id> {...}\` will fail with a generic "could not find a \`view <id>\`" error instead.
|
|
351
|
-
|
|
352
|
-
Use "preview-view" to iterate on a new view definition before creating it for real. Use "render-view" to render a view that's already saved.`,inputSchema:{dsl:T.string().describe("A single `view <id> ... { ... }` LikeC4 DSL definition"),project:J},outputSchema:{id:T.string(),title:T.string(),project:T.string(),view:T.record(T.string(),T.unknown()),model:T.record(T.string(),T.unknown())},annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Preview view`},_meta:{ui:{resourceUri:X}}},async e=>{try{var n=_usingCtx();let r=useLanguageServices(),i=r.projectsManager.ensureProjectId(e.project),a=extractViewId(e.dsl);if(!a)return toolError("Could not find a `view <id> ...` declaration at the start of `dsl`. Example: `view myView of someElement { include * }`");let s=r.project(i);if((await r.computedModel(i))?.findView(a))return toolError(`View "${a}" already exists in the project. Use a different view id for the preview, or use "render-view" to render the existing view.`);let c={};for(let[e,t]of s.documents.entries()){let n=toVirtualSourcePath(s.folder.fsPath,t.fsPath,`seed-${e}.c4`);c[n]=r.documentText(t.toString())??``}let l=`${L()}.c4`;c[l]=wrapAsViewsBlock(e.dsl);let u=n.a(await t(c,{printErrors:!1,throwIfInvalid:!1})),f=u.getErrors();if(f.length>0)return toolError(`Failed to build preview:\n${formatDiagnostics(f)}`);let p=await u.computedModel(),m=p.findView(a);if(!m)return toolError(`View "${a}" was not found after building the preview.`);let h=await u.viewsService.layoutView({viewId:m.id,projectId:i});if(!h)return toolError(`Failed to layout preview view "${a}".`);let g=m.title??m.id;return{content:[{type:`text`,text:`Rendered preview of view "${g}"`}],structuredContent:buildRenderPayload({projectId:i,viewId:m.id,title:g,layoutedView:h.diagram,modelData:p.$data})}}catch(e){n.e=e}finally{await n.d()}}),e}const me=T.enum([`exact`,`contains`,`exists`]),he=likec4Tool({name:`query-by-metadata`,description:`
|
|
353
|
-
Search elements and deployment nodes by metadata key-value pairs with flexible matching modes.
|
|
354
|
-
|
|
355
|
-
Request:
|
|
356
|
-
- key: string — metadata key to filter by
|
|
357
|
-
- value: string (optional) — metadata value to match (ignored for 'exists' mode)
|
|
358
|
-
- matchMode: "exact" | "contains" | "exists" (optional, default: "exact")
|
|
359
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
360
|
-
|
|
361
|
-
Match Modes:
|
|
362
|
-
- exact: Value must match exactly (case-sensitive)
|
|
363
|
-
Example: key="owner", value="platform-team" matches only exact "platform-team"
|
|
364
|
-
- contains: Value contains the search string (case-insensitive)
|
|
365
|
-
Example: key="technology", value="aws" matches "AWS Lambda", "aws-s3", etc.
|
|
366
|
-
- exists: Element has the key (value parameter is ignored)
|
|
367
|
-
Example: key="owner" returns all elements with any "owner" metadata
|
|
368
|
-
|
|
369
|
-
Response (JSON object):
|
|
370
|
-
- results: Array of matching elements/deployment-nodes, each with:
|
|
371
|
-
- id: string — element/node id (FQN)
|
|
372
|
-
- name: string — element/node name
|
|
373
|
-
- kind: string — element/node kind
|
|
374
|
-
- title: string — human-readable title
|
|
375
|
-
- tags: string[] — assigned tags
|
|
376
|
-
- metadata: Record<string, string | string[]> — all element metadata
|
|
377
|
-
- matchedValue: string — the metadata value that matched (for reference)
|
|
378
|
-
- includedInViews: View[] — views that include this element
|
|
379
|
-
|
|
380
|
-
View (object) fields:
|
|
381
|
-
- id: string — view identifier
|
|
382
|
-
- title: string — view title
|
|
383
|
-
- type: "element" | "deployment" | "dynamic"
|
|
384
|
-
|
|
385
|
-
Notes:
|
|
386
|
-
- Read-only, idempotent, no side effects.
|
|
387
|
-
- Safe to call repeatedly.
|
|
388
|
-
- Handles both string and array metadata values.
|
|
389
|
-
- For array values, matches if any element in the array matches.
|
|
390
|
-
- Returns empty array if no matches found.
|
|
391
|
-
- Limited to 50 results to avoid overwhelming responses.
|
|
392
|
-
- Case-sensitive for exact mode, case-insensitive for contains mode.
|
|
393
|
-
|
|
394
|
-
Example response:
|
|
395
|
-
{
|
|
396
|
-
"results": [
|
|
397
|
-
{
|
|
398
|
-
"id": "shop.frontend",
|
|
399
|
-
"name": "frontend",
|
|
400
|
-
"kind": "container",
|
|
401
|
-
"title": "Frontend",
|
|
402
|
-
"tags": ["public"],
|
|
403
|
-
"metadata": {
|
|
404
|
-
"owner": "platform-team",
|
|
405
|
-
"tier": "critical"
|
|
406
|
-
},
|
|
407
|
-
"matchedValue": "platform-team",
|
|
408
|
-
"includedInViews": [
|
|
409
|
-
{
|
|
410
|
-
"id": "system-overview",
|
|
411
|
-
"title": "System Overview",
|
|
412
|
-
"type": "element"
|
|
413
|
-
}
|
|
414
|
-
]
|
|
415
|
-
}
|
|
416
|
-
]
|
|
417
|
-
}
|
|
418
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by metadata`},inputSchema:{key:T.string().describe(`Metadata key to filter by`),value:T.string().optional().describe(`Metadata value to match (ignored for exists mode)`),matchMode:me.optional().default(`exact`).describe(`Matching mode`),project:J},outputSchema:{results:T.array(K.extend({matchedValue:T.string().describe(`The metadata value that matched`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.matchMode,a=[],matches=(e,t,n)=>{let r=Array.isArray(e)?e:[e];switch(n){case`exists`:return!0;case`exact`:return t!==void 0&&r.some(e=>e===t);case`contains`:{if(t===void 0)return!1;let e=t.toLowerCase();return r.some(t=>t.toLowerCase().includes(e))}default:return!1}},getMatchedValue=(e,t,n)=>{let r=Array.isArray(e)?e:[e];if(n===`exists`||t===void 0)return r[0]||``;if(n===`exact`)return r.find(e=>e===t)||r[0]||``;if(n===`contains`){let e=t.toLowerCase();return r.find(t=>t.toLowerCase().includes(e))||r[0]||``}return r[0]||``};for(let e of r.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}if(a.length<50)for(let e of r.deployment.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}return{results:a}}),ge=likec4Tool({name:`query-by-tag-pattern`,description:`
|
|
419
|
-
Search elements by tag patterns using prefix or substring matching.
|
|
420
|
-
Useful for tag taxonomies with structured naming conventions (e.g., "schedule_*", "*_asil_*").
|
|
421
|
-
|
|
422
|
-
Request:
|
|
423
|
-
- pattern: string — tag pattern to match
|
|
424
|
-
- matchMode: "prefix" | "contains" | "suffix" (optional, default: "prefix")
|
|
425
|
-
- prefix: matches tags starting with the pattern (e.g., "target_asil" matches "target_asil_qm", "target_asil_asil_b")
|
|
426
|
-
- contains: matches tags containing the pattern anywhere (e.g., "asil" matches "target_asil_qm", "unit_asil_b")
|
|
427
|
-
- suffix: matches tags ending with the pattern (e.g., "_tbc" matches "target_asil_qm__tbc")
|
|
428
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
429
|
-
|
|
430
|
-
Response (JSON object):
|
|
431
|
-
- results: Array of matching elements, each with:
|
|
432
|
-
- id: string — element id (FQN)
|
|
433
|
-
- name: string — element name
|
|
434
|
-
- kind: string — element kind
|
|
435
|
-
- title: string — human-readable title
|
|
436
|
-
- tags: string[] — all assigned tags
|
|
437
|
-
- metadata: Record<string, string | string[]> — element metadata
|
|
438
|
-
- matchedTags: string[] — the specific tags that matched the pattern
|
|
439
|
-
- includedInViews: View[] — views that include this element
|
|
440
|
-
- truncated: boolean — true if results were truncated due to exceeding the 50-result limit
|
|
441
|
-
- matchedTagValues: string[] — all unique tag values that matched the pattern across all elements
|
|
442
|
-
|
|
443
|
-
View (object) fields:
|
|
444
|
-
- id: string — view identifier
|
|
445
|
-
- title: string — view title
|
|
446
|
-
- type: "element" | "deployment" | "dynamic"
|
|
447
|
-
|
|
448
|
-
Notes:
|
|
449
|
-
- Read-only, idempotent, no side effects.
|
|
450
|
-
- Safe to call repeatedly.
|
|
451
|
-
- Pattern matching is case-insensitive.
|
|
452
|
-
- Returns empty array if no matches found.
|
|
453
|
-
- Limited to 50 results.
|
|
454
|
-
- matchedTagValues provides a summary of all distinct matching tag values found.
|
|
455
|
-
|
|
456
|
-
Example response:
|
|
457
|
-
{
|
|
458
|
-
"results": [
|
|
459
|
-
{
|
|
460
|
-
"id": "top.planner.behaviorNode",
|
|
461
|
-
"name": "behaviorNode",
|
|
462
|
-
"kind": "cgf-node",
|
|
463
|
-
"title": "behaviorNode :dwBehaviorPlannerNode",
|
|
464
|
-
"tags": ["is_in_dag", "target_asil_qm", "process_camera_master"],
|
|
465
|
-
"metadata": {},
|
|
466
|
-
"matchedTags": ["target_asil_qm"],
|
|
467
|
-
"includedInViews": []
|
|
468
|
-
}
|
|
469
|
-
],
|
|
470
|
-
"truncated": false,
|
|
471
|
-
"matchedTagValues": ["target_asil_qm", "target_asil_asil_b", "target_asil_qm__tbc"]
|
|
472
|
-
}
|
|
473
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tag pattern`},inputSchema:{pattern:T.string().min(1).describe(`Tag pattern to match`),matchMode:T.enum([`prefix`,`contains`,`suffix`]).optional().default(`prefix`).describe(`Pattern matching mode (default: prefix)`),project:J},outputSchema:{results:T.array(K.extend({matchedTags:T.array(T.string()).describe(`Tags that matched the pattern`)})),truncated:T.boolean().describe(`True if results were truncated`),matchedTagValues:T.array(T.string()).describe(`All unique tag values matching the pattern across all elements`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.pattern.toLowerCase(),matchesTag=e=>{let n=e.toLowerCase();switch(t.matchMode){case`prefix`:return n.startsWith(i);case`contains`:return n.includes(i);case`suffix`:return n.endsWith(i)}},a=[],s=!1,c=new Set;for(let e of r.elements()){let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}for(let e of r.deployment.elements()){if(!N(e))continue;let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}return{results:a,truncated:s,matchedTagValues:[...c].sort((e,t)=>e.localeCompare(t))}}),_e=likec4Tool({name:`query-by-tags`,description:`
|
|
474
|
-
Advanced tag filtering with boolean logic (AND, OR, NOT).
|
|
475
|
-
|
|
476
|
-
Request:
|
|
477
|
-
- allOf: string[] (optional) — element must have ALL these tags (AND logic)
|
|
478
|
-
- anyOf: string[] (optional) — element must have ANY of these tags (OR logic)
|
|
479
|
-
- noneOf: string[] (optional) — element must have NONE of these tags (NOT logic)
|
|
480
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
481
|
-
|
|
482
|
-
Boolean Logic:
|
|
483
|
-
- All three conditions are combined with AND logic
|
|
484
|
-
- At least one condition must be specified
|
|
485
|
-
- Tags are case-sensitive
|
|
486
|
-
|
|
487
|
-
Example Queries:
|
|
488
|
-
- Public APIs: {"allOf": ["public", "api"]}
|
|
489
|
-
- Deprecated or legacy: {"anyOf": ["deprecated", "legacy"]}
|
|
490
|
-
- Public but not deprecated: {"allOf": ["public"], "noneOf": ["deprecated"]}
|
|
491
|
-
- Critical services not in migration: {"allOf": ["critical", "service"], "noneOf": ["migration", "deprecated"]}
|
|
492
|
-
|
|
493
|
-
Response (JSON object):
|
|
494
|
-
- results: Array of matching elements/deployment-nodes, each with:
|
|
495
|
-
- id: string — element/node id (FQN)
|
|
496
|
-
- name: string — element/node name
|
|
497
|
-
- kind: string — element/node kind
|
|
498
|
-
- title: string — human-readable title
|
|
499
|
-
- tags: string[] — assigned tags (for reference)
|
|
500
|
-
- metadata: Record<string, string | string[]> — element metadata
|
|
501
|
-
- includedInViews: View[] — views that include this element
|
|
502
|
-
|
|
503
|
-
View (object) fields:
|
|
504
|
-
- id: string — view identifier
|
|
505
|
-
- title: string — view title
|
|
506
|
-
- type: "element" | "deployment" | "dynamic"
|
|
507
|
-
|
|
508
|
-
Notes:
|
|
509
|
-
- Read-only, idempotent, no side effects.
|
|
510
|
-
- Safe to call repeatedly.
|
|
511
|
-
- Returns empty array if no matches found.
|
|
512
|
-
- Limited to 50 results to avoid overwhelming responses.
|
|
513
|
-
- Conflicting conditions (e.g., allOf and noneOf with same tag) will return no results.
|
|
514
|
-
|
|
515
|
-
Example response:
|
|
516
|
-
{
|
|
517
|
-
"results": [
|
|
518
|
-
{
|
|
519
|
-
"id": "shop.api",
|
|
520
|
-
"name": "api",
|
|
521
|
-
"kind": "container",
|
|
522
|
-
"title": "API Gateway",
|
|
523
|
-
"tags": ["public", "api", "critical"],
|
|
524
|
-
"metadata": {
|
|
525
|
-
"owner": "platform-team"
|
|
526
|
-
},
|
|
527
|
-
"includedInViews": [
|
|
528
|
-
{
|
|
529
|
-
"id": "system-overview",
|
|
530
|
-
"title": "System Overview",
|
|
531
|
-
"type": "element"
|
|
532
|
-
}
|
|
533
|
-
]
|
|
534
|
-
}
|
|
535
|
-
]
|
|
536
|
-
}
|
|
537
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tags`},inputSchema:{allOf:T.array(T.string()).optional().describe(`Element must have ALL these tags (AND)`),anyOf:T.array(T.string()).optional().describe(`Element must have ANY of these tags (OR)`),noneOf:T.array(T.string()).optional().describe(`Element must have NONE of these tags (NOT)`),project:J},outputSchema:{results:T.array(K),truncated:T.boolean().describe(`True if results were truncated due to exceeding the 50-result limit`)}})(async(e,t)=>{m(t.allOf&&t.allOf.length>0||t.anyOf&&t.anyOf.length>0||t.noneOf&&t.noneOf.length>0,`At least one condition (allOf, anyOf, or noneOf) must be specified with at least one tag`);let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=[],a=!1,matchesTags=e=>{let n=e instanceof Set?e:new Set(e);return!(t.allOf&&t.allOf.length>0&&!t.allOf.every(e=>n.has(e))||t.anyOf&&t.anyOf.length>0&&!t.anyOf.some(e=>n.has(e))||t.noneOf&&t.noneOf.length>0&&t.noneOf.some(e=>n.has(e)))};for(let e of r.elements()){if(i.length>=50){a=!0;break}matchesTags(e.tags)&&i.push(serializeElement(e))}if(!a)for(let e of r.deployment.elements()){if(i.length>=50){a=!0;break}N(e)&&matchesTags(e.tags)&&i.push(serializeElement(e))}return{results:i,truncated:a}}),ve=T.enum([`ancestors`,`descendants`,`siblings`,`children`,`parent`,`incomers`,`outgoers`]),ye=likec4Tool({name:`query-graph`,description:`
|
|
538
|
-
Query element hierarchy and relationships in the architecture graph.
|
|
539
|
-
|
|
540
|
-
Request:
|
|
541
|
-
- elementId: string — element id (FQN) to query
|
|
542
|
-
- queryType: "ancestors" | "descendants" | "siblings" | "children" | "parent" | "incomers" | "outgoers"
|
|
543
|
-
- includeIndirect: boolean (optional, default: true) — for incomers/outgoers, include indirect relationships (through nested elements)
|
|
544
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
545
|
-
|
|
546
|
-
Query Types:
|
|
547
|
-
- ancestors: Returns all parent elements up to the root (hierarchical)
|
|
548
|
-
Example: shop.frontend.auth.service returns [shop.frontend.auth, shop.frontend, shop]
|
|
549
|
-
- descendants: Returns all child elements recursively (hierarchical)
|
|
550
|
-
Example: shop.frontend returns all nested elements like shop.frontend.auth, shop.frontend.auth.service
|
|
551
|
-
- siblings: Returns elements at the same hierarchy level with the same parent
|
|
552
|
-
Example: shop.frontend returns [shop.backend, shop.database] if they're siblings
|
|
553
|
-
- children: Returns direct child elements only (not recursive)
|
|
554
|
-
Example: shop returns [shop.frontend, shop.backend] but not shop.frontend.auth
|
|
555
|
-
- parent: Returns the direct parent element
|
|
556
|
-
Example: shop.frontend.auth returns shop.frontend
|
|
557
|
-
- incomers: Returns elements that have outgoing relationships to this element (single hop, not recursive).
|
|
558
|
-
For recursive upstream traversal, use query-incomers-graph instead.
|
|
559
|
-
includeIndirect=true: Includes relationships to nested children
|
|
560
|
-
Example: Elements that depend on this element
|
|
561
|
-
- outgoers: Returns elements that receive incoming relationships from this element (single hop, not recursive).
|
|
562
|
-
For recursive downstream traversal, use query-outgoers-graph instead.
|
|
563
|
-
includeIndirect=true: Includes relationships from nested children
|
|
564
|
-
Example: Elements this element depends on
|
|
565
|
-
|
|
566
|
-
Response (JSON object):
|
|
567
|
-
- results: Array of elements (max 100), each with:
|
|
568
|
-
- id: string — element id (FQN)
|
|
569
|
-
- name: string — element name
|
|
570
|
-
- kind: string — element kind
|
|
571
|
-
- title: string — human-readable title
|
|
572
|
-
- tags: string[] — assigned tags
|
|
573
|
-
- metadata: Record<string, string> — element metadata
|
|
574
|
-
- includedInViews: View[] — views that include this element
|
|
575
|
-
- truncated: boolean — true if results were truncated due to exceeding maximum limit (100)
|
|
576
|
-
|
|
577
|
-
View (object) fields:
|
|
578
|
-
- id: string — view identifier
|
|
579
|
-
- title: string — view title
|
|
580
|
-
- type: "element" | "deployment" | "dynamic"
|
|
581
|
-
|
|
582
|
-
Notes:
|
|
583
|
-
- Read-only, idempotent, no side effects.
|
|
584
|
-
- Safe to call repeatedly.
|
|
585
|
-
- For parent query on root element, returns empty array.
|
|
586
|
-
- For hierarchical queries (ancestors, descendants, siblings, children), includeIndirect is ignored.
|
|
587
|
-
|
|
588
|
-
Example response:
|
|
589
|
-
{
|
|
590
|
-
"results": [
|
|
591
|
-
{
|
|
592
|
-
"id": "shop.frontend",
|
|
593
|
-
"name": "frontend",
|
|
594
|
-
"kind": "container",
|
|
595
|
-
"title": "Frontend",
|
|
596
|
-
"tags": ["public"],
|
|
597
|
-
"metadata": { "owner": "web-team" },
|
|
598
|
-
"includedInViews": [
|
|
599
|
-
{
|
|
600
|
-
"id": "system-overview",
|
|
601
|
-
"title": "System Overview",
|
|
602
|
-
"type": "element"
|
|
603
|
-
}
|
|
604
|
-
]
|
|
605
|
-
}
|
|
606
|
-
],
|
|
607
|
-
"truncated": false
|
|
608
|
-
}
|
|
609
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query element graph`},inputSchema:{elementId:T.string().describe(`Element id (FQN) to query`),queryType:ve.describe(`Type of graph query`),includeIndirect:T.boolean().optional().default(!0).describe(`For incomers/outgoers: include indirect relationships (default: true)`),project:J},outputSchema:{results:T.array(K),truncated:T.boolean().describe(`True if results were truncated due to exceeding maximum limit`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.elementId);m(r,`Element "${t.elementId}" not found in project "${n}"`);let i=[],a=!1;switch(t.queryType){case`ancestors`:for(let e of r.ancestors()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`descendants`:for(let e of r.descendants()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`siblings`:for(let e of r.siblings()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`children`:for(let e of r.children()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`parent`:{let e=r.parent;e&&i.push(serializeElement(e));break}case`incomers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.incomers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}case`outgoers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.outgoers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}}return{results:i,truncated:a}}),be=T.object({elementId:T.string().describe(`ID of the incoming element`),relationshipLabel:T.string().optional().describe(`Label on the relationship`),technology:T.string().optional().describe(`Technology specified on the relationship`)}),xe=likec4Tool({name:`query-incomers-graph`,description:`
|
|
610
|
-
Query the complete graph of all elements that provide input to the target element (recursive incomers/producers).
|
|
611
|
-
|
|
612
|
-
This tool performs a breadth-first traversal to discover all upstream dependencies - elements that directly or
|
|
613
|
-
indirectly provide input to the target element. It returns the complete subgraph in a single response,
|
|
614
|
-
making it much more efficient than repeated individual queries.
|
|
615
|
-
|
|
616
|
-
Request:
|
|
617
|
-
- elementId: string — target element id (FQN) to start from
|
|
618
|
-
- includeIndirect: boolean (optional, default: true) — include relationships through nested elements
|
|
619
|
-
- maxDepth: number (optional, default: 10, max: 50) — maximum traversal depth to prevent infinite recursion
|
|
620
|
-
- maxNodes: number (optional, default: 200, max: 2000) — maximum number of nodes to return
|
|
621
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
622
|
-
|
|
623
|
-
Response Structure:
|
|
624
|
-
{
|
|
625
|
-
"target": "element.id",
|
|
626
|
-
"totalNodes": number,
|
|
627
|
-
"maxDepth": number,
|
|
628
|
-
"truncated": boolean,
|
|
629
|
-
"nodes": {
|
|
630
|
-
"element.id": {
|
|
631
|
-
"id": "element.id",
|
|
632
|
-
"name": "name",
|
|
633
|
-
"kind": "kind",
|
|
634
|
-
"title": "title",
|
|
635
|
-
"tags": ["tag1", "tag2"],
|
|
636
|
-
"metadata": {},
|
|
637
|
-
"includedInViews": [...],
|
|
638
|
-
"incomers": [
|
|
639
|
-
{
|
|
640
|
-
"elementId": "id1",
|
|
641
|
-
"relationshipLabel": "uses",
|
|
642
|
-
"technology": "REST"
|
|
643
|
-
}
|
|
644
|
-
],
|
|
645
|
-
"depth": number
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
Use Cases:
|
|
651
|
-
- Find all producers/dependencies for an element
|
|
652
|
-
- Trace data lineage upstream
|
|
653
|
-
- Identify root causes and dependencies
|
|
654
|
-
- Build complete dependency trees
|
|
655
|
-
- Answer "what feeds into this?" questions
|
|
656
|
-
|
|
657
|
-
Notes:
|
|
658
|
-
- Read-only, idempotent, no side effects
|
|
659
|
-
- Cycle detection prevents infinite loops
|
|
660
|
-
- Result size limited to maxNodes to prevent huge responses
|
|
661
|
-
- If truncated=true, increase maxNodes or reduce maxDepth to get more specific results
|
|
662
|
-
|
|
663
|
-
Example:
|
|
664
|
-
For a database element, this returns all services, APIs, and components that write to it,
|
|
665
|
-
plus all their dependencies, recursively up to maxDepth levels.
|
|
666
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete incomers graph`},inputSchema:{elementId:T.string().describe(`Target element id (FQN) to query incomers for`),includeIndirect:T.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:T.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:T.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:J},outputSchema:{target:T.string().describe(`Target element id`),totalNodes:T.number().describe(`Total number of nodes in the graph`),maxDepth:T.number().describe(`Maximum depth reached`),truncated:T.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:T.record(K.extend({incomers:T.array(be).describe(`Incoming relationships with details`),depth:T.number().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);m(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`incoming`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,incomers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),Se=T.object({elementId:T.string().describe(`ID of the outgoing element`),relationshipLabel:T.string().optional().describe(`Label on the relationship`),technology:T.string().optional().describe(`Technology specified on the relationship`)}),$=likec4Tool({name:`query-outgoers-graph`,description:`
|
|
667
|
-
Query the complete graph of all elements that receive output from the target element (recursive outgoers/consumers).
|
|
668
|
-
|
|
669
|
-
This tool performs a breadth-first traversal to discover all downstream dependencies - elements that directly or
|
|
670
|
-
indirectly consume output from the target element. It returns the complete subgraph in a single response,
|
|
671
|
-
making it much more efficient than repeated individual queries.
|
|
672
|
-
|
|
673
|
-
Request:
|
|
674
|
-
- elementId: string — target element id (FQN) to start from
|
|
675
|
-
- includeIndirect: boolean (optional, default: true) — include relationships through nested elements
|
|
676
|
-
- maxDepth: number (optional, default: 10, max: 50) — maximum traversal depth to prevent infinite recursion
|
|
677
|
-
- maxNodes: number (optional, default: 200, max: 2000) — maximum number of nodes to return
|
|
678
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
679
|
-
|
|
680
|
-
Response Structure:
|
|
681
|
-
{
|
|
682
|
-
"target": "element.id",
|
|
683
|
-
"totalNodes": number,
|
|
684
|
-
"maxDepth": number,
|
|
685
|
-
"truncated": boolean,
|
|
686
|
-
"nodes": {
|
|
687
|
-
"element.id": {
|
|
688
|
-
"id": "element.id",
|
|
689
|
-
"name": "name",
|
|
690
|
-
"kind": "kind",
|
|
691
|
-
"title": "title",
|
|
692
|
-
"tags": ["tag1", "tag2"],
|
|
693
|
-
"metadata": {},
|
|
694
|
-
"includedInViews": [...],
|
|
695
|
-
"outgoers": [
|
|
696
|
-
{
|
|
697
|
-
"elementId": "id1",
|
|
698
|
-
"relationshipLabel": "sends data to",
|
|
699
|
-
"technology": "Kafka"
|
|
700
|
-
}
|
|
701
|
-
],
|
|
702
|
-
"depth": number
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
Use Cases:
|
|
708
|
-
- Find all consumers/dependents of an element
|
|
709
|
-
- Trace data lineage downstream
|
|
710
|
-
- Assess impact of changes (blast radius)
|
|
711
|
-
- Build complete consumer trees
|
|
712
|
-
- Answer "what depends on this?" questions
|
|
713
|
-
|
|
714
|
-
Notes:
|
|
715
|
-
- Read-only, idempotent, no side effects
|
|
716
|
-
- Cycle detection prevents infinite loops
|
|
717
|
-
- Result size limited to maxNodes to prevent huge responses
|
|
718
|
-
- If truncated=true, increase maxNodes or reduce maxDepth to get more specific results
|
|
719
|
-
|
|
720
|
-
Example:
|
|
721
|
-
For an API service, this returns all clients, services, and systems that consume its output,
|
|
722
|
-
plus all their consumers, recursively up to maxDepth levels.
|
|
723
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete outgoers graph`},inputSchema:{elementId:T.string().describe(`Target element id (FQN) to query outgoers for`),includeIndirect:T.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:T.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:T.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:J},outputSchema:{target:T.string().describe(`Target element id`),totalNodes:T.number().describe(`Total number of nodes in the graph`),maxDepth:T.number().describe(`Maximum depth reached`),truncated:T.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:T.record(K.extend({outgoers:T.array(Se).describe(`Outgoing relationships with details`),depth:T.number().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);m(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`outgoing`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,outgoers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),Ce=likec4Tool({name:`read-deployment`,description:`
|
|
724
|
-
Read details about a deployment node or a deployed instance in a LikeC4 project.
|
|
725
|
-
|
|
726
|
-
What it does:
|
|
727
|
-
- Returns metadata about a deployment entity (node or instance), including kind, tags, color/shape, children, which views include it, and its source location.
|
|
728
|
-
|
|
729
|
-
Inputs:
|
|
730
|
-
- id: string — Deployment id (FQN)
|
|
731
|
-
- project: string (optional, defaults to "default") — Project id
|
|
732
|
-
|
|
733
|
-
Output fields:
|
|
734
|
-
- type: "deployment-node" | "deployed-instance"
|
|
735
|
-
- id: string — Deployment id (FQN)
|
|
736
|
-
- kind: string — Deployment node kind, or element kind for deployed instances
|
|
737
|
-
- name: string — Name of the deployment entity
|
|
738
|
-
- title: string — Title of the deployment entity
|
|
739
|
-
- description: string|null — Description text
|
|
740
|
-
- technology: string|null — Technology info, if any
|
|
741
|
-
- tags: string[] — Tags assigned to this entity
|
|
742
|
-
- project: string — Project id
|
|
743
|
-
- metadata: Record<string, string>
|
|
744
|
-
- links: Array<{ title: string|null, url: string, relative: string|null }> — external links associated with this deployment entity
|
|
745
|
-
- shape: string — Rendered shape
|
|
746
|
-
- color: string — Rendered color
|
|
747
|
-
- children: string[] — Child deployment ids (empty for instances)
|
|
748
|
-
- includedInViews: View[] — Views that include this entity
|
|
749
|
-
- instanceof: { id: string, title: string, kind: string } | null — If type is "deployed-instance", the referenced element
|
|
750
|
-
- sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null
|
|
751
|
-
|
|
752
|
-
View (object) fields:
|
|
753
|
-
- id: string — view identifier
|
|
754
|
-
- title: string — view title
|
|
755
|
-
- type: "element" | "deployment" | "dynamic"
|
|
756
|
-
|
|
757
|
-
Notes:
|
|
758
|
-
- Read-only, idempotent; does not mutate the model.
|
|
759
|
-
|
|
760
|
-
Example request:
|
|
761
|
-
{ "id": "k8s.cluster.frontend", "project": "default" }
|
|
762
|
-
|
|
763
|
-
Example response (deployed instance):
|
|
764
|
-
{
|
|
765
|
-
"type": "deployed-instance",
|
|
766
|
-
"id": "k8s.cluster.frontend",
|
|
767
|
-
"kind": "k8s.pod",
|
|
768
|
-
"name": "frontend",
|
|
769
|
-
"title": "Frontend Pod",
|
|
770
|
-
"description": null,
|
|
771
|
-
"technology": "Kubernetes",
|
|
772
|
-
"tags": ["prod"],
|
|
773
|
-
"project": "default",
|
|
774
|
-
"metadata": {},
|
|
775
|
-
"links": [],
|
|
776
|
-
"shape": "rectangle",
|
|
777
|
-
"color": "#2F80ED",
|
|
778
|
-
"children": [],
|
|
779
|
-
"includedInViews": [
|
|
780
|
-
{ "id": "runtime-overview", "title": "Runtime Overview", "type": "deployment" }
|
|
781
|
-
],
|
|
782
|
-
"instanceof": { "id": "shop.frontend", "title": "Frontend", "kind": "component" },
|
|
783
|
-
"sourceLocation": {
|
|
784
|
-
"path": "/abs/path/project/model.c4",
|
|
785
|
-
"range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read deployment entity`},inputSchema:{id:T.string().describe(`Deployment id (FQN)`),project:J},outputSchema:{type:T.enum([`deployment-node`,`deployed-instance`]),id:T.string().describe(`Deployment id (FQN)`),kind:T.string().describe(`Deployment node kind, or element kind for deployed instances`),name:T.string(),title:T.string(),description:T.string().nullable(),technology:T.string().nullable(),tags:T.array(T.string()),project:T.string(),metadata:T.record(T.union([T.string(),T.array(T.string())])),links:T.array(T.object({title:T.string().nullable().describe(`Optional link title`),url:T.string().describe(`Link URL`),relative:T.string().nullable().describe(`Relative path (if URL is relative to workspace root)`)})).describe(`External links associated with this deployment entity`),shape:T.string(),color:T.string(),children:T.array(T.string()).describe(`Children of this deployment node (Array of Deployment ids)`),includedInViews:Y.describe(`Views that include this deployment node`),instanceof:T.object({id:T.string().describe(`Element ID (FQN)`),title:T.string(),kind:T.string()}).nullable().describe(`If type is "deployed-instance", the referenced element`),sourceLocation:q}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).deployment.findElement(t.id);m(r,`Deployment entity "${t.id}" not found in project "${n}"`);let i=mkLocate(e,n);return{type:r.isInstance()?`deployed-instance`:`deployment-node`,id:r.id,name:r.name,kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags],project:n,metadata:r.getMetadata(),links:(r.links??[]).map(e=>({title:e.title??null,url:e.url,relative:e.relative??null})),shape:r.shape,color:r.color,children:r.isInstance()?[]:[...r.children()].map(e=>e.id),includedInViews:includedInViews(r.views()),instanceof:r.isInstance()?{id:r.element.id,title:r.element.title,kind:r.element.kind}:null,sourceLocation:i({deployment:r.id})}}),we=likec4Tool({name:`read-element`,description:`
|
|
789
|
-
Read detailed information about a LikeC4 element.
|
|
790
|
-
|
|
791
|
-
Request:
|
|
792
|
-
- id: string — element id (FQN)
|
|
793
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
794
|
-
|
|
795
|
-
Response (JSON object):
|
|
796
|
-
- id: string — element id (FQN)
|
|
797
|
-
- name: string — element name
|
|
798
|
-
- kind: string — element kind
|
|
799
|
-
- title: string — human-readable title
|
|
800
|
-
- description: string|null — optional description
|
|
801
|
-
- technology: string|null — optional technology
|
|
802
|
-
- tags: string[] — assigned tags
|
|
803
|
-
- project: string — project id this element belongs to
|
|
804
|
-
- metadata: Record<string, string> — element metadata
|
|
805
|
-
- links: Array<{ title: string|null, url: string, relative: string|null }> — external links associated with this element
|
|
806
|
-
- shape: string — rendered shape
|
|
807
|
-
- color: string — rendered color
|
|
808
|
-
- children: string[] — ids (FQNs) of direct child elements
|
|
809
|
-
- defaultView: string|null — default view name if set
|
|
810
|
-
- includedInViews: View[] — views that include this element
|
|
811
|
-
- relationships: object — relationships of this element (direct and indirect)
|
|
812
|
-
- incoming: Array<{ source: { id: string, title: string, kind: string }, kind: string|null, target: string, title: string|null, description: string|null, technology: string|null, tags: string[] }>
|
|
813
|
-
- outgoing: Array<{ source: string, target: { id: string, title: string, kind: string }, kind: string|null, title: string|null, description: string|null, technology: string|null, tags: string[] }>
|
|
814
|
-
- deployedInstances: string[] — deployed instance ids (Deployment FQNs)
|
|
815
|
-
- sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null — source location if available
|
|
816
|
-
|
|
817
|
-
View (object) fields:
|
|
818
|
-
- id: string — view identifier
|
|
819
|
-
- title: string — view title
|
|
820
|
-
- type: "element" | "deployment" | "dynamic"
|
|
821
|
-
|
|
822
|
-
Notes:
|
|
823
|
-
- Read-only, idempotent, no side effects.
|
|
824
|
-
- Safe to call repeatedly.
|
|
825
|
-
|
|
826
|
-
Example response:
|
|
827
|
-
{
|
|
828
|
-
"id": "shop.frontend",
|
|
829
|
-
"name": "frontend",
|
|
830
|
-
"kind": "container",
|
|
831
|
-
"title": "Frontend",
|
|
832
|
-
"description": "User-facing web app",
|
|
833
|
-
"technology": "React",
|
|
834
|
-
"tags": ["public"],
|
|
835
|
-
"project": "default",
|
|
836
|
-
"metadata": { "owner": "web" },
|
|
837
|
-
"links": [
|
|
276
|
+
// Reverse edge rank
|
|
277
|
+
"reverseRank": ["e4"],
|
|
278
|
+
// Exclude edges from ranking
|
|
279
|
+
"excludeFromRanking": ["e5"],
|
|
280
|
+
// Add invisible edges to enforce better layout
|
|
281
|
+
"invisibleEdges": [
|
|
838
282
|
{
|
|
839
|
-
"
|
|
840
|
-
"
|
|
841
|
-
"
|
|
283
|
+
"source": "n1", // Node ID
|
|
284
|
+
"target": "n2", // Node ID
|
|
285
|
+
"weight": 8, // (optional, default: 1)
|
|
286
|
+
"minlen": 2 // (optional, default: 1)
|
|
842
287
|
}
|
|
843
288
|
],
|
|
844
|
-
|
|
845
|
-
"
|
|
846
|
-
|
|
847
|
-
"
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
"type": "element"
|
|
853
|
-
}
|
|
854
|
-
],
|
|
855
|
-
"relationships": {
|
|
856
|
-
"incoming": [
|
|
857
|
-
{
|
|
858
|
-
"source": { "id": "shop.api", "title": "API", "kind": "container" },
|
|
859
|
-
"kind": "uses",
|
|
860
|
-
"target": "shop.frontend",
|
|
861
|
-
"title": "Calls",
|
|
862
|
-
"description": null,
|
|
863
|
-
"technology": "HTTPS",
|
|
864
|
-
"tags": []
|
|
865
|
-
}
|
|
866
|
-
],
|
|
867
|
-
"outgoing": []
|
|
868
|
-
},
|
|
869
|
-
"deployedInstances": ["k8s.cluster.frontend"],
|
|
870
|
-
"sourceLocation": {
|
|
871
|
-
"path": "/abs/path/project/model.c4",
|
|
872
|
-
"range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
|
|
873
|
-
}
|
|
289
|
+
// Suggest to change order of edges to satisfy semantics better (if order from input does not)
|
|
290
|
+
"edgeOrder": ["e2", "e1", "e3"],
|
|
291
|
+
// Suggest to change order of nodes to represent flows better (if order from input does not)
|
|
292
|
+
"nodeOrder": ["n2", "n1", "n3", "n4", "n5"],
|
|
293
|
+
// Suggest to change layout direction, if it would improve readability
|
|
294
|
+
"direction": "LR",
|
|
295
|
+
// Reasoning for debugging. Use ID in brackets, like [e1] or [n1], to reference nodes, compounds or edges (for invisible edges use [source->target]). This is important for displaying references on UI correctly.
|
|
296
|
+
"reasoning": "User-facing actor [n1] at top, data store [n3] at bottom. [n4] and [n2] on separate ranks to show the request flow clearly. Main flows are [e1][e2][e3] and [e4][e6], [e5] is auxiliary and does not affect ranking. Added invisible edge [n8->n9] to pull them closer and emphasize their connection."
|
|
874
297
|
}
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
878
|
-
|
|
879
|
-
Response (JSON object):
|
|
880
|
-
- title: string — human-readable project title
|
|
881
|
-
- folder: string — absolute path to the project root
|
|
882
|
-
- sources: string[] — absolute file paths of model documents
|
|
883
|
-
- config: object — project configuration
|
|
884
|
-
- name: string — project identifier
|
|
885
|
-
- title?: string — human-readable title
|
|
886
|
-
- contactPerson?: string — maintainer contact
|
|
887
|
-
- metadata?: object — custom project metadata as key-value pairs
|
|
888
|
-
- extends?: string | string[] — style inheritance paths
|
|
889
|
-
- exclude?: string[] — file exclusion patterns
|
|
890
|
-
- include?: object — include configuration (paths, maxDepth, fileThreshold)
|
|
891
|
-
- manualLayouts?: object — manual layouts config (outDir)
|
|
892
|
-
- styles?: object — simplified styles (hasTheme, hasDefaults, hasCustomCss)
|
|
893
|
-
- specification: object
|
|
894
|
-
- elementKinds: string[] — all element kinds
|
|
895
|
-
- relationshipKinds: string[] — all relationship kinds
|
|
896
|
-
- deploymentKinds: string[] — all deployment kinds
|
|
897
|
-
- tags: string[] — all tags
|
|
898
|
-
- metadataKeys: string[] — used metadata keys
|
|
899
|
-
- elements: Element[] — list of elements
|
|
900
|
-
- deployments: Deployment[] — list of deployment entities
|
|
901
|
-
- views: View[] — list of views defined in the model
|
|
902
|
-
|
|
903
|
-
Element (object) fields:
|
|
904
|
-
- id: string — element id (FQN)
|
|
905
|
-
- kind: string — element kind
|
|
906
|
-
- title: string — element title
|
|
907
|
-
- tags: string[] — element tags
|
|
298
|
+
\`\`\`
|
|
299
|
+
</output>
|
|
908
300
|
|
|
909
|
-
|
|
910
|
-
- type = "deployment-node": { id: string, kind: string, title: string, tags: string[] }
|
|
911
|
-
- type = "deployed-instance": { id: string, title: string, tags: string[], referencedElementId: string }
|
|
301
|
+
<example>
|
|
912
302
|
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
- title: string — view title
|
|
916
|
-
- type: "element" | "deployment" | "dynamic"
|
|
917
|
-
|
|
918
|
-
Notes:
|
|
919
|
-
- Read-only, idempotent, no side effects.
|
|
920
|
-
- Safe to call repeatedly.
|
|
921
|
-
|
|
922
|
-
Example response:
|
|
303
|
+
INPUT:
|
|
304
|
+
\`\`\`json
|
|
923
305
|
{
|
|
924
|
-
"
|
|
925
|
-
"
|
|
926
|
-
|
|
927
|
-
"
|
|
306
|
+
"direction": "TB",
|
|
307
|
+
"compounds": [
|
|
308
|
+
{ "id": "c1", "title": "Cloud System", "children": ["n2", "n3", "n4"], "level": 0 },
|
|
309
|
+
{ "id": "c2", "title": "Amazon", "children": ["n6", "n7", "n8"], "level": 0 }
|
|
928
310
|
],
|
|
929
|
-
"config": {
|
|
930
|
-
"name": "cloud-boutique",
|
|
931
|
-
"title": "Cloud Boutique",
|
|
932
|
-
"contactPerson": "admin@example.com"
|
|
933
|
-
},
|
|
934
|
-
"specification": {
|
|
935
|
-
"elementKinds": ["system", "container", "component"],
|
|
936
|
-
"relationshipKinds": ["uses", "depends-on"],
|
|
937
|
-
"deploymentKinds": ["node", "cluster"],
|
|
938
|
-
"tags": ["public", "internal"],
|
|
939
|
-
"metadataKeys": ["owner", "tier"]
|
|
940
|
-
},
|
|
941
|
-
"elements": [
|
|
942
|
-
{
|
|
943
|
-
"id": "shop.frontend",
|
|
944
|
-
"kind": "component",
|
|
945
|
-
"title": "Frontend",
|
|
946
|
-
"tags": ["public"]
|
|
947
|
-
}
|
|
948
|
-
],
|
|
949
|
-
"deployments": [
|
|
950
|
-
{
|
|
951
|
-
"type": "deployment-node",
|
|
952
|
-
"id": "k8s.shop.frontend",
|
|
953
|
-
"kind": "cluster",
|
|
954
|
-
"title": "Frontend",
|
|
955
|
-
"tags": []
|
|
956
|
-
}
|
|
957
|
-
],
|
|
958
|
-
"views": [
|
|
959
|
-
{
|
|
960
|
-
"id": "system-overview",
|
|
961
|
-
"title": "System Overview",
|
|
962
|
-
"type": "element"
|
|
963
|
-
}
|
|
964
|
-
]
|
|
965
|
-
}
|
|
966
|
-
`,inputSchema:{project:J},outputSchema:{title:T.string(),folder:T.string(),sources:T.array(T.string()),config:G.describe(`Project configuration`),specification:T.object({elementKinds:T.array(T.string()),relationshipKinds:T.array(T.string()),deploymentKinds:T.array(T.string()),tags:T.array(T.string()),metadataKeys:T.array(T.string())}),elements:T.array(T.object({id:T.string(),kind:T.string(),title:T.string(),tags:T.array(T.string())})).describe(`List of elements in the project`),deployments:T.array(T.discriminatedUnion(`type`,[T.object({type:T.literal(`deployment-node`),id:T.string().describe(`Node ID`),kind:T.string().describe(`Deployment node kind`),title:T.string().describe(`Node title`),tags:T.array(T.string())}),T.object({type:T.literal(`deployed-instance`),id:T.string().describe(`Node ID`),title:T.string().describe(`Node title`),tags:T.array(T.string()),referencedElementId:T.string().describe(`Element ID (FQN)`)})])).describe(`List of deployment nodes and deployed instances in the project`),views:T.array(T.object({id:T.string(),title:T.string(),type:T.enum([`element`,`deployment`,`dynamic`])}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=await e.computedModel(n);return{title:r.title,folder:r.folder.fsPath,sources:r.documents?.map(e=>e.fsPath)??[],config:serializeConfig(r.config),specification:{elementKinds:v(i.specification.elements),relationshipKinds:v(i.specification.relationships),deploymentKinds:v(i.specification.deployments),tags:[...i.tags],metadataKeys:i.specification.metadataKeys??[]},elements:[...i.elements()].filter(e=>!e.imported).map(e=>({id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]})),deployments:[...i.deployment.elements()].map(e=>e.isInstance()?{type:`deployed-instance`,id:e.id,title:e.title,tags:[...e.tags],referencedElementId:e.element.id}:{type:`deployment-node`,id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]}),views:[...i.views()].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type}))}}),modelRef=e=>e.hasElement()?e.element.id:e.hasDeployment()?e.deployment.id:null,Ee=T.discriminatedUnion(`type`,[T.object({type:T.literal(`element`),id:T.string().describe(`Node ID`),elementId:T.string().describe(`Element ID (FQN)`),kind:T.string().describe(`Element kind`),title:T.string().describe(`Node title`),description:T.string().nullable(),technology:T.string().nullable(),children:T.array(T.string()).describe(`Children nodes, array of node IDs`),shape:T.string().describe(`Rendered shape`),color:T.string().describe(`Rendered color`),tags:T.array(T.string())}),T.object({type:T.literal(`deployment-node`),id:T.string().describe(`Node ID`),deploymentId:T.string().describe(`Deployment entity ID (FQN)`),kind:T.string().describe(`Deployment kind`),title:T.string().describe(`Node title`),description:T.string().nullable(),technology:T.string().nullable(),children:T.array(T.string()).describe(`Children nodes, array of node IDs`),shape:T.string().describe(`Rendered shape`),color:T.string().describe(`Rendered color`),tags:T.array(T.string())}),T.object({type:T.literal(`deployed-instance`),id:T.string().describe(`Node ID`),deploymentId:T.string().describe(`Deployment entity ID (FQN)`),title:T.string().describe(`Node title`),description:T.string().nullable(),technology:T.string().nullable(),referencedElement:T.object({id:T.string().describe(`Element ID (FQN)`),kind:T.string().describe(`Element kind`),title:T.string().describe(`Element title`)}),shape:T.string().describe(`Rendered shape`),color:T.string().describe(`Rendered color`),tags:T.array(T.string())})]),De=likec4Tool({name:`read-view`,description:`
|
|
967
|
-
Read detailed information about a LikeC4 view.
|
|
968
|
-
|
|
969
|
-
Request:
|
|
970
|
-
- viewId: string — view id (name)
|
|
971
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
972
|
-
|
|
973
|
-
Response (JSON object):
|
|
974
|
-
- id: string — view id
|
|
975
|
-
- type: "element" | "deployment" | "dynamic" — view type
|
|
976
|
-
- title: string — view title (falls back to id if not set)
|
|
977
|
-
- description: string|null — optional description
|
|
978
|
-
- tags: string[] — view tags
|
|
979
|
-
- project: string — project id this view belongs to
|
|
980
|
-
- nodes: Node[] — nodes included in the view
|
|
981
|
-
- edges: Edge[] — relationships between nodes
|
|
982
|
-
- sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null — source location if available
|
|
983
|
-
|
|
984
|
-
Node (discriminated union by "type"):
|
|
985
|
-
- type = "element": { id: string, elementId: string, kind: string, title: string, description: string|null, technology: string|null, children: string[], shape: string, color: string, tags: string[] }
|
|
986
|
-
- type = "deployment-node": { id: string, deploymentId: string, kind: string, title: string, description: string|null, technology: string|null, children: string[], shape: string, color: string, tags: string[] }
|
|
987
|
-
- type = "deployed-instance": { id: string, deploymentId: string, title: string, description: string|null, technology: string|null, referencedElement: { id: string, kind: string, title: string }, shape: string, color: string, tags: string[] }
|
|
988
|
-
|
|
989
|
-
Edge object:
|
|
990
|
-
- { source: string, target: string, label: string|null, description: string|null, technology: string|null, tags: string[] }
|
|
991
|
-
|
|
992
|
-
Notes:
|
|
993
|
-
- Read-only, idempotent, no side effects.
|
|
994
|
-
|
|
995
|
-
Example response:
|
|
996
|
-
{
|
|
997
|
-
"id": "system-overview",
|
|
998
|
-
"type": "element",
|
|
999
|
-
"title": "System Overview",
|
|
1000
|
-
"description": null,
|
|
1001
|
-
"tags": [],
|
|
1002
|
-
"project": "default",
|
|
1003
311
|
"nodes": [
|
|
1004
|
-
{ "
|
|
312
|
+
{ "id": "n2", "kind": "service", "title": "Cloud Legacy", "parent": "c1", "level": 1 },
|
|
313
|
+
{ "id": "n3", "kind": "service", "title": "Cloud Next", "parent": "c1", "level": 1 },
|
|
314
|
+
{ "id": "n4", "kind": "ui", "title": "Frontends", "parent": "c1", "level": 1 },
|
|
315
|
+
{ "id": "n6", "kind": "storage", "title": "S3", "parent": "c2", "level": 1 },
|
|
316
|
+
{ "id": "n7", "kind": "service", "title": "Lambda", "parent": "c2", "level": 1 },
|
|
317
|
+
{ "id": "n8", "kind": "storage", "title": "Postgres", "parent": "c2", "level": 1 }
|
|
1005
318
|
],
|
|
1006
319
|
"edges": [
|
|
1007
|
-
{ "
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
"
|
|
1011
|
-
"
|
|
1012
|
-
|
|
1013
|
-
}
|
|
1014
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read view`},inputSchema:{viewId:T.string().describe(`View id (name)`),project:J},outputSchema:{id:T.string(),type:T.enum([`element`,`deployment`,`dynamic`]).describe(`View type`),title:T.string(),description:T.string().nullable(),tags:T.array(T.string()),project:T.string(),nodes:T.array(Ee),edges:T.array(T.object({source:T.string().describe(`Source node`),target:T.string().describe(`Target node`),label:T.string().nullable(),description:T.string().nullable(),technology:T.string().nullable(),tags:T.array(T.string())})).describe(`Edge represents relationship between nodes`),sourceLocation:q}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=(await e.computedModel(n)).findView(t.viewId);if(!i)throw Error(`View with ID '${t.viewId}' not found in project ${r.id}`);let a=mkLocate(e,r.id);return{id:i.id,type:i.$view._type,title:i.title??i.id,description:i.description.text,tags:[...i.tags],project:r.id,nodes:[...i.nodes()].flatMap(e=>{let t={id:e.id,title:e.title,description:e.description.text,technology:e.technology,shape:e.shape,color:e.color,tags:[...e.tags]};return e.hasDeployedInstance()?{...t,type:`deployed-instance`,deploymentId:e.deployment.id,referencedElement:{id:e.deployment.element.id,kind:e.deployment.element.kind,title:e.deployment.element.title}}:e.hasDeployment()?{...t,type:`deployment-node`,kind:e.deployment.kind,deploymentId:e.deployment.id,children:[...e.children()].map(e=>e.id)}:e.hasElement()?{...t,type:`element`,elementId:e.element.id,kind:e.element.kind,children:[...e.children()].flatMap(e=>modelRef(e)??[])}:[]}),edges:[...i.edges()].map(e=>({source:e.source.id,target:e.target.id,label:e.label,description:e.description.text,technology:e.technology,tags:[...e.tags]})),sourceLocation:a({view:i.id})}}),Oe=T.array(T.discriminatedUnion(`type`,[T.object({type:T.literal(`element`),project:T.string().describe(`Project ID`),id:T.string().describe(`Element ID (FQN)`),name:T.string().describe(`Element name`),kind:T.string(),title:T.string(),technology:T.string().nullable(),shape:T.string(),includedInViews:Y,metadata:T.record(T.union([T.string(),T.array(T.string())])),tags:T.array(T.string())}),T.object({type:T.literal(`deployment-node`),project:T.string().describe(`Project ID`),id:T.string().describe(`Deployment ID (FQN)`),name:T.string().describe(`Deployment name`),kind:T.string(),title:T.string(),technology:T.string().nullable(),shape:T.string(),includedInViews:Y,metadata:T.record(T.union([T.string(),T.array(T.string())])),tags:T.array(T.string())})])),ke=likec4Tool({name:`search-element`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Search elements`},description:`
|
|
1015
|
-
Search LikeC4 elements and deployment nodes across all projects.
|
|
1016
|
-
|
|
1017
|
-
Query syntax (case-insensitive):
|
|
1018
|
-
- kind:<value> filters by kind
|
|
1019
|
-
- shape:<value> filters by shape
|
|
1020
|
-
- meta:<key> filters by having metadata with the given key
|
|
1021
|
-
- #<value> matches assigned tags
|
|
1022
|
-
- <value> matches id (FQN) or title
|
|
1023
|
-
|
|
1024
|
-
Request:
|
|
1025
|
-
- search: string — at least 2 characters
|
|
1026
|
-
|
|
1027
|
-
Response (JSON object):
|
|
1028
|
-
- total: number - total number of results
|
|
1029
|
-
- found: Result[] - returns top 20 results
|
|
1030
|
-
|
|
1031
|
-
Result (discriminated union by "type"):
|
|
1032
|
-
- type = "element": { id: string, name: string, kind: string, title: string, technology: string|null, shape: string, project: string, includedInViews: View[], tags: string[], metadata: Record<string, string> }
|
|
1033
|
-
- type = "deployment-node": { id: string, name: string, kind: string, title: string, technology: string|null, shape: string, project: string, includedInViews: View[], tags: string[], metadata: Record<string, string> }
|
|
1034
|
-
|
|
1035
|
-
View (object) fields:
|
|
1036
|
-
- id: string — view identifier
|
|
1037
|
-
- title: string — view title
|
|
1038
|
-
- type: "element" | "deployment" | "dynamic"
|
|
1039
|
-
|
|
1040
|
-
Notes:
|
|
1041
|
-
- Read-only, idempotent.
|
|
1042
|
-
- Use results as input to other tools (e.g., read-element, read-view).
|
|
1043
|
-
|
|
1044
|
-
Example response:
|
|
1045
|
-
{
|
|
1046
|
-
"total": 1,
|
|
1047
|
-
"found": [
|
|
1048
|
-
{
|
|
1049
|
-
"type": "logical",
|
|
1050
|
-
"project": "default",
|
|
1051
|
-
"id": "shop.frontend",
|
|
1052
|
-
"name": "frontend",
|
|
1053
|
-
"kind": "container",
|
|
1054
|
-
"title": "Frontend",
|
|
1055
|
-
"technology": "React",
|
|
1056
|
-
"shape": "rectangle",
|
|
1057
|
-
"includedInViews": [
|
|
1058
|
-
{
|
|
1059
|
-
"id": "system-overview",
|
|
1060
|
-
"title": "System Overview",
|
|
1061
|
-
"type": "element"
|
|
1062
|
-
}
|
|
1063
|
-
],
|
|
1064
|
-
"tags": ["public"],
|
|
1065
|
-
"metadata": {}
|
|
1066
|
-
}
|
|
320
|
+
{ "id": "e1", "source": "n7", "target": "n8", "parent": "c2"},
|
|
321
|
+
{ "id": "e2", "source": "n3", "target": "n7", "label": "calls lambda" },
|
|
322
|
+
{ "id": "e3", "source": "n4", "target": "n2", "parent": "c1", "label": "requests" },
|
|
323
|
+
{ "id": "e4", "source": "n3", "target": "n4", "parent": "c1", "label": "serves" },
|
|
324
|
+
{ "id": "e5", "source": "n3", "target": "n2", "parent": "c1", "label": "calls legacy" },
|
|
325
|
+
{ "id": "e6", "source": "n2", "target": "n6", "label": "persists" },
|
|
326
|
+
{ "id": "e7", "source": "n3", "target": "n8", "label": "reads users from the database" }
|
|
1067
327
|
]
|
|
1068
328
|
}
|
|
1069
|
-
|
|
1070
|
-
Get a compact, table-friendly summary of all descendants of a parent element.
|
|
1071
|
-
Returns each descendant with its depth, metadata, tags, and relationship counts in a single call.
|
|
1072
|
-
Much more efficient than calling read-element for each descendant individually.
|
|
1073
|
-
|
|
1074
|
-
Request:
|
|
1075
|
-
- elementId: string — parent element id (FQN) whose descendants to summarize
|
|
1076
|
-
- maxDepth: number (optional, default: 10, max: 20) — maximum depth of descendants to include
|
|
1077
|
-
- metadataKeys: string[] (optional) — if provided, only include these metadata keys in the response (reduces response size)
|
|
1078
|
-
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
1079
|
-
|
|
1080
|
-
Response (JSON object):
|
|
1081
|
-
- root: object — the root element summary
|
|
1082
|
-
- id: string — element id
|
|
1083
|
-
- kind: string — element kind
|
|
1084
|
-
- title: string — element title
|
|
1085
|
-
- childCount: number — number of direct children
|
|
1086
|
-
- descendants: Array of descendant summaries, each with:
|
|
1087
|
-
- id: string — element id (FQN)
|
|
1088
|
-
- name: string — element name
|
|
1089
|
-
- kind: string — element kind
|
|
1090
|
-
- title: string — human-readable title
|
|
1091
|
-
- depth: number — depth relative to root (1 = direct child)
|
|
1092
|
-
- tags: string[] — assigned tags
|
|
1093
|
-
- metadata: Record<string, string | string[]> — element metadata (filtered by metadataKeys if provided)
|
|
1094
|
-
- childCount: number — number of direct children
|
|
1095
|
-
- incomingCount: number — number of incoming relationships
|
|
1096
|
-
- outgoingCount: number — number of outgoing relationships
|
|
1097
|
-
- totalDescendants: number — total number of descendants (may differ from array length if truncated)
|
|
1098
|
-
- truncated: boolean — true if results were truncated due to exceeding the 200-result limit
|
|
1099
|
-
- truncatedByDepth: boolean — true if deeper descendants exist beyond maxDepth
|
|
329
|
+
\`\`\`
|
|
1100
330
|
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
- Safe to call repeatedly.
|
|
1104
|
-
- Limited to 200 descendants in the response.
|
|
1105
|
-
- Use metadataKeys to reduce response size when you only need specific metadata.
|
|
1106
|
-
- Descendants are returned in breadth-first order (closest to root first).
|
|
1107
|
-
- depth=1 means direct child, depth=2 means grandchild, etc.
|
|
1108
|
-
|
|
1109
|
-
Example response:
|
|
331
|
+
OUTPUT:
|
|
332
|
+
\`\`\`json
|
|
1110
333
|
{
|
|
1111
|
-
"
|
|
1112
|
-
|
|
1113
|
-
"
|
|
1114
|
-
"
|
|
1115
|
-
"
|
|
1116
|
-
},
|
|
1117
|
-
"descendants": [
|
|
1118
|
-
{
|
|
1119
|
-
"id": "top.planner.nodeA",
|
|
1120
|
-
"name": "nodeA",
|
|
1121
|
-
"kind": "cgf-node",
|
|
1122
|
-
"title": "nodeA :dwNodeTypeA",
|
|
1123
|
-
"depth": 1,
|
|
1124
|
-
"tags": ["is_in_dag", "target_asil_qm"],
|
|
1125
|
-
"metadata": { "target_asil": "QM", "safety_info_unit_asil": "QM" },
|
|
1126
|
-
"childCount": 0,
|
|
1127
|
-
"incomingCount": 3,
|
|
1128
|
-
"outgoingCount": 2
|
|
1129
|
-
}
|
|
334
|
+
"direction": "TB",
|
|
335
|
+
"ranks": [
|
|
336
|
+
{ "rank": "source", "nodes": ["n4"] },
|
|
337
|
+
{ "rank": "same", "nodes": ["n2", "n3"] },
|
|
338
|
+
{ "rank": "sink", "nodes": ["n6", "n8"] }
|
|
1130
339
|
],
|
|
1131
|
-
"
|
|
1132
|
-
|
|
1133
|
-
|
|
340
|
+
"edgeMinlen": {
|
|
341
|
+
"e5": 0
|
|
342
|
+
},
|
|
343
|
+
"reverseRank": ["e4"],
|
|
344
|
+
"excludeFromRanking": ["e1"],
|
|
345
|
+
"edgeOrder": ["e3", "e4", "e5", "e6", "e7", "e1"],
|
|
346
|
+
"nodeOrder": ["n4", "n2", "n3", "n6", "n7", "n8"],
|
|
347
|
+
"reasoning": "I reversed [e4] as it moves [n4] to the top, pushes [n3] to the next row and balances layout, [e5] \`minlen=0\` to keep [n2][n3] on same rank"
|
|
1134
348
|
}
|
|
1135
|
-
|
|
349
|
+
\`\`\`
|
|
350
|
+
</example>`,userPrompt:`Analyze semantics and suggest layout hints for the following diagram. Return only JSON object without any additional text or markdown formatting.`};async function enhanceLayoutWithAI(e,t,r){try{cg.debug`generating AI layout hints for ${e.id} using ${t.name}`;let{serialized:i,mapping:a}=prepareLLMInput(e);return parseOutput(await t.sendRequest({..._g,view:e,mapping:a,diagram:JSON.stringify(i)},r),{mapping:a,view:e})}catch(e){cg.warn(`AI layout enhancement failed`,{error:e});return}}function applySemanticLayoutTool(e){let t=useLanguageServices();return e.registerTool(`apply-semantic-layout`,{description:`Apply semantic layout to the likec4 view`,inputSchema:mcpToolSchema({projectId:ci(z.string().default(`default`).describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(A(`id`))),viewId:ci(z.string().describe(`View ID to apply semantic layout to`),async(e,r)=>{let i=r?.arguments?.projectId??t.projectsManager.default.id,a=await t.computedModel(i);if(!a)return[];let s=e??``;return Array.from(a.views()).filter(e=>e.id.startsWith(s)).map(A(`id`))})}),outputSchema:mcpToolSchema({reasoning:z.string().describe(`Reasoning behind the layout changes`),snapshotUri:z.string().nullish().describe(`Where snapshot was saved (after applying layout)`)})},async(r,i)=>{let a=t.projectsManager.ensureProjectId(r.projectId);a!==r.projectId&&await e.sendLoggingMessage({level:`notice`,data:`Using project "${a}" instead of "${r.projectId}"`},i.sessionId);let s=await t.computedModel(a),c=s.findView(r.viewId);if(!c)return toolError(`View "${r.viewId}" not found in project "${a}"`);let l=await enhanceLayoutWithAI(c.$view,{name:`MCP`,async sendRequest({systemPrompt:e,userPrompt:t,diagram:r}){let a=await i.sendRequest({method:`sampling/createMessage`,params:{maxTokens:2e4,includeContext:`none`,systemPrompt:e,messages:[{role:`user`,content:{type:`text`,text:t+`
|
|
351
|
+
|
|
352
|
+
`+r}}]}},z.object({content:z.object({type:z.literal(`text`),text:z.string()})}));return a.content.type===`text`?a.content.text:JSON.stringify(a.content)}},i.signal);if(!l)return await e.sendLoggingMessage({level:`error`,data:`Failed to generate layout hints`},i.sessionId),toolError(`Failed to generate layout hints`);await e.sendLoggingMessage({level:`info`,data:`Applying semantic layout...`},i.sessionId);let u=await t.views.layouter.aiLayout({view:c.$view,styles:s.$styles},l),p=await t.editor.applyChange({change:{op:`save-view-snapshot`,layout:u.diagram},viewId:c.id,projectId:a});return await e.sendLoggingMessage({level:`info`,data:`Layout applied successfully`},i.sessionId),{content:[],structuredContent:{reasoning:l.reasoning,...!!p.location&&{snapshotUri:p.location.uri.toString()}}}}),e}const vg=tg.extend({description:z.string().nullable().describe(`Element description`),technology:z.string().nullable().describe(`Element technology`),shape:z.string().describe(`Rendered shape`),color:z.string().describe(`Rendered color`),children:z.array(z.string()).describe(`Direct child element ids`),incomingCount:z.number().describe(`Number of incoming relationships`),outgoingCount:z.number().describe(`Number of outgoing relationships`),links:rg,sourceLocation:ng}),yg=likec4Tool({name:`batch-read-elements`,description:`Read summaries of up to 50 elements in one call: properties, metadata, children, relationship counts, the views that include them, links and source location. Ids not found are listed in notFound instead of failing the call. Use read-element only when you also need relationships, deployedInstances, defaultView or project.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Batch read elements`},inputSchema:{ids:z.array(z.string()).min(1).max(50).describe(`Array of element ids (FQNs) to read (max 50)`),project:ig},outputSchema:{elements:z.array(vg),notFound:z.array(z.string()).describe(`Element ids that were not found`)}})(async(e,t)=>{invariant(t.ids.length<=50,`Maximum 50 element ids per call`);let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r),a=mkLocate(e,r),s=[],c=[];for(let e of t.ids){let t=i.findElement(e);t?s.push({...serializeElement(t),description:t.description.text,technology:t.technology,shape:t.shape,color:t.color,children:[...t.children()].map(e=>e.id),incomingCount:t.allIncoming.size,outgoingCount:t.allOutgoing.size,links:serializeLinks(t),sourceLocation:a({element:t.id})}):c.push(e)}return{elements:s,notFound:c}}),bg=z.object({id:z.string(),kind:z.string(),title:z.string(),description:z.string().nullable(),technology:z.string().nullable(),shape:z.string(),color:z.string()}),xg=z.object({element1:bg,element2:bg,propertyDiffs:z.array(z.object({property:z.string().describe(`Property name`),element1Value:z.string().nullable().describe(`Value in element1`),element2Value:z.string().nullable().describe(`Value in element2`)})).describe(`Properties that differ between the two elements`),tags:z.object({onlyInElement1:z.array(z.string()).describe(`Tags present only in element1`),onlyInElement2:z.array(z.string()).describe(`Tags present only in element2`),common:z.array(z.string()).describe(`Tags present in both elements`)}),metadata:z.object({onlyInElement1:z.record(z.string(),z.union([z.string(),z.array(z.string())])).describe(`Metadata keys only in element1`),onlyInElement2:z.record(z.string(),z.union([z.string(),z.array(z.string())])).describe(`Metadata keys only in element2`),different:z.array(z.object({key:z.string(),element1Value:z.union([z.string(),z.array(z.string())]),element2Value:z.union([z.string(),z.array(z.string())])})).describe(`Metadata keys present in both but with different values`),common:z.record(z.string(),z.union([z.string(),z.array(z.string())])).describe(`Metadata keys with identical values in both`)}),relationships:z.object({incomingOnlyElement1:z.number().describe(`Count of unique source elements sending to element1 only`),incomingOnlyElement2:z.number().describe(`Count of unique source elements sending to element2 only`),incomingShared:z.number().describe(`Count of unique source elements sending to both`),outgoingOnlyElement1:z.number().describe(`Count of unique target elements receiving from element1 only`),outgoingOnlyElement2:z.number().describe(`Count of unique target elements receiving from element2 only`),outgoingShared:z.number().describe(`Count of unique target elements receiving from both`)})}),Sg=likec4Tool({name:`element-diff`,description:`Compare two elements of the same project: properties that differ, tags and metadata on each side or shared, and incoming and outgoing relationship counts on each side or shared. Useful for seeing why two similar elements differ.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Compare two elements`},inputSchema:{element1Id:z.string().describe(`First element id (FQN)`),element2Id:z.string().describe(`Second element id (FQN)`),project:ig},outputSchema:xg.shape})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r),a=i.findElement(t.element1Id);invariant(a,`Element "${t.element1Id}" not found in project "${r}"`);let s=i.findElement(t.element2Id);invariant(s,`Element "${t.element2Id}" not found in project "${r}"`);let c=[],l=[{name:`kind`,get:e=>e.kind},{name:`title`,get:e=>e.title},{name:`description`,get:e=>e.description.text},{name:`technology`,get:e=>e.technology},{name:`shape`,get:e=>e.shape},{name:`color`,get:e=>e.color}];for(let e of l){let t=e.get(a),r=e.get(s);t!==r&&c.push({property:e.name,element1Value:t,element2Value:r})}let u=new Set(a.tags),p=new Set(s.tags),m=[],h=[],g=[];for(let e of u)p.has(e)?m.push(e):h.push(e);for(let e of p)u.has(e)||g.push(e);let _=a.getMetadata(),v=s.getMetadata(),y=/* @__PURE__ */ new Set([...Object.keys(_),...Object.keys(v)]),b={},x={},S=[],ee={};for(let e of y){let t=_[e],r=v[e];t!==void 0&&r===void 0?b[e]=t:t===void 0&&r!==void 0?x[e]=r:t!==void 0&&r!==void 0&&(JSON.stringify(t)===JSON.stringify(r)?ee[e]=t:S.push({key:e,element1Value:t,element2Value:r}))}let te=new Set([...a.incoming()].map(e=>e.source.id)),ne=new Set([...s.incoming()].map(e=>e.source.id)),re=new Set([...a.outgoing()].map(e=>e.target.id)),C=new Set([...s.outgoing()].map(e=>e.target.id)),ie=0,ae=0,w=0;for(let e of te)ne.has(e)?ie++:ae++;for(let e of ne)te.has(e)||w++;let oe=0,T=0,se=0;for(let e of re)C.has(e)?oe++:T++;for(let e of C)re.has(e)||se++;return{element1:{id:a.id,kind:a.kind,title:a.title,description:a.description.text,technology:a.technology,shape:a.shape,color:a.color},element2:{id:s.id,kind:s.kind,title:s.title,description:s.description.text,technology:s.technology,shape:s.shape,color:s.color},propertyDiffs:c,tags:{onlyInElement1:h,onlyInElement2:g,common:m},metadata:{onlyInElement1:b,onlyInElement2:x,different:S,common:ee},relationships:{incomingOnlyElement1:ae,incomingOnlyElement2:w,incomingShared:ie,outgoingOnlyElement1:T,outgoingOnlyElement2:se,outgoingShared:oe}}}),Cg=likec4Tool({name:`find-relationship-paths`,description:`Find chains of relationships from a source element to a target element, shortest first, up to maxDepth hops and at most 100 paths. Follows direct relationships only, unless includeIndirect adds implied relationships through nested elements. Source and target must differ; no connection returns an empty list.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationship paths`},inputSchema:{sourceId:z.string().describe(`Source element FQN`),targetId:z.string().describe(`Target element FQN`),maxDepth:z.number().int().min(1).max(5).optional().default(3).describe(`Maximum path length (default: 3, max: 5)`),includeIndirect:z.boolean().optional().default(!1).describe(`Include indirect (implied) relationships through nested elements (default: false)`),project:ig},outputSchema:{paths:z.array(z.object({length:z.number().describe(`Number of hops in the path`),steps:z.array(z.object({source:z.string().describe(`Source element FQN`),target:z.string().describe(`Target element FQN`),relationship:z.object({kind:z.string().nullable().describe(`Relationship kind`),title:z.string().nullable().describe(`Relationship title`),description:z.string().nullable().describe(`Relationship description`),technology:z.string().nullable().describe(`Relationship technology`),tags:z.array(z.string()).describe(`Relationship tags`)})})).describe(`Ordered sequence of relationships in the path`)}))}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r),a=i.findElement(t.sourceId);invariant(a,`Source element "${t.sourceId}" not found in project "${r}"`);let s=i.findElement(t.targetId);invariant(s,`Target element "${t.targetId}" not found in project "${r}"`),invariant(a.id!==s.id,`Source and target must be different elements`);let c=t.maxDepth,l=t.includeIndirect?`all`:`direct`,u=[{elementId:a.id,path:[],visited:/* @__PURE__ */ new Set([a.id])}],p=[];for(;u.length>0&&p.length<100;){let e=u.shift();if(e.path.length>=c)continue;let t=i.findElement(e.elementId);if(t)for(let r of t.outgoing(l)){let t=r.target.id;if(t===s.id){let t={source:r.source.id,target:r.target.id,relationship:{kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags]}};if(p.push({length:e.path.length+1,steps:[...e.path,t]}),p.length>=100)break;continue}if(e.visited.has(t))continue;let i={source:r.source.id,target:r.target.id,relationship:{kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags]}};u.push({elementId:t,path:[...e.path,i],visited:/* @__PURE__ */ new Set([...e.visited,t])})}}return p.sort((e,t)=>e.length-t.length),{paths:p}}),wg=z.object({id:z.string(),title:z.string(),kind:z.string()}),Tg=z.object({type:z.enum([`direct`,`indirect`]).describe(`Type of relationship, "direct" for direct relationships, "indirect" for relationships through nested elements`),source:wg,target:wg,kind:z.string().nullable().describe(`Relationship kind`),title:z.string().nullable().describe(`Relationship title`),description:z.string().nullable().describe(`Relationship description`),technology:z.string().nullable().describe(`Relationship technology`),tags:z.array(z.string()).describe(`Relationship tags`),includedInViews:ag.describe(`Views that include this relationship`),sourceLocation:ng}),Eg=likec4Tool({name:`find-relationships`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationships between two elements`},description:`Find the relationships between two elements: direct ones between them, and indirect ones through their nested elements. Each comes with kind, title, technology, tags, the views it appears in and source location. Result order is not guaranteed. For multi-hop chains, use find-relationship-paths.`,inputSchema:{element1:z.string().describe(`Element ID (FQN)`),element2:z.string().describe(`Element ID (FQN)`),project:ig},outputSchema:{found:z.array(Tg)}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project);if(isSameHierarchy(t.element1,t.element2))throw Error(`No relationships possible between parent-child`);let i=[],a=await e.computedModel(r),s=a.findElement(t.element1);invariant(s,`Element "${t.element1}" not found in project "${r}"`);let c=a.findElement(t.element2);invariant(c,`Element "${t.element2}" not found in project "${r}"`);let l=mkLocate(e,r),u=findConnection$3(s,c,`both`).flatMap(e=>[...e.relations]);for(let e of u){let t=e.source===s&&e.target===c||e.source===c&&e.target===s;i.push({type:t?`direct`:`indirect`,source:{id:e.source.id,title:e.source.title,kind:e.source.kind},target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags],includedInViews:includedInViews(e.views()),sourceLocation:l({relation:e.id})})}return{found:i}}),Dg=likec4Tool({name:`list-projects`,description:`List the LikeC4 projects in the workspace. Pass a project's id as the "project" argument of other tools.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List projects`},inputSchema:{},outputSchema:{projects:z.array(z.object({id:z.string(),title:z.string(),folder:z.string(),sources:z.array(z.string())}))}})(async e=>({projects:e.projects().map(e=>({id:e.id,title:e.title,folder:e.folder.fsPath,sources:e.documents.map(e=>e.fsPath)}))}));function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var r=Error();return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},t={},r=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var i=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(i===void 0&&(i=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var a=i;if(typeof i!=`function`)throw TypeError(`Object is not disposable.`);a&&(i=function o(){try{a.call(t)}catch(e){return Promise.reject(e)}}),r.push({v:t,d:i,a:e})}else e&&r.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var i,a=this.e,s=0;function next(){for(;i=r.pop();)try{if(!i.a&&s===1)return s=0,r.push(i),Promise.resolve().then(next);if(i.d){var e=i.d.call(i.v);if(i.a)return s|=2,Promise.resolve(e).then(next,err)}else s|=1}catch(e){return err(e)}if(s===1)return a===t?Promise.resolve():Promise.reject(a);if(a!==t)throw a}function err(r){return a=a===t?r:new e(r,a),next()}return next()}}}const Og=/^\s*view\s+([A-Za-z_][\w-]*)/;function extractViewId(e){let t=Og.exec(e);return t?t[1]:null}function wrapAsViewsBlock(e){return`views {\n${e}\n}\n`}function toPortablePath(e){return e.split(hr).join(`/`)}function toVirtualSourcePath(e,t,r){let i=toPortablePath(pr(e,t));return i===``||i.startsWith(`..`)?r:i}function formatDiagnostics(e){return e.map(e=>`- line ${e.range.start.line+1}, column ${e.range.start.character+1}: ${e.message}`).join(`
|
|
353
|
+
`)}function previewViewTool(e){return fi(e,`preview-view`,{title:`Preview View`,description:'Renders a draft view from DSL against an existing project\'s real elements, without saving anything. The DSL must be a single element view, `view <id> ... { ... }`, with a new id: an existing id is rejected (use "render-view" for saved views), and a dynamic or deployment view fails with a generic "could not find a `view <id>`" error. Custom theme and style extensions are not applied. Use it to iterate on a view before creating it for real.',inputSchema:mcpToolSchema({dsl:z.string().describe("A single `view <id> ... { ... }` LikeC4 DSL definition"),project:ig,fullModel:z.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`)}),outputSchema:mcpToolSchema({id:z.string(),title:z.string(),project:z.string(),view:z.record(z.string(),z.unknown()),model:z.record(z.string(),z.unknown())}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Preview view`},_meta:{ui:{resourceUri:og}}},async e=>{try{var t=_usingCtx();let r=useLanguageServices(),i=r.projectsManager.ensureProjectId(e.project),a=extractViewId(e.dsl);if(!a)return toolError("Could not find a `view <id> ...` declaration at the start of `dsl`. Example: `view myView of someElement { include * }`");let s=r.project(i);if((await r.computedModel(i))?.findView(a))return toolError(`View "${a}" already exists in the project. Use a different view id for the preview, or use "render-view" to render the existing view.`);let c={};for(let[e,t]of s.documents.entries()){let i=toVirtualSourcePath(s.folder.fsPath,t.fsPath,`seed-${e}.c4`);c[i]=r.documentText(t.toString())??``}let l=`${ur()}.c4`;c[l]=wrapAsViewsBlock(e.dsl);let u=t.a(await fromSources(c,{printErrors:!1,throwIfInvalid:!1})),p=u.getErrors();if(p.length>0)return toolError(`Failed to build preview:\n${formatDiagnostics(p)}`);let m=await u.computedModel(),h=m.findView(a);if(!h)return toolError(`View "${a}" was not found after building the preview.`);let g=u.projectsManager.ensureProjectId(ProjectId(m.$data.projectId)),_=await u.viewsService.layoutView({viewId:h.id,projectId:g});if(!_)return toolError(`Failed to layout preview view "${a}".`);let v=h.title??h.id;return{content:[{type:`text`,text:`Rendered preview of view "${v}"`}],structuredContent:buildRenderPayload({projectId:i,viewId:h.id,title:v,layoutedView:_.diagram,model:m,fullModel:e.fullModel})}}catch(e){t.e=e}finally{await t.d()}}),e}const kg=z.enum([`exact`,`contains`,`exists`]),Ag=likec4Tool({name:`query-by-metadata`,description:`Find elements and deployment nodes by metadata. matchMode "exact" (default) compares the value case-sensitively, "contains" matches a substring case-insensitively, and "exists" matches any element with the key and ignores value. An array value matches if any item matches. At most 50 results.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by metadata`},inputSchema:{key:z.string().describe(`Metadata key to filter by`),value:z.string().optional().describe(`Metadata value to match (ignored for exists mode)`),matchMode:kg.optional().default(`exact`).describe(`Matching mode`),project:ig},outputSchema:{results:z.array(tg.extend({matchedValue:z.string().describe(`The metadata value that matched`)}))}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r),a=t.matchMode,s=[],matches=(e,t,r)=>{let i=Array.isArray(e)?e:[e];switch(r){case`exists`:return!0;case`exact`:return t!==void 0&&i.some(e=>e===t);case`contains`:{if(t===void 0)return!1;let e=t.toLowerCase();return i.some(t=>t.toLowerCase().includes(e))}default:return!1}},getMatchedValue=(e,t,r)=>{let i=Array.isArray(e)?e:[e];if(r===`exists`||t===void 0)return i[0]||``;if(r===`exact`)return i.find(e=>e===t)||i[0]||``;if(r===`contains`){let e=t.toLowerCase();return i.find(t=>t.toLowerCase().includes(e))||i[0]||``}return i[0]||``};for(let e of i.elements()){if(s.length>=50)break;let r=e.getMetadata();if(t.key in r){let i=r[t.key];i!==void 0&&matches(i,t.value,a)&&s.push({...serializeElement(e),matchedValue:getMatchedValue(i,t.value,a)})}}if(s.length<50)for(let e of i.deployment.elements()){if(s.length>=50)break;let r=e.getMetadata();if(t.key in r){let i=r[t.key];i!==void 0&&matches(i,t.value,a)&&s.push({...serializeElement(e),matchedValue:getMatchedValue(i,t.value,a)})}}return{results:s}}),jg=likec4Tool({name:`query-by-tag-pattern`,description:`Find elements whose tags match a pattern, for structured tag naming such as "team_*". matchMode is "prefix" (default), "contains" or "suffix", case-insensitive. Returns the matching tags per element and every distinct matching tag. At most 50 results. For exact tags with boolean logic, use query-by-tags.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tag pattern`},inputSchema:{pattern:z.string().min(1).describe(`Tag pattern to match`),matchMode:z.enum([`prefix`,`contains`,`suffix`]).optional().default(`prefix`).describe(`Pattern matching mode (default: prefix)`),project:ig},outputSchema:{results:z.array(tg.extend({matchedTags:z.array(z.string()).describe(`Tags that matched the pattern`)})),truncated:z.boolean().describe(`True if results were truncated`),matchedTagValues:z.array(z.string()).describe(`All unique tag values matching the pattern across all elements`)}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r),a=t.pattern.toLowerCase(),matchesTag=e=>{let r=e.toLowerCase();switch(t.matchMode){case`prefix`:return r.startsWith(a);case`contains`:return r.includes(a);case`suffix`:return r.endsWith(a)}},s=[],c=!1,l=/* @__PURE__ */ new Set;for(let e of i.elements()){let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>l.add(e)),s.length>=50){c=!0;continue}s.push({...serializeElement(e),matchedTags:t})}}for(let e of i.deployment.elements()){if(!isDeploymentNodeModel(e))continue;let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>l.add(e)),s.length>=50){c=!0;continue}s.push({...serializeElement(e),matchedTags:t})}}return{results:s,truncated:c,matchedTagValues:[...l].sort((e,t)=>e.localeCompare(t))}}),Mg=likec4Tool({name:`query-by-tags`,description:`Find elements and deployment nodes by tags with boolean logic: allOf (AND), anyOf (OR) and noneOf (NOT), combined with AND. At least one condition is required, and tags are case-sensitive. At most 50 results. For partial tag names, use query-by-tag-pattern.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tags`},inputSchema:{allOf:z.array(z.string()).optional().describe(`Element must have ALL these tags (AND)`),anyOf:z.array(z.string()).optional().describe(`Element must have ANY of these tags (OR)`),noneOf:z.array(z.string()).optional().describe(`Element must have NONE of these tags (NOT)`),project:ig},outputSchema:{results:z.array(tg),truncated:z.boolean().describe(`True if results were truncated due to exceeding the 50-result limit`)}})(async(e,t)=>{invariant(t.allOf&&t.allOf.length>0||t.anyOf&&t.anyOf.length>0||t.noneOf&&t.noneOf.length>0,`At least one condition (allOf, anyOf, or noneOf) must be specified with at least one tag`);let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r),a=[],s=!1,matchesTags=e=>{let r=e instanceof Set?e:new Set(e);return!(t.allOf&&t.allOf.length>0&&!t.allOf.every(e=>r.has(e))||t.anyOf&&t.anyOf.length>0&&!t.anyOf.some(e=>r.has(e))||t.noneOf&&t.noneOf.length>0&&t.noneOf.some(e=>r.has(e)))};for(let e of i.elements()){if(a.length>=50){s=!0;break}matchesTags(e.tags)&&a.push(serializeElement(e))}if(!s)for(let e of i.deployment.elements()){if(a.length>=50){s=!0;break}isDeploymentNodeModel(e)&&matchesTags(e.tags)&&a.push(serializeElement(e))}return{results:a,truncated:s}}),Ng=z.enum([`ancestors`,`descendants`,`siblings`,`children`,`parent`,`incomers`,`outgoers`]),Pg=likec4Tool({name:`query-graph`,description:`One-step graph query around an element. Hierarchy: ancestors (up to the root), descendants (recursive), siblings, children, parent (empty for a root element); includeIndirect is ignored for these. Relationships: incomers and outgoers, single hop; includeIndirect (default true) adds relationships of nested children. For recursive traversal, use query-incomers-graph or query-outgoers-graph. At most 100 results.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query element graph`},inputSchema:{elementId:z.string().describe(`Element id (FQN) to query`),queryType:Ng.describe(`Type of graph query`),includeIndirect:z.boolean().optional().default(!0).describe(`For incomers/outgoers: include indirect relationships (default: true)`),project:ig},outputSchema:{results:z.array(tg),truncated:z.boolean().describe(`True if results were truncated due to exceeding maximum limit`)}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=(await e.computedModel(r)).findElement(t.elementId);invariant(i,`Element "${t.elementId}" not found in project "${r}"`);let a=[],s=!1;switch(t.queryType){case`ancestors`:for(let e of i.ancestors()){if(a.length>=100){s=!0;break}a.push(serializeElement(e))}break;case`descendants`:for(let e of i.descendants()){if(a.length>=100){s=!0;break}a.push(serializeElement(e))}break;case`siblings`:for(let e of i.siblings()){if(a.length>=100){s=!0;break}a.push(serializeElement(e))}break;case`children`:for(let e of i.children()){if(a.length>=100){s=!0;break}a.push(serializeElement(e))}break;case`parent`:{let e=i.parent;e&&a.push(serializeElement(e));break}case`incomers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of i.incomers(e)){if(a.length>=100){s=!0;break}a.push(serializeElement(t))}break}case`outgoers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of i.outgoers(e)){if(a.length>=100){s=!0;break}a.push(serializeElement(t))}break}}return{results:a,truncated:s}}),Fg=z.object({elementId:z.string().describe(`ID of the incoming element`),relationshipLabel:z.string().optional().describe(`Label on the relationship`),technology:z.string().optional().describe(`Technology specified on the relationship`)}),Ig=likec4Tool({name:`query-incomers-graph`,description:`Recursive upstream traversal: every element that feeds into the target, directly or transitively, returned as one graph with each node's depth and incomers. Answers "what feeds into this?" in one call instead of repeated query-graph calls. Stops at maxDepth or maxNodes; if truncated is true, raise maxNodes or lower maxDepth.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete incomers graph`},inputSchema:{elementId:z.string().describe(`Target element id (FQN) to query incomers for`),includeIndirect:z.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:z.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:z.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:ig},outputSchema:{target:z.string().describe(`Target element id`),totalNodes:z.number().describe(`Total number of nodes in the graph`),maxDepth:z.number().describe(`Maximum depth reached`),truncated:z.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:z.record(z.string(),tg.extend({incomers:z.array(Fg).describe(`Incoming relationships with details`),depth:z.number().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r);invariant(i.findElement(t.elementId),`Element "${t.elementId}" not found in project "${r}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(i,t.elementId,`incoming`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:r,...i}=t;c[e]={...i,incomers:r}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),Lg=z.object({elementId:z.string().describe(`ID of the outgoing element`),relationshipLabel:z.string().optional().describe(`Label on the relationship`),technology:z.string().optional().describe(`Technology specified on the relationship`)}),Rg=likec4Tool({name:`query-outgoers-graph`,description:`Recursive downstream traversal: every element that consumes output from the target, directly or transitively, returned as one graph with each node's depth and outgoers. Answers "what depends on this?" (blast radius) in one call instead of repeated query-graph calls. Stops at maxDepth or maxNodes; if truncated is true, raise maxNodes or lower maxDepth.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete outgoers graph`},inputSchema:{elementId:z.string().describe(`Target element id (FQN) to query outgoers for`),includeIndirect:z.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:z.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:z.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:ig},outputSchema:{target:z.string().describe(`Target element id`),totalNodes:z.number().describe(`Total number of nodes in the graph`),maxDepth:z.number().describe(`Maximum depth reached`),truncated:z.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:z.record(z.string(),tg.extend({outgoers:z.array(Lg).describe(`Outgoing relationships with details`),depth:z.number().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=await e.computedModel(r);invariant(i.findElement(t.elementId),`Element "${t.elementId}" not found in project "${r}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(i,t.elementId,`outgoing`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:r,...i}=t;c[e]={...i,outgoers:r}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),zg=likec4Tool({name:`read-deployment`,description:`Read one deployment node or deployed instance: kind, tags, metadata, links, children (empty for an instance), the views that include it, the element a deployed instance instantiates, and source location.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read deployment entity`},inputSchema:{id:z.string().describe(`Deployment id (FQN)`),project:ig},outputSchema:{type:z.enum([`deployment-node`,`deployed-instance`]),id:z.string().describe(`Deployment id (FQN)`),kind:z.string().describe(`Deployment node kind, or element kind for deployed instances`),name:z.string(),title:z.string(),description:z.string().nullable(),technology:z.string().nullable(),tags:z.array(z.string()),project:z.string(),metadata:z.record(z.string(),z.union([z.string(),z.array(z.string())])),links:rg.describe(`External links associated with this deployment entity`),shape:z.string(),color:z.string(),children:z.array(z.string()).describe(`Children of this deployment node (Array of Deployment ids)`),includedInViews:ag.describe(`Views that include this deployment node`),instanceof:z.object({id:z.string().describe(`Element ID (FQN)`),title:z.string(),kind:z.string()}).nullable().describe(`If type is "deployed-instance", the referenced element`),sourceLocation:ng}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=(await e.computedModel(r)).deployment.findElement(t.id);invariant(i,`Deployment entity "${t.id}" not found in project "${r}"`);let a=mkLocate(e,r);return{type:i.isInstance()?`deployed-instance`:`deployment-node`,id:i.id,name:i.name,kind:i.kind,title:i.title,description:i.description.text,technology:i.technology,tags:[...i.tags],project:r,metadata:i.getMetadata(),links:serializeLinks(i),shape:i.shape,color:i.color,children:i.isInstance()?[]:[...i.children()].map(e=>e.id),includedInViews:includedInViews(i.views()),instanceof:i.isInstance()?{id:i.element.id,title:i.element.title,kind:i.element.kind}:null,sourceLocation:a({deployment:i.id})}}),Bg=likec4Tool({name:`read-element`,description:`Read one element in full: properties, metadata, links, children, the views that include it, its direct and indirect incoming and outgoing relationships, deployed instances and source location. For many elements, use batch-read-elements.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read element`},inputSchema:{id:z.string().describe(`Element id (FQN)`),project:ig},outputSchema:{id:z.string().describe(`Element id (FQN)`),kind:z.string().describe(`Element kind`),name:z.string().describe(`Element name`),title:z.string(),description:z.string().nullable(),technology:z.string().nullable(),tags:z.array(z.string()),project:z.string(),metadata:z.record(z.string(),z.union([z.string(),z.array(z.string())])),links:rg,shape:z.string(),color:z.string(),children:z.array(z.string()).describe(`Children of this element (Array of FQNs)`),defaultView:z.string().nullable().describe(`Name of the default view of this element`),includedInViews:ag.describe(`Views that include this element`),relationships:z.object({incoming:z.array(z.object({source:z.object({id:z.string(),title:z.string(),kind:z.string()}).describe(`Source element of this relationship`),kind:z.string().nullable().describe(`Relationship kind`),target:z.string().describe(`Target element id (FQN), either this element or nested element, if relationship is indirect`),title:z.string().nullable().describe(`Relationship title`),description:z.string().nullable().describe(`Relationship description`),technology:z.string().nullable().describe(`Relationship technology`),tags:z.array(z.string()).describe(`Relationship tags`)})).describe(`Incoming relationships of this element (direct and indirect, incoming to nested elements)`),outgoing:z.array(z.object({source:z.string().describe(`Source element id (FQN), either this element or nested element, if relationship is indirect`),target:z.object({id:z.string(),title:z.string(),kind:z.string()}).describe(`Target element of this relationship`),kind:z.string().nullable().describe(`Relationship kind`),title:z.string().nullable().describe(`Relationship title`),description:z.string().nullable().describe(`Relationship description`),technology:z.string().nullable().describe(`Relationship technology`),tags:z.array(z.string()).describe(`Relationship tags`)})).describe(`Outgoing relationships of this element (direct and indirect, outgoing from nested elements)`)}).describe(`Relationships of this element`),deployedInstances:z.array(z.string()).describe(`Deployed instances of this element (Array of Deployment FQNs)`),sourceLocation:ng}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=(await e.computedModel(r)).findElement(t.id);invariant(i,`Element "${t.id}" not found in project "${r}"`);let a=mkLocate(e,r);return{id:i.id,name:i.name,kind:i.kind,title:i.title,description:i.description.text,technology:i.technology,tags:[...i.tags],project:r,metadata:i.getMetadata(),links:serializeLinks(i),shape:i.shape,color:i.color,children:[...i.children()].map(e=>e.id),defaultView:i.defaultView?.id||null,includedInViews:includedInViews(i.views()),relationships:{incoming:[...i.incoming()].map(e=>({source:{id:e.source.id,title:e.source.title,kind:e.source.kind},kind:e.kind,target:e.target.id,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]})),outgoing:[...i.outgoing()].map(e=>({source:e.source.id,target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]}))},deployedInstances:[...i.deployments()].map(e=>e.id),sourceLocation:a({element:i.id})}}),Vg=likec4Tool({name:`read-project-summary`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read project summary`},description:`Overview of a LikeC4 project: its configuration, its specification (element, relationship and deployment kinds, tags, metadata keys), and every element, deployment entity and view with id, kind, title and tags. Use it to orient in a project before reading individual elements or views.`,inputSchema:{project:ig},outputSchema:{title:z.string(),folder:z.string(),sources:z.array(z.string()),config:eg.describe(`Project configuration`),specification:z.object({elementKinds:z.array(z.string()),relationshipKinds:z.array(z.string()),deploymentKinds:z.array(z.string()),tags:z.array(z.string()),metadataKeys:z.array(z.string())}),elements:z.array(z.object({id:z.string(),kind:z.string(),title:z.string(),tags:z.array(z.string())})).describe(`List of elements in the project`),deployments:z.array(z.discriminatedUnion(`type`,[z.object({type:z.literal(`deployment-node`),id:z.string().describe(`Node ID`),kind:z.string().describe(`Deployment node kind`),title:z.string().describe(`Node title`),tags:z.array(z.string())}),z.object({type:z.literal(`deployed-instance`),id:z.string().describe(`Node ID`),title:z.string().describe(`Node title`),tags:z.array(z.string()),referencedElementId:z.string().describe(`Element ID (FQN)`)})])).describe(`List of deployment nodes and deployed instances in the project`),views:z.array(z.object({id:z.string(),title:z.string(),type:z.enum([`element`,`deployment`,`dynamic`])}))}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=e.project(r),a=await e.computedModel(r);return{title:i.title,folder:i.folder.fsPath,sources:i.documents?.map(e=>e.fsPath)??[],config:serializeConfig(i.config),specification:{elementKinds:Te(a.specification.elements),relationshipKinds:Te(a.specification.relationships),deploymentKinds:Te(a.specification.deployments),tags:[...a.tags],metadataKeys:a.specification.metadataKeys??[]},elements:[...a.elements()].filter(e=>!e.imported).map(e=>({id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]})),deployments:[...a.deployment.elements()].map(e=>e.isInstance()?{type:`deployed-instance`,id:e.id,title:e.title,tags:[...e.tags],referencedElementId:e.element.id}:{type:`deployment-node`,id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]}),views:[...a.views()].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type}))}}),modelRef=e=>e.hasElement()?e.element.id:e.hasDeployment()?e.deployment.id:null,Hg=z.discriminatedUnion(`type`,[z.object({type:z.literal(`element`),id:z.string().describe(`Node ID`),elementId:z.string().describe(`Element ID (FQN)`),kind:z.string().describe(`Element kind`),title:z.string().describe(`Node title`),description:z.string().nullable(),technology:z.string().nullable(),children:z.array(z.string()).describe(`Children nodes, array of node IDs`),shape:z.string().describe(`Rendered shape`),color:z.string().describe(`Rendered color`),tags:z.array(z.string())}),z.object({type:z.literal(`deployment-node`),id:z.string().describe(`Node ID`),deploymentId:z.string().describe(`Deployment entity ID (FQN)`),kind:z.string().describe(`Deployment kind`),title:z.string().describe(`Node title`),description:z.string().nullable(),technology:z.string().nullable(),children:z.array(z.string()).describe(`Children nodes, array of node IDs`),shape:z.string().describe(`Rendered shape`),color:z.string().describe(`Rendered color`),tags:z.array(z.string())}),z.object({type:z.literal(`deployed-instance`),id:z.string().describe(`Node ID`),deploymentId:z.string().describe(`Deployment entity ID (FQN)`),title:z.string().describe(`Node title`),description:z.string().nullable(),technology:z.string().nullable(),referencedElement:z.object({id:z.string().describe(`Element ID (FQN)`),kind:z.string().describe(`Element kind`),title:z.string().describe(`Element title`)}),shape:z.string().describe(`Rendered shape`),color:z.string().describe(`Rendered color`),tags:z.array(z.string())})]),Ug=likec4Tool({name:`read-view`,description:`Read a view's structure: its nodes (elements, deployment nodes or deployed instances) and the edges between them, with source location. A view without a title returns its id as the title. Use render-view to show the diagram to the user.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read view`},inputSchema:{viewId:z.string().describe(`View id (name)`),project:ig},outputSchema:{id:z.string(),type:z.enum([`element`,`deployment`,`dynamic`]).describe(`View type`),title:z.string(),description:z.string().nullable(),tags:z.array(z.string()),project:z.string(),nodes:z.array(Hg),edges:z.array(z.object({source:z.string().describe(`Source node`),target:z.string().describe(`Target node`),label:z.string().nullable(),description:z.string().nullable(),technology:z.string().nullable(),tags:z.array(z.string())})).describe(`Edge represents relationship between nodes`),sourceLocation:ng}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=e.project(r),a=(await e.computedModel(r)).findView(t.viewId);if(!a)throw Error(`View with ID '${t.viewId}' not found in project ${i.id}`);let s=mkLocate(e,i.id);return{id:a.id,type:a.$view._type,title:a.title??a.id,description:a.description.text,tags:[...a.tags],project:i.id,nodes:[...a.nodes()].flatMap(e=>{let t={id:e.id,title:e.title,description:e.description.text,technology:e.technology,shape:e.shape,color:e.color,tags:[...e.tags]};return e.hasDeployedInstance()?{...t,type:`deployed-instance`,deploymentId:e.deployment.id,referencedElement:{id:e.deployment.element.id,kind:e.deployment.element.kind,title:e.deployment.element.title}}:e.hasDeployment()?{...t,type:`deployment-node`,kind:e.deployment.kind,deploymentId:e.deployment.id,children:[...e.children()].map(e=>e.id)}:e.hasElement()?{...t,type:`element`,elementId:e.element.id,kind:e.element.kind,children:[...e.children()].flatMap(e=>modelRef(e)??[])}:[]}),edges:[...a.edges()].map(e=>({source:e.source.id,target:e.target.id,label:e.label,description:e.description.text,technology:e.technology,tags:[...e.tags]})),sourceLocation:s({view:a.id})}}),Wg=z.array(z.discriminatedUnion(`type`,[z.object({type:z.literal(`element`),project:z.string().describe(`Project ID`),id:z.string().describe(`Element ID (FQN)`),name:z.string().describe(`Element name`),kind:z.string(),title:z.string(),technology:z.string().nullable(),shape:z.string(),includedInViews:ag,metadata:z.record(z.string(),z.union([z.string(),z.array(z.string())])),tags:z.array(z.string())}),z.object({type:z.literal(`deployment-node`),project:z.string().describe(`Project ID`),id:z.string().describe(`Deployment ID (FQN)`),name:z.string().describe(`Deployment name`),kind:z.string(),title:z.string(),technology:z.string().nullable(),shape:z.string(),includedInViews:ag,metadata:z.record(z.string(),z.union([z.string(),z.array(z.string())])),tags:z.array(z.string())})])),Gg=likec4Tool({name:`search-element`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Search elements`},description:`Search elements and deployment nodes across all projects by id, title, kind, shape, tag or metadata key. Returns the total number of matches and the first 20. Pass the ids found to read-element or other tools.`,inputSchema:{search:z.string().min(2,`Search must be at least 2 characters long`).describe(`Case-insensitive. "kind:<value>" or "shape:<value>" matches a kind or shape exactly, "meta:<key>" elements with that metadata key, "#<value>" tags containing the value; anything else matches id (FQN) or title.`)},outputSchema:{total:z.number(),found:Wg}})(async(e,t)=>{let r=e.projects(),i=[],a=t.search.toLowerCase(),predicate;a.startsWith(`kind:`)?(a=a.slice(5),$.debug(`search by kind: {search}`,{search:a}),predicate=e=>e.kind.toLowerCase()===a):a.startsWith(`shape:`)?(a=a.slice(6),$.debug(`search by shape: {search}`,{search:a}),predicate=e=>e.shape.toLowerCase()===a):a.startsWith(`meta:`)?(a=a.slice(5),$.debug(`search by metadata: {search}`,{search:a}),predicate=e=>!!e.getMetadata(a)):a.startsWith(`#`)?(a=a.slice(1),$.debug(`search by tag: {search}`,{search:a}),predicate=e=>e.tags.some(e=>e.toLowerCase().includes(a))):($.debug(`search by id/title: {search}`,{search:a}),predicate=e=>e.id.toLowerCase().includes(a)||e.title.toLowerCase().includes(a));for(let t of r)try{let r=await e.computedModel(t.id);for(let e of ifilter(r.elements(),e=>!e.imported&&predicate(e)))i.push({type:`element`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())});for(let e of ifilter(r.deployment.nodes(),predicate))i.push({type:`deployment-node`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())})}catch(e){$.error(`Error searching in project ${t.id}:`,{error:e})}return{total:i.length,found:i.slice(0,20)}}),Kg=z.object({id:z.string().describe(`Element id (FQN)`),name:z.string().describe(`Element name`),kind:z.string().describe(`Element kind`),title:z.string().describe(`Human-readable title`),depth:z.number().describe(`Depth relative to the root element (1 = direct child)`),tags:z.array(z.string()).describe(`Assigned tags`),metadata:z.record(z.string(),z.union([z.string(),z.array(z.string())])).describe(`Element metadata`),childCount:z.number().describe(`Number of direct children`),incomingCount:z.number().describe(`Number of incoming relationships`),outgoingCount:z.number().describe(`Number of outgoing relationships`)}),qg=likec4Tool({name:`subgraph-summary`,description:`Summarize all descendants of an element in one call, breadth-first, each with depth (1 = direct child), tags, metadata, and child and relationship counts. At most 200 descendants; truncated and truncatedByDepth say what was cut. Pass metadataKeys to return only those keys. Cheaper than read-element per descendant.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Subgraph summary`},inputSchema:{elementId:z.string().describe(`Parent element id (FQN) whose descendants to summarize`),maxDepth:z.number().int().min(1).max(20).optional().default(10).describe(`Maximum depth of descendants to include (default: 10, max: 20)`),metadataKeys:z.array(z.string()).optional().describe(`If provided, only include these metadata keys in the response`),project:ig},outputSchema:{root:z.object({id:z.string(),kind:z.string(),title:z.string(),childCount:z.number()}),descendants:z.array(Kg),totalDescendants:z.number().describe(`Total number of descendants found`),truncated:z.boolean().describe(`True if results were truncated due to exceeding the limit`),truncatedByDepth:z.boolean().describe(`True if deeper descendants exist beyond maxDepth`)}})(async(e,t)=>{let r=e.projectsManager.ensureProjectId(t.project),i=(await e.computedModel(r)).findElement(t.elementId);invariant(i,`Element "${t.elementId}" not found in project "${r}"`);let a=t.maxDepth,s=t.metadataKeys,c=[],l=0,u=!1,p=!1,m=[],h=[...i.children()];for(let e of h)m.push({element:e,depth:1});for(;m.length>0;){let{element:e,depth:t}=m.shift();if(t>a){p=!0;continue}l++;let r=[...e.children()];if(c.length<200){let i=e.getMetadata(),a=s?Object.fromEntries(s.filter(e=>e in i).map(e=>[e,i[e]])):i;c.push({id:e.id,name:e.name,kind:e.kind,title:e.title,depth:t,tags:[...e.tags],metadata:a,childCount:r.length,incomingCount:[...e.incoming()].length,outgoingCount:[...e.outgoing()].length})}else u=!0;for(let e of r)m.push({element:e,depth:t+1})}return{root:{id:i.id,kind:i.kind,title:i.title,childCount:h.length},descendants:c,totalDescendants:l,truncated:u,truncatedByDepth:p}});function createMCPServer(e){let t=new oi({name:`LikeC4`,version:$h},{instructions:`LikeC4 MCP – query and navigate LikeC4 models.
|
|
1136
354
|
|
|
1137
355
|
Conventions:
|
|
1138
356
|
- All tools are read-only and idempotent.
|
|
@@ -1154,7 +372,7 @@ Available tools:
|
|
|
1154
372
|
- query-by-metadata — Search elements by metadata key-value pairs with exact/contains/exists matching. Input: { key, value?, matchMode?, project? }.
|
|
1155
373
|
- query-by-tags — Advanced tag filtering with boolean logic (allOf, anyOf, noneOf). Input: { allOf?, anyOf?, noneOf?, project? }.
|
|
1156
374
|
- find-relationship-paths — Discover all paths (chains of relationships) between two elements with BFS traversal. Input: { sourceId, targetId, maxDepth?, includeIndirect?, project? }.
|
|
1157
|
-
- batch-read-elements — Read details of multiple elements in a single call, reducing round-trips. Input: { ids, project? }.
|
|
375
|
+
- batch-read-elements — Read details of multiple elements in a single call, reducing round-trips. Includes links and sourceLocation, same as read-element. Input: { ids, project? }.
|
|
1158
376
|
- query-by-tag-pattern — Search elements by tag prefix/contains/suffix patterns. Input: { pattern, matchMode?, project? }.
|
|
1159
377
|
- element-diff — Compare two elements side-by-side showing differences in properties, tags, metadata, and relationships. Input: { element1Id, element2Id, project? }.
|
|
1160
378
|
- subgraph-summary — Compact summary of all descendants of a parent element with metadata, tags, and relationship counts. Input: { elementId, maxDepth?, metadataKeys?, project? }.
|
|
@@ -1167,4 +385,4 @@ Instructions:
|
|
|
1167
385
|
- If response returns "sourceLocation", provide link to this location in the editor
|
|
1168
386
|
|
|
1169
387
|
Full documentation: https://likec4.dev/llms-full.txt
|
|
1170
|
-
`,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{
|
|
388
|
+
`,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{ga.error(loggable(e))},N(t,setMcpServerCtx,Dg,Vg,Bg,zg,Ug,Gg,Eg,Cg,ue(Pg,Ig,Rg,Ag,Mg,jg),ue(yg,Sg,qg),ue(applySemanticLayoutPrompt,applySemanticLayoutTool,renderViewTool,previewViewTool),ue(projectResource,renderViewResource))}var StdioLikeC4MCPServer=class{services;options;transport=void 0;_mcp=void 0;constructor(e,t={}){this.services=e,this.options=t}get mcp(){if(!this._mcp)throw Error(`MCP server is not started`);return this._mcp}get isStarted(){return this.transport!==void 0}get port(){return NaN}async dispose(){await this.stop()}async start(){if(!this.transport){$.info(`Starting MCP stdio server`),this._mcp=createMCPServer(this.services),setMcpServerCtx(this._mcp),this.transport=new ai(this.options.stdin,this.options.stdout);try{await this._mcp.connect(this.transport)}catch(e){throw await this.stop(),e}$.info(`LikeC4 MCP Server running on stdio`)}}async stop(){if(this.transport)try{$.info(`Stopping MCP stdio server`),await this.transport.close(),this._mcp&&await this._mcp.close()}finally{this._mcp=void 0,this.transport=void 0,setMcpServerCtx(void 0)}}};async function createHonoApp(e){let t=new gi;t.use(`*`,_i({origin:`*`,allowHeaders:[`Content-Type`,`mcp-session-id`,`Last-Event-ID`,`mcp-protocol-version`],exposeHeaders:[`mcp-session-id`,`mcp-protocol-version`]})),t.get(`/health`,e=>e.json({status:`ok`}));let r=e();setMcpServerCtx(r);let i=new mi({eventStore:new pi({})});return t.all(`/mcp`,async e=>(r.isConnected()||await r.connect(i),await i.handleRequest(e))),t.notFound(e=>($.debug(`${e.req.method} ${e.req.url} not found`),e.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not found.`},id:null},{status:404}))),t.onError((e,t)=>($.error(loggable(e)),t.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null},{status:500}))),t}async function startServer(e){let{factory:t,port:r}=e,i=await createHonoApp(t);return new Promise((e,t)=>{let a=hi({fetch:i.fetch,hostname:`0.0.0.0`,port:r}).prependOnceListener(`error`,t).prependOnceListener(`listening`,()=>{a.removeListener(`error`,t),e(a.unref())})})}var StreamableLikeC4MCPServer=class{services;_port;server=void 0;constructor(e,t=33335){this.services=e,this._port=t}get mcp(){throw Error(`StreamableLikeC4MCPServer has access to McpServer only during the request`)}get isStarted(){return this.server?.listening===!0}get port(){return this._port}async dispose(){await this.stop()}async start(e=this._port){if(this.server){if(this.port===e)return;await this.stop()}$.info(`Starting MCP server on port {port}`,{port:e}),this._port=e,this.server=await startServer({factory:()=>createMCPServer(this.services),port:e}),$.info(`MCP server ready at http://0.0.0.0:{port}/mcp`,{port:e})}stop(){let e=this.server;return e?($.info(`Stopping MCP server`),this.server=void 0,setMcpServerCtx(void 0),new Promise(t=>{e.close(e=>{e?$.error(`Failed to stop MCP server`,{err:e}):$.info(`MCP server stopped`),t()})})):($.info(`MCP server is not running, nothing to stop`),Promise.resolve())}};async function initLikeC4MCP(e){let t=Yi(e,{workspacePath:`.`,mcp:`stdio`,graphviz:`wasm`,watch:!0,throwIfInvalid:!1,configureLogger:!0});t.configureLogger&&(configureLanguageServerLogger({useStdErr:t.mcp===`stdio`,colors:ii.isColorSupported&&t.mcp!==`stdio`,logLevel:Kr?`debug`:`info`}),process.on(`uncaughtException`,e=>{$.error(`uncaughtException`,{err:e})}),process.on(`unhandledRejection`,e=>{$.error(`unhandledRejection`,{err:e})}));let r=mr(t.workspacePath);$.info`Loading LikeC4 from workspace: ${r}`;let i=await fromWorkspace(r,{graphviz:t.graphviz,manualLayouts:!0,configureLogger:!1,watch:t.watch,throwIfInvalid:t.throwIfInvalid}),a=setLanguageServicesCtx(i.languageServices);return{server:t.mcp===`stdio`?new StdioLikeC4MCPServer(a,t.stdio):new StreamableLikeC4MCPServer(a,t.mcp.port),likec4:i}}async function startLikeC4MCP(e){let t=e?.mcp===void 0||e.mcp===`stdio`?e?.stdio?.stdin??process.stdin:void 0,r,i=!1,a=t?t.readableEnded||t.destroyed:!1,s,cleanup=async()=>{let e=r;e&&(s??=(async()=>{try{await e.server.stop()}finally{try{await e.likec4.dispose()}finally{setLanguageServicesCtx(void 0)}}})(),await s)};function stopObservingStdin(){t&&(t.off(`end`,onStdinClosed),t.off(`close`,onStdinClosed))}function onStdinClosed(){a=!0,stopObservingStdin(),i&&cleanup().catch(e=>{$.error(`Failed to stop MCP stdio server after stdin closed`,{err:e})})}t&&!a&&(t.once(`end`,onStdinClosed),t.once(`close`,onStdinClosed),a=t.readableEnded||t.destroyed);try{if(r=await initLikeC4MCP(e),r.server instanceof StdioLikeC4MCPServer){if(a)return stopObservingStdin(),await cleanup(),r;await r.server.start(),i=!0,a&&await cleanup()}else await r.server.start();return r}catch(e){if(stopObservingStdin(),r)try{await cleanup()}catch(e){$.error(`Failed to clean up MCP stdio server after start error`,{err:e})}throw e}}export{startLikeC4MCP as n,$ as r,initLikeC4MCP as t};
|