# Core Architecture

# Core Architecture

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [.githooks/pre-commit](.githooks/pre-commit)
- [package.json](package.json)
- [scripts/version-sync.mjs](scripts/version-sync.mjs)
- [src/lib/api-types.ts](src/lib/api-types.ts)
- [src/lib/api.ts](src/lib/api.ts)
- [src/lib/app-connectivity-events.ts](src/lib/app-connectivity-events.ts)
- [src/lib/backend-availability.svelte.ts](src/lib/backend-availability.svelte.ts)
- [src/lib/components/AppShell.svelte](src/lib/components/AppShell.svelte)
- [src/lib/components/AppSidebar.svelte](src/lib/components/AppSidebar.svelte)
- [src/lib/components/toasts/EventToast.svelte](src/lib/components/toasts/EventToast.svelte)
- [src/lib/errors/app-errors.ts](src/lib/errors/app-errors.ts)
- [src/lib/errors/rfc7807.ts](src/lib/errors/rfc7807.ts)
- [src/lib/errors/toast.ts](src/lib/errors/toast.ts)
- [src/routes/login/+page.svelte](src/routes/login/+page.svelte)
- [vite.config.ts](vite.config.ts)

</details>



This page provides a high-level overview of the foundational layers that support the Primebrick frontend. The architecture is designed for resilience, featuring automated backend health monitoring, a robust RFC 7807-compliant error system, and a strictly versioned deployment pipeline.

### Architectural Overview

The application is built on SvelteKit and Svelte 5, utilizing a centralized communication and monitoring strategy. The diagram below illustrates the relationship between the core subsystems and the code entities that manage them.

**Core System Interaction**
```mermaid
graph TD
    subgraph "Client Layer"
        A["AppShell.svelte"] -- "mounts" --> B["probeHealth()"]
        A -- "listens" --> C["appErrors store"]
    end

    subgraph "Communication Layer"
        D["apiFetch"] -- "triggers" --> E["noteGatewayFailure()"]
        D -- "refreshes" --> F["triggerRefresh()"]
        D -- "reports" --> G["pushRFC7807Error()"]
    end

    subgraph "State Layer"
        H["backendState (rune)"]
        I["userProfileState (rune)"]
    end

    B --> H
    F --> I
    G --> C
    E --> H
```
Sources: [src/lib/components/AppShell.svelte:22-46](), [src/lib/api.ts:139-210](), [src/lib/backend-availability.svelte.ts:19-30]()

---

### [API Client & Authentication](#2.1)
The application uses a customized `apiFetch` wrapper around the native `fetch` API. It handles environment-specific URL rewriting for SSR, automatic token refresh via a concurrency-controlled `triggerRefresh` loop, and gateway failure attribution. Authentication is managed through SvelteKit Superforms in SPA mode, with session data persisted in `sessionStorage` and reactive access provided by `userProfileState`.

For details, see [API Client & Authentication](#2.1).

**Key Entities:**
*   `apiFetch`: The primary data fetching utility [src/lib/api.ts:139-160]().
*   `triggerRefresh`: Manages concurrent JWT refresh requests [src/lib/api.ts:99-106]().
*   `loginSchema`: Zod validation for authentication [src/routes/login/+page.svelte:34-37]().

Sources: [src/lib/api.ts:1-106](), [src/routes/login/+page.svelte:41-133]()

---

### [Backend Health Monitoring](#2.2)
A global `backendState` rune serves as the single source of truth for the connectivity status of the API, Database, and Identity Provider (IDP). The system performs periodic polling via `probeHealth()` and responds to immediate network failures detected during standard API calls via `noteGatewayFailure()`.

For details, see [Backend Health Monitoring](#2.2).

**Health States and UI Mapping**
| State | Condition | UI Chip Class |
| :--- | :--- | :--- |
| `backend_offline` | Network/Gateway Failure | `text-red-700` |
| `db_offline` | API up, Postgres down (503) | `text-red-700` |
| `idp_offline` | OIDC/Auth provider down | `text-orange-700` |
| `ok` | All systems nominal | `text-emerald-700` |

Sources: [src/lib/backend-availability.svelte.ts:11-30](), [src/lib/components/AppSidebar.svelte:144-166]()

---

### [Error Handling System](#2.3)
Errors are categorized by `ImpactLevel` (CRITICAL, HIGH, MEDIUM, LOW) and processed through a unified pipeline. The system supports the **RFC 7807 (Problem Details for HTTP APIs)** standard, allowing the backend to send rich error metadata (internal codes, instance IDs) that the frontend automatically maps to global error panels or `svelte-sonner` toasts.

For details, see [Error Handling System](#2.3).

**Error Pipeline Flow**
```mermaid
graph LR
    subgraph "Natural Language Space"
        Input["API Error Response"]
    end

    subgraph "Code Entity Space"
        Fetch["apiFetch"] --> Handle["handleRFC7807Error"]
        Handle --> Push["pushRFC7807Error()"]
        Push --> Store["appErrors (writable)"]
        Push --> Toast["showImpactToast()"]
    end
```
Sources: [src/lib/errors/app-errors.ts:7-35](), [src/lib/api.ts:122-137](), [src/lib/errors/toast.ts:65-75]()

---

### [Versioning & GitFlow](#2.4)
The project enforces a strict versioning pipeline tied to Git branch naming conventions. A `version-sync.mjs` script runs as a `prebuild` hook to ensure the `package.json` version matches the `release/` or `hotfix/` branch name. This ensures that the `APP_VERSION` displayed in the UI is always synchronized with the deployment metadata.

For details, see [Versioning & GitFlow](#2.4).

**Version Synchronization Logic:**
*   **Release Branches:** `release/0.X.0` increments the minor version [scripts/version-sync.mjs:49-49]().
*   **Hotfix Branches:** `hotfix/0.X.Y` increments the patch version [scripts/version-sync.mjs:50-50]().
*   **Validation:** The `.githooks/pre-commit` hook prevents commits if branch names do not follow the required semantic patterns.

Sources: [package.json:4-9](), [scripts/version-sync.mjs:69-91]()

---
