# @typstream/heal

> The self-healing parser that turns any prefix of streamed Typst into a source that parses, with lint fixes for Markdown habits.

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

`@typstream/heal` takes any prefix of a model's Typst output and returns a source that parses. It closes what is open
(`[b` becomes `[b]`), drops what can't be completed yet (`#let x = `), and fixes Markdown habits in text that has
settled (`## Heading` becomes `== Heading`). It is a faithful port of Typst 0.15.1's lexer and parser, checked against
Typst's own parser, with no dependencies beyond `@typstream/core`. [Healing](/docs/concepts/healing) explains the
model behind it.

## When to use it

You usually don't call it yourself. `@typstream/engine` heals every document before compiling it, and `<Typstream>` and
`mountTypstream` pass their `heal` option through to it. Use this package directly when you:

- compile streamed Typst with your own engine and need each prefix to parse;
- want the "writing a table…" status from `openFrames` without rendering anything;
- lint a finished document for Markdown habits (`@typstream/node`'s `validate` does this for you);
- write [heal handlers](#handlers) for a plugin and want to test them in isolation.

## Install

```npm
npm install @typstream/heal
```

## Example

```ts
import { createHealer, heal } from "@typstream/heal";

heal("#table(columns: 2, [a], [b").source; // "#table(columns: 2, [a], [b])"
heal("Hello *bold").source; // "Hello *bold*"
heal("$x^").source; // "$x$"
heal("#let x = ").source; // ""  (an incomplete statement is dropped, not guessed)
heal("#set text(size: 12").source; // ""  (a half-written rule is never applied)

// Streaming: re-parses only from the last checkpoint before each change.
const healer = createHealer();
for await (const chunk of stream) {
  const { source, openFrames, stableOffset } = healer.push(chunk);
  compile(source); // always parses
}
const done = healer.finish(); // the complete document: lint everything, report what's still broken
```

## How it works

1. **Normalize** the raw output: strip a ```` ```typst ```` (or ```` ```typ ````) fence around the whole document and a
   BOM, and hold back half a surrogate pair at the end.
2. **Recognize** the text with the ported lexer and parser. It records what the end of the text needs (close a
   delimiter, or cut an incomplete construct), settled syntax errors, and checkpoints to resume from after an edit.
3. **Repair the tail**: cut, then close. Every candidate is re-recognized before it is accepted. A closer that would
   merge with the last token (`\` followed by `*`) gets a separator, or the token is dropped.
4. **Lint settled text**: text before the stable offset, or everything in final mode.

Text before `stableOffset` never changes meaning as more text arrives, and the healer never rewrites it except for lint
fixes. All offsets are UTF-16 indices into the input (JS string indices).

## API

| Export | What it is |
| --- | --- |
| [`heal(input, options?)`](#heal) | One-shot healing. |
| [`createHealer(options?)`](#createhealer) | Incremental healer: `push`, `set`, `applyEdit`, `setStreamingRange`, `finish`, `result`, `reset`. |
| [`HealOptions`](#healoptions) | `final`, `dropIncompleteRules`, `lint`, `unwrapFences`, `streamingRange`, `handlers`. |
| [`HealResult`](#healresult) | `source`, `stableOffset`, `suffixOffset`, `map`, `patches`, `openFrames`, `findings`, `errors`. |
| [`blockStarts(text, checkpoints?)`](#blockstarts) | Where a text's top-level blocks start (`@beta`): the units a streaming range covers. |
| [`DEFAULT_LINT`](#lint-rules) | The lint rules and their default severities. |
| [`HealHandler`](#handlers) | Product-specific fixes: `{ name, phase, priority?, run(ctx) }`. |
| [`recognize(text, from?, options?)`](#recognize) | The recognizer on its own: requirements, errors, checkpoints. |
| [`normalize(raw, options?)`](#normalize) | The normalization step on its own. |

### heal

```ts
const heal: (input: string, opts?: HealOptions) => HealResult;
```

Heals a complete or partial Typst source in one call. It is stateless: each call recognizes the whole input. For a
stream, use [`createHealer`](#createhealer), which gives the same results while re-parsing only what changed.

```ts
import { heal } from "@typstream/heal";

const { source, openFrames } = heal("= Quiz\n#question(points: 2)[What is $1/2");
// source: "= Quiz\n#question(points: 2)[What is $1/2$]"
// openFrames: [{ frame: "math", open: 36 }, { frame: "content", open: 27 }]

// A finished document: no tail repair, and every rule lints the whole text.
const { source: fixed, findings } = heal("## Results\n**Total**: 12", { final: true });
// fixed: "== Results\n*Total*: 12"
```

### createHealer

```ts
const createHealer: (options?: HealOptions) => Healer;
```

Creates an incremental healer. It keeps the recognizer's state and, after each change, resumes at the last checkpoint
before it and stops as soon as recognition is back in step with the previous state. Results equal what
[`heal`](#heal) returns for the same input and options.

| Method | What it does |
| --- | --- |
| `push(chunk)` | Appends streamed text. |
| `set(input)` | Replaces the whole input (for example a `source` prop that grows) and diffs it against the previous one. |
| `applyEdit({ from, to, insert })` | Applies an edit to the input: editors, collaboration, AI rewrites. |
| `setStreamingRange(range)` | Marks `[from, to)` of the input as being written by a model; `null` heals the whole tail again. |
| `finish()` | The stream ended: heals the complete document (no tail repair) and lints all of it. |
| `result()` | The latest result, without changing anything. |
| `reset(input?)` | Starts over with the original options and `input` (default `""`). |
| `input` | The current input (read-only). |

Every method except `reset` returns a [`HealResult`](#healresult).

```ts
import { createHealer } from "@typstream/heal";

const healer = createHealer();
healer.push("= Quiz\n");
const r = healer.push("#question(points: 2)[What is ");
r.source; // "= Quiz\n#question(points: 2)[What is ]"
r.openFrames; // [{ frame: "content", open: 27 }]
r.stableOffset; // 7: "= Quiz\n" is settled

const done = healer.finish();
done.errors; // syntax errors healing could not fix, e.g. a delimiter the model never closed
```

**Streaming into the middle of a document.** When a model rewrites part of an existing document, mark the part with
`setStreamingRange` and write into it with `applyEdit`. Only the range is repaired, as a tail; the text before and after
it is settled, and comes out as it did, lint fixes included (`suffixOffset` is where the text after it starts in
`source`). The range moves with later edits: text inserted at its end extends it. On a finished healer, the document
heals in streaming mode again until `finish()`. Keep the range block-aligned: from a block's start
([`blockStarts`](#blockstarts)) to the end of a block's text, leaving the blank line after it outside, or the range's
last line runs into the next block while it's written.

```ts
const doc = "= Notes\n\nIntro.\n\nOld question.\n\nOutro, with m/s$^2$.";
const healer = createHealer();
healer.set(doc);
healer.finish(); // a finished document
const from = doc.indexOf("Old");
const to = from + "Old question.".length; // the block's text, not the blank line after it
healer.setStreamingRange({ from, to });
const r = healer.applyEdit({ from, to, insert: "#table(columns: 2, [a" }); // the range follows the edit
r.source; // '= Notes\n\nIntro.\n\n#table(columns: 2, [a])\n\nOutro, with m/s$""^2$.'
r.source.slice(r.suffixOffset); // the settled text after the range, with its lint fix
healer.finish(); // done: final mode again
```

### Healer

An incremental healer (createHealer): every change returns what heal gives for the new input.

| Prop                | Type                                   | Description                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `push`              | `(chunk: string) => HealResult`        | Appends streamed text.                                                                                                                                                                                                                                                                                                                                                             |
| `set`               | `(input: string) => HealResult`        | Replaces the whole input (e.g. a `source` prop that grows); diffs it against the previous one.                                                                                                                                                                                                                                                                                     |
| `applyEdit`         | `(edit: TextEdit) => HealResult`       | Applies an edit to the input (editors, collaboration, AI rewrites).                                                                                                                                                                                                                                                                                                                |
| `setStreamingRange` | `(range: Range \| null) => HealResult` | Marks `[from, to)` of the input as being written by a model (an edit streaming into the document, PLAN §5.2): only it is repaired, as a tail, and the text after it is settled. Edits move it, and text inserted at its end extends it. On a finished healer, the document is being written again: it heals in streaming mode until `finish()`. `null` heals the whole tail again. |
| `streamingRange`    | `Range \| null`                        | The range `setStreamingRange` marked, as edits since have moved it, or `null`.                                                                                                                                                                                                                                                                                                     |
| `finish`            | `() => HealResult`                     | The stream ended: heal the complete document (no tail repair).                                                                                                                                                                                                                                                                                                                     |
| `result`            | `() => HealResult`                     | The latest result.                                                                                                                                                                                                                                                                                                                                                                 |
| `reset`             | `(input?: string) => void`             | Starts over with `input` (default "") and the healer's original options (undoes `finish`, `setStreamingRange`).                                                                                                                                                                                                                                                                    |
| `input`             | `string`                               | The current raw input, before normalization: everything pushed, set or edited in so far.                                                                                                                                                                                                                                                                                           |

### HealOptions

### HealOptions

Options for heal and createHealer.

| Prop                   | Type                                                                | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ---------------------- | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `final?`               | `boolean \| undefined`                                              | The document is complete: no tail repair; lint everything.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `dropIncompleteRules?` | `boolean \| undefined`                                              | Drop a set/show/import/include rule entirely while it is incomplete (default true).                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `lint?`                | `Partial<Record<LintRuleId, boolean \| LintSeverity>> \| undefined` | Per-rule overrides of DEFAULT_LINT: a severity, or `true` for `fix` and `false` for `off`.                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `unwrapFences?`        | `"auto" \| "never" \| undefined`                                    | Strip a Markdown code fence (typst or typ) around the whole output (default "auto").                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `streamingRange?`      | `Range \| null \| undefined`                                        | Heal only text written into `[from, to)` of an existing document (AI edits): the text after it is settled, and is linted as it would be on its own. Ignored with `final`. Keep it block-aligned, the case healing is tested on: from the start of a top-level block (blockStarts) to the end of a block's text, so that the text after it starts with the blank line between blocks (or the range ends the document). Otherwise, while the range is written, its last line runs into the next block's first (a heading would turn into text). |
| `handlers?`            | `HealHandler[] \| undefined`                                        | Product-specific fixes (a plugin's `heal.handlers`): `settled` ones run with lint, `output` ones on `source`.                                                                                                                                                                                                                                                                                                                                                                                                                                 |

- `final`: use it when the document is complete. Nothing is cut or closed, every rule lints the whole text, and
  whatever is still open at the end is reported in `errors`. `Healer.finish()` sets it for you.
- `dropIncompleteRules` (default `true`): a `set`, `show`, `import` or `include` statement is dropped entirely while it
  is incomplete, so a half-written `#set text(size: 12` never restyles the whole document for one frame. With `false`
  it is closed like any other call.
- `lint`: per-rule overrides of [`DEFAULT_LINT`](#lint-rules), by rule id. `"fix"`, `"warn"` or `"off"`; `true` means
  `"fix"` and `false` means `"off"`.
- `unwrapFences` (default `"auto"`): strip a Markdown code fence (`typst` or `typ`) wrapped around the whole output.
  `"never"` leaves it.
- `streamingRange`: heal only text written into `[from, to)` of an existing document, in input offsets.
- `handlers`: [heal handlers](#handlers), run alongside the lint rules or on the healed output.

### HealResult

### HealResult

What healing returns: a source that parses, how it maps to the input, and what was fixed or is still wrong.

| Prop           | Type                                                                                           | Description                                                                                                                                                                                                                                               |
| -------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`       | `string`                                                                                       | Source to compile.                                                                                                                                                                                                                                        |
| `stableOffset` | `number`                                                                                       | Text before this source offset is settled: appending can't change how it parses.                                                                                                                                                                          |
| `suffixOffset` | `number \| null`                                                                               | With a streaming range, where the untouched text after it starts in `source`: settled too, and healed as it is on its own (lint fixes included), so it shows as it did before the range was written. `null` without a streaming range, and in final mode. |
| `map`          | `{ toSource(inputPos: number): number; toInput(sourcePos: number, assoc?: 1 \| -1): number; }` | Maps positions between the input and `source`.                                                                                                                                                                                                            |
| `patches`      | `Patch[]`                                                                                      | Changes from the normalized input to `source` (lint fixes, tail repair, output handlers).                                                                                                                                                                 |
| `openFrames`   | `OpenFrame[]`                                                                                  | Constructs still open at the end of the input, innermost first (e.g. "writing a table…").                                                                                                                                                                 |
| `findings`     | `LintFinding[]`                                                                                | Lint rules' and `settled` handlers' findings on settled text (all of it in final mode), as input offsets. `fix` findings are already applied to `source`.                                                                                                 |
| `errors`       | `SyntaxIssue[]`                                                                                | Syntax errors healing could not fix (input offsets).                                                                                                                                                                                                      |

`map` converts positions in both directions. Use `map.toInput` to carry a compile diagnostic from the healed `source`
back to the raw text the user sees (`@typstream/core`'s `mapDiagnostic` does it for a whole diagnostic):

```ts
const r = heal("Hello *bold");
r.map.toSource(6); // 6: the `*` is where it was
r.map.toInput(12); // 11: the inserted closer maps to the end of the input
```

`patches` lists every change from the normalized input to `source`, each with a machine-readable `reason`
(`"heal:close"`, `"heal:cut"`, `"lint:<rule>"`, `"handler"`).

### OpenFrame

### OpenFrame

A construct open at the end of the input that tail repair closed in `source` (none in final mode).

| Prop    | Type        | Description                                                                               |
| ------- | ----------- | ----------------------------------------------------------------------------------------- |
| `frame` | `FrameKind` | What kind of construct it is, e.g. `content` for a `[…]` block or `math` for an equation. |
| `open`  | `number`    | Input offset of the opening delimiter.                                                    |

`openFrames` lists the constructs still open at the end of the input, innermost first. Use it for status text such as
"writing a table…". `FrameKind` is one of `"content"`, `"code-block"`, `"args"`, `"params"`, `"parens"`, `"math"`,
`"math-args"`, `"math-delimited"`, `"strong"`, `"emph"`, `"string"`, `"raw"`, `"term"` and `"text-bracket"`.

### Lint rules

Lint rules fix mistakes that are permanent, not streaming artifacts: Markdown habits and stray delimiters models
produce. They only look at settled text (or the whole document in final mode) and only at markup positions, so math,
code, raw blocks and comments are left alone.

```ts
const DEFAULT_LINT: Readonly<Record<LintRuleId, LintSeverity>>;
type LintSeverity = "fix" | "warn" | "off"; // fix applies the change, warn only reports it
```

| Rule id | Default | What it does |
| --- | --- | --- |
| `markdown-heading` | `fix` | `## Heading` becomes `== Heading`. |
| `markdown-bold` | `fix` | `**bold**` becomes `*bold*` (and `__x__` becomes `_x_`). |
| `markdown-link` | `fix` | `[text](https://…)` becomes `#link("https://…")[text]` (`http` and `https` URLs). |
| `email-at` | `fix` | Escapes an `@` inside a word (`a\@b.com`), which Typst would read as a reference. |
| `bare-hash` | `fix` | Escapes a `#` followed by a space (`\#`), which starts no expression. |
| `stray-closer` | `fix` | Escapes an unmatched `]` (`\]`). |
| `unclosed-delim` | `fix` | Escapes a `*` or `_` that is never closed in its paragraph. |
| `math-lone-script` | `fix` | Gives a `^` or `_` without a base an empty one: `m/s$^2$` becomes `m/s$""^2$`. |
| `layout-profile` | `fix` | Takes `justify`, `leading` and `linebreaks` out of `par(…)` calls and `show par: set par(…)` rules, `hyphenate` and the text edges out of `show text: set text(…)`, and `breakable` out of `show table: set table.cell(…)`: they would win over the engine's layout profile. Takes a small fixed `radius` (up to 12 pt, 1em or 4 mm) out of `block`, `rect` and `box` calls that hold content and out of their set rules: a DOCX export would make a picture of a box with rounded corners, its text not editable. A ratio or a larger radius draws a shape and stays. |
| `unclosed-block-comment` | `warn` | Reports a `/*` that is never closed and hides the rest of the document. |
| `currency-dollar` | `warn` | Reports `$` signs that look like prices (`$5 and $10`), not math. As a fix it escapes both (`\$`). |

```ts
heal("It costs $5 and $10 today", { final: true, lint: { "currency-dollar": "fix" } }).source;
// "It costs \\$5 and \\$10 today"
```

Each finding is a `LintFinding`; its `changes` are applied when its severity is `fix`:

### LintFinding

A mistake a lint rule (or a `settled` heal handler) found in settled text.

| Prop       | Type              | Description                                                                                                    |
| ---------- | ----------------- | -------------------------------------------------------------------------------------------------------------- |
| `rule`     | `string`          | The lint rule's id, or the handler's `name` for a handler's edit.                                              |
| `severity` | `"fix" \| "warn"` | `fix`: its changes are applied to the healed source; `warn`: only reported. Rules set to `off` report nothing. |
| `start`    | `number`          | Start of the flagged text (UTF-16 offset; input offsets in `HealResult.findings`).                             |
| `end`      | `number`          | End of the flagged text, exclusive (same offsets as `start`).                                                  |
| `message`  | `string`          | Human-readable explanation of the problem; a handler's finding repeats its name.                               |
| `changes`  | `TextChange[]`    | Changes this finding applies when its severity is `fix`.                                                       |

### TextChange

An edit a finding applies: replace `[from, to)` with `insert`. Offsets are into the normalized text the rule
ran on, which is the input unless normalization removed something before them (a leading fence or BOM).

| Prop     | Type     | Description                                                            |
| -------- | -------- | ---------------------------------------------------------------------- |
| `from`   | `number` | Start of the replaced text (UTF-16 offset).                            |
| `to`     | `number` | End of the replaced text, exclusive; equal to `from` for an insertion. |
| `insert` | `string` | Text put in its place (empty for a deletion).                          |

### Handlers

A heal handler is a product-specific fix that runs inside the healer, for example expanding a `[[blank]]` shorthand your
prompt allows. `HealHandler` and `HealHandlerContext` are declared in `@typstream/core` and re-exported here. Plugins
carry them in their `heal.handlers` facet, which the engine passes to the healer; see
[Writing a plugin](/docs/guides/writing-a-plugin).

```ts
import { heal, type HealHandler } from "@typstream/heal";

const blanks: HealHandler = {
  name: "blank-shorthand",
  phase: "settled",
  run({ text, from, to, modeAt }) {
    const edits = [];
    for (const m of text.slice(from, to).matchAll(/\[\[blank\]\]/g)) {
      const at = from + m.index;
      if (modeAt(at) === "markup") edits.push({ from: at, to: at + m[0].length, insert: "#blank()" });
    }
    return edits;
  },
};

heal("Fill in [[blank]] here", { final: true, handlers: [blanks] }).source; // "Fill in #blank() here"
```

There are two phases:

- `settled` handlers run with the lint rules on text whose parse can no longer change: `ctx.text` is the normalized
  input and `[ctx.from, ctx.to)` is the newly settled range. Their edits must lie inside that range (others are
  ignored), and each one appears in `findings` with the handler's name as its `rule` and severity `fix`.
- `output` handlers run on the final healed source, over all of it. `modeAt` always answers `"markup"` there.

Edits are against `ctx.text` and must not overlap. Handlers run in ascending `priority` (default 100).

### HealHandler

Extension point of `@typstream/heal` (PLAN §8.1): product-specific fixes,
run alongside the built-in lint rules (`settled`, on text whose parse can no
longer change) or on the final healed source (`output`). Returned edits are
against `ctx.text`, non-overlapping, inside `[ctx.from, ctx.to)`.

| Prop        | Type                                      | Description                                                                                                                             |
| ----------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `name`      | `string`                                  | Identifies the handler. A `settled` handler's edits are reported as lint findings with this as their rule (patch reason `lint:<name>`). |
| `priority?` | `number \| undefined`                     | Lower runs first; the default is 100. The built-in lint rules run before every handler.                                                 |
| `phase`     | `"output" \| "settled"`                   | When it runs: `settled` on newly settled normalized text, like the lint rules; `output` on the whole healed source, after tail repair.  |
| `run`       | `(ctx: HealHandlerContext) => TextEdit[]` | The handler's edits to `ctx.text` (see above), or `[]` when it has none.                                                                |

### HealHandlerContext

What a HealHandler sees.

| Prop     | Type                          | Description                                                                         |
| -------- | ----------------------------- | ----------------------------------------------------------------------------------- |
| `text`   | `string`                      | Normalized text (`settled`) or healed source (`output`).                            |
| `from`   | `number`                      | Range the handler may change (`settled`: newly settled text; `output`: everything). |
| `to`     | `number`                      | End of that range (exclusive).                                                      |
| `final`  | `boolean`                     | The document is complete (no tail repair runs).                                     |
| `modeAt` | `(pos: number) => SyntaxMode` | Lexical mode at a position (`settled` only; `output` handlers get `markup`).        |

### recognize

```ts
const recognize: (text: string, from?: Checkpoint, opts?: RecognizeOptions) => Recognition;
```

Runs the recognizer on its own, without repairing anything. It tells you what the end of `text` needs, the syntax errors
before it, and the root checkpoints recognition can resume from. Pass a `Checkpoint` as `from` to resume there.

```ts
import { recognize } from "@typstream/heal";

recognize("#table(columns: 2, [a").requirements;
// [{ type: "close", text: "]", open: 19, frame: "content" },
//  { type: "close", text: ")", open: 6, frame: "args" }]
```

A `Requirement` is either `{ type: "close", text, open, frame, display? }` (append `text` to close the construct opened
at `open`) or `{ type: "cut", at, reason, soft? }` (the construct from `at` can't be completed yet).

### Recognition

What recognize records about a text: what its end needs, settled errors, and where to resume.

| Prop           | Type            | Description                                                |
| -------------- | --------------- | ---------------------------------------------------------- |
| `checkpoints`  | `Checkpoint[]`  | Root checkpoints, ascending.                               |
| `requirements` | `Requirement[]` | What the end of the text needs, innermost construct first. |
| `errors`       | `SyntaxIssue[]` | Syntax errors not at the end of the text.                  |

### RecognizeOptions

Options for recognize.

| Prop                   | Type                   | Description                                                                                        |
| ---------------------- | ---------------------- | -------------------------------------------------------------------------------------------------- |
| `dropIncompleteRules?` | `boolean \| undefined` | Turn any requirement inside a set/show/import/include statement into a cut of the whole statement. |

### Checkpoint

A root-level position where the parser can resume.

| Prop      | Type     | Description                                                                                            |
| --------- | -------- | ------------------------------------------------------------------------------------------------------ |
| `offset`  | `number` | Start of the first token on a root-level line (or of the text), in the recognized text.                |
| `nesting` | `number` | Text brackets (`[` in markup that opens no block) still open here: resuming needs them to match a `]`. |

### SyntaxIssue

A syntax error appending text can't fix: recognized text's offsets, or the input's in `HealResult.errors`.

| Prop      | Type     | Description                                  |
| --------- | -------- | -------------------------------------------- |
| `start`   | `number` | Start of the erroneous text (UTF-16 offset). |
| `end`     | `number` | End of the erroneous text, exclusive.        |
| `message` | `string` | What is wrong, e.g. `unclosed delimiter`.    |

### blockStarts

```ts
function blockStarts(text: string, checkpoints?: Checkpoint[]): number[]; // @beta
```

The offsets where the text's top-level blocks start: 0, then every line after a blank line, or with a heading, at the
top level. Block `i` runs to the start of block `i + 1`. A `#question[…]` with blank lines inside is one block, and the
items of a list separated by blank lines stay one block. It's the split the engine's source anchors and its block
isolation (Layer 4) use, and what a streaming range should cover. Pass `recognize(text).checkpoints` if you have them.

### normalize

```ts
const normalize: (raw: string, opts?: NormalizeOptions) => Normalized;
```

The first step of healing on its own: strips a code fence around the whole document and a BOM, and with
`streaming: true` holds back a trailing half surrogate pair or partial fence. `@typstream/node`'s `fixLoop` uses it to
unwrap a model's fenced reply.

```ts
import { normalize } from "@typstream/heal";

normalize("```typst\n= Hi\n```").text; // "= Hi"
```

### NormalizeOptions

Options for normalize.

| Prop            | Type                             | Description                                                                         |
| --------------- | -------------------------------- | ----------------------------------------------------------------------------------- |
| `unwrapFences?` | `"auto" \| "never" \| undefined` | Strip a Markdown code fence (typst or typ) wrapped around the whole document.       |
| `streaming?`    | `boolean \| undefined`           | The text may still grow: hold back a trailing half surrogate pair or partial fence. |

### Normalized

What normalize returns: the cleaned text and how it maps back to the raw input.

| Prop      | Type      | Description                                                                    |
| --------- | --------- | ------------------------------------------------------------------------------ |
| `text`    | `string`  | The raw input without what normalization removed: the text healing recognizes. |
| `patches` | `Patch[]` | Changes from the raw input to `text`, sorted.                                  |

## See also

- [Healing](/docs/concepts/healing): what healing guarantees, with an interactive playground.
- [Streaming](/docs/concepts/streaming): how healed prefixes flow into the engine.
- [@typstream/engine](/docs/reference/engine): the client that heals and compiles each document.
- [@typstream/core](/docs/reference/core): `TextEdit`, `Patch`, `SourceMap` and the plugin contract.
- [Writing a plugin](/docs/guides/writing-a-plugin): shipping heal handlers in a plugin.
