# Internals

How Mote itself is built: the compiler's passes and files, how a part of the
runtime is chosen and written out, how a battery is built, embedded and
called, and how to add a namespace end to end. For someone about to change
Mote. Back to the [map](README.md).

## The pieces

```text
compiler/     Rust. The `mote` binary. No dependencies (see Cargo.toml).
  build.rs      embeds the runtime's sources and the icon table; builds the batteries to wasm
  src/          the passes (below)
runtime/      Mote, in the runtime dialect. What a page and the back end run on.
  page/         the page's parts: the reactive core, the DOM, events, widgets, …
  shared/       parts both sides use: bytes, patterns, net, the search, syntax and font drivers
  server/       the back end's parts: the server, auth, live, data, push
  README.md     the dialect's reference
batteries/    Rust, built to wasm with `rustc` alone: argon2 mlkem pow zip img mp4 aud scan search syntax font xlsx pdf re plot layouts html charsets
  rt.rs         the allocator and how data crosses, shared by all
  sqlite/       SQLite's own wasm, pinned, with glue.js (the one thing that is not Mote's own Rust)
kit/          Mote. The components that come with it.
icons/        Lucide's icons as text, one per line.
tests/        browser tests and their expectations (testing.md)
tools/        the editor plug-in (editor-plugin.md)
examples/     kit galleries, the playground, larger apps
docs/         these pages
```

Everything above ends up inside the one binary. A built page carries only
what its program uses.

## From source to page

`build::compile(entry, mode)` in `compiler/src/build.rs` runs it all. In
order:

