# How Hatch fits together

## The layers

```
apps/web  apps/desktop  apps/mobile        shells: open a vault, give a FileSystem and settings
            \      |      /
            packages/app                    the UI: store, components, styles
       /       |        |        \
  editor   plugin-api  publish  canvas ...   features as packages
       \       |        |        /
  text (render, sanitize, diff)              the text engine
           |
  markdown   vault   theme   platform        the base: files, parsing, tokens
                                    \
                          apps/server        optional: accounts, sync, hosting, email
```

A package only imports from packages below it. Shells are thin. Anything that works the same on every platform belongs in a package.

See `docs/tree.md` for the file tree (where new notes and folders go, empty folders) and tag colors.

## A note's life

1. The shell opens a folder and gives `@hatch/vault` a `FileSystem` (Node fs on desktop, the File System Access API or memory on web, Capacitor on mobile).
2. `Vault` lists files and indexes every `.md` file: title, links, tags, frontmatter, search text.
3. `NoteView` opens the note in the editor. `NoteSync` saves edits (debounced), notices outside changes by polling, and keeps both versions when it finds a real conflict.
4. `@hatch/markdown` keeps unchanged blocks byte for byte, so opening and saving never reformats a file.

Canvas boards (`.canvas`) open in `CanvasView` instead, with their own save path.

## Opening fast

The app should show the last note at once, with no loading screen on repeat visits.

- **Web vault.** The browser keeps notes in the origin private file system (OPFS). The starter notes are copied in once.
- **Saved index.** After changes, the vault index is saved to IndexedDB (`snapshots.ts`). Next time `Vault.fromSnapshot` opens from it, then `syncFromDisk` checks the disk in the background. Plugins and themes found on disk are reloaded if they changed.
- **Service worker.** `apps/web/public/sw.js` serves the app shell from cache and refreshes it in the background, so the app also opens offline.
- **Nothing waits on the network.** The account check runs alongside opening the vault.
- **Loading state.** It only appears if opening takes longer than 400ms.
- Reopening the vault that's already open skips the saved index and reads the disk.

`scripts/e2e-instant.py` checks all of this. Repeat visits show the note in under 100ms locally.

## Plugins

`PluginHost` (in `plugin-api`) runs built-in and community plugins on one API: commands, panels, status items, settings tabs, editor extensions and vault access, each behind a permission.

Community plugins run in a sandboxed iframe with an opaque origin and talk to the host over a private message channel. They see only what their permissions allow.

## Server

One Hono app (`apps/server/src/app.ts`) with SQLite for rows and a blob store for file bytes:

| Area | File | Notes |
|---|---|---|
| Features | `features.ts` | The catalog: every feature's entitlement, limits, migrations and site paths. Plans read this. |
| Schema | `db.ts` | Numbered migrations (`pragma user_version`). Every row belongs to a site or vault, and goes with it. Sites and vaults go with their user. |
| File bytes | `blobs.ts` | SQLite table by default, Cloudflare R2 when configured. Content-addressed keys, a read cache, and a background move to R2. |
| Inbox | `inbox.ts` | One table for what visitors send (applications, form responses). Drained into the vault by the owner's app. |
| Accounts | `auth.ts` | Better Auth, bearer tokens. Email confirmation when mail is set up. Deleting an account removes its sites, vaults and files. |
| Sync | `sync.ts` | Files keyed by path and content hash. Optionally end-to-end encrypted, so the server stores only ciphertext. |
| Sharing | `sharing.ts` | Shared vaults: people the owner invited by email edit a synced vault from their own accounts. Their writes count toward the owner's storage. Access follows the owner's plan. |
| Hosting | `sites.ts` | Static sites from a zip. Each site gets its own origin (`<slug>.<HATCH_SITES_HOST>`). Public, link or invite visibility. |
| Abuse | `abuse.ts` | Reports from visitors, takedowns by the server's admin (signed review links in email, or `admin.ts` from the shell). A site that's down answers 451 everywhere. |
| Email updates | `newsletter.ts` | Double opt-in, issues, one-click unsubscribe |
| Sending | `mail.ts` | Resend, Postmark, or a log for development |
| Plans | `plans.ts` | Free, Pro and Careers: each plan's entitlements, lower limits and price. Data only. |
| Billing | `billing.ts`, `stripe.ts` | The account's plan (`account_plan`), checkout, the portal and the webhook. The payment provider is behind `BillingProvider`, so another one can replace Stripe. |

Requests to a site's host are answered by `sitesHostGate` before any API route runs.

### Features are modules

Each feature (sync, live, sites, newsletter, forms, careers, votes) has the same shape, so it can be sold, priced and turned on per plan:

- **Catalog entry** in `features.ts`: title, the plan entitlement that turns it on, the features it needs, its limits (default plus the env var that changes it), its migrations and the site paths it answers. Data only.
- **Module** in the feature's own file: `syncModule`, `liveModule` and `sitesModule` mount API routes. Features on sites (`newsletterModule`, `formsModule`, `careersModule`, `votesModule`) are site modules: owner routes under `/api/sites/:id/`, a `visit` handler for their site paths, and the bytes they keep for a site, which count toward its owner's storage.
- `app.ts` mounts the modules whose store is passed in. A feature that's off has no routes, and its site paths answer 404, never a file.

A new feature adds a catalog entry, puts its migrations there (ids are one sequence with `db.ts`), and exports a module.

### Plans

Every module gets `ctx.plans` (an `Entitlements`). Before serving a paid feature it asks `plans.has(userId, feature)`, and reads limits with `plans.limit(userId, feature, key)`. A refusal answers 403 with `code: 'plan'` and the feature (`planRequired`), with a message that names it.

- Without billing (`STRIPE_SECRET_KEY` unset) `plans` is `ALL_ENTITLED`: every account gets everything, at the server's limits.
- With billing, the account's plan comes from `account_plan`, which only the provider's webhook changes. The webhook reads the subscription again from the provider, because events arrive late and out of order.
- A site feature the owner's plan lacks answers 404 at its site path, like a feature the server doesn't run. Unsubscribe links always work. Owners keep reading and clearing their inboxes after a downgrade.
- Deleting an account cancels its subscription first. If that fails, the account stays.

What the server stores, and why: only what has to be online while the owner's devices are off. Accounts, sync copies, published files, inboxes, subscribers and votes. Content lives in the vault. A new feature adds a numbered migration, keys its rows to a site or vault, keeps bytes in the blob store, and uses the inbox if visitors send it something.

## Publishing

`buildSite` (in `publish`) turns chosen notes into static files with relative links: docs, blog, portfolio, careers or roadmap. The app either downloads them as a zip or uploads them to the server. Only selected notes and the files they use leave the vault.

The last step names static files by their content hash and gives images WebP copies with `srcset`, `width` and `height` (`fingerprint.ts`). The server caches hashed files for a year and revalidates pages, which is what a CDN in front needs.

## Testing

- Unit tests sit next to the code (`*.test.ts`).
- Browser suites in `scripts/*.py` drive a production build with Playwright. Each prints PASS or FAIL per check.
- `scripts/check.sh` runs everything.
