---
title: System Architecture
description: Deep dive into VertiWiki's client-side zero-backend architecture, lifecycle stages, and C4 container topology.
tags: [vertiwiki, architecture, c4-diagram, system-design, internals]
---

# System Architecture

> For the complete documentation index and agent navigation, see [llms.txt](/llms.txt).

VertiWiki represents a radical departure from traditional Static Site Generators (SSGs) and Content Management Systems (CMSs). Instead of compiling Markdown documents into hundreds of individual HTML files on a build server, VertiWiki ships as an autonomous single-file SPA that handles routing, fetching, parsing, sanitizing, and rendering entirely in the client browser.

---

## 🏛️ C4 Container Architecture

The diagram below illustrates VertiWiki's system context and runtime containers:

```mermaid
C4Container
    title Container Diagram for VertiWiki Client Runtime

    Person(user, "Human Reader / AI Agent", "Consumes documentation and searches content.")
    
    Container_Boundary(c1, "Browser Client Runtime") {
        Component(router, "Router", "TypeScript (src/core/router.ts)", "Intercepts hash changes, resolves locales, normalizes paths.")
        Component(pipeline, "Pipeline", "TypeScript (src/core/pipeline.ts)", "Executes beforeParse, afterParse, and afterRender plugin middleware.")
        Component(parser, "MarkdownParser", "TypeScript (src/core/parser.ts)", "Parses YAML frontmatter, marked AST, and DOMPurify sanitization.")
        Component(layout, "LayoutManager", "TypeScript (src/ui/layout.ts)", "Builds DOM layout, TOC, sidebar, and layout modes.")
        Component(theme, "ThemeManager", "TypeScript (src/ui/theme.ts)", "Resolves custom theme presets and applies CSS custom properties.")
        Component(search, "SearchEngine", "TypeScript (src/plugins/search.ts)", "Builds in-memory MiniSearch index for instant full-text filtering.")
    }

    Container_Boundary(c2, "Static Storage / Edge CDN") {
        ComponentDb(markdown, "Markdown Files", "Standard .md files", "Raw documentation source and navigation.md.")
        ComponentDb(config, "config.json", "JSON Config", "Runtime configuration and theme definitions.")
        ComponentDb(assets, "Static Assets", "SVG/PNG/CSS", "Logos, favicons, and modular theme files.")
    }

    Rel(user, router, "Navigates to URL", "HTTPS / Hash Route")
    Rel(router, markdown, "Fetches document", "HTTP GET (fetch API)")
    Rel(router, config, "Loads settings", "HTTP GET (fetch API)")
    Rel(router, pipeline, "Passes raw markdown", "Internal Pipeline Call")
    Rel(pipeline, parser, "Invokes marked & DOMPurify", "Synchronous AST")
    Rel(pipeline, layout, "Mounts clean HTML", "DOM Injection")
    Rel(layout, theme, "Applies design tokens", "CSS Variables")
    Rel(pipeline, search, "Feeds document content", "MiniSearch Ingestion")
```

---

## 🔄 The Zero-Backend Lifecycle

The execution lifecycle occurs across six well-defined phases:

```mermaid
stateDiagram-v2
    [*] --> Bootstrap: Single-file HTML loads
    Bootstrap --> ConfigLoading: Fetch config.json
    ConfigLoading --> ThemeInitialization: Apply theme preset
    ThemeInitialization --> NavigationParsing: Fetch & parse navigation.md
    NavigationParsing --> RouteDispatch: Evaluate window.location.hash
    RouteDispatch --> MarkdownFetch: Fetch requested .md file
    MarkdownFetch --> PipelineExecution: Run beforeParse hooks
    PipelineExecution --> DOMPurifySanitization: Parse Markdown & sanitize HTML
    DOMPurifySanitization --> DOMMounting: Mount HTML to #verti-app
    DOMMounting --> PostRenderHooks: Run afterRender (Prism, KaTeX, Mermaid)
    PostRenderHooks --> Idle: Awaiting user interaction or navigation
    Idle --> RouteDispatch: Hashchange event fired
```

### 1. Engine Bootstrap
When `index.html` loads, the critical skeleton screen (`.verti-loading-shell`) displays instantly, matching the user's OS color scheme (`prefers-color-scheme`). This achieves a 0ms perceived First Contentful Paint (FCP) and prevents Cumulative Layout Shift (CLS).

### 2. Configuration & Theme Setup
The `loadConfig()` routine fetches `config.json`. If custom theme files (`themes/*.json`) are specified, they are fetched asynchronously. `ThemeManager` calculates CSS custom properties and updates `--verti-*` variables on `:root`.

### 3. Parallelized Manifest & Route Resolution
`Router` inspects `window.location.hash`. Concurrently, `Promise.all` downloads:
1. `navigation.md` (or the localized equivalent, e.g. `ro/navigation.md`).
2. The initial Markdown document (e.g. `index.md`).

