---
title: Core Engine Architecture
description: Deep dive into the core TypeScript modules powering VertiWiki: Router, Pipeline, MarkdownParser, and Config.
tags: [vertiwiki, core, router, parser, pipeline, config, typescript]
---

# Core Engine Architecture

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

The core subsystem of VertiWiki resides in `src/core/`. It contains zero UI rendering code, focusing strictly on URL normalization, resource loading, pipeline middleware execution, markdown parsing, and security sanitization.

---

## 🧭 1. The Router Subsystem (`src/core/router.ts`)

The Router manages all navigation interactions, hash parsing, path normalization, and multi-language routing.

```typescript
export interface RouteInfo {
  filePath: string;
  anchor: string;
  isMarkdown: boolean;
  locale?: LocaleConfig;
}
```

### Key Responsibilities:
1. **Deterministic Path Resolution**:
   - `normalizePath(path: string): string`: Cleans double slashes (`//`), removes relative prefixes (`./`), and resolves directory traversals (`../`).
   - `getBaseDirectory(): string`: Resolves whether the application runs from domain root (`/`) or a subfolder (`/docs/`), even when the user omitted the trailing slash.
   - `resolveResourceUrl(relativePath: string): string`: Guarantees that requests for `config.json` or Markdown files resolve against the true base directory.
2. **Locale Routing**:
   - Matches the first URL path segment against configured `locales` (`config.json`).
   - Dynamically routes to `ro/` or `fr/` when locale prefixes are present, while transparently serving the default locale when absent.
3. **Query Parameter Compatibility**:
   - Inspects `?page=`, `?p=`, and `?doc=` query parameters, redirecting them into modern path hash routes (`#/path.md`).

---

## ⚙️ 2. Configuration & Bootstrapping (`src/core/config.ts`)

Configuration is driven by `config.json`. The `loadConfig()` function loads, validates, and normalizes settings into a strongly-typed `VertiWikiConfig` object:

- **Theme Resolution**: Asynchronously loads external theme presets declared in `customThemes` (e.g. `themes/obsidian.json`).
- **Brand Settings**: Handles `brandDisplay` (`both`, `logo`, `title`), custom logo URLs, and favicon paths.
- **Defensive Defaults**: Falls back gracefully to sensible defaults if `config.json` is missing or malformed.

---

## 🔌 3. The Middleware Pipeline (`src/core/pipeline.ts`)

VertiWiki employs a three-stage middleware pipeline allowing plugins to hook into every phase of content processing:

```typescript
export interface VertiWikiPlugin {
  name: string;
  beforeParse?: BeforeParseHook;
  afterParse?: AfterParseHook;
  afterRender?: AfterRenderHook;
}
```

### Lifecycle Hooks:
1. **`beforeParse(markdown, context)`**: Operates on raw markdown text before `marked` executes. Used by Wikilinks (`[[target]]`), Callouts (`> [!NOTE]`), and Tab containers (`::: tabs`).
2. **`afterParse(html, context)`**: Operates on the sanitized HTML string produced by the parser before it is injected into the DOM.
3. **`afterRender(context)`**: Invoked after the HTML has been mounted into `#verti-app`. Used by runtime engines like Prism.js, Mermaid.js, KaTeX, and MiniSearch.

---

## 📝 4. Markdown Parser & DOMPurify Sanitizer (`src/core/parser.ts`)

The parser transforms Markdown into secure, interactive HTML:

### Frontmatter Extraction
`parseFrontmatter(markdown)` extracts YAML frontmatter delimited by `---` lines, isolating metadata properties:
```yaml
---
title: Page Title
description: Meta description
tags: [tag1, tag2]
---
```

### Auto-Closing Fences
`autoCloseFences(markdown)` defends against unclosed code fences (```` ``` ```` or `~~~`), preventing syntax highlighting and styling corruption across the page.

### Zero-XSS Security Sanitization
Before any HTML enters the DOM, it is passed through `DOMPurify.sanitize()` with an intentionally hardened configuration:
- Script execution is strictly blocked.
- SVG elements required by Mermaid (`<foreignObject>`, `<style>`, `<path>`) are permitted under strict sanitization.
- MathML elements required by KaTeX are preserved.

---

## 🌲 5. Static Bot Crawl Tree (`src/core/crawl-tree.ts`)

To solve the classic Single Page Application indexing penalty ("Discovered – currently not indexed" in Google Search Console), VertiWiki generates a semantic, hidden HTML navigation tree:

- Renders `<nav class="verti-crawl-tree">` containing standard `<a href="...">` anchor tags for every document in `navigation.md`.
- Crawlers immediately discover all wiki URLs without executing JavaScript.
- Avoids cloaking penalties by styling the element accessibly for screen readers and search bots.

---

## 🔗 Next Steps

- Explore the UI and design token layer in [UI & Theming Engine](ui-and-theming.md).
- Learn how plugins extend the engine in [Plugins & Extensions](plugins-and-extensions.md).
- Review the complete TypeScript signatures in the [API Catalog](../reference/api.md).
