Every application feature is a module: a self-contained, self-registering unit in /modules/.

This overview covers the architecture, modules, settings, caching and security. Step-by-step guides are listed under Admin > Documentation (files in docs/).

Key Features & Highlights

  • Bun Runtime Speed: Ultra-fast startup times, native TypeScript execution, and minimal memory footprint.
  • Hono Router: Lightweight, expressive, type-safe HTTP routing.
  • Turso / libSQL Database: Zero-configuration local SQLite (file:local.db) or globally distributed database on Turso Cloud via .env.
  • Modular Architecture (/modules/): Drop in self-contained folders with their own HTML templates, CSS/JS, database schemas, API routes, and admin views. Modules are auto-discovered from modules/*/init.ts at boot. A module's css/, js/, images/ and fonts/ folders are served at /modules/<id>/css/..., /js/..., /images/... and /fonts/... (images: png, jpg, gif, svg, webp, ico; e.g. the admin logo, /modules/admin/images/img-tent-120x120.png; fonts: woff2, woff, ttf, otf; e.g. the brand font, /modules/admin/fonts/Fiesta.ttf). Other files in those folders (such as a font's licence text) are not served.
  • Vanilla HTML Templates: No client-side JSX hydration penalty. Clean HTML templates with variable slots ({{ variable }}) and theme inheritance.
  • Theme Engine (/themes/): Built-in themes are auto-discovered from /themes/ (in git), uploaded ones from uploaded-themes/ (on the persistent disk, not in git); all are listed in Admin > Themes (add a theme as a ZIP, upload new versions, enable or disable, duplicate any theme, download it as a ZIP; administrators also edit an uploaded theme's files in a code editor with version history, and preview any theme privately on the public site). Enabled themes are offered in the Admin > Sites theme dropdown; switch a site's theme without editing code.
  • Page & API Cache (/cache/): Disk-backed page caching for anonymous visitors with TTL, tag-based invalidation, opt-in API caching, and admin cache management.
  • Structured Logging (/logs/): Errors-only by default (LOG_LEVEL=ERROR): server errors (5xx) and SECURITY events such as failed logins and CSRF rejections. Set LOG_LEVEL to WARN, INFO or DEBUG for more detail. Includes an admin log viewer.
  • Security by Default: Random server-side session tokens, CSRF protection on every state-changing request, a core-enforced admin guard, rate limiting, and standard security response headers.
  • Collections (no code): design content types in the admin (fields, order, public pages), add items with optional details rows (master-detail), and show them at /c/<collection> or embed them in any page. See Collections.
  • Admin bar on the site: signed-in staff (administrators, managers, editors) see a slim dark bar above every public page: Dashboard; Edit page (a page from Admin > Pages), Edit product, Edit item (a collection item) or Edit products / Edit items (the lists), each opening that thing in its editor (?edit=<id>), shown only when the role may edit it; their initials and name; Hide (for this browser session: cookie admin_bar=hidden; the admin header then offers Show site bar); Sign out. Theme pages such as the home page show Dashboard only. It is part of the page, not fixed, so it never covers a theme's own fixed or sticky header. Never for visitors or site users (staff are never served cached pages), on error pages or in static exports.
  • Maintenance Mode: Built-in core module, switched on the active site's row in Admin > Sites (the Maintenance column, shown while the module is enabled) or in Settings > Maintenance. When enabled, visitors see the active theme's maintenance.html page while signed-in staff keep seeing the site; the admin header shows a red Maintenance ON reminder (for administrators a link to Sites). It is one switch for the install, applied to the active site, and only while the module is enabled.
  • License key (src/core/license.ts): the commercial license key from Settings > License or LICENSE_KEY, verified offline with a built-in Ed25519 public key (no license server, nothing fetched). Without a valid key for the host of APP_URL staff see a red notice in the admin header (next to Maintenance ON) and an item under Needs attention; nothing is switched off and the public site and static export never show it. localhost counts as development. Modules can mark themselves premium: true; enabled ones the key does not include are listed. See Licensing.
  • Server Health: an optional module (administrators) with live readings of the server and graphs: memory (and the container's limit on Render or Docker), CPU, requests, errors, response times, database delay, event-loop delay, disk space and folder sizes. See Server Health.
  • Tested and typed: a bun test suite (430+ tests against a separate test.db), TypeScript in strict mode with no any in the app code, and ESLint for browser scripts.

Directory Structure

my-app/
├── .env.example             # Environment variables template
├── .gitignore               # Git ignore rules
├── tsconfig.json            # TypeScript configuration (Bun)
├── package.json             # Project scripts & dependencies
├── server.ts                # App entry point (Bun.serve)
├── cli.ts                   # CLI tool for cache, users, settings, health, db:backup, setup
├── render.yaml              # Render Blueprint (see Deploy on Render)
├── local.db                 # Local SQLite database (auto-created)
├── backups/                 # bun run cli db:backup copies (next to the database)
│
├── src/
│   ├── core/
│   │   ├── app.ts           # Application factory & middleware pipeline
│   │   ├── config.ts        # Environment loader (loads .env via dotenv)
│   │   ├── db.ts            # Turso / libSQL client & query helpers
│   │   ├── auth.ts          # Password hashing & cookie sessions
│   │   ├── cache.ts         # Disk-backed cache engine w/ tag invalidation
│   │   ├── logger.ts        # Structured file logging & log rotation
│   │   ├── renderer.ts      # HTML layout & template engine ({{ }}, {{#if}}, {{#each}}…)
│   │   ├── security.ts      # CSRF, rate-limiting, CORS, and headers
│   │   ├── permissions.ts   # Roles, permission matrix, admin gate, can()
│   │   ├── audit.ts         # audit(): who did what (Admin > Audit Log)
│   │   ├── alerts.ts        # Error alerts by email
│   │   ├── lifecycle.ts     # Restart server (Admin > Modules), running tasks, code changed since the start
│   │   ├── request-timing.ts # onRequestTimed(): every request's time and status, for Server Health
│   │   ├── docs-menu.ts     # The Documentation menu: Overview, Developer's Guide, Designer's Guide
│   │   ├── sites.ts         # Sites (cached active site), site folders
│   │   ├── themes.ts        # Theme resolution, theme records (Admin > Themes)
│   │   ├── usage.ts         # "Used in": theme templates and pages that embed something
│   │   ├── static-export.ts # A site as plain HTML/CSS/JS in a ZIP
│   │   ├── site-starter.ts  # The commented init.ts of a new site
│   │   ├── zip.ts           # Safe ZIP extraction (theme and widget uploads)
│   │   ├── dates.ts         # Date formatting (Settings > General)
│   │   ├── mime.ts          # Shared MIME type map
│   │   ├── i18n.ts          # Lightweight i18n with locale JSON files
│   │   ├── request-limits.ts # Request timeout and body size limit middleware
│   │   └── types.ts         # Module and system TypeScript interfaces
│
├── modules/                 # Extensible self-contained modules
│   ├── registry.ts          # Central module registry & state loader
│   ├── site/                # Site manager + one folder per site
│   │   ├── init.ts          # site-manager module: sites admin, contact form
│   │   └── starter/
│   │       └── init.ts      # optional custom code for the starter site (comments only)
│   ├── admin/               # Control panel (Dashboard, Modules, Logs, Cache, Settings)
│   │   ├── init.ts
│   │   ├── css/             # Admin-only styles, theme-independent
│   │   ├── js/              # Admin-only scripts
│   │   └── templates/
│   ├── themes/              # Admin > Themes: add (ZIP), new version, status, duplicate, download, preview
│   │   ├── init.ts
│   │   ├── editor.ts        # File editor of uploaded themes: paths, checks, version history
│   │   ├── js/
│   │   └── templates/
│   ├── users/               # Auth (site and admin sign-in), registration, profiles, user CRUD
│   │   ├── init.ts
│   │   └── templates/
│   ├── products/            # Sample catalog/e-commerce module with CRUD (images from the Media Manager)
│   │   ├── init.ts
│   │   └── templates/
│   ├── collections/         # Content types designed in the admin (fields, items, details rows)
│   │   ├── init.ts          # Routes (/c/...), admin API, embed code
│   │   ├── fields.ts        # Field types, checks, template values
│   │   ├── store.ts         # Queries
│   │   ├── js/              # designer.js, items.js (admin screens)
│   │   └── templates/       # Admin pages + built-in list/details/embed templates
│   ├── pages/               # Content pages with WYSIWYG editor, SEO, nav integration
│   │   ├── init.ts
│   │   ├── js/
│   │   │   └── pages.js     # TabulatorJS grid + modal handlers + rich-text editor
│   │   └── templates/
│   ├── media/               # Media manager — upload, browse, and manage files
│   │   ├── init.ts
│   │   ├── css/
│   │   ├── js/
│   │   └── templates/
│   ├── email/               # Email service — SMTP settings, test sender, provider registry
│   │   ├── init.ts
│   │   └── templates/
│   ├── maintenance/         # Core maintenance mode toggle + public maintenance page
│   │   ├── init.ts
│   │   └── templates/
│   ├── server-health/       # Server Health: live memory, CPU, response times, disk, with graphs
│   │   ├── init.ts
│   │   ├── metrics.ts       # samples every 5 s, one saved row per minute
│   │   ├── css/ js/
│   │   └── templates/
│   ├── stats/               # Statistics & analytics — page views, visitors, charts
│   │   ├── init.ts
│   │   └── templates/
│   └── widgets/             # Widgets admin module
│       ├── init.ts
│       ├── js/
│       │   └── widgets.js  # TabulatorJS grid + modal handlers
│       └── templates/
│
├── widgets/                 # Widget type definitions (auto-discovered)
│   ├── card/                # Built-in card widget
│   │   ├── index.html
│   │   ├── style.css
│   │   └── script.js
│   ├── image/               # Built-in image widget
│   │   ├── index.html
│   │   ├── style.css
│   │   └── script.js
│   ├── html/                # Raw HTML embed widget
│   │   ├── index.html
│   │   ├── style.css
│   │   └── script.js
│   ├── embed/               # URL-based embed widget with auto-detection
│   │   ├── index.html
│   │   ├── style.css
│   │   └── script.js
│   ├── rich-html/           # HTML written in a WYSIWYG editor (CKEditor 5)
│   │   ├── index.html
│   │   ├── schema.json
│   │   └── style.css
│   └── contact-form/        # Ready contact form (posts to the site-manager contact endpoint)
│
├── locales/                 # i18n translation files
│   └── en.json              # Default English translations
│
├── uploaded-themes/         # Themes added in Admin > Themes (not in git; .history/ = file versions)
├── themes/                  # All site HTML: one folder per built-in theme
│   ├── starter/             # Neutral starter: the fallback theme and a fresh install's theme
│   │   ├── layout.html      # header (site title, menu), footer, <!-- @content -->
│   │   ├── home.html        # hero + the pages shown as home page sections
│   │   ├── 404.html 500.html maintenance.html
│   │   ├── css/
│   │   └── js/
│   ├── dark-slate/          # The starter theme in dark colours (layout, home, CSS; other pages from starter)
│   ├── one-page/            # One-page site: hero + numbered home sections from Pages
│   ├── hero/                # Hero layout: banner picture, intro card, cards or sections; navy header and footer
│   └── c3/                  # Sections layout, the Carnival CMS look: orange header (Fiesta logo), hero, feature bands
│
├── docs/                    # Documentation pages and guides
│   ├── overview.html        # This overview (Admin > Documentation > Overview)
│   ├── deployment.html      # Deployment guide (Bun + PM2/systemd + reverse proxy)
│   ├── deploy-render.html   # Deploy on Render (persistent disk, local SQLite)
│   ├── deploy-as-zip.html   # Deploy as a ZIP: static export, static hosts, XAMPP
│   ├── how-to-create-a-site.html
│   ├── how-to-create-a-theme.html  # Designer guide: themes without programming
│   ├── how-to-create-a-module.html
│   ├── helper-registry-pattern.html
│   ├── roles-and-permissions.html
│   ├── how-to-create-a-widget.html
│   └── how-to-create-a-collection.html
│
├── uploads/                 # Media: shared files, plus uploads/<site>/ per site
│   └── thumbs/              # Generated WebP sizes: thumb_* (320px square), w640_* (listing)
│
├── cache/                   # Cached HTML pages and API responses
├── logs/                    # Application and security logs (logs/test/ for the test suite)
├── tests/                   # bun test: tests/api, tests/core, tests/modules, tests/helpers
└── scripts/
    ├── setup.ts             # Initial database & admin user seeder
    ├── make-module.ts       # Module generator (bun run make:module)
    ├── make-site.ts         # Site generator (bun run make:site)
    └── render-start.sh      # Render start script (uploads/, uploaded-themes/ and logs/ on the disk)

Quick Start

1. Installation

# Clone or create from template
bun create <your-repo> my-new-app
cd my-new-app

# Install dependencies
bun install

2. Environment Configuration

Copy .env.example to .env:

cp .env.example .env

Default development values in .env:

PORT=3000
APP_SECRET=your-secret-key-here
TURSO_DATABASE_URL="file:local.db"
TURSO_AUTH_TOKEN=""
SITE_THEME=starter
CACHE_ENABLED=true
CACHE_DEFAULT_TTL=3600
LOG_LEVEL=ERROR
APP_URL="https://carnivalcms.com"
APP_ENV=production
CLIENT_IP_HEADER=            # e.g. True-Client-IP on Render (see Deployment)

3. Run Setup & Start Development Server

# Initialize database tables and seed default admin account
bun run setup

# Start the dev server (restarts when a loaded file changes)
bun run dev

Visit http://localhost:3000 in your browser; the admin is at https://carnivalcms.com/admin/login.

Default Admin Credentials

  • Email: test@c3.com
  • Password: 123456
  • Admin URL: https://carnivalcms.com/admin (sign in at /admin/login)

Change this password after the first sign-in (My Profile in the admin's top bar). The sign-in pages never show these credentials.

Creating a New Module

Modules are the primary way to add functionality. To scaffold a new module:

bun run make:module blog

This creates:

  • modules/blog/init.ts
  • modules/blog/templates/blog-public.html
  • modules/blog/templates/blog-admin.html

Module Anatomy (modules/<name>/init.ts):

import type { AppModule } from '../../src/core/types.js';

export const blogModule: AppModule = {
  id: 'blog',
  name: 'Blog Module',
  version: '1.0.0',
  description: 'Articles and news management.',
  isCore: false,

  // Database schema automatically executed on boot
  schema: `
    CREATE TABLE IF NOT EXISTS articles (
      id TEXT PRIMARY KEY,
      title TEXT NOT NULL,
      content TEXT,
      created_at INTEGER NOT NULL
    );
  `,

  // Seed data
  onSeed: async (db) => {
    // optional seed logic
  },

  // Public frontend routes + nav
  site: {
    nav: [
      { label: 'Blog', path: '/blog', order: 10 }
    ],
    routes: [
      {
        path: '/blog',
        template: 'modules/blog/templates/blog-public.html',
        cacheTtl: 60,
        cacheTags: ['blog'],
      }
    ]
  },

  // Admin panel integration
  admin: {
    navItem: {
      id: 'blog',
      label: 'Blog Posts',
      path: '/admin/blog',
      icon: 'file-text',
      order: 40,
    },
    views: [
      {
        path: '/blog',
        title: 'Blog Management',
        template: 'modules/blog/templates/blog-admin.html',
      }
    ],
    settingsFields: [
      { key: 'articles_per_page', label: 'Posts Per Page', type: 'number', defaultValue: 10 }
    ]
  },

  // Optional template data injection
  extendBaseData: async (data, c) => {
    return { blogEnabled: true };
  },

  // Optional public API routes: /api/v1/blog/*
  apiRoutes: (() => {
    const api = new Hono();
    api.get('/posts', async (c) => c.json({ posts: [] }));
    return api;
  })(),

  // Optional admin API routes: /api/v1/blog/admin/*
  // The core's admin gate checks the role's permissions, so no auth checks are needed here.
  adminApiRoutes: (() => {
    const adminApi = new Hono();
    adminApi.post('/save', async (c) => c.json({ success: true }));
    return adminApi;
  })(),
};

Admin API convention. Admin endpoints go in adminApiRoutes and are mounted at /api/v1/<moduleId>/admin/*. The core's admin gate checks that prefix (and every /admin/* page) against the user's role and permissions (see Roles & Permissions), so handlers never check roles themselves. Public endpoints go in apiRoutes at /api/v1/<moduleId>/*. When a module is disabled, both its API and its admin views return 404.

Widgets Module

The Widgets module provides a flexible system for creating and managing reusable UI components that can be embedded anywhere in site pages using helper syntax. Each widget instance combines a type (the component definition) with instance-specific data.

Features

  • Widget Types: Define reusable component templates with their own HTML, CSS, and JS files. Types are stored as folders in widgets/.
  • Auto-Discovery: Widget types are automatically discovered by scanning the widgets/ directory. Each subfolder with an index.html is an available widget type.
  • Instance Management: Create multiple instances of a widget type, each with its own data (title, description, image, link, etc.).
  • Helper Embedding: Embed widgets in theme pages, the theme layout or page content (Admin > Pages) with {{ widgets:render type="..." instance_name="..." }} or the short form [[type, name]].
  • Admin Interface: Full CRUD for widget instances at /admin/widgets using TabulatorJS grid with modal dialogs for add/edit.
  • Zip Upload: Upload widget types as ZIP files containing index.html, style.css, and script.js.
  • Isolated Styles/Scripts: Each widget type's CSS and JS are scoped and only loaded on pages where the widget is used.
  • Visibility Toggle: Show or hide individual widget instances directly from the admin grid or the add/edit modal. Hidden widgets do not render on the site.
  • Used in: the grid shows, as badges, the theme templates and pages that embed each instance; hiding or deleting one that is used asks first (see Used in below for how places are found).

Built-in Widget Types

TypeFolderDescriptionSchema Fields
Cardwidgets/card/Responsive card with image, title, description, and linktitle, description, image, link, link_text
Imagewidgets/image/Image with optional caption and linkimage, alt_text, caption, link
HTMLwidgets/html/Raw HTML content block (trusted admin input)html (textarea)
Rich HTMLwidgets/rich-html/Like HTML, but written in a WYSIWYG editor (CKEditor 5) with Media Manager integrationhtml (richtext)
Embedwidgets/embed/Auto-detecting URL embed for YouTube, Vimeo, Maps, social, and moreurl
Contact formwidgets/contact-form/Name / email / message form posting to the contact endpoint (the active site's contact email)heading, intro, button_text

Database Schema

CREATE TABLE widgets (
  id TEXT PRIMARY KEY,
  type TEXT NOT NULL,           -- 'card', 'image', 'html', 'embed', etc.
  name TEXT NOT NULL,           -- instance name, unique per type
  params TEXT NOT NULL DEFAULT '{}', -- JSON: type-specific fields (never is_visible)
  is_visible INTEGER NOT NULL DEFAULT 1, -- 1 = shown, 0 = hidden
  added_by TEXT NOT NULL,       -- user_id who created this instance
  date_added INTEGER NOT NULL,  -- Unix timestamp
  date_updated INTEGER NOT NULL,-- Unix timestamp
  updated_by TEXT,              -- user_id who last updated this instance
  UNIQUE(type, name)
);

API Routes

  • All widget endpoints are admin-only.
  • GET /api/v1/widgets/admin/types — List available widget types (auto-discovered from filesystem)
  • GET /api/v1/widgets/admin/list — List all widget instances, each with usedIn (the places that embed it)
  • GET /api/v1/widgets/admin/:id — Get single widget instance
  • POST /api/v1/widgets/admin/save — Create or update widget instance
  • POST /api/v1/widgets/admin/delete — Delete widget instance
  • POST /api/v1/widgets/admin/toggle-visibility — Toggle widget visibility (show/hide)
  • POST /api/v1/widgets/admin/upload-type — Upload widget type ZIP
  • POST /api/v1/widgets/admin/delete-type — Delete widget type (if no instances exist)

Helper Syntax

Embed a widget instance in any template:

{{ widgets:render type="card" instance_name="home-hero" }}

Or the short form:

[[card, product-card]]

Both forms can override fields for one placement (quote values containing spaces or commas):

{{ widgets:render type="card" instance_name="product-card" title="New Product" }}
[[card, product-card, title="New Product, limited", link_text=Shop now]]

See docs/how-to-create-a-widget.html.

HTML Widget — Raw Output

The HTML widget supports a raw modifier to bypass HTML escaping:

<div class="html-widget">
  {{ html | raw }}
</div>

Use this only for trusted admin input. The raw modifier is only available inside widget templates, not in site page templates.

Embed Widget — Supported Sources

The Embed widget auto-detects the source from the pasted URL and generates the proper embed code:

  • YouTube: youtube.com/watch?v=..., youtu.be/..., youtube.com/shorts/..., youtube.com/live/..., m.youtube.com/watch?v=...
  • Vimeo: vimeo.com/VIDEO_ID, vimeo.com/channels/.../VIDEO_ID, vimeo.com/groups/.../videos/VIDEO_ID
  • Google Maps: maps.google.com/maps?..., www.google.com/maps/..., @lat,lng short URLs
  • Twitter / X: twitter.com/user/status/ID, x.com/user/status/ID
  • Instagram: instagram.com/p/..., instagram.com/reel/..., instagram.com/tv/...
  • SoundCloud: soundcloud.com/user/track
  • Spotify: open.spotify.com/track/..., spotify.com/album/..., spotify.com/playlist/..., spotify.com/artist/...
  • SlideShare: slideshare.net/user/presentation
  • CodePen: codepen.io/user/pen/HASH, with /full/ and /details/ variations
  • GitHub Gist: gist.github.com/user/GIST_ID
  • TikTok: tiktok.com/@user/video/ID, vm.tiktok.com/shortcode
  • Facebook: facebook.com/user/posts/ID, facebook.com/user/videos/ID, fb.watch/ID
  • Generic iframe fallback: Any unmatched URL shows a fallback link instead of attempting to frame the page.

External embed scripts (Twitter, Instagram, TikTok, Gist) are deduplicated so multiple widgets of the same type only load the SDK once.

Widget Type Structure

Each widget type lives in widgets/<type-name>/ with optional files:

widgets/
├── card/
│   ├── index.html    # Required: widget HTML template
│   ├── style.css     # Optional: scoped CSS
│   └── script.js     # Optional: vanilla JS (runs on DOMContentLoaded)
├── image/
│   ├── index.html
│   ├── style.css
│   └── script.js
├── html/
│   ├── index.html
│   ├── style.css
│   └── script.js
└── embed/
    ├── index.html
    ├── style.css
    └── script.js

Used in

The Used in columns of Admin > Widgets and Admin > Collections show where each widget or collection is embedded, as badges (pages blue, drafts yellow, theme templates gray). One scanner, scanUsage() in src/core/usage.ts, reads every theme's .html templates and the content of all pages; each module tells it what to look for (findWidgetCodes() for widgets, findModuleShortcodes(html, 'collections', 'render') for collections; both skip code blocks, as the renderer does). Hiding or deleting a used widget, or deleting a used collection, asks for confirmation first. Templates are read through the template cache, so a scan costs one file check per template.

Widget Type Zip Upload

Upload a zip file containing the type files via Admin > Widgets > Upload Type. The zip must contain at least index.html. CSS and JS files are optional. Types are extracted to widgets/ and become immediately available for new instances.

Data Access in Templates

Widget templates receive the merged data object (instance data + helper overrides) and can use standard template syntax:

<div class="card">
  <h3>{{ title }}</h3>
  <p>{{ description }}</p>
  <a href="{{ link }}">{{ link_text }}</a>
</div>

Note: The widget template file must be named index.html (not template.html).

JavaScript Lifecycle

Widget script.js files run on DOMContentLoaded and can access their container element:

// script.js
document.addEventListener('DOMContentLoaded', () => {
  const cards = document.querySelectorAll('.card');
  cards.forEach(card => {
    // Initialize card behavior
  });
});

Built-in Card Widget

The CMF includes a built-in Card widget at widgets/card/:

widgets/card/
├── index.html   # Responsive card with image, title, description, link
├── style.css    # Full-width white card with hover effects
└── script.js    # Link click handling

The Card widget params: title, description, image, link, link_text. It is fully responsive and fills 100% of its container.

Built-in Image Widget

The CMF includes an Image widget at widgets/image/:

widgets/image/
├── index.html   # Responsive figure with image, caption, and optional link
├── style.css    # Scoped image styles
└── script.js    # Optional behavior

The Image widget params: image, alt_text, caption, link.

Built-in HTML Widget

The CMF includes an HTML widget at widgets/html/ for raw HTML content:

widgets/html/
├── index.html   # Outputs {{ html | raw }} inside a scoped container
├── style.css    # Basic container styles
└── script.js    # Optional behavior

The HTML widget param: html (textarea). Content is rendered as raw HTML using the raw modifier. Only admins can edit this widget, so the input is trusted.

Built-in Rich HTML Widget

The Rich HTML widget at widgets/rich-html/ works like the HTML widget, but its html param is a richtext schema field: the admin form shows the shared content editor (see The content editor: text formatting, lists, links, images with text wrapping that you can resize and move by dragging, video, tables, source view).

  • Media Manager: the Media toolbar button lists the Media Manager's images, videos and audio and inserts the chosen file at the cursor (images as <img>, videos and audio as players). The browse button in the image, video and link dialogs also opens the Media Manager picker (shared files plus the active site's). Images dropped or pasted into the editor are uploaded to the Media Manager (shared folder; needs media.create).
  • URLs are kept root-relative (/uploads/photo.png), so the content works on any page.
  • CKEditor 5 is an npm dependency served from node_modules at /vendor/ckeditor5/ (only its .js and .css files) and loaded only when a richtext field is opened. It is used under its open-source GPL v2+ licence (licenseKey: 'GPL').
  • style.css keeps images, videos and tables inside the widget's width; fonts and colours come from the theme.

Use it in a page or theme like any widget: [[rich-html, promo]]. Only admins can edit widgets, so the HTML is trusted and output unescaped.

Built-in Embed Widget

The CMF includes an Embed widget at widgets/embed/ for auto-detecting embeds from URLs:

widgets/embed/
├── index.html   # Container with data-url attribute and fallback link
├── style.css    # Responsive embed wrapper styles
└── script.js    # Source detection and embed generation

The Embed widget param: url (text). Paste a URL from any supported source and the widget generates the proper iframe/embed HTML automatically. Unknown URLs show a fallback link instead of breaking the page.

Collections Module

Collections (modules/collections/, optional) are content types designed in the admin without code: testimonials, team, FAQ, events with sessions, products with variants. Guide: docs/how-to-create-a-collection.html (a Testimonials walkthrough).

  • Designer (Admin > Collections, administrators): name, slug (pages at /c/<slug>), public pages on/off, title field, order, page size, and up to 50 fields of 14 types: text, text area, rich text, HTML, number, price, rating, date, yes/no, select, image, file, link, relation. Values are stored as JSON, so adding a field never changes the database; keys never change once saved.
  • Master-detail: a collection marked "Details of" another holds child rows edited in a table inside each item (Products → Variants); the item and its rows are saved together. One level.
  • Items (Admin > Collections > name): grid + full-window form built from the fields; drafts and publishing follow the collections permissions (view, edit, delete, publish).
  • Public pages: /c/<collection> (published items, paginated) and /c/<collection>/<item> (the item and its details rows). Templates come from the theme when it has them (themes/<theme>/collections/<collection>/list.html, then themes/<theme>/collections/list.html, then the same files in the starter theme), else the built-in ones.
  • Embed code: {{ collections:render collection="testimonials" limit="4" }}, with sort, template and field filters (featured="yes"). Pages showing an embed are tagged collections in the page cache.
  • Template values per item: each field by key plus extras (rating_stars, date_formatted, price_formatted, file_name, <key>_excerpt for rich text, relation _url/_id), title, url, slug.

The content editor (CKEditor 5)

One editor is used everywhere rich text is written: Pages, collection fields of type Rich text, the Rich HTML widget and richtext fields of other widget types. (Product descriptions are a plain text field.) It is CKEditor 5 (open-source edition, GPL v2+, licenseKey: 'GPL'; the GPL edition shows a small "Powered by CKEditor" badge in the editing area, admin only), set up once in modules/admin/js/richtext.js (RichText.init / save / confirmSave / destroy) with its styles in modules/admin/css/richtext.css. The package ckeditor5 is pinned, served from node_modules at /vendor/ckeditor5/ (.js and .css only) and loaded only when a form with a rich-text field opens. If it cannot load, the field stays a plain HTML text box.

What editors can do

AreaIn the editor
TextParagraphs and headings (the Paragraph list), bold, italic, underline, strikethrough, text and background colour, left / centre / right / justified alignment, indent and outdent, clear formatting; undo and redo. Markdown-style shortcuts while typing (## for a heading, * for a list).
ListsBulleted and numbered lists, nested by indenting.
LinksLinks to pages or files, opening in the same or a new tab; bookmarks (the bookmark button) to link to within a page (#name); plain web addresses become links as they are typed.
ImagesInsert from the Media Manager (the Media button) or by web address (the image button). Click an image for its toolbar: in line with the text, image left with the text wrapping on the right, centred, image right with the text wrapping on the left, full width; size (25 / 50 / 75% or the original size, or drag a corner handle); caption; alt text; link. Move an image by dragging it to another place in the text. The styles are classes (img-left, img-center, img-right, img-full, on the image or on its captioned figure), styled in themes/starter/css/content-images.css: a gap between image and text, at most half the column wide, and on phones (under 600px) the image above the text instead; the editor loads the same file, so it looks the same while editing. Images floated before (an inline float, or the older editor's figure classes) look the same. Images dropped or pasted into the editor are uploaded to the Media Manager (shared folder) and inserted.
Video and audioFiles from the Media Manager become players; a YouTube, Vimeo or similar address (the media button) becomes an embedded player, saved as its <iframe>.
TablesInsert, add and remove rows and columns, merge cells, header rows.
EmbedsWidget (a list of the widgets) inserts a widget's shortcode and Collection opens a pop-up (collection, number of items 1 to 50, order, template variant) and inserts a collection embed, on Pages only (where shortcodes are rendered); both work for editors who may not open Admin > Widgets or Collections.
OtherCode blocks (a <pre><code> block marked with its language; plain on the site unless the theme loads a highlighter), block quotes, horizontal lines, special characters, find and replace, show blocks (outlines of every paragraph, heading and list), full screen, a word and character count under the editor, and the Source view to edit the HTML directly.

Links and images keep root-relative addresses (/uploads/photo.png), so the content works on every page. The Media, Widget and Collection buttons appear only while their module is enabled (window.__MODULES__) and the role may use them: picking from the Media Manager needs media.view, uploading dropped or pasted images media.create. Without them, images and links are added by address and pasted images are not uploaded.

Markup it has no feature for (classes, styles, attributes, other elements) is kept by General HTML Support. When content is opened, the editor compares what it would save with what is stored (images, iframes, tables, links, shortcodes, the amount of text); if anything would be lost, the form shows a warning, and saving asks first (RichText.confirmSave(), called by the Pages, Widgets and collection item forms).

Heights: in Pages the editor fills its column of the pop-up (data-height="fill"); widget and collection fields start at 320px (data-height="320"), grow with their text up to twice that, then scroll.

What it does not do (yet)

  • Layouts: no ready-made columns, image-beside-text rows or card grids to insert; content flows top to bottom (tables, or HTML in the source view, can approximate columns). Layout blocks are the planned next step.
  • Dragging whole blocks (a section, a column) to reorder them, or dragging column widths, as block editors and page builders do.
  • Free positioning of text or images anywhere on the page: deliberately not offered, because it cannot adapt to phone and desktop screens; themes and (planned) layout blocks keep pages responsive.
  • Images are not cropped or edited in the editor; upload the size you need, or resize them with the image toolbar or the corner handles.

Pages Module

The Pages module provides a full-featured content page management system with WYSIWYG editing, SEO metadata, navigation integration, and public page rendering. It is an optional (non-core) module that can be enabled or disabled independently.

Features

  • WYSIWYG Editor: the shared rich-text editor (CKEditor 5); see The content editor below for what it can do.
  • SEO Metadata: Per-page meta title and description, rendered in the page when the page is published. (Meta keywords are no longer edited or written: search engines ignore them; the column stays.) Each page also gets a canonical address and WebPage structured data (JSON-LD: name, description, published and modified dates). Sharing Image (a Media Manager image, about 1200x630) is the page's own og:image; empty, the site's default from Settings > SEO.
  • Navigation Integration: Pages can be added to the site navigation menu with custom label and ordering. The show_in_nav toggle adds the page to the siteNavItems loop used by themes.
  • Display: Redirect to another address makes the page a link: its address forwards (302, temporary, so the target may change later) to a path on this site (/docs) or a full http(s) address, checked on save (never javascript:, never the page itself); with Show in navigation its menu link goes straight to the target; it is not in the sitemap; a draft forwards only staff. Otherwise Own page (at /<slug>) or Section of the home page: shown on the home page in navigation order through {{#each homeSections}} in the theme's home.html, linked as /#<slug>, and /<slug> redirects there. Single-page sites are built this way, without code. The editor warns when the active theme's home page does not show sections.
  • Starter pages: a fresh install (no pages yet) gets About and Contact (each its own page at /<slug>, in the menu; Contact holds the Contact form widget) and Privacy (its own page, not in the menu).
  • Draft/Published Workflow: Pages save as drafts by default. Only published pages are accessible to anonymous visitors; drafts are visible to logged-in admins for preview.
  • System Page Protection: Pages flagged as is_system=1 cannot be deleted via the admin UI or API.
  • Public URL Routing: Published pages are served at /<slug> with the site's layout and theme; /page/<slug> redirects there (301). Theme pages and other modules' routes win over a page with the same address, so the editor refuses slugs they use (products, c, admin, ...).
  • Edited in the site's look: the Pages editor shows the content styled by the active theme (WYSIWYG): the stylesheets and web fonts its layout.html links and its <body> classes, with the editing area as the page's .article-body (src/core/editor-styles.ts). The editor edits in the admin page itself, so it loads GET /api/v1/pages/admin/editor-styles.css: the theme's CSS rewritten to apply only inside the editing area (every selector prefixed; body / :root rules set only its font, colours, background and variables, never layout such as min-height; local @imports inlined, url()s made absolute, web fonts kept), so the admin around it is unchanged. Widget and collection rich-text fields keep the neutral look: on the site they are not inside .article-body.
  • Site details in the text: {{ site.title }}, {{ site.tagline }}, {{ site.url }}, {{ site.year }} and {{ site.email }} typed in a page become the active site's title, tagline, address, the current year and its Contact form email (escaped; the email is empty when the site has none, never the admin email; also in home page sections and the Preview). Only these five: editor content is never run through the template engine, so any other {{ ... }} stays as written, and so does code in <code> / <pre>. A widget's or collection's own output is not scanned.
  • Preview: the eye beside the pop-up's close button opens the page as it is in the editor, unsaved changes included, in a new tab in the site's theme (POST /api/v1/pages/admin/preview, pages.view; nothing is saved; not cached, not indexed). A Redirect page opens its target.
  • Redirects: when a published page, product or collection item gets a new address (a new slug; a product's follows its title), the old address answers with a permanent redirect (301) to the new one, query string kept, so links and search rankings keep working. No chains: renaming again points every older address at the newest; content created at an old address makes it live again. Listed in Admin > Pages > Redirects (pages.view; deleting one needs pages.delete and makes the old address a 404). Core: src/core/redirects.ts (table redirects, kept in memory, looked up before any public route; never /admin or /api).
  • Where the content sits: pages and home page sections are in the theme's container (the header and footer width), the text column left-aligned with them and at most 960px wide (.article-body in the starter CSS; section titles left-aligned too). Error, maintenance and account pages keep the narrow centred container-narrow.
  • What a page shows: its content only (modules/pages/templates/page.html). The title names the page in the menu (unless a navigation label is set), the browser tab, search results and the admin; it is not printed above the content, so start the content with its own heading (Heading 1 in the editor). The starter pages do. The meta description goes into the meta tags only. A home page section still shows its title as the section heading.
  • TabulatorJS Admin Grid: Search, pagination, status/visibility toggles, and inline action icons (View, Edit, Delete).
  • Page Shortcode: Embed page content in other templates with {{ page='slug' }}.

Database Schema

CREATE TABLE IF NOT EXISTS pages (
  id TEXT PRIMARY KEY,
  slug TEXT NOT NULL UNIQUE,
  title TEXT NOT NULL,
  content TEXT NOT NULL DEFAULT '',
  status TEXT DEFAULT 'draft',          -- 'draft' or 'published'
  meta_title TEXT,
  meta_description TEXT,
  meta_keywords TEXT,
  show_in_nav INTEGER NOT NULL DEFAULT 0,
  display TEXT NOT NULL DEFAULT 'page', -- 'page' (/slug) or 'section' (home page, /#slug)
  nav_label TEXT,
  nav_order INTEGER DEFAULT 0,
  is_system INTEGER NOT NULL DEFAULT 0,
  site_id TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  created_by TEXT,
  updated_by TEXT
);
CREATE INDEX IF NOT EXISTS idx_pages_status ON pages(status);
CREATE INDEX IF NOT EXISTS idx_pages_slug ON pages(slug);

Admin Routes

  • GET /admin/pages — Pages management UI (TabulatorJS grid + modals)
  • GET /api/v1/pages/admin/list — List all pages
  • GET /api/v1/pages/admin/:id — Get single page
  • POST /api/v1/pages/admin/save — Create or update page
  • POST /api/v1/pages/admin/delete — Delete page (blocked if is_system=1)
  • POST /api/v1/pages/admin/toggle-visibility — Toggle published/draft status

Public Routes

  • GET /:slug — Render a published page (drafts for staff only); a section redirects to /#slug; no such page: the request goes on to later routes (e.g. 404)
  • GET /page/:slug — 301 to the page's address

Template Helpers

{{ page='about-us' }}

Renders the content of the page with slug about-us inline. The page must be published (or the viewer must be an admin).

Navigation Integration

When a page has show_in_nav=1 and status=published, it is automatically added to the siteNavItems array passed to the theme layout. Themes use {{#each siteNavItems}} to render navigation. The nav_label field overrides the page title in the menu; nav_order controls position.

Menu order by drag and drop: in Admin > Pages, users with pages.edit drag a row by its handle to change the order. The grid sends every page id in the new order to POST /api/v1/pages/admin/reorder, which numbers them 10, 20, 30, ... in one transaction (room for manual numbers in the page form), leaves "Updated" alone, clears the page cache and records page.reorder in the audit log. The same order is used for the menu and for home page sections. Dragging is off while the grid is sorted by another column or searched ("Back to menu order" restores it); with several grid pages, a row moves within its grid page (choose a larger page size to move it further).

Admin UI

  • Grid columns: Page (title + slug), Published (toggle), Nav (toggle: adds the page to the menu or takes it out), Last Update (date, time below), Actions (View, Edit, Delete)
  • Modal form: fills the browser window, in two columns that scroll independently: the rich-text editor on the left (filling the column), and on the right Title, Slug (auto-generated if blank), Status, Show in Navigation (+ Nav Label, Nav Order) and SEO fields. On screens up to 1024px wide the right column moves above the editor
  • Actions: Eye icon opens the public page in a new tab; Edit opens the modal; Delete removes the page (unless is_system=1)
  • Search: Real-time filtering by title, slug, or content
  • Status toggle: Inline switch in the Published column — on = published, off = draft

Template Structure

modules/pages/
├── init.ts                    # Module definition, schema, API routes, admin views
├── js/
│   └── pages.js               # TabulatorJS grid, modal handlers, editor setup (RichText.init)
└── templates/
    ├── pages.html             # Admin list page + modals
    └── page.html              # Public page render template

Module Registration

The Pages module registers itself as a non-core module (isCore: false). It is auto-discovered from modules/pages/init.ts on boot. When enabled, it contributes:

  • Public routes /:slug and /page/:slug (redirect) via site.routes
  • Admin view at /admin/pages
  • Admin API routes at /api/v1/pages/admin/*
  • Template helper page, navigation items via pages:getNavItems, home page sections via pages:homeSections

Switching to Remote Turso Cloud

To use Turso Cloud in staging or production:

  1. Create a database using Turso CLI:
turso db create my-app-db
turso db show my-app-db --url
turso db tokens create my-app-db
  1. Update your .env file:
TURSO_DATABASE_URL="libsql://my-app-db-[org].turso.io"
TURSO_AUTH_TOKEN="your-turso-jwt-token"

No code changes are required! The @libsql/client driver works identically across local SQLite and remote Turso.

Deployment

Carnival3 is Bun-only with no build step: production runs the same source as development, because modules are discovered at startup from modules/*/init.ts.

