# Custom renderers

A renderer turns what your command collected into the text a reader gets. readerly ships one for each built-in format, and you can replace any of them when your tool already has an output other programs depend on.

## renderers or render

`createOut` takes two options for this:

- `renderers` replaces the renderer of the formats you name, such as `{ json, text }`, and keeps the built-in ones for the rest. Combined with `formats`, it adds new formats.
- `render` replaces every format with one function. It gets `ctx.profile.format` and decides for itself.

When you pass both, `render` wins. When the picked format has no renderer, `createOut` throws `No renderer for format <name>.`

```ts [check.ts]
import { createOut, type Renderer } from "readerly";

const grep: Renderer = {
  render(run) {
    if (run.failure) return { stderr: `error: ${run.failure.error.message}\n` };
    const rows = run.entries.flatMap((entry) =>
      entry.type === "diagnostic"
        ? [`${entry.diagnostic.file}: ${entry.diagnostic.severity} ${entry.diagnostic.code} ${entry.diagnostic.message}`]
        : [],
    );
    return { stdout: rows.map((row) => `${row}\n`).join("") };
  },
};

const out = createOut({ tool: "acme", command: "check", argv, formats: ["grep"], renderers: { grep } });
```

With two diagnostics, `acme check --format grep` prints:

```text
src/app.ts: error ACME001 Route handler reads process.env at module scope
vite.config.ts: warn ACME010 Alias shadows a workspace package
```

`--format grep` and `ACME_FORMAT=grep` now work, and a bad `--format` lists `grep` with the built-in four. readerly still owns the exit code, the rerun command and the reader flags.

## The Renderer interface

```ts [types.ts]
interface Chunk {
  stdout?: string;
  stderr?: string;
}

interface Renderer<Result extends object = object> {
  entry?(entry: Entry, run: RunState<Result>, ctx: RenderContext): Chunk | undefined;
  render(run: RunState<Result>, ctx: RenderContext): Chunk;
}
```

`entry` runs once per entry as you add it, for output that streams. The built-in `text` renderer uses it to print logs as they happen, and `jsonl` to print each record. Return `undefined` to print nothing yet. `render` runs when the command ends and before prompts, and returns everything else.

A renderer returns strings and never writes. readerly writes the chunk's `stdout` first, then its `stderr`. Because renderers are pure functions of their input, you can test one by calling it with a `RunState` you build by hand.

## RunState

`RunState` is what the command collected:

| Field | What it holds |
| --- | --- |
| `tool`, `command`, `version` | From `createOut`. |
| `schema` | `<tool>.<command>/v1`, unless the tool sets one. |
| `rerun` | The invocation without reader flags, shell-quoted, such as `acme check src 'my dir'`. |
| `entries` | Diagnostics, logs and next steps, in the order you added them. |
| `counts` | `{ error, warn, info }` across every diagnostic. |
| `result` | What `out.set()` merged, as `Partial<Result>`. |
| `status` | `ok`, `failed` or `action_required`. |
| `summary` | The words after the counts, from the `summary` option or `out.end()`. |
| `failure` | Set by `out.fail()` and by a bad reader flag. |
| `answer` | What `out.write()` set. |
| `part` | `whole`, `head` or `tail`. |
| `before` | The counts, status and summary the last part showed. |

## RenderContext

| Field | What it holds |
| --- | --- |
| `profile` | The reader's [`Profile`](https://readerly.loadsheet.dev/guide/api#types): format, color, budget, `full`, verbosity and the detection. |
| `style` | A `Style` function that colors text when `profile.color` is on and returns it unchanged otherwise. |
| `maxRows` | The `maxRows` option on a terminal reader with `text`. `Infinity` in CI, pipes and with `--full`. |

## Parts around prompts

A command that never prompts gets one call to `render` with `part: "whole"`. A prompt changes that, because findings have to print above the question:

1. Before the first prompt, `render` gets `part: "head"` with everything so far.
2. Before each later prompt that has something new, and at `out.end()`, it gets `part: "tail"`. `entries` holds only what came since the last part, and `counts` still covers every diagnostic. `answer` is there only when it was written since the last part.
3. `before` holds what the last part showed, so a tail can repeat the verdict only when it changed.

The built-in `text` renderer prints the verdict in the head and starts each tail section with a blank line. A renderer that writes one document, such as `json`, never sees a head, because prompts only run on `text`.