### 4. Pipeline & Middleware Execution
The raw Markdown text enters the `Pipeline`:
- **`beforeParse`**: Plugins transform specialized markdown syntax (such as wikilinks `[[target]]`, container directives `::: tabs`, callout alerts `> [!NOTE]`).
- **Parsing**: `marked` compiles markdown into an HTML string.
- **Sanitization**: `DOMPurify` scrubs untrusted tags, scripts, and attributes while safely preserving SVG containers for Mermaid diagrams and MathML for KaTeX.
- **`afterParse`**: Plugins manipulate the sanitized HTML tree before injection.

### 5. DOM Mounting & View Hydration
The `LayoutManager` mounts the article into `.verti-article`. Table of contents (`TocManager`), breadcrumbs, and previous/next navigation cards are computed and rendered.

### 6. Post-Render Hydration
- `mermaid.run()` renders SVG diagrams in-place.
- `Prism.highlightAllUnder()` applies syntax highlighting.
- `renderMathInElement()` formats LaTeX equations.
- `SearchEngine` asynchronously indexes the document content.

---

## 💾 Memory Model & Client Cache

To ensure instantaneous transitions during interactive reading, VertiWiki maintains an in-memory LRU cache (`Map<string, string>`) in `src/main.ts`:
- Visited Markdown documents are cached in memory.
- Subfolder navigation trees are preserved.
- When a user navigates between previously visited pages, network requests are completely bypassed (0 ms latency).
- Pressing browser Back/Forward operates instantaneously.

---

## ⚖️ Architectural Invariants & Design Rationale

VertiWiki was engineered around strict architectural invariants designed to eliminate the operational overhead of traditional documentation platforms:

### 1. The Zero-Backend Invariant
No server-side runtime (Node.js, Python, PHP, Ruby) or database (PostgreSQL, MySQL, SQLite) is required in production:
- **Zero Server Infrastructure**: The application is deployed as purely static files (HTML, JS, CSS, and Markdown).
- **Reduced Attack Surface**: Eliminating server runtimes and databases eliminates SQL injection, remote code execution in application servers, and ongoing database patch management.
- **Trivial Disaster Recovery & Backups**: Documentation content lives as plain Markdown files versioned directly in Git; no database backups or restoration procedures exist.

### 2. The Zero-Build on Edit Invariant
Unlike traditional Static Site Generators (SSGs) like Docusaurus, VitePress, or Hugo, VertiWiki requires no compilation or static asset generation when documentation changes:
- **Immediate Authoring Loop**: Updating or creating documentation is strictly a matter of committing or editing `.md` files on the host. Refreshing the browser instantly displays the updated content.
- **Eliminating CI Build Bottlenecks**: As documentation repositories scale to hundreds or thousands of pages, SSG build times grow linearly or super-linearly. In VertiWiki, the build step is executed once when compiling the engine itself; content scales indefinitely without increasing deployment time.

### 3. Strict Client-Side Sanitization Invariant
Because markdown documents are parsed in the client browser, security is enforced via an uncompromising sanitization pipeline:
- **DOMPurify Sandbox**: All HTML generated from markdown passes through DOMPurify with strict attribute policies, neutralizing cross-site scripting (XSS) attacks from untrusted markdown or pull requests.
- **Selective Preservation**: Only safe graphical elements (such as SVG nodes generated for Mermaid diagrams and MathML for KaTeX formulas) are permitted through the sanitization barrier.

### 4. Universal Portability Invariant
The engine bundle is designed for complete deployment agnosticism:
- **Path Portability**: Functions identically when hosted at a root domain (`/`), nested inside a subfolder (`/docs/`), or served from static edge CDNs (Cloudflare Pages, Vercel, GitHub Pages, AWS S3).
- **Offline & Local Execution**: Fully functional offline through local static web servers (`npx serve`, Python `http.server`, or Caddy) without internet connectivity.

### 5. Architectural Trade-offs & Built-in Mitigations

| Concern | Architectural Trade-Off | Built-in Mitigation |
| :--- | :--- | :--- |
| **Search Engine Bot Crawling** | Client-side SPAs do not provide pre-rendered HTML out of the box. | VertiWiki dynamically generates a semantic `<nav class="verti-crawl-tree">` and provides edge server rewrite recipes for AI Content Negotiation (`Accept: text/markdown`). |
| **Initial Bundle Size** | Bundling parser engines (Mermaid, KaTeX, Prism, MiniSearch) into a single file produces an initial ~4 MB bundle. | Modern edge caching and browser HTTP caching download this bundle once; all subsequent document navigations are instant with 0 ms in-memory retrieval. |

---

## 🔗 Next Steps

- Trace the step-by-step request flow in [Execution Workflows](workflows.md).
- Inspect the core modules in [Core Architecture](core-architecture.md).
- Explore the component plugin ecosystem in [Plugins & Extensions](plugins-and-extensions.md).
