import{invariant as le,isNonEmptyArray as pe}from"@likec4/core";import{relative as ue}from"node:path";import{t as fe}from"./likec4.DO_7oUns.mjs";import{t as ge,a as A}from"./likec4.CB2-Uaub.mjs";import{f as he,g as J,T as me,N as V,i as we,e as x,j as _,u as v,t as Ie,a as ve,n as ye,b as Ne,c as ke,d as G,L as $e}from"./likec4.BJupup6Q.mjs";import{compareNatural as Le}from"@likec4/core/utils";import{a as W}from"./likec4.DASl7M77.mjs";import{t as je}from"./likec4.DOUP9ptn.mjs";import{RichText as Ce}from"@likec4/core/types";
function Se(...t){return je(Re,t)}function Re(t,e){let i={};for(let n of e)n in t&&(i[n]=t[n]);return i}function Te(t){var e,i;if(t){if("astNode"in t)return Me(t);if(Array.isArray(t))return t.reduce(B,void 0);{const n=t,r=Ee(n)?be((i=(e=n?.root)===null||e===void 0?void 0:e.astNode)!==null&&i!==void 0?i:n?.astNode):void 0;return C(n,r)}}else return}function Ee(t){return typeof t<"u"&&"element"in t&&"text"in t}function be(t){try{return J(t).uri.toString()}catch{return}}function Me(t){var e,i;const{
astNode:n,property:r,index:o}=t??{},c=(e=n?.$cstNode)!==null&&e!==void 0?e:n?.$textRegion;if(!(n===void 0||c===void 0)){if(r===void 0)return C(c,D(n));{const a=d=>o!==void 0&&o>-1&&Array.isArray(n[r])?o<d.length?d[o]:void 0:d.reduce(B,void 0);if(!((i=c.assignments)===null||i===void 0)&&i[r]){const d=a(c.assignments[r]);return d&&C(d,D(n))}else if(n.$cstNode){const d=a(he(n.$cstNode,r));return d&&C(d,D(n))}else return}}}function D(t){var e,i,n,r;return t.$cstNode?(i=(e=J(t))===null||e===void 0?void 0:
e.uri)===null||i===void 0?void 0:i.toString():t.$textRegion?t.$textRegion.documentURI||((r=(n=new me(t,o=>o.$container?[o.$container]:[]).find(o=>{var c;return(c=o.$textRegion)===null||c===void 0?void 0:c.documentURI}))===null||n===void 0?void 0:n.$textRegion)===null||r===void 0?void 0:r.documentURI):void 0}function C(t,e){var i,n;const r={offset:t.offset,end:(i=t.end)!==null&&i!==void 0?i:t.offset+t.length,length:(n=t.length)!==null&&n!==void 0?n:t.end-t.offset};return t.range&&(r.range=t.range),
e??(e=t.fileURI),e&&(r.fileURI=e),r}function B(t,e){var i,n;if(t){if(!e)return t&&C(t)}else return e&&C(e);const r=(i=t.end)!==null&&i!==void 0?i:t.offset+t.length,o=(n=e.end)!==null&&n!==void 0?n:e.offset+e.length,c=Math.min(t.offset,e.offset),a=Math.max(r,o),d=a-c,f={offset:c,end:a,length:d};if(t.range&&e.range&&(f.range={start:e.range.start.line<t.range.start.line||e.range.start.line===t.range.start.line&&e.range.start.character<t.range.start.character?e.range.start:t.range.start,end:e.range.
end.line>t.range.end.line||e.range.end.line===t.range.end.line&&e.range.end.character>t.range.end.character?e.range.end:t.range.end}),t.fileURI||e.fileURI){const u=t.fileURI,p=e.fileURI,g=u&&p&&u!==p?`<unmergable text regions of ${u}, ${p}>`:u??p;f.fileURI=g}return f}class xe{constructor(e){this.defaultIndentation="    ",this.pendingIndent=!0,this.currentIndents=[],this.recentNonImmediateIndents=[],this.traceData=[],this.lines=[[]],this.length=0,typeof e=="string"?this.defaultIndentation=e:typeof e==
"number"&&(this.defaultIndentation="".padStart(e))}get content(){return this.lines.map(e=>e.join("")).join("")}get contentLength(){return this.length}get currentLineNumber(){return this.lines.length-1}get currentLineContent(){return this.lines[this.currentLineNumber].join("")}get currentPosition(){return{offset:this.contentLength,line:this.currentLineNumber,character:this.currentLineContent.length}}append(e,i){if(e.length>0){const n=i&&this.currentPosition;this.lines[this.currentLineNumber].push(
e),this.length+=e.length,n&&this.indentPendingTraceRegions(n)}}indentPendingTraceRegions(e){for(let i=this.traceData.length-1;i>=0;i--){const n=this.traceData[i];n.targetStart&&n.targetStart.offset===e.offset&&(n.targetStart=this.currentPosition)}}increaseIndent(e){this.currentIndents.push(e),e.indentImmediately||this.recentNonImmediateIndents.push(e)}decreaseIndent(){this.currentIndents.pop()}get relevantIndents(){return this.currentIndents.filter(e=>!this.recentNonImmediateIndents.includes(e))}resetCurrentLine(){
this.length-=this.lines[this.currentLineNumber].join("").length,this.lines[this.currentLineNumber]=[],this.pendingIndent=!0,this.recentNonImmediateIndents.length=0}addNewLine(){this.lines.push([]),this.pendingIndent=!0,this.recentNonImmediateIndents.length=0}pushTraceRegion(e){const i=Ue(e,this.currentPosition,n=>{var r,o;return(o=(r=this.traceData[this.traceData.length-1])===null||r===void 0?void 0:r.children)===null||o===void 0?void 0:o.push(n)});return this.traceData.push(i),i}popTraceRegion(e){
const i=this.traceData.pop();return this.assertTrue(i===e,"Trace region mismatch!"),i}getParentTraceSourceFileURI(){var e;for(let i=this.traceData.length-1;i>-1;i--){const n=(e=this.traceData[i].sourceRegion)===null||e===void 0?void 0:e.fileURI;if(n)return n}}assertTrue(e,i){if(!e)throw new Error(i)}}function Ue(t,e,i){const n={sourceRegion:t,targetRegion:void 0,children:[],targetStart:e,complete:r=>{var o,c;return n.targetRegion={offset:n.targetStart.offset,end:r.offset,length:r.offset-n.targetStart.
offset,range:{start:{line:n.targetStart.line,character:n.targetStart.character},end:{line:r.line,character:r.character}}},delete n.targetStart,((o=n.children)===null||o===void 0?void 0:o.length)===0&&delete n.children,!((c=n.targetRegion)===null||c===void 0)&&c.length&&i(n),delete n.complete,n}};return n}function Pe(t,e){const i=new xe(e),n=i.pushTraceRegion(void 0);z(t,i),i.popTraceRegion(n),n.complete&&n.complete(i.currentPosition);const r=n.children&&n.children.length===1?n.children[0]:void 0,
o=r?.targetRegion,c=n.targetRegion;return o&&r.sourceRegion&&o.offset===c.offset&&o.length===c.length?{text:i.content,trace:r}:{text:i.content,trace:n}}function z(t,e){typeof t=="string"?_e(t,e):t instanceof O?De(t,e):t instanceof h?H(t,e):t instanceof E&&Fe(t,e)}function q(t,e){return typeof t=="string"?t.length!==0:t instanceof h?t.contents.some(i=>q(i,e)):t instanceof E?!(t.ifNotEmpty&&e.currentLineContent.length===0):!1}function _e(t,e){t&&(Y(e,!1),e.append(t))}function Y(t,e){var i;if(t.pendingIndent){
let n="";for(const r of t.relevantIndents.filter(o=>o.indentEmptyLines||!e))n+=(i=r.indentation)!==null&&i!==void 0?i:t.defaultIndentation;t.append(n,!0),t.pendingIndent=!1}}function H(t,e){let i;const n=Te(t.tracedSource);n&&(i=e.pushTraceRegion(n));for(const r of t.contents)z(r,e);if(i){e.popTraceRegion(i);const r=e.getParentTraceSourceFileURI();r&&n?.fileURI===r&&delete n.fileURI,i.complete&&i.complete(e.currentPosition)}}function De(t,e){var i;if(q(t,e)){t.indentImmediately&&!e.pendingIndent&&
e.append((i=t.indentation)!==null&&i!==void 0?i:e.defaultIndentation,!0);try{e.increaseIndent(t),H(t,e)}finally{e.decreaseIndent()}}}function Fe(t,e){t.ifNotEmpty&&!Oe(e.currentLineContent)?e.resetCurrentLine():(Y(e,!0),e.append(t.lineDelimiter),e.addNewLine())}function Oe(t){return t.trimStart()!==""}Object.freeze("__\xABSKIP^NEW^LINE^IF^EMPTY\xBB__");const Ae=/\S|$/;function Je(t){const e=t.filter(n=>n.length>0).map(n=>n.search(Ae)),i=e.length===0?0:Math.min(...e);return Math.max(0,i)}function $(t,...e){
const i=Ge(t),n=We(t,e,i);return ze(n)}function Ve(t,e,i){return(n,...r)=>Ye(t,e,i)($(n,...r))}function Ge(t){const e=t.join("_").split(V),i=e.length>1&&e[0].trim().length===0,n=i&&e.length>1&&e[e.length-1].trim().length===0;if(e.length===1||e.length!==0&&e[0].trim().length!==0||e.length===2&&e[1].trim().length===0)return{indentation:0,omitFirstLine:i,omitLastLine:n,trimLastLine:e.length!==1&&e[e.length-1].trim().length===0};{let r=i?e.slice(1):e;r=n?r.slice(0,r.length-1):r,r=r.filter(c=>c.length!==
0);const o=Je(r);return{indentation:o,omitFirstLine:i,omitLastLine:n&&(e[e.length-1].length<o||!e[e.length-1].startsWith(r[0].substring(0,o)))}}}function We(t,e,{indentation:i,omitFirstLine:n,omitLastLine:r,trimLastLine:o}){const c=[];t.forEach((f,u)=>{c.push(...f.split(V).map((p,g)=>g===0||p.length<i?p:p.substring(i)).reduce(u===0?(p,g,w)=>w===0?n?[]:[g]:w===1&&p.length===0?[g]:p.concat(U,g):(p,g,w)=>w===0?[g]:p.concat(U,g),[]).filter(p=>!(typeof p=="string"&&p.length===0)).concat(T(e[u])?e[u]:
e[u]!==void 0?{content:String(e[u])}:u<e.length?K:[]))});const a=c.length,d=a!==0?c[a-1]:void 0;return(r||o)&&typeof d=="string"&&d.trim().length===0?n&&a!==1&&c[a-2]===U?c.slice(0,a-2):c.slice(0,a-1):c}const U={isNewLine:!0},K={isUndefinedSegment:!0},X=t=>t===U,F=t=>t===K,Be=t=>t.content!==void 0;function ze(t){return t.reduce((i,n,r)=>F(n)?i:X(n)?{node:r!==0&&(F(t[r-1])||T(t[r-1]))||r>1&&typeof t[r-1]=="string"&&(F(t[r-2])||T(t[r-2]))?i.node.appendNewLineIfNotEmpty():i.node.appendNewLine()}:(()=>{
var o;const c=(r===0||X(t[r-1]))&&typeof n=="string"&&n.length!==0?"".padStart(n.length-n.trimStart().length):"",a=Be(n)?n.content:n;let d;return{node:i.indented?i.node:c.length!==0?i.node.indent({indentation:c,indentImmediately:!1,indentedChildren:f=>d=f.append(a)}):i.node.append(a),indented:d??((o=i.indented)===null||o===void 0?void 0:o.append(a))}})(),{node:new h}).node}const qe=typeof process>"u"?`
`:process.platform==="win32"?`\r
`:`
`;function T(t){return t instanceof h||t instanceof O||t instanceof E}function L(t,e){return T(t)?Pe(t,e).text:String(t)}class h{constructor(...e){this.contents=[],this.append(...e)}isEmpty(){return this.contents.length===0}trace(e,i,n){if(we(e)){if(this.tracedSource={astNode:e,property:i,index:n},this.tracedSource.property===void 0&&this.tracedSource.index!==void 0&&this.tracedSource.index>-1)throw new Error("Generation support: 'property' argument must not be 'undefined' if a non-negative valu\
e is assigned to 'index' in 'CompositeGeneratorNode.trace(...)'.")}else this.tracedSource=e;return this}append(...e){for(const i of e)typeof i=="function"?i(this):i&&this.contents.push(i);return this}appendIf(e,...i){return e?this.append(...i):this}appendNewLine(){return this.append(s)}appendNewLineIf(e){return e?this.append(s):this}appendNewLineIfNotEmpty(){return this.append(He)}appendNewLineIfNotEmptyIf(e){return e?this.appendNewLineIfNotEmpty():this}appendTemplate(e,...i){return this.append(
$(e,...i))}appendTemplateIf(e){return e?(i,...n)=>this.appendTemplate(i,...n):()=>this}indent(e){const{indentedChildren:i,indentation:n,indentEmptyLines:r,indentImmediately:o}=Array.isArray(e)||typeof e=="function"?{indentedChildren:e}:typeof e=="object"?e:{},c=new O(n,o,r);return this.contents.push(c),Array.isArray(i)?c.append(...i):i&&c.append(i),this}appendTraced(e,i,n){return r=>this.append(new h().trace(e,i,n).append(r))}appendTracedIf(e,i,n,r){return e?this.appendTraced(typeof i=="function"?
i():i,n,r):()=>this}appendTracedTemplate(e,i,n){return(r,...o)=>this.append(Ve(e,i,n)(r,...o))}appendTracedTemplateIf(e,i,n,r){return e?this.appendTracedTemplate(typeof i=="function"?i():i,n,r):()=>this}}function Ye(t,e,i){return n=>n instanceof h&&n.tracedSource===void 0?n.trace(t,e,i):new h().trace(t,e,i).append(n)}class O extends h{constructor(e,i=!0,n=!1){super(),this.indentImmediately=!0,this.indentEmptyLines=!1,typeof e=="string"?this.indentation=e:typeof e=="number"&&(this.indentation="".
padStart(e)),this.indentImmediately=i,this.indentEmptyLines=n}}class E{constructor(e,i=!1){this.ifNotEmpty=!1,this.lineDelimiter=e??qe,this.ifNotEmpty=i}}const s=new E,He=new E(void 0,!0),Q=t=>t===void 0||typeof t=="string"||T(t)?t:String(t);function y(t,e=Q,i={}){const n=typeof e=="function"?e:Q,{filter:r,prefix:o,suffix:c,separator:a,appendNewLineIfNotEmpty:d,skipNewLineAfterLastItem:f}=typeof e=="object"?e:i,u=typeof o=="function"?o:(()=>o),p=typeof c=="function"?c:(()=>c);return Ke(t,(g,w,l,m)=>{
if(r&&!r(w,l,m))return g;const I=n(w,l,m);return I===void 0?g:(g??(g=new h)).append(u(w,l,m)).append(I).append(p(w,l,m)).appendIf(!m,a).appendNewLineIfNotEmptyIf(!g.isEmpty()&&!!d&&(!m||!f))})}function Ke(t,e,i){const n=t[Symbol.iterator]();let r=n.next(),o=0,c=i;for(;!r.done;){const a=n.next();c=e(c,r.value,o,!!a.done),r=a,o++}return c}const Xe=t=>t.charAt(0).toLocaleUpperCase()+t.slice(1),Qe=t=>t.split(".").map(Xe).join(""),Ze=t=>Qe(t.parent?t.id.slice(t.parent.length+1):t.id),et=({autoLayout:t})=>{
switch(t.direction){case"TB":return"down";case"BT":return"up";case"LR":return"right";case"RL":return"left"}},tt=({shape:t})=>{switch(t){case"queue":case"cylinder":case"rectangle":case"person":return t;case"storage":return"stored_data";case"mobile":case"browser":return"rectangle"}};function Z(t){const e=t.$view,{nodes:i,edges:n}=e,r=new Map,o=(a,d)=>{const f=Ze(a),u=(d?d+".":"")+f;r.set(a.id,u);const p=JSON.stringify(a.title),g=tt(a);return new h().append(f,": {",s).indent({indentedChildren:w=>w.
append("label: ",p,s).appendIf(g!=="rectangle","shape: ",g,s).appendIf(a.children.length>0,s,y(i.filter(l=>l.parent===a.id),l=>o(l,u))),indentation:2}).append("}",s)},c=a=>new h().append(r.get(a.source)," -> ",r.get(a.target)).append(d=>a.label&&d.append(": ",JSON.stringify(a.label)));return L(new h().append("direction: ",et(e),s,s).append(y(i.filter(a=>x(a.parent)),a=>o(a),{appendNewLineIfNotEmpty:!0})).appendIf(n.length>0,s,y(n,a=>c(a),{appendNewLineIfNotEmpty:!0})))}const nt=t=>t.charAt(0).toLocaleUpperCase()+
t.slice(1),it=t=>t.split(".").map(nt).join(""),rt=t=>it(t.parent?t.id.slice(t.parent.length+1):t.id),ot=({shape:t})=>{switch(t){case"queue":case"cylinder":return["[(",")]"];case"person":return["[fa:fa-user ","]"];case"storage":return["([","])"];case"mobile":case"browser":case"rectangle":return["[","]"]}};function ee(t){const e=t.$view,{nodes:i,edges:n}=e,r=new Map,o=(a,d)=>{const f=rt(a),u=(d?d+".":"")+f;r.set(a.id,u);const p=a.title.replaceAll(`
`,"\\n"),g=ot(a),w=new h;return a.children.length>0?w.append("subgraph ",u,"[",JSON.stringify(a.title),"]",s).indent({indentedChildren:[y(i.filter(l=>l.parent===a.id),l=>o(l,u),{appendNewLineIfNotEmpty:!0})],indentation:2}).append("end",s):w.append(u,g[0],p,g[1]),w},c=a=>new h().append(r.get(a.source)," -.",a.label?' "'+a.label.replaceAll(`
`,"\\n")+'" .-':"-","> ",r.get(a.target));return L(new h().appendIf(e.title!==null&&e.title.length>0,"---",s,`title: ${JSON.stringify(e.title)}`,s,"---",s).append("graph ",e.autoLayout.direction,s).indent({indentedChildren:a=>{a.append(y(i.filter(d=>x(d.parent)),d=>o(d),{appendNewLineIfNotEmpty:!0})).appendIf(n.length>0,y(n,d=>c(d),{appendNewLineIfNotEmpty:!0}))},indentation:2}))}const at=t=>t.charAt(0).toLocaleUpperCase()+t.slice(1),P=t=>t.split(/[.-]/).map(at).join(""),te=t=>P(t.parent?t.id.slice(
t.parent.length+1):t.id),S=(t,e,i="#3b82f6")=>t?e(t)??i:i,st=({autoLayout:t})=>{switch(t.direction){case"TB":return"top to bottom";case"BT":return console.warn("Bottom to top direction is not supported. Defaulting to top to bottom."),"top to bottom";case"LR":return"left to right";case"RL":return console.warn("Right to left direction is not supported. Defaulting to left to right."),"left to right"}},ne=({shape:t})=>{switch(t){case"queue":case"rectangle":case"person":return t;case"storage":case"cy\
linder":return"database";case"mobile":case"browser":return"rectangle"}},R=t=>x(t)?null:JSON.stringify(t).slice(1,-1);function ie(t){const e=t.$view,i=t.$model.$styles.theme.colors,{nodes:n,edges:r}=e,o=l=>m=>m in i?i[m].elements[l]:void 0,c=l=>m=>m in i?i[m].relationships[l]:void 0,a=new Map,d=()=>new h().append('title "',e.title||e.id,'"',s).append(st(e)," direction",s),f=()=>new h().append("hide stereotype",s).append("skinparam ranksep ","60",s).append("skinparam nodesep ","30",s).append("skin\
param {",s).indent({indentedChildren:l=>l.append("arrowFontSize ","10",s).append("defaultTextAlignment ","center",s).append("wrapWidth ","200",s).append("maxMessageSize ","100",s).append("shadowing ","false",s),indentation:2}).append("}",s),u=l=>{const m=ne(l),I=P(l.id);return new h().append("skinparam ",m,"<<",I,">>","{",s).indent({indentedChildren:k=>k.append("BackgroundColor ",S(l.color,o("fill")),s).append("FontColor ",S(l.color,o("hiContrast"),"#FFFFFF"),s).append("BorderColor ",S(l.color,o(
"stroke")),s),indentation:2}).append("}",s)},p=l=>{const m=ne(l),I=P(l.id),k=R(l.title)||te(l),N=R(l.technology);a.set(l.id,I);const M=Ce.from(l.description);return new h().append(m," ").append('"').append("==",k).appendIf(!!N,"\\n","<size:10>[",N,"]</size>").appendIf(M.nonEmpty,"\\n\\n",R(M.text)).append('"'," <<",I,">> ","as ",I,s)},g=l=>{const m=R(l.title)||te(l),I=P(l.id);return a.set(l.id,I),new h().append('rectangle "',m,'" <<',I,">> as ",I," {",s).indent({indentedChildren:k=>k.append("ski\
nparam ","RectangleBorderColor<<",I,">> ",S(l.color,o("fill")),s).append("skinparam ","RectangleFontColor<<",I,">> ",S(l.color,o("fill")),s).append("skinparam ","RectangleBorderStyle<<",I,">> ","dashed",s,s).append(y(n.filter(N=>N.parent===l.id),N=>N.children.length>0?g(N):p(N))),indentation:2}).append("}",s)},w=l=>{const m=R(l.technology)||"",I=R(l.label)||"",k=S(l.color,c("line"),"#777777"),N=M=>`<color:${M}>`;return new h().append(a.get(l.source)," .[",k,",thickness=2].> ",a.get(l.target)).appendIf(
!!(I||m),' : "',N(k)).appendIf(!!I,I,N(k)).appendIf(!!(I&&m),"\\n").appendIf(!!m,N(k),"<size:8>[",m,"]</size>").appendIf(!!(I||m),'"').append(s)};return L(new h().append("@startuml",s).append(d(),s).append(f(),s).append(y(n.filter(l=>l.children.length==0),l=>u(l),{appendNewLineIfNotEmpty:!0})).append(y(n.filter(l=>x(l.parent)),l=>l.children.length>0?g(l):p(l),{appendNewLineIfNotEmpty:!0})).appendIf(r.length>0,s,y(r,l=>w(l),{appendNewLineIfNotEmpty:!0})).append("@enduml",s))}function j(t){return{
matches:e=>{let{module:i,projectId:n}=e.match(/^likec4:plugin\/(?<projectId>.+)\/(?<module>.+)$/)?.groups??e.match(/^likec4:(?<module>.+)\/(?<projectId>.+)$/)?.groups??{};return!i||!n?null:(i.endsWith(".js")&&(i=i.slice(0,-3)),i===t?n:null)},virtualId:e=>_("likec4:plugin",e,t)+".js"}}const dt={"<":"\\u003C",">":"\\u003E","/":"\\u002F","\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","	":"\\t","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};function ct(t){return t.replace(/[<>\b\f\n\r\t\0\u2028\u2029\\]/g,
e=>dt[e])}function b(t,e){return{id:`likec4:${t}`,virtualId:`likec4:plugin/${t}.js`,async load({logger:i,projects:n}){i.info(v.dim(`generating likec4:${t}`));const r=n.map(({id:o})=>{const c=ct(JSON.stringify(_(`likec4:${t}`,o)));return`  ${JSON.stringify(o)}: () => import(${c})`});return`
export let ${e}Fn = {
${r.join(`,
`)}
}      

export async function ${e}(projectId) {
  let fn = ${e}Fn[projectId]
  if (!fn) {
    const projects = Object.keys(${e}Fn)
    console.error('Unknown projectId: ' + projectId + ' (available: ' + projectIds + ')')
    if (projects.length === 0) {
      throw new Error('No projects found, invalid state')
    }
    projectId = projects[0]
    console.warn('Falling back to project: ' + projectId)
    fn = ${e}Fn[projectId]
  }
  return await fn()
}

if (import.meta.hot) {
  import.meta.hot.accept(md => {
    if (!import.meta.hot.data.$update) {
      import.meta.hot.data.$update = ${e}Fn
    }
    const update = md.${e}Fn
    if (update) {
      Object.assign(import.meta.hot.data.$update, update)
    } else {
      import.meta.hot.invalidate()
    }
  })
}
    `}}}function lt(t){const e=new h;return e.appendTemplate`
    /******************************************************************************
     * This file was generated
     * DO NOT EDIT MANUALLY!
     ******************************************************************************/
    /* eslint-disable */

    export function d2Source(viewId) {
      switch (viewId) {
  `.appendNewLine().indent({indentation:4,indentedChildren(i){i.append(y([...t.views()],n=>$`
              case ${JSON.stringify(n.id)}: {
                return ${JSON.stringify(Z(n))}
              }
            `,{appendNewLineIfNotEmpty:!0})).appendTemplate`
        default: {
          throw new Error('Unknown viewId: ' + viewId)
        }
      `}}).append(s,"  }",s).appendTemplate`
    }
    `.append(s,s),L(e)}const pt={...j("d2"),async load({likec4:t,project:e,logger:i}){i.info(v.dim(`generating likec4:d2/${e.id}`));const n=await t.computedModel(e.id);return lt(n)}},ut=b("d2","loadD2Sources");function ft(t){const e=new h;return e.appendTemplate`
    /******************************************************************************
     * This file was generated
     * DO NOT EDIT MANUALLY!
     ******************************************************************************/
    /* eslint-disable */

    export function dotSource(viewId) {
      switch (viewId) {
  `.appendNewLine().indent({indentation:4,indentedChildren(i){i.append(y(Object.keys(t),n=>$`
              case ${JSON.stringify(n)}: {
                return ${JSON.stringify(t[n].dot)}
              }
            `,{appendNewLineIfNotEmpty:!0})).appendTemplate`
          default: {
            throw new Error('Unknown viewId: ' + viewId)
          }
        `}}).append(s,"  }",s).appendTemplate`
    }

    export function svgSource(viewId) {
      switch (viewId) {
    `.appendNewLine().indent({indentation:4,indentedChildren(i){i.append(y(Object.keys(t),n=>$`
              case ${JSON.stringify(n)}: {
                return ${JSON.stringify(t[n].svg)}
              }
            `,{appendNewLineIfNotEmpty:!0})).appendTemplate`
          default: {
            throw new Error('Unknown viewId: ' + viewId)
          }
        `}}).append(s,"  }",s,"}",s,s),L(e)}const gt={...j("dot"),async load({likec4:t,project:e,logger:i}){i.info(v.dim(`generating likec4:dot/${e.id}`));const n=await t.views.viewsAsGraphvizOut(e.id),r=Ie(n,({id:o,svg:c,dot:a})=>[o,{dot:a,svg:c}]);return ft(r)}},ht=b("dot","loadDotSources");function mt(t){const e=ge(t.flatMap(r=>r.nodes.map(o=>o.icon)),Ne(r=>ke(r)&&!(r.toLowerCase().startsWith("http:")||r.toLowerCase().startsWith("https:"))),ye(),ve(Le)),{imports:i,cases:n}=e.reduce((r,o,c)=>{
const a=o.startsWith("file:"),d="Icon"+c.toString().padStart(2,"0");if(a)return r.imports.push(`import ${d} from '${o}?inline'`),r.cases.push(`  '${o}': () => jsx('img', { src: ${d} })`),r;const[f,u]=o.split(":");return r.imports.push(`import ${d} from 'likec4/icons/${f}/${u}'`),r.cases.push(`  '${f}:${u}': ${d}`),r},{imports:[],cases:[]});return`
import { jsx } from 'react/jsx-runtime'
${i.join(`
`)}

const Icons = {
${n.join(`,
`)}
}
export function IconRenderer(props) {
  const IconComponent = Icons[props.node.icon ?? '']
  if (!IconComponent) {
    return null
  }
  return jsx(IconComponent, props)
}
  
if (import.meta.hot) {
  import.meta.hot.accept()
}
`}const wt={...j("icons"),async load({likec4:t,project:e,logger:i}){i.info(v.dim(`generating likec4:icons/${e.id}`));const n=await t.views.computedViews(e.id);return mt(n)}},It={id:"likec4:icons",virtualId:"likec4:plugin/icons.jsx",async load({projects:t,logger:e}){e.info(v.dim("generating likec4:icons"));const{imports:i,cases:n}=t.reduce((r,{id:o},c)=>{const a="Icons"+c.toString().padStart(2,"0"),d=_("likec4:icons",o);return r.imports.push(`import { IconRenderer as ${a} } from ${JSON.stringify(
d)}`),r.cases.push(`   case ${JSON.stringify(o)}: return ${a}`),r},{imports:[],cases:[]});return`
import { jsx } from 'react/jsx-runtime'    
${i.join(`
`)}

function getProjectIcons(projectId) {
  switch (projectId) {
${n.join(`
`)}
    default:
      throw new Error('Unknown projectId: ' + projectId)
  }
}

export function ProjectIcons({ projectId, ...props }) {
  const IconComponent = getProjectIcons(projectId)
  return jsx(IconComponent, props)
}
if (import.meta.hot) {
  import.meta.hot.accept()
}  
`}};function vt(t){const e=new h;return e.appendTemplate`
    /******************************************************************************
     * This file was generated
     * DO NOT EDIT MANUALLY!
     ******************************************************************************/
    /* eslint-disable */

    export function mmdSource(viewId) {
      switch (viewId) {
  `.appendNewLine().indent({indentation:4,indentedChildren(i){i.append(y([...t.views()],n=>$`
              case ${JSON.stringify(n.id)}: {
                return ${JSON.stringify(ee(n))}
              }
            `,{appendNewLineIfNotEmpty:!0})).appendTemplate`
          default: {
            throw new Error('Unknown viewId: ' + viewId)
          }
        `}}).append(s,"  }",s).appendTemplate`
    }

    `.append(s,s),L(e)}const yt={...j("mmd"),async load({likec4:t,project:e,logger:i}){i.info(v.dim(`generating virtual:likec4/mmd/${e.id}`));const n=await t.computedModel(e.id);return vt(n)}},Nt=b("mmd","loadMmdSources"),kt=t=>`
import { createHooksForModel, atom } from 'likec4/vite-plugin/internal'

export const $likec4data = atom(${W.stringify(t.$data)})

export const {
  updateModel,
  $likec4model,
  useLikeC4Model,
  useLikeC4Views,
  useLikeC4View
} = createHooksForModel($likec4data)

if (import.meta.hot) {
  import.meta.hot.accept(md => {
    if (!import.meta.hot.data.$update) {
      import.meta.hot.data.$update = updateModel
    }
    const update = md.$likec4data?.get()
    if (update) {
      import.meta.hot.data.$update(update)
    } else {
      import.meta.hot.invalidate()
    }
  })
}
`,$t={...j("model"),async load({likec4:t,project:e,logger:i}){i.info(v.dim(`generating likec4:model/${e.id}`));const n=await t.layoutedModel(e.id);return kt(n)}},re=b("model","loadModel"),Lt=t=>`
export const isSingleProject = ${t.length===1};
export const projects = ${W.stringify(t,null,2)};
`,oe={id:"likec4:projects",virtualId:"likec4:plugin/projects.js",async load({logger:t,projects:e}){return t.info(v.dim("generating likec4:projects")),Lt(A(e,Se(["id","title"])))}};function jt(t){const e=new h;return e.appendTemplate`
    /******************************************************************************
     * This file was generated
     * DO NOT EDIT MANUALLY!
     ******************************************************************************/
    /* eslint-disable */

    export function pumlSource(viewId) {
      switch (viewId) {
  `.appendNewLine().indent({indentation:4,indentedChildren(i){i.append(y([...t.views()],n=>$`
              case ${JSON.stringify(n.id)}: {
                return ${JSON.stringify(ie(n))}
              }
            `,{appendNewLineIfNotEmpty:!0})).appendTemplate`
        default: {
          throw new Error('Unknown viewId: ' + viewId)
        }
      `}}).append(s,"  }",s).appendTemplate`
    }
    `.append(s,s),L(e)}const Ct={...j("puml"),async load({likec4:t,project:e,logger:i}){i.info(v.dim(`generating likec4:puml/${e.id}`));const n=await t.computedModel(e.id);return jt(n)}},St=b("puml","loadPumlSources"),ae=t=>`
import { jsx as _jsx } from "react/jsx-runtime";
import { LikeC4ModelProvider as Provider, LikeC4View as GenericView, ReactLikeC4 as GenericReactLikeC4 } from 'likec4/react';
import { IconRenderer } from 'likec4:icons/${t}'

import { useLikeC4Model, useLikeC4Views, useLikeC4View } from 'likec4:model/${t}'

export function LikeC4ModelProvider({ children }) {
  const likeC4Model = useLikeC4Model()
  return (_jsx(Provider, { likec4model: likeC4Model, children: children }));
}
export function LikeC4View(props) {
  return (_jsx(LikeC4ModelProvider, { children: _jsx(GenericView, { renderIcon: IconRenderer, ...props }) }));
}
export function ReactLikeC4(props) {
  return (_jsx(LikeC4ModelProvider, { children: _jsx(GenericReactLikeC4, { renderIcon: IconRenderer, ...props }) }));
}

export {
  useLikeC4Model,
  useLikeC4View,
  useLikeC4Views
}
`,Rt={...j("react"),async load({project:t,logger:e}){return e.info(v.dim(`generating likec4:react/${t.id}`)),ae(t.id)}},Tt={id:"likec4:react",virtualId:"likec4:plugin/react.js",async load({logger:t,projects:e}){const i=G(e);return t.info(v.dim("generating likec4:react for")+" "+i.id),ae(i.id)}},Et=t=>`
export { IconRenderer } from 'likec4:icons/${t}'
export {
  $likec4data,
  $likec4model,
  useLikeC4Model,
  useLikeC4Views,
  useLikeC4View
} from 'likec4:model/${t}'
export const projectId = ${JSON.stringify(t)}
`,bt={id:"likec4:single-project",virtualId:"likec4:plugin/single-project.js",async load({logger:t,projects:e}){const i=G(e);return t.info(v.dim("generating likec4:single-project for")+" "+i.id),Et(i.id)}},se=[$t,wt,pt,gt,yt,Ct],de=[...se,Rt],ce=[oe,re,bt,Tt,ut,ht,Nt,St,It];function Mt({useOverviewGraph:t=!1,...e}){let i,n,r,o,c=e.watch??!1;return{name:"vite-plugin-likec4",async configResolved(a){if(i=a.root,n=a.logger,t===!0){const d=a.resolve.alias.find(f=>f.find==="likec4/previews")?.replacement;
d?(o=d,n.info(v.dim("likec4/previews alias")+" "+v.dim(o))):n.warn("likec4/previews alias not found")}if(e.languageServices)r=e.languageServices;else{const d=c=e.watch??a.mode==="development";r=(await $e.fromWorkspace(e.workspace??a.root,{logger:n,graphviz:e.graphviz??"wasm",printErrors:e.printErrors??!0,throwIfInvalid:e.throwIfInvalid??!1,watch:d})).languageServices}o=r.workspaceUri.fsPath},resolveId(a){for(const d of de){const f=d.matches(a);if(f)return d.virtualId(f)}for(const d of ce)if(d.id===
a)return d.virtualId;return null},async load(a){for(const d of de){const f=d.matches(a);if(f){const u=r.project(f);return await d.load({logger:n,likec4:r,project:u,assetsDir:o,useOverviewGraph:t})}}for(const d of ce)if(d.virtualId===a){const f=r.projects();return le(pe(f)),await d.load({logger:n,likec4:r,projects:f,assetsDir:o,useOverviewGraph:t})}return null},configureServer(a){const d=()=>A(r.projects(),p=>({id:p.id,title:p.title,folder:p.folder.fsPath}));let f=d();const u=async p=>{const g=a.
moduleGraph.getModuleById(p);if(g&&g.importers.size>0)try{await a.reloadModule(g)}catch(w){n.error(w)}};r.builder.onModelParsed(async()=>{const[p]=r.getErrors();if(p){a.ws.send({type:"error",err:{name:"LikeC4ValidationError",message:`Validation failed
`+p.message.slice(0,500),stack:"",plugin:"vite-plugin-likec4",loc:{file:ue(i,p.sourceFsPath),line:p.range.start.line+1,column:p.range.start.character+1}}});return}const g=d();fe(g,f)||(f=g,await u(oe.virtualId),await u(re.virtualId));for(const w of f)for(const l of se)await u(l.virtualId(w.id))}),xt.call(this,{logger:n,likec4:r,server:a,reloadModule:u})},async buildEnd(){c&&await r.dispose()}}}function xt({logger:t,likec4:e,server:i}){i.ws.on("likec4:view:onChange",async function(n){try{t.info([
v.green("view:onChange"),v.dim("project")+":",n.projectId,v.dim("view")+":",n.viewId,v.dim("change")+":",n.change.op].join(" "));const r=await e.editor.applyChange(n);if(!r.success){t.error(`Failed to apply view change:
${r.error}`),i.ws.send({type:"error",err:{message:r.error,stack:"",name:"LikeC4ViewChangeError",plugin:"vite-plugin-likec4"}});return}t.info([v.green("view:onChange"),"\u2705"].join(" "))}catch(r){const o=r;t.error("Failed to apply view change",{error:o}),i.ws.send({type:"error",err:{message:o.message,stack:o.stack??"",name:o.name,plugin:"vite-plugin-likec4"}})}})}export{h as C,Mt as L,s as N,ee as a,Z as b,$ as e,ie as g,y as j,L as t};