bun install --production
bun run start        # = bun server.ts

Keep it running with PM2 (pm2 start server.ts --name my-app --interpreter bun) or a systemd service, and put a reverse proxy such as Caddy or Nginx in front for HTTPS. See docs/deployment.html for step-by-step instructions.

On Render, the repository's render.yaml Blueprint creates a web service with a persistent disk for the SQLite database, uploads/ and logs/; see docs/deploy-render.html. Behind a hosting proxy, set CLIENT_IP_HEADER to the header that carries the visitor's real address (True-Client-IP on Render), and back up a local database with bun run cli db:backup.

Production hardening

  • Set APP_ENV=production to suppress detailed error pages.
  • Use strong APP_SECRET values.
  • Back up uploads/ and the database (bun run cli db:backup copies a local database while the app runs; schedule it); cache/ and logs/ are disposable.
  • Put a reverse proxy (Nginx, Caddy, Cloudflare) in front for TLS termination.
  • Enable Turso Cloud for managed database backups and global replication.

Theme Customization

1. Themes live inside /themes/<theme-name>/. 2. A theme needs layout.html (and usually home.html, css/, js/); anything else falls back to the starter theme. 3. Choose a site's theme in Admin > Sites (see Sites & Themes). Start a new theme by copying themes/starter/.