## Real tools through renderers

[`test/golden-tools.test.ts`](https://github.com/loadsheet/readerly/blob/main/test/golden-tools.test.ts) runs fleet's and glosslint's output through `createOut` and compares it byte for byte with their own tests.

fleet keeps its `--json` document and moves human lines to stderr under `--json`:

```ts [fleet.ts]
const json: Renderer = {
  entry: (entry) => (entry.type === "log" ? { stderr: `${entry.message}\n` } : undefined),
  render: (run) =>
    run.failure
      ? {
          stdout: `${JSON.stringify({ ok: false, error: run.failure.error.message }, null, 2)}\n`,
          stderr: `fleetrc: ${run.failure.error.message}\n`,
        }
      : { stdout: `${JSON.stringify(run.result, null, 2)}\n` },
};
const text: Renderer = {
  entry: (entry) => (entry.type === "log" ? { stdout: `${entry.message}\n` } : undefined),
  render: (run) => (run.failure ? { stderr: `fleetrc: ${run.failure.error.message}\n` } : {}),
};

createOut({ tool: "fleetrc", command: "list", argv, renderers: { json, text } });
```

glosslint replaces `text` with a [`tree()`](https://readerly.loadsheet.dev/guide/diagnostics#using-tree-on-its-own) per finding and its own summary line, and ends with `out.end({ status: "failed" })` because it exits 1 on warnings too. One finding and the summary line, as glosslint prints them:

```text
[GLOSSLINT_AVOID] "rack" in docs/riding.md:7:51
├▶ why: Racks are unpowered.
├▶ fix: Use "dock": "Unlock a bike at any station. Return it to a free dock when you"
├▶ term: Dock, a powered stand where one bike is locked.
╰▶ see: https://example.com/docs/docks

5 findings in 3 of 4 files.
```

The `term:` branch comes from the diagnostic's `data`, which the built-in renderers don't print.

## Answers the tool renders

Some commands answer with text, such as an explanation or a Markdown page, instead of findings. `out.write(answer)` hands it to the built-in renderers, which place it for each reader. With `out.write("ACME001 reads process.env at module scope.\nMove the read into the handler.")` and one `next`, a coding agent gets:

```text
acme explain: ok. no problems.
ACME001 reads process.env at module scope.
Move the read into the handler.
next: acme explain ACME004   (the next code)
```

`text` prints it between the verdict and the `next:` lines, separated by blank lines. In `agent`, the answer replaces the diagnostic and log rows, and under a [budget](https://readerly.loadsheet.dev/guide/budget) it is cut at line boundaries with `hidden: N lines`. `json` and `jsonl` carry it as `answer`. To render Markdown for the terminal first, see [Markdown answers](https://readerly.loadsheet.dev/integrations/markdown-answers).

Next: [API](https://readerly.loadsheet.dev/guide/api).

<!-- vitehub-docs:section-links -->
## In this section

- [Introduction](https://readerly.loadsheet.dev/raw/guide.md)
- [Installation](https://readerly.loadsheet.dev/raw/guide/installation.md)
- [Readers](https://readerly.loadsheet.dev/raw/guide/readers.md)
- [Coding agents](https://readerly.loadsheet.dev/raw/guide/agents.md)
- [Formats](https://readerly.loadsheet.dev/raw/guide/formats.md)
- [Shared flags](https://readerly.loadsheet.dev/raw/guide/flags.md)
- [Color and glyphs](https://readerly.loadsheet.dev/raw/guide/color.md)
- [Diagnostics](https://readerly.loadsheet.dev/raw/guide/diagnostics.md)
- [Budget](https://readerly.loadsheet.dev/raw/guide/budget.md)
- [Prompts and input](https://readerly.loadsheet.dev/raw/guide/prompts.md)
- [Failures and exit codes](https://readerly.loadsheet.dev/raw/guide/failures.md)
- [JSON and JSONL](https://readerly.loadsheet.dev/raw/guide/json.md)
- [Custom renderers](https://readerly.loadsheet.dev/raw/guide/renderers.md) (this page)
- [API](https://readerly.loadsheet.dev/raw/guide/api.md)

Next: [API](https://readerly.loadsheet.dev/raw/guide/api.md)

All pages: [llms.txt](https://readerly.loadsheet.dev/llms.txt)
