Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

Add architecture renderer; share renderer helpers; harden against malformed input

tt-a1i166a9ff8095b
diff --git a/archify/assets/template.html b/archify/assets/template.html
index 031c2f5d..b400799c 100644
--- a/archify/assets/template.html
+++ b/archify/assets/template.html
@@ -3,8 +3,36 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="generator" content="archify 2.6.0">
<title>[PROJECT NAME] Architecture Diagram</title>
- <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
+ <script>
+ // Resolve the theme before first paint so light-preference users don't
+ // see a dark flash. The toolbar script below re-applies with UI state.
+ (function () {
+ try {
+ var theme = null;
+ try {
+ var param = new URLSearchParams(window.location.search).get('theme');
+ if (param === 'light' || param === 'dark') theme = param;
+ } catch (_) {}
+ if (!theme) {
+ try { theme = localStorage.getItem('archify-theme'); } catch (_) {}
+ }
+ if (theme !== 'light' && theme !== 'dark') {
+ theme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
+ }
+ document.documentElement.setAttribute('data-theme', theme);
+ } catch (_) {}
+ })();
+ </script>
+ <!-- Async font load: a blackholed network must not block first paint.
+ The body font stack falls back to system monospace until it lands. -->
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap"
+ rel="stylesheet" media="print" onload="this.media='all'">
+ <noscript>
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
+ </noscript>
<style>
/* ==========================================================
THEME VARIABLES — switch by toggling [data-theme] on <html>
@@ -16,6 +44,8 @@
--text: #ffffff;
--text-muted: #94a3b8;
--text-dim: #475569;
+ /* UI chrome (menu hints, footer) needs more contrast than SVG .t-dim accents */
+ --text-faint: #7d8da1;
--panel: rgba(15, 23, 42, 0.5);
--panel-border: #1e293b;
@@ -57,6 +87,7 @@
--text: #0f172a;
--text-muted: #64748b;
--text-dim: #94a3b8;
+ --text-faint: #64748b;
--panel: #ffffff;
--panel-border: #e2e8f0;
@@ -93,7 +124,7 @@
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
- font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace;
background: var(--bg);
min-height: 100vh;
padding: 2rem;
@@ -199,7 +230,7 @@
.footer {
text-align: center;
margin-top: 1.5rem;
- color: var(--text-dim);
+ color: var(--text-faint);
font-size: 0.75rem;
}
@@ -212,6 +243,9 @@
@page { size: landscape; margin: 1.5cm; }
@media print {
+ /* Force the FULL light palette — including component fills/strokes and
+ lane/arrow colors — so printing from dark theme doesn't put neon
+ strokes and translucent dark fills on white paper. */
:root, [data-theme="dark"], [data-theme="light"] {
--bg: #ffffff;
--grid: transparent;
@@ -220,11 +254,30 @@
--text: #0f172a;
--text-muted: #475569;
--text-dim: #94a3b8;
+ --text-faint: #64748b;
--mask: #ffffff;
+ --lane-fill: rgba(248, 250, 252, 0.65);
+ --lane-stroke: #cbd5e1;
+ --arrow: #94a3b8;
+ --arrow-emphasis: #059669;
+ --frontend-fill: rgba(34, 211, 238, 0.15);
+ --frontend-stroke: #0891b2;
+ --backend-fill: rgba(52, 211, 153, 0.18);
+ --backend-stroke: #059669;
+ --database-fill: rgba(167, 139, 250, 0.2);
+ --database-stroke: #7c3aed;
+ --cloud-fill: rgba(251, 191, 36, 0.18);
+ --cloud-stroke: #d97706;
+ --security-fill: rgba(251, 113, 133, 0.15);
+ --security-stroke: #e11d48;
+ --messagebus-fill: rgba(251, 146, 60, 0.15);
+ --messagebus-stroke:#ea580c;
+ --external-fill: rgba(148, 163, 184, 0.18);
+ --external-stroke: #64748b;
}
body { background: #ffffff !important; padding: 0; }
.container { max-width: none; }
- .toolbar, .archify-toast { display: none !important; }
+ .toolbar, .archify-toast, .no-print { display: none !important; }
.diagram-container, .card { box-shadow: none; border-color: #e2e8f0; }
.cards { grid-template-columns: 1fr 1fr; }
/* Ensure elements break sensibly across pages */
@@ -295,7 +348,7 @@
background: var(--toolbar-hover);
}
.toolbar .export-menu .hint {
- color: var(--text-dim);
+ color: var(--text-faint);
font-size: 0.625rem;
}
.toolbar .export-menu hr {
@@ -426,11 +479,11 @@
</button>
<div class="export-menu" id="export-menu" role="menu" aria-label="Export">
<button data-action="copy" type="button" role="menuitem" tabindex="-1">Copy to clipboard <span class="hint">PNG</span></button>
- <hr role="separator" aria-hidden="true">
+ <hr role="separator">
<button data-format="png" type="button" role="menuitem" tabindex="-1">Download PNG</button>
<button data-format="jpeg" type="button" role="menuitem" tabindex="-1">Download JPEG</button>
<button data-format="webp" type="button" role="menuitem" tabindex="-1">Download WebP</button>
- <hr role="separator" aria-hidden="true">
+ <hr role="separator">
<button data-format="svg" type="button" role="menuitem" tabindex="-1">Download SVG <span class="hint">vector</span></button>
</div>
</div>
@@ -449,7 +502,7 @@
<!-- Main Diagram -->
<div class="diagram-container">
<!-- ARCHIFY:SVG_SLOT_START -->
- <svg viewBox="0 0 1000 680">
+ <svg viewBox="0 0 1000 680" role="img" aria-label="[PROJECT NAME] architecture diagram">
<!-- Definitions -->
<defs>
<marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
@@ -660,13 +713,27 @@
var icon = document.getElementById('theme-icon');
var label = document.getElementById('theme-label');
- function resolveInitial() {
+ // localStorage can throw (blocked cookies, sandboxed iframes); the whole
+ // script element dies on an uncaught error, so guard every access.
+ function readStored() {
+ try { return localStorage.getItem(STORAGE_KEY); } catch (_) { return null; }
+ }
+ function writeStored(value) {
+ try { localStorage.setItem(STORAGE_KEY, value); } catch (_) {}
+ }
+ function urlOverride() {
// URL param wins (useful for deterministic screenshots / share links)
try {
var param = new URLSearchParams(window.location.search).get('theme');
if (param === 'light' || param === 'dark') return param;
} catch (_) {}
- var saved = localStorage.getItem(STORAGE_KEY);
+ return null;
+ }
+
+ function resolveInitial() {
+ var fromUrl = urlOverride();
+ if (fromUrl) return fromUrl;
+ var saved = readStored();
if (saved === 'light' || saved === 'dark') return saved;
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
}
@@ -681,12 +748,24 @@
function toggle() {
var next = html.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
apply(next);
- localStorage.setItem(STORAGE_KEY, next);
+ writeStored(next);
}
apply(resolveInitial());
btn.addEventListener('click', toggle);
+ // Follow live OS theme changes while the user has no explicit preference.
+ try {
+ var media = window.matchMedia('(prefers-color-scheme: light)');
+ var onChange = function (e) {
+ var saved = readStored();
+ if (urlOverride() || saved === 'light' || saved === 'dark') return;
+ apply(e.matches ? 'light' : 'dark');
+ };
+ if (media.addEventListener) media.addEventListener('change', onChange);
+ else if (media.addListener) media.addListener(onChange);
+ } catch (_) {}
+
return { toggle: toggle };
})();
@@ -706,7 +785,10 @@
var RASTER_SCALE = 4;
function diagramFilename() {
- var title = (document.title || 'diagram').replace(/\s+Architecture(\s+Diagram)?$/i, '').trim();
+ var title = (document.title || 'diagram')
+ .replace(/\s+Architecture(\s+Diagram)?$/i, '')
+ .replace(/\s+Diagram$/i, '')
+ .trim();
return title.replace(/[^a-z0-9_\-]+/gi, '-')
.toLowerCase()
.replace(/^-+|-+$/g, '') || 'diagram';
@@ -749,21 +831,37 @@
clone.setAttribute('height', vb.height * scale);
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
- var hostStyle = Array.prototype.map.call(document.querySelectorAll('style'), function (s) {
- return s.textContent;
- }).join('\n');
-
- var varNames = [
- '--bg','--grid','--text','--text-muted','--text-dim',
- '--arrow','--arrow-emphasis','--mask',
- '--frontend-fill','--frontend-stroke',
- '--backend-fill','--backend-stroke',
- '--database-fill','--database-stroke',
- '--cloud-fill','--cloud-stroke',
- '--security-fill','--security-stroke',
- '--messagebus-fill','--messagebus-stroke',
- '--external-fill','--external-stroke'
- ];
+ // Only the SVG-relevant rules: semantic classes, markers, and the
+ // theme variable blocks. Toolbar/cards/print CSS can never apply
+ // inside a standalone SVG and would only bloat the export.
+ var hostStyle = (function () {
+ var out = [];
+ Array.prototype.forEach.call(document.styleSheets, function (sheet) {
+ var rules;
+ try { rules = sheet.cssRules; } catch (_) { return; } // cross-origin
+ if (!rules) return;
+ Array.prototype.forEach.call(rules, function (rule) {
+ if (rule.type !== 1) return; // plain style rules only
+ var sel = rule.selectorText || '';
+ if (/(^|,)\s*(svg|:root|\[data-theme|\.c-|\.t-|\.a-|\.m-)/.test(sel)) {
+ out.push(rule.cssText);
+ }
+ });
+ });
+ return out.join('\n');
+ })();
+
+ // Derive the variable list from the stylesheet so newly added theme
+ // variables can never be missed by the export pipeline again
+ // (--lane-fill/--lane-stroke once were).
+ var varNames = (function () {
+ var seen = {};
+ var names = [];
+ (hostStyle.match(/--[a-zA-Z0-9-]+(?=\s*:)/g) || []).forEach(function (n) {
+ if (!seen[n]) { seen[n] = true; names.push(n); }
+ });
+ return names;
+ })();
// Resolve the full variable set for a given data-theme via an
// off-DOM probe, independent of what the viewer is currently set to.
@@ -808,7 +906,7 @@
style.textContent =
fontFallback + "\n" +
- "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; }\n" +
+ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace; }\n" +
hostStyle + "\n" +
":root, svg { " + darkVars + " }\n" +
"@media (prefers-color-scheme: light) { :root, svg { " + lightVars + " } }\n" +
@@ -836,7 +934,7 @@
// Keep this order.
style.textContent =
fontFallback + "\n" +
- "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; }\n" +
+ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace; }\n" +
hostStyle + "\n" +
":root, svg { " + vars + " }\n";
@@ -961,23 +1059,30 @@
});
// ---- Toast ----------------------------------------------------------
+ // A live region only announces CHANGES to an existing node, so the toast
+ // element is created once up front and updated in place.
+ var toastEl = document.createElement('div');
+ toastEl.className = 'archify-toast';
+ toastEl.setAttribute('role', 'status');
+ document.body.appendChild(toastEl);
+ var toastTimer = null;
+
function toast(msg) {
- var t = document.createElement('div');
- t.className = 'archify-toast';
- t.textContent = msg;
- document.body.appendChild(t);
- requestAnimationFrame(function () { t.classList.add('show'); });
- setTimeout(function () {
- t.classList.remove('show');
- setTimeout(function () { t.remove(); }, 300);
- }, 1500);
+ toastEl.textContent = '';
+ requestAnimationFrame(function () {
+ toastEl.textContent = msg;
+ toastEl.classList.add('show');
+ });
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(function () { toastEl.classList.remove('show'); }, 1500);
}
- function open() {
+ function open(focusLast) {
menu.classList.add('open');
btn.setAttribute('aria-expanded', 'true');
- var first = items().filter(function (i) { return !i.disabled; })[0];
- if (first) first.focus();
+ var available = items().filter(function (i) { return !i.disabled; });
+ var target = focusLast ? available[available.length - 1] : available[0];
+ if (target) target.focus();
}
function close(focusTrigger) {
menu.classList.remove('open');
@@ -991,6 +1096,13 @@
if (isOpen()) close(false);
else open();
});
+ // APG menu-button pattern: ArrowDown/ArrowUp on the trigger opens the menu.
+ btn.addEventListener('keydown', function (e) {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault();
+ if (!isOpen()) open(e.key === 'ArrowUp');
+ }
+ });
document.addEventListener('click', function (e) {
if (!menu.contains(e.target) && e.target !== btn) close(false);
});
@@ -1026,7 +1138,7 @@
function runExport(format) {
var base = diagramFilename();
- close(false);
+ close(true);
return (format === 'svg'
? Promise.resolve(serializeSvg(1, { autoTheme: true })).then(function (d) {
download(new Blob([d.svgString], { type: 'image/svg+xml;charset=utf-8' }), base + '.svg');
@@ -1041,14 +1153,25 @@
}
function runCopy() {
- close(false);
+ close(true);
if (!canCopyImage()) {
alert('Clipboard image write not supported in this browser.');
return;
}
- return rasterize('png').then(function (blob) {
- return navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
- }).then(function () {
+ // WebKit requires ClipboardItem to be constructed synchronously inside
+ // the user gesture — pass the pending Promise<Blob> as the item value.
+ // Browsers that reject promise values throw synchronously; fall back
+ // to awaiting the blob first (works in Chromium/Firefox).
+ var blobPromise = rasterize('png');
+ var writePromise;
+ try {
+ writePromise = navigator.clipboard.write([new ClipboardItem({ 'image/png': blobPromise })]);
+ } catch (_) {
+ writePromise = blobPromise.then(function (blob) {
+ return navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ });
+ }
+ return writePromise.then(function () {
toast('Copied PNG to clipboard');
}).catch(function (err) {
console.error(err);
diff --git a/archify/examples/agent-tool-call.workflow.json b/archify/examples/agent-tool-call.workflow.json
index 74f68cdb..5b8e126f 100644
--- a/archify/examples/agent-tool-call.workflow.json
+++ b/archify/examples/agent-tool-call.workflow.json
@@ -31,11 +31,11 @@
{ "from": "chat", "to": "planner", "label": "plan", "variant": "emphasis", "fromSide": "bottom", "toSide": "top", "route": "drop", "labelSegment": 1 },
{ "from": "planner", "to": "router", "variant": "default" },
{ "from": "router", "to": "approval", "label": "needs approval?", "variant": "security", "fromSide": "bottom", "toSide": "top", "route": "drop", "labelSegment": 0, "labelDx": 34, "labelDy": 18 },
- { "from": "approval", "to": "tool", "label": "approved", "variant": "emphasis", "fromSide": "bottom", "toSide": "top", "route": "drop-right", "labelSegment": 1, "labelDy": 14 },
+ { "from": "approval", "to": "tool", "label": "approved", "variant": "emphasis", "fromSide": "bottom", "toSide": "top", "route": "drop", "labelSegment": 1, "labelDy": 14 },
{ "from": "tool", "to": "external", "variant": "default" },
{ "from": "external", "to": "trace", "label": "record result", "variant": "dashed", "fromSide": "bottom", "toSide": "bottom", "route": "bottom-channel", "labelSegment": 1 },
{ "from": "trace", "to": "final", "label": "summarize outcome", "variant": "emphasis", "fromSide": "right", "toSide": "right", "route": "outside-right", "labelSegment": 1, "labelDx": -22 },
- { "from": "planner", "to": "store", "label": "load context", "variant": "dashed", "fromSide": "bottom", "toSide": "top", "route": "drop-left", "labelSegment": 1 },
+ { "from": "planner", "to": "store", "label": "load context", "variant": "dashed", "fromSide": "bottom", "toSide": "top", "route": "drop", "labelSegment": 1 },
{ "from": "store", "to": "trace", "label": "write trace + memory", "variant": "dashed", "labelAt": [380, 622] }
],
"cards": [
diff --git a/archify/examples/web-app.architecture.json b/archify/examples/web-app.architecture.json
new file mode 100644
index 00000000..208c3983
--- /dev/null
+++ b/archify/examples/web-app.architecture.json
@@ -0,0 +1,41 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "Sample Web App",
+ "subtitle": "Classic 3-tier SaaS on AWS — rendered by Archify",
+ "output": "web-app-rendered.html"
+ },
+ "components": [
+ { "id": "users", "type": "external", "label": "Users", "sublabel": "Browser / Mobile", "pos": [40, 300], "size": [120, 60] },
+ { "id": "auth", "type": "security", "label": "Auth Provider", "sublabel": "OAuth 2.0", "pos": [40, 110], "size": [120, 64], "tag": "JWT + PKCE" },
+ { "id": "cdn", "type": "cloud", "label": "CloudFront", "sublabel": "CDN", "pos": [250, 300], "size": [130, 60] },
+ { "id": "lb", "type": "cloud", "label": "Load Balancer", "sublabel": "HTTPS :443", "pos": [460, 300], "size": [130, 60] },
+ { "id": "api", "type": "backend", "label": "API Server", "sublabel": "FastAPI :8000", "pos": [670, 300], "size": [130, 60] },
+ { "id": "cache", "type": "database", "label": "Redis", "sublabel": "cache :6379", "pos": [670, 150], "size": [130, 60] },
+ { "id": "db", "type": "database", "label": "PostgreSQL", "sublabel": "primary :5432", "pos": [880, 300], "size": [130, 60] },
+ { "id": "s3", "type": "cloud", "label": "S3", "sublabel": "static assets", "pos": [250, 440], "size": [130, 60], "tag": "OAI protected" },
+ { "id": "queue", "type": "messagebus", "label": "SQS", "sublabel": "job queue", "pos": [670, 440], "size": [130, 60] },
+ { "id": "worker", "type": "backend", "label": "Worker", "sublabel": "async jobs", "pos": [880, 440], "size": [130, 60] }
+ ],
+ "boundaries": [
+ { "kind": "region", "label": "AWS Region: us-west-2", "wraps": ["cdn", "lb", "api", "cache", "db", "s3", "queue", "worker"] },
+ { "kind": "security-group", "label": "sg-api :443/:8000", "wraps": ["lb", "api"] }
+ ],
+ "connections": [
+ { "from": "users", "to": "cdn", "label": "HTTPS", "variant": "emphasis" },
+ { "from": "auth", "to": "api", "label": "verify JWT", "variant": "security", "fromSide": "right", "toSide": "top" },
+ { "from": "cdn", "to": "lb" },
+ { "from": "cdn", "to": "s3", "label": "static", "variant": "dashed", "fromSide": "bottom", "toSide": "top", "labelDy": 58 },
+ { "from": "lb", "to": "api" },
+ { "from": "api", "to": "cache", "label": "read-through", "fromSide": "top", "toSide": "bottom", "labelDy": -68 },
+ { "from": "api", "to": "db", "label": "SQL" },
+ { "from": "api", "to": "queue", "label": "enqueue", "variant": "dashed", "fromSide": "bottom", "toSide": "top", "labelDy": 58 },
+ { "from": "queue", "to": "worker" }
+ ],
+ "cards": [
+ { "dot": "cyan", "title": "Edge", "items": ["CloudFront CDN fronts all traffic", "S3 serves static assets via OAI"] },
+ { "dot": "emerald", "title": "Application", "items": ["FastAPI behind an HTTPS load balancer", "Redis read-through cache", "Async work drained from SQS by a worker"] },
+ { "dot": "rose", "title": "Security", "items": ["OAuth 2.0 with JWT + PKCE", "API + LB isolated in a security group"] }
+ ]
+}
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
new file mode 100644
index 00000000..7e2745e9
--- /dev/null
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -0,0 +1,307 @@
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { esc, renderDefinitions, textUnits } from '../shared/utils.mjs';
+import { loadDiagram, writeDiagram, svgRootAttrs } from '../shared/cli.mjs';
+import {
+ asArray,
+ isFinitePoint,
+ rectsOverlap,
+ anchor,
+ defaultFromSide,
+ defaultToSide,
+ chosenSide,
+ polylinePath,
+ roundedPath,
+ labelPoint,
+ componentFill,
+ componentText,
+ arrowClassMap,
+ variantAccent,
+} from '../shared/geometry.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const { diagram: arch, template, outPath } = loadDiagram({
+ rendererDir: __dirname,
+ diagramType: 'architecture',
+ defaultExample: 'web-app.architecture.json',
+});
+
+const layout = {
+ defaultW: 120,
+ defaultH: 60,
+ margin: 40,
+ // Boundary padding — the 30/50 rule that was a hand-arithmetic footgun
+ // (CHANGELOG v2.2.1): 30px on top/left/right, plus 20px extra at the bottom.
+ boundaryPad: 30,
+ boundaryExtraBottom: 20,
+ legendH: 28,
+};
+
+// ---- Measure components from free coordinates --------------------------------
+function measureComponent(c) {
+ const [x, y] = Array.isArray(c.pos) ? c.pos : [NaN, NaN];
+ const [w, h] = Array.isArray(c.size) ? c.size : [layout.defaultW, layout.defaultH];
+ return { ...c, x, y, width: w, height: h, cx: x + w / 2, cy: y + h / 2 };
+}
+
+const components = new Map(asArray(arch.components).map((c) => [c.id, measureComponent(c)]));
+
+// ---- Boundaries computed from the `wraps` id list ---------------------------
+function boundaryRect(boundary) {
+ const members = asArray(boundary.wraps).map((id) => components.get(id)).filter(Boolean);
+ if (!members.length) return null;
+ const minX = Math.min(...members.map((m) => m.x));
+ const minY = Math.min(...members.map((m) => m.y));
+ const maxX = Math.max(...members.map((m) => m.x + m.width));
+ const maxY = Math.max(...members.map((m) => m.y + m.height));
+ const pad = boundary.pad ?? layout.boundaryPad;
+ return {
+ ...boundary,
+ x: minX - pad,
+ y: minY - pad,
+ width: maxX - minX + pad * 2,
+ height: maxY - minY + pad + layout.boundaryExtraBottom,
+ };
+}
+
+const boundaries = asArray(arch.boundaries).map(boundaryRect).filter(Boolean);
+
+// ---- Auto viewBox: fit all geometry + a legend row --------------------------
+function autoViewBox() {
+ let maxX = 0;
+ let maxY = 0;
+ for (const c of components.values()) {
+ maxX = Math.max(maxX, c.x + c.width);
+ maxY = Math.max(maxY, c.y + c.height);
+ }
+ for (const b of boundaries) {
+ maxX = Math.max(maxX, b.x + b.width);
+ maxY = Math.max(maxY, b.y + b.height);
+ }
+ return [
+ Math.ceil(maxX + layout.margin),
+ Math.ceil(maxY + layout.margin + layout.legendH),
+ ];
+}
+
+const viewBox = arch.meta?.viewBox || autoViewBox();
+const legendY = () => viewBox[1] - 16;
+
+// ---- Validation: mechanical correctness, never layout taste -----------------
+function validateArchitecture() {
+ const problems = [];
+ if (arch.schema_version !== 1) problems.push('Architecture files must set "schema_version": 1.');
+ if (arch.diagram_type !== 'architecture') problems.push('Architecture files must set "diagram_type": "architecture".');
+ if (!arch.meta?.title) problems.push('Architecture files must include meta.title.');
+ if (!Array.isArray(arch.components) || arch.components.length < 1) {
+ problems.push('Architecture diagrams need at least one component.');
+ }
+ if (arch.connections !== undefined && !Array.isArray(arch.connections)) problems.push('Architecture "connections" must be an array.');
+ if (arch.boundaries !== undefined && !Array.isArray(arch.boundaries)) problems.push('Architecture "boundaries" must be an array.');
+ if (arch.cards !== undefined && !Array.isArray(arch.cards)) problems.push('Architecture "cards" must be an array.');
+ if (components.size !== asArray(arch.components).length) problems.push('Component ids must be unique.');
+ if (problems.length) {
+ throw new Error(`Architecture layout validation failed:\n- ${problems.join('\n- ')}`);
+ }
+
+ for (const c of components.values()) {
+ if (!isFinitePoint(c.x, c.y, c.width, c.height)) {
+ problems.push(`Component "${c.id}" has non-finite pos/size — pos and size must be [number, number].`);
+ continue;
+ }
+ if (c.x < 0 || c.y < 0 || c.x + c.width > viewBox[0] || c.y + c.height > viewBox[1]) {
+ problems.push(`Component "${c.id}" falls outside the viewBox ${viewBox[0]}x${viewBox[1]} — adjust pos/size or set a larger meta.viewBox.`);
+ }
+ const estLabelW = textUnits(c.label) * 6.6;
+ if (estLabelW > c.width + 8) {
+ problems.push(`Label "${c.label}" (~${Math.round(estLabelW)}px) is wider than component "${c.id}" (${c.width}px) — shorten the label, move detail to sublabel, or widen size.`);
+ }
+ }
+
+ // Component overlap — the highest-traffic hand-placement failure mode.
+ const list = [...components.values()];
+ for (let i = 0; i < list.length; i += 1) {
+ for (let j = i + 1; j < list.length; j += 1) {
+ if (rectsOverlap(list[i], list[j], 8)) {
+ problems.push(`Components "${list[i].id}" and "${list[j].id}" are less than 8px apart — move one or shrink its size.`);
+ }
+ }
+ }
+
+ // Boundaries: every wrapped id must exist; the computed box must stay in view.
+ for (const boundary of asArray(arch.boundaries)) {
+ for (const id of asArray(boundary.wraps)) {
+ if (!components.has(id)) problems.push(`Boundary "${boundary.label}" wraps unknown component "${id}".`);
+ }
+ }
+ for (const b of boundaries) {
+ if (b.x < 0 || b.y < 0 || b.x + b.width > viewBox[0] || b.y + b.height > viewBox[1]) {
+ problems.push(`Boundary "${b.label}" extends outside the viewBox — its members sit too close to the canvas edge; add margin or enlarge meta.viewBox.`);
+ }
+ }
+
+ for (const conn of asArray(arch.connections)) {
+ if (!components.has(conn.from)) problems.push(`Connection "${conn.label || conn.from}" references unknown source "${conn.from}".`);
+ if (!components.has(conn.to)) problems.push(`Connection "${conn.label || conn.to}" references unknown target "${conn.to}".`);
+ if (components.has(conn.from) && components.has(conn.to)) {
+ const routed = pathFor(conn);
+ const [start, end] = [routed.points[0], routed.points[routed.points.length - 1]];
+ const distance = Math.hypot(end[0] - start[0], end[1] - start[1]);
+ if (distance < 24) problems.push(`Connection "${conn.label || `${conn.from}->${conn.to}`}" is too short (${Math.round(distance)}px; minimum 24px) — place its components farther apart.`);
+ }
+ }
+
+ // Connection labels must not land on top of components.
+ const labelRects = [];
+ for (const conn of asArray(arch.connections)) {
+ if (!conn.label || !components.has(conn.from) || !components.has(conn.to)) continue;
+ const [lx, ly] = labelPoint(conn, pathFor(conn).points);
+ const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
+ labelRects.push({ label: conn.label, x: lx - w / 2, y: ly - 10, width: w, height: 14 });
+ }
+ for (const rect of labelRects) {
+ for (const c of components.values()) {
+ if (rectsOverlap(rect, c, -2)) {
+ problems.push(`Label "${rect.label}" overlaps component "${c.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.`);
+ }
+ }
+ }
+
+ if (problems.length) {
+ throw new Error(`Architecture layout validation failed:\n- ${problems.join('\n- ')}`);
+ }
+}
+
+// ---- Connection routing ------------------------------------------------------
+function routeVia(conn, from, to, start, end) {
+ if (conn.via) return conn.via;
+ switch (conn.route || 'auto') {
+ case 'straight':
+ return [];
+ case 'orthogonal-h': {
+ const midX = (start[0] + end[0]) / 2;
+ return [[midX, start[1]], [midX, end[1]]];
+ }
+ case 'orthogonal-v': {
+ const midY = (start[1] + end[1]) / 2;
+ return [[start[0], midY], [end[0], midY]];
+ }
+ case 'auto':
+ default: {
+ // Direct line unless the anchors are clearly orthogonal-friendly.
+ if (Math.abs(start[0] - end[0]) < 4 || Math.abs(start[1] - end[1]) < 4) return [];
+ const midX = (start[0] + end[0]) / 2;
+ return [[midX, start[1]], [midX, end[1]]];
+ }
+ }
+}
+
+const pathCache = new Map();
+function pathFor(conn) {
+ if (pathCache.has(conn)) return pathCache.get(conn);
+ const from = components.get(conn.from);
+ const to = components.get(conn.to);
+ const start = anchor(from, chosenSide(conn.fromSide, defaultFromSide(from, to)));
+ const end = anchor(to, chosenSide(conn.toSide, defaultToSide(from, to)));
+ const points = [start, ...routeVia(conn, from, to, start, end), end];
+ const routed = { d: roundedPath(points, 8), points };
+ pathCache.set(conn, routed);
+ return routed;
+}
+
+// ---- Rendering ---------------------------------------------------------------
+function renderBoundary(b) {
+ const cls = b.kind === 'security-group' ? 'c-security-group' : 'c-region';
+ const labelCls = b.kind === 'security-group' ? 't-security' : 't-cloud';
+ const rx = b.kind === 'security-group' ? 8 : 12;
+ return ` <rect x="${b.x}" y="${b.y}" width="${b.width}" height="${b.height}" rx="${rx}" class="${cls}" stroke-width="1"/>
+ <text x="${b.x + 8}" y="${b.y + 18}" class="${labelCls}" font-size="9" font-weight="600">${esc(b.label)}</text>`;
+}
+
+function renderConnectionPath(conn) {
+ const [cls, marker] = arrowClassMap[conn.variant || 'default'] || arrowClassMap.default;
+ const routed = pathFor(conn);
+ const strokeWidth = conn.width || (conn.variant === 'emphasis' ? 1.8 : 1.5);
+ return ` <path d="${routed.d}" class="${cls}" stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
+}
+
+function renderConnectionLabel(conn) {
+ if (!conn.label) return '';
+ const [lx, ly] = labelPoint(conn, pathFor(conn).points);
+ const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
+ return ` <rect x="${lx - w / 2}" y="${ly - 10}" width="${w}" height="14" rx="3" class="c-mask"/>
+ <text x="${lx}" y="${ly}" class="${variantAccent(conn.variant)}" font-size="8" text-anchor="middle">${esc(conn.label)}</text>`;
+}
+
+function renderComponent(c) {
+ const fill = componentFill[c.type] || 'c-external';
+ const accent = componentText[c.type] || 't-muted';
+ const cx = c.cx;
+ const hasSub = c.sublabel != null && c.sublabel !== '';
+ const labelY = hasSub ? c.y + c.height / 2 - 2 : c.y + c.height / 2 + 4;
+ const sub = hasSub
+ ? `\n <text x="${cx}" y="${c.y + c.height / 2 + 14}" class="t-muted" font-size="9" text-anchor="middle">${esc(c.sublabel)}</text>`
+ : '';
+ const tag = c.tag
+ ? `\n <text x="${cx}" y="${c.y + c.height - 8}" class="${accent}" font-size="7" text-anchor="middle">${esc(c.tag)}</text>`
+ : '';
+ return ` <rect x="${c.x}" y="${c.y}" width="${c.width}" height="${c.height}" rx="6" class="c-mask"/>
+ <rect x="${c.x}" y="${c.y}" width="${c.width}" height="${c.height}" rx="6" class="${fill}" stroke-width="1.5"/>
+ <text x="${cx}" y="${labelY}" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">${esc(c.label)}</text>${sub}${tag}`;
+}
+
+// Auto legend: one swatch per component type actually used, left to right.
+const TYPE_LABELS = {
+ frontend: 'Frontend', backend: 'Backend', database: 'Database', cloud: 'Cloud',
+ security: 'Security', messagebus: 'Message bus', external: 'External',
+};
+function renderLegend() {
+ const used = [];
+ const seen = new Set();
+ for (const c of components.values()) {
+ if (!seen.has(c.type)) { seen.add(c.type); used.push(c.type); }
+ }
+ const y = legendY();
+ let x = layout.margin;
+ const parts = [` <text x="${x}" y="${y - 13}" class="t-primary" font-size="9" font-weight="600">Legend</text>`];
+ for (const type of used) {
+ parts.push(` <rect x="${x}" y="${y - 8}" width="14" height="9" rx="2" class="${componentFill[type] || 'c-external'}" stroke-width="1"/>`);
+ parts.push(` <text x="${x + 20}" y="${y}" class="t-muted" font-size="8">${TYPE_LABELS[type] || type}</text>`);
+ x += 30 + (textUnits(TYPE_LABELS[type] || type) * 5 + 28);
+ }
+ return parts.join('\n');
+}
+
+function renderSvg() {
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(arch.meta, 'architecture diagram')}>
+${renderDefinitions()}
+
+ <!-- Background Grid -->
+ <rect width="100%" height="100%" fill="url(#grid)" />
+
+ <!-- Boundaries (behind everything) -->
+${boundaries.map(renderBoundary).join('\n\n')}
+
+ <!-- Connection paths (before components for correct z-order) -->
+${asArray(arch.connections).map(renderConnectionPath).join('\n')}
+
+ <!-- Components -->
+${[...components.values()].map(renderComponent).join('\n\n')}
+
+ <!-- Connection labels -->
+${asArray(arch.connections).map(renderConnectionLabel).join('\n')}
+
+ <!-- Legend -->
+${renderLegend()}
+ </svg>`;
+}
+
+validateArchitecture();
+writeDiagram({
+ outPath,
+ template,
+ meta: arch.meta,
+ footerLabel: 'Architecture diagram',
+ svg: renderSvg(),
+ cards: arch.cards,
+});
diff --git a/archify/renderers/dataflow/README.md b/archify/renderers/dataflow/README.md
index 6735fc88..38e2ed82 100644
--- a/archify/renderers/dataflow/README.md
+++ b/archify/renderers/dataflow/README.md
@@ -7,6 +7,11 @@ template.
node archify/renderers/dataflow/render-dataflow.mjs input.dataflow.json output.html
```
+Run `npm install` once in the skill folder first — the renderer validates the
+input against `archify/schemas/dataflow.schema.json` via ajv. Without it, the
+renderer prints a warning and skips schema validation; its own layout checks
+still run.
+
If `output.html` is omitted, the renderer uses `meta.output` from the JSON file
or falls back to `dataflow.html` in the current working directory.
@@ -21,7 +26,7 @@ Data-flow JSON files must set:
"meta": {
"title": "Product Analytics Data Flow",
"subtitle": "Events, consent, PII isolation, warehouse sync, and consumers",
- "viewBox": [900, 720]
+ "viewBox": [940, 720]
},
"stages": [],
"nodes": [],
@@ -30,12 +35,31 @@ Data-flow JSON files must set:
}
```
+A complete worked example lives at
+`archify/examples/product-analytics.dataflow.json`.
+
The schema lives at:
```text
archify/schemas/dataflow.schema.json
```
+## Layout budget
+
+| Constant | Value |
+|----------|-------|
+| viewBox | default `[940, 720]`; schema minimum `[360, 360]` |
+| Stages (2–5) | centers at x = 100 + stage×215; stage band 168 wide, header at y 46 |
+| Row tops (`row` 0–4) | y = 128, 242, 356, 470, 584 (plus `yOffset`) |
+| Default node | 112×58 |
+| Node area | x within `[24, width − 24]`; y within `[104, height − 74]` |
+| Node spacing | ≥10px between any two nodes (checked across stages and rows) |
+| Flow length | ≥34px between endpoints |
+| Legend row | y = height − 36 |
+
+Route presets for flows: `straight`, `vertical-channel`, `bottom-channel`,
+`top-channel`, explicit `via` points, or the default `auto` (midpoint elbow).
+
## Design Rules
- Use stages for data lifecycle boundaries: source, ingest, process, store,
@@ -51,7 +75,10 @@ archify/schemas/dataflow.schema.json
derivations.
- Keep labels short enough to fit in narrow previews.
-The renderer fails when it can detect layout problems, including missing stages,
-duplicate node IDs, nodes outside the readable diagram area, node overlap,
-unknown flow endpoints, missing flow labels, unreadably short flows, or stages
-that exceed the viewBox.
+Schema violations exit non-zero with path-prefixed messages annotated with the
+element's id or label. The renderer additionally fails when it can detect
+layout problems, including missing stages, duplicate node IDs, nodes outside
+the readable diagram area, node overlap, labels colliding with nodes or other
+labels, labels wider than their node, unknown flow endpoints, missing flow
+labels, unreadably short flows, or stages that exceed the viewBox. Text width
+is estimated CJK-aware: fullwidth glyphs count as two units.
diff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjs
index d5914b1f..f5307005 100644
--- a/archify/renderers/dataflow/render-dataflow.mjs
+++ b/archify/renderers/dataflow/render-dataflow.mjs
@@ -1,20 +1,31 @@
-import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { esc, renderDefinitions, renderCards, applyTemplate } from '../shared/utils.mjs';
-import { validateSchema } from '../shared/validator.mjs';
+import { esc, renderDefinitions, textUnits } from '../shared/utils.mjs';
+import { loadDiagram, writeDiagram, svgRootAttrs } from '../shared/cli.mjs';
+import {
+ asArray,
+ isFinitePoint,
+ rectsOverlap,
+ anchor,
+ defaultFromSide,
+ defaultToSide,
+ chosenSide,
+ polylinePath,
+ labelPoint,
+ componentFill,
+ componentText,
+ arrowClassMap,
+ variantAccent
+} from '../shared/geometry.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const skillRoot = path.resolve(__dirname, '../..');
-const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/product-analytics.dataflow.json'));
-const dataflow = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
-validateSchema('dataflow', dataflow);
+const { diagram: dataflow, template, outPath } = loadDiagram({
+ rendererDir: __dirname,
+ diagramType: 'dataflow',
+ defaultExample: 'product-analytics.dataflow.json'
+});
-const templatePath = path.join(skillRoot, 'assets/template.html');
-const template = fs.readFileSync(templatePath, 'utf8');
-const outPath = path.resolve(process.cwd(), process.argv[3] || dataflow.meta.output || 'dataflow.html');
-
-const viewBox = dataflow.meta.viewBox || [940, 720];
+const viewBox = dataflow.meta?.viewBox || [940, 720];
const layout = {
stageY: 46,
stageH: 36,
@@ -28,33 +39,6 @@ const layout = {
labelH: 16
};
-const typeClass = {
- frontend: 'c-frontend',
- backend: 'c-backend',
- database: 'c-database',
- cloud: 'c-cloud',
- security: 'c-security',
- messagebus: 'c-messagebus',
- external: 'c-external'
-};
-
-const textClass = {
- frontend: 't-frontend',
- backend: 't-backend',
- database: 't-database',
- cloud: 't-cloud',
- security: 't-security',
- messagebus: 't-messagebus',
- external: 't-external'
-};
-
-const arrowClass = {
- default: ['a-default', 'arrowhead'],
- emphasis: ['a-emphasis', 'arrowhead-emphasis'],
- security: ['a-security', 'arrowhead-security'],
- dashed: ['a-dashed', 'arrowhead-dashed']
-};
-
function stageX(index) {
return layout.leftX + index * layout.colGap;
}
@@ -75,16 +59,7 @@ function measureNode(node) {
};
}
-const nodes = new Map((dataflow.nodes || []).map((node) => [node.id, measureNode(node)]));
-
-function rectsOverlap(a, b, gap = 0) {
- return !(
- a.x + a.width + gap <= b.x ||
- b.x + b.width + gap <= a.x ||
- a.y + a.height + gap <= b.y ||
- b.y + b.height + gap <= a.y
- );
-}
+const nodes = new Map(asArray(dataflow.nodes).map((node) => [node.id, measureNode(node)]));
function validateDataflow() {
const problems = [];
@@ -98,34 +73,45 @@ function validateDataflow() {
problems.push('Data-flow diagrams need at least two nodes.');
}
if (!Array.isArray(dataflow.flows)) problems.push('Data-flow diagrams must include a flows array.');
- if (nodes.size !== (dataflow.nodes || []).length) problems.push('Node ids must be unique.');
+ if (dataflow.cards !== undefined && !Array.isArray(dataflow.cards)) problems.push('Data-flow "cards" must be an array.');
+ if (nodes.size !== asArray(dataflow.nodes).length) problems.push('Node ids must be unique.');
+ const stageCount = asArray(dataflow.stages).length;
for (const node of nodes.values()) {
- if (typeof node.stage !== 'number' || node.stage < 0 || node.stage >= dataflow.stages.length) {
- problems.push(`Node "${node.id}" uses invalid stage ${node.stage}.`);
+ if (typeof node.stage !== 'number' || node.stage < 0 || node.stage >= stageCount) {
+ problems.push(`Node "${node.id}" uses invalid stage ${node.stage} — valid stages are 0..${stageCount - 1}.`);
}
if (typeof node.row !== 'number' || node.row < 0 || node.row >= layout.rowYs.length) {
- problems.push(`Node "${node.id}" uses invalid row ${node.row}.`);
+ problems.push(`Node "${node.id}" uses invalid row ${node.row} — valid rows are 0..${layout.rowYs.length - 1}.`);
+ }
+ if (!isFinitePoint(node.x, node.y, node.cx, node.cy)) {
+ problems.push(`Node "${node.id}" produced non-finite coordinates — check stage, row, width, height, and yOffset are numbers.`);
+ continue;
}
if (node.x < 24 || node.x + node.width > viewBox[0] - 24) {
- problems.push(`Node "${node.id}" exceeds the horizontal bounds of the viewBox.`);
+ problems.push(`Node "${node.id}" exceeds the horizontal bounds of the viewBox — reduce node.width or increase meta.viewBox[0].`);
}
if (node.y < layout.stageY + layout.stageH + 22 || node.y + node.height > viewBox[1] - layout.stageBottomPad) {
- problems.push(`Node "${node.id}" exceeds the readable diagram area.`);
+ problems.push(`Node "${node.id}" exceeds the readable diagram area — keep y between ${layout.stageY + layout.stageH + 22} and ${viewBox[1] - layout.stageBottomPad} (adjust row/yOffset or increase meta.viewBox[1]).`);
+ }
+ const estLabelW = textUnits(node.label) * 6.2;
+ if (estLabelW > node.width + 6) {
+ problems.push(`Label "${node.label}" (~${Math.round(estLabelW)}px) is wider than node "${node.id}" (${node.width}px) — shorten the label, move detail to sublabel, or increase node.width.`);
}
}
- for (let i = 0; i < dataflow.nodes.length; i += 1) {
- for (let j = i + 1; j < dataflow.nodes.length; j += 1) {
- const a = nodes.get(dataflow.nodes[i].id);
- const b = nodes.get(dataflow.nodes[j].id);
+ const nodeList = asArray(dataflow.nodes);
+ for (let i = 0; i < nodeList.length; i += 1) {
+ for (let j = i + 1; j < nodeList.length; j += 1) {
+ const a = nodes.get(nodeList[i].id);
+ const b = nodes.get(nodeList[j].id);
if (rectsOverlap(a, b, 10)) {
- problems.push(`Nodes "${a.id}" and "${b.id}" are too close.`);
+ problems.push(`Nodes "${a.id}" and "${b.id}" are less than 10px apart — move one to another stage/row or adjust yOffset.`);
}
}
}
- for (const flow of dataflow.flows || []) {
+ for (const flow of asArray(dataflow.flows)) {
if (!nodes.has(flow.from)) problems.push(`Flow "${flow.label || flow.from}" references unknown source "${flow.from}".`);
if (!nodes.has(flow.to)) problems.push(`Flow "${flow.label || flow.to}" references unknown target "${flow.to}".`);
if (!flow.label) problems.push(`Flow "${flow.from}" -> "${flow.to}" must include a short data label.`);
@@ -133,41 +119,42 @@ function validateDataflow() {
const routed = pathFor(flow);
const [start, end] = [routed.points[0], routed.points[routed.points.length - 1]];
const distance = Math.hypot(end[0] - start[0], end[1] - start[1]);
- if (distance < 34) problems.push(`Flow "${flow.label}" is too short to read cleanly.`);
+ if (distance < 34) problems.push(`Flow "${flow.label}" is too short (${Math.round(distance)}px; minimum 34px) — route it through a channel or spread its nodes.`);
}
}
- const lastStageX = stageX((dataflow.stages || []).length - 1);
- if (lastStageX + layout.stageW / 2 > viewBox[0] - 24) problems.push('Stages exceed viewBox width.');
-
- if (problems.length) {
- throw new Error(`Data-flow layout validation failed:\n- ${problems.join('\n- ')}`);
+ const labelRects = [];
+ for (const flow of asArray(dataflow.flows)) {
+ if (!flow.label || !nodes.has(flow.from) || !nodes.has(flow.to)) continue;
+ const [lx, ly] = labelPoint(flow, pathFor(flow).points);
+ const longestLine = Math.max(textUnits(flow.label), textUnits(flow.classification || ''));
+ const width = Math.max(34, longestLine * 4.9 + 12);
+ const height = flow.classification ? 27 : layout.labelH;
+ labelRects.push({ label: flow.label, x: lx - width / 2, y: ly - 11, width, height });
}
-}
-
-function anchor(node, side) {
- switch (side || 'auto') {
- case 'left': return [node.x, node.cy];
- case 'right': return [node.x + node.width, node.cy];
- case 'top': return [node.cx, node.y];
- case 'bottom': return [node.cx, node.y + node.height];
- default:
- return [node.x + node.width, node.cy];
+ for (const rect of labelRects) {
+ for (const node of nodes.values()) {
+ if (rectsOverlap(rect, node, -2)) {
+ problems.push(`Label "${rect.label}" overlaps node "${node.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.`);
+ }
+ }
+ }
+ for (let i = 0; i < labelRects.length; i += 1) {
+ for (let j = i + 1; j < labelRects.length; j += 1) {
+ if (rectsOverlap(labelRects[i], labelRects[j], -2)) {
+ problems.push(`Labels "${labelRects[i].label}" and "${labelRects[j].label}" overlap — adjust labelDx/labelDy.`);
+ }
+ }
}
-}
-function defaultFromSide(from, to) {
- if (to.cx < from.cx) return 'left';
- if (to.cx > from.cx) return 'right';
- if (to.cy > from.cy) return 'bottom';
- return 'top';
-}
+ const lastStageX = stageX(asArray(dataflow.stages).length - 1);
+ if (lastStageX + layout.stageW / 2 > viewBox[0] - 24) {
+ problems.push(`Stages exceed viewBox width — set meta.viewBox[0] to at least ${Math.ceil(lastStageX + layout.stageW / 2 + 24)}.`);
+ }
-function defaultToSide(from, to) {
- if (to.cx < from.cx) return 'right';
- if (to.cx > from.cx) return 'left';
- if (to.cy > from.cy) return 'top';
- return 'bottom';
+ if (problems.length) {
+ throw new Error(`Data-flow layout validation failed:\n- ${problems.join('\n- ')}`);
+ }
}
function routeVia(flow, from, to, start, end) {
@@ -176,15 +163,15 @@ function routeVia(flow, from, to, start, end) {
case 'straight':
return [];
case 'vertical-channel': {
- const x = flow.channelX || start[0] + (end[0] > start[0] ? 44 : -44);
+ const x = flow.channelX ?? start[0] + (end[0] > start[0] ? 44 : -44);
return [[x, start[1]], [x, end[1]]];
}
case 'bottom-channel': {
- const y = flow.channelY || Math.max(from.y + from.height, to.y + to.height) + 26;
+ const y = flow.channelY ?? Math.max(from.y + from.height, to.y + to.height) + 26;
return [[start[0], y], [end[0], y]];
}
case 'top-channel': {
- const y = flow.channelY || Math.min(from.y, to.y) - 24;
+ const y = flow.channelY ?? Math.min(from.y, to.y) - 24;
return [[start[0], y], [end[0], y]];
}
case 'auto':
@@ -196,30 +183,18 @@ function routeVia(flow, from, to, start, end) {
}
}
+const pathCache = new Map();
+
function pathFor(flow) {
+ if (pathCache.has(flow)) return pathCache.get(flow);
const from = nodes.get(flow.from);
const to = nodes.get(flow.to);
- const start = anchor(from, flow.fromSide || defaultFromSide(from, to));
- const end = anchor(to, flow.toSide || defaultToSide(from, to));
+ const start = anchor(from, chosenSide(flow.fromSide, defaultFromSide(from, to)));
+ const end = anchor(to, chosenSide(flow.toSide, defaultToSide(from, to)));
const points = [start, ...routeVia(flow, from, to, start, end), end];
- return {
- d: points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' '),
- points
- };
-}
-
-function labelPoint(flow, points) {
- if (flow.labelAt) return flow.labelAt;
- if (points.length === 2) {
- return [
- (points[0][0] + points[1][0]) / 2 + (flow.labelDx || 0),
- points[0][1] - 10 + (flow.labelDy || 0)
- ];
- }
- const segmentIndex = Math.min(points.length - 2, Math.max(0, flow.labelSegment ?? 1));
- const a = points[segmentIndex];
- const b = points[segmentIndex + 1];
- return [(a[0] + b[0]) / 2 + (flow.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (flow.labelDy || 0)];
+ const routed = { d: polylinePath(points), points };
+ pathCache.set(flow, routed);
+ return routed;
}
function renderStage(stage, index) {
@@ -231,8 +206,8 @@ function renderStage(stage, index) {
}
function renderNode(node) {
- const fill = typeClass[node.type] || 'c-external';
- const accent = textClass[node.type] || 't-muted';
+ const fill = componentFill[node.type] || 'c-external';
+ const accent = componentText[node.type] || 't-muted';
const tag = node.tag
? `\n <text x="${node.cx}" y="${node.y + node.height - 11}" class="${accent}" font-size="7" text-anchor="middle">${esc(node.tag)}</text>`
: '';
@@ -242,18 +217,8 @@ function renderNode(node) {
<text x="${node.cx}" y="${node.y + 37}" class="t-muted" font-size="7" text-anchor="middle">${esc(node.sublabel || '')}</text>${tag}`;
}
-function flowAccent(flow) {
- return flow.variant === 'security'
- ? 't-security'
- : flow.variant === 'emphasis'
- ? 't-backend'
- : flow.variant === 'dashed'
- ? 't-messagebus'
- : 't-muted';
-}
-
function renderFlowPath(flow) {
- const [cls, marker] = arrowClass[flow.variant || 'default'] || arrowClass.default;
+ const [cls, marker] = arrowClassMap[flow.variant || 'default'] || arrowClassMap.default;
const routed = pathFor(flow);
const strokeWidth = flow.width || (flow.variant === 'emphasis' ? 1.8 : 1.4);
return ` <path d="${routed.d}" class="${cls}" stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
@@ -262,14 +227,14 @@ function renderFlowPath(flow) {
function renderFlowLabel(flow) {
const routed = pathFor(flow);
const [lx, ly] = labelPoint(flow, routed.points);
- const longestLine = Math.max(flow.label.length, (flow.classification || '').length);
+ const longestLine = Math.max(textUnits(flow.label), textUnits(flow.classification || ''));
const labelW = Math.max(34, longestLine * 4.9 + 12);
const classification = flow.classification
? `\n <text x="${lx}" y="${ly + 11}" class="t-dim" font-size="7" text-anchor="middle">${esc(flow.classification)}</text>`
: '';
const labelH = flow.classification ? 27 : layout.labelH;
return ` <rect x="${lx - labelW / 2}" y="${ly - 11}" width="${labelW}" height="${labelH}" rx="4" class="c-mask"/>
- <text x="${lx}" y="${ly}" class="${flowAccent(flow)}" font-size="8" text-anchor="middle">${esc(flow.label)}</text>${classification}`;
+ <text x="${lx}" y="${ly}" class="${variantAccent(flow.variant)}" font-size="8" text-anchor="middle">${esc(flow.label)}</text>${classification}`;
}
function renderLegend() {
@@ -286,7 +251,7 @@ function renderLegend() {
}
function renderSvg() {
- return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(dataflow.meta, 'data-flow diagram')}>
${renderDefinitions()}
<!-- Background Grid -->
@@ -296,13 +261,13 @@ ${renderDefinitions()}
${dataflow.stages.map(renderStage).join('\n\n')}
<!-- Flow paths -->
-${(dataflow.flows || []).map(renderFlowPath).join('\n')}
+${asArray(dataflow.flows).map(renderFlowPath).join('\n')}
<!-- Nodes -->
${[...nodes.values()].map(renderNode).join('\n\n')}
<!-- Flow labels -->
-${(dataflow.flows || []).map(renderFlowLabel).join('\n')}
+${asArray(dataflow.flows).map(renderFlowLabel).join('\n')}
<!-- Legend -->
${renderLegend()}
@@ -310,12 +275,11 @@ ${renderLegend()}
}
validateDataflow();
-fs.mkdirSync(path.dirname(outPath), { recursive: true });
-fs.writeFileSync(outPath, applyTemplate(template, {
- title: dataflow.meta.title,
- subtitle: dataflow.meta.subtitle,
- footer: 'Data-flow diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export',
+writeDiagram({
+ outPath,
+ template,
+ meta: dataflow.meta,
+ footerLabel: 'Data-flow diagram',
svg: renderSvg(),
- cards: renderCards(dataflow.cards),
-}));
-console.log(outPath);
+ cards: dataflow.cards,
+});
diff --git a/archify/renderers/lifecycle/README.md b/archify/renderers/lifecycle/README.md
index 20745912..cb5b9806 100644
--- a/archify/renderers/lifecycle/README.md
+++ b/archify/renderers/lifecycle/README.md
@@ -7,6 +7,11 @@ template.
node archify/renderers/lifecycle/render-lifecycle.mjs input.lifecycle.json output.html
```
+Run `npm install` once in the skill folder first — the renderer validates the
+input against `archify/schemas/lifecycle.schema.json` via ajv. Without it, the
+renderer prints a warning and skips schema validation; its own layout checks
+still run.
+
If `output.html` is omitted, the renderer uses `meta.output` from the JSON file
or falls back to `lifecycle.html` in the current working directory.
@@ -30,12 +35,42 @@ Lifecycle JSON files must set:
}
```
+Lane ids are semantic and reserved: a lane with id `main` is required and maps
+to the top phase band; `terminal` maps to the bottom outcome band; every other
+lane id (up to 4 lanes total) shares the single middle event band. The three
+band headers render from your lane labels — the middle band joins the labels of
+all event lanes with ` + `. A complete worked example lives at
+`archify/examples/agent-run.lifecycle.json`.
+
The schema lives at:
```text
archify/schemas/lifecycle.schema.json
```
+## Layout budget
+
+| Band | Lane id | Top y | Column centers | Default state |
+|------|---------|-------|----------------|---------------|
+| Phase | `main` (required) | 126 | `col` 0–4 → x = 94, 248, 402, 556, 710 | 118×62 |
+| Event | any other id | 278 | `col` 0–2 → x = 402, 556, 710 | 126×58 |
+| Outcome | `terminal` | 450 | `col` 0–2 → x = 402, 556, 710 | 118×58 |
+
+| Constant | Value |
+|----------|-------|
+| viewBox | default `[980, 660]`; schema minimum `[420, 360]` |
+| State area | x within `[32, width − 32]`; y within `[64, legend y − 24]` |
+| State spacing | ≥10px between any two states — checked across lanes, because all event lanes share one band; separate same-band states with `col` or `yOffset` |
+| Transition length | ≥32px between endpoints |
+| Legend row | y = height − 98 |
+
+The primary lifecycle rail runs along the phase band and extends to the
+furthest occupied phase column. Route presets for transitions: `straight`,
+`drop` (bend at `channelY`, defaulting to the vertical midpoint),
+`bottom-channel`, `top-channel`, `right-channel`, `left-channel`, explicit
+`via` points, or the default `auto`. Multi-segment transitions get rounded
+corners; tune them with `cornerRadius` (default 10, `0` for sharp bends).
+
## Design Rules
- Treat lifecycle diagrams as a phase map, not a dense state-transition graph.
@@ -49,7 +84,10 @@ archify/schemas/lifecycle.schema.json
- Use `success` for completion, `failure` for failure/terminal exits,
`waiting` for pauses, and `decision` for quality gates.
-The renderer fails when it can detect layout problems, including duplicate state
-IDs, unknown lanes, unknown transition endpoints, states outside their lanes,
-overlapping states, unreadably short transitions, or a legend outside the
-viewBox.
+Schema violations exit non-zero with path-prefixed messages annotated with the
+element's id or label. The renderer additionally fails when it can detect
+layout problems, including a missing `main` lane, duplicate state IDs, unknown
+lanes, unknown transition endpoints, states outside the lifecycle area,
+overlapping states (including across lanes), labels colliding with states or
+other labels, labels wider than their state, or unreadably short transitions.
+Text width is estimated CJK-aware: fullwidth glyphs count as two units.
diff --git a/archify/renderers/lifecycle/render-lifecycle.mjs b/archify/renderers/lifecycle/render-lifecycle.mjs
index b02f7a6f..4016710d 100644
--- a/archify/renderers/lifecycle/render-lifecycle.mjs
+++ b/archify/renderers/lifecycle/render-lifecycle.mjs
@@ -1,20 +1,29 @@
-import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { esc, renderDefinitions, renderCards, applyTemplate } from '../shared/utils.mjs';
-import { validateSchema } from '../shared/validator.mjs';
+import { esc, renderDefinitions, textUnits } from '../shared/utils.mjs';
+import { loadDiagram, writeDiagram, svgRootAttrs } from '../shared/cli.mjs';
+import {
+ asArray,
+ isFinitePoint,
+ rectsOverlap,
+ anchor,
+ defaultFromSide,
+ defaultToSide,
+ chosenSide,
+ roundedPath,
+ labelPoint,
+ arrowClassMap,
+ variantAccent
+} from '../shared/geometry.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const skillRoot = path.resolve(__dirname, '../..');
-const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/agent-run.lifecycle.json'));
-const lifecycle = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
-validateSchema('lifecycle', lifecycle);
+const { diagram: lifecycle, template, outPath } = loadDiagram({
+ rendererDir: __dirname,
+ diagramType: 'lifecycle',
+ defaultExample: 'agent-run.lifecycle.json'
+});
-const templatePath = path.join(skillRoot, 'assets/template.html');
-const template = fs.readFileSync(templatePath, 'utf8');
-const outPath = path.resolve(process.cwd(), process.argv[3] || lifecycle.meta.output || 'lifecycle.html');
-
-const viewBox = lifecycle.meta.viewBox || [980, 660];
+const viewBox = lifecycle.meta?.viewBox || [980, 660];
const layout = {
phaseY: 126,
eventY: 278,
@@ -52,20 +61,22 @@ const textClass = {
external: 't-muted'
};
-const arrowClass = {
- default: ['a-default', 'arrowhead'],
- emphasis: ['a-emphasis', 'arrowhead-emphasis'],
- security: ['a-security', 'arrowhead-security'],
- dashed: ['a-dashed', 'arrowhead-dashed']
-};
-
function legendY() {
- return 562;
+ return viewBox[1] - 98;
+}
+
+// Lane semantics are fixed: lane id "main" maps to the top phase band, lane id
+// "terminal" maps to the bottom outcome band, and every other lane shares the
+// middle event band (separated visually via yOffset).
+function bandFor(lane) {
+ if (lane === 'main') return 'phase';
+ if (lane === 'terminal') return 'outcome';
+ return 'event';
}
function measureState(state) {
- const isPhase = state.lane === 'main';
- const isOutcome = state.lane === 'terminal';
+ const isPhase = bandFor(state.lane) === 'phase';
+ const isOutcome = bandFor(state.lane) === 'outcome';
const width = state.width || (isPhase ? layout.phaseW : isOutcome ? layout.outcomeW : layout.eventW);
const height = state.height || (isPhase ? layout.phaseH : isOutcome ? layout.outcomeH : layout.eventH);
const xs = isPhase ? layout.phaseXs : isOutcome ? layout.outcomeXs : layout.eventXs;
@@ -86,16 +97,7 @@ function measureState(state) {
};
}
-const states = new Map((lifecycle.states || []).map((state) => [state.id, measureState(state)]));
-
-function rectsOverlap(a, b, gap = 0) {
- return !(
- a.x + a.width + gap <= b.x ||
- b.x + b.width + gap <= a.x ||
- a.y + a.height + gap <= b.y ||
- b.y + b.height + gap <= a.y
- );
-}
+const states = new Map(asArray(lifecycle.states).map((state) => [state.id, measureState(state)]));
function validateLifecycle() {
const problems = [];
@@ -105,187 +107,175 @@ function validateLifecycle() {
if (!Array.isArray(lifecycle.lanes) || lifecycle.lanes.length < 1) problems.push('Lifecycle diagrams need at least one lane.');
if (!Array.isArray(lifecycle.states) || lifecycle.states.length < 2) problems.push('Lifecycle diagrams need at least two states.');
if (!Array.isArray(lifecycle.transitions)) problems.push('Lifecycle diagrams must include a transitions array.');
- if (states.size !== (lifecycle.states || []).length) problems.push('State ids must be unique.');
+ if (lifecycle.cards !== undefined && !Array.isArray(lifecycle.cards)) problems.push('Lifecycle "cards" must be an array.');
+ if (states.size !== asArray(lifecycle.states).length) problems.push('State ids must be unique.');
- const laneIds = new Set((lifecycle.lanes || []).map((lane) => lane.id));
- if (laneIds.size !== (lifecycle.lanes || []).length) problems.push('Lane ids must be unique.');
+ // The three bands are fixed at y=112/264/436; the legend (viewBox[1] - 98)
+ // must clear the outcome band's header zone.
+ if (legendY() - 20 < 448) {
+ problems.push(`viewBox height ${viewBox[1]} is too short for the fixed band layout — set meta.viewBox[1] to at least 566.`);
+ }
+
+ const laneIds = new Set(asArray(lifecycle.lanes).map((lane) => lane.id));
+ if (laneIds.size !== asArray(lifecycle.lanes).length) problems.push('Lane ids must be unique.');
+ if (!laneIds.has('main')) {
+ problems.push('Lifecycle diagrams need a lane with id "main" (the phase rail). Lane ids "main" and "terminal" are reserved: "main" maps to the top phase band, "terminal" to the bottom outcome band, and all other lanes share the middle event band.');
+ }
for (const state of states.values()) {
if (!laneIds.has(state.lane)) {
problems.push(`State "${state.id}" uses unknown lane "${state.lane}".`);
continue;
}
- const maxCol = state.lane === 'main'
+ const band = bandFor(state.lane);
+ const maxCol = band === 'phase'
? layout.phaseXs.length
- : state.lane === 'terminal'
+ : band === 'outcome'
? layout.outcomeXs.length
: layout.eventXs.length;
- if (typeof state.col !== 'number' || state.col < 0 || state.col >= maxCol) {
- problems.push(`State "${state.id}" uses invalid column ${state.col}.`);
+ if (!Number.isInteger(state.col) || state.col < 0 || state.col >= maxCol) {
+ problems.push(`State "${state.id}" uses invalid column ${state.col} — the ${band} band has integer columns 0..${maxCol - 1}.`);
+ continue;
+ }
+ if (!isFinitePoint(state.x, state.y, state.cx, state.cy)) {
+ problems.push(`State "${state.id}" produced non-finite coordinates — check col, width, height, and yOffset are numbers.`);
+ continue;
}
if (state.x < 32 || state.x + state.width > viewBox[0] - 32) {
- problems.push(`State "${state.id}" exceeds the horizontal bounds of the diagram.`);
+ problems.push(`State "${state.id}" exceeds the horizontal bounds of the diagram — reduce state.width or increase meta.viewBox[0].`);
}
if (state.y < 64 || state.y + state.height > legendY() - 24) {
- problems.push(`State "${state.id}" exceeds the vertical lifecycle area.`);
+ problems.push(`State "${state.id}" exceeds the vertical lifecycle area — keep y between 64 and ${legendY() - 24} (adjust yOffset or increase meta.viewBox[1]).`);
+ }
+ const estLabelW = textUnits(state.label) * 6.2;
+ if (estLabelW > state.width + 6) {
+ problems.push(`Label "${state.label}" (~${Math.round(estLabelW)}px) is wider than state "${state.id}" (${state.width}px) — shorten the label, move detail to sublabel, or increase state.width.`);
}
}
- const byLane = new Map();
- for (const state of states.values()) {
- byLane.set(state.lane, [...(byLane.get(state.lane) || []), state]);
- }
- for (const [lane, laneStates] of byLane) {
- for (let i = 0; i < laneStates.length; i += 1) {
- for (let j = i + 1; j < laneStates.length; j += 1) {
- if (rectsOverlap(laneStates[i], laneStates[j], 10)) {
- problems.push(`States "${laneStates[i].id}" and "${laneStates[j].id}" are too close in lane "${lane}".`);
- }
+ // All non-main/non-terminal lanes share the same y band, so the overlap
+ // check must run across lanes — not per-lane.
+ const allStates = [...states.values()];
+ for (let i = 0; i < allStates.length; i += 1) {
+ for (let j = i + 1; j < allStates.length; j += 1) {
+ if (rectsOverlap(allStates[i], allStates[j], 10)) {
+ problems.push(`States "${allStates[i].id}" and "${allStates[j].id}" are less than 10px apart — move one to another col or separate them with yOffset (lanes other than "main"/"terminal" share one band).`);
}
}
}
- for (const transition of lifecycle.transitions || []) {
+ for (const transition of asArray(lifecycle.transitions)) {
if (!states.has(transition.from)) problems.push(`Transition "${transition.label || transition.from}" references unknown source "${transition.from}".`);
if (!states.has(transition.to)) problems.push(`Transition "${transition.label || transition.to}" references unknown target "${transition.to}".`);
if (states.has(transition.from) && states.has(transition.to)) {
const routed = pathFor(transition);
const [start, end] = [routed.points[0], routed.points[routed.points.length - 1]];
const distance = Math.hypot(end[0] - start[0], end[1] - start[1]);
- if (distance < 32) problems.push(`Transition "${transition.label || `${transition.from}->${transition.to}`}" is too short.`);
+ if (distance < 32) problems.push(`Transition "${transition.label || `${transition.from}->${transition.to}`}" is too short (${Math.round(distance)}px; minimum 32px) — route it through a channel or drop its label.`);
}
}
- if (legendY() + 18 > viewBox[1]) problems.push(`Legend exceeds viewBox height ${viewBox[1]}.`);
+ const labelRects = [];
+ for (const transition of asArray(lifecycle.transitions)) {
+ if (!transition.label || !states.has(transition.from) || !states.has(transition.to)) continue;
+ const [lx, ly] = labelPoint(transition, pathFor(transition).points);
+ const longestLine = Math.max(textUnits(transition.label), textUnits(transition.note || ''));
+ const width = Math.max(32, longestLine * 4.9 + 12);
+ const height = transition.note ? 27 : 16;
+ labelRects.push({ label: transition.label, x: lx - width / 2, y: ly - 11, width, height });
+ }
+ for (const rect of labelRects) {
+ for (const state of states.values()) {
+ if (rectsOverlap(rect, state, -2)) {
+ problems.push(`Label "${rect.label}" overlaps state "${state.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.`);
+ }
+ }
+ }
+ for (let i = 0; i < labelRects.length; i += 1) {
+ for (let j = i + 1; j < labelRects.length; j += 1) {
+ if (rectsOverlap(labelRects[i], labelRects[j], -2)) {
+ problems.push(`Labels "${labelRects[i].label}" and "${labelRects[j].label}" overlap — adjust labelDx/labelDy.`);
+ }
+ }
+ }
if (problems.length) {
throw new Error(`Lifecycle layout validation failed:\n- ${problems.join('\n- ')}`);
}
}
-function anchor(state, side) {
- switch (side || 'auto') {
- case 'left': return [state.x, state.cy];
- case 'right': return [state.x + state.width, state.cy];
- case 'top': return [state.cx, state.y];
- case 'bottom': return [state.cx, state.y + state.height];
- default:
- return [state.x + state.width, state.cy];
- }
-}
-
-function defaultFromSide(from, to) {
- if (to.cx < from.cx) return 'left';
- if (to.cx > from.cx) return 'right';
- if (to.cy > from.cy) return 'bottom';
- return 'top';
-}
-
-function defaultToSide(from, to) {
- if (to.cx < from.cx) return 'right';
- if (to.cx > from.cx) return 'left';
- if (to.cy > from.cy) return 'top';
- return 'bottom';
-}
-
function routeVia(transition, from, to, start, end) {
if (transition.via) return transition.via;
switch (transition.route || 'auto') {
case 'straight':
return [];
case 'drop': {
- const y = transition.channelY || (start[1] + end[1]) / 2;
- return [[start[0], y], [end[0], y]];
- }
- case 'raise': {
- const y = transition.channelY || (start[1] + end[1]) / 2;
+ const y = transition.channelY ?? (start[1] + end[1]) / 2;
return [[start[0], y], [end[0], y]];
}
case 'bottom-channel': {
- const y = transition.channelY || Math.max(from.y + from.height, to.y + to.height) + 34;
+ const y = transition.channelY ?? Math.max(from.y + from.height, to.y + to.height) + 34;
return [[start[0], y], [end[0], y]];
}
case 'top-channel': {
- const y = transition.channelY || Math.min(from.y, to.y) - 28;
+ const y = transition.channelY ?? Math.min(from.y, to.y) - 28;
return [[start[0], y], [end[0], y]];
}
case 'right-channel': {
- const x = transition.channelX || Math.max(from.x + from.width, to.x + to.width) + 36;
+ const x = transition.channelX ?? Math.max(from.x + from.width, to.x + to.width) + 36;
return [[x, start[1]], [x, end[1]]];
}
case 'left-channel': {
- const x = transition.channelX || Math.min(from.x, to.x) - 36;
+ const x = transition.channelX ?? Math.min(from.x, to.x) - 36;
return [[x, start[1]], [x, end[1]]];
}
case 'auto':
default: {
if (from.lane === to.lane) return [];
- const y = transition.channelY || (start[1] + end[1]) / 2;
+ const y = transition.channelY ?? (start[1] + end[1]) / 2;
return [[start[0], y], [end[0], y]];
}
}
}
+const pathCache = new Map();
+
function pathFor(transition) {
+ if (pathCache.has(transition)) return pathCache.get(transition);
const from = states.get(transition.from);
const to = states.get(transition.to);
- const start = anchor(from, transition.fromSide || defaultFromSide(from, to));
- const end = anchor(to, transition.toSide || defaultToSide(from, to));
+ const start = anchor(from, chosenSide(transition.fromSide, defaultFromSide(from, to)));
+ const end = anchor(to, chosenSide(transition.toSide, defaultToSide(from, to)));
const points = [start, ...routeVia(transition, from, to, start, end), end];
- return {
+ const routed = {
d: roundedPath(points, transition.cornerRadius ?? 10),
points
};
+ pathCache.set(transition, routed);
+ return routed;
}
-function roundedPath(points, radius) {
- if (points.length < 3 || radius <= 0) {
- return points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' ');
- }
-
- const commands = [`M ${points[0][0]} ${points[0][1]}`];
- for (let i = 1; i < points.length - 1; i += 1) {
- const [px, py] = points[i - 1];
- const [cx, cy] = points[i];
- const [nx, ny] = points[i + 1];
- const prevLen = Math.hypot(cx - px, cy - py);
- const nextLen = Math.hypot(nx - cx, ny - cy);
- const r = Math.min(radius, prevLen / 2, nextLen / 2);
- if (r < 1) {
- commands.push(`L ${cx} ${cy}`);
- continue;
- }
- const before = [cx - ((cx - px) / prevLen) * r, cy - ((cy - py) / prevLen) * r];
- const after = [cx + ((nx - cx) / nextLen) * r, cy + ((ny - cy) / nextLen) * r];
- commands.push(`L ${before[0]} ${before[1]}`);
- commands.push(`Q ${cx} ${cy} ${after[0]} ${after[1]}`);
- }
- const [endX, endY] = points[points.length - 1];
- commands.push(`L ${endX} ${endY}`);
- return commands.join(' ');
-}
-
-function labelPoint(transition, points) {
- if (transition.labelAt) return transition.labelAt;
- if (points.length === 2) {
- return [
- (points[0][0] + points[1][0]) / 2 + (transition.labelDx || 0),
- points[0][1] - 10 + (transition.labelDy || 0)
- ];
- }
- const segmentIndex = Math.min(points.length - 2, Math.max(0, transition.labelSegment ?? 1));
- const a = points[segmentIndex];
- const b = points[segmentIndex + 1];
- return [(a[0] + b[0]) / 2 + (transition.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (transition.labelDy || 0)];
+function bandTitles() {
+ const lanes = asArray(lifecycle.lanes);
+ const mainLane = lanes.find((lane) => lane.id === 'main');
+ const terminalLane = lanes.find((lane) => lane.id === 'terminal');
+ const eventLanes = lanes.filter((lane) => lane.id !== 'main' && lane.id !== 'terminal');
+ return [
+ mainLane?.label || 'Lifecycle phases',
+ eventLanes.length ? eventLanes.map((lane) => lane.label).join(' + ') : 'Interruptions + recovery',
+ terminalLane?.label || 'Outcomes'
+ ];
}
function renderBands() {
- return ` <path d="M 72 112 L 908 112" class="a-default" stroke-width="0.8" stroke-dasharray="3,8"/>
- <text x="72" y="100" class="t-dim" font-size="10" font-weight="600">01 / Lifecycle phases</text>
- <path d="M 72 264 L 908 264" class="a-default" stroke-width="0.8" stroke-dasharray="3,8"/>
- <text x="72" y="252" class="t-dim" font-size="10" font-weight="600">02 / Interruptions + recovery</text>
- <path d="M 72 436 L 908 436" class="a-default" stroke-width="0.8" stroke-dasharray="3,8"/>
- <text x="72" y="424" class="t-dim" font-size="10" font-weight="600">03 / Outcomes</text>`;
+ const right = viewBox[0] - 72;
+ const titles = bandTitles();
+ return ` <path d="M 72 112 L ${right} 112" class="a-default" stroke-width="0.8" stroke-dasharray="3,8"/>
+ <text x="72" y="100" class="t-dim" font-size="10" font-weight="600">01 / ${esc(titles[0])}</text>
+ <path d="M 72 264 L ${right} 264" class="a-default" stroke-width="0.8" stroke-dasharray="3,8"/>
+ <text x="72" y="252" class="t-dim" font-size="10" font-weight="600">02 / ${esc(titles[1])}</text>
+ <path d="M 72 436 L ${right} 436" class="a-default" stroke-width="0.8" stroke-dasharray="3,8"/>
+ <text x="72" y="424" class="t-dim" font-size="10" font-weight="600">03 / ${esc(titles[2])}</text>`;
}
function renderState(state) {
@@ -303,18 +293,8 @@ function renderState(state) {
<text x="${state.cx}" y="${state.y + 37}" class="t-muted" font-size="7" text-anchor="middle">${esc(state.sublabel || '')}</text>${tag}`;
}
-function transitionAccent(transition) {
- return transition.variant === 'security'
- ? 't-security'
- : transition.variant === 'emphasis'
- ? 't-backend'
- : transition.variant === 'dashed'
- ? 't-messagebus'
- : 't-muted';
-}
-
function renderTransitionPath(transition) {
- const [cls, marker] = arrowClass[transition.variant || 'default'] || arrowClass.default;
+ const [cls, marker] = arrowClassMap[transition.variant || 'default'] || arrowClassMap.default;
const routed = pathFor(transition);
const strokeWidth = transition.width || (transition.variant === 'emphasis' ? 2 : 1.1);
return ` <path d="${routed.d}" class="${cls}" stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
@@ -324,14 +304,14 @@ function renderTransitionLabel(transition) {
if (!transition.label) return '';
const routed = pathFor(transition);
const [lx, ly] = labelPoint(transition, routed.points);
- const longestLine = Math.max(transition.label.length, (transition.note || '').length);
+ const longestLine = Math.max(textUnits(transition.label), textUnits(transition.note || ''));
const labelW = Math.max(32, longestLine * 4.9 + 12);
const labelH = transition.note ? 27 : 16;
const note = transition.note
? `\n <text x="${lx}" y="${ly + 11}" class="t-dim" font-size="7" text-anchor="middle">${esc(transition.note)}</text>`
: '';
return ` <rect x="${lx - labelW / 2}" y="${ly - 11}" width="${labelW}" height="${labelH}" rx="4" class="c-mask"/>
- <text x="${lx}" y="${ly}" class="${transitionAccent(transition)}" font-size="8" text-anchor="middle">${esc(transition.label)}</text>${note}`;
+ <text x="${lx}" y="${ly}" class="${variantAccent(transition.variant)}" font-size="8" text-anchor="middle">${esc(transition.label)}</text>${note}`;
}
function renderLegend() {
@@ -348,11 +328,16 @@ function renderLegend() {
}
function renderLifecycleRail() {
- return ` <path d="M 154 ${layout.phaseY + 31} L 748 ${layout.phaseY + 31}" class="a-emphasis" stroke-width="2.2" marker-end="url(#arrowhead-emphasis)"/>`;
+ const mainCols = [...states.values()]
+ .filter((state) => bandFor(state.lane) === 'phase')
+ .map((state) => state.col);
+ if (!mainCols.length) return '';
+ const railEnd = layout.phaseXs[Math.max(...mainCols)] + 38;
+ return ` <path d="M 154 ${layout.phaseY + 31} L ${railEnd} ${layout.phaseY + 31}" class="a-emphasis" stroke-width="2.2" marker-end="url(#arrowhead-emphasis)"/>`;
}
function renderSvg() {
- return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(lifecycle.meta, 'lifecycle diagram')}>
${renderDefinitions()}
<!-- Background Grid -->
@@ -365,13 +350,13 @@ ${renderBands()}
${renderLifecycleRail()}
<!-- Transition paths -->
-${(lifecycle.transitions || []).map(renderTransitionPath).join('\n')}
+${asArray(lifecycle.transitions).map(renderTransitionPath).join('\n')}
<!-- States -->
${[...states.values()].map(renderState).join('\n\n')}
<!-- Transition labels -->
-${(lifecycle.transitions || []).map(renderTransitionLabel).join('\n')}
+${asArray(lifecycle.transitions).map(renderTransitionLabel).join('\n')}
<!-- Legend -->
${renderLegend()}
@@ -379,12 +364,11 @@ ${renderLegend()}
}
validateLifecycle();
-fs.mkdirSync(path.dirname(outPath), { recursive: true });
-fs.writeFileSync(outPath, applyTemplate(template, {
- title: lifecycle.meta.title,
- subtitle: lifecycle.meta.subtitle,
- footer: 'Lifecycle diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export',
+writeDiagram({
+ outPath,
+ template,
+ meta: lifecycle.meta,
+ footerLabel: 'Lifecycle diagram',
svg: renderSvg(),
- cards: renderCards(lifecycle.cards),
-}));
-console.log(outPath);
+ cards: lifecycle.cards,
+});
diff --git a/archify/renderers/sequence/README.md b/archify/renderers/sequence/README.md
index a0830beb..7a80d271 100644
--- a/archify/renderers/sequence/README.md
+++ b/archify/renderers/sequence/README.md
@@ -7,6 +7,11 @@ template.
node archify/renderers/sequence/render-sequence.mjs input.sequence.json output.html
```
+Run `npm install` once in the skill folder first — the renderer validates the
+input against `archify/schemas/sequence.schema.json` via ajv. Without it, the
+renderer prints a warning and skips schema validation; its own layout checks
+still run.
+
If `output.html` is omitted, the renderer uses `meta.output` from the JSON file
or falls back to `sequence.html` in the current working directory.
@@ -21,7 +26,7 @@ Sequence JSON files must set:
"meta": {
"title": "Cache Miss Request Sequence",
"subtitle": "Frontend request path with auth and cache fallback",
- "viewBox": [820, 760]
+ "viewBox": [920, 760]
},
"participants": [],
"segments": [],
@@ -31,12 +36,34 @@ Sequence JSON files must set:
}
```
+The timeline scales with the viewBox height: a taller `meta.viewBox` buys more
+message room, a shorter one shrinks the readable band instead of clipping. A
+complete worked example lives at
+`archify/examples/cache-miss-request.sequence.json`.
+
The schema lives at:
```text
archify/schemas/sequence.schema.json
```
+## Layout budget
+
+| Constant | Value |
+|----------|-------|
+| viewBox | default `[920, 760]`; schema minimum `[480, 480]` |
+| Participant boxes | 86×54 at y 72; centers at x = 62 + index×108 |
+| Participant count | last center + 43 must be ≤ width − 40 (8 fit at width 920) |
+| Lifelines | from y 142 down to height − 65; band must be ≥120px tall |
+| Message `y` range | `[160, height − 83]` |
+| Message spacing | ≥28px vertical between messages that share horizontal space |
+| Arrow span | ≥60px horizontal between the two participants |
+| Segments | y pixel ranges with `to > from`, inside `[72, lifeline bottom + 20]` |
+| Legend row | y = height − 54 |
+
+`segments[].from/to` and `activations[].from/to` are y pixel coordinates, not
+participant ids; activations also require `to > from`.
+
## Design Rules
- Put participants across the top, ordered by the story the reader should
@@ -49,7 +76,11 @@ archify/schemas/sequence.schema.json
- Use segments as light background guides; keep segment labels short.
- Keep labels short enough to fit in narrow previews.
-The renderer fails when it can detect layout problems, including missing
-participants, duplicate participant IDs, unknown message endpoints, messages
-outside the readable timeline, overly tight vertical message spacing, invalid
-activation ranges, or participants that exceed the viewBox.
+Schema violations exit non-zero with path-prefixed messages annotated with the
+element's id or label. The renderer additionally fails when it can detect
+layout problems, including missing participants, duplicate participant IDs,
+participant labels wider than their box, unknown message endpoints, messages
+outside the readable timeline, overly tight vertical spacing between messages
+that overlap horizontally, invalid segment or activation ranges, or
+participants that exceed the viewBox. Text width is estimated CJK-aware:
+fullwidth glyphs count as two units.
diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjs
index eb9b4f37..28e38e2b 100644
--- a/archify/renderers/sequence/render-sequence.mjs
+++ b/archify/renderers/sequence/render-sequence.mjs
@@ -1,56 +1,33 @@
-import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { esc, renderDefinitions, renderCards, applyTemplate } from '../shared/utils.mjs';
-import { validateSchema } from '../shared/validator.mjs';
+import { esc, renderDefinitions, textUnits } from '../shared/utils.mjs';
+import { loadDiagram, writeDiagram, svgRootAttrs } from '../shared/cli.mjs';
+import { componentFill, arrowClassMap, rectsOverlap, asArray, isFinitePoint } from '../shared/geometry.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const skillRoot = path.resolve(__dirname, '../..');
-const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/cache-miss-request.sequence.json'));
-const sequence = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
-validateSchema('sequence', sequence);
+const { diagram: sequence, template, outPath } = loadDiagram({
+ rendererDir: __dirname,
+ diagramType: 'sequence',
+ defaultExample: 'cache-miss-request.sequence.json'
+});
-const templatePath = path.join(skillRoot, 'assets/template.html');
-const template = fs.readFileSync(templatePath, 'utf8');
-const outPath = path.resolve(process.cwd(), process.argv[3] || sequence.meta.output || 'sequence.html');
-
-const viewBox = sequence.meta.viewBox || [920, 760];
+const viewBox = sequence.meta?.viewBox || [920, 760];
+// The timeline scales with viewBox height: a taller viewBox gains message room,
+// a shorter one shrinks the readable band (validated below) instead of clipping.
const layout = {
topY: 72,
participantW: 86,
participantH: 54,
lifelineTop: 142,
- lifelineBottom: 695,
+ lifelineBottom: viewBox[1] - 65,
+ legendY: viewBox[1] - 54,
leftX: 62,
colGap: 108,
labelH: 16
};
-const typeClass = {
- frontend: 'c-frontend',
- backend: 'c-backend',
- database: 'c-database',
- cloud: 'c-cloud',
- security: 'c-security',
- messagebus: 'c-messagebus',
- external: 'c-external'
-};
-
-const textClass = {
- frontend: 't-frontend',
- backend: 't-backend',
- database: 't-database',
- cloud: 't-cloud',
- security: 't-security',
- messagebus: 't-messagebus',
- external: 't-external'
-};
-
const arrowClass = {
- default: ['a-default', 'arrowhead'],
- emphasis: ['a-emphasis', 'arrowhead-emphasis'],
- security: ['a-security', 'arrowhead-security'],
- dashed: ['a-dashed', 'arrowhead-dashed'],
+ ...arrowClassMap,
return: ['a-default', 'arrowhead']
};
@@ -58,7 +35,7 @@ function participantX(index) {
return layout.leftX + index * layout.colGap;
}
-const participants = new Map(sequence.participants.map((participant, index) => [
+const participants = new Map(asArray(sequence.participants).map((participant, index) => [
participant.id,
{
...participant,
@@ -76,36 +53,94 @@ function validateSequence() {
if (!Array.isArray(sequence.participants) || sequence.participants.length < 2) {
problems.push('Sequence diagrams need at least two participants.');
}
- if (participants.size !== sequence.participants.length) problems.push('Participant ids must be unique.');
+ if (participants.size !== asArray(sequence.participants).length) problems.push('Participant ids must be unique.');
+ if (!Array.isArray(sequence.messages) || sequence.messages.length < 1) {
+ problems.push('Sequence diagrams need at least one message.');
+ }
+ if (sequence.cards !== undefined && !Array.isArray(sequence.cards)) problems.push('Sequence "cards" must be an array.');
+ for (const arr of ['segments', 'activations']) {
+ if (sequence[arr] !== undefined && !Array.isArray(sequence[arr])) problems.push(`Sequence "${arr}" must be an array.`);
+ }
- for (const message of sequence.messages || []) {
+ if (layout.lifelineBottom - layout.lifelineTop < 120) {
+ problems.push(`viewBox height ${viewBox[1]} leaves under 120px of timeline — set meta.viewBox[1] to at least ${layout.lifelineTop + 120 + 65}.`);
+ }
+
+ for (const participant of participants.values()) {
+ const estLabelW = textUnits(participant.label) * 6.8;
+ if (estLabelW > layout.participantW + 6) {
+ problems.push(`Label "${participant.label}" (~${Math.round(estLabelW)}px) is wider than the ${layout.participantW}px participant box — shorten it or move detail to sublabel.`);
+ }
+ }
+
+ for (const message of asArray(sequence.messages)) {
if (!participants.has(message.from)) problems.push(`Message "${message.label}" references unknown source "${message.from}".`);
if (!participants.has(message.to)) problems.push(`Message "${message.label}" references unknown target "${message.to}".`);
if (typeof message.y !== 'number') problems.push(`Message "${message.label}" must provide a numeric y.`);
if (message.y < layout.lifelineTop + 18 || message.y > layout.lifelineBottom - 18) {
- problems.push(`Message "${message.label}" sits outside the readable timeline.`);
+ problems.push(`Message "${message.label}" sits outside the readable timeline — keep y between ${layout.lifelineTop + 18} and ${layout.lifelineBottom - 18}.`);
}
if (participants.has(message.from) && participants.has(message.to)) {
const distance = Math.abs(participants.get(message.to).cx - participants.get(message.from).cx);
- if (distance < 60) problems.push(`Message "${message.label}" is too short to read cleanly.`);
+ if (distance < 60) problems.push(`Message "${message.label}" spans ${Math.round(distance)}px (minimum 60px) — give its participants more column distance.`);
+ }
+ }
+
+ // Vertical crowding only matters when the arrows share horizontal space;
+ // disjoint arrows may legitimately run in parallel rows.
+ const placed = asArray(sequence.messages)
+ .filter((m) => participants.has(m.from) && participants.has(m.to))
+ .map((m) => ({
+ label: m.label,
+ y: m.y,
+ x1: Math.min(participants.get(m.from).cx, participants.get(m.to).cx),
+ x2: Math.max(participants.get(m.from).cx, participants.get(m.to).cx)
+ }))
+ .sort((a, b) => a.y - b.y);
+ for (let i = 0; i < placed.length; i += 1) {
+ for (let j = i + 1; j < placed.length && placed[j].y - placed[i].y < 28; j += 1) {
+ if (placed[i].x1 < placed[j].x2 && placed[j].x1 < placed[i].x2) {
+ problems.push(`Messages "${placed[i].label}" and "${placed[j].label}" are less than 28px apart and share horizontal space — spread their y values.`);
+ }
}
}
- const sorted = [...(sequence.messages || [])].sort((a, b) => a.y - b.y);
- for (let i = 1; i < sorted.length; i += 1) {
- if (sorted[i].y - sorted[i - 1].y < 28) {
- problems.push(`Messages "${sorted[i - 1].label}" and "${sorted[i].label}" are too close vertically.`);
+ // Label masks can extend well past the arrow span, so check the actual
+ // label rectangles too — tangent arrows with long labels still collide.
+ const labelRects = asArray(sequence.messages)
+ .filter((m) => participants.has(m.from) && participants.has(m.to) && typeof m.y === 'number')
+ .map((m) => {
+ const x1 = participants.get(m.from).cx;
+ const x2 = participants.get(m.to).cx;
+ const width = Math.max(34, textUnits(m.label) * 5.2 + 12);
+ return { label: m.label, x: (x1 + x2) / 2 - width / 2, y: m.y - 20, width, height: layout.labelH };
+ });
+ for (let i = 0; i < labelRects.length; i += 1) {
+ for (let j = i + 1; j < labelRects.length; j += 1) {
+ if (rectsOverlap(labelRects[i], labelRects[j], -2)) {
+ problems.push(`Labels "${labelRects[i].label}" and "${labelRects[j].label}" overlap — spread their message y values or shorten the labels.`);
+ }
+ }
+ }
+
+ for (const segment of asArray(sequence.segments)) {
+ if (segment.to <= segment.from) {
+ problems.push(`Segment "${segment.label}" has invalid y range (from ${segment.from} to ${segment.to}) — "to" must be greater than "from".`);
+ }
+ if (segment.from < layout.topY || segment.to > layout.lifelineBottom + 20) {
+ problems.push(`Segment "${segment.label}" extends outside the canvas — keep its y range between ${layout.topY} and ${layout.lifelineBottom + 20}.`);
}
}
- for (const activation of sequence.activations || []) {
+ for (const activation of asArray(sequence.activations)) {
if (!participants.has(activation.participant)) problems.push(`Activation references unknown participant "${activation.participant}".`);
- if (activation.to <= activation.from) problems.push(`Activation for "${activation.participant}" has invalid time range.`);
+ if (activation.to <= activation.from) problems.push(`Activation for "${activation.participant}" has invalid time range — "to" must be greater than "from".`);
}
- const lastParticipant = sequence.participants[sequence.participants.length - 1];
+ const lastParticipant = asArray(sequence.participants)[asArray(sequence.participants).length - 1];
if (lastParticipant && participants.get(lastParticipant.id).cx + layout.participantW / 2 > viewBox[0] - 40) {
- problems.push('Participants exceed viewBox width.');
+ const requiredWidth = Math.ceil(participants.get(lastParticipant.id).cx + layout.participantW / 2 + 40);
+ problems.push(`Participants exceed viewBox width — set meta.viewBox[0] to at least ${requiredWidth} or remove a participant.`);
}
if (problems.length) {
@@ -114,7 +149,7 @@ function validateSequence() {
}
function renderParticipant(participant) {
- const fill = typeClass[participant.type] || 'c-external';
+ const fill = componentFill[participant.type] || 'c-external';
return ` <rect x="${participant.x}" y="${layout.topY}" width="${layout.participantW}" height="${layout.participantH}" rx="6" class="c-mask"/>
<rect x="${participant.x}" y="${layout.topY}" width="${layout.participantW}" height="${layout.participantH}" rx="6" class="${fill}" stroke-width="1.5"/>
<text x="${participant.cx}" y="${layout.topY + 22}" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">${esc(participant.label)}</text>
@@ -132,7 +167,7 @@ function renderSegment(segment) {
function renderActivation(activation) {
const participant = participants.get(activation.participant);
- const fill = typeClass[activation.type] || typeClass[participant.type] || 'c-external';
+ const fill = componentFill[activation.type] || componentFill[participant.type] || 'c-external';
const x = participant.cx - 5;
const height = activation.to - activation.from;
return ` <rect x="${x}" y="${activation.from}" width="10" height="${height}" rx="3" class="c-mask"/>
@@ -142,7 +177,7 @@ function renderActivation(activation) {
function messageLabel(message, x1, x2) {
const center = (x1 + x2) / 2;
const y = message.y - 10;
- const labelW = Math.max(34, message.label.length * 5.2 + 12);
+ const labelW = Math.max(34, textUnits(message.label) * 5.2 + 12);
const accent = message.variant === 'security'
? 't-security'
: message.variant === 'dashed'
@@ -171,7 +206,7 @@ ${messageLabel(message, start, end)}${note}`;
}
function renderLegend() {
- const y = 706;
+ const y = layout.legendY;
return ` <text x="150" y="${y - 20}" class="t-primary" font-size="10" font-weight="600">Legend</text>
<path d="M 150 ${y} L 184 ${y}" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
<text x="193" y="${y + 3}" class="t-muted" font-size="8">request</text>
@@ -185,23 +220,23 @@ function renderLegend() {
function renderSvg() {
const participantList = [...participants.values()];
- return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(sequence.meta, 'sequence diagram')}>
${renderDefinitions()}
<!-- Background Grid -->
<rect width="100%" height="100%" fill="url(#grid)" />
<!-- Time Segments -->
-${(sequence.segments || []).map(renderSegment).join('\n\n')}
+${asArray(sequence.segments).map(renderSegment).join('\n\n')}
<!-- Lifelines -->
${participantList.map(renderLifeline).join('\n')}
<!-- Messages -->
-${(sequence.messages || []).map(renderMessage).join('\n\n')}
+${asArray(sequence.messages).map(renderMessage).join('\n\n')}
<!-- Activations -->
-${(sequence.activations || []).map(renderActivation).join('\n')}
+${asArray(sequence.activations).map(renderActivation).join('\n')}
<!-- Participants -->
${participantList.map(renderParticipant).join('\n\n')}
@@ -212,12 +247,11 @@ ${renderLegend()}
}
validateSequence();
-fs.mkdirSync(path.dirname(outPath), { recursive: true });
-fs.writeFileSync(outPath, applyTemplate(template, {
- title: sequence.meta.title,
- subtitle: sequence.meta.subtitle,
- footer: 'Sequence diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export',
+writeDiagram({
+ outPath,
+ template,
+ meta: sequence.meta,
+ footerLabel: 'Sequence diagram',
svg: renderSvg(),
- cards: renderCards(sequence.cards),
-}));
-console.log(outPath);
+ cards: sequence.cards,
+});
diff --git a/archify/renderers/shared/cli.mjs b/archify/renderers/shared/cli.mjs
new file mode 100644
index 00000000..41e89b9a
--- /dev/null
+++ b/archify/renderers/shared/cli.mjs
@@ -0,0 +1,37 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { applyTemplate, renderCards, esc } from './utils.mjs';
+import { validateSchema } from './validator.mjs';
+
+// Common CLI head: node render-<type>.mjs [input.json] [output.html]
+export function loadDiagram({ rendererDir, diagramType, defaultExample }) {
+ const skillRoot = path.resolve(rendererDir, '../..');
+ const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples', defaultExample));
+ const diagram = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
+ validateSchema(diagramType, diagram);
+ const template = fs.readFileSync(path.join(skillRoot, 'assets/template.html'), 'utf8');
+ // Optional chaining: in degraded mode (no ajv) malformed input must still
+ // reach the renderer's friendly layout checks instead of crashing here.
+ const outPath = path.resolve(process.cwd(), process.argv[3] || diagram.meta?.output || `${diagramType}.html`);
+ return { diagram, template, outPath };
+}
+
+// Common CLI tail: fill the template and write the standalone HTML file.
+// The keyboard hint is screen-only — it means nothing on paper.
+export function writeDiagram({ outPath, template, meta, footerLabel, svg, cards }) {
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
+ fs.writeFileSync(outPath, applyTemplate(template, {
+ title: meta.title,
+ subtitle: meta.subtitle,
+ footer: `${footerLabel} &bull; Built with Archify<span class="no-print"> &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export</span>`,
+ svg,
+ cards: renderCards(cards),
+ }));
+ console.log(outPath);
+}
+
+// Accessible name for the generated diagram SVG.
+export function svgRootAttrs(meta, kind) {
+ const name = meta.subtitle ? `${meta.title} — ${meta.subtitle}` : meta.title;
+ return `role="img" aria-label="${esc(`${name} (${kind})`)}"`;
+}
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
new file mode 100644
index 00000000..7a89b6b0
--- /dev/null
+++ b/archify/renderers/shared/geometry.mjs
@@ -0,0 +1,140 @@
+// Geometry helpers shared by all typed renderers. Every function here is
+// pure; renderers own their layout tables and pass measured rects
+// ({x, y, width, height, cx, cy}) in.
+
+// In degraded mode (no ajv) a type-wrong top-level field reaches the renderer.
+// Coerce non-arrays to [] so the module-level Maps build without throwing and
+// the friendly validator checks (which run later) report the real problem.
+export function asArray(value) {
+ return Array.isArray(value) ? value : [];
+}
+
+// A computed coordinate must be a finite number; NaN/undefined would silently
+// write `<rect x="NaN">` into the output. Used by the validators as a backstop.
+export function isFinitePoint(...coords) {
+ return coords.every((c) => Number.isFinite(c));
+}
+
+export function rectsOverlap(a, b, gap = 0) {
+ return !(
+ a.x + a.width + gap <= b.x ||
+ b.x + b.width + gap <= a.x ||
+ a.y + a.height + gap <= b.y ||
+ b.y + b.height + gap <= a.y
+ );
+}
+
+export function anchor(rect, side) {
+ switch (side) {
+ case 'left': return [rect.x, rect.cy];
+ case 'right': return [rect.x + rect.width, rect.cy];
+ case 'top': return [rect.cx, rect.y];
+ case 'bottom': return [rect.cx, rect.y + rect.height];
+ default:
+ return [rect.x + rect.width, rect.cy];
+ }
+}
+
+export function defaultFromSide(from, to) {
+ if (to.cx < from.cx) return 'left';
+ if (to.cx > from.cx) return 'right';
+ if (to.cy > from.cy) return 'bottom';
+ return 'top';
+}
+
+export function defaultToSide(from, to) {
+ if (to.cx < from.cx) return 'right';
+ if (to.cx > from.cx) return 'left';
+ if (to.cy > from.cy) return 'top';
+ return 'bottom';
+}
+
+export function chosenSide(side, fallback) {
+ return side && side !== 'auto' ? side : fallback;
+}
+
+export function polylinePath(points) {
+ return points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' ');
+}
+
+export function roundedPath(points, radius) {
+ if (points.length < 3 || radius <= 0) {
+ return polylinePath(points);
+ }
+
+ const commands = [`M ${points[0][0]} ${points[0][1]}`];
+ for (let i = 1; i < points.length - 1; i += 1) {
+ const [px, py] = points[i - 1];
+ const [cx, cy] = points[i];
+ const [nx, ny] = points[i + 1];
+ const prevLen = Math.hypot(cx - px, cy - py);
+ const nextLen = Math.hypot(nx - cx, ny - cy);
+ const r = Math.min(radius, prevLen / 2, nextLen / 2);
+ if (r < 1) {
+ commands.push(`L ${cx} ${cy}`);
+ continue;
+ }
+ const before = [cx - ((cx - px) / prevLen) * r, cy - ((cy - py) / prevLen) * r];
+ const after = [cx + ((nx - cx) / nextLen) * r, cy + ((ny - cy) / nextLen) * r];
+ commands.push(`L ${before[0]} ${before[1]}`);
+ commands.push(`Q ${cx} ${cy} ${after[0]} ${after[1]}`);
+ }
+ const [endX, endY] = points[points.length - 1];
+ commands.push(`L ${endX} ${endY}`);
+ return commands.join(' ');
+}
+
+// Shared by edges/flows/transitions: all carry the same optional
+// labelAt/labelDx/labelDy/labelSegment knobs.
+export function labelPoint(item, points) {
+ if (item.labelAt) return item.labelAt;
+ if (points.length === 2) {
+ return [
+ (points[0][0] + points[1][0]) / 2 + (item.labelDx || 0),
+ points[0][1] - 10 + (item.labelDy || 0)
+ ];
+ }
+ const segmentIndex = Math.min(points.length - 2, Math.max(0, item.labelSegment ?? 1));
+ const a = points[segmentIndex];
+ const b = points[segmentIndex + 1];
+ return [(a[0] + b[0]) / 2 + (item.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (item.labelDy || 0)];
+}
+
+export const componentFill = {
+ frontend: 'c-frontend',
+ backend: 'c-backend',
+ database: 'c-database',
+ cloud: 'c-cloud',
+ security: 'c-security',
+ messagebus: 'c-messagebus',
+ external: 'c-external'
+};
+
+export const componentText = {
+ frontend: 't-frontend',
+ backend: 't-backend',
+ database: 't-database',
+ cloud: 't-cloud',
+ security: 't-security',
+ messagebus: 't-messagebus',
+ external: 't-external'
+};
+
+export const arrowClassMap = {
+ default: ['a-default', 'arrowhead'],
+ emphasis: ['a-emphasis', 'arrowhead-emphasis'],
+ security: ['a-security', 'arrowhead-security'],
+ dashed: ['a-dashed', 'arrowhead-dashed']
+};
+
+// Label accent per edge variant. Workflow colors dashed (async trace) labels
+// like the trace store it points at; the other renderers use the bus color.
+export function variantAccent(variant, { dashed = 't-messagebus' } = {}) {
+ return variant === 'security'
+ ? 't-security'
+ : variant === 'emphasis'
+ ? 't-backend'
+ : variant === 'dashed'
+ ? dashed
+ : 't-muted';
+}
diff --git a/archify/renderers/shared/utils.mjs b/archify/renderers/shared/utils.mjs
index 4ff6bfcb..5392d20a 100644
--- a/archify/renderers/shared/utils.mjs
+++ b/archify/renderers/shared/utils.mjs
@@ -26,7 +26,7 @@ export function renderDefinitions() {
}
export function renderCards(cards) {
- const list = cards || [];
+ const list = Array.isArray(cards) ? cards : [];
return ` <!-- Info Cards -->
<div class="cards">
${list.map((card) => ` <div class="card">
@@ -65,11 +65,24 @@ export function applyTemplate(template, { title, subtitle, footer, svg, cards })
throw new Error(`applyTemplate: template missing placeholder ${JSON.stringify(ph)}`);
}
}
+ // Function replacers: a literal `$&`, `$'`, `$\`` or `$$` in titles, labels,
+ // or rendered SVG must not be interpreted as a replacement pattern.
return template
- .replace(TEMPLATE_PLACEHOLDERS[0], `<title>${esc(title)} Diagram</title>`)
- .replace(TEMPLATE_PLACEHOLDERS[1], `<h1>${esc(title)}</h1>`)
- .replace(TEMPLATE_PLACEHOLDERS[2], `<p class="subtitle">${esc(subtitle ?? '')}</p>`)
- .replace(SVG_SLOT_RE, svg)
- .replace(CARDS_SLOT_RE, cards)
- .replace(TEMPLATE_PLACEHOLDERS[3], footer);
+ .replace(TEMPLATE_PLACEHOLDERS[0], () => `<title>${esc(title)} Diagram</title>`)
+ .replace(TEMPLATE_PLACEHOLDERS[1], () => `<h1>${esc(title)}</h1>`)
+ .replace(TEMPLATE_PLACEHOLDERS[2], () => `<p class="subtitle">${esc(subtitle ?? '')}</p>`)
+ .replace(SVG_SLOT_RE, () => svg)
+ .replace(CARDS_SLOT_RE, () => cards)
+ .replace(TEMPLATE_PLACEHOLDERS[3], () => footer);
+}
+
+// CJK and other fullwidth glyphs render at roughly twice the advance width of
+// ASCII in the monospace stacks the template uses. Includes the supplementary
+// CJK extensions and emoji, which also render double-width.
+const FULLWIDTH_RE = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩ -〿\u{1F000}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u;
+
+export function textUnits(text) {
+ let units = 0;
+ for (const ch of String(text ?? '')) units += FULLWIDTH_RE.test(ch) ? 2 : 1;
+ return units;
}
diff --git a/archify/renderers/shared/validator.mjs b/archify/renderers/shared/validator.mjs
index a0023bbf..c00c1e32 100644
--- a/archify/renderers/shared/validator.mjs
+++ b/archify/renderers/shared/validator.mjs
@@ -1,22 +1,55 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import Ajv2020 from 'ajv/dist/2020.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const schemasDir = path.resolve(__dirname, '../../schemas');
-const ajv = new Ajv2020({ allErrors: true, strict: false });
+let validators = null;
-const validators = {};
-for (const type of ['workflow', 'sequence', 'dataflow', 'lifecycle']) {
- const schema = JSON.parse(fs.readFileSync(path.join(schemasDir, `${type}.schema.json`), 'utf8'));
- validators[type] = ajv.compile(schema);
+try {
+ const { default: Ajv2020 } = await import('ajv/dist/2020.js');
+ const ajv = new Ajv2020({ allErrors: true, strict: true });
+ const commonPath = path.join(schemasDir, 'common.schema.json');
+ if (fs.existsSync(commonPath)) {
+ ajv.addSchema(JSON.parse(fs.readFileSync(commonPath, 'utf8')));
+ }
+ validators = {};
+ for (const type of ['workflow', 'sequence', 'dataflow', 'lifecycle', 'architecture']) {
+ const schema = JSON.parse(fs.readFileSync(path.join(schemasDir, `${type}.schema.json`), 'utf8'));
+ validators[type] = ajv.compile(schema);
+ }
+} catch (err) {
+ if (err && err.code === 'ERR_MODULE_NOT_FOUND') {
+ console.warn(
+ 'archify: ajv is not installed — skipping JSON-schema validation. '
+ + 'Run "npm install" in the skill folder to enable it; renderer layout checks still run.'
+ );
+ } else {
+ throw err;
+ }
+}
+
+// "/nodes/3/label" reads much better as "/nodes/3 (id: "router") /label" for the
+// LLM fixing the JSON; resolve the nearest enclosing element's id or label.
+function annotatePath(instancePath, data) {
+ if (!instancePath) return '/';
+ let node = data;
+ let hint = null;
+ for (const seg of instancePath.split('/').slice(1)) {
+ if (node == null || typeof node !== 'object') break;
+ node = node[/^\d+$/.test(seg) ? Number(seg) : seg];
+ if (node && typeof node === 'object' && !Array.isArray(node)) {
+ const tag = node.id ?? node.label;
+ if (tag != null) hint = String(tag);
+ }
+ }
+ return hint != null ? `${instancePath} (id/label: ${JSON.stringify(hint)})` : instancePath;
}
-function formatErrors(errors) {
+function formatErrors(errors, data) {
return errors.map((e) => {
- const where = e.instancePath || '/';
+ const where = annotatePath(e.instancePath, data);
const detail = e.params && Object.keys(e.params).length
? ' ' + JSON.stringify(e.params)
: '';
@@ -25,13 +58,14 @@ function formatErrors(errors) {
}
export function validateSchema(diagramType, data) {
+ if (!validators) return; // ajv unavailable — renderer layout checks still apply
const validate = validators[diagramType];
if (!validate) {
throw new Error(`validateSchema: unknown diagram type "${diagramType}"`);
}
if (!validate(data)) {
throw new Error(
- `${diagramType} schema validation failed:\n${formatErrors(validate.errors)}`
+ `${diagramType} schema validation failed:\n${formatErrors(validate.errors, data)}`
);
}
}
diff --git a/archify/renderers/workflow/README.md b/archify/renderers/workflow/README.md
index b6487559..e6d1df51 100644
--- a/archify/renderers/workflow/README.md
+++ b/archify/renderers/workflow/README.md
@@ -7,6 +7,11 @@ template.
node archify/renderers/workflow/render-workflow.mjs input.workflow.json output.html
```
+Run `npm install` once in the skill folder first — the renderer validates the
+input against `archify/schemas/workflow.schema.json` via ajv. Without it, the
+renderer prints a warning and skips schema validation; its own layout checks
+still run.
+
If `output.html` is omitted, the renderer uses `meta.output` from the JSON file
or falls back to `workflow.html` in the current working directory.
@@ -20,8 +25,7 @@ Workflow JSON files must set:
"diagram_type": "workflow",
"meta": {
"title": "Agent Tool Call Workflow",
- "subtitle": "Renderer-driven workflow prototype",
- "viewBox": [720, 780]
+ "subtitle": "Renderer-driven workflow prototype"
},
"lanes": [],
"nodes": [],
@@ -30,23 +34,50 @@ Workflow JSON files must set:
}
```
+Omit `meta.viewBox` for the common case: the width is fixed at 720 and the
+height is derived from the lane count, so lanes and legend always fit. A
+complete worked example lives at
+`archify/examples/agent-tool-call.workflow.json`.
+
The schema lives at:
```text
archify/schemas/workflow.schema.json
```
+## Layout budget
+
+| Constant | Value |
+|----------|-------|
+| viewBox | default `[720, auto]` — auto height = 52 + lanes×104 + (lanes−1)×20 + 124 |
+| Lane frame | x 40, width 640, height 104, gap 20; first lane top at y 52 |
+| Lane title strip | top 30px of each lane; node boxes must stay below it |
+| Column centers (`col` 0–5) | x = 88, 220, 300, 430, 500, 625 |
+| Default node | 92×52 (height 68 when `tag` is set) |
+| Node spacing | ≥8px between nodes in the same lane |
+| Edge length | straight segments must span ≥28px |
+| Legend row | y = lane bottom + 44; viewBox height must be ≥ legend y + 18 |
+
+Column-center gaps are 132 / 80 / 130 / 70 / 125 px: columns 1↔2 (80px) and
+3↔4 (70px) cannot both hold default-width 92px nodes in the same lane — skip a
+column or reduce `width`.
+
## Design Rules
- Use lanes for ownership or runtime boundaries.
- Place nodes with lane IDs and column indexes, not raw SVG coordinates.
- Leave short adjacent links unlabeled; the arrow is enough.
- Use labels for cross-lane decisions, approvals, async traces, and return paths.
-- Prefer route presets such as `drop`, `drop-left`, `drop-right`,
- `outside-right`, and `bottom-channel` before using raw `via` points.
+- Prefer route presets — `drop` (bend between lanes; `bias` 0–1 picks where),
+ `outside-right`, `return-left`, `bottom-channel`, and `up-channel` — before
+ using raw `via` points. `straight` and the default `auto` cover the rest.
- Keep workflow examples compact enough to render well in narrow chat/browser
previews.
-The renderer fails when it can detect layout problems, including node overlap,
-nodes outside their lanes, unknown edge targets, legends outside the viewBox, or
-straight arrows that are too short to read cleanly.
+Schema violations exit non-zero with path-prefixed messages annotated with the
+element's id or label. The renderer additionally fails when it can detect
+layout problems, including node overlap, nodes outside their lanes, unknown
+edge targets, labels colliding with nodes or other labels, labels wider than
+their node, legends outside the viewBox, or straight arrows that are too short
+to read cleanly. Text width is estimated CJK-aware: fullwidth glyphs count as
+two units.
diff --git a/archify/renderers/workflow/render-workflow.mjs b/archify/renderers/workflow/render-workflow.mjs
index f85f6377..b37dfd44 100644
--- a/archify/renderers/workflow/render-workflow.mjs
+++ b/archify/renderers/workflow/render-workflow.mjs
@@ -1,22 +1,30 @@
-import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { esc, renderDefinitions, renderCards, applyTemplate } from '../shared/utils.mjs';
-import { validateSchema } from '../shared/validator.mjs';
+import { esc, renderDefinitions, textUnits } from '../shared/utils.mjs';
+import { loadDiagram, writeDiagram, svgRootAttrs } from '../shared/cli.mjs';
+import {
+ asArray,
+ isFinitePoint,
+ rectsOverlap,
+ anchor,
+ defaultFromSide,
+ defaultToSide,
+ chosenSide,
+ polylinePath,
+ labelPoint,
+ componentFill,
+ componentText,
+ arrowClassMap,
+ variantAccent
+} from '../shared/geometry.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const skillRoot = path.resolve(__dirname, '../..');
-const repoRoot = path.resolve(skillRoot, '..');
-const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/agent-tool-call.workflow.json'));
-const workflow = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
-validateSchema('workflow', workflow);
+const { diagram: workflow, template, outPath } = loadDiagram({
+ rendererDir: __dirname,
+ diagramType: 'workflow',
+ defaultExample: 'agent-tool-call.workflow.json'
+});
-const templatePath = path.join(skillRoot, 'assets/template.html');
-const template = fs.readFileSync(templatePath, 'utf8');
-
-const outPath = path.resolve(process.cwd(), process.argv[3] || workflow.meta.output || 'workflow.html');
-
-const viewBox = workflow.meta.viewBox || [1000, 720];
const layout = {
laneX: 40,
laneY: 52,
@@ -29,34 +37,14 @@ const layout = {
nodeH: 52
};
-const typeClass = {
- frontend: 'c-frontend',
- backend: 'c-backend',
- database: 'c-database',
- cloud: 'c-cloud',
- security: 'c-security',
- messagebus: 'c-messagebus',
- external: 'c-external'
-};
-
-const textClass = {
- frontend: 't-frontend',
- backend: 't-backend',
- database: 't-database',
- cloud: 't-cloud',
- security: 't-security',
- messagebus: 't-messagebus',
- external: 't-external'
-};
-
-const arrowClass = {
- default: ['a-default', 'arrowhead'],
- emphasis: ['a-emphasis', 'arrowhead-emphasis'],
- security: ['a-security', 'arrowhead-security'],
- dashed: ['a-dashed', 'arrowhead-dashed']
-};
+// Content is 680px wide (laneX + laneW); auto height fits the lanes plus legend.
+const autoHeight = layout.laneY
+ + (workflow.lanes?.length || 1) * layout.laneH
+ + ((workflow.lanes?.length || 1) - 1) * layout.laneGap
+ + 124;
+const viewBox = workflow.meta?.viewBox || [720, autoHeight];
-const laneIndex = new Map(workflow.lanes.map((lane, index) => [lane.id, index]));
+const laneIndex = new Map(asArray(workflow.lanes).map((lane, index) => [lane.id, index]));
function laneTop(id) {
return layout.laneY + laneIndex.get(id) * (layout.laneH + layout.laneGap);
@@ -87,23 +75,14 @@ function measureNode(node) {
};
}
-const nodes = new Map(workflow.nodes.map((node) => [node.id, measureNode(node)]));
-
-function rectsOverlap(a, b, gap = 0) {
- return !(
- a.x + a.width + gap <= b.x ||
- b.x + b.width + gap <= a.x ||
- a.y + a.height + gap <= b.y ||
- b.y + b.height + gap <= a.y
- );
-}
+const nodes = new Map(asArray(workflow.nodes).map((node) => [node.id, measureNode(node)]));
function validateWorkflow() {
const problems = [];
if (workflow.schema_version !== 1) {
problems.push('Workflow files must set "schema_version": 1.');
}
- if (workflow.diagram_type && workflow.diagram_type !== 'workflow') {
+ if (workflow.diagram_type !== 'workflow') {
problems.push(`Unsupported diagram_type "${workflow.diagram_type}". Expected "workflow".`);
}
if (!workflow.meta || !workflow.meta.title) {
@@ -118,6 +97,9 @@ function validateWorkflow() {
if (!Array.isArray(workflow.edges)) {
problems.push('Workflow files must include an edges array.');
}
+ if (workflow.cards !== undefined && !Array.isArray(workflow.cards)) {
+ problems.push('Workflow "cards" must be an array.');
+ }
if (problems.length) {
throw new Error(`Workflow layout validation failed:\n- ${problems.join('\n- ')}`);
}
@@ -135,8 +117,17 @@ function validateWorkflow() {
problems.push(`Node "${node.id}" uses unknown lane "${node.lane}".`);
continue;
}
- if (node.col < 0 || node.col >= layout.colXs.length) {
- problems.push(`Node "${node.id}" uses column ${node.col}, but only ${layout.colXs.length} columns exist.`);
+ if (!Number.isInteger(node.col) || node.col < 0 || node.col >= layout.colXs.length) {
+ problems.push(`Node "${node.id}" uses column ${node.col}, but valid columns are integers 0..${layout.colXs.length - 1}.`);
+ continue;
+ }
+ if (!isFinitePoint(node.x, node.y, node.cx, node.cy)) {
+ problems.push(`Node "${node.id}" produced non-finite coordinates — check col, width, height, and yOffset are numbers.`);
+ continue;
+ }
+ const estLabelW = textUnits(node.label) * 6.8;
+ if (estLabelW > node.width + 6) {
+ problems.push(`Label "${node.label}" (~${Math.round(estLabelW)}px) is wider than node "${node.id}" (${node.width}px) — shorten the label, move detail to sublabel, or increase node.width.`);
}
const top = laneTop(node.lane);
@@ -158,7 +149,7 @@ function validateWorkflow() {
for (let i = 0; i < laneNodes.length; i += 1) {
for (let j = i + 1; j < laneNodes.length; j += 1) {
if (rectsOverlap(laneNodes[i], laneNodes[j], 8)) {
- problems.push(`Nodes "${laneNodes[i].id}" and "${laneNodes[j].id}" are too close in lane "${lane}".`);
+ problems.push(`Nodes "${laneNodes[i].id}" and "${laneNodes[j].id}" are less than 8px apart in lane "${lane}" — move one to another col, adjust yOffset, or reduce width/height.`);
}
}
}
@@ -173,14 +164,39 @@ function validateWorkflow() {
const [start, end] = routed.points;
const segmentLength = Math.hypot(end[0] - start[0], end[1] - start[1]);
if (segmentLength < 28) {
- problems.push(`Edge "${edge.from}" -> "${edge.to}" is too short (${Math.round(segmentLength)}px).`);
+ problems.push(`Edge "${edge.from}" -> "${edge.to}" is too short (${Math.round(segmentLength)}px; minimum 28px) — drop its label or route it through a channel.`);
}
}
}
}
+ const labelRects = [];
+ for (const edge of workflow.edges) {
+ if (!edge.label || !nodes.has(edge.from) || !nodes.has(edge.to)) continue;
+ const [lx, ly] = labelPoint(edge, pathFor(edge).points);
+ const width = Math.max(30, textUnits(edge.label) * 4.8 + 10);
+ labelRects.push({ label: edge.label, x: lx - width / 2, y: ly - 10, width, height: 14 });
+ }
+ for (const rect of labelRects) {
+ for (const node of nodes.values()) {
+ if (rectsOverlap(rect, node, -2)) {
+ problems.push(`Label "${rect.label}" overlaps node "${node.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.`);
+ }
+ }
+ }
+ for (let i = 0; i < labelRects.length; i += 1) {
+ for (let j = i + 1; j < labelRects.length; j += 1) {
+ if (rectsOverlap(labelRects[i], labelRects[j], -2)) {
+ problems.push(`Labels "${labelRects[i].label}" and "${labelRects[j].label}" overlap — adjust labelDx/labelDy or remove one label.`);
+ }
+ }
+ }
+
+ if (viewBox[0] < layout.laneX + layout.laneW + 16) {
+ problems.push(`viewBox width ${viewBox[0]} clips the ${layout.laneW}px lanes — set meta.viewBox[0] to at least ${layout.laneX + layout.laneW + 16}.`);
+ }
if (legendY() + 18 > viewBox[1]) {
- problems.push(`Legend exceeds viewBox height ${viewBox[1]}.`);
+ problems.push(`Legend exceeds viewBox height ${viewBox[1]} — set meta.viewBox[1] to at least ${legendY() + 18}.`);
}
if (problems.length) {
@@ -188,43 +204,6 @@ function validateWorkflow() {
}
}
-function anchor(node, side) {
- switch (side || 'auto') {
- case 'left': return [node.x, node.cy];
- case 'right': return [node.x + node.width, node.cy];
- case 'top': return [node.cx, node.y];
- case 'bottom': return [node.cx, node.y + node.height];
- default:
- return [node.x + node.width, node.cy];
- }
-}
-
-function defaultTargetSide(from, to) {
- if (to.cx < from.cx) return 'right';
- if (to.cx > from.cx) return 'left';
- if (to.cy > from.cy) return 'top';
- return 'bottom';
-}
-
-function defaultFromSide(from, to) {
- if (to.cx < from.cx) return 'left';
- if (to.cx > from.cx) return 'right';
- if (to.cy > from.cy) return 'bottom';
- return 'top';
-}
-
-function pathFor(edge) {
- const from = nodes.get(edge.from);
- const to = nodes.get(edge.to);
- const start = anchor(from, edge.fromSide || defaultFromSide(from, to));
- const end = anchor(to, edge.toSide || defaultTargetSide(from, to));
- const points = [start, ...routeVia(edge, from, to, start, end), end];
- return {
- d: points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' '),
- points
- };
-}
-
function gapYBetween(fromLane, toLane, bias = 0.5) {
const a = laneTop(fromLane) + layout.laneH;
const b = laneTop(toLane);
@@ -237,56 +216,46 @@ function routeVia(edge, from, to, start, end) {
case 'straight':
return [];
case 'drop': {
- const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);
- return [[start[0], y], [end[0], y]];
- }
- case 'drop-right': {
- const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);
- return [[start[0], y], [end[0], y]];
- }
- case 'drop-left': {
- const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);
+ const y = gapYBetween(from.lane, to.lane, edge.bias ?? 0.5);
return [[start[0], y], [end[0], y]];
}
- case 'same-lane':
- return [];
case 'outside-right': {
- const x = edge.channelX || layout.laneX + layout.laneW + 12;
+ const x = edge.channelX ?? layout.laneX + layout.laneW + 12;
return [[x, start[1]], [x, end[1]]];
}
case 'return-left': {
- const x = edge.channelX || Math.min(from.x, to.x) - 28;
+ const x = edge.channelX ?? Math.min(from.x, to.x) - 28;
return [[x, start[1]], [x, end[1]]];
}
case 'bottom-channel': {
- const y = edge.channelY || Math.max(from.y + from.height, to.y + to.height) + 32;
+ const y = edge.channelY ?? Math.max(from.y + from.height, to.y + to.height) + 32;
return [[start[0], y], [end[0], y]];
}
case 'up-channel': {
- const y = edge.channelY || Math.min(from.y, to.y) - 28;
+ const y = edge.channelY ?? Math.min(from.y, to.y) - 28;
return [[start[0], y], [end[0], y]];
}
case 'auto':
default: {
if (from.lane === to.lane) return [];
- const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);
+ const y = gapYBetween(from.lane, to.lane, edge.bias ?? 0.5);
return [[start[0], y], [end[0], y]];
}
}
}
-function labelPoint(edge, points) {
- if (edge.labelAt) return edge.labelAt;
- if (points.length === 2) {
- return [
- (points[0][0] + points[1][0]) / 2 + (edge.labelDx || 0),
- points[0][1] - 10 + (edge.labelDy || 0)
- ];
- }
- const segmentIndex = Math.min(points.length - 2, Math.max(0, edge.labelSegment ?? 1));
- const a = points[segmentIndex];
- const b = points[segmentIndex + 1];
- return [(a[0] + b[0]) / 2 + (edge.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (edge.labelDy || 0)];
+const pathCache = new Map();
+
+function pathFor(edge) {
+ if (pathCache.has(edge)) return pathCache.get(edge);
+ const from = nodes.get(edge.from);
+ const to = nodes.get(edge.to);
+ const start = anchor(from, chosenSide(edge.fromSide, defaultFromSide(from, to)));
+ const end = anchor(to, chosenSide(edge.toSide, defaultToSide(from, to)));
+ const points = [start, ...routeVia(edge, from, to, start, end), end];
+ const routed = { d: polylinePath(points), points };
+ pathCache.set(edge, routed);
+ return routed;
}
function renderLane(lane, index) {
@@ -296,8 +265,8 @@ function renderLane(lane, index) {
}
function renderNode(node) {
- const fill = typeClass[node.type] || 'c-external';
- const accent = textClass[node.type] || 't-muted';
+ const fill = componentFill[node.type] || 'c-external';
+ const accent = componentText[node.type] || 't-muted';
const tag = node.tag
? `\n <text x="${node.cx}" y="${node.y + node.height - 12}" class="${accent}" font-size="7" text-anchor="middle">${esc(node.tag)}</text>`
: '';
@@ -307,18 +276,8 @@ function renderNode(node) {
<text x="${node.cx}" y="${node.y + 38}" class="t-muted" font-size="8" text-anchor="middle">${esc(node.sublabel || '')}</text>${tag}`;
}
-function edgeAccent(edge) {
- return edge.variant === 'security'
- ? 't-security'
- : edge.variant === 'emphasis'
- ? 't-backend'
- : edge.variant === 'dashed'
- ? 't-database'
- : 't-muted';
-}
-
function renderEdgePath(edge) {
- const [cls, marker] = arrowClass[edge.variant || 'default'] || arrowClass.default;
+ const [cls, marker] = arrowClassMap[edge.variant || 'default'] || arrowClassMap.default;
const routed = pathFor(edge);
const strokeWidth = edge.width || (edge.variant === 'emphasis' ? 1.8 : 1.4);
return ` <path d="${routed.d}" class="${cls}" stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
@@ -328,9 +287,9 @@ function renderEdgeLabel(edge) {
if (!edge.label) return '';
const routed = pathFor(edge);
const [lx, ly] = labelPoint(edge, routed.points);
- const labelW = Math.max(30, edge.label.length * 4.8 + 10);
+ const labelW = Math.max(30, textUnits(edge.label) * 4.8 + 10);
return ` <rect x="${lx - labelW / 2}" y="${ly - 10}" width="${labelW}" height="14" rx="3" class="c-mask"/>
- <text x="${lx}" y="${ly}" class="${edgeAccent(edge)}" font-size="8" text-anchor="middle">${esc(edge.label)}</text>`;
+ <text x="${lx}" y="${ly}" class="${variantAccent(edge.variant, { dashed: 't-database' })}" font-size="8" text-anchor="middle">${esc(edge.label)}</text>`;
}
function renderLegend() {
@@ -349,7 +308,7 @@ function renderLegend() {
}
function renderSvg() {
- return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(workflow.meta, 'workflow diagram')}>
${renderDefinitions()}
<!-- Background Grid -->
@@ -372,14 +331,12 @@ ${renderLegend()}
</svg>`;
}
-
-fs.mkdirSync(path.dirname(outPath), { recursive: true });
validateWorkflow();
-fs.writeFileSync(outPath, applyTemplate(template, {
- title: workflow.meta.title,
- subtitle: workflow.meta.subtitle,
- footer: 'Workflow diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export',
+writeDiagram({
+ outPath,
+ template,
+ meta: workflow.meta,
+ footerLabel: 'Workflow diagram',
svg: renderSvg(),
- cards: renderCards(workflow.cards),
-}));
-console.log(outPath);
+ cards: workflow.cards,
+});
diff --git a/archify/schemas/README.md b/archify/schemas/README.md
new file mode 100644
index 00000000..166529f6
--- /dev/null
+++ b/archify/schemas/README.md
@@ -0,0 +1,69 @@
+# Archify JSON IR Schemas
+
+Each typed renderer consumes a JSON intermediate representation (IR) validated
+against one of the schemas in this folder before any layout work happens.
+
+## Files
+
+| Schema | Governs | Structural arrays |
+|--------|---------|-------------------|
+| `workflow.schema.json` | `diagram_type: "workflow"` | `lanes`, `nodes`, `edges` |
+| `sequence.schema.json` | `diagram_type: "sequence"` | `participants`, `segments`, `messages`, `activations` |
+| `dataflow.schema.json` | `diagram_type: "dataflow"` | `stages`, `nodes`, `flows` |
+| `lifecycle.schema.json` | `diagram_type: "lifecycle"` | `lanes`, `states`, `transitions` |
+| `architecture.schema.json` | `diagram_type: "architecture"` | `components`, `boundaries`, `connections` |
+| `common.schema.json` | shared `$defs` only (no top-level document) | — |
+
+Every diagram schema requires `schema_version`, `diagram_type`, `meta` (with
+`title`), and its structural arrays — except `segments`, `activations`, and
+`cards`, which are optional — and sets `additionalProperties: false` at every
+level, so unknown fields are rejected rather than silently ignored.
+
+## schema_version policy
+
+`schema_version` is `"const": 1`. The constant pins the IR contract: a file
+that validates today keeps rendering identically on every 2.x release. A
+breaking change to any IR shape bumps the constant to `2`; renderers will then
+reject version-1 files with a clear schema error instead of misrendering them.
+Additive, backwards-compatible fields do not bump the version.
+
+## Shared definitions (common.schema.json)
+
+The five diagram schemas reference `common.schema.json#/$defs/...`:
+
+- `id` — element identifiers, pattern `^[a-zA-Z][a-zA-Z0-9_-]*$`
+- `point` — an `[x, y]` pair of numbers (used by `via` and `labelAt`)
+- `componentType` — `frontend`, `backend`, `database`, `cloud`, `security`,
+ `messagebus`, `external`
+- `variant` — `default`, `emphasis`, `security`, `dashed` (sequence messages
+ extend this list locally with `return`)
+- `cards` — the summary-card blocks rendered below the SVG
+
+Lifecycle state `type` is mode-specific (`start`/`active`/`waiting`/...) and
+stays in `lifecycle.schema.json`.
+
+## Runtime validation
+
+`renderers/shared/validator.mjs` compiles all five schemas with ajv
+(draft 2020-12 dialect via `ajv/dist/2020.js`) using `strict: true` and
+`allErrors: true`; `common.schema.json` is registered with `ajv.addSchema` so
+the `$ref`s resolve. Validation runs when a renderer loads its input, before
+the renderer's own layout checks.
+
+If ajv is not installed (no `npm install` in the skill folder), the validator
+prints a warning and skips schema validation; renderer layout checks still
+run, so structurally valid files keep rendering.
+
+## Error format
+
+Schema violations exit non-zero. Each ajv error is reported on its own line as
+the instance path — annotated with the nearest enclosing element's `id` or
+`label` — followed by the message and parameters:
+
+```text
+workflow schema validation failed:
+ /nodes/3 (id/label: "router") must NOT have additional properties {"additionalProperty":"colour"}
+```
+
+Schemas catch shape errors (types, enums, ranges, unknown fields); geometry
+problems such as overlaps and label collisions are the renderers' job.
diff --git a/archify/schemas/architecture.schema.json b/archify/schemas/architecture.schema.json
new file mode 100644
index 00000000..1bc1184d
--- /dev/null
+++ b/archify/schemas/architecture.schema.json
@@ -0,0 +1,95 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/tt-a1i/archify/schemas/architecture.schema.json",
+ "title": "Archify Architecture Diagram",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["schema_version", "diagram_type", "meta", "components"],
+ "properties": {
+ "schema_version": { "const": 1 },
+ "diagram_type": { "const": "architecture" },
+ "meta": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["title"],
+ "properties": {
+ "title": { "type": "string", "minLength": 1 },
+ "subtitle": { "type": "string" },
+ "output": { "type": "string" },
+ "viewBox": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number", "minimum": 320 },
+ { "type": "number", "minimum": 240 }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ }
+ }
+ },
+ "components": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "type", "label", "pos"],
+ "properties": {
+ "id": { "$ref": "common.schema.json#/$defs/id" },
+ "type": { "$ref": "common.schema.json#/$defs/componentType" },
+ "label": { "type": "string", "minLength": 1 },
+ "sublabel": { "type": "string" },
+ "tag": { "type": "string" },
+ "pos": { "$ref": "common.schema.json#/$defs/point" },
+ "size": { "$ref": "common.schema.json#/$defs/point" }
+ }
+ }
+ },
+ "boundaries": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["kind", "label", "wraps"],
+ "properties": {
+ "kind": { "enum": ["region", "security-group"] },
+ "label": { "type": "string", "minLength": 1 },
+ "wraps": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "common.schema.json#/$defs/id" }
+ },
+ "pad": { "type": "number", "minimum": 0 }
+ }
+ }
+ },
+ "connections": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["from", "to"],
+ "properties": {
+ "from": { "$ref": "common.schema.json#/$defs/id" },
+ "to": { "$ref": "common.schema.json#/$defs/id" },
+ "label": { "type": "string" },
+ "variant": { "$ref": "common.schema.json#/$defs/variant" },
+ "fromSide": { "enum": ["left", "right", "top", "bottom"] },
+ "toSide": { "enum": ["left", "right", "top", "bottom"] },
+ "route": { "enum": ["auto", "straight", "orthogonal-h", "orthogonal-v"] },
+ "via": {
+ "type": "array",
+ "items": { "$ref": "common.schema.json#/$defs/point" }
+ },
+ "labelAt": { "$ref": "common.schema.json#/$defs/point" },
+ "labelDx": { "type": "number" },
+ "labelDy": { "type": "number" },
+ "labelSegment": { "type": "integer", "minimum": 0 },
+ "width": { "type": "number", "minimum": 0.5 }
+ }
+ }
+ },
+ "cards": { "$ref": "common.schema.json#/$defs/cards" }
+ }
+}
diff --git a/archify/schemas/common.schema.json b/archify/schemas/common.schema.json
new file mode 100644
index 00000000..60c55089
--- /dev/null
+++ b/archify/schemas/common.schema.json
@@ -0,0 +1,43 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/tt-a1i/archify/schemas/common.schema.json",
+ "title": "Archify Shared Definitions",
+ "$defs": {
+ "id": {
+ "type": "string",
+ "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"
+ },
+ "point": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number" },
+ { "type": "number" }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ },
+ "componentType": {
+ "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
+ },
+ "variant": {
+ "enum": ["default", "emphasis", "security", "dashed"]
+ },
+ "cards": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["dot", "title", "items"],
+ "properties": {
+ "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },
+ "title": { "type": "string", "minLength": 1 },
+ "items": {
+ "type": "array",
+ "items": { "type": "string" }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/archify/schemas/dataflow.schema.json b/archify/schemas/dataflow.schema.json
index 673ef861..930ccb82 100644
--- a/archify/schemas/dataflow.schema.json
+++ b/archify/schemas/dataflow.schema.json
@@ -4,7 +4,14 @@
"title": "Archify Data Flow Diagram",
"type": "object",
"additionalProperties": false,
- "required": ["schema_version", "diagram_type", "meta", "stages", "nodes", "flows"],
+ "required": [
+ "schema_version",
+ "diagram_type",
+ "meta",
+ "stages",
+ "nodes",
+ "flows"
+ ],
"properties": {
"schema_version": {
"const": 1
@@ -15,16 +22,31 @@
"meta": {
"type": "object",
"additionalProperties": false,
- "required": ["title"],
+ "required": [
+ "title"
+ ],
"properties": {
- "title": { "type": "string", "minLength": 1 },
- "subtitle": { "type": "string" },
- "output": { "type": "string" },
+ "title": {
+ "type": "string",
+ "minLength": 1
+ },
+ "subtitle": {
+ "type": "string"
+ },
+ "output": {
+ "type": "string"
+ },
"viewBox": {
"type": "array",
"prefixItems": [
- { "type": "number", "minimum": 360 },
- { "type": "number", "minimum": 360 }
+ {
+ "type": "number",
+ "minimum": 360
+ },
+ {
+ "type": "number",
+ "minimum": 360
+ }
],
"items": false,
"minItems": 2,
@@ -39,9 +61,14 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["label"],
+ "required": [
+ "label"
+ ],
"properties": {
- "label": { "type": "string", "minLength": 1 }
+ "label": {
+ "type": "string",
+ "minLength": 1
+ }
}
}
},
@@ -51,20 +78,49 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["id", "type", "label", "stage", "row"],
+ "required": [
+ "id",
+ "type",
+ "label",
+ "stage",
+ "row"
+ ],
"properties": {
- "id": { "$ref": "#/$defs/id" },
+ "id": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
"type": {
- "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
- },
- "label": { "type": "string", "minLength": 1 },
- "sublabel": { "type": "string" },
- "tag": { "type": "string" },
- "stage": { "type": "integer", "minimum": 0 },
- "row": { "type": "integer", "minimum": 0 },
- "width": { "type": "number", "minimum": 48 },
- "height": { "type": "number", "minimum": 36 },
- "yOffset": { "type": "number" }
+ "$ref": "common.schema.json#/$defs/componentType"
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ },
+ "sublabel": {
+ "type": "string"
+ },
+ "tag": {
+ "type": "string"
+ },
+ "stage": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "row": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "width": {
+ "type": "number",
+ "minimum": 48
+ },
+ "height": {
+ "type": "number",
+ "minimum": 36
+ },
+ "yOffset": {
+ "type": "number"
+ }
}
}
},
@@ -73,77 +129,87 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["from", "to", "label"],
+ "required": [
+ "from",
+ "to",
+ "label"
+ ],
"properties": {
- "from": { "$ref": "#/$defs/id" },
- "to": { "$ref": "#/$defs/id" },
- "label": { "type": "string", "minLength": 1 },
- "classification": { "type": "string" },
+ "from": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "to": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ },
+ "classification": {
+ "type": "string"
+ },
"variant": {
- "enum": ["default", "emphasis", "security", "dashed"]
+ "$ref": "common.schema.json#/$defs/variant"
},
"route": {
- "enum": ["auto", "straight", "vertical-channel", "bottom-channel", "top-channel"]
+ "enum": [
+ "auto",
+ "straight",
+ "vertical-channel",
+ "bottom-channel",
+ "top-channel"
+ ]
},
"fromSide": {
- "enum": ["left", "right", "top", "bottom"]
+ "enum": [
+ "left",
+ "right",
+ "top",
+ "bottom"
+ ]
},
"toSide": {
- "enum": ["left", "right", "top", "bottom"]
+ "enum": [
+ "left",
+ "right",
+ "top",
+ "bottom"
+ ]
+ },
+ "channelX": {
+ "type": "number"
+ },
+ "channelY": {
+ "type": "number"
},
- "channelX": { "type": "number" },
- "channelY": { "type": "number" },
"labelAt": {
- "type": "array",
- "prefixItems": [
- { "type": "number" },
- { "type": "number" }
- ],
- "items": false,
- "minItems": 2,
- "maxItems": 2
- },
- "labelDx": { "type": "number" },
- "labelDy": { "type": "number" },
- "labelSegment": { "type": "integer", "minimum": 0 },
+ "$ref": "common.schema.json#/$defs/point"
+ },
+ "labelDx": {
+ "type": "number"
+ },
+ "labelDy": {
+ "type": "number"
+ },
+ "labelSegment": {
+ "type": "integer",
+ "minimum": 0
+ },
"via": {
"type": "array",
"items": {
- "type": "array",
- "prefixItems": [
- { "type": "number" },
- { "type": "number" }
- ],
- "items": false,
- "minItems": 2,
- "maxItems": 2
+ "$ref": "common.schema.json#/$defs/point"
}
},
- "width": { "type": "number", "minimum": 0.5 }
+ "width": {
+ "type": "number",
+ "minimum": 0.5
+ }
}
}
},
"cards": {
- "type": "array",
- "items": {
- "type": "object",
- "additionalProperties": false,
- "required": ["dot", "title", "items"],
- "properties": {
- "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },
- "title": { "type": "string", "minLength": 1 },
- "items": {
- "type": "array",
- "items": { "type": "string" }
- }
- }
- }
- }
- },
- "$defs": {
- "id": {
- "type": "string",
- "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"
+ "$ref": "common.schema.json#/$defs/cards"
}
}
}
diff --git a/archify/schemas/lifecycle.schema.json b/archify/schemas/lifecycle.schema.json
index ccc3448c..cea6fc98 100644
--- a/archify/schemas/lifecycle.schema.json
+++ b/archify/schemas/lifecycle.schema.json
@@ -4,7 +4,14 @@
"title": "Archify Lifecycle Diagram",
"type": "object",
"additionalProperties": false,
- "required": ["schema_version", "diagram_type", "meta", "lanes", "states", "transitions"],
+ "required": [
+ "schema_version",
+ "diagram_type",
+ "meta",
+ "lanes",
+ "states",
+ "transitions"
+ ],
"properties": {
"schema_version": {
"const": 1
@@ -15,16 +22,31 @@
"meta": {
"type": "object",
"additionalProperties": false,
- "required": ["title"],
+ "required": [
+ "title"
+ ],
"properties": {
- "title": { "type": "string", "minLength": 1 },
- "subtitle": { "type": "string" },
- "output": { "type": "string" },
+ "title": {
+ "type": "string",
+ "minLength": 1
+ },
+ "subtitle": {
+ "type": "string"
+ },
+ "output": {
+ "type": "string"
+ },
"viewBox": {
"type": "array",
"prefixItems": [
- { "type": "number", "minimum": 420 },
- { "type": "number", "minimum": 360 }
+ {
+ "type": "number",
+ "minimum": 420
+ },
+ {
+ "type": "number",
+ "minimum": 566
+ }
],
"items": false,
"minItems": 2,
@@ -39,10 +61,18 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["id", "label"],
+ "required": [
+ "id",
+ "label"
+ ],
"properties": {
- "id": { "$ref": "#/$defs/id" },
- "label": { "type": "string", "minLength": 1 }
+ "id": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ }
}
}
},
@@ -52,21 +82,61 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["id", "type", "label", "lane", "col"],
+ "required": [
+ "id",
+ "type",
+ "label",
+ "lane",
+ "col"
+ ],
"properties": {
- "id": { "$ref": "#/$defs/id" },
+ "id": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
"type": {
- "enum": ["start", "active", "waiting", "decision", "success", "failure", "neutral", "external"]
- },
- "label": { "type": "string", "minLength": 1 },
- "sublabel": { "type": "string" },
- "tag": { "type": "string" },
- "step": { "type": "string" },
- "lane": { "$ref": "#/$defs/id" },
- "col": { "type": "integer", "minimum": 0 },
- "width": { "type": "number", "minimum": 48 },
- "height": { "type": "number", "minimum": 36 },
- "yOffset": { "type": "number" }
+ "enum": [
+ "start",
+ "active",
+ "waiting",
+ "decision",
+ "success",
+ "failure",
+ "neutral",
+ "external"
+ ]
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ },
+ "sublabel": {
+ "type": "string"
+ },
+ "tag": {
+ "type": "string"
+ },
+ "step": {
+ "type": "string"
+ },
+ "lane": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "col": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 4
+ },
+ "width": {
+ "type": "number",
+ "minimum": 48
+ },
+ "height": {
+ "type": "number",
+ "minimum": 36
+ },
+ "yOffset": {
+ "type": "number"
+ }
}
}
},
@@ -75,78 +145,91 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["from", "to"],
+ "required": [
+ "from",
+ "to"
+ ],
"properties": {
- "from": { "$ref": "#/$defs/id" },
- "to": { "$ref": "#/$defs/id" },
- "label": { "type": "string" },
- "note": { "type": "string" },
+ "from": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "to": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "label": {
+ "type": "string"
+ },
+ "note": {
+ "type": "string"
+ },
"variant": {
- "enum": ["default", "emphasis", "security", "dashed"]
+ "$ref": "common.schema.json#/$defs/variant"
},
"route": {
- "enum": ["auto", "straight", "drop", "raise", "bottom-channel", "top-channel", "right-channel", "left-channel"]
+ "enum": [
+ "auto",
+ "straight",
+ "drop",
+ "bottom-channel",
+ "top-channel",
+ "right-channel",
+ "left-channel"
+ ]
},
"fromSide": {
- "enum": ["left", "right", "top", "bottom"]
+ "enum": [
+ "left",
+ "right",
+ "top",
+ "bottom"
+ ]
},
"toSide": {
- "enum": ["left", "right", "top", "bottom"]
+ "enum": [
+ "left",
+ "right",
+ "top",
+ "bottom"
+ ]
+ },
+ "channelX": {
+ "type": "number"
+ },
+ "channelY": {
+ "type": "number"
+ },
+ "cornerRadius": {
+ "type": "number",
+ "minimum": 0
},
- "channelX": { "type": "number" },
- "channelY": { "type": "number" },
- "bias": { "type": "number", "minimum": 0, "maximum": 1 },
"labelAt": {
- "type": "array",
- "prefixItems": [
- { "type": "number" },
- { "type": "number" }
- ],
- "items": false,
- "minItems": 2,
- "maxItems": 2
- },
- "labelDx": { "type": "number" },
- "labelDy": { "type": "number" },
- "labelSegment": { "type": "integer", "minimum": 0 },
+ "$ref": "common.schema.json#/$defs/point"
+ },
+ "labelDx": {
+ "type": "number"
+ },
+ "labelDy": {
+ "type": "number"
+ },
+ "labelSegment": {
+ "type": "integer",
+ "minimum": 0
+ },
"via": {
"type": "array",
"items": {
- "type": "array",
- "prefixItems": [
- { "type": "number" },
- { "type": "number" }
- ],
- "items": false,
- "minItems": 2,
- "maxItems": 2
+ "$ref": "common.schema.json#/$defs/point"
}
},
- "width": { "type": "number", "minimum": 0.5 }
+ "width": {
+ "type": "number",
+ "minimum": 0.5
+ }
}
}
},
"cards": {
- "type": "array",
- "items": {
- "type": "object",
- "additionalProperties": false,
- "required": ["dot", "title", "items"],
- "properties": {
- "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },
- "title": { "type": "string", "minLength": 1 },
- "items": {
- "type": "array",
- "items": { "type": "string" }
- }
- }
- }
- }
- },
- "$defs": {
- "id": {
- "type": "string",
- "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"
+ "$ref": "common.schema.json#/$defs/cards"
}
}
}
diff --git a/archify/schemas/sequence.schema.json b/archify/schemas/sequence.schema.json
index 2564842a..96a19ef2 100644
--- a/archify/schemas/sequence.schema.json
+++ b/archify/schemas/sequence.schema.json
@@ -4,7 +4,13 @@
"title": "Archify Sequence Diagram",
"type": "object",
"additionalProperties": false,
- "required": ["schema_version", "diagram_type", "meta", "participants", "messages"],
+ "required": [
+ "schema_version",
+ "diagram_type",
+ "meta",
+ "participants",
+ "messages"
+ ],
"properties": {
"schema_version": {
"const": 1
@@ -15,16 +21,31 @@
"meta": {
"type": "object",
"additionalProperties": false,
- "required": ["title"],
+ "required": [
+ "title"
+ ],
"properties": {
- "title": { "type": "string", "minLength": 1 },
- "subtitle": { "type": "string" },
- "output": { "type": "string" },
+ "title": {
+ "type": "string",
+ "minLength": 1
+ },
+ "subtitle": {
+ "type": "string"
+ },
+ "output": {
+ "type": "string"
+ },
"viewBox": {
"type": "array",
"prefixItems": [
- { "type": "number", "minimum": 320 },
- { "type": "number", "minimum": 240 }
+ {
+ "type": "number",
+ "minimum": 480
+ },
+ {
+ "type": "number",
+ "minimum": 480
+ }
],
"items": false,
"minItems": 2,
@@ -38,14 +59,25 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["id", "type", "label"],
+ "required": [
+ "id",
+ "type",
+ "label"
+ ],
"properties": {
- "id": { "$ref": "#/$defs/id" },
+ "id": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
"type": {
- "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
+ "$ref": "common.schema.json#/$defs/componentType"
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
},
- "label": { "type": "string", "minLength": 1 },
- "sublabel": { "type": "string" }
+ "sublabel": {
+ "type": "string"
+ }
}
}
},
@@ -54,11 +86,22 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["from", "to", "label"],
+ "required": [
+ "from",
+ "to",
+ "label"
+ ],
"properties": {
- "from": { "type": "number" },
- "to": { "type": "number" },
- "label": { "type": "string", "minLength": 1 }
+ "from": {
+ "type": "number"
+ },
+ "to": {
+ "type": "number"
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ }
}
}
},
@@ -68,16 +111,39 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["from", "to", "y", "label"],
+ "required": [
+ "from",
+ "to",
+ "y",
+ "label"
+ ],
"properties": {
- "from": { "$ref": "#/$defs/id" },
- "to": { "$ref": "#/$defs/id" },
- "y": { "type": "number" },
- "label": { "type": "string", "minLength": 1 },
+ "from": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "to": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "y": {
+ "type": "number",
+ "minimum": 160
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ },
"variant": {
- "enum": ["default", "emphasis", "security", "dashed", "return"]
+ "enum": [
+ "default",
+ "emphasis",
+ "security",
+ "dashed",
+ "return"
+ ]
},
- "note": { "type": "string" }
+ "note": {
+ "type": "string"
+ }
}
}
},
@@ -86,38 +152,29 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["participant", "from", "to"],
+ "required": [
+ "participant",
+ "from",
+ "to"
+ ],
"properties": {
- "participant": { "$ref": "#/$defs/id" },
- "from": { "type": "number" },
- "to": { "type": "number" },
+ "participant": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "from": {
+ "type": "number"
+ },
+ "to": {
+ "type": "number"
+ },
"type": {
- "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
+ "$ref": "common.schema.json#/$defs/componentType"
}
}
}
},
"cards": {
- "type": "array",
- "items": {
- "type": "object",
- "additionalProperties": false,
- "required": ["dot", "title", "items"],
- "properties": {
- "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },
- "title": { "type": "string", "minLength": 1 },
- "items": {
- "type": "array",
- "items": { "type": "string" }
- }
- }
- }
- }
- },
- "$defs": {
- "id": {
- "type": "string",
- "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"
+ "$ref": "common.schema.json#/$defs/cards"
}
}
}
diff --git a/archify/schemas/workflow.schema.json b/archify/schemas/workflow.schema.json
index 75a07233..8eda3c91 100644
--- a/archify/schemas/workflow.schema.json
+++ b/archify/schemas/workflow.schema.json
@@ -4,7 +4,14 @@
"title": "Archify Workflow Diagram",
"type": "object",
"additionalProperties": false,
- "required": ["schema_version", "diagram_type", "meta", "lanes", "nodes", "edges"],
+ "required": [
+ "schema_version",
+ "diagram_type",
+ "meta",
+ "lanes",
+ "nodes",
+ "edges"
+ ],
"properties": {
"schema_version": {
"const": 1
@@ -15,16 +22,31 @@
"meta": {
"type": "object",
"additionalProperties": false,
- "required": ["title"],
+ "required": [
+ "title"
+ ],
"properties": {
- "title": { "type": "string", "minLength": 1 },
- "subtitle": { "type": "string" },
- "output": { "type": "string" },
+ "title": {
+ "type": "string",
+ "minLength": 1
+ },
+ "subtitle": {
+ "type": "string"
+ },
+ "output": {
+ "type": "string"
+ },
"viewBox": {
"type": "array",
"prefixItems": [
- { "type": "number", "minimum": 320 },
- { "type": "number", "minimum": 240 }
+ {
+ "type": "number",
+ "minimum": 700
+ },
+ {
+ "type": "number",
+ "minimum": 240
+ }
],
"items": false,
"minItems": 2,
@@ -38,10 +60,18 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["id", "label"],
+ "required": [
+ "id",
+ "label"
+ ],
"properties": {
- "id": { "$ref": "#/$defs/id" },
- "label": { "type": "string", "minLength": 1 }
+ "id": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ }
}
}
},
@@ -51,20 +81,49 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["id", "lane", "col", "type", "label"],
+ "required": [
+ "id",
+ "lane",
+ "col",
+ "type",
+ "label"
+ ],
"properties": {
- "id": { "$ref": "#/$defs/id" },
- "lane": { "$ref": "#/$defs/id" },
- "col": { "type": "integer", "minimum": 0 },
+ "id": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "lane": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "col": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 5
+ },
"type": {
- "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
- },
- "label": { "type": "string", "minLength": 1 },
- "sublabel": { "type": "string" },
- "tag": { "type": "string" },
- "width": { "type": "number", "minimum": 32 },
- "height": { "type": "number", "minimum": 32 },
- "yOffset": { "type": "number" }
+ "$ref": "common.schema.json#/$defs/componentType"
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1
+ },
+ "sublabel": {
+ "type": "string"
+ },
+ "tag": {
+ "type": "string"
+ },
+ "width": {
+ "type": "number",
+ "minimum": 32
+ },
+ "height": {
+ "type": "number",
+ "minimum": 32
+ },
+ "yOffset": {
+ "type": "number"
+ }
}
}
},
@@ -73,66 +132,89 @@
"items": {
"type": "object",
"additionalProperties": false,
- "required": ["from", "to"],
+ "required": [
+ "from",
+ "to"
+ ],
"properties": {
- "from": { "$ref": "#/$defs/id" },
- "to": { "$ref": "#/$defs/id" },
- "label": { "type": "string" },
- "variant": { "enum": ["default", "emphasis", "security", "dashed"] },
- "fromSide": { "$ref": "#/$defs/side" },
- "toSide": { "$ref": "#/$defs/side" },
+ "from": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "to": {
+ "$ref": "common.schema.json#/$defs/id"
+ },
+ "label": {
+ "type": "string"
+ },
+ "variant": {
+ "$ref": "common.schema.json#/$defs/variant"
+ },
+ "fromSide": {
+ "$ref": "#/$defs/side"
+ },
+ "toSide": {
+ "$ref": "#/$defs/side"
+ },
"route": {
- "enum": ["auto", "straight", "drop", "drop-right", "drop-left", "same-lane", "outside-right", "return-left", "bottom-channel", "up-channel"]
+ "enum": [
+ "auto",
+ "straight",
+ "drop",
+ "outside-right",
+ "return-left",
+ "bottom-channel",
+ "up-channel"
+ ]
},
"via": {
"type": "array",
- "items": { "$ref": "#/$defs/point" }
- },
- "labelAt": { "$ref": "#/$defs/point" },
- "labelDx": { "type": "number" },
- "labelDy": { "type": "number" },
- "labelSegment": { "type": "integer", "minimum": 0 },
- "channelX": { "type": "number" },
- "channelY": { "type": "number" },
- "bias": { "type": "number", "minimum": 0, "maximum": 1 },
- "width": { "type": "number", "minimum": 0.5 }
+ "items": {
+ "$ref": "common.schema.json#/$defs/point"
+ }
+ },
+ "labelAt": {
+ "$ref": "common.schema.json#/$defs/point"
+ },
+ "labelDx": {
+ "type": "number"
+ },
+ "labelDy": {
+ "type": "number"
+ },
+ "labelSegment": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "channelX": {
+ "type": "number"
+ },
+ "channelY": {
+ "type": "number"
+ },
+ "bias": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 1
+ },
+ "width": {
+ "type": "number",
+ "minimum": 0.5
+ }
}
}
},
"cards": {
- "type": "array",
- "items": {
- "type": "object",
- "additionalProperties": false,
- "required": ["dot", "title", "items"],
- "properties": {
- "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },
- "title": { "type": "string", "minLength": 1 },
- "items": {
- "type": "array",
- "items": { "type": "string" }
- }
- }
- }
+ "$ref": "common.schema.json#/$defs/cards"
}
},
"$defs": {
- "id": {
- "type": "string",
- "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"
- },
"side": {
- "enum": ["auto", "left", "right", "top", "bottom"]
- },
- "point": {
- "type": "array",
- "prefixItems": [
- { "type": "number" },
- { "type": "number" }
- ],
- "items": false,
- "minItems": 2,
- "maxItems": 2
+ "enum": [
+ "left",
+ "right",
+ "top",
+ "bottom"
+ ]
}
}
}