How Archify Transforms Typed JSON IR into HTML/SVG Diagrams: The 4-Stage Pipeline
Archify transforms typed JSON Intermediate Representation (IR) into standalone HTML/SVG diagrams through a rigorous four-stage pipeline that validates schema, computes geometric layouts, enforces visual correctness, and injects the resulting SVG into a localized HTML template.
Archify, an open-source visualization tool maintained at tt-a1i/archify, converts structured typed JSON IR—such as web-app.architecture.json—into self-contained, accessible web pages. This transformation process bridges the gap between declarative system descriptions and production-ready visual diagrams through a tightly-coupled rendering engine written in modern JavaScript.
The Four-Stage Rendering Pipeline
The core transformation logic resides in archify/renderers/architecture/render-architecture.mjs and shared utilities in archify/renderers/shared/cli.mjs. The pipeline processes JSON IR through four distinct phases before emitting the final HTML artifact.
Stage 1: Load and Validate JSON IR
The renderer begins by ingesting the typed JSON IR through loadDiagram in archify/renderers/shared/cli.mjs. This stage performs rigorous validation to ensure diagram integrity before any geometric computation occurs.
The validation suite includes:
validateSchema– Verifies the JSON structure against Archify’s schema definitions inarchify/schemas/validateRelationshipIds– Ensures all connection references point to existing componentsvalidateGuidedViews– Confirms guided view configurations are well-formedvalidateEngineeringProfile– Checks engineering profile metadata for consistency
If validation fails, the process aborts immediately with detailed diagnostic messages. For batch operations, scripts/render-examples.mjs orchestrates multiple renderer invocations, each calling loadDiagramWithBrandMarks to optionally enrich diagrams with brand metadata via prepareDiagramBrandMarks.
Stage 2: Prepare Layout and Compute Geometry
Once validated, the diagram enters layout computation. The renderer determines positioning through either grid layout or free placement based on the meta.layout.mode property.
Key layout functions in render-architecture.mjs include:
gridLayout– Arranges components in a structured grid whenlayout.mode === 'grid'measureComponent– Calculates bounding boxes for each elementresolveBoundaryTitles– Positions boundary labels and framespathForandrouteVia– Compute connection paths with automatic port spreading
The layout engine resolves automatic port placement using side-aware bridge algorithms (automaticPortRhythmBridge) that respect explicit fromSide/toSide hints in the JSON IR. This ensures connection lines avoid component interiors while maintaining readable routing.
Stage 3: Validate Geometric Correctness
Before rendering, Archify enforces geometric integrity through validateArchitecture. This stage catches visual defects that would compromise readability.
The validation suite scans for:
- Overlap detection –
cleanEndpointSideProblemsprevents component collisions - Flow validation –
cleanFlowProblemschecks connection continuity - Crossing optimization –
cleanCrossingProblemsminimizes line intersections - Label clearance –
cleanLabelRouteClearanceProblemsensures text remains legible and unoccluded - Boundary containment – Verifies boundary frames properly encapsulate their children
If any validator detects issues, throwDiagnosticProblems aggregates all errors into a single diagnostic bundle and aborts the render. This geometric gatekeeping guarantees that only visually sound diagrams proceed to SVG generation.
Stage 4: Render SVG and Assemble HTML
The final stage constructs the visual output through renderSvg and writeDiagram. The renderer builds SVG elements programmatically using helpers from archify/renderers/shared/utils.mjs.
SVG construction proceeds through specialized renderers:
renderComponent– Emits rectangles, type sigils, and primary labelsrenderConnectionPathandrenderConnectionLabel– Draws polylines with arrowheads and connection annotationsrenderBoundaryFrameandrenderBoundaryLabel– Creates containment visualizationsrenderLegend– Generates the diagram keyrenderDefinitions– Establishes SVG<defs>for patterns and markers
The resulting SVG string is injected into archify/assets/template.html via writeDiagram. This template replacement system substitutes placeholders like ARCHIFY:SVG_SLOT, ARCHIFY:CARDS_SLOT, and ARCHIFY:GUIDED_VIEWS_SLOT with generated content. Localization applies through applyTemplate in utils.mjs, producing a standalone HTML file that requires no external dependencies.
Orchestration and Entry Points
The rendering pipeline is accessible through multiple entry points. For batch processing, scripts/render-examples.mjs iterates over example JSON files:
node archify/scripts/render-examples.mjs
This generates web-app-rendered.html, workflow-agent-tool-call-rendered.html, and other artifacts by invoking type-specific renderers (render-architecture.mjs, render-workflow.mjs, etc.).
For programmatic use, the renderer follows this synchronous flow:
import { loadDiagramWithBrandMarks } from '../renderers/shared/cli.mjs';
import { renderSvg, validateArchitecture } from './render-architecture.mjs';
async function run(inputJson, outputHtml) {
const { diagram, template, outPath, sourceEvidence } = await loadDiagramWithBrandMarks({
rendererDir: import.meta.url,
diagramType: 'architecture',
defaultExample: 'web-app.architecture.json',
argv: [process.execPath, inputJson, outputHtml],
});
// Compute layout and validate geometry
validateArchitecture(diagram);
// Produce SVG string
const svg = renderSvg(diagram);
// Write final HTML with template injection
writeDiagram({
outPath,
template,
diagramType: 'architecture',
meta: diagram.meta,
svg,
cards: diagram.cards,
sourceEvidence
});
}
Input Format and Output Structure
Archify expects typed JSON IR with explicit typing for components, connections, and metadata:
{
"meta": {
"title": "Web App",
"locale": "en",
"viewBox": [800, 600]
},
"components": [
{
"id": "frontend",
"type": "frontend",
"label": "UI",
"pos": [100, 150],
"size": [120, 60]
},
{
"id": "backend",
"type": "backend",
"label": "API",
"pos": [300, 150]
}
],
"connections": [
{
"from": "frontend",
"to": "backend",
"label": "REST"
}
],
"boundaries": [
{
"id": "zone1",
"label": "Public",
"wraps": ["frontend"]
}
]
}
Processing this input yields semantic SVG markup embedded in HTML:
<svg viewBox="0 0 800 600" role="img" lang="en"
aria-labelledby="archify-diagram-title archify-diagram-description">
<rect width="100%" height="100%" fill="url(#grid)" />
<rect data-graph-role="structural-frame" ... />
<path data-composition-points="..." d="M112 180 L312 180"
class="c-default" marker-end="url(#arrowhead)" />
<g id="node-frontend" ...>
<rect x="100" y="150" width="120" height="60" rx="6" class="c-frontend" />
<text x="160" y="180" class="t-primary" font-size="11"
font-weight="600" text-anchor="middle">UI</text>
</g>
</svg>
Summary
Archify’s JSON IR to HTML/SVG transformation provides a deterministic pipeline for generating architectural diagrams:
- Strict validation at both schema and geometric levels prevents malformed output
- Grid or free-form layout engines accommodate different diagramming needs with automatic routing
- Geometric validators enforce readability standards before rendering occurs
- Template-based HTML generation produces localized, self-contained files with no external dependencies
- Accessibility features including ARIA labels and semantic roles are baked into the SVG output
Frequently Asked Questions
What is the typed JSON IR format in Archify?
The typed JSON IR (Intermediate Representation) is a declarative schema that describes system architecture through typed components, connections, boundaries, and metadata. Defined by JSON Schema files in archify/schemas/, this format separates diagram structure from presentation, allowing architects to define systems in web-app.architecture.json files while the renderer handles visual layout and styling.
How does Archify handle component positioning and layout?
Archify supports two layout modes controlled by meta.layout.mode. When set to grid, the renderer uses gridLayout in render-architecture.mjs to arrange components in structured rows and columns. Otherwise, it respects explicit pos coordinates from the JSON IR. The system automatically calculates viewBox dimensions, measures component bounds with measureComponent, and resolves boundary containment for visual grouping.
What validation ensures diagram correctness before rendering?
Archify implements a two-tier validation system. First, validateSchema in cli.mjs checks JSON structure and relationship integrity. Second, validateArchitecture runs geometric checks including overlap detection (cleanEndpointSideProblems), label collision avoidance (cleanLabelRouteClearanceProblems), and boundary containment. These validators throw aggregated diagnostic bundles if any geometric or structural issues exist, preventing the generation of invalid diagrams.
Can Archify-generated diagrams be embedded in existing web applications?
Yes. The output of writeDiagram is a self-contained HTML file with an embedded SVG diagram. The SVG includes inline CSS classes and definitions, requiring no external stylesheets. For direct embedding, extract the <svg> element from the ARCHIFY:SVG_SLOT template replacement—the markup includes proper viewBox, ARIA labels, and language attributes, making it suitable for inclusion in documentation sites, wikis, or single-page applications.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →