# Previews

> Previews is a fast, lightweight, edge-native HTML preview and multi-page web app hosting service built on Cloudflare Workers, Cloudflare D1 (SQLite metadata), and Cloudflare R2 (asset storage).

Previews enables developers and automated coding agents to publish static web projects to isolated subdomains (`<slug>.previews.kartikarora.me`), manage immutable version histories, view unified diffs across versions, and secure previews with optional password protection.

## Documentation

- [How Previews Works](/how-it-works.md): Comprehensive guide to Previews architecture, immutable versioning, edge routing, plain-text diffing, and password authentication.
- [Full Documentation](/llms-full.txt): Complete aggregated documentation, API reference, and architecture details in a single markdown document.

## Core Features & Architecture

- [Immutable Versioning](/how-it-works.md#immutable-versioning): Every publish creates an incremented version (v1, v2, v3...) stored at deterministic R2 keys (`projects/<slug>/versions/<n>/<path>`).
- [Password Protection](/how-it-works.md#password-protection): Optional per-project password protection with HMAC-SHA256 signed session cookies valid for 7 days.
- [Plain-Text Diff Viewer](/how-it-works.md#plain-text-diff-viewer): Plain-text unified diffs between any two versions (`/<versionA>..<versionB>`, e.g. `/1..2`).
- [Subdomain Isolation](/how-it-works.md#subdomain-isolation): Each project is served from its own isolated subdomain with clean relative asset resolution.
- [Mutable Slugs](/how-it-works.md#mutable-slugs): Project slugs can be changed at any time with immediate edge routing updates.

## API Reference

- [List Projects](/how-it-works.md#api-reference): `GET /api/projects` - Retrieve all preview projects for the authenticated user.
- [Create Project](/how-it-works.md#api-reference): `POST /api/projects` - Create a new preview project with optional password and HTML document.
- [Publish Version](/how-it-works.md#api-reference): `POST /api/projects/:slug/versions` or `POST /api/projects/:slug/edit` - Publish a new version to an existing preview.
- [Get Usage Analytics](/how-it-works.md#api-reference): `GET /api/projects/:slug/usage` - Retrieve view counts, request rates, and bandwidth metrics.


---

# How Previews Works

Previews is an edge-native HTML and web application preview hosting service built entirely on Cloudflare's serverless stack: Cloudflare Workers, Cloudflare D1 (SQLite database), and Cloudflare R2 (object storage).

---

## 1. Architecture Overview

- **Routing & Edge Serving**: A single unified Cloudflare Worker (`worker-app`) routes both the dashboard at `previews.kartikarora.me` and preview subdomains at `*.previews.kartikarora.me`.
- **Database (D1)**: Stores project records, versions, asset manifests, access tokens, and per-project request rate counters.
- **Storage (R2)**: Stores all static files (HTML, CSS, JavaScript, images, web fonts) under deterministic key prefixes.
- **Security & Sessions**: Google OAuth 2.0 SSO for dashboard access; HMAC-SHA256 signed session cookies (`preview_auth`) for password-protected previews.

---

## 2. Immutable Versioning

Every time you update a project (via dashboard paste, HTML upload, or API request), Previews creates a new sequential version (`v1`, `v2`, `v3`...):

1. Assets are written to R2 under the key pattern:
   `projects/<slug>/versions/<versionNumber>/<filePath>`
2. An entry is created in the `versions` table in D1 with the version number, file count, and byte size.
3. Each individual file is indexed in the `assets` table in D1.
4. The project's `current_version` pointer is updated to point to the newly published version.

Historical versions are preserved permanently in R2 object storage.

---

## 3. Password Protection

Password protection is optional for projects on Previews:

- Passwords are encrypted with bcrypt before storing in D1.
- When a viewer enters the correct password, Previews sets a signed HMAC-SHA256 cookie:
  `preview_auth=<projectId>:<passwordVersion>:<expiresAt>:<signature>`
- The cookie is valid for 7 days. Changing or removing the project password increments `password_version`, immediately invalidating all existing viewer sessions.
- When no password is set (null), visitors can access the preview directly without a password prompt.

---

## 4. Plain-Text Diff Viewer for LLMs & Agents

Previews includes a built-in plain-text edge diff engine optimized for LLMs and automated tools:

- **URL Pattern**: `https://<slug>.previews.kartikarora.me/<versionA>..<versionB>` (e.g. `/1..2`)
- **Format**: Plain text (`text/plain; charset=utf-8`) with markdown headers and standard unified diff blocks (no HTML, no CSS, no JavaScript).
- **Functionality**:
  - Compares the asset trees of both versions in D1.
  - Summarizes total changed, added, removed, and modified files.
  - Fetches text files from R2 and computes unified line-by-line diffs (`+` / `-`).
  - Automatically normalizes version ordering so `/1..2` and `/2..1` produce consistent output.

---

## 5. Subdomain Routing & Isolation

- **Live Preview URL**: `https://<slug>.previews.kartikarora.me/`
- **Historical Snapshot URL**: `https://<slug>.previews.kartikarora.me/<versionNumber>/` (e.g. `/1/`)
- **Relative Path Resolution**: Relative links (e.g. `./app.js`, `../css/styles.css`, `/images/logo.png`) resolve naturally within the project's root.

---

## 6. REST API Reference

### Create Project
- **Endpoint**: `POST /api/projects`
- **Content-Type**: `multipart/form-data`
- **Form Fields**:
  - `name` (string, required): Project display name.
  - `password` (string, optional): Password for preview protection.
  - `slug` (string, optional): Subdomain slug (alphanumeric and hyphens).
  - `html` (file / blob, required): HTML content or file.

### Publish New Version
- **Endpoint**: `POST /api/projects/:slug/versions` or `POST /api/projects/:slug/edit`
- **Content-Type**: `multipart/form-data` or `application/json`
- **Payload**: Form data with `html` field or JSON with `{ "html_content": "..." }`.

### Usage & Analytics
- **Endpoint**: `GET /api/projects/:slug/usage`
- **Response**: JSON containing request counts, bandwidth, and rate limit status.

