# @frontierjs/sierra

> Vite-native meta-framework built on Mesa

Latest version **0.1.15** (published 2026-11-19) · MIT license · 0 weekly downloads

## Install

```sh
npm install @frontierjs/sierra
pnpm add @frontierjs/sierra
yarn add @frontierjs/sierra
bun add @frontierjs/sierra
```

Provides the command `sierra`.

## Health

**Score 60/100 (C)** — status: active.

Positive: esm support; no vulnerabilities; recently updated; high maintenance score.

Warnings: low downloads; no types; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.1.15 |
| Published | 2026-11-19 |
| First published | 2026-08-11 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM |
| Dependencies | 1 |
| Unpacked size | 1.7 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Maintainers | jdkdev |

## Links

- npm: https://www.npmjs.com/package/@frontierjs/sierra
- Repository: https://github.com/frontierJS/frontierjs
- npm.io page: https://npm.io/package/@frontierjs/sierra

## Dependencies (1)

- [@frontierjs/toolbelt](https://npm.io/package/@frontierjs/toolbelt.md) 0.1.15

## Recent versions

- 0.1.15 (latest) — 2026-11-19
- 0.1.14 — 2026-11-18
- 0.1.12 — 2026-11-05
- 0.1.10 — 2026-11-02
- 0.1.9 — 2026-10-30
- 0.1.8 — 2026-10-20
- 0.1.7 — 2026-09-18
- 0.1.6 — 2026-09-13
- 0.1.5 — 2026-09-10
- 0.1.4 — 2026-09-08
- 0.1.3 — 2026-08-16
- 0.1.2 — 2026-08-14
- 0.1.0 — 2026-08-11

## README

# @frontierjs/sierra

The UI realm of FrontierJS. Sierra turns a directory of Mesa components into a routed
application: it scans `src/routes/`, emits a route table, produces the whole Vite
config, and binds the running app to a Junction API.

```
db/schema.lite  ──►  Junction (API)  ──►  Sierra (UI)
      │                    │                  │
 generateJsonSchema    services/WS      routes + resources
      └──────────────────────────────────────►┘
                  registerSchemas()
```

Sierra sits at the end of the dependency chain — `Litestone ← Junction ← Sierra` — and
never the reverse. Mesa is the component substrate underneath it.

**Status:** pre-1.0. `bun run test` passes, typecheck clean.
All three targets are built and driven in a real browser. The SPA target is solid and
verified end-to-end; `static` prerendering works and its pages are **interactive** —
see [Islands](#islands--making-a-static-page-interactive), verified by clicking a
prerendered button in headless Chrome; `widget` builds one self-contained IIFE per
`.mesa` file — see [Build targets](#build-targets) — and `bun run test:widgets` loads
two of them **cross-origin** onto a host page with hostile CSS.

There is a runnable app in [`example/`](example/) — a real Junction API over real SQLite,
with a form generated entirely from `db/schema.lite`. The whole app is driven in headless
Chrome — navigation, sign-in, form submit, delete — with the console watched for errors;
see its [README](example/README.md) for what was found that way.

```bash
cd example && bun run api    # :8130
cd example && bun run dev    # :8030
```

---

## Installation

```bash
bun add @frontierjs/sierra @frontierjs/mesa
bun add -d vite
```

Sierra declares `@frontierjs/mesa` as a required peer and `@frontierjs/junction` and
`@frontierjs/litestone` as optional ones. Install what you use:

| Package | Needed for |
| --- | --- |
| `@frontierjs/mesa` | always — the compiler and runtime |
| `@frontierjs/junction` | `sierra/resource`, `sierra/presence` |
| `@frontierjs/litestone` | schema seeding from `db/schema.lite` (optional; absence is not an error) |

---

## Quick start

**Sierra owns `web/`, and only `web/`.** A FrontierJS app puts one directory at the root
per realm — `db/` (Data), `api/` (API), `web/` (UI) — so every Sierra file, `config/` and
`src/` included, lives under `web/`. That is also why schema auto-detection looks at
`../db/schema.lite`: the schema is a sibling of `web/`, not something inside it. The full
layout is in the [root README](../../README.md#project-structure).

Inside `web/`, every sub-project follows the same six-folder shape — `config/` to
configure it, `src/` to build it, `public/` for static assets, `test/` for tests, `dist/`
for output, `deploy/` for shipping:

```
my-app/
├── db/
│   └── schema.lite             ← seeds the API and the UI both
├── api/                        ← Junction — a peer of web/, not a parent
└── web/                        ← everything below here is Sierra's; the Vite root
    ├── index.html
    ├── config/
    │   ├── vite.config.js      ← configuration lives in config/
    │   ├── sierra.config.js
    │   └── routes.js           ← generated, do not edit
    ├── public/                 ← static assets, copied verbatim
    ├── src/
    │   ├── main.js
    │   ├── App.mesa
    │   └── routes/
    │       ├── _module.mesa
    │       ├── index.mesa
    │       └── blog/
    │           ├── [slug].mesa
    │           └── [slug].meta.js
    ├── test/
    └── dist/                   ← build output
```

Vite runs with `web/` as its root and the config named explicitly:

```bash
cd web && vite -c config/vite.config.js
cd web && vite build -c config/vite.config.js
```

Paths in `sierra.config.js` (`routesDir`, `outDir`, `routeTable.output`) are relative to
the Vite root — `web/` — never to `config/` and never to the app root.

**`config/vite.config.js`**

```js fragment
import { defineConfig } from 'vite'
import { createSierraViteConfig } from '@frontierjs/sierra/build'
import sierraConfig from './sierra.config.js'   // sibling — both live in config/

export default defineConfig(createSierraViteConfig(sierraConfig))
```

**`config/sierra.config.js`**

```js
export default {
  target:        'spa',
  routesDir:     'src/routes',
  trailingSlash: 'always',

  junction: {
    // Where there is no page; a page calls its own origin (see Resource below)
    url:       'http://localhost:8000',
    apiPrefix: '/api',       // must match the API's config.apiPrefix
    tokenKey:  'myapp_token',
  },
}
```

**`index.html`**

```html
<div id="app"></div>
<script type="module" src="virtual:sierra"></script>
```

`virtual:sierra` boots the router, Junction, theme and analytics, imports
`src/main.js` if there is one, and mounts `src/App.mesa` into `#app` — or the bare
`RouterView` when there is no `App.mesa` (`FJS-D1085`). An `index.html` that still
loads `/src/main.js` is refused at build.

**`src/main.js`** — optional, the app's side-effect imports. A top-level `await` is
refused: a build would run main.js's imports before the boot. A first render that
must wait goes in `App.mesa`, as an `{#if}`.

```js fragment
import '@frontierjs/css'
```

**`src/App.mesa`**

```html
<script>
  import { RouterView } from '@frontierjs/sierra/router'
</script>

<RouterView />
```

**A route that throws while it renders is replaced, not left half-drawn.** Every
layout and page renders inside a `<mesa:boundary>`, so the nearest level shows a
failed state and the layouts above it stay standing (`FJS-D376`). The default is a
plain message and a *Try again* button; an app supplies its own through `failed`:

```html
{#snippet failed(error, reset)}
  <p>This page could not be shown.</p>
  <button onclick={reset}>Try again</button>
{/snippet}

<RouterView {failed} />
```

A prerendered route does not get this: a throw there fails the build (`FJS-D377`).

Then `vite -c config/vite.config.js` for dev and `vite build -c config/vite.config.js`
for production.

> **The browser gets three keys of `sierra.config.js`, as JSON.** `virtual:sierra`
> writes `junction`, `analytics` and `theme` into the app's entry by value and imports
> nothing else of the config, so a plugin that reads the disk stays in Node. A function
> anywhere under those three keys is refused at startup, naming its key path
> (`FJS-D552`); a custom analytics provider is a module path instead.

---

## Routing

The route table is derived from the file tree. Nothing is registered by hand.

### File roles

| Pattern | Role | Result |
| --- | --- | --- |
| `index.mesa` | route | the folder's index — contributes no URL segment |
| `about.mesa` (lowercase) | route | `/about/` |
| `_module.mesa` | layout | wraps every descendant route |
| `Sidebar.mesa` (PascalCase) | component | co-located, never routed |
| `_helper.mesa` (`_` prefix) | component | co-located, never routed |
| `about.meta.js` | companion | `meta` / `load` / `getStaticPaths` for `about.mesa` |
| `automations.mount.js` | mount | default-exports a directory (a `URL` or absolute path, normally re-exported from the package that owns it); its files route as if they sat in `automations/` beside the mount (`FJS-D282`) |
| anything else | ignored | — |

`.md` files route exactly like `.mesa` — the Mesa compiler handles both, and fenced code
blocks are escaped before compilation.

### Path syntax

| File | URL | Notes |
| --- | --- | --- |
| `leads/index.mesa` | `/leads/` | |
| `leads/[leadId].mesa` | `/leads/:leadId/` | `page.params.leadId` |
| `[...404].mesa` | `/*` | catch-all — `page.params['404']` is the unmatched path |
| `docs/[...rest].mesa` | `/docs/*` | catch-all below a folder — `/docs/a/b/` gives `page.params.rest` `'a/b'`, `/docs/` gives `''`; any static or `[param]` sibling wins first |
| `(auth)/login.mesa` | `/login/` | `(group)` folders are organizational — zero URL impact |
| `account/settings/index.mesa` | `/account/settings/` | |

Trailing slashes are appended by default (`trailingSlash: 'always' | 'never' | 'preserve'`).
A file and a folder with the same name (`leads.mesa` + `leads/`) is a build error.

### Layouts

`_module.mesa` wraps every route beneath it, and layouts nest. A layout renders its child
through `<slot />`:

```html
---
siteName: My App
---
<script>
  import { page, isActive } from '@frontierjs/sierra/router'
  $: (page.siteName, page.route)
</script>

<header>{page.siteName}</header>
<main><slot /></main>
```

Layouts are loaded lazily — only the chain a route actually needs is fetched, and the
chain is complete before the route commits. `reset: true` in a route's frontmatter opts
it out of all layouts.

### Frontmatter

Frontmatter is a block at the top of a `.mesa`/`.md` file, written in the YAML subset that [`@frontierjs/toolbelt/frontmatter`](../toolbelt/README.md#frontmatter--what-a----block-means) reads: no anchors, aliases or tags, and a date stays a string. It is merged in this order, with
the rightmost winning:

```
layout _module.mesa frontmatter → layout _module.meta.js → route .meta.js → route frontmatter → system flags
```

Keys Sierra acts on:

| Key | Effect |
| --- | --- |
| `reset: true` | render this route with no layout |
| `render: static` | under `target: 'static'`, the page MUST prerender — one the build cannot prerender fails it |
| `render: spa` | under `target: 'static'`, never prerendered — the browser renders it |
| `redirect: /path/` | navigating here redirects; also emitted to `_redirects` |
| `status: draft` | excluded from `published` and `indexed` |
| `robots: noindex` | excluded from `indexed` and the sitemap |

Everything else is yours, and is spread onto `page` — `siteName: My App` becomes
`{page.siteName}`. System flags (`dynamic`, `spread`, `isIndex`) are added by the scanner.

---

## The `page` object

One import, one object, everything about the current route. It is **not** a signal — it is
a plain object, and components make the fields they use reactive with a `$:` path watch
(Mesa RULE 43):

```html
<script>
  import { page } from '@frontierjs/sierra/router'
  $: (page.params, page.data)
</script>

<h1>{page.title}</h1>
<p>{page.params.slug}</p>
{#if page.error}<p class="error">{page.error.message}</p>{/if}
```

**A list that lives in its URL.** `query` and `directives` are the same split the
API realm makes — filters, and how much of the answer in what order — over the same
table, so the pair goes straight into a call with nothing to translate:

```html
<script>
  import { page } from '@frontierjs/sierra/router'
  import { orders } from '@/resources/Order.mesa'

  const list = orders.tethered()      // page.query and page.directives ARE its state
</script>
```

Filtering, sorting and paging then survive a reload, a back button and a pasted link,
because the URL is where they live. `setParams(obj)` and `updateParams(fn)` write them.
The `$` is transport syntax and reaches neither field (Invariant 10).

Router-owned fields — these are reserved, and the scanner warns if frontmatter shadows one:

| Field | Value |
| --- | --- |
| `pathname` | current pathname |
| `search` | current query string |
| `hash` | the fragment, leading `#` — or `''` |
| `params` | path params — `/leads/:leadId/` → `{ leadId }`. Path captures only |
| `query` | the URL's filters, coerced — `?status=active&tier=3` → `{ status: 'active', tier: 3 }` |
| `directives` | the URL's `$` params, structured — `?$limit=20&$orderBy=-name` → `{ limit: 20, orderBy: '-name' }` |
| `meta` | the raw frontmatter object, un-spread |
| `route` | the matched route node |
| `pending` | the in-flight route during navigation, else `null` |
| `data` | whatever the route's `load()` returned |
| `error` | the error `load()` threw, else `null` |
| `slots` | named slots registered via `provideSlot()` |

`page` replaced eight separate signals (`params`, `activeRoute`, `meta`, `data`, …). The
old names are gone.

**`title` is NOT one of them, and it does two jobs.** It stays an ordinary
frontmatter key spread onto `page`, so `{page.title}` renders in a heading as
every example here shows — and the router also writes it to `document.title` on
every navigation, which is the tab, the bookmark, the history entry and what a
screen reader announces on arrival. The sources are the two the static target
reads, in the same order: `head({ params, data, url })` off the route's `.meta.js`
companion first, then frontmatter, then whatever `index.html` booted with for a
route that declares neither. Nothing is templated and no site name is appended —
the static half composes neither, and an app wanting `Page · Acme` says so in
`head()`, the one place that can see both.

---

## Navigation API

```js
import {
  goto, back, forward, url, isActive, getDirection,
  setParams, updateParams,
  beforeNavigate, afterNavigate,
  prefetch, provideSlot,
} from '@frontierjs/sierra/router'
```

| Call | Behavior |
| --- | --- |
| `goto(path, query?, { scroll, replace, directives })` | navigate. `directives` is `page.directives` shaped and unprefixed; the router joins it to the URL as `$` params, so a page never spells one. Resolves `true` when it committed, `false` when a guard cancelled, the route failed to load or a newer navigation won — never rejects |
| `back()` / `forward()` | history |
| `reload(path?, query?)` | the whole app again from the code on disk, at `path` (where it is, by default) — a page load, or under `fli dev:tui` a new shell process |
| `url(path, query?)` | build a URL with the configured trailing-slash policy |
| `isActive(path, { exact })` | prefix match by default. **Name `page.route` in the expression too** — `aria-current={(page.route, isActive('/leads/')) ? 'page' : null}` — or the call is evaluated once at mount. Mesa reads dependencies out of the expression text, and the route read happens inside `isActive`, where it cannot see it |
| `setParams(obj)` | replace all query params (`replace: true`, no scroll) |
| `updateParams(fn)` | merge query params through a function |
| `getDirection()` | `'next' \| 'prev' \| 'first'` from history indices |
| `prefetch(path)` | preload a route's chunk and data programmatically |

### Guards and hooks

```js fragment
beforeNavigate(async ({ from, to }) => {
  if (to.pathname.startsWith('/admin/') && !isAdmin()) return '/login/'  // redirect
  if (unsavedChanges) return false                                    // cancel
  return true
})

afterNavigate(({ from, to }) => trackPageview(to.pathname))
```

Both return an unsubscribe function. Guards run on the boot navigation too — the initial
`_navigate` is deferred by one microtask precisely so guards registered during app mount
are in place before it runs. A guard therefore protects a direct page load and a refresh,
not just client-side navigation.

**They run on the Back button as well.** A refusal there puts the address bar back where
it was, because the browser has already moved by the time popstate fires and a URL naming
the page the guard just declined is the same lie as no guard at all. A redirect must be a
path on this origin, and ten redirects without landing is reported as a loop rather than
recursed.

### Prefetching

Add the attribute to a link:

```html
<a href="/blog/" prefetch>immediate</a>
<a href="/blog/" prefetch="hover">on mouseenter / touchstart</a>
<a href="/blog/" prefetch="visible">on IntersectionObserver entry</a>
```

Prefetch loads both the route chunk and its `load()` payload. Payloads are cached per URL,
capped at 32 entries, and expire after 30s.

A prefetched `load()` runs with the same `fetch` a navigated one does — `sierraFetch`,
which attaches the session token — so a protected route prefetches as the person who is
signed in. And because a payload is an answer to *what may this person see*, the cache is
dropped on any change of identity — a sign-in, a sign-out, a mid-session 401 — so
prefetching cannot serve one identity's data to another. The route chunks survive that,
being nobody's in particular. **A route the router would never render at that URL is not
prefetched**: one declaring `redirect` or `spread` is skipped, and guards are deliberately
not run on hover, since they are app functions that may await, redirect and have side
effects.

### Named slots

A page pushes content up into its layout. Both sides are compile-time rewrites — you
write markup, not snippet plumbing:

```html
<!-- route: src/routes/blog/[slug].mesa -->
<mesa:slot name="sidebar">
  <nav>…</nav>
</mesa:slot>

<h1>{page.title}</h1>
```

```html
<!-- layout: src/routes/blog/_module.mesa -->
<aside><slot name="sidebar">No sidebar for this page.</slot></aside>
<main><slot /></main>

{#if $slots.sidebar}<p>this page has a sidebar</p>{/if}
```

`<slot />` is the default slot (the route itself), `<slot name="X">` a named one with
optional fallback content, and `$slots` a derived record of which named slots the current
page provided. The underlying `provideSlot(name, snippetFn)` is exported from
`sierra/router` if you need to register a slot imperatively.

A named layout slot currently emits a benign Mesa compiler warning —
`'__slot_sidebar' is already declared` — because the rewrite emits both a watch and an
assignment for the same local. The build succeeds and the slot works.

---

## Data loading

A route gets data from a co-located `.meta.js` companion:

```js
// src/routes/blog/[slug].meta.js

export const meta = { section: 'blog' }        // merged into frontmatter

export async function load({ params, url, meta, fetch }) {
  const res = await fetch(`/posts/${params.slug}`)
  if (!res.ok) throw new Error('Post not found')
  return res.json()                             // → page.data
}

export async function getStaticPaths() {        // static builds only
  return [{ slug: 'hello' }, { slug: 'world' }]
}
```

- `fetch` is `sierraFetch` — it attaches the session automatically, so the page never
  needs to know whether Junction is wired. **It attaches it to the app's own origin and
  to nothing else**: a relative URL is the app's by construction, and an absolute one is
  checked against the page's origin, the API's and the configured `baseUrl`. A page
  geocoding a postcode with it is not handing that vendor a replayable session. In cookie
  mode there is no token to attach and the request carries `credentials: 'include'` to
  that same audience instead.
- **`url` is a STRING — the path plus the search (`'/surveys/?status=open'`) — never a
  `URL`.** `url.search` is therefore `String.prototype.search`, a function, and a redirect
  built from it carries no query; read the query off the string (`url.split('?')[1]`,
  or `new URL(url, 'http://x').searchParams`). A static build hands `load()` and `head()`
  the page's path alone, since a prerendered page has no query.
- Returning a string starting with `/` performs a redirect.
- A thrown error lands in `page.error` and the router **stays on the route** so the page
  can render its own error state. Data failures are not routing failures — there is no
  redirect to the catch-all.
- `load()` runs after the component chunk and the layout chain resolve, and the prefetch
  cache is checked first.

---

## Junction binding

```js
import {
  status, session, signIn, signOut, getClient, whenReady,
  createResource, paletteSource,
} from '@frontierjs/sierra/resource'
```

`initJunction()` is called for you by `virtual:sierra` whenever `junction.url` is set. It
is synchronous — boot is never blocked on a WebSocket handshake. `whenReady` is there for
the rare caller that specifically needs the socket; service calls made before it resolves
simply take the HTTP path.

**A page calls its own origin, and a build that is not proxied names the API with
`FRONTIER_PUBLIC_API_URL`.** `virtual:sierra` hands the client `import.meta.env.FRONTIER_PUBLIC_API_URL ||
location.origin`, decided in the page. `junction.url` in the config is the answer where there
is no page — the terminal shell, a prerender — and is what turns the client on. The config is
evaluated in Node and reaches the browser as JSON (`FJS-D552`), so a `typeof location` guard
there always takes its fallback; that is why the config cannot say *the page's origin*
itself (`FJS-D1042`).

The page's origin is right while Vite in dev, or nginx in `fli deploy`, proxies `/api` and
`/ws` to the API. An API on an origin of its own — `api.example.com` beside
`app.example.com` — and a build a native shell bundles, where the page is
`tauri://localhost`, have no proxy, so every call would go to a host with no API on it:
`FRONTIER_PUBLIC_API_URL=https://api.example.com bun run build`. Vite inlines the value: Sierra sets `envPrefix` to `['VITE_', 'FRONTIER_PUBLIC_']` (`ENV_PREFIX` from `@frontierjs/sierra/build`), so `FRONTIER_PUBLIC_` is the framework's one door into a bundle and every other `FRONTIER_*` name stays on the server. The API must
then allow that page's origin in its CORS configuration. A family
of origins is a predicate rather than a list — `middleware: { cors: { origins: o =>
o.endsWith('.preview.example.com') } }` in `junction.config.js` admits every frozen Basecamp
preview of the app, with nothing to add or remove as previews come and go.

### A header on every call — the tenant the call is for

An app under `tenancy { strategy row }` names the account a call is for in a header its
principal resolver reads (`membershipClaim({ tenantFrom: header('X-Account-Id') })`, junction's
`AGENTS.md` § *Who the caller is*). The page sets it once on the client — after `await ready`,
with `session.user` set, `getClient().setCallHeader('X-Account-Id', accountId)` from
`@frontierjs/sierra/resource` — and every later call carries it, over HTTP and over the socket;
`null` removes it.

A header a resolver reads through `header()` is declared already: the server lets it through
the CORS preflight and onto a socket frame without a `callHeaders` entry. Any other header
`setCallHeader` sets goes in `middleware: { callHeaders }` in `junction.config.js`, or it is
absent the moment the socket connects.

**Which accounts the person belongs to is the app's own read.** No tenant-scoped service can
answer it — each refuses a call that names no account — so the membership model is
`@@tenant(none)`, admits its own subject's rows (`@@allow(read, userId == auth().id || accountId
== auth().accountId)`), and a find-only service over it (`memberships` above) is the list a
switcher shows.

### Connection state

```html
<script>
  import { status } from '@frontierjs/sierra/resource'
  $: status.connected
</script>

<span class:online={status.connected}></span>
```

`status` is a plain object (`{ connected, reconnecting, stale }`) — same contract as
`page`.

`status.stale` is `null` until the server states a build this bundle is not, then
`{ client, server }`. It is set at most once per page — a banner that reappears on every
request is one nobody reads — and it is recorded rather than acted on, because whether
that is a banner, a prompt or a silent reload is the app's answer:

```html
{#if status.stale}<a href="/">A new version is available</a>{/if}
```

### Resources

`createResource` wraps a Junction service with a four-phase hook pipeline that mirrors the
API realm:

```js fragment
import { createResource } from '@frontierjs/sierra/resource'

export const leads = createResource('leads', {
  hooks: {
    around: { all:    [async (ctx, next) => { loading.set(true); await next(); loading.set(false) }] },
    before: { create: [validateLead] },
    after:  { all:    [formatDates] },
    error:  { all:    [handleApiErrors] },
  },
})
```

```
around:enter → before → [network call] → after → around:exit
                             ↓ on throw
                           error
```

Returns `{ service, tethered, record, make, save, move, fields, relations, gate, can, validate, normalize, coerce, context, hooks, … }`.

**A Resource is the model's whole client-side surface** (`FJS-D114`) — the tether, the
verbs, the reads it is asked for, and its default form. Four of those are worth naming:

```js fragment
export const leads = createResource('leads', {
  detailQuery:  { directives: { populate: ['company'] } },   // what get(id) asks for
  optionsQuery: { directives: { orderBy: 'name', limit: 500 } },  // what a picker asks for
  tetheredQuery: { directives: { orderBy: '-createdAt' } },      // what tethered() starts on
})

await leads.save(record)                     // create — this row does not exist yet
await leads.save(row)                        // patch  — it does
await leads.save(row, { mode: 'create' })    // force it
```

`save()` is **the one owner of the write**, and it is record-shaped: you hand it the whole
record and it works out both the call and the payload. That is why the decision lives here
and not in a component — a caller answering it with the literal `id` on a model keyed by
something else creates a duplicate row while looking like an edit. `upsert` is an alias of
`auto`, not a fourth thing. `<Form {resource} />` calls exactly this, and everything the
pipeline does — coercion, blank-stripping, validation, the `@version` this screen read,
the resource's own hooks — happens on the way through.

**A patch sends what CHANGED against the row this resource read.** `<Form record={row}>`
hands back the whole row, and sending it whole makes a PATCH a PUT: a column the screen
never rendered — `formFields({ except })`, a hand-written form, a column added to the
`.lite` after the screen was — would ride along at the value it held when the form opened
and overwrite whoever wrote to it meanwhile, with nothing said. A key is compared, never
tested for truthiness, so an explicit `null` still travels and still clears; a diff omits
a key and never substitutes one. With no baseline — a record this resource never fetched
— the whole record goes up, which is what every patch did before.

**`service.patch(id, data)` is the escape and is unchanged: it sends what you hand it.**
The line is that `save()` takes a record and `patch()` takes a payload.

**`auto` asks whether the row exists, and the schema says how to ask.** Where the server
assigns the key, the id being present means it came from a row. Where the caller supplies
it — a `String @id` a person types — the id is in the create schema by design, so presence
proves nothing and the question is instead whether this resource has read that id; a miss
creates, and a create over a key already taken is refused by the key's own uniqueness.
`mode: 'patch'` with a blank id is refused rather than sent, because a patch with no id is
a write over every row the caller can reach.

All three declared reads are `{ query, directives }`. It is `detailQuery` rather than plain
`query` because `query` means FILTERS at every other boundary here (Invariant 10).

**Return shapes — read this before `.map()`.** The service methods are a pass-through of
Junction's browser client, and Junction's envelope rule applies unchanged: a list keeps
its envelope, a single record unwraps.

```js
const res = await leads.service.find({}, { limit: 20 })
res.data     // the rows
res.total    // total matching — for a pager

const list = leads.tethered({ state: 'local' })
list.rows    // the rows, live
list.total   // total matching, null until the first answer
```

**A screen lists rows through one door, `tethered()`** (`FJS-D1318`). The tether,
`load`, `more` and `stale` it is built from are not keys of the resource. The rows are
live and mean the query that filled them: a pushed row outside that query is not
added, one a patch moved out of it is removed, and where `orderBy` says so the row is
placed rather than appended. Whether a new row belongs on an earlier page, and which
row slides up when one leaves a full one, a browser cannot answer — `list.reload()`
asks the server again.

`{ state: 'local' }` keeps the filters off the address bar — a dock, a widget, an
embedded panel. `{ all: true }` grows the window to the query's end, which is how a
screen holds every row: a `service.find` naming a limit above the server's page max is
refused. Reach for `service.find()` for a one-off read that needs the envelope. `ctx.query` is filters (goes over the wire), `ctx.directives` is
`{ limit, offset, orderBy, select }` (also the wire, and the same word `page.directives`
uses), and `ctx.locals` is per-call scratch that never leaves the browser — how `before`
hands something to `after`.

### Schema seeding

If `db/schema.lite` is present, Sierra runs Litestone's `generateJsonSchema` at build
time and `virtual:sierra` calls `registerSchemas()` before any route module evaluates.
That is why a resource file names a model and nothing else — `make()` gets its field
shape from the schema instead of restating it:

```js
const blank = leads.make({ status: 'new' })   // defaults from db/schema.lite
```

Lookup order is `db/schema.lite`, `../db/schema.lite`, then `schema.lite` — all relative
to the Vite root. In the standard layout the second one is the hit: Vite's root is `web/`
and the schema is at `../db/schema.lite`, its sibling. Override with
`schema: 'path/to/x.lite'`, or disable with `schema: false`.

Only models become resources. Enums, `type T { … }` declarations and `FileRef` are
registered too, but as **definitions** — they are what `$ref` points at, not things you
can `createResource()`.

### Naming: service ⇄ model

A resource is addressed by its **service** name and seeded from a **model**. The registry
bridges the two with English's regular plural rules, so these need no help:

| `createResource(…)` | model | rule |
| --- | --- | --- |
| `'leads'` | `Lead` | `-s` |
| `'companies'` | `Company` | consonant + `y` → `-ies` |
| `'statuses'`, `'boxes'`, `'churches'` | `Status`, `Box`, `Church` | sibilant → `-es` |
| `'lead'`, `'Lead'` | `Lead` | accessor / declared name |

Irregular plurals are not guessable, and Sierra does not guess. Name the model:

```js
createResource('children', { model: 'Child' })
```

`model` is the override for any mismatch, not just plurals — use it whenever a service
is deliberately named something other than its model (`createResource('roster', { model:
'Person' })`). It works in all three signatures, and the service name is still what gets
called on the wire.

When nothing resolves, the warning names the fix and lists what is registered:

```
[resource:children] no schema found for 'children'. make() returns a bare object,
fields is empty, and validate() reports nothing.
  Name the model explicitly: createResource('children', { model: 'Child' })   ← 'Child' looks like the one
  Known models: Lead, Company, Status, Person, Child
```

Once resolved, `ctx.model` and `resource.context.model` report the **model** name as
declared in the `.lite` file — `Status`, not `statuses` — whether you named it or the
plural rules found it.

### Field rules

`resource.fields` is the model's schema flattened into per-field rules, with `$ref`
followed — the same information Junction compiles its server-side validator from:

```js
leads.fields.plan
// { type: 'string', required: true, nullable: false,
//   enum: ['starter', 'pro', 'enterprise'] }

leads.fields.email    // { type:'string', required:true, format:'email' }
leads.fields.name     // { type:'string', required:true, minLength:1, maxLength:200 }
```

That is enough to render a `<select>`, mark a required label, or set an input's
`maxlength` without restating anything from `db/schema.lite`.

`resource.validate(data, mode)` checks a record against those rules and returns
`[{ field, message }]` — empty when the record is acceptable. `mode` is `'create'`
(default) or `'patch'`, which skips absent fields:

```js
const draft = leads.make({ name: 'Ada' })
const problems = leads.validate(draft)
// [{ field: 'email', message: 'email is required' },
//  { field: 'plan',  message: 'plan is required'  }]
```

The resource *also* runs that check automatically before every `create` and `patch`,
throwing `ResourceValidationError` instead of making the request:

```js throws
export const leads = createResource('leads')

await leads.service.create({ name: 'Ada' })
// throws ResourceValidationError; err.errors is the same array as validate()
```

**On by default**, and `validate: false` turns it off. The server validates either way —
Junction derives its rules from the same `.lite` file — so this is about failing in the
browser before a round trip, not about being the thing that says no. What it changes is
*where* an invalid payload surfaces, so the case for turning it off is a form that
cannot see a column the schema requires.

Enforcement runs **after** the `before` hooks, so a hook that completes the record
(stamping a tenant id, coercing a field) is reflected in what gets checked. The throw
travels the normal `error` phase, so an `error` hook can present it — or clear
`ctx.error` to recover.

Both halves are kept honest by a shared rule: `required` means *absent or null*, so an
empty string satisfies a required `String` on the client exactly as it does on the
server. Sierra's checker covers what Litestone's generator actually emits and is not a
general JSON Schema validator.

A bulk create is validated element-wise, and each error carries the row `index`.

### Relations

Relations have no wire representation, so they are absent from `properties` —
`x-relations` is the only place they exist on the client. `resource.relations`
reads it:

```js
leads.relations.account
// { field:'account', type:'belongsTo', model:'Account',
//   foreignKeys:['accountId'], references:['id'], optional:false, onDelete:'Cascade' }

leads.relations.tags
// { field:'tags', type:'m2m', model:'Tag' }
```

`model` is normalized to the name as declared in the `.lite` file, so it can be
handed straight to `schemaFor()` — or used to build the related resource, which
is how a picker finds its options without naming the service:

```js
const related = createResource('accounts', { model: leads.relations.account.model })
```

Foreign keys are also marked on the field rules, because `accountId` is a plain
integer on the wire and a generated form would otherwise render a number input
for a reference:

```js
leads.fields.accountId.references
// { model: 'Account', field: 'id', relation: 'account' }
```

### Another app

A page that shows a FrontierJS app it is not, such as a studio over the app it
hosts, builds the resource from a handle on that app:

```js fragment
import { connectApp, createResource } from '@frontierjs/sierra/resource'

const hosted = connectApp({ url: `/hosted/${id}`, apiPrefix: '/api', schema, user })
export const leads = createResource('leads', { app: hosted })
```

`schema` is what `generateSchemas(path)` from `@frontierjs/sierra/build`
answers for that app's `db/schema.lite`, made on the server. Fields,
relations, `can()` and moves are read from it, every call goes to that app, and
a related resource built for a picker inherits the handle.

**The client sends the page's own credential.** So `url` is a route on the
page's API that forwards to the other app and swaps the credential for one that
app accepts, which stays on the server. A `url` on another origin is refused.
The socket is `url` + `/ws`, so the forward bridges that path too, or the live
stores never move. `user` is who that app sees, and a create seeds a column
pinned to `auth()` from it. `@@sync` and `offlineQuery` stay off, because what
a device holds belongs to the page's own app. `hosted.close()` stops following
the page's sign-in.

### Gate

`resource.gate` is the model's `@@gate` levels, and `can()` compares a level
against them:

```js
leads.gate                       // { read: 0, create: 4, update: 4, delete: 5 }
leads.can('delete', userLevel)   // false at 4, true at 5
leads.can('patch',  userLevel)   // service method names work too
```

**This is a UI affordance, not a security boundary.** The gate is enforced at the
data layer by Litestone and turned into a status code by Junction; `can()` only
lets you avoid offering a button that is going to 403. Never guard anything on
it that the server does not also guard.

Unknown answers are permissive — no gate declared, no level supplied, an
operation the gate does not mention. Hiding a control the user could have used is
a worse and much quieter failure than showing one that errors. A `SYSTEM` (8) or
`LOCKED` (9) need is the exception: no browser caller reaches either at any
level, so `can()` answers no to it with no level supplied too.

Levels are the 0–9 ladder (`STRANGER` 0 … `USER` 4 … `OWNER` 6, `SYSTEM` 8), owned by
`@frontierjs/toolbelt/gate`. Pass a number, or read a name off that kit rather than
writing a mapping here.

### Coercion

`el.value` is a string for **every** DOM control — `<input type="number">` and
`<select>` included — and Mesa's `bindInput` passes it through unchanged, correctly,
because it has no idea what the field is. So a form bound to `make()` sends `"42"` for a
`Float` and `"1"` for an `Int`, and both the server and `validate()` reject them.

Only the schema knows what they were meant to be:

```js throws
export const leads = createResource('leads')

await leads.service.create({ value: '42', accountId: '1' })
// sent as { value: 42, accountId: 1 }
```

Conservative on purpose:

- **`''` is never coerced.** `Number('')` is `0`, and silently inventing a zero for an
  empty box is worse than a validation error. Blank handling belongs to `blankToNull`,
  which runs after this.
- A string that isn't a clean number is **left alone**, so `validate()` can say so rather
  than NaN reaching the server. `'7.5'` in an `integer` field stays `'7.5'`.
- Only strings are touched; anything already of the right type is left alone.

**On by default**, like the others, and `coerce: false` turns it off — but a form bound
to DOM inputs wants it, and validation without it rejects every numeric field.
`resource.coerce(data)` does the same on demand.

The three compose in this order: **coerce → blankToNull → validate**, so validation
judges exactly what will be sent.

### Blank → null

A text input cannot produce "no value" — an untouched box submits `''`. So a form bound
to `make()` writes `''` into a column the schema declared nullable, and SQLite does not
treat those as the same value:

```
two NULLs   : ok | ok
two ''      : ok | REJECTED: UNIQUE constraint failed
```

`String? @unique` accepts any number of NULLs but rejects a second `''` — a create that
works once and then fails, from a default nobody wrote. And `WHERE col IS NULL` never
matches `''`, so "records with no X" silently excludes everything the app created.

The resource replaces `''` with `null` on nullable fields before every create and
patch — on by default, off with `blankToNull: false`:

```js throws
export const leads = createResource('leads')

await leads.service.create({ name: 'Ada', slug: '', notes: '' })
// sent as { name: 'Ada', slug: null, notes: null }
```

The form keeps binding to a string — no `?? ''` at every input, no `null.trim()` — and
the wire carries the distinction the schema actually made. `resource.normalize(data)`
does the same thing on demand, without the flag.

Only **nullable** fields are touched (`''` on a required `String` is a real empty string,
and nulling it would turn a valid record invalid), only fields **present** in the record
(a patch is never widened), and only the exact value `''` — whitespace is content, and
trimming is a separate decision this does not make.

It composes with `validate`: normalization runs first, so validation judges what will
actually be sent.

### Auth

`session` is the UI half — a reactive object (`user`, `level`, `checked`, `error`)
alongside `ready`, `signIn`, `signUp` and `signOut`; the wire half is `client.auth`. A `401` from any service call fires the
client's `unauthorized` event, which clears the credential and redirects to
`auth.redirectTo`. Route protection is declarative:

```js fragment
junction: {
  url: '…',
  cookieAuth: true,                      // only if the server issues a cookie
  auth: { publicRoutes: ['/login/', '/blog/*'], redirectTo: '/login/', returnPath: true },
}
```

The guard awaits the boot restore and then checks credential *presence*, not validity —
validity is the server's job. A trailing `*` is a **segment boundary**: `'/blog/*'` covers
`/blog/` and everything under it and does not cover `/blogadmin`.

**`cookieAuth` must match the server.** `auth(auth, { cookieAuth: true })` on
the API has a twin here, because the browser cannot see the server's source and there is
nothing to derive it from. Left off against a cookie-mode server, the client answers
"signed out" for a signed-in caller: no boot restore, no socket, and a sign-out that never
reaches the server while telling the person it did.

### Presence

Who else is on a channel, as a signal:

```html
<script>
  import { presence } from '@frontierjs/sierra/presence'
  const members = presence('workspace:42', { meta: { name: user.name } })
</script>

<p>{members.count} here</p>
{#each members.others as m}<span>{m.meta.name}</span>{/each}
```

The value is `{ members, others, self, count }`. `members.updateMeta(meta, { debounce })`
publishes a new meta for this connection — a cursor position, a "typing" flag — and
`members.leave()` stops; a component that called `presence()` at init scope leaves
automatically on destroy. Two views of the same channel on one page are refcounted, so the
first to unmount does not release the channel the second is still showing.

**What this cannot do is the part to know.** Channel MEMBERSHIP is the server's, decided by
the app's own `channels(setup)` calling `channel.join(conn)`; nothing a browser sends joins
a channel. What `presence()` sends is *here is my meta, send me the roster*, so a channel
this connection was never joined to answers nothing — in silence, which is exactly what a
misspelt channel id looks like. **An anonymous connection is never tracked**: presence keys
off a session's user, so a signed-out socket neither appears in a roster nor receives one.
And `self` is the server's own statement about which member this connection is, so until
the first `presence:sync` lands every member is an *other* — the safe way round for an
avatar strip.

Presence is socket-only and has no HTTP fallback: it is a fact about a live connection, and
a request that opens and closes one has nothing to be present in. A reconnect re-announces
every channel this client had announced, because the server keys presence by connection id
and a new socket is a new connection with no meta and no roster.

### Search

`paletteSource(client, { models, link })` is `CommandPalette`'s `search`, over the API's
`searchService({ models })` from `@frontierjs/junction/search` (`FJS-D970`):

```js
import { getClient, paletteSource } from '@frontierjs/sierra/resource'

const search = paletteSource(getClient(), {
  models: ['issue', 'comment', 'project'],
  link:   { comment: async hit => `/issues/${(await comments.get(hit.id)).issueId}` },
})
```

```html
<CommandPalette items={NAV} {search} />
```

One round trip per pause in typing, answering one list ranked on one scale and already
graded by the Data boundary — a row the caller may not read is never a hit. Each hit
becomes a row: the group is the model's plural (`Issues`), the label its `@@label` column,
the sub its identifying key, and choosing it goes to `/<service>/<id>` lowercased —
`/productvariants/7`, `/persons/3` — the route `fli scaffold` writes. A model whose rows live elsewhere states its own `link`, which may
answer a promise: a hit carries `model`, `id`, `title` and `sub` and nothing else, so
finding a comment's issue is a read.

`models` narrows what the service mounts and cannot widen it — a model outside the mount
is a 400 naming it. A `link` key that is not in `models` throws at the call, because a
misspelled one would send its rows to the default route, which for most models is a page
that exists and so reads as a wrong record rather than an error. A kind the index does not
hold is the app's own source, appended to what this answers.

---

## Configuration

Everything in `sierra.config.js`:

| Key | Default | Meaning |
| --- | --- | --- |
| `target` | `'spa'` | `'spa'` \| `'static'` \| `'widget'` |
| `widgets` | — | `widget` target only — `{ dir, outDir, prefix, minify }`: where the widgets are (`src/embeds`), where their scripts go (`dist/embeds`), the tag prefix |
| `dev.staticData` | `true` | run a prerendered route's `load()` on the dev server, so dev shows the page with its data |
| `islands` | `true` | `static` only — the island marker pass; `false` turns it off |
| `db` | — | `static` only — a module exporting a Litestone client, used to grade what a prerendered route reads against `@@gate` |
| `routesDir` | `'src/routes'` | scanned directory |
| `outDir` | `'dist/client'` | build output |
| `base` | `'/'` | public base path |
| `trailingSlash` | `'always'` | `'always'` \| `'never'` \| `'preserve'` |
| `document` | — | `static` only — the document a prerendered page is wrapped in: `{ bodyClass, bodyAttrs, htmlClass, lang, head, bodyEnd, meta, links, jsonLd }`. The build's own CSS assets are linked automatically. Every target's `index.html` gets `lang="en"` on `<html>` and the skip link to `#main` first in `<body>` where it wrote neither (`FJS-D836`) |
| `routeTable.output` | `'config/routes.js'` | where the generated route table is written. A build writes `routes.build.js` beside it, so it never overwrites the table a running dev server serves |
| `schema` | auto-detect | path to the `.lite` file, or `false` |
| `junction` | — | `{ url, apiPrefix, authPrefix, tokenKey, cookieAuth, auth, services, debug, … }` — data only, since it reaches the browser as JSON |
| `theme` | — | `{ themes, default, system, persist, key, apply, attribute }` — `attribute` only with `apply: 'attribute'` |
| `analytics` | — | `{ provider }` — `'plausible'` (`domain`, `apiHost`), `'gtm'` (`containerId`), or a custom provider's module path relative to the Vite root (`'/src/analytics.js'`), which exports `init`, `pageview` and `track`. On `static` the build writes the vendor's tag into every page's `<head>` and an island's `track()` reaches it; a custom provider is refused there, since a prerendered page has nothing to run it. Plausible gets the address without its search or fragment. **GTM's built-in Page URL variable reads `location.href` itself and the tag cannot override it**, so a container's tags must read a Data Layer Variable named `page_location` (the address without its search, pushed on `gtm.js` and on each pageview) to keep a query-string token from the vendor; whether Page URL carries the fragment is unmeasured |
| `devtools` | — | `{ port, position, n1Threshold }` |
| `autoImport.components` | `[]` | directories, scanned recursively, whose PascalCase components need no import. Ordered: a later directory wins a name an earlier one holds, and the build logs each override; the same name twice in one directory, or against a `modules` binding, is a build error |
| `autoImport.modules` | `{}` | package → bindings that need no import |
| `siteUrl` | `''` | absolute origin for the sitemap |
| `llms` | `false` | `true` emits `llms.txt` unless `public/llms.txt` exists · `'auto'` always regenerates it |
| `functions` | — | directory of host functions, relative to the root. A file answers its own path (`functions/api/event.js` is `/api/event`, `index.js` its directory) and is `export default (request, env) => Response`; `env` carries strings only, and a module importing `cloudflare:` or a `[param]` file name is refused. The build writes `.sierra/functions.js`; `sierra site --serve` and a `--compile` binary mount it before the static answers (the binary reads `env` from its own process), and `vite dev` on a `static` target answers the directory per request, so an edit needs no restart |
| `offline` | `false` | `true` writes `sw.js` with a precache list of what this build emitted, so a visited app opens with no network |
| `push` | `false` | `true` adds Web Push handlers to `sw.js`, with or without `offline`: a push shows the notification, a click focuses or opens its `url`. The payload is `PushMessage` in `@frontierjs/notifications`, and `notifications/test/fixtures/push-message.json` is the shape both ends are tested against |
| `markdownPages` | `false` | `true` \| `'auto'` — emit `index.md` beside each page |
| `speculationRules` | `true` | static build: prerender a same-origin link on hover (Speculation Rules, `moderate`); `rel="nofollow"` opts a link out |
| `build.deferJS` | `false` | defer script tags in `index.html` |
| `plugins` | `[]` | extra Vite plugins. A `closeBundle` on one is the post-build hook: Sierra calls it once, with `{ outDir, root, config, routeTable }`, after the pages are written, and Vite never calls it |
| `vite` | `{}` | raw Vite overrides — deep-merged last, arrays concatenated |

`junction.debug: true` logs every service call with payloads; `'verbose'` adds every
client event. Both are off by default — the console retains logged objects, which on a
WebSocket-heavy app keeps every response payload alive for the tab's lifetime.

---

## Build targets

**`spa`** — the supported path. Vite's default chunking, client-side routing, one
`index.html`. Verified end-to-end.

**`static`** — same bundle, plus a prerender pass in `closeBundle`. Every route but
`render: spa` is rendered to its own `index.html` via Mesa's `renderComponent`, with
layouts composed around it (`FJS-D2194`). A route that cannot be — the static-safety
check refuses what it reads, its `load()` or render throws, or it is dynamic with no
`getStaticPaths()` — is left to the browser and listed under *Rendered in the browser*
with the reason, and the safety table marks it `browser` (`FJS-D2195`). Declaring
`render: static` turns each of those into a build failure, and a dynamic route that
declares it **must** have a companion exporting `getStaticPaths()`. A static build that
produces no pages says so rather than silently emitting an SPA.

A prerendered layout reads `page` as it does in the browser. Before each page renders,
`page` holds what a navigation to it would commit: its `pathname`, `params`, load() `data`,
and its frontmatter merged down the layout chain, spread and as `meta`. A route with
`status: draft` or `redirect:` is not prerendered, and the build lists both under
*Not prerendered, by their frontmatter*. A redirect is served by `_redirects`.

> **A prerendered module resolves imports from the APP's tree, not Mesa's.** Mesa's
> `renderComponent` takes a `tmpDir` and Sierra points it at
> `node_modules/.sierra/render` inside the app. Written into the Mesa package
> directory instead, a page importing `@frontierjs/sierra/*` fails to resolve under a
> linked workspace and that page is skipped.
>
> One caveat remains: `load()` cannot use relative URLs at build time — there is no
> origin, so `sierraFetch` throws and directs you to `getStaticPaths()`.

**`static/` is a SURFACE too, and it is `site/`** — a peer of `api/` and `web/`,
never a second config inside the SPA (Invariant 3, `FJS-D127`). Its build
prerenders and checks what it may publish, its tests run against FILES rather
than a running app, and its release is a bucket with no application server behind
it. The fourth answer is what makes folding it in a defect rather than a
preference: **one Vite root is one `dist/`**, so a static site inside `web/` lands
inside the SPA's output, and `vite build` empties `outDir` — the SPA's build
deletes the site and says nothing. `fli make:site` writes the surface;
`fli check`'s `app-layout` reports a `target: 'static'` config found inside
another one.

```
site/                         ← beside api/ and web/, never inside either
  config/
    vite.config.js            ← the Vite root is site/, port 8600
    sierra.config.js          ← target: 'static', plus `db` and `document`
  index.html                  ← the DEV shell; a built page never uses it
  src/
    main.js                   ← optional side-effect imports; virtual:sierra mounts the routes
    routes/                   ← file-tree routes, the same convention as web/
    islands/                  ← the only JavaScript a prerendered page runs
  test/                       ← what proves the BUILD: files, not a running app
  deploy/                     ← serve.js + Dockerfile — the site origin
  dist/                       ← one index.html per route, plus island chunks
```

**Dev is an SPA and the build is files.** `target: 'static'` uses the SPA's Vite
config, so `vite dev` on the surface serves the routes client-routed — that is the
writing loop. Everything that makes the target what it is happens in
`closeBundle`, so a change to a `load()` or to frontmatter is proved by building.

**`sierra site --serve`** is the origin the surface deploys with, and a drive
should point at it rather than a `createServer` of its own: it resolves a
directory to its `index.html`, revalidates HTML while leaving hashed assets
immutable, and serves the site's own `404.html` with a 404 status. It sends no
CORS, deliberately — this origin serves documents a browser navigates to.

**`sierra site --compile`** makes the same origin and the built site one
executable — `bin/site` by default, `--out` to move it, `--target bun-darwin-arm64`
for another OS, `--dir` for a `dist/` something else built. It needs bun to
compile and nothing to run: `./bin/site --port 8080`, or `PORT`.

**`widget`** — an embeddable script for a page this app does not own. One `.mesa` file
in `src/embeds/` becomes one self-contained IIFE: the component, the Mesa runtime and
the CSS in a single file a host page loads with one `<script src>` and nothing else.

**`widgets/` is a SURFACE, a peer of `api/` and `web/`** — not a folder inside the SPA
(Invariant 3). It earns its own directory because its config, its tests and its release
are all a different set of answers: one Vite root of its own, host pages it does not own
to test against, and static files served from an origin a stranger's page links to.
`fli make:widget <Name>` writes it the first time and tops it up after.

```
widgets/                      ← beside api/ and web/, never inside either
  config/
    vite.config.js            ← the Vite root is widgets/, port 8200
    sierra.config.js          ← target: 'widget'
  src/embeds/
    Counter.mesa              → dist/embeds/Counter.js
    LeadForm/
      index.mesa              → dist/embeds/LeadForm.js
      Field.mesa                …a part of LeadForm, not a second widget
  test/                       ← a host page per widget, hostile CSS on purpose
  deploy/                     ← serve.js + Dockerfile — the widget origin
```

```html
<!-- the host page: no bundler, no framework, no init call -->
<mt-counter data-start="5"></mt-counter>
<script defer src="https://cdn.example.com/embeds/Counter.js"></script>
```

It mounts in a **shadow root**, so the host page's `button { … !important }` cannot
reach the widget and the widget's styles cannot reach the host page. Props are
`data-*` attributes, camelCased — `data-api-url` → `apiUrl` — and they arrive as
strings, because that is what an HTML attribute is.

A widget says how it is found in `<script module>`, and everything it does not say
comes from the config:

```html
<script module>
  export const widget = {
    // Also mount into pages that already say <div class="mt-counter"> — host
    // markup often lives somewhere its author cannot edit. New pages use the
    // element; both are the same mechanism.
    selector: '.mt-counter',
    // tag:    'mt-counter'   the whole tag, overriding prefix + file name
    // shadow: false          mount in the light DOM instead
  }
</script>
```

```js
// config/sierra.config.js
export default {
  target:  'widget',
  widgets: { dir: 'src/embeds', outDir: 'dist/embeds', prefix: 'mt-' },
}
```

**Built by `sierra widgets`, not by `vite build`** — a widget is a library build and
Vite's library mode takes one entry, so N widgets is N builds. That is also the cost:
the runtime is in every bundle, once per widget on a page that embeds several. It buys
the property the target exists for — a widget is one file, and a page embedding it
needs to know nothing about the others.

```sh
sierra widgets --config config/sierra.config.js          # from widgets/, the Vite root
sierra widgets --serve --config config/sierra.config.js  # the release — serves dist/embeds
vite --config config/vite.config.js                      # dev, over the surface's own page
```

`--serve` is the surface's release rather than a preview: `bun run test:widgets` builds
the fixture, starts that server and loads the bundles **cross-origin** through it, so the
CORS and cache answers under test are the ones that ship.

A host that serves `dist/embeds` as plain files (Outpost's static origin, Cloudflare)
gets the same answers from the `_headers` the build writes beside the scripts, plus an
`index.html` listing them, because a static release needs one at its root. An
`index.html` the app put there is kept.

An element that arrives after the script has run is mounted too (a tag manager, a CMS,
a host-page route change), and a script included twice produces one widget, not two.

### The document around a prerendered page

Sierra assembles it — Vite's HTML transform never runs on these files, so what
`index.html` gives the SPA has to be stated here. **And only here:** Sierra applies
the same `document` to `index.html` in dev and in the build, so the dev page carries
what every built page does. An attribute stated in both — a body class in
`document.bodyClass` and on `index.html`'s `<body>` — fails with both names
(`FJS-D971`):

- **The stylesheets the build emitted are linked automatically.** Without that a
  prerendered page carries every class name the app uses and none of the rules
  (without it a `static` page is unstyled while the SPA built
  from the same source is not, which is the shape that reads as a CSS bug). They come before the page's own scoped
  `<style>` blocks, so a component's rules win.
- **`document: { bodyClass, lang }`** is the rest of it. A theme in
  `@frontierjs/css` is one class on an ancestor, so `bodyClass: 'app
  theme-default'` is what makes a prerendered page look like the app. `lang`
  defaults to `en`, and a route may override it with `lang:` in its frontmatter.
  Every page, and every target's `index.html`, also opens `<body>` with
  `<a class="skip-link" href="#main">Skip to content</a>` unless the layout or
  the shell wrote a `.skip-link` of its own (`FJS-D836`); the layout renders
  the `<main id="main" tabindex="-1">` it lands on. What a rendered page then
  owes — `lang`, that one link first in body and landing on a focusable
  `#main`, one `<main>`, a name on each of several `<nav>`s, one `h1` and no
  skipped heading level — is `PAGE_AUDIT` in `@frontierjs/mesa/drive`, which
  `example`'s drives and basecamp's evaluate on every page they open.
- **`document: { head, bodyEnd, bodyAttrs }`** is what is the same on every page: `head` and
  `bodyEnd` are HTML strings written verbatim at the end of `<head>` and `<body>` (a
  site-wide third-party loader), and `bodyAttrs`
  (`{ id: 'app' }`) is attributes for `<body>` beside `bodyClass`.
- **`document: { meta, links, jsonLd }`** are `head()`'s keys for every page — a
  business's Organization graph, a `theme-color` — written before the page's own and
  escaped the same way. Reach for these over `head` whenever the tag is data: `head` is
  verbatim, so a value in it is the app's to escape.
- **`head()` answers the per-page tags too:** `{ title, description, meta, links, jsonLd }`.
  `meta` and `links` are arrays of attribute objects
  (`meta: [{ property: 'og:title', content }]`, `links: [{ rel: 'canonical', href }]`) and
  `jsonLd` is one object or an array. These values come from a row, so they are escaped; an
  attribute name that is not a name fails the build. Static only — the router's `head()`
  reads title and description.

### Islands — making a static page interactive

A `target: 'static'` page ships HTML and CSS and **no script**, so on its own it is inert
forever. Islands are how a piece of one comes alive. Mark a component with a `client:*`
directive and Sierra does the rest:

```html
<script>
  import Counter from '../islands/Counter.mesa'
</script>
<main>
  <h1>prerendered, ships no JS</h1>
  <Counter client:load start={7} />
</main>
```

The prerendered HTML carries the island inside comment markers, and Sierra puts a script
tag only on pages that have one:

```html
<main><h1>prerendered, ships no JS</h1>
<!--mesa-island {"component":"Counter","directive":"load","props":{"start":7}}-->
<button>count: 7</button>
<!--/mesa-island--></main>
<script type="module" src="/assets/islands-C6C54-f9.js"></script>
```

| Directive | When it mounts |
|---|---|
| `client:load` | immediately, as soon as the bundle runs |
| `client:idle` | on `requestIdleCallback` (a timeout where that is missing) |
| `client:visible` | when the island's first element scrolls into view |
| `client:media="(min-width: 600px)"` | when the query matches, then and there or on change |
| `client:static` | **never** — "no JS even if the component is reactive"; its chunk is not fetched |

Four things worth knowing:

- **Mounting replaces the prerendered markup**; it does not adopt it. Mesa has no
  hydration, so there is nothing to adopt with. For equal props the markup is identical,
  so nothing visibly moves.
- **An island's CSS ships once.** Scope hashes are content-addressed, so the
  `<style id="mHASH">` in the prerendered page is the same id the island's chunk
  would inject under — and Mesa's `addStyles` skips an id already in the
  document. Each component gets its own `<style>` block rather than one blob.
- **Props must survive JSON.** They are serialized into the marker at render time, so a
  function prop is dropped with a warning and the island mounts without it.
- **One chunk per island, fetched when its directive fires.** A `client:visible` island
  below the fold downloads nothing until it is scrolled to; a `client:media` island whose
  query never matches is never downloaded at all. Verified against resource timing in a
  real browser. The shared entry (Mesa runtime + loader) is loaded by any page with an
  island.
- **A component name is the key.** The marker carries a name, so two different modules
  used under the same component name collide; the build warns and mounts the first.

Turn the whole pass off with `islands: false` in `sierra.config.js`.

`test/fixtures/island-site/` is a runnable app for this, and `verify.mjs` beside it
proves the claims the only way they can be proved — clicking prerendered buttons in
headless Chrome, and reading resource timing to confirm which chunks were fetched. It
covers all five directives, per-island splitting, and CSS scoping. See its README.

`test/fixtures/widget-site/` is the same thing for the `widget` target: two widgets, a
plain host page written to be hostile (`button { background: red !important }`), and a
drive that builds the scripts and proves the lot in Chrome — element upgrade, the
selector form, a late-inserted host, shadow isolation in both directions, a delegated
click, and a script included twice producing one widget. See its README.

---

## Post-build pipeline

Runs automatically after `vite build`:

| Step | Condition |
| --- | --- |
| `404/index.html` → `404.html` | always |
| `robots.txt`: the public directory's, or a default naming `siteUrl`'s sitemap | always |
| `_redirects`: routes with `redirect:` first, then the app's own `_redirects` from the public directory; one path sent two places stops the build | always |
| `sitemap.xml` from `indexed` routes | always |
| `llms.txt` | `llms` is `true` or `'auto'` |
| per-page `index.md` | `markdownPages` |
| Speculation Rules (prerender on hover) | static target and `speculationRules !== false` |
| `defer` on script tags | `build.deferJS` |
| theme flash-prevention inline script | `theme` configured |
| whether a browser will install the app | `index.html` links a manifest, or `public/manifest.webmanifest` exists |
| user plugin `closeBundle` hooks | `plugins` |

**A manifest is graded, never written.** The app owns `public/manifest.webmanifest` and the
`<link rel="manifest">`; the build prints `manifest.webmanifest — installable`, or a warning naming
the rule it fails, because a browser that will not install an app does not say so — the install
button just never appears. The rules are Chrome's, measured: a `name` or `short_name`, a `start_url`
on this origin, `display` of `standalone`, `fullscreen` or `minimal-ui`, and one icon with purpose
`any` whose file is in the build and whose declared and real size are both at least 144px (an SVG
with `sizes: "any"` counts). No service worker and no 512px icon are required. `bun run
test:installable` holds the grader against Chrome's own `Page.getInstallabilityErrors`.

---

## Dev experience

- **HMR.** Editing a route file swaps the component in place. Sierra injects a Mesa HMR
  boundary and suppresses its own `sierra:hmr` event for files that received one, so an
  update is applied once rather than twice. The route table is written byte-stable so
  a no-op rewrite doesn't escalate to a full reload.
- **Error overlay.** Runtime errors are forwarded to an in-page overlay and the terminal.
  `load()` failures are excluded — they are data errors, and the page renders `page.error`.
- **Devtools toolbar.** Injected in dev only. It connects over WebSocket to Junction's
  devtools plugin (`app.configure(devtools())`, port 5503) and shows requests, events,
  logs, connections and an N+1 waterfall. Zero production bundle cost.
- **Build warnings.** Unexported snippets, frontmatter shadowing a reserved `page` field,
  and duplicate snippet/layout-prop names.
- **Auto-import.** Two registries, one namespace:

  ```js fragment
  autoImport: {
    components: ['src/components/UI'],
    modules: {
      'svelte/store':       ['writable', 'readable'],
      '@frontierjs/sierra': [['theme', 'appTheme']],   // named, under an alias
      'some/pkg':           { default: 'Pkg', star: 'ns' },
      dayjs:                'dayjs',                   // shorthand for a default import
    }
  }
  ```

  Component directories are scanned **recursively** and keyed on the basename, so a
  component's directory organizes it and its name identifies it. A **component** is
  injected where the template uses it as a `<Tag>`; a **module binding** where any code —
  a `<script>` body or a `{…}` expression — uses it as a bare identifier. Prose is not
  code: `<p>Use dayjs</p>` imports nothing. Neither is a property access (`x.writable`),
  an object key, a string, or a comment.

  A name the file already binds always wins — an explicit import, or a local `const`.
  Two sources providing the same name is a build error, whether they are two directories,
  two packages, or one of each; alias the binding or rename the component.

---

## Theme

```js
import { theme, setTheme, toggleTheme } from '@frontierjs/sierra'
```

`theme` is a plain object — `{ value: 'theme-dark', preference: 'system' }` — like `page`
and `status`. `value` is the resolved class name, never `'system'`; `preference` is what
was chosen, `'system'` or a name, and is what a picker marks as checked. Watch it to make
it reactive:

```html
<script>
  import { theme, toggleTheme } from '@frontierjs/sierra'
  $: theme.value
</script>

<button onclick={toggleTheme}>{theme.value}</button>
```

Without the `$:` the read is a snapshot taken at mount. Sierra passes
`externalReactivityHints: 'strict'` to the Mesa compiler, so an uncovered member read on
any imported object is reported at build time — say `var` if a one-time read is what you
meant. A `static` build reports it only for a component a published script contains, such
as an island, since a page that ships no script never re-renders, and it prints a count
of the ones it held back.

With `theme` configured, the post-build pipeline injects an inline `<head>` script that
applies the persisted preference before first paint, so there is no flash.

The preference is a `persisted()` value from `@frontierjs/mesa/browser`, stored as
`<prefix>:<key>` — `key` defaults to `theme` and the prefix is the app's (`prefix` in
`sierra.config.js`, else its `package.json` name), so `key` never carries the app's name.
A pick made in one tab reaches the app's other open tabs. Under `default: 'system'` the
theme follows the OS scheme (`colorScheme()`) until somebody picks one, and
`setTheme('system')` follows it again — under a named default too. An app never reads or
clears the key itself: the stored name carries the prefix, so the bare key reads nothing.

`setScheme('light' | 'dark')` is for a page whose window somebody else owns — an MCP
host handing a view its `hostContext.theme`. It maps onto the pair `theme.system` names,
the same mapping the OS preference gets, and from then on the OS query yields to it. It is
never persisted: the answer is the host's.

---

## `virtual:sierra`

The page's entry, named by `index.html`. It imports `virtual:sierra/boot`, then
`src/main.js`, then mounts `src/App.mesa`. The boot is generated from your config, so it
contains only what you configured — router init always, then Junction, schemas, analytics
and theme if present, plus the dev-only overlay and HMR bridge. An entry that mounts
somewhere other than `#app` imports `virtual:sierra/boot` and mounts itself. The boot
exports the route table:

```js fragment
import { tree, components, loaders, layouts, published, indexed, redirects } from 'virtual:sierra/boot'
```

| Export | Contents |
| --- | --- |
| `tree` | the route node tree (metadata only) |
| `components` / `loaders` / `layouts` | lazy factory maps |
| `all` / `published` / `indexed` | route paths — raw, minus drafts, minus noindex + dynamic |
| `redirects` | `[[from, to], …]` |

---

## Package exports

| Subpath | Contents |
| --- | --- |
| `@frontierjs/sierra` | the router and theme API, and nothing else — a battery or the build is reached by its subpath (`FJS-D649`) |
| `.../build` | `createSierraViteConfig` |
| `.../router` | navigation, `page`, guards, `RouterView`, `ChainRenderer` |
| `.../router/internals` | chain resolution — used by `RouterView`, not public |
| `.../scanner` | `scan`, `scanAndWrite`, `buildTree`, `classify`, frontmatter parsing |
| `.../resource` | client wiring, `status`, auth, `createResource`, `buildFieldRules`, `buildRelations`, `buildGate`, `canAtLevel`, `validateAgainstFields`, `normalizeBlanks`, `coerceToSchema`, `resolveRef` |
| `.../field-rules` | the Schema → UI projection alone — `controlFor`, `formFieldList`, `buildFieldRules`, `toFieldErrors`; imports no client |
| `.../fetch` | `sierraFetch`, `configureFetch` |
| `.../theme` | `theme`, `setTheme`, `toggleTheme`, `setScheme`, `initTheme` |
| `.../presence` | `presence(channelId, opts)` |
| `.../analytics` | `initAnalytics`, `configureAnalytics` (the provider alone, for a page whose tag is already in the HTML), `track` |
| `.../devtools` | `initToolbar` |
| `.../postbuild` | `runPostBuild`, `htmlFiles` (every page a build emitted, for a config plugin's `closeBundle` that rewrites them) |
| `.../site/serve` | `serveSite` — the prerendered-site origin |
| `.../site/compile` | `compileSite` — a built site and its origin as one executable |
| `.../widget/serve` | `serveWidgets` — the widget origin |
| `.../components/RouterView` | the router outlet component |
| `.../components/ChainRenderer` | the layout-chain renderer `RouterView` uses |
| `.../islands` | `findIslands`, `mountIsland` — the island loader a prerendered page runs |
| `.../widget` | `embed` — mounting one component as a custom element in a shadow root |

---

## Testing

```bash
bun run test        # vitest
bun run typecheck   # scripts/typecheck.mjs — baseline 0
```

Use `bun run test`, not `bun test`: this package's tests are vitest-authored, and the bun
runner reports failures that are runner artifacts rather than bugs.

---

## Known rough edges

- Every named layout slot emits a duplicate-declaration warning from the Mesa compiler.
  Cosmetic — the build and the slot both work.

See git history for what was fixed and why, and the
repo's `DECISIONS.md` before relitigating any semantics.

---
_Source: https://npm.io/package/@frontierjs/sierra · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
