Pattern Library
Every pattern in v10r — 136 records across 20 categories, with its purpose in one line. 11 deep-tier patterns carry invariants and emulation notes on their pages; the rest are index cards pointing at docs, code, and proof.
Foundations
Architecture & Request Pipeline
- Multi-client core (hexagonal domain modules) deep
- One backend operations layer ($lib/server/[domain]/) serves four clients — human UI, AI tools, REST API, background jobs — via thin wrappers, with zero duplicated business logic.
- Runtime layers & request flow (7-layer view)
- Documents v10r's seven-layer abstraction hierarchy, from tech stack down to code, anchored by the hooks.server.ts composition root and the hexagonal domain core.
- Codebase map ("where does X live")
- Provides a spatial quick-reference table mapping each kind of code (business logic, route adapters, schemas, components, state) to its canonical directory.
- Middleware / 12-stage hook chain (CSRF, headers, guards)
- Describes the ordered SvelteKit hook chain in src/hooks.server.ts — security headers, i18n, auth, CSRF, session, consent, and guards — as the single source of truth for request interception.
- REST API patterns (pagination, envelopes, rate limits)
- Defines the file-based +server.ts convention for REST endpoints, covering Valibot validation, error() status codes, pagination, and response envelopes.
- Error handling (expected/unexpected/form/API)
- Classifies errors into expected, unexpected, form, and API categories, each handled by a distinct SvelteKit mechanism (error(), handleError, fail(), json()).
- State management (Svelte 5 runes)
- Establishes v10r's rune-based state strategy — $state/$derived for component state, .svelte.ts modules or the Context API for shared state, with an SSR-safety rule against module-level state leaking across requests.
- Request-cycle visualizer (form · API · AI)
- An interactive showcase that visualizes the full form, REST API, and AI request cycles as they pass through the hooks chain and domain layers.
- Deployment (Vercel primary, tri-target)
- Covers the tri-target deployment strategy — Vercel Node.js (stable), Vercel Bun (experimental), and Koyeb Bun container — sharing one codebase with per-target adapter configuration.
- Testing infrastructure (Vitest, PGlite isolation)
- Describes the Vitest + PGlite testing harness that runs entirely inside the dev container, giving each test an isolated in-process Postgres instance via drizzle-kit's pushSchema.
- Pattern MCP (agent-queryable pattern registry, local stdio)
- A read-only local stdio MCP server that exposes v10r's curated pattern registry (docs, code, tests, invariants) to coding agents so they can emulate patterns instead of grepping.
- Hosted MCP (two trust surfaces: public read-only · bearer admin)
- Serves the pattern registry and a separate demo-state service over HTTP through distinct trust boundaries — an unauthenticated public endpoint and bearer-token-protected private/admin endpoints.
App Shell & Navigation
- Shell layout (no global header, sidebar-first)
- Defines the app shell's structural layout — a collapsible sidebar for primary navigation, a main content area, and a persistent footer, with no global header.
- Responsive sidebar (rail / drawer / FAB)
- Implements an asymmetric responsive sidebar — a persistent hover-expanding rail on desktop and an off-canvas thumb-accessible drawer on mobile, triggered by a FAB.
- Navigation structure & progressive disclosure
- Structures nav items as compound split buttons — a primary click zone that navigates and a dropdown zone that progressively reveals subpages or section anchors.
- Keyboard shortcuts registry + help modal
- A central registry of global, navigation, and contextual keyboard shortcuts (e.g. Cmd+K for search, ? for help) surfaced through a discoverable help modal.
- Modals & layer stack
- Manages a stacked layer of modals and dialogs (quick search, shortcuts help, session expiry) through a shared state module and dialog primitives.
- Toasts (stacking, undo)
- Ephemeral, stacking feedback messages (success/error/warning/info) shown in response to user-initiated actions, distinct from the persistent notification center.
- Session lifecycle UI (expiry, re-auth)
- Shell-level UI that reacts to authentication session state — showing an expiry warning, a re-authentication modal on expiry, and immediate redirect on revocation.
- Settings (theme cookie, language, a11y)
- A settings hub page covering appearance (theme cookie), language, privacy toggles, and accessibility preferences, backed by a load/save form action.
- Style randomizer (theme × typography × palette)
- Randomizes decorative styling (typography pairing and color palette) on each visit from pre-validated, WCAG-compliant sets, kept orthogonal to the user's dark/light theme choice.
- Loading states (skeletons, nav progress)
- Defines visual feedback for initial load, navigation, data fetch, action, and streaming states using skeleton screens and a navigation progress bar.
- Empty states
- Standardizes the anatomy (icon, title, description, action) for UI shown when there is no data — first-run, zero search results, deleted content, or error recovery.
- Page header (per-page, XSS-safe)
- A per-page header component (breadcrumbs, title, actions) rendered inside the main content area instead of a global header, keeping page-specific chrome scoped and safe against XSS.
- Quick Search / command palette (two-lane FTS)
- A universal search combining an instant client-side lane with a debounced server-side full-text-search lane, surfaced via a Cmd+K command palette and a dedicated /search page.
UI Components & Design System
- Component-first UI system (primitives/composites/layout, CVA, tokens) deep
- A layered component system — Bits UI → primitives (styled atoms) → composites (business logic) → layout (structural wrappers) — styled entirely through CVA → UnoCSS → design-token CSS variables.
- Design philosophy & three-tier theming
- Five content-first, accessibility-driven design principles paired with a three-tier token system (primitives → semantic tokens → component usage) flowing from src/app.css through tokens.ts into UnoCSS.
- Design tokens (breakpoints, fluid type/space, z-index)
- Centralizes breakpoints, fluid typography/spacing clamp() scales, and z-index values in a single tokens.ts file consumed by the UnoCSS theme so no component hardcodes design values.
- Tonal (surface) elevation engine
- A pure, SSR-safe TypeScript engine that computes each surface's relative depth (parent level + 1) via Svelte context and stamps it as a data-elevation attribute, decoupled from z-index.
- Primitives (~40 Bits UI wrappers)
- Roughly 40 styled atomic components (Button, Input, Badge, Select, Table, etc.) that wrap Bits UI headless primitives with CVA variants and design tokens.
- Composites
- Higher-level components (Card, FormField, CommandPalette, Chatbot, Dock, etc.) composed from primitives that add business logic and feature behavior.
- Layout primitives (Stack, Cluster, Surface)
- Structural wrapper components (Stack, Cluster, Surface, PageContainer) that provide consistent spacing and layout without one-off CSS.
- Fluid responsive styling (UnoCSS, container queries)
- A UnoCSS-driven mobile-first strategy combining clamp()-based fluid typography/spacing, media-query breakpoints for page layout, and container queries for self-contained component responsiveness.
- Tables
- A styled table primitive built on the primitives layer for rendering tabular data consistently across the app.
- Menus (dropdown, context, menu bar)
- Dropdown menu, context menu, and menu bar composites built on Bits UI for triggerable and right-click action lists.
- Split panes (resizable · reorderable)
- Resizable and reorderable split-pane primitives and composites for dividing screen space into adjustable regions.
- Workbench / dock layout
- A binary split-tree dock layout (DockLayout) powering the /desk workspace with resizable panes, drag-and-drop tabs, and a panel-type registry.
- Typography
- Typography primitive components applying the design system's fluid type scale and heading/body/UI/code character rules.
- Decorative (ornaments · backgrounds)
- Decorative primitive components (ornaments, backgrounds) used by the style-randomization system to vary visual flourish without affecting core UI predictability.
Forms & Validation
- Superforms + Valibot foundation
- The default form stack pairing Superforms v2 with Valibot schemas for progressive-enhancement-friendly, type-safe form validation.
- Basic forms (contact · settings)
- Reference contact and settings forms demonstrating the standard Superforms + Valibot schema and server-action wiring for a single-step form.
- Validation timing (realtime · async · server)
- Demonstrates the three Superforms validation timing strategies: realtime (oninput), debounced async server checks, and onblur/server-only validation.
- Multi-step & dynamic (wizard · dynamic · dependent)
- Wizard (per-step schema validation), dynamic array fields, and dependent/cascading field patterns built on top of Superforms.
- Advanced (confirm · reset · edit)
- Confirmation-modal submit, reset-after-submit, and edit-with-existing-data patterns layered on top of the base Superforms flow.
- Auth forms (Better Auth client, not Superforms)
- Passwordless login (magic link + OTP) and OAuth forms built directly on the Better Auth client instead of Superforms, since Better Auth already handles rate limiting and token validation.
- File uploads (withFiles + Sharp + R2)
- Server-side file upload handling that processes images with Sharp and persists them to Cloudflare R2, validating file metadata via Valibot rather than the file bytes themselves in-schema.
Internationalization (i18n)
- Locale routing (optional catch-all, matcher, 308 canonical)
- URL-based locale routing using an optional [[locale=locale]] catch-all segment and a param matcher, with the unprefixed default locale (en) 308-redirected from /en/* to keep canonical URLs.
- Messages (Paraglide JS, ICU, compile-time)
- Compile-time translated messages via Paraglide JS v2 using ICU MessageFormat, authored as per-language JSON files that compile to typed functions.
- Formatting & CLDR plural correctness
- Locale-explicit date, number, currency, percent, and relative-time formatting helpers built on the native Intl API, decoupled from the translation locale to avoid SSR/CSR hydration mismatches.
- DB content i18n (JSONB sidecar + `tc()`)
- A source-column plus JSONB-sidecar convention (e.g. name / name_i18n) for translating short database fields, resolved at read time by the tc() helper with an explicit locale argument.
Docs & Agent Experience
- Docs navigation hubs (README-per-directory convention) deep
- An AI-optimized docs tree where every directory's README.md is a navigation hub with topic tables, so agents read index → target file, never everything.
- Pattern Index (the generated README capability map) deep
- A generated table in README.md mapping every repo pattern to the doc that explains it, the code that implements it, and the showcase page that proves it — rendered from this registry (136 rows, 20 categories, two tiers).
- Agent Experience (AX) surfaces deep
- Five derived surfaces make the repo consumable by coding agents: a root AGENTS.md contract, raw-markdown doc variants with Accept negotiation, an /llms.txt URL map with in-band prior corrections, MCP tool errors that carry machine-actionable recovery steps, and a generated pattern library (README index + per-pattern docs pages) rendered from the pattern registry.
Data
Databases & Storage
- Postgres client & connection (Neon serverless)
- Sets up the Drizzle client for PostgreSQL using the Neon serverless driver as the app's single database connection entrypoint.
- Schema & type inference (Drizzle, 14 namespaces)
- Drizzle table definitions split across 14 pgSchema() namespaces and re-exported from a single schema index for compile-time type inference.
- Queries/mutations split (reads-writes duality)
- Splits each domain's database access into separate queries.ts (reads) and mutations.ts (writes) modules.
- Neo4j connection (Aura)
- Connects to a managed Neo4j Aura database over its HTTP Query API via fetch, with no driver, session, or connection pool.
- Graph modeling
- Defines how entities and their relationships are represented as nodes and edges in the Neo4j graph.
- Graph traversal
- Runs Cypher traversal queries, such as shortest-path and multi-hop lookups, over the modeled graph.
- Polyglot freshness (Postgres ↔ Neo4j sync)
- Documents strategies for keeping references between Postgres and Neo4j valid, since no foreign keys exist across the two stores.
- Object storage (Cloudflare R2, presigned transfer)
- S3-compatible object storage on Cloudflare R2, accessed via @aws-sdk/client-s3 with presigned URLs for direct client uploads and downloads.
- Cache (Upstash Redis, ephemeral patterns)
- In-memory key-value store on Upstash Redis, reached over HTTP REST, used for rate limiting, the circuit breaker, and other ephemeral counters.
Database Operations
- Dev→prod schema workflow (push-only, no migrations dir)
- Uses drizzle-kit push for schema changes during development and defers versioned generate/migrate SQL files until production holds real data.
- Neon branch refresh from prod (control plane, run ledger)
- Resets the dev Neon Postgres branch from its production parent through Neon's control-plane API, recording each run in a ledger and surfacing it at an admin-only page.
- DB bootstrap & seed
- Scripts and seed modules that populate a fresh database with baseline and sample data.
Identity & Safety
Identity & Access
- Passwordless auth (magic link + OTP)
- Session-based authentication through Better Auth using a magic link and OTP code sent together in one email, with no passwords stored.
- OAuth (GitHub, Google)
- Sign-in via OAuth 2.0 providers, GitHub and Google, wired through Better Auth's built-in OAuth plugin.
- Route guards & per-route authorization
- Server-side guard functions that check a user's capability grants or admin status before allowing access to a route or API endpoint.
- Capability grants (request → approve → expire)
- A request-approve-expire workflow where users request a named capability, an admin approves or denies it, and pending requests auto-expire after 14 days.
- Passkeys & step-up TOTP
- WebAuthn passkeys serve as a phishing-resistant first-factor sign-in credential, while TOTP is repurposed as a step-up check before sensitive actions, gated by a Redis freshness stamp.
- User management
- User account routes and server-side data access covering profile, settings, notifications, security, and GDPR data export.
Anti-Abuse
- ALTCHA proof-of-work captcha
- A self-hosted proof-of-work captcha where the client solves a CPU-bound puzzle and the server verifies an HMAC-signed payload via altcha-lib.
- Honeypot (hidden field + min fill time)
- A no-interaction bot check combining a hidden form field bots tend to fill with a minimum elapsed-time threshold between render and submit.
- Rate limiting (sliding window, fail-closed)
- A sliding-window rate limiter factory backed by Upstash Redis that produces per-purpose limiters (email, IP, comments, grants) and fails closed when Redis is unavailable.
- AI daily token budget
- A per-user daily token cap stored in Redis that prevents a single authenticated user from exhausting AI quota through cost-amplification abuse.
- Bot decision & abuse audit
- A shared Decision type and audit trail that lets the anti-abuse layers (captcha, honeypot, rate limits) record and explain their bot/allow decisions consistently.
Admin & Privacy
- Admin area, guards & data-table pattern
- The overall admin area architecture — a vertical sidebar, route guards, and a canonical data-table pattern reused across admin pages.
- GDPR data transparency (view · export · delete)
- A privacy aggregator that collects everything the app knows about a user into one report, backing the view, export, and delete surfaces required by GDPR.
- Consent & cookies
- Client-side consent state and a consent banner component that gate any cookie or storage write, satisfying ePrivacy/TDDDG consent requirements.
- Data retention policy & purge jobs
- Scheduled jobs that enforce data-retention policy by purging stale records on a fixed cadence, using the shared backend jobs framework.
- Cross-device debug pairing (QR + HMAC cookie)
- A short-lived, single-use pairing code and QR flow that attributes a phone's anonymous pageviews to an admin's identity via an HMAC-signed cookie, without logging the phone in.
- Style picking + custom palettes
- A per-visitor palette, typography, and radius resolution system with a randomizer, manual picker, and optional saved custom palettes, deliberately without a site-wide brand lock.
- Audit log, announcements, feature flags
- Admin-side systems for recording an audit trail of privileged actions, publishing site announcements, and toggling feature flags, all under the admin server module.
- Feedback capture
- A user feedback capture form protected by the honeypot bot-detection pattern to keep submissions spam-free.
Intelligence
AI
- AI tool manifest & harness split (tool defs, risk metadata, registry) deep
- Tool definitions are thin wrappers whose risk-tier metadata and per-surface membership live in a registry, with harness concerns (agent loop, compaction, policy) factored out separately.
- AI surfaces (chatbot vs deskbot split over one guard) deep
- Two AI surfaces over one shared guard: a read-only, citation-faithful chatbot (Vely) vs an agentic, mutating, approval-gated deskbot — with a showcase-only rag-demo value kept out of production paths.
- Deskbot approval gate (proposal → approve, plan-gated mutation) deep
- Write/destructive desk tools never mutate inside the agent loop; they return a requiresApproval sentinel that becomes a proposal (PlanCard), executed only via an approve-route replay that records the real approver and time.
- Layered RAG (llmwiki pointer layer over a rawrag kernel) deep
- A shared rawrag retrieve() kernel (embed → tiers → RRF fusion → drill) feeds two layers: llmwiki TLDR pointer pages as the answer surface over immutable rawrag chunks as the audit trail.
- Retrieval ingest/search endpoints (one ingest door, /api/retrieval/*) deep
- The RAG corpus is fed and queried through /api/retrieval/* HTTP endpoints plus a unified ingest door: the app runtime and the Bun docs-ingest script share the same pure planChunks() core.
- Chat assistant "Vely" (orchestrator, streaming)
- The chat-orchestrator module streams multi-provider LLM responses through Vely, v10r's floating chat assistant, using Vercel AI SDK v6.
- Persistent minimizable chatbot session
- A client-side Svelte state machine keeps Vely's conversation alive across page navigation, minimizing the panel instead of closing it when the user follows a link.
- Provider registry & routing (chat/tools/vision + circuit breaker)
- Resolver functions pick an active chat, tool-calling, or vision LLM provider per turn and trip a Redis-backed circuit breaker on rate-limited providers.
- Chatbot site awareness (page context)
- Server-resolved page context is injected as a passive block into the chatbot's prompt so deictic questions like "how does this work?" resolve to the page the user is viewing.
- Graph RAG pipeline (three tiers, RRF fusion)
- Vector-similarity chunk retrieval is combined with Neo4j knowledge-graph traversal across three parallel tiers, fused by reciprocal rank fusion, for more explainable answers.
- Retrieval observability (waterfall, explorer)
- A waterfall/step-timeline view exposes the concurrent-tier timing, provenance paths, and token breakdown behind each nRAG retrieval turn.
- Image metadata reader (vision)
- A vision-capable LLM proposes title, caption, alt text, keywords, and category for an uploaded image, which a human reviews and approves before anything persists.
- Cost & usage monitoring
- Chat and image telemetry are merged into one admin table that derives a reference token cost at read time from a hand-maintained price table, without charging or faking a real bill.
- TOON token-efficient context format
- A compact, TOON-style serialization packs structured context data for LLM prompts more densely than JSON, currently implemented as a hand-rolled layout rather than the external @toon-format/toon library.
- Deskbot (AI in the desk workspace)
- An agentic AI surface embedded in the desk workspace calls desk-mutating tools, with writes routed through the harness's proposal-and-approval gate.
- Agent-harness audit lens (loop/context/policy/tools)
- A conceptual audit lens (not a module) names which slice — loop, context, policy, or tools — owns each agent-harness primitive such as compaction, step caps, and approval gating.
Toolkits
Features
Analytics
- Pageview collector hook (last of 12 middleware stages)
- A hooks.server.ts middleware stage that runs last in the 12-stage sequence and records public GET pageviews into separate anonymous and authenticated lanes only after auth and routing have resolved.
- Consent-gated sessions (cookieless day-rotating id)
- Session identification switches between a cookie-based id under the analytics consent tier and a cookieless hash(visitorId + UTC day) id under the necessary tier, so both tiers still produce a countable session.
- User journeys (client beacon)
- Page-to-page journeys are computed in Postgres with a LEAD() window function over consecutive pageviews in a session and shown as a ranked table rather than an aggregate flow diagram.
- Funnels
- Funnel conversion is computed as count(distinct session_id) per step in one grouped query, so a reload mid-funnel is deduped instead of double-counted.
- Live events feed
- An unauthenticated, self-limiting SSE stream at /api/analytics/stream pushes live event-style updates for the showcase demo, using synthetic rather than production data.
- Rollup & cleanup jobs
- Two scheduled jobs aggregate yesterday's events into a daily_page_stats table and enforce per-table retention windows (60-180 days) across the analytics tables.
- Visitor "my data" transparency
- An authenticated "Your data" page streams cookie state, live request metadata, and a full collectUserData report so a visitor can see what analytics has captured about them.
Notifications
- Router, outbox & delivery worker
- NotificationService.send() writes an in-app record, evaluates the settings matrix per channel, then queues outbox rows delivered by an in-process worker on containers or a cron sweep on Vercel.
- Channel providers (email · Telegram · Discord)
- Email (Resend), Telegram (bot API), and Discord (OAuth2) each implement a common provider interface (send/validateConnection/getProviderName) behind their own connection and token-management flow.
- In-app SSE stream & notification center
- A container-mode in-memory connection map pushes notifications over SSE in real time (falling back to invalidate()-based polling on Vercel serverless) and feeds a Svelte 5 runes notification-center state.
- Settings matrix (channel × type)
- The settings UI renders a channel-by-notification-type matrix backed by a form schema, letting a user toggle which channels receive which notification types.
- Schema & delivery log
- The multi-channel schema adds per-user channel-connection tables, verification tokens, and push subscriptions, plus a notification_deliveries table logging per-channel send status.
Jobs & Scheduling
- Jobs & scheduling (registry, runner, platform-owned cadence) deep
- A slug→execute job registry with a unified runner; cadence lives entirely in platform config (Vercel cron vs container setInterval), so switching hosts needs zero job-code change.
- Platform scheduling (Vercel cron vs container `setInterval`)
- Cadence is owned entirely by platform config — vercel.json crons hitting /api/cron/[job] on serverless, or a single flat setInterval scheduler on persistent containers — so the job registry itself never changes when switching hosts.
- Registered jobs (retention, cleanup, sync, delivery)
- The concrete job implementations — retention sweeps, cleanup, external sync, and delivery — are idempotent slug-keyed functions run by the shared runner and manageable from an admin UI.
PWA
- Localized manifest & installability
- The web manifest is served dynamically so name/description follow the Paraglide locale cookie, with maskable icons and an explicit cache header that pre-empts the hooks' no-store stamp.
- Service-worker caching contract (HTML network-only, kill switch)
- The custom service worker precaches the hashed build and icons, serves HTML and __data.json network-only while never intercepting /api/* or SSE, and ships a kill switch that force-wipes caches and unregisters on a bad deploy.
- Update flow (silent + idle toast, no auto skipWaiting)
- A pending service-worker update rides the next client-side navigation silently, or for navigation-less sessions surfaces one persistent reload toast after 30 minutes, and never auto-activates with skipWaiting().
- Web push channel (declarative JSON, no PII)
- Web push uses one Declarative Web Push JSON payload carrying no PII (brand title, generic body, same-origin navigate path) so real content only loads after tap-through session auth, delivered synchronously and bypassing the outbox.
Data Viz
- Charts
- Chart.js wrapper components for standard statistical charts (bar, line, area, pie, radar, bubble, scatter) with SSR-safe canvas lifecycle handling.
- Plots
- Chart.js scatter plots and a canvas-based heatmap component for visualizing continuous or correlated data.
- Diagrams
- @xyflow/svelte-based flow and state diagram components with custom node types for interactive node-edge visualizations.
- Node graphs
- D3-powered network, tree, DAG, Sankey, and knowledge-graph layout components, rendered as SVG by Svelte while D3 only computes positions.
- Maps
- MapLibre GL components for a base map, markers, and GeoJSON choropleth overlays, using free CartoDB tiles.
- Timelines
- Timeline visualization components for displaying a sequence of dated events.
3D
- Threlte integration (SSR-off, code-split model registry)
- Threlte 8 is wired into SvelteKit with SSR and prerendering disabled for the 3D route subtree, plus a static model config registry driving camera, lights, and controls.
- Static & animated scenes
- A shared scene component that renders either a static GLTF model with orbit controls or one with animation clips playing via an AnimationMixer.
- Full-screen model viewer & customizer (layout reset)
- A full-screen model viewer and GLTF customizer (materials, parts, morph targets, presets) that resets the app layout while open.
Content, Blog & Desk
- Blog engine (posts, revisions, locale-aware publishing)
- A DB-backed blog system with posts, immutable revisions, and locale-aware publishing supporting multiple authors.
- Comments (flat, per-locale, moderated)
- A flat, per-locale comment system with a short author edit window and admin moderation (hide/unhide/remove).
- Markdown pipeline & custom syntax (directives, wikilinks)
- A remark/rehype-based markdown rendering pipeline extended with custom directive syntax for embeds; wikilink cross-references are designed for but not yet implemented.
- Desk workspace (panels, DeskBus, file registry)
- A full-page DockLayout workspace with resizable panel panes, drag-and-drop tabs, a panel-type registry, and a typed pub/sub DeskBus for cross-panel communication.
- Spreadsheet panel (file type, dual-mode)
- A spreadsheet file type managed through the desk's unified file registry, editable in a dual-mode (grid/panel) UI.
- Markdown editor (CodeMirror, slash commands)
- A CodeMirror-based source markdown editor with a slash-command palette that auto-inserts custom syntax.
- Prerendered docs site
- A prerendered documentation site where each page both explains and demonstrates the feature it documents.
Geht dieses Pattern noch besser? Sag uns, wie.
Feedback geben