# 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.