| Step | Where | What it does |
|---|---|---|
| 1. Read | `build.rs`: `load` | Reads the entry and every file it reaches with `use` (and `pkg:` through `mote.toml`), into one `Body`. |
| 2. Lex | `lex.rs`: `lex` | Text to tokens. Indentation becomes `Indent`/`Dedent`; a newline inside brackets is whitespace. Each token knows whether a space came before it, which markup needs ("a space ends a value"). |
| 3. Parse | `parse.rs`: `Parser::body` | Tokens to the tree in `ast.rs`: a `Body` is `items` (declarations) and `view` (markup nodes). Two grammars share one expression parser: logic (`stmt`) and markup (`node`, `attr_value`). `match` is turned into an `if` chain here. A position's line number also says which file it is in (`FILE_LINES`). |
| 4. Survey | `agents.rs`: `survey`, `read` | What the program says of itself (actions, state, routes, calls), before the kit joins it; `agents.mote` is read and checked. |
| 5. Kit | `build.rs`: `with_kit` | The kit components the page names, and those they use, are parsed from the embedded kit and put before the page's items. |
| 6. Mark | `agents.rs`: `mark` | Adds `data-mote` to every control. |
| 7. Check | `types.rs`: `check` | Types. Passes that learn each fn's return type until none changes, then one pass that reports. `Checker::call` holds the standard library's signatures. |
| 8. Split | `emit.rs`: `find_server`, `find_off`, `find_async` | Which fns are the back end's and which never reach the page; which fns go to workers (a fn's own `main`/`off`, else its file's `fns` line or `mote.toml`'s: `Body.fns`, `build.rs` `Placing`); which fns and actions wait. |
| 9. Moves | `moves.rs`: `find` | Which named values are moved to a worker instead of copied. |
| 10. Emit logic | `emit.rs`: `Gen::items` | Declarations to JavaScript: state as signals, derives, resources, fns, actions, components. Every runtime part that is needed is noted with `g.u("NAME")`. |
| 11. Emit markup | `view.rs`: `html_nodes`, then `nodes` | If nothing on the page can change, it is HTML and no JavaScript ships. Otherwise each element is split (`prep`) into what is known now (HTML text, atomic CSS classes) and what is dynamic (effects, listeners). |
| 12. Runtime | `build.rs`: `runtime_for` | The parts noted in step 10 and 11, and all they need, compiled from the runtime's Mote by `sys.rs`. |
| 13. Back end | `build.rs`: `finish` | A second `Gen` in `server_mode` emits the `server fn`s and what they reach, with the server's runtime parts and the table of parameter types (`wire`). |
| 2b. The tree as written | `parse.rs`: `note`; `tree.rs` | As it reads, the parser notes every part with where it starts and ends (`ast::Span`, kept on `Body::tree`). `tree.rs` puts them inside one another (`mote tree`) and gives a diagnostic's place its end. The tree the passes compile is `ast.rs`'s; this one is beside it, and is whole: nothing written is missing from it. |
| 14b. Source maps | `srcmap.rs` | The emitter leaves a mark where each statement, declaration and node of markup was written (`Gen::stmt`, `Gen::items`, `Gen::nodes`), and `runtime_for` one where each part begins. `strip` takes the marks out of the page's script and of the back end's module (what ships is as it would be without them) and says where each stood; `write` makes `server/page.map` (in `index.html`'s lines and columns) and `server/main.js.map` of that. A runtime part maps to its file, by its name. |
| 14. Assemble | `build.rs`: `finish` | The document: head, base CSS, the atomic classes (`Css::render`), the agent block, static HTML, one `<script type=module>` holding runtime + worker set-up + declarations + view. For a full build: manifest, service worker, icons, assets, `public/`, `agent.json`, `llms.txt` (`pwa.rs`, `assets.rs`). |

Diagnostics from every step are collected, sorted and reported together
(`diag.rs`). Any error means nothing is written.

### What the emitted code looks like

```text
state n = 0                     const $n=S(0);
derive d = n * 2                const $d=D(()=>($n.v*2));
action add                      function $add(){$n.v+=1;}
  n += 1
text `${n}`                     const _1=el("span");const _2=tx("");_1.append(_2);E(()=>T(_2,`${$n.v}`));
```

- The program's names carry a `$`; the runtime's are short capitals (`S`
  signal, `D` derive, `E` effect, `I` if, `L` list, `el`, `tx`, `A`
  attribute, `O` listen, `W` a worker call, `RPC` a back-end call).
- A write into state is followed by a tell: `$todos.v.push(x);$todos.n();`.
  `Gen::write` finds which states to tell by following the written value
  back through locals, loop variables and `for` rows (`Gen::srcs`, the `K`
  enum). A parameter's write tells every state that is not plain
  (`types::Door::plain`: a number, a text, a bool); a prop's is
  `p.list$n?.()`, which the caller wrote as `list$n:()=>{$todos.n();}`
  for a component in `Gen::writers` (`Gen::tells`, `view.rs`).
- A call that waits is `await`ed and makes its fn `async`; an action that
  waits is wrapped in `AC(…)`.

To see what a program compiles to, build it with `--single` and read the
`<script>`.

## The runtime

The runtime is written in Mote's own logic syntax, with what a runtime needs
added: [../runtime/README.md](../runtime/README.md) is the dialect's
reference. `compiler/src/sys.rs` compiles it (`sys::compile`).

A runtime file is a list of **parts**:

```mote
host document, MutationObserver      // host names this file touches
short observers o, sources s         // field names that ship short
part core                            // a part: in a page only when needed
  let current as cur = none          // `as`: the name it ships under
  fn signal(v) as S
    …
part D needs core                    // `needs`: parts that must come with it
  fn derive(f) as D
    …
```

**How a part is chosen.** The compiler never ships the whole runtime. When
`emit.rs` or `view.rs` writes code that calls something of the runtime, it
says so with `self.u("PART")` (for example `self.u("RC")` where a resource
is declared, then writes `RC(…)`). At the end, `runtime_for` takes those
names, adds every part they `need`, to a fixed point, and writes the chosen
parts in order, each after the parts it needs. A name no part has is an
error for the back end ("a `server fn` uses something only a page has").

**How a part is written out.** `sys.rs` checks every name (a local, a
part's `let` or `fn`, a `host` name; anything else is an error), gives
locals one- and two-letter names, and ships each part's own names as written
or as their `as`, and fields as written or as their `short`. So the source
says `observers` and the page carries `.o`.

**The same source, two sides.** `mote_parts(false)` compiles `page/` and
`shared/`; `mote_parts(true)` compiles `server/` and `shared/`. A part of
the same name may exist on both sides with different bodies (`SQ`, `FS`,
`WK`, `WX`): the compiler emits the same call and each side answers it its
own way.

**Working on it.** `mote runtime` says whether it all compiles and how big
each part is; `mote runtime NAME` prints one part's JavaScript. With
`MOTE_RUNTIME=/path/to/runtime` the compiler reads the runtime from that
folder instead of the copy built into it, so a change can be tried without
rebuilding the compiler:

```sh
MOTE_RUNTIME=$PWD/runtime mote runtime
MOTE_RUNTIME=$PWD/runtime MOTE_BIN=$PWD/compiler/target/debug/mote tests/all.sh real_el
```

The runtime's files are embedded when the compiler is built
(`compiler/build.rs`, `runtime_mote`), so a change to `runtime/` reaches
everyone only after `cargo build`.

### The parts, by file

| File | Parts | What |
|---|---|---|
| `page/core.mote` | `core` `D` `U` `R` `I` `L` | Signals and effects, derive, untracked reads, owners, `if`, `for`. |
| `page/dom.mote` | `tx` `F` `el` `H` `T` `A` `P` `O` `PR` `PX` `PG` `PW` | Nodes, text, attributes, a field's value, listeners, `press=` (the innermost hears it), pixels, `persist`. |
| `page/field.mote` | `CAR` | A field's caret and selection: `el.selection`, `el.select`, `el.replace`, `el.caret`. |
| `page/actions.mote` | `AC` `NW` `PD` `RC` `FH` `FR` `ASM` | Actions that wait, those that say `newest`, `pending`/`failure`, resources; `on failure`; a fault of the page's own code told to its back end, for `f.at`. `assume` + a block: what an action assigned, kept to be taken back if it fails (`ASK`, `ASU`, `ASD`). |
| `page/agent.mote` | `AG` | `self.mote`, the page as an agent or a test meets it: the page as lines of text and what changed in it, a thing found by number, name or words, presses, typing, holds and swipes made in the page, the page at rest (requests, timers, motion, frames), the clock held and advanced. Stands alone (needs no part): a built app serves it as `mote.js`, taken when first asked for; a one-file page carries it unrun. `tools/drive/mote-drive.mjs` (`mote drive`) is the driver that sends real input and asks it. |
| `page/ahead.mote` | `AHP` `AHT` `AHL` `AHI` | A page drawn ahead, in the browser: its first calls answered from what came with the page, a `live` value started from what was read for it, the first drawing's `img` elements taken by `el` in place of new ones (`AHI`), its drawing put where the one sent stood when the page is at rest: laid out behind it unseen (`html[data-ahead]`) while a request of the page's own is out (until its answer is read through) or a worker owes it an answer, three seconds at most ([back-end.md](back-end.md#a-page-drawn-ahead)). `mote.settled()` waits for it. |
| `page/try.mote` | `TRY` `DT` `TRV` | `try` in markup: an owner whose owned set guards every effect added to it, and gives each a guarded set of its own; a derive that keeps its failure (in a program with a `try`); a resource or a `live` value that throws its failure where a `try` reads it. |
| `shared/bytes.mote` | `BY` `BYJ` `BYN` `BYF` `BYW` `SHA` `HMAC` `PBK` `HKDF` `SEAL` `CEQ` `CRC` `RND` | Bytes and their text forms, `bytes.join`, numbers of several bytes, `bytes.find`, `bytes.buffer`; hashes (MD5 written out, the rest the host's), HMAC, PBKDF2, HKDF, AES-256-GCM, a compare in constant time, CRC-32, random bytes. |
| `shared/charsets.mote` | `TXC` | `b.text(label)`: the WHATWG labels and the single-byte sets' tables, generated by `tools/charset-tables.mjs` (do not edit it). The multi-byte sets go to `TXB` under `if CHARSETS`, a switch the compiler turns on for a side whose code has `TXB`. |
| `shared/multibyte.mote` | `TXB` | The legacy multi-byte sets read by the charsets battery (`batteries/charsets`): its instance kept on the fn, made from `CSW` (inside: inflated, `INF`) or from the module part `CSQ` or `WX` fetched. |
| `shared/failure.mote` | `ER` `FK` | A failure's words, for `else err => …` on either side; and the failure whole (`err.kind`), and what `fail(words, {kind, data})` throws. |
| `page/events.mote` | `EV` `WA` `DR` `PST` `PT` `WH` `WHW` `KM` `KF` `KS` | Timers, `watch`, drop, paste, pointer, wheel, `keys`, which keys typed in a field are heard around it, `shortcut` lines. |
| `page/drag.mote` | `DD` | `drag=`, `dropped=`, `over=`. |
| `page/touch.mote` | `PH` `PCD` `SW` `TF` | A pointer held from its press to its one end, however that comes; `pointerdown=` with `pointermove=` or `pointercancel=`; `swipe=`; `el.transform`. |
| `page/routes.mote` | `RT` `RTA` `RS` `HR` `RTP` `RTQ` `RTF` `RTT` | Routes, after `#` or as paths; the page's whole address, origin and links; its query; what stands after `#` (`RTF`), and that taken out of the address by the page's first script (`RTT`, with `TAKE_FRAGMENT` in `build.rs`). |
| `page/virtual.mote` | `VR` `VLS` `SEEN` | `for … virtual`: the rows in view drawn, spacers for the rest, sizes in Fenwick trees over the lines, the row at the top held still, keys, aria, a place kept for coming back; a row of one by key or place, `el.inView`, `el.shown`; `seen=`. |
| `page/screen.mote` | `RO` `SC` `SCI` `SCP` `SCF` `SCW` | `root` (values of the whole page, less motion); `screen`, `scheme`, in front and focused; `screen.idle`; print; the whole screen; `screen.awake` (a wake lock, asked for again whenever the page is seen). |
| `page/workers.mote` | `WK` `NWS` `WX` `SK` | The worker pool; ending a call in a worker that a `newest` action called off; a battery's wasm in a worker, asked of the page or unpacked there; `search`'s calls, a searcher's to the search worker (one of the pool's source, kept apart), the rest to the pool. |
| `page/delivery.mote` | `APB` `APU` `APH` `CSP` | How the app was delivered ([delivery.md](delivery.md)): `app.build()`; the page's side of `update=ask` (`on app.update`, `app.check()`, `app.update()`); what was handed to the installed app (`on app.handed`, `APH`); and, only in a page that says `policy=strict`, a sheet handed over as a constructed style sheet (`CSPA`) and text made into elements with its `style=` set through each element (`CSPH`). |
| `page/lazy.mote` | `BL` `WXL` `REQ` `CSQ` `CSR` | The batteries as files of the build ([Batteries](#batteries)): fetched and compiled by the page when first asked for, and handed to the workers; `re`'s engine fetched before a pattern can run. |
| `page/batteries.mote` | `BU` `MP` `AU` | The drivers of mp4, aud; `b.url()`. |
| `page/chart.mote` | `CH` | The `chart` element: data into columns, the charts' own worker and the plot battery in it, painting the draw list, the axes' words, the pointer, zoom and brush, the keyboard, groups ([charts.md](charts.md)). |
| `shared/batteries.mote` | `SY` `SE` `FT` `ZP` `IM` `HT` | The drivers of syntax, search, font, zip, img and html: the back end has them too (`html`'s is called there by name, `HT(…)`, not through `W`). |
| `page/htmlframe.mote` | `HF` | `htmlframe`: a letter cleaned by `HT` (with the tree), built element by element into a sandboxed frame of the page's own with a policy of its own, its height followed, its links the page's ([text.md](text.md#htmlframe)). |
| `shared/keys.mote` | `AES` `X25` `EDS` `RNB` `A2` `KEM` `POW` | `crypto`'s own keys ([data.md](data.md#keys-of-the-pages-own)): AES-256-GCM, X25519 and Ed25519 over the host's WebCrypto (X25519 on the back end over `node:crypto`); the drivers of argon2 (with BLAKE2b), mlkem (with SHA-3) and pow, each of which zeroes its module's memory after a call that held a secret. Every fn here is whole in itself, so that a worker can be sent it when an `off fn` calls `crypto`. |
| `shared/sheets.mote` | `SH` | `csv` (read and written here, in a worker for a whole file) and the driver of the xlsx battery, which uses `zip`'s and `flate`'s Rust as modules of its own. |
| `shared/pdf.mote` | `PDP` `PDF` `PB` | `pdf`: the parts of a document, a call (its bytes beside its JSON, pictures decoded by img first), the driver. |
| `page/font.mote` | `UFT` | `font.use`. |
| `page/storage.mote` | `DB` `ROOM` `FULL` `FS` `FSOP` `FWR` `NFP` `NXP` `FSK` `SQ` | `db`, how much room there is, a full disk's failure, `fs` (and its `append`, `info`, `entries`, `move`, `mkdir`), what `fs.open` reads a private file through (in a worker, in place) and `fs.writer`, a file as a page's `net.send` body and `progress` (an `XMLHttpRequest`), the file chooser, `sql`. |
| `shared/files.mote` | `RDR` `FSO` `ZPS` `TAR` | Large files a piece at a time ([data.md](data.md#large-files)): a reader over a source (`RDR`, and `RDB` over a Blob), `fs.open`, a .zip's list read from its end with zip64 and an entry inflated as it is read (`ZPD` `ZPN` `ZPO` `ZPI`, the zip battery's op 8, `flate::inflate_more`), `zip.gunzipStream` (`ZPG`), `tar.entries` (`TRE`). Every fn is whole in itself: an `off fn` that reads a file is sent them by name (`build.rs`, `worker`). The back end's `FSOP` and `FWR` are in `server/data.mote`. |
| `page/rpc.mote` | `LBK` `RPC` `NO` `LV` `LVR` `FUP` | Calls to the back end (each under an id, sent again when it got no answer); `net.online`; live values and events; a model's read kept by its rows ([below](#rows-not-lists)); `files.upload`, `files.sending`. |
| `page/window.mote`, `shared/window.mote`, `server/window.mote` | `WV` `WINM` `WIN` | A `live` read kept a window at a time ([below](#a-list-a-window-at-a-time)): in the page the value (`WV`), the places a `for … virtual` draws (`WVD`) and their keys (`WVK`), the writes shown at once put in it; on both sides the places held and the steps that change them (`WINM`); on the back end each window's reads and turns (`WIN`, wrapping the line and `modelTell` once `WINS()` is called). |
| `page/writes.mote` | `MW` | A model's write from the page, shown at once ([below](#a-write-shown-at-once)): the row expected, the writes in order, what is taken back; `pending(row)`. |
| `page/model.mote` | `MX` | Local models: the page's SQLite under the engine, resources that follow writes. |
| `shared/model.mote` | `MDM` `MDK` `MD` | Models: matching a row to a filter, and two values in the order SQLite gives them; a model's checks in the page; the engine (an operation to SQL, rules, turns, `atomic`, migration). |
| `page/popover.mote` | `DG` `PO` `CL` `CB` `UT` | Dialogs, popovers and tips, `close()`, `clipboard`, `copy`/`focus`/`scroll`. |
| `page/speech.mote` | `SP` `TS` `SN` `SR` | Speech, `toast`, `scan`. |
| `page/notify.mote` | `NT` `NTK` `NTO` `NTE` `NTSO` `NTW` | `notify`, `push`: asking, showing and `notify.allowed`; what kind of device this is, and which notes its page hears; a notification pressed (`on notify.opened`); signing a device up and off; `notify.show` with buttons (`NTSO`), and showing in the service worker, counted (`NTW`, `push.js` only). |
| `page/paint.mote` | `PA` | `paint`, `canvas layers=`. |
| `page/surface.mote` | `SF` `SFL` `SFT` `GLS` | `surface`; layers and reading back; typing; `surface gl`. |
| `page/boxes.mote`, `trace.mote`, `three.mote` | `BX` `BT` `TH` | The 3D canvas, its lit picture, `three.*`. |
| `page/pictures.mote` | `BXP` `BTP` | Pictures on materials (`map`) and a thing's sides in a material of their own (`sides`): the page's decoded pictures, a context's array texture, the program that draws what is dressed (`BXP`), and what the tracer's shader is given to read them (`BTP`, with `render=`). `BX` and `BT` only `use` them (`typeof … != "undefined"`): the compiler asks for them where the program says `map` or `sides` as a field of a record (`Gen::dress_said`, `build.rs`), so a scene with neither carries none of it. |
| `page/video.mote`, `reel.mote` | `VD` `RL` | `vid`, `aud`, `reel`. |
| `page/camera.mote` | `CM` | `camera`, `cam`. |
| `page/media.mote` | `REC` `MEL` `SND` `TTL` | `mic.record` and `mic.meter`; an `audio` or `video` led from the page; `sound`; `title` and `badge`. |
| `page/rtc.mote` | `RTC` `RTCA` | Calls: `rtc.join`, each pair's connection, `video of=`; rings; Answer pressed on a ring's notification (`on rtc.answer`, `RTCA`). |
| `page/glass.mote` | `GL` | `glass`. |
| `page/editor.mote`, `terminal.mote`, `flow.mote` | `ED` `TM` `FL` | The widgets. |
| `page/richtext.mote`, `shared/richtext.mote` | `RX` `RXM` | `richtext`: the editing surface, drawn from the document, its input (`beforeinput`, and a composition read back), toolbar, link field, paste and pictures (`RX`); the document itself, whole in one fn so that a worker can be sent it: made whole, its operations done and taken back, mail of it (`RXM`). |
| `shared/bytes.mote` | `rmv` `BY` `BYJ` `BYN` `SHA` `HMAC` `CEQ` `CRC` `RND` `CV` | `remove`, bytes (`join`; `read` and `write`), hashing (`crypto.hash`, `hmac`, `equal`, `crc32`), random, a field's number. |
| `shared/check.mote` | `CHK` | `check(value, Shape)`: a value held to a shape as api.json describes it (the checker writes the description, `types/outside.rs`), the path and what is there when it differs. |
| `shared/patterns.mote` | `RE` `REI` `INF` | `re`; its engine made from the wasm carried beside it (the back end, a page that is one file), and the inflate that needs. |
| `shared/net.mote` | `NET` | `net`. |
| `shared/js.mote`, `page/js.mote` | `XJ` `XJB` | `extern js`: a file loaded once, its export called and waited for, what it gives checked against the declared type, `mote:gone` for an element handed to it; where the page's files are found from ([js.md](js.md)). |
| `shared/time.mote` | `TI` | `time`: a moment in a zone and a language, on `Intl`. |
| `server/serve.mote` | `VAL` `CTX` `SRV` `DET` `BG` | Argument checks, who is calling, the server; `detach`; `server start` and `server every`. |
| `server/data.mote` | `DATA` `KEPT` `DBS` `ENV` `SQ` `FS` | The data folder and the settings that name folders (`MOTE_SQL`, `MOTE_BACKUP`); the folders nothing is served from (`KEPT`: all a back end that keeps nothing has of this file); the one place a database on disk is opened (a write-ahead log, a wait, snapshots) and, at the stop, closed (a last snapshot first); `env`, `sql`, `fs` and `fs.folder`. |
| `server/pg.mote` | `PGW` `PGS` `PGA` `PGQ` | Postgres for the back end's own stores (`MOTE_SQL=postgres://…`): the wire protocol on part TCP's connections (TLS, SCRAM, the pool, statements kept by name unless a pooler stands before it, LISTEN); the setting; and SQLite's SQL as the engine writes it, said again as Postgres's (`$n`, `IS NOT DISTINCT FROM`, `mote_rowid`, the types). `server/model.mote` runs a turn on it (a lock of the transaction), `server/shared.mote` brings its schema and carries the bus on it (`mote_changes` and NOTIFY); `PGA` says the accounts' statements again for their tables (`mote_user`, `mote_session`, …) and counts `limit`s for every back end (`mote_limits`). |
| `server/move.mote` | `MOVE` | `mote migrate --to postgres`: the mover a program is built as in place of the server (`build::compile_move`, `MOVE(schema, plan)`; its runtime is this part, what it needs, and `NOTE`, `FILE`, `AUTH` where the program has them: no part that asks for a setting of its own as it loads): the data folder's SQLite files taken with an exclusive lock, the target's schema made by `modelSchema` under the name of a move not over, a copier a store (models, records, accounts, notify, the log's segments into `mote_log_rows`, the facts; their tables made by parts ST and NOTE first) in batches written down in `mote_move`, every table counted and summed on both sides; with `MOTE_FILES`, the stored files sent to the store after their rows by part FILE's own requests (`storeStream`, SigV4) and listed there after; the report. In no other build. |
| `server/shared.mote` | `BUS` `MSH` `LCK` | Several apps at one database: the bus (`publish`, `subscribe`, an adapter), the lease (and `lock(name)` on it), a program's start-up among other programs' tables, and the database as the bus's first carrier (`mote_changes`, polled). At the stop its leases are let go and the polling ends. |
| `server/proc.mote` | `PROC` | `proc`: other programs. |
| `server/socket.mote` | `TCP` `WSC` `LSN` | `tcp.open` (on `Bun.connect`: TLS checked here, as Bun does not refuse a certificate it could not verify), reading by count, delimiter or as it comes, `startTls`, a proxy's CONNECT, the pools of `tcp.take`; `ws.open` (the host's WebSocket), reconnecting; `server listen` (on `Bun.listen`: caps, a limit by address, paused while much waits unread, certificates read again as their files change, TLS as the server through a TLS listener of its own on 127.0.0.1, since Bun 1.2's `upgradeTLS` of an accepted socket crashes when it closes); every one closed at the stop. |
| `server/oaep.mote` | `OAEP` | `crypto.encrypt` and `crypto.decrypt`: RSA-OAEP. |
| `server/webhook.mote` | `WHK` `WHO` | `webhook.check`: the schemes, each signature worked out over the bytes sent and compared in constant time, the moment held to the tolerance, the body read; `webhook.once`: an id kept in `mote_webhooks`, in the turn the caller holds. |
| `server/once.mote` | `ANS` | A call answered once: each caller's ids and the answers they were given. |
| `server/stack.mote` | `STK` `PFD` | A stack by the program's lines: the source maps beside the module, read and decoded once, when a fault first needs them; the runtime's frames folded. The door a page tells its faults at (`mote.fault`). |
| `server/log.mote` | `CID` `LOG` `STOP` | A call's id; the log (one line of JSON), faults and `server on failure`; the one place that hears signals, and stopping in order. |
| `shared/clock.mote` | `CLK` | What time it is, asked in one place (`NOW`): the machine's clock unless a test set it. Not asked there: how long something took, and how long to go on waiting for something real. |
| `shared/opening.mote` | `MDL` | What is done last as the models' database is opened (the back end's `migrate` blocks). |
| `server/jobs.mote` | `JOB` | `job fn`: the queue (`mote_jobs`, in the models' database), the worker's loop, retries, `jobs.…`, stopping. |
| `server/at.mote` | `AT` | `server at`: a timer for each block's next moment, the lease, and the moment written down as run (`mote_ran`). |
| `server/migrate.mote` | `MIG` | `migrate`: each block once for a database (`mote_migrated`), in a turn of its own, as the last part of opening it. |
| `server/test.mote` | `TEST` | `mote test`'s harness: the runner, a test's door (`TCALL`), `expect`, the clock, the stand-ins for `net`, `proc`, `emit` and `notify`. A test build is the whole back end as one fn, called once a test. A `test "…" page` (its fn is named `testpage$…`; the module then begins `const TPAGE=1;`, and `mote test` builds the page beside it and writes the driver there): `TPG`, the listener begun by the harness at a free port for that test, a tab of the run's one browser, `as` setting the session's cookie in it, `clock +` advancing the page's clock too. |
| `page/usage.mote`, `server/usage.mote` | `UG` | [Usage](usage.md), only in a program that says `usage=on` and has a `server on usage` block: in the page, what was seen (`UGS` a route shown, `UGA` an action's run, `UGT` `track`, and with `autocapture=on` presses and fields changed) and its sending, on the open line (part `LV`, which a page with usage on keeps) or posted; on the back end, the calls and jobs wrapped (`UGW`, `UGJ`), the door a page posts to (`UGD`), the open line's messages heard before `LIVE` hears them and its tabs here and gone (`Bun.serve` wrapped: `usageServing`), and the handing over (`UGF`, one more `server every`). Nothing a built program carries without usage knows of it (only the test harness asks `typeof UGF`). |
| `server/zz_admin.mote` | `MDG`, `AUL`, `INFO` | What an [admin page](admin.md) asks of the back end, each only in a program that says it: `MDGL` and `MDGO` (`models.list()`, `models.of(name)`: a name looked up in the schema, then the engine's own `MD`), `AULL` and `AULS` (`auth.list`, `auth.sessions`), `INFO` and `INFA` (`app.info()`, `app.access()`; the build hands over its name, the settings it reads and, if asked for, the access report: `INFS`). None is in the server's table of calls. The file's name sorts last so that the parts it needs keep their place in every other back end. |
| `server/net.mote` | `NETS` `NRC` `NFL` `NPC` | `net` on the back end: `public: true` (a request led step by step to addresses looked up once and checked), `net.lookup`, `net.public`; a name's records of one kind (`net.lookup(host, kind)`), typed; `net.send` to a file as the answer arrives (`to`, `resume`) and from one (`body: {file, from, length}`); a host's pace and breaker (`net.pace`, `net.breaker`, `net.health`), each try through them. |
| `server/auth.mote` | `AUTH` | Accounts and sessions. |
| `server/live.mote` | `LIVE` | Live values and events. |
| `server/rtc.mote` | `RTS` `RTSP` | Calls: rooms, the guard (`server call`), signalling passed on, ICE servers, rings; rings pushed to devices and declined from one (`RTSP`, where the program notifies and shows rings). |
| `server/model.mote` | `MX` `MDD` | Models on the back end: Bun's SQLite under the engine, `me`, hooks, which `live` values a write touches and what each is sent of it ([rows](#rows-not-lists)); the door (`/rpc/T.op`). |
| `server/push.mote` | `PUSH` `NOTE` | Web Push, notifications. |
| `server/batteries.mote` | `WK` `WX` | Batteries on the back end: the same wasm, run in place. |
| `server/dom.mote` | `DOM` `DOMK` | A page's DOM stood in for on the back end: elements, texts, fragments, attributes, styles, a parser for the markup the compiler writes, simple selectors; what the page is drawn into ahead of time. |
| `server/ahead.mote` | `AHD` `AHX` | `render=ahead`, in the back end: the process that draws begun (Bun again, with its script `AHWS` on standard input, which the build writes from parts `DOM` and `AHW`; none of the back end's settings; messages both ways), each drawing asked of it and timed, the page's calls answered here as the asker's and its `live` values read over the line's handlers with no socket, what was drawn written into the page with what the calls answered, and the title and description the page set there (`root title=`, `root description=`: `TTL`, `DSC`) into its head; a process that does not come back is ended and another begun, and one grown past `MOTE_AHEAD_MB` or `MOTE_AHEAD_TURNS` is let go when its last drawing is in; a path that could not be drawn is not tried for a minute; with `MOTE_AHEAD_KEEP`, drawings kept by address and by who is signed in, and drawn again behind when old. |
| `compiler/src/main.rs`: `draw_pages` | | `mote build`, for a program drawn ahead with no back end of its own (`Output::drawn`): the back end just built run at a free port, each written-out route asked for, and what it sent written as that address's `index.html`; the page as built kept as `server/index.html` (which `serve.mote` then draws from). |
| `server/aheadwork.mote` | `AHW` | That process: the page's script run in a context of its own (`node:vm`) against the stand-in, until at rest or the limit; its `fetch` and its `WebSocket` are messages to the back end; a `Worker` of the page's is its script run there in a context of its own (with `DecompressionStream` stood in for over `node:zlib`, and compiled `WebAssembly` modules kept, for the batteries). |

### Rows, not lists

A `live` value over a model's read (`find`, `get`, `one`, `count`, `has`)
is kept by the rows a write changed, where a row is enough to know what the
read now gives ([models.md](models.md#what-a-write-sends-a-page) says when
it is not). Three pieces:

- **The back end** (`server/model.mote`). `modelDone` calls `modelTell`
  before anything is waited for, so turns are told in the order they were
  kept. For each subscription a changed row touches, `rowsPlan` says
  whether the read is one a row can tell (the filter is one `rowMatches`
  answers exactly as the SQL does; no `after:`; and so on), worked out once
  and kept on the subscription. If so, `rowsSend` is queued in the
  subscription's own line (`subQueue`, in `server/live.mote`: runs and rows
  of one value go out strictly in order), and there `rowFor` works out, for
  that reader, whether they could read the row as it was (`was`) and the
  row as they may have it now (`now`): from the row in memory where the
  `read` rule is about the row and `me` (`ruleHolds`, which answers as SQL
  would, NULLs included, or declines), else by reading the row again by its
  key as that person. One answer a person a turn is kept, and one for
  everybody where neither the rule nor a `private` field is anyone's own.
  A subscription that did not say `rows: 1` when it was made is always run
  again.
- **The clock.** `modelEnd` counts commits in the same breath as the
  `COMMIT`. A run of a subscription notes the count when it began and when
  it ended (`sub.ran`); a turn's rows carry the count at their commit. Rows
  from a turn the last run already read are dropped; rows from a turn that
  was kept *while* it ran are sent without the claims that need an exact
  starting point ("just added, so last among equals"; a `count`, which is
  run again instead). With `MOTE_SQL` nothing is exact (another process's
  writes are heard later): rows are still sent, each read again by its key.
- **The page** (`page/rpc.mote`, part `LVR`, in a page only when it keeps a
  model's read). `rowsApply` puts `[1, row, how]` and `[0, key]` in the
  value held: by key, so doing it twice is doing it once; at the place the
  order gives (`valueOrder`, in `shared/model.mote`, orders text as SQLite
  does, by code point, where JavaScript's `<` goes by UTF-16); kept to
  `limit` or `last`. Where the row and the value do not say what the read
  now gives, it returns nothing and `rowsAsk` sends the `sub` again: the
  value comes whole, and rows that arrive before it are dropped. A list
  made this way is marked (`__s`), and `for` (`page/core.mote`, part `L`)
  leaves alone a row whose item is the very one it holds.

Two settings of the back end, for looking:

| | |
|---|---|
| `MOTE_ROWS_CHECK=1` | After the rows of a turn are sent for a subscription, the read is also run, and the page is sent a number for what it gave (`{t: "chk", id, h}`: FNV-1a of the JSON); the page holds it against its own value, counts (`self.__moterows`: `{rows, asked, same, differ}`), and on a difference says so on the console and asks for the value again. Sent only when nothing more is waiting to be told for that value, so a difference is a fault, not a race. The d1b runs are started with it. |
| `MOTE_ROWS=0` | No rows: every kept read is run again after a write, and sent whole if it differs. For measuring, and for ruling rows out. |

**For a write the page makes itself** (groundwork for showing a write at
once; nothing calls it yet): `ROWP(model, keyName, key, row)` in part `LVR`
puts a row the page expects to be kept (or, with `row` none, takes the row
of that key out) in every `live` value on the page it belongs in by that
value's filter (`find`, `one`, `get`; not `count`, `has`, or a `find` with
`with`), with the same code a row from the back end goes through, so the
row the back end then sends, or the answer to the write, lands on the same
key and replaces it. It gives back a fn that undoes it: each value gets
the row it held of that key again, or none of it, and a value that cannot
be put back so is asked for whole. The page knows no `read` rule, so what
it puts in a list is a guess until the back end's row arrives: the caller
undoes it when the write fails. (A test reaches it as `self.__moterows.put`:
`tests/live_rows.real.mjs`.)

### A list a window at a time

`live xs = T.find(f, {order, window: n})` ([models.md](models.md#a-long-list-a-window-at-a-time)).
A program that says no `window` carries none of it, page and back end byte for byte as
before: the pieces are parts of their own, and the back end's is put in front of what it
needs from outside it.

- **The compiler.** The checker types the read `T?[]` and holds it to what it needs
  (`types.rs`, `window_checks`: `H327`–`H332`). `emit.rs` writes `WV(…)` for it in place of
  `LV(…)` and notes its name; `view.rs` writes a `for … virtual` over that name with its row
  fn wrapped, `WVD($xs, row)` (each row it makes tells the value its place while it is
  drawn), and its key wrapped, `WVK($xs, key, measured)` (a place not come yet has a key of
  its own, by its place; in a list whose rows are measured, a row just come to a place keeps
  that key for the one drawing it comes in, `fresh`, so that the list, which holds the row at
  the top of its view still by its key, holds it there; a moment after it is drawn again
  under its own). A
  page that has `WV` has its back end call `WINS()` before it starts (`build.rs`).
- **What both hold** (`shared/window.mote`, `WINM`): the count `n`, and the places held,
  `held`, each `{i, row, ord}` (`ord`: the row's order field and key). The order is the field
  and then the key, so a row's place among the held ones is told from its two values
  (`windowAfter`). The steps: `[0, n, key]` begin again, `[1, at, rows]` rows at places,
  `[2, at, key]` a place in that is not held, `[3, at, key]` a place out, `[4, at, length]`
  places let go of, `[5, at, row]` a place in holding a row. `windowRemoving` and
  `windowInserting` say which step a row out or in is; `windowStep` does one. The back end
  does each to its own copy before it sends it, so the two copies are the same by doing the
  same.
- **The line.** The page asks with a `sub` of `T.find` whose options say `window` (and
  `wanted`, the places it wants, and `after: 0`, which tells part `MW` to leave a row new to
  it to this part), and sends `{t: "want", id, wanted}` as it scrolls. Every answer is a
  `val` whose value is `{"~": [n, step…]}` (`n`: the count after the steps, which the page
  holds its own against, and asks again where they differ). A plain `val` and the `sub` sent
  again on every opening of the line are LV's own: nothing in `rpc.mote` knows of windows.
- **The back end** (`server/window.mote`, `WIN`). `WINS()` wraps `Bun.serve` (the line's
  messages are heard here before LIVE hears them: a window's `sub`, `want`, `unsub`, each
  counted against the line's rate), `modelTell` (every turn), and `changedHere` and
  `changedAll`. Each value (`socket.data.wins`) has its own line of work (`tail`). A read is
  made in a turn of its own (`modelTake(false)`): no write is kept while it reads, and every
  write kept before has been told, so it is the data at one clock (`at`); a turn told later
  whose clock is not past it is in the read already. A turn's rows are taken down as it is
  told (`rowsOfTurn`), and done to what is held in the value's line (`windowTurn`): each row
  out and in by `windowMember` (the filter by `rowMatches`, the `read` rule by `ruleHolds`
  on the row as it was and as it is, for that reader), the row the page is given by
  `shownRow` (read again by its key where the model has bytes or files). Where that cannot
  be told, or the turn is not one a row can tell (more than eight rows, told without them,
  another model's, another process's), the value is read again whole (`windowWhole`).
  Wanted places not held are read from the held row beside them by order and key
  (`windowBeyond`), else by offset (`windowFill`), in a turn, and only when no turn of the
  value is still to be done (`pending`), else after it.
- **The page** (`page/window.mote`, `WV`). The value shows `held`, with every row of the
  model that a write of the page has not had answered (and one answered or taken back, until
  the back end has spoken of its key since: `windowAgrees`) put where it would stand
  (`windowPlace`, with `windowInserting`). It hears of those writes through part `MW`'s
  `writeTick`, whose `tell` it wraps; to `MW` the value is a `find` whose `last` is the rows
  held, so a `set` or a `del` of a row in it finds its row. `windowWant` turns the places
  drawn into the windows wanted.

### A write shown at once

`T.add`, `T.set` and `T.del` in a page, for a model the back end keeps
([models.md](models.md#a-write-shows-at-once)). The pieces:

- **The compiler** (`emit.rs`, `at_once`) decides at each call whether the
  write is one the page can show: not under `confirmed` (the call, the
  model, `app … writes=confirmed`), not in a `fn` that passes its failure
  on, not where the row is used after a `server before` hook may have
  changed it, not `addAll`/`setAll`/`take`. If so it writes
  `MW("T","add",[args],$action,late)` in place of `RPC("T.add",[args])`:
  `$action` is the action the call stands in, `late` the `else` beside it
  as a fn of the failure. The page is told the model's key and what fills
  its fields (`MWS({…})`, from `model::page_data`: nothing hidden, no rule).
- **`MW`** (`page/writes.mote`) keeps one record for each row with a write
  not yet answered: `base`, the row as the back end last said it was, and
  `ops`, the writes in order. What the page shows of the row is `base`
  with `ops` done to it (`folded`), put in each kept value by the code a
  row from the back end goes through (`rowsPut`/`rowsApply` in `LVR`). An
  answer, a refusal, a row on the open line (`MWR`) and a whole value
  arriving (`MWV`) each change `base` or `ops` and show again; so the order
  in which the answer and the row's message arrive does not matter, and a
  change queued behind another is not lost from the screen when the
  first's row arrives.
- **One line of writes.** They are sent one at a time, each under the id it
  was given when made (`RPC(name, args, {id})`), and every other call
  waits for the writes made before it (`MWD`, asked by `RPC`). A write that
  got no answer stays first in the line and is sent again when the page is
  online (an effect on `NO`, and a timer); past `writeLimits` the line is
  failed as `"offline"`.
- **Who is signed in** (`= me`): the page asks the open line when it opens
  (`{t: "who"}`), and the back end says. Until it has, a row that needs it
  is not shown ahead.
- **A row its writer may not read**: the door's `add` and `set` look, after
  the write, whether the row passes the `read` rule for the caller (one
  `has` by key; not where the rule is `anyone`), and the answer says so
  (`"u": 1`): the page takes the row back.
- **MOTE_ROWS_CHECK**: while a model has a write not yet answered, what
  the page holds of it is by design not what the back end has. A number
  that arrives then is kept (`one.check`) and held against the value when
  the last such write is answered, unless more has arrived for that value
  meanwhile.
- **A call answered once** is what makes sending a write again safe:
  `server/once.mote` (memory), and for the door's writes `modelAnswered`
  in `server/model.mote`, which reads and writes `mote_answered` inside
  the write's own turn ([back-end.md](back-end.md#a-call-is-answered-once)).

## Batteries

A battery is a piece of Mote's standard library written in Rust and run as
wasm: `argon2`, `mlkem`, `pow`, `zip`, `img`, `mp4`, `aud`, `scan`, `search`, `syntax`,
`font`, `xlsx`, `pdf`, `re`, `plot`, `layouts`, `html`, `charsets`. (`batteries/flate/` is not one: it is the inflate and deflate that
`zip`, `img`, `font` and `pdf` share; `pdf` takes `font`'s reading of a font
file, `batteries/font/face.rs` and its parts, by `#[path]` too.)

**Built.** `compiler/build.rs` compiles each `batteries/<name>/lib.rs` with
`rustc` alone (`--target wasm32-unknown-unknown`, no crate, no `std`) and
leaves `<name>.wasm` in the build's output folder. `batteries/rt.rs`,
`include!`d by each, is the allocator and the calls that carry data in and
out: the page writes input into memory from `alloc`, calls the battery's
entry, and reads the result at `out_ptr()` for `out_len()` bytes; `reset`
frees everything. A battery's pure core (`core.rs`) is also compiled into
the compiler's unit tests (`#[path]` in `main.rs`), where it is tested
natively.

**Carried.** `build.rs` holds each wasm with `include_bytes!`. When a
program uses a battery (`g.batteries` in `emit.rs`), the page is handed it
beside the battery's driver (`worker` in `finish`), in one of two ways
(`Carry` in `build.rs`):

- **As a file of the build** (`mote build`, `mote dev`). The wasm is written
  once, as it is, at `assets/<battery>.<hash>.wasm` (`batteries()` in
  `build.rs`: the first eight digits of its contents' hash, as an asset's
  name has, so the back end and any host that knows the convention send it
  to be kept for good), and the page carries only that path:
  `WK([…fns],{IM,IMW:"assets/img.1a2b3c4d.wasm",WX})`. Nothing of a battery
  is in the page, and none is fetched until something calls it. The files
  are in the service worker's list, so an installed app has them offline;
  with a back end a `.gz` is written beside each (`ops::zips`); `mote dev`
  writes nothing and answers the path from the compiler's own copy
  (`battery_at`).
- **Inside the page** (`mote build --single`, which is one file and opens
  from `file://`, where nothing can be fetched; and `mote test`): deflated,
  as base64, `IMW:"…"`.

A path has a `.` in it and base64 never has: the runtime tells the two apart
by that.

**Called.** A call compiles to `await W("IM",[op,…args],moved,token)`
(`runtime/page/workers.mote`). The pool sends it to a free worker. In the
worker, the driver (a part such as `IM` in `runtime/page/batteries.mote`)
calls `WX(driver, IMW)` for the wasm on first use, copies the arguments into
its memory, calls it, and copies the answer out. A driver's text is sent to
the worker as it is, so it may use only its parameters, its locals, itself,
`WX` and the host.

**Fetched by the page, once.** Where `IMW` is a path, `WX` asks the page for
it (`postMessage([0, path])`) and waits. The page (part `BL`,
`runtime/page/lazy.mote`; `WXL` ties it to the pool) fetches the file and
compiles it as it arrives (`WebAssembly.compileStreaming`, or from the bytes
where the host does not say `application/wasm`), keeps the promise by path,
and answers every worker that asks with the module (`[0, path, module]`: a
module is handed over, not compiled again). So a battery is fetched on its
first call and compiled once however many workers run it; the address is
the page's own (`document.baseURI`: a worker made from a text has none);
and a page drawn ahead counts the fetch among what its first drawing waits
for. A file that cannot be fetched fails the call (`[0, path, 0, words,
"offline"]`: a failure of kind `offline`, said as a call the back end could
not be reached for), is forgotten, and is asked for again by the next call.

**On the back end** there is no pool: `runtime/server/batteries.mote` runs
the same wasm in place. `search`, `syntax`, `font`, `zip`, `img`, `xlsx`, `pdf`, `argon2`, `mlkem`, `pow` and `html` are offered there
(`finish` in `build.rs` lists them).

**`re` is called where it is used**, not in a worker: a pattern runs in a
derive or a binding, where nothing may wait. `batteries/re/core.rs` is the
engine (also compiled into the compiler, which reads a written-out pattern
with it: `types/re.rs`, H300 to H303, and into any battery that wants it:
`#[path = "../re/core.rs"] mod re;`); `batteries/re/lib.rs` is its wasm
interface, with an allocator of its own that gives memory back, since the
compiled patterns and the last text stay between calls. Part `RE`
(`runtime/shared/patterns.mote`) drives it. Its Unicode tables are
`batteries/re/tables.rs`, written by `tools/re-tables.mjs` from Node's own
RegExp; `tests/re_table.mjs` writes the cases the engine is held to (`cargo
test re_`), and `tests/re_diff.mjs` holds the runtime part to the host's
RegExp on random patterns.

Where the engine comes from depends on the build, as for the others:

- On the back end, and in a page that is one file, its wasm, deflated, goes
  beside `RE` as `REW`, and part `REI` makes it when a pattern is first run
  (part `INF` inflates it at once).
- In a page of `mote build` or `mote dev` it is a file like any battery,
  `assets/re.<hash>.wasm`, and `REW` is its path. A pattern cannot wait for
  a fetch, so the engine is brought **before any code that can run a pattern
  runs**, and `compiler/src/lazy.rs` works out where that is, from the
  program's names alone:
  - *The page's own lines run one* (a top-level `state`, `derive` or
    `resource`, a model's `check`, the markup outside every component, a fn
    that runs one and that nothing is seen to call, a component that does
    and is always drawn). Then the page waits: its head asks for the file
    as the page arrives (`<link rel=preload as=fetch crossorigin>`), and
    its script begins with `await REP();`.
  - *Only components do.* A component whose own code can run a pattern (its
    declarations, its markup, its handlers, the fns they call) is drawn
    under the engine's arrival: where one is written, `view.rs` writes
    `I(parent,REQ,…)`, an `if` on `REQ()`, which is true at once when the
    engine is here, and otherwise asks for it and turns true when it
    arrives. Nothing of the component runs before. A component that only
    draws such components says `REP();` as it is drawn, so the file is on
    its way before the inner one needs it. A page that never draws one never
    fetches the engine. And while the engine is on its way, a worker's
    answer waits for it (`workers.mote`): what is drawn from the answer (a
    Markdown document's links) is then drawn whole, not a moment after the
    words around it.

  This is sound because code runs only by being named: whatever runs a
  pattern was reached, name by name, from the page's own lines (the page
  waited) or from a gated component's (it was drawn after), and the engine,
  once here, stays. Names are read without scopes, so a local that shadows
  `re` only makes the answer more careful. Part `REQ`
  (`runtime/page/lazy.mote`) holds `REP` and `REQ`. If the file cannot be
  fetched, nothing hangs: the page starts, the gates open, and a pattern
  that is then run fails as a wrong pattern does (kind `offline`) and asks
  for the engine again. The kit's `Markdown` is the common case: its links
  and pictures test an address with `re`, so they are gated, and a page
  with Markdown on one route fetches `syntax` and `re` when that route is
  first shown.

**The charsets battery is placed as `re` is.** `b.text(label)` with a
legacy multi-byte set (Shift_JIS, GBK, Big5, …) reads it with
`batteries/charsets` (the WHATWG Encoding Standard's decoders, `core.rs`,
over its index files: `tables.rs`, written by `tools/charset-tables.mjs` as
runs of pointers in LEB128 and base64, read back when the battery is
compiled, written out into memory of its own the first time an encoding is
asked for). Such a read cannot wait either, so the compiler marks every
`b.text` whose label is not written out as another set's (`TXB`,
`lazy::label_may_be_multibyte`), and `lazy::charsets` places the battery as
`lazy::re` places the engine: `await CSP();` at the page's start (and a
`preload` link) where the page's own lines can read one, `I(…,CSQ,…)` around
a component that can (`()=>REQ()&CSQ()` for one that needs both), `CSP();`
in one that draws such a component. A call the page makes of an `off fn` that can read one
(`lazy::charsets_fns`) first has the worker ask the page for the file
(`CSR`, by `WX`): the fn's entry in the worker's table is wrapped (`CSRW`,
built in `finish`), so the fn itself, which other fns in the worker call
as it is, is not made to wait. On the back end it is carried
inside, deflated (`const CSW="…"` from `runtime_for`), and made at the first
read. The runtime's `if CHARSETS` (part TXC) is turned on only for a side
whose runtime has `TXB`, so a program that reads none of these is built as it
was. Its tests: `compiler/src/tests_charsets.rs` (the decoders natively, and
the builds) and `tests/all.sh real_charsets`.

**Charts keep their data.** `plot` (and `layouts`, the same code built with
`--cfg rare`: the rarer charts and the tree and flow layouts) is driven not by
the pool but by a worker of the charts' own (`runtime/page/chart.mote`, part
`CH`, which makes it from `chartServe`'s text), because a chart's columns stay
in the battery between calls: a frame is sent once, and then only views are
asked for. Its allocator gives memory back (`batteries/plot/wasm.rs`). The
compiler hands both over as `CHI("…","…")` (paths or base64, as above), the
second only where the program names a rarer chart (`tables::chart_rare`); the
worker asks the page for a file the same way the pool's do, when a chart first
needs it. [charts.md](charts.md).

SQLite is the exception: it is the SQLite project's own wasm, driven by
`batteries/sqlite/glue.js` in a worker of its own
(`runtime/page/storage.mote`, part `SQ`). In a build both are files
(`assets/sqlite.<hash>.wasm`, and the glue as `assets/sqlite.<hash>.js`),
fetched when a database is first opened: `SQI("assets/sqlite.….js","assets/sqlite.….wasm")`.

`tests/expect/real_batteries.txt` is the record of all this as a browser
sees it (what the page holds, what it asks for and when, a file that is
gone, offline, `--single`, drawn ahead); `compiler/src/tests_batteries.rs`
holds the compiler's side.

**A page drawn ahead** (`render=ahead`) runs the same script in the back
end's drawing process, where a battery's file is fetched from the back end
itself, as any call of the page's is (`runtime/server/aheadwork.mote`), and
each module is compiled once for the process. The files a page was drawn
with are written into the head of the page sent, as `preload` links
(`runtime/server/ahead.mote`), so the browser asks for them beside the page
and not after its script has run. The back end's own batteries are as they
were: inside `server/main.js`.

## Adding a namespace: a worked example

Add `slug.make(text)`: a text as part of an address (`"Red Oak Door!"` →
`"red-oak-door"`). It does not wait, and works on both sides. Three edits.
(These steps were built and run in a scratch copy while this page was
written; the namespace is an example and is not in Mote.)

**1. The runtime part.** In `runtime/shared/patterns.mote` (shared, so the
back end has it too):

```mote
// `slug.make(text)`: a text as part of an address: lower case, with a `-`
// wherever something is neither a letter nor a digit.
part SLG
  let slugGaps as slgg = new RegExp("[^a-z0-9]+", "g")
  let slugEnds as slge = new RegExp("^-|-$", "g")

  fn makeSlug(text) as SLG = text.toLowerCase().replace(slugGaps, "-").replace(slugEnds, "")
```

Check it alone: `MOTE_RUNTIME=$PWD/runtime mote runtime | grep SLG`.

**2. The type.** In `compiler/src/types.rs`, in `Checker::call`, among the
namespaces (beside `("re", "test")`):

```rust
// `slug.make(text)`: a text as part of an address.
("slug", "make") => {
    match args.first() {
        Some(a) => {
            self.fit(a, &Y::Str, "the text `slug.make` takes");
        }
        None => self.err(p, "H064", "`slug.make` takes a text", None),
    }
    Y::Str
}
("slug", _) => {
    self.err(p, "H063", &format!("slug has no `{m}`"), Some("slug has make"));
    Y::Unknown
}
```

Without this the call still compiles, as `json`, unchecked. The second arm
is what makes `slug.nope()` an error with the list of what there is.

**3. The call.** In `compiler/src/emit.rs`, in `Gen::call`, among the
namespaces (beside `if ns == "re"`):

```rust
if ns == "slug" && self.lookup(ns).is_none() {
    self.u("SLG");
    return format!("SLG({})", self.args(args));
}
```

`self.u("SLG")` is what puts the part in the page. `self.lookup(ns).is_none()`
lets a program still have a variable of its own called `slug`.

Build the compiler, then:

```mote
state title = "Red Oak Door!"
derive address = slug.make(title)          // "red-oak-door"

server fn onBack(t: string): string
  return slug.make(t)                      // the same part, in server/main.js
```

**If the call waits or can fail**, three more things:

- Its type is `Y::Fail(Box::new(…))`, so callers must settle it.
- The emitted call goes through `self.wait(…)`, which `await`s it and
  refuses it in a binding (`H082`).
- Add the namespace to the list in `find_async` (`emit.rs`), so the fns and
  actions that call it are known to wait.

**If it is a battery**, also:

- `batteries/<name>/lib.rs` (include `../rt.rs`), and its name and
  optimisation level in the list in `compiler/build.rs`;
- an `include_bytes!` constant in `build.rs`, and a row in the list in
  `finish`'s `worker` closure (`("name", "XX", NAME)`), and in the back
  end's list if it runs there;
- a driver part `XX needs WX` in `runtime/page/batteries.mote` (or
  `shared/` for both sides);
- in `Gen::call`: `self.u("XX"); self.off_used = true;
  self.batteries.insert("name");` and
  `self.wait(format!("W(\"XX\",[{op},{a}]{k})"))`;
- in `moves.rs`, `battery`, if its first argument is large data that may be
  moved.

**Then, always:**

- a unit test in `compiler/src/tests.rs` (`ok(…)` for the output, `ids(…)`
  for the refusal) and a browser test ([testing.md](testing.md#writing-a-test));
- the name in the editor grammar's namespace list
  (`tools/vscode-mote/syntaxes/mote.tmLanguage.json`);
- the docs: a section on the namespace's page, a row in the
  [map](README.md#namespaces), and a line in [card.md](card.md) if most
  programs will want it.

## Adding other things

### Adding a runtime part

Write `part NAME needs …` in the file where it belongs (or a new `.mote`
file under `runtime/page`, `shared` or `server`: every file there is read).
Give what compiled pages call an `as` name. Make the compiler ask for it
with `self.u("NAME")` wherever it emits a call to it. A part that reads
another part's names must reach it through `needs` (or `uses`), or `sys.rs`
refuses it.

What only some builds are to carry (and the rest not one byte of) is
written under `if STRICT` or `if ASK`, which are settled when a program is
built ([the dialect](../runtime/README.md#the-dialect); `sys::pick`): the
runtime's other way of writing styles under `policy=strict`, the headers a
back end then sends.

### Adding a tag, an attribute, a style, an event

`compiler/src/tables.rs` is the vocabulary: `tag`, `HTML_ATTRS`, `CSS` and
`CSS_FAMILIES`, `event`, `role`, `UNITLESS`, `habit` (what people coming
from elsewhere write, and Mote's word for it). An event that hands its
handler something also needs its payload in `types.rs` (`Checker::payload`)
and in `view.rs` (`Dyn::Event` in `Gen::el`).

### Adding a widget

A row in `tables::widget` (the tag, its runtime part, its typed
attributes), the tag in `tables::tag`, and the part in `runtime/page/`: a
fn `(element, gets, sets)` where `gets` has a getter per attribute the page
gave and `sets` a setter per attribute it can write back. See
[widgets.md](widgets.md).

### Adding a kit component

Write it in the right `kit/*.mote` file. It is ordinary Mote; it sees only
its props. A new file must be added to `KIT` in `build.rs`.
See [kit.md](kit.md#where-a-new-component-goes).

### Adding a diagnostic

`self.err(pos, "H0xx", "what is wrong", Some("what to write instead"))`.
Take the next free id in the range for its kind
([cli.md](cli.md#the-ids)); ids are stable and are never reused. Say what
is wrong in one line and give the fix as text to write.

## Conventions

- `cargo fmt` in `compiler/` (its `rustfmt.toml`) before handing work over.
- No crates: the compiler and the batteries use the standard library (or
  `core` and `alloc`) alone.
- Comments say what a thing is and why, in plain sentences; each runtime
  part and each module starts with one.
- The compiler binary is shared by everything in the repository (tests,
  docs, examples). Build it deliberately.

## In the source

| File | Lines of thought |
|---|---|
| `compiler/src/main.rs` | The command line. |
| `compiler/src/build.rs` | The whole pipeline (`compile`, `finish`), files and packages, the kit, choosing runtime parts, the back end's module. |
| `compiler/src/lex.rs`, `parse.rs`, `ast.rs` | Text to tree. |
| `compiler/src/types.rs` | The checker and the standard library's signatures. |
| `compiler/src/emit.rs` | Logic to JavaScript; atomic CSS (`Css`); workers, waiting, the back end's split. |
| `compiler/src/view.rs` | Markup to HTML and DOM code. |
| `compiler/src/tables.rs` | The vocabulary. |
| `compiler/src/model.rs` | Models: what a declaration means, rules as data, tables, `schema.lock` and what a change asks of a database ([models.md](models.md)). |
| `compiler/src/moves.rs`, `perf.rs` | Moves to workers; `--perf`. |
| `compiler/src/openapi.rs` | `api Name from "spec.json"`: an OpenAPI 3 file made into Mote source (shapes, a call fn, a fn an operation), parsed in `build.rs` `load` as though a file of it were used; `mote api expand` prints it ([services.md](services.md#a-service-with-an-openapi-file)). |
| `compiler/src/access.rs` | `mote check --access`: who may do what ([back-end.md](back-end.md#who-may-do-what)). |
| `compiler/src/agents.rs` | Pages for agents. |
| `compiler/src/assets.rs`, `icons.rs`, `pwa.rs` | Assets, icons, what makes a build installable. |
| `compiler/src/policy.rs` | How a build is delivered ([delivery.md](delivery.md)): SHA-256, `build.txt` and the build's hash, the strict policy read off the page as built, `_headers`. |
| `compiler/src/dev.rs` | `mote dev`, `mote serve`. |
| `compiler/src/sys.rs` | The runtime dialect's compiler. |
| `compiler/src/diag.rs` | Diagnostics. |
| `compiler/src/srcmap.rs` | Source maps: the marks, taken out, and the maps' JSON. |
| `compiler/src/tests.rs` | Unit tests. |