Theme-aware admin assets

Admin CSS and JS are served from modules/admin/css/ and modules/admin/js/ so the admin panel stays consistent regardless of the active site theme. The admin uses one font, Inter (loaded by modules/admin/templates/layout.html), for the menu, headings, tables, pop-ups and every form control. Static asset routes were added in src/core/app.ts.

Sites & Themes

One site is active per deployment. Several sites can exist (for example to A/B test designs); the one selected in Admin > Sites is served, and it stays active across restarts.

  • A site is a row in the sites table (name, title, tagline, contact email, theme, active) plus modules/site/<name>/init.ts for optional custom code.
  • A theme (themes/<theme>/, or uploaded-themes/<theme>/ when added in the admin; themeDir() in src/core/themes.ts finds it, built-in first) holds all of the HTML. layout.html is required; home.html is served at / and every other page file x.html at /x. 404.html, 500.html and maintenance.html are special pages; files starting with _ are partials. Missing pages fall back to the starter theme (layout, home, 404, 500, maintenance), which is also the theme of a fresh install's site.
  • Menu: {{#each siteNavItems}} in the layout lists Home (plus About / Contact only if the theme has about.html / contact.html), links from enabled modules (each module's site.nav, e.g. Products), then every published page marked "Show in navigation" in Admin > Pages (/slug, or /#slug for a home page section). A site's init.ts can replace the standard links.
  • Pages from the Pages module are shared by all sites. With the starter theme, all content comes from Pages: the theme is only the frame.
  • Custom code goes in the site's init.ts (written by a developer, never uploaded). Its routes take precedence over theme pages; a handler returning data is rendered with the theme page of the same name.
  • Contact form: the Contact form widget (or a theme's own form) posts to POST /api/v1/site-manager/contact, which emails the active site's contact email, or the admin email in Settings > General when the site has none (rate limited; Settings > Contact Form). The contact email is set in each site's form; the Sites list no longer shows it as a column.
  • A fresh install has the starter site, titled "My Site", on the starter theme (default and active), with the starter pages, ready to rename and edit. The repository's modules/site/carnival-cms/ folder adds a second, inactive site, carnival-cms.
  • Stats record the site name and theme of every page view; the dashboard filters by both.
  • Maintenance mode is switched on the active site's row in the Sites grid (the Maintenance column, while the Maintenance module is enabled); it is one switch for the install and applies to the site being served.

Static export

The download button on a site's row in Admin > Sites exports that site (any site, active or not) as plain HTML, CSS and JS in a ZIP for static hosts (src/core/static-export.ts). A crawler renders the site as an anonymous visitor from / and from every address modules list (publicPaths: published pages, collections, products), follows links, copies every file the pages use, rewrites list pagination (?page=2 to /page/2/) and absolute addresses, and writes sitemap.xml, robots.txt and 404.html. The contact form keeps posting to the server (?site=<name> picks that site's contact email; the endpoint is CSRF-exempt because static sites post from another domain). Export requests carry a one-time token: they render the chosen site and skip the cache, statistics and maintenance mode.

Adding a site

  • Admin > Sites > New Site: creates the row and a starter init.ts (comments with how-to only). The form takes a title, tagline, theme (the themes enabled in Admin > Themes) and contact form email. New sites are inactive until you activate them. Content images go through the Media Manager.
  • Terminal: bun run make:site <name> [--theme t] [--title "T"] [--email e] [--activate].
  • Admin > Themes (core module modules/themes/): every theme folder with its layout picture, name, description, status, the sites using it and its source (built-in or uploaded). Editing a theme sets its Layout: one of 18 page layouts (one column, two to four columns, sidebar left or right, hero, cards grid, gallery, sections, landing page, ...), picked from a dropdown that shows each layout's picture and name, or Not set. The list is modules/themes/layouts.ts (pictures in modules/admin/images/); the choice is stored in themes.layout and checked against that list. Add Theme takes a ZIP (folder = the ZIP's file name), a name, a description and a status; Upload new version merges a ZIP into an uploaded theme (same paths replaced, new files added, others kept). Only enabled themes are offered in the site forms; starter cannot be disabled; a theme that sites use cannot be disabled or deleted. Built-in themes cannot be replaced or deleted from the admin. Records live in the themes table (a folder found at startup gets one, enabled); helpers in src/core/themes.ts (themeChoices, isThemeSelectable, syncThemeRecords).
  • No restart is needed for a new site; only editing an init.ts needs one.

Step-by-step guide: docs/how-to-create-a-site.html (also in Admin > Documentation).

Admin Site Routes

  • GET /admin/sites, /admin/sites/new, /admin/sites/:id/edit — site list and forms
  • POST /api/v1/site-manager/admin — create site (row + init.ts; themes are added in Admin > Themes)
  • PUT /api/v1/site-manager/admin/:id — update site (sites cannot be renamed)
  • DELETE /api/v1/site-manager/admin/:id — delete site; its folder is removed only while it holds the untouched starter
  • POST /api/v1/site-manager/admin/switch — make a site the active one

Available NPM / Bun Scripts

  • bun run dev: Start development server.
  • bun run setup: Run initial database setup and create the default administrator.
  • bun run make:module <name>: Scaffold a new self-registering module.
  • bun run make:site <name>: Create a site (database row + starter init.ts).
  • bun run start: Start the production server (bun server.ts, no build step).
  • bun run lint: Type-check the project with tsc --noEmit (strict mode; no any in the app code).
  • bun run lint:js: Lint widget and module JavaScript files with ESLint.
  • bun test: Run the test suite (test:serial runs files one at a time, test:coverage adds a coverage report).
  • bun run cli <command>: cache:clear, cache:stats, user:create, user:list, user:delete, settings:list, settings:get, settings:set, health, db:backup, setup.

User Registration, Sign-in & Passwords

  • Registration (/users/register, can be turned off in Settings > Users): name (up to 100 characters), a valid email address (up to 254) and a password (6 to 128 characters), checked on the server. New accounts get the "Default Role for New Users" (keep it on User).
  • Without email verification (default): the account is active and the person is signed in straight away.
  • With "Require Email Verification": the account is pending until the person opens the link emailed to them (valid 7 days). The link opens /users/verify-email, which activates the account and signs them in; the page confirms with a request of its own, so mail scanners that open links cannot use up the link. Requirements and safeguards:
    • Email must be set up (SMTP in Admin > Settings > Email Service, with a Test Email box below the form). If it is not, registration is refused with an explanation; if a verification email cannot be sent, the account is not created, so the person can try again later.
    • Registering again with an address that is still pending sends a new link (the password is not changed). The login page offers Resend verification email for pending accounts, and expired links offer a resend form. Resending answers the same whether or not the address is registered.
    • Administrators can activate pending accounts in Admin > Users (shown with a Pending badge); this cancels the emailed link.
  • Account statuses: active, pending (waiting for email verification) and inactive (deactivated by an administrator).
  • Two sign-in pages: site visitors use /users/login (in the site's theme, with links to registration and password reset); staff use /admin/login (in the admin's look: email, password and a Forgot password? link; no registration). Admin pages send visitors there, and only administrators, managers and editors can sign in on it (a site user is told the account has no admin access). Signing out returns staff to the admin sign-in page.
  • Admin password reset: Forgot password? opens /admin/forgot-password, which asks for the sign-in email (the API call carries area: "admin"). Only an active or pending staff account gets an email; its link opens /admin/reset-password in the admin's look, and after the change the person signs in again at /admin/login. Site users and unknown addresses get the same answer and no email, so the page does not reveal which addresses are admin accounts. Otherwise it works like the site's reset below (needs email set up, link valid for Settings > reset link minutes, works once, signs out every device).
  • Sign-in: a wrong email or password gets the same answer ("Invalid email or password"), so the form does not reveal which addresses are registered. Only after the right password does a pending account hear "verify your email first" and a deactivated one "deactivated, contact the administrator".
  • Password reset (/users/forgot-password, needs email set up: without it the request is refused with an explanation): the emailed link is valid for 1 hour and works once. The reset page checks the link when it opens (expired or used links offer a new one) and asks for the new password twice. Completing a reset signs the account out on every device, and activates an account that was still waiting for email verification (the link proves the address). Deactivated accounts get no reset link; the answer is the same whether or not an address is registered.
  • Profile: change the display name and password (current password required, new one entered twice). Changing the password signs you out on your other devices and keeps you signed in; Sign out of all other devices does the same without a password change. The email address cannot be changed yet. Site users have it at /users/profile (in the theme). Staff have it in the admin at /admin/profile (My Profile in the top bar; every staff role may open it), which also shows their role and last sign-in (the one before the current session, so a sign-in they don't recognise stands out); /users/profile sends them there. Every sign-in stores its time in users.last_login_at, moving the earlier one to previous_login_at.
  • Emailed tokens (verification and password reset) are stored as SHA-256 hashes, so a copy of the database cannot be used to open anyone's link.
  • Themes: the account pages bring their own stylesheet (modules/users/css/account.css) that fills in whatever the active theme does not style, so they work in every theme.
  • Rate limits per visitor and minute: sign-in 20, registration 10, verification 10, password reset 10, resending a verification link 5, requesting a password reset 5.
  • During maintenance the sign-in, registration, password and verification pages keep working.
  • API: POST /api/v1/users/register, /login, /verify-email ({ token }), /resend-verification ({ email }), /forgot-password ({ email }), /reset-password ({ token, password }), /profile/update, /sessions/revoke (signs out the other devices).

Roles & Permissions

Four roles: admin (everything, always), manager and editor (what the matrix grants) and user (public site only, no admin access). Permissions are <area>.<action> with the actions view, edit (create + update), delete and publish; every module with an admin surface is an area automatically.

  • Matrix: Admin > Users > Roles & Permissions (administrators only). Actions: view, create (add new), edit (change existing), delete, publish. Defaults: managers get the dashboard, pages, products, widgets and collections (all actions), media, users and themes (view, create, edit, delete) and stats (view); editors get pages, products and collections (view, create, edit, publish) and media (view, create, edit). Designing collections, settings, modules, sites, email, cache, application logs, the audit log, maintenance and widget types are administrator-only; the documentation is open to every staff member.
  • Checks: the admin gate maps each request to a permission (admin pages: view; admin API GET view, DELETE delete, other edit; modules declare exceptions in permissions.routes). Publishing is checked on save: without it new items are unpublished and status changes are refused.
  • Users: managers manage editors and users only; administrators are read-only to them. The last active administrator cannot lose the role.
  • For developers: can(c, 'pages.publish'), requirePermission(), {{#if can.pages.delete}} in templates, window.__CAN__ in admin scripts, audit(c, action, entity) for the audit log. Full guide: docs/roles-and-permissions.html (Admin > Documentation).

Admin Dashboard

Admin > Dashboard (/admin, permission dashboard.view: administrators and managers by default) shows each part only to those who may see it (modules/admin/dashboard.ts):

  • Needs attention (administrators): email not set up or the Email module off; the default test@c3.com account still there (and whether it still has the published password); APP_ENV not production; APP_URL left on localhost while the admin is opened at a public address (also a warning in the admin header; src/core/app-url.ts), or pointing to localhost in production; a missing, invalid, expired or wrong-domain license key, and enabled premium modules the key does not include (see Licensing); maintenance mode on; search engines blocked; errors in the last 24 hours with the time of the last error alert; no database backup (bun run cli db:backup) in 7 days, in production with a local database; a disk almost full. Each item links to where it is fixed. The list is hidden when nothing needs attention.
  • Numbers from enabled modules the user may view (dashboardStats in the module, see the module guide): published pages and drafts, media files and their size, collection items, products, users.
  • Traffic (Statistics module, stats.view): the active site's page views today and over 7 days, visitors, a bar per day and the top 5 pages.
  • Recent changes from the audit log, limited to areas the user may view (sign-ins and account housekeeping are left out; they are in the Audit Log).
  • Live site: the active site and its theme, with View site, Sites and Export as static site (administrators).
  • Quick actions: New page (/admin/pages?new=1 opens an empty page form), Media library, Collections, Widgets, and for administrators Settings, Users, Application Logs and Clear page cache.
  • Server line (administrators): Bun version, uptime, memory, database (local file or Turso), cached pages, free disk space, APP_ENV.

Admin Settings

Admin > Settings (administrators only) has one tab per group. Every value is validated when saved (limits, formats, choices), and nothing is stored unless the whole tab is valid. Passwords are never shown again after saving.

TabSettings
GeneralAdmin notification email, date format, time zone, default language, Public documentation (off by default: on, these guides are also at /docs/<guide> for everyone, in the site's theme with the list of guides on the left and "On this page" on the right, links between guides kept public, listed in the sitemap; /docs opens the Overview, and a page cannot take that address. The guides name the default administrator login, so change it before turning this on). The date format applies to dates the server writes (Media library, the maintenance page's return time, collection date fields on the site, the profile pages); times are on a 12-hour clock (2:05 PM). The time zone is chosen from a dropdown of every standard (IANA) zone, with today's offset; until one is chosen it is America/Los_Angeles (DEFAULT_TIMEZONE in src/core/dates.ts). The admin grids always show 2026-10-31 with the time below (AdminFormat.dateTimeCell).
SEO & AnalyticsDefault description and sharing image (Open Graph / Twitter tags), site logo (the Organization's logo in the home page's structured data), Google Search Console and Bing Webmaster Tools verification (the code, or the whole meta tag pasted; written on the home page), allow search engines (noindex + robots.txt), Google Analytics ID or Plausible domain. Always on, without a setting: a canonical address on every public page (no query string, except ?page=N), structured data (JSON-LD: WebSite and Organization on the home page, WebPage for pages, Product for products, BreadcrumbList for products and collection items), og:site_name and og:type (article for pages, product for products), and sitemap.xml with each address's real <lastmod> date. Per item: a page's Sharing Image; a product's SEO Description (else the start of its description) and its photo as the sharing image; a collection item's first text field after the title (cut to about 160 characters; else the collection's description) and its first image.
Security & SessionsStay signed in for (days), minimum password length, reset and verification link lifetimes, sign-in attempts per minute, account lockout after failed sign-ins
Error AlertsEmail an alert when errors pile up (on by default): after how many errors, within how many minutes, quiet period before the next alert, recipients (empty: the admin notification email, else every active administrator). Needs working email.
CacheCache pages on/off (overrides CACHE_ENABLED once saved), theme page lifetime
SystemRequest timeout, max body size, log rotation, logs per page, audit log retention; a read-only table of .env settings
Contact FormMessage after sending, extra recipients, messages per minute
EmailProvider, SMTP, from name/address, reply-to address
MaintenanceMaintenance mode, message to visitors, expected end time (also sent as Retry-After), IP addresses that see the site
MediaUpload size limit, allowed extensions (AVIF included), shrink wide images (AVIF stays AVIF), convert JPEG/PNG to WebP
StatisticsTracking on/off, dashboard range, leave out staff, leave out bots, delete old page views
UsersAllow registration, allowed email domains, default role, email verification, notify administrators of registrations, users per page
Pages, Products, WidgetsAdmin list sizes; products: currency symbol and catalog page size
CollectionsCurrency symbol for Price fields, items per admin page

Server settings that are needed before the database is available stay in .env (APP_URL, PORT, TURSO_DATABASE_URL, APP_SECRET, LOG_LEVEL).

Security

Carnival3 ships with security hardened defaults suitable for production deployments.

  • Admin gate: every /admin/* page and every /api/v1/<module>/admin/* endpoint (a module's adminApiRoutes) is checked by the core against the user's role and permissions. Modules never write their own role checks, so a new module cannot forget one; a new module is administrator-only until permissions are granted.
  • Audit log: who did what to which record, with IP and path, in Admin > Audit Log (administrators only).
  • CSRF: every POST/PUT/PATCH/DELETE must send the _csrf cookie value in an x-csrf-token header or a _csrf form/JSON field, and must not carry a foreign Origin. The check runs before the route handler. Page scripts read the token from window.__CSRF_TOKEN__.
  • Safe redirects: post-login redirects only accept same-site paths (safeRedirect() in src/core/security.ts).
  • Path safety: site and theme names must be lowercase letters, digits and dashes, because they become folder names. A site cannot take the name of a module. ZIP uploads are rejected if any entry would land outside its target folder.
  • Code blocks: shortcodes inside <pre>, <code>, <script>, <style> or <textarea> are left as written (never run), so pages can show embed codes as examples and scripts are never rewritten.
  • Disabled modules: a disabled module's API and admin views return 404, and its shortcodes (widgets, {{ page='slug' }}, module shortcodes such as {{ collections:render ... }}) render nothing.
  • APP_SECRET: src/core/config.ts generates a random secret and persists it to .app_secret if APP_SECRET is not set in .env. It is reserved for signing; sessions are random tokens stored in the database and do not use it.
  • Session cleanup: cleanupExpiredSessions() in src/core/auth.ts runs at startup and every 24 hours and deletes expired sessions from the database (sessions are indexed by user and by expiry).
  • Password reset: 1-hour, single-use links whose tokens are stored hashed; a reset signs the account out everywhere. See User Registration, Sign-in & Passwords.
  • Email verification / admin activation: see User Registration & Sign-in. The verification token is only ever sent by email, never returned by the API; opening the link does not activate the account by itself (the page confirms with a POST).
  • Sign-in privacy: wrong email and wrong password get the same answer, and account status is only revealed after the correct password. No sign-in page shows the seeded admin's password.
  • Rate limiter: Expired rate-limit buckets are cleaned lazily on each request; no background setInterval timer.
  • CORS: corsMiddleware() in src/core/security.ts handles preflight OPTIONS requests and adds CORS headers to /api/v1/*.
  • Request limits: src/core/request-limits.ts adds configurable request timeout and body-size-limit middleware.
  • No runtime CDNs: every third-party script the admin uses (CKEditor, CodeMirror, Tabulator, Lucide icons, ApexCharts) is a pinned dependency served from node_modules under /vendor/, so a CDN outage or a compromised CDN release cannot change the admin; a test fails on unpkg / jsDelivr links.
  • Template values in scripts: values are HTML-escaped, which does not make them safe inside JavaScript (an onclick attribute decodes &#039; back to '). Put values in data- attributes and read them from a script instead.

Caching

Carnival3 caches rendered pages, and optionally API responses, as files in /cache/. An in-memory index of keys, expiry times and tags keeps lookups, tag invalidation and stats from scanning the folder. Turn it off with CACHE_ENABLED=false.

Page cache

  • Opt-in per route: a site route is cached when it declares cacheTtl (seconds) and optional cacheTags. Theme pages are cached for 5 minutes.
  • Anonymous visitors only: signed-in users always get a fresh render, so personal content (profiles, admin draft previews) never enters the cache.
  • Key: active site + visitor language + path + query string (parameters sorted), so /products?page=2 is cached separately from /products. The language is the first Accept-Language entry that has a locales/<lang>.json file, otherwise English. Theme pages (whose templates cannot read the query string) and routes declaring cacheQuery: false leave the query string out, so ?utm_source=... links share one entry.
  • Cleared at startup: the cache is on disk, so cached pages would outlive a restart; they are dropped when the server starts, so a deploy never serves pages rendered by old templates or code. API entries are kept.
  • CSRF-safe: the CSRF token is replaced by a placeholder before storing, and each visitor's own token is put back when the page is served.
  • Only successful HTML (status 200) is stored. Response headers are never replayed.
  • Tags: every page gets its route's cacheTags plus the module id, site:<siteId>, site and pages (layout, settings and navigation appear on every page). Pages that embed widgets also get widgets, and module shortcodes add their own tags (collection embeds: collections, via the X-Cache-Tags header the renderer sets). Saving settings, sites or pages clears every page; editing products, widgets or collections clears only the pages that use them.
  • Headers: cached routes answer with X-Cache: HIT or MISS. Every response for a signed-in user, and every /admin page or admin API response, carries Cache-Control: private, no-store, so browsers and shared caches (a CDN "cache everything" rule) never store personal pages. Static assets keep their own caching.

API cache (opt-in)

Wrap a public JSON GET endpoint with cacheApi(). Like pages, only anonymous requests and 200 responses are cached:

import { cache, cacheApi } from '../../src/core/cache.js';

api.get('/posts', cacheApi({ ttl: 60, tags: ['blog'] }), async (c) => {
  return c.json({ posts: await dbAll('SELECT * FROM posts') });
});

// after a post is saved:
cache.invalidateTag('blog');

Limits and settings

  • At most 5,000 entries: beyond that, expired entries go first, then the oldest, down to 4,500 (so a full cache is not re-sorted on every write).
  • Settings read with getSetting() are kept in memory after the first read and refreshed whenever setSetting() runs (for example, saving in Admin > Settings). Changes made outside the running server, such as bun run cli settings:set, apply after a restart.
  • The cache is per process. If you run several instances, each keeps its own /cache/.

Database connection

  • One connection per server process (getDb()), kept open; tests also keep one connection to test.db for the whole run.
  • Local files wait for locks: with a file: database, the connection sets PRAGMA busy_timeout = 5000, so a write waits up to 5 seconds when another process (such as bun run cli db:backup) holds the lock, instead of failing at once with SQLITE_BUSY.
  • Sessions are indexed by user (signing out other devices, password changes and resets) and by expiry (the cleanup at startup and once a day).

Other in-memory caches

These keep ordinary requests off the database and the disk; each refreshes itself when its source changes.

  • Active site: the site middleware reads the active site on every request. Sites looked up by id and the active site are kept in memory (src/core/sites.ts), cleared by any write to the sites table and after 30 seconds at most (for several instances sharing one database). This matters most on Turso, where every query is a network round trip. Code that caches another table can do the same with onTableWrite('table', fn) from db.ts, which runs fn after every dbRun / dbBatch statement that writes to that table.
  • Static files skip the session and site lookups: requests under /themes/, /vendor/, /uploads/, /widgets/ and /modules/<id>/css|js|images|fonts/ (isStaticAsset() in app.ts) are the same for everyone, so they do not touch the database.
  • Templates: a template file's text is kept in memory until the file changes (size or modified time), so an uncached render costs one file check per template instead of a full read. Theme uploads and edits apply at once.
  • Module CSS, JS and images: still revalidated on every load (no-cache + ETag), but the bytes and ETag are kept in memory until the file changes, instead of reading and hashing the file on every request.
  • Log lines: queued and written once per file after the current task, without blocking the request; anything still queued is written when the process exits. The admin log viewer shows recent lines from memory, so nothing is hidden while a write is pending. Tests call await flushLogs() before reading a log file.

Core Engine

The CMF core is intentionally small. It provides module registration, template rendering, caching, logging, security, and asset serving. Feature logic lives in modules.

  • Self-registration: modules declare an AppModule and are auto-discovered from modules/*/init.ts.
  • Template engine: supports {{ variable }}, {{#if}}, {{#each}}, and nested blocks.
  • Cache: disk-backed page/API cache with an in-memory index, TTL and tag-based invalidation (see Caching).
  • Logger: structured JSON file logging (errors and security events by default) with automatic log rotation and retention.
  • i18n: lightweight translation support via src/core/i18n.ts and /locales/.
  • Error pages: 404 and 500 errors render through theme templates instead of inline HTML.
  • Static files: theme, upload, widget and vendor files are streamed (Bun.file(path).stream()) without blocking the event loop. Templates and module CSS/JS/images are kept in memory until the file changes, and static files skip the session and active-site lookups (isStaticAsset()).
  • Graceful shutdown: server.ts listens for SIGTERM/SIGINT, closes the DB, and stops accepting connections.
  • Favicon: GET /favicon.ico serves the active theme's images/favicon.ico, .png or .svg, else uploads/favicon.png, else an inline SVG.

Media Manager

The Media module provides a full-featured file management interface for uploading, browsing, and managing media files.

Features

  • Alt text (images, users with media.edit): the captions button on an image opens a pop-up to describe what it shows (up to 250 characters; column media.alt_text; audited as media.alt). It is used wherever the image appears: product pages and the catalog (else the product title), collection image fields (alt, <key>_alt), and images inserted into the editor from the Media Manager (else the file name without its extension). Other modules read it with callHelper<string>('media:altFor', url) or media:altMap (all of them, address to text).
  • Drag & Drop Upload: upload multiple files via drag-and-drop or the file picker (offering only the allowed extensions). Each file shows its progress, and a failed upload shows the server's reason (too large, type not allowed, ...).
  • Folders: shared files live in uploads/, a site's files in uploads/<site>/. Uploads go to the folder selected in the folder filter (shared when "All folders" is selected).
  • AVIF: allowed for upload by default (the AVIF box in Settings > Media > Allowed Extensions), and treated as an image everywhere (pickers, the Images filter, generated sizes). Browsers often save web images as AVIF. Existing installs got AVIF added to their allowed types once; unticking it later sticks. "Shrink uploaded images wider than" also shrinks AVIF (it stays AVIF); "Convert to WebP" leaves AVIF alone, as it is usually smaller.
  • Generated image sizes: PNG, JPG, GIF, WebP and AVIF images get two WebP files in uploads/thumbs/ (transparency kept, phone photos rotated upright), made on upload and, for files placed in uploads/ another way or uploaded before a size existed, at the next sync (every server start):
    • Thumbnail thumb_<file>.webp: 320×320, cropped square. Used by the Media grid, the list, the media pickers and admin grids (media:thumbnailUrl).
    • Listing image w640_<file>.webp: 640px wide, the image's own proportions, never enlarged. Used by cards and listings such as the Products catalog (media:listingUrl).
    The sizes are fixed in modules/media/init.ts (not a setting: changing one would mix old and new files); the size is part of each file name, so a size added or changed later never collides with the old files. SVG and ICO files are shown from the original file. Other modules turn an /uploads/... address into a generated size with await callHelper<string>('media:listingUrl', url) or 'media:thumbnailUrl'; any other address (an outside link, an SVG, a file without that size yet) comes back unchanged.
  • File Type Icons: other files show an icon in both grid and list views.
  • Grid & List Views: toggle between grid cards and a table (remembered per browser).
  • Search, Filter & Pages: search by filename (% and _ are literal), filter by folder and type (images, videos, audio, documents, archives, other), sort by date, name, size or type. 48 files per page with Prev / Next. The filters are kept in the URL, so a reload or a shared link shows the same view.
  • Admin Settings: max upload size, allowed file extensions, maximum image width and WebP conversion in Admin > Settings > Media.

Storage, Sync & Cleanup

Uploaded files are stored in uploads/ (and site folders). Database records track filename, original name, MIME type, size, extension, file category, folder, thumbnail and timestamps. File URLs are URL-encoded, so names with spaces or # work.

Files can also be copied into uploads/ directly. On startup and via the Sync button, the library is made to match the disk:

  • New files: files without a record are added (dotfiles such as .gitkeep are ignored).
  • Missing files: records whose file is gone are removed, together with their thumbnail and listing image.
  • Thumbnails: images with a missing or outdated thumbnail, or no listing image, get a new one.

Cleanup Orphans deletes what the library does not know about: files in uploads/ without a record (e.g. copied in since the last sync; use Sync to keep them instead) and generated images no record uses (a library file's thumbnail and listing image are kept). It first lists exactly what would be deleted and asks for confirmation (POST /api/v1/media/admin/cleanup-orphans?dryRun=1 returns the list without deleting).

Email Service

The Email module provides centralized email delivery via SMTP using nodemailer. It supports configurable SMTP providers, email verification, password resets, contact form notifications, and a built-in provider registry for custom email backends.

Features

  • SMTP Delivery: Uses nodemailer to send emails through any SMTP provider (Mailtrap, Gmail, SendGrid, etc.).
  • Provider Registry: Core module exposes helpers (email:send, email:registerProvider, email:getProviders) so other modules can send emails or register custom email providers without tight coupling.
  • Admin Settings: SMTP host, port, security mode, username, password, from-name/address and reply-to address are stored in the database and editable from Admin > Settings > Email Service.
  • Test Sender: the Email Service settings tab has a Test Email box below the form: it shows whether email is configured and sends a sample message with the saved settings. There is no separate Email page or menu link any more; /admin/email redirects to the tab.
  • Contact Form Integration: The site contact form uses email:send to notify the site owner when a visitor submits a message.
  • User Email Flows: Registration verification and password reset emails are sent through the same registry, so they automatically use the active provider.

Available Helpers

  • email:send(options) — send an email with to, subject, html, text, from, replyTo
  • email:getProvider() — returns the active provider name and whether it is configured
  • email:getConfig() — returns the current SMTP config object
  • email:registerProvider(name, sendFn) — register a custom email provider
  • email:getProviders() — list all registered provider names

Provider Logic

The active provider is selected by the email_provider setting:

  • Default: Uses the built-in SMTP/nodemailer transport.
  • Custom: Any third-party module can call email:registerProvider('sendgrid', async (options) => { ... }) and set email_provider = 'sendgrid' to take over delivery.

API Routes

  • POST /api/v1/email/admin/test — send a test email to a provided address (admin only)
  • GET /api/v1/email/admin/providers — return active provider, configured status, and available providers

Server Health

The Server Health module (modules/server-health/, not core: it can be disabled in Admin > Modules) shows how this server process is doing, at Admin > System > Server Status (/admin/server-health). Administrators only.

What it shows

  • Cards: memory, CPU, response time (average and p95 of the last minute), server errors in the last hour, uptime, database delay, event-loop delay, requests per minute.
  • Graphs (ApexCharts): memory, CPU (% of one core), requests and server errors per minute, response time (average, p95), database delay, event-loop delay. Periods: the last hour live (a point every 5 seconds), the last 24 hours (5-minute points) and the last 7 days (30-minute points).
  • Disk space of the disk holding uploads/ and the database, folder sizes (uploads/, logs/, cache/, the database file), and server details (host, Bun version, CPU cores, page cache).

How it measures

  • Every 5 seconds a sample in memory (the last hour is kept): the process's memory and CPU time, the worst event-loop delay (how late a 500 ms timer fires), and the requests since the previous sample. The database answers a minimal query every 15 seconds.
  • Requests are timed in the core request logger and handed to modules through onRequestTimed() (src/core/request-timing.ts). Static files are not reported; the module also leaves out /health and its own API, so the page does not measure itself.
  • Every minute one row goes to server_health_minutes; rows older than Settings > Server Health > Keep history for (1 to 30 days, default 7) are deleted every hour. The 24 hour and 7 day graphs read these rows; their p95 and event-loop delay show the worst minute of each point.
  • In a container (Render, Docker) the operating system reports the host machine's memory, so the container's own use and limit are read from the Linux cgroup files (/sys/fs/cgroup) and drawn as a limit line. Elsewhere the page shows the process's memory and the machine's total.
  • Folder sizes walk every file, so they are measured only when the page asks, at most every 10 minutes. Disk space is a single cheap call.
  • While the module is disabled nothing is measured.

Polling and its cost

The page asks GET /api/v1/server-health/admin/live?since=<last sample> every 5 seconds and gets the new samples only; the answer comes from memory, with no database work. It polls only while the tab is visible, and stops after 15 minutes without mouse or keyboard activity ("Paused", with a Resume button), so a forgotten tab neither loads the server nor keeps a free Render instance awake. Other admin pages do not poll. GET /api/v1/server-health/admin/history?range=24h|7d serves the saved minutes.

What it cannot do

  • Report that the server is down: the page is served by the same server. Use the host's health check (Render calls /health) or an external uptime monitor.
  • Compare several servers: the readings are per process (a Render service with a disk runs one instance).

/health itself stays small and public: status, timestamp, uptime and db, answering 503 when the database fails. Versions, port and cache figures are on the Server Health page only.

Statistics & Analytics

The Stats module provides page-view tracking, visitor analytics, and an ApexCharts dashboard. It creates a page_views table for raw events and tracks visits via server-side middleware.

Features

  • Page View Tracking: Server-side middleware records each page view with timestamp, path, session ID, device type, browser, and OS.
  • Visitor Analytics: Track unique visitors, active sessions, and average pages per session.
  • Interactive Dashboard: The admin dashboard at /admin/stats shows total views, unique visitors, active sessions, and pages per session.
  • Charts: Visualize page views over time (bar + line), top pages (horizontal bar), device types (donut), browsers (donut), and operating systems (bar) using ApexCharts (pinned, served from node_modules at /vendor/apexcharts/).
  • Period Selector: Switch between last 7, 30, 90 days, or 1 year to analyze trends.
  • Admin Settings: Tracking on/off, leaving out staff and bots, and deleting old page views in Admin > Settings > Statistics.
  • Retention: a new install keeps page views for 365 days (Delete page views older than, checked at startup and once a day). An existing install keeps its own choice; when it was never set, page views are kept forever until you choose a limit.
  • Indexes: every report filters by date, so page_views is indexed on (site, date), (site, theme, date) and (date). Reports stay fast as the table grows.

Tracking Middleware

Stats tracking is implemented as middleware in src/core/app.ts. It intercepts GET requests, extracts user agent info (device type, browser, OS), generates a session ID, and stores the event asynchronously in the page_views table. API routes, admin pages, and static assets are excluded from tracking.

Admin Routes

  • GET /admin/stats — Statistics dashboard with charts and metrics

Database Schema

The module's main table is page_views (one row per page view; stats_summary and stats_visitors hold aggregates):

CREATE TABLE IF NOT EXISTS page_views (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  site_id TEXT NOT NULL DEFAULT 'default',   -- the site's name
  theme TEXT NOT NULL DEFAULT '',            -- the theme the page was rendered with
  path TEXT NOT NULL,
  timestamp INTEGER NOT NULL,
  session_id TEXT NOT NULL,
  user_agent TEXT DEFAULT '',
  referrer TEXT DEFAULT '',
  country TEXT DEFAULT 'Unknown',
  device_type TEXT DEFAULT 'desktop',
  browser TEXT DEFAULT 'Unknown',
  os TEXT DEFAULT 'Unknown'
);
-- indexes: (site_id, timestamp), (site_id, theme, timestamp), (timestamp)

How module registration works

The CMF uses a self-registration model: each module declares itself as an AppModule object. After that, routes, views, settings, and DB schema are wired automatically.

Auto-discovery

On boot, src/core/app.ts scans modules/*/init.ts, dynamically imports each file, and registers the exported AppModule. You no longer need to manually import or register modules in core code — just drop a module folder with an init.ts exporting an AppModule, and it appears automatically in the admin.

Boot sequence

createApp() calls autoDiscoverModules() then initModulesState() (modules/registry.ts), which inserts any new module into modules_state as enabled, runs each module's onMigrate and schema SQL (applied once per SHA-256 of the SQL), then, once every module's tables exist, each onSeed hook, and finally each onInit hook.

Module template data hook

Modules can inject their own template variables without touching core code by implementing the optional extendBaseData hook on AppModule. src/core/renderer.ts calls every module's extendBaseData after building the base template context, merging the result into the template data.

Auto-mounted routes

After registration, app.ts loops through all modules and mounts:

  • Public site routes at their declared paths (core modules directly; other modules through the site router, see Sites & Themes)
  • Public API routes (apiRoutes) at /api/v1/<moduleId>/*
  • Admin API routes (adminApiRoutes) at /api/v1/<moduleId>/admin/*, behind the core admin guard
  • Admin views at /admin/<view.path>, behind the same guard

Auto admin config pages

The admin module (settingsTabs() in modules/admin/init.ts) builds the Settings page from every module's admin.settingsFields (one tab named after the module) and admin.settingsSections (one tab per section). General comes first, the other tabs follow in alphabetical order; without ?tab= the page opens on General. A settingsFields tab uses the module's nav icon, or admin.settingsIcon for a module without a menu link (Email Service). Field types: text, number, boolean, textarea, select, checkboxGroup, password, datetime; fields may declare min, max, maxLength and format (email, emails, domains, ips, gaId, timezone). Saving posts to POST /api/v1/admin/admin/settings/save, which validates the tab's fields and writes them to the settings table.

Auto-generated navigation

The renderer builds navigation from module metadata:

  • site.nav drives the public site header nav. Only enabled modules appear.
  • admin.navItem drives the admin sidebar. Every enabled module's links, core or not, form one list by order: Dashboard (0), Sites (5), Themes (6), Pages (7), Media (8), Users (20), Statistics (50), Products (60), Collections (61), Widgets (62), Modules (90) and Settings (91); pick an order to place a new module's link among them. A link with group: 'system' goes to the collapsible System group instead (Cache, Application Logs, Audit Log and Server Health's Server Status, by order). The current page's link is highlighted; a group opens on page load only when the current page is one of its links. Links the user may not open are left out, and so is a group with none (managers and editors see no System group).
  • Disabled modules are automatically excluded from both navs.

So in practice: drop a module folder with an init.ts exporting an AppModule, and its routes, admin nav item, settings tab, DB schema, template data hook, and nav entries all work without further wiring. The make-module.ts script scaffolds this structure.

New module code: Restart server

Modules are discovered once, at startup (Hono cannot add routes once it has answered a request), so a module folder added to a running server, or TypeScript changed by a git pull, is loaded by a restart. Templates, CSS and JavaScript are read live and need none.

Admin > Modules (administrators) has a Server panel (src/core/lifecycle.ts): when the server started, the module folders that are new, changed or removed since then (and changed core code; a new site whose init.ts is comments only is not listed), and a Restart server button. A restart answers the request, stops taking new ones, lets those in progress finish (at most 10 seconds), writes the logs, closes the database and exits; the process manager starts it again. The page waits for /health to answer from the new process, then reloads. Nobody is signed out (sessions are in the database); cached pages are rebuilt, and rate-limit and error-alert counters start again. The restart is recorded in the audit log (server.restart).

The button is disabled, with the reason shown, when:

  • nothing would start the server again: PM2 (pm_id), systemd (INVOCATION_ID; the service needs Restart=always) and Render (RENDER) are detected; for anything else (e.g. Docker with a restart policy) set RESTART_SUPPORTED=true in .env, and false turns it off everywhere. A plain bun run start would stop and stay down, so it gets no restart;
  • APP_ENV=development, unless RESTART_SUPPORTED=true (restart by hand there);
  • a long task is running: a static export, a media upload, sync or cleanup, a theme or widget type upload. The panel names it and checks again every few seconds. A module can register its own long work with const done = beginTask('Label') and call done() when it ends (in a finally);
  • a restart is already in progress.

The same checks run again on the server when the button is pressed (POST /api/v1/admin/admin/server/restart answers 409 with the reasons). On Render, new code arrives with a deploy, which restarts anyway.

Admin Sites Grid

The Admin > Sites page renders its data table with TabulatorJS (v6.5.3, vendored under /vendor/tabulator/). This provides client-side pagination, column sorting, and live search with a consistent admin-styled theme. The grid is initialized in modules/admin/js/sites.js and styled via overrides in modules/admin/css/admin.css. CSS loading order in modules/admin/templates/layout.html was adjusted so admin.css loads after tabulator.min.css, ensuring custom overrides take precedence.

Columns: Name shows the site's title with its folder name below (and the Default badge), sorted by title; Theme shows the theme's display name from Admin > Themes (the page passes a folder-to-name map, themeTitlesJson); then Status, Maintenance (while the module is enabled) and Last Update. Search matches the title, folder name, theme (folder or display name) and contact email.

Future Usage: Adding New TabulatorJS Grids

To create a new TabulatorJS grid for a module, follow the Sites and Widgets pattern:

1. CSS Classes

Use the generic Tabulator toolbar classes in admin.css:

<div class="grid-toolbar">
  <div class="grid-search-wrap">
    <i data-lucide="search" style="width:16px;height:16px;"></i>
    <input id="my-search" class="form-control grid-search" type="search" placeholder="Search..." autocomplete="off">
  </div>
  <span id="my-count" class="badge badge-md badge-gray"></span>
</div>
<div id="my-grid" class="grid"></div>

2. Template Data

Pass data to the template as JSON-escaped strings (like Sites and Widgets):

return {
  itemsJson: JSON.stringify(items).replace(/</g, '\\u003c'),
};

3. JavaScript

Initialize Tabulator in a module JS file:

(() => {
  'use strict';

  let table = null;
  let rows = [];

  function loadItems() {
    try {
      rows = JSON.parse(document.getElementById('my-data').textContent || '[]');
    } catch (error) {
      rows = [];
      showAlert('Unable to load data');
    }
    initializeGrid();
  }

  function initializeGrid() {
    table = new Tabulator('#my-grid', {
      data: rows,
      layout: 'fitColumns',
      height: false,
      pagination: true,
      paginationMode: 'local',
      paginationSize: 25,
      columns: [
        { title: 'Name', field: 'name', widthGrow: 2 },
        // ... more columns
      ],
    });

    table.on('renderComplete', () => {
      if (window.lucide) window.lucide.createIcons();
    });
  }

  // ... bind events, modal handlers, etc.

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', loadItems);
  } else {
    loadItems();
  }
})();

4. Modal Pattern

Use the modal pattern from Sites/Widgets for add/edit dialogs:

<div id="my-modal" class="modal-backdrop hidden">
  <div class="modal-card">
    <div class="modal-header">
      <h2 id="my-modal-title">Modal Title</h2>
      <button class="modal-close" onclick="closeModal()">Close</button>
    </div>
    <div id="my-modal-content" class="modal-body">
      <!-- Form content -->
    </div>
  </div>
</div>

Generic Classes Reference

ClassPurpose
.grid-toolbarToolbar container with search + actions
.grid-search-wrapSearch input wrapper with icon
.grid-searchSearch input with icon padding
.grid-actionsAction buttons container
.grid-cell-stackStacked cell content layout

DataGrids and Modals

All admin list pages should use TabulatorJS for the data grid and a modal overlay for add/edit forms. This is the standardized pattern across Sites, Widgets, and Users.

When to Use

  • Any admin page that lists records with CRUD operations
  • When you need client-side pagination, search, and sorting without page reloads
  • When add/edit forms should open in a modal dialog rather than a separate page

File Structure

modules/<module-name>/
├── init.ts              # Module definition + API routes
├── templates/
│   └── list.html        # Page shell: header, toolbar, grid container, modals
└── js/
    └── list.js          # Tabulator init, search, modal handlers, API calls

Backend: API Routes

Expose a GET /api/v1/<module>/admin/list endpoint (on the module's adminApiRoutes router, so the core enforces the admin role) that returns all records as JSON. Include computed fields the grid needs:

adminApi.get('/list', async (c) => {
  const records = await dbAll('SELECT * FROM table_name ORDER BY created_at DESC');
  return c.json({
    records: records.map(r => ({
      ...r,
      computedField: r.name.slice(0, 2).toUpperCase(),
      isActive: r.status === 'active',
    })),
  });
});

Backend: Admin View Handler

The admin view handler should be simplified — just fetch all records and pass them as JSON to the template. No server-side pagination, search, or sort:

views: [
  {
    path: '/items',
    title: 'Item Management',
    template: path.resolve('modules/my-module/templates/list.html'),
    handler: async (c) => {
      const records = await dbAll('SELECT * FROM items ORDER BY created_at DESC');
      const rows = records.map(r => ({
        ...r,
        initials: r.name.slice(0, 2).toUpperCase(),
        isActive: r.status === 'active',
      }));

      return {
        records: rows,
        recordsJson: JSON.stringify(rows).replace(/</g, '\\u003c'),
      };
    },
  },
]

Template: list.html

The template is a shell with a header, toolbar, grid container, and modals. Use the same structure as Sites, Widgets, and Users:

<div class="admin-page-header">
  <div>
    <h1 class="admin-page-title">Items</h1>
    <p class="admin-page-desc">Manage items.</p>
  </div>
  <button class="btn btn-primary" onclick="openModal()">+ Add Item</button>
</div>

<div class="card p-0 overflow-hidden">
  <div class="grid-toolbar">
    <div class="grid-search-wrap">
      <i data-lucide="search" style="width:16px;height:16px;"></i>
      <input type="search" id="item-search" class="form-control grid-search" placeholder="Search items..." autocomplete="off">
    </div>
    <span id="item-count" class="text-muted text-sm badge badge-md badge-gray">0 items</span>
  </div>
  <div id="items-grid"></div>
</div>

<div id="item-modal" class="modal-backdrop hidden" onclick="if(event.target === this) closeModal()">
  <div class="modal-card">
    <div class="modal-header">
      <h2 id="item-modal-title" class="modal-title">Add Item</h2>
      <button class="modal-close" type="button" aria-label="Close" onclick="closeModal()">
        <i data-lucide="x" style="width:20px;height:20px;"></i>
      </button>
    </div>
    <div id="item-modal-content" class="modal-body">
      <!-- Form content -->
    </div>
  </div>
</div>

<script id="items-data" type="application/json">{{{ itemsJson }}}</script>
<script src="/modules/my-module/js/items.js"></script>

JavaScript: items.js

Follow the same IIFE pattern as Sites, Widgets, and Users. Key functions:

(() => {
  'use strict';

  let table = null;
  let rows = [];

  function showAlert(message, type) {
    // ...
  }

  function openModal(item) {
    // load form, show modal
  }

  function closeModal() {
    // hide modal
  }

  function initializeGrid() {
    // Tabulator setup
  }

  // event bindings, modal handlers, etc.

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Scope & Limitations

Carnival3 is a flexible foundation for conventional web apps, but it is not a one-size-fits-all framework. Knowing its fit up front will save rework.

Well-suited for

  • Content / marketing sites, blogs, and documentation (server-rendered, SEO-friendly)
  • CRUD applications, internal tools, dashboards, and admin panels
  • Small-to-medium SaaS (auth + users + modules + settings; integrate payments, etc. as modules)
  • Catalog / e-commerce (the bundled products module is a working sample)
  • Multi-feature apps composed from self-contained modules

Current limitations / trade-offs

  • Server-rendered HTML + vanilla JS, no SPA framework. Excellent for forms, content, and admin UIs; a poor fit for heavily interactive client experiences (real-time collaboration, rich canvas apps, app-like SPA UX). You can add JavaScript "sprinkles", but it is not React/SPA.
  • Single process, SQLite by default. Fine up to moderate load. Sessions are in the database (several instances could share them with Turso Cloud), but the page cache (on disk), the settings memo, the active-site cache and the rate limiter are per process, so several instances would serve different cached pages and count limits separately. Run one process, or move those to a shared store first.
  • No built-in realtime / WebSockets, job queues, or background workers. All are addable, but not included.
  • Auth is session-cookie based with four roles (administrator, manager, editor, user) and a permissions matrix per area and action (Admin > Users > Roles & Permissions). No two-factor sign-in yet.
  • It is a CMF, not a framework — you still build the actual application logic on top.

Notes / known limitations

  • bun create one-command scaffolding is not wired up; install via clone + bun install.
  • Not built yet: content revisions (undo), scheduled publishing, site search, content in several languages (only the interface text is translatable), two-factor sign-in, RSS feeds. Planned work is in TODO.md (widget areas, theme customizer, log permissions, changing one's email address).
  • Carnival3 is Bun-only. Modules are imported from modules/*/init.ts at runtime, so Node.js hosts and bun build --compile binaries are not supported.