# API reference

```ts
import { whoasks, mdream } from "whoasks";
import { whoasks as core } from "whoasks/core";
import { middleware } from "whoasks/h3";
```

| Import         | Holds                                                                                     |
| -------------- | ----------------------------------------------------------------------------------------- |
| `whoasks`      | `whoasks` with mdream as its converter, `mdream`, and the seven types                     |
| `whoasks/core` | `whoasks` with no converter, and the seven types. It has no imports and stays under 10 kB |
| `whoasks/h3`   | `middleware`                                                                              |

## Functions

### whoasks(...layers)

```ts
function whoasks(...layers: Layer[]): WhoAsks;
```

- From `whoasks`: `{ convert: mdream() }` is the first layer. From `whoasks/core`: no converter until a layer sets one.
- Merge order: later `forms` replace earlier ones, renderers and hooks run in layer order, and the last `convert` and the last `strict` win. See [How layers merge](https://whoasks.loadsheet.dev/guide/layers#how-layers-merge).

### mdream(options?)

```ts
function mdream(options?: Partial<MdreamOptions>): Convert;
```

- Exported from `whoasks` only.
- Calls mdream's `htmlToMarkdown(html, { minimal: true, origin: url.origin, ...options })`. Your options override the two defaults. `MdreamOptions` is mdream's own type.

### middleware(site)

```ts
function middleware(site: WhoAsks): Middleware;
```

- From `whoasks/h3`. `Middleware` is h3's type. Needs h3 2.0.8 or later.
- Use: `new H3().use(middleware(site))`.

## WhoAsks

```ts
interface WhoAsks {
  readonly forms: Readonly<Record<string, Form>>;
  ask(request: Request, offers?: readonly string[]): Ask;
  respond(
    request: Request,
    renders: Record<string, unknown>,
    init?: ResponseInit,
  ): Promise<Response>;
  handle(
    request: Request,
    next: (request: Request) => Response | Promise<Response>,
  ): Promise<Response>;
}
```

### forms

The merged forms: `html`, `markdown`, `json`, plus what layers added.

### ask(request, offers?)

- Synchronous. Reads the URL and the `Accept` header, then runs the hooks.
- `offers` lists form names, default first. Without it: `html`, then each form that has a renderer, then `markdown` when a converter is set.
- Throws `whoasks: no form named "<name>"` for an offer that is not a form.
- See [Negotiation](https://whoasks.loadsheet.dev/guide/negotiation).

### respond(request, renders, init?)

- The keys of `renders` are the offers, and the first is the default.
- A value is a string, a `Response`, anything `JSON.stringify` takes, or a function returning one of those.
- With `html` and no `markdown`, and a converter set, it also offers `markdown` made from the HTML.
- With `strict`, answers 406 when nothing offered is acceptable.
- Throws `whoasks: no form named "<name>"` for a key that is not a form.
- See [API routes](https://whoasks.loadsheet.dev/guide/api-routes).

### handle(request, next)

- `next` is the app. It gets the request it should answer: the original one, or the canonical URL for a twin or `?format=`.
- Passes any method but GET and HEAD to `next` untouched.
- Never answers 406.
- See [Pages](https://whoasks.loadsheet.dev/guide/pages).

## Response headers

| Header                                       | Set by whoasks                                                                                           |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `Content-Type`                               | The picked type. `; charset=utf-8` is added to `text/*` types. Not changed on a `Response` you return    |
| `Vary`                                       | Each entry of `ask.vary`, once. Existing values are kept                                                 |
| `Content-Length`, `Content-Encoding`, `ETag` | Removed from a page that was converted                                                                   |
| Status                                       | Kept from the app's page, from `init`, or from a `Response` you return. 406 only from a strict `respond` |

## Ask

```ts
interface Ask {
  form: string;
  type: string;
  reason: "twin" | "query" | "accept" | "default" | "layer";
  acceptable: boolean;
  url: URL;
  vary: string[];
}
```

| Field        | Meaning                                                             |
| ------------ | ------------------------------------------------------------------- |
| `form`       | Name of the picked form                                             |
| `type`       | Media type to send, without parameters                              |
| `reason`     | What decided. See [Read the pick](https://whoasks.loadsheet.dev/guide/negotiation#read-the-pick) |
| `acceptable` | False when the request allowed none of the offered types            |
| `url`        | The request URL without the twin suffix and without `?format=`      |
| `vary`       | Request headers the pick depended on. Starts as `["Accept"]`        |

## Form

```ts
interface Form {
  types: readonly string[];
  ext?: string;
}
```

| Field   | Meaning                                                                                  |
| ------- | ---------------------------------------------------------------------------------------- |
| `types` | Media types that name this form in `Accept`. A wildcard or a URL override gets the first |
| `ext`   | Suffix of the twin URL, such as `.md`. Without the dot it is also a `?format=` value     |

Built-in forms:

| Form       | Media types                                      | `ext` |
| ---------- | ------------------------------------------------ | ----- |
| `html`     | `text/html`                                      | none  |
| `markdown` | `text/markdown`, `text/x-markdown`, `text/plain` | `.md` |
| `json`     | `application/json`                               | none  |

## Layer

```ts
interface Layer {
  forms?: Record<string, Form>;
  render?: Record<string, Render>;
  ask?(ask: Ask, request: Request): Partial<Pick<Ask, "form" | "type" | "vary">> | void;
  convert?: Convert | false;
  strict?: boolean;
}
```

| Field     | Meaning                                                           | Default                                             |
| --------- | ----------------------------------------------------------------- | --------------------------------------------------- |
| `forms`   | Add a form, or replace a built-in one by name                     | The three built-in forms                            |
| `render`  | Produce a form for a URL in `handle`. Keyed by form name          | None                                                |
| `ask`     | Change the pick. A change the request did not allow is dropped    | None                                                |
| `convert` | The HTML to Markdown converter, or `false` for none               | `mdream()` from `whoasks`, none from `whoasks/core` |
| `strict`  | In `respond`, answer 406 when the request allowed nothing offered | `false`                                             |

See [Layers](https://whoasks.loadsheet.dev/guide/layers).

## Render and RenderContext

```ts
type Render = (
  ctx: RenderContext,
) => string | Response | null | undefined | Promise<string | Response | null | undefined>;

interface RenderContext {
  request: Request;
  ask: Ask;
  next(): Promise<Response>;
}
```

- Returns the body for a form, or nothing to let the next renderer try.
- `next()` is the app's own response for `ask.url`. The app runs once, and each call returns a fresh copy.

## Convert

```ts
type Convert = (html: string, ctx: { request: Request; url: URL }) => string | Promise<string>;
```

- `url` is the canonical URL, `request` the request as it arrived.

## Exported types

`Ask`, `Convert`, `Form`, `Layer`, `Render`, `RenderContext` and `WhoAsks` are exported from `whoasks` and from `whoasks/core`.

<!-- vitehub-docs:section-links -->
All pages: [llms.txt](https://whoasks.loadsheet.dev/llms.txt)

Something on this page does not work as written? Tell the user, and draft an issue for them to post: [issue tracker](https://github.com/words-with-agents/whoasks/issues). Report a security vulnerability privately, never in a public issue.
