# Extend whoasks with layers

A layer is a plain object. `whoasks(...layers)` merges the layers it gets. An integration is a function that returns a layer, and the app passes its result to `whoasks()`. There is no plugin type, no hook registry, and no lifecycle.

```ts
import { whoasks, type Layer } from "whoasks";

const layer: Layer = {}; // every slot is optional
const site = whoasks(layer);
```

## The slots

| Slot      | Type                       | Answers                                                        |
| --------- | -------------------------- | -------------------------------------------------------------- |
| `forms`   | `Record<string, Form>`     | What can a request ask for                                     |
| `render`  | `Record<string, Render>`   | Who makes this form for this URL, without asking the converter |
| `ask`     | `(ask, request) => change` | Should the pick change, within what the request allowed        |
| `convert` | `Convert \| false`         | How HTML becomes Markdown                                      |
| `strict`  | `boolean`                  | Should `respond` answer 406                                    |

## How layers merge

- `forms`: a later layer replaces a form with the same name, built-in forms included.
- `render`: each form keeps its renderers in layer order. The first one that returns a body wins.
- `ask`: every hook runs, in layer order. Each sees the pick as the hooks before it left it.
- `convert` and `strict`: the last layer that sets one wins.
- `whoasks` from `"whoasks"` puts `{ convert: mdream() }` before your layers, so your `convert` replaces it. `whoasks` from `"whoasks/core"` starts with nothing.

## Add a form

```ts [yaml.ts]
import { whoasks, type Layer } from "whoasks";

export const yaml: Layer = {
  forms: { yaml: { types: ["application/yaml"], ext: ".yaml" } },
};

const site = whoasks(yaml);

export function route(request: Request): Promise<Response> {
  return site.respond(request, {
    json: { n: 1 },
    yaml: () => "n: 1\n",
  });
}
```

The key in `forms` is the form's name. `types` are the media types that name it in `Accept`. A wildcard or a URL override sends the first one.

`ext` is optional. It makes a twin URL, and without its dot it is also a `?format=` value.

On the route above, `Accept: application/yaml` and `?format=yaml` get `application/yaml`. `Accept: */*` gets JSON, the first key.

whoasks does not serialize YAML. The value you give for `yaml` is a string. A form with a renderer is also offered on pages behind `handle`, as shown in the next section.

You can also add a form for error responses:

```ts
const problem: Layer = {
  forms: { problem: { types: ["application/problem+json"] } },
};

// In a route of whoasks(problem):
return site.respond(
  request,
  { problem: body, markdown: () => `failed validate. ${body.title}` },
  { status: 422 },
);
```

The object under `problem` goes through `JSON.stringify` and is sent as `application/problem+json`.

## Render a form from your own source

A content source knows the Markdown a page was written in. A renderer returns it, so that page is not converted from HTML.

```ts [content-layer.ts]
import { whoasks, type Layer, type WhoAsks } from "whoasks";

type Find = (path: string) => Promise<{ markdown: string } | undefined>;

// A content source answers for the pages it knows. Returning nothing lets the next renderer try.
export function contentMarkdown(find: Find): Layer {
  return {
    render: {
      markdown: async ({ ask }) => (await find(ask.url.pathname))?.markdown,
    },
  };
}

export function createSite(find: Find): WhoAsks {
  return whoasks(contentMarkdown(find));
}
```

`find` stands for the source's own lookup. It is not a real ViteHub Content function. The layer lives in the content package, not in whoasks.

Pages that `find` knows answer with their source Markdown. Every other page is still converted with mdream.

A renderer runs in `handle` only, for GET and HEAD, when the request picked its form. It receives `{ request, ask, next }`:

| Field     | What it is                                                                                                                 |
| --------- | -------------------------------------------------------------------------------------------------------------------------- |
| `request` | The request as it arrived, twin URL included                                                                               |
| `ask`     | The pick. `ask.url` is the canonical URL, `ask.type` the media type to send                                                |
| `next()`  | The app's own response for `ask.url`. The app runs once however many renderers call it, and each call returns a fresh copy |

A renderer returns a string, a `Response`, or nothing. `null` and `undefined` let the next renderer try, then the converter.

A string is sent with the picked type and `Vary`. A `Response` is sent as it is, plus `Vary`, so set its `Content-Type` from `ask.type`.

A form that has a renderer is offered on every page, after `html` and in layer order.

### Use the app's response

```ts
export function contentMarkdown(find: Find): Layer {
  return {
    render: {
      markdown: async ({ ask, next }) => {
        const page = await next();
        if (!page.ok) return undefined;
        return (await find(ask.url.pathname))?.markdown;
      },
    },
  };
}
```

When the app answers 404 for the page, this renderer returns nothing, and the app's 404 page is converted and sent with its 404.

### Return a Response

```ts
const cached: Layer = {
  render: {
    markdown: async ({ ask }) => {
      const source = await find(ask.url.pathname);
      if (!source) return undefined;
      return new Response(source.markdown, {
        headers: { "content-type": `${ask.type}; charset=utf-8`, "cache-control": "max-age=300" },
      });
    },
  },
};
```

## Change the pick

A hook runs after the rules. It gets the pick and the request, and returns the part it wants to change: `form`, `type`, `vary`, or nothing.

```ts [codex.ts]
import { whoasks, type Layer } from "whoasks";

// Codex asks for Markdown with a browser-like Accept and rejects text/markdown. Send text/plain to it.
export const codexText: Layer = {
  ask(ask, request) {
    const codex = /ChatGPT-User\//.test(request.headers.get("user-agent") ?? "");
    if (codex && ask.form === "markdown") return { type: "text/plain", vary: ["User-Agent"] };
  },
};

const site = whoasks(codexText);
```

With this layer, a `ChatGPT-User` request that picks Markdown gets it as `text/plain; charset=utf-8`, with `Vary: Accept, User-Agent`. `ask.reason` becomes `layer`.

It names `User-Agent` in `vary` so a cache keeps the two answers apart. See [Codex and twin URLs](https://whoasks.loadsheet.dev/guide/negotiation#codex-and-twin-urls) for why.

| Returned     | Kept when                                                                                                                 |
| ------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `form`       | The form is offered and the request permits one of its types. After a twin or `?format=`, only the forced form is offered |
| `type`       | It is one of the form's types and the request permits it                                                                  |
| `form` alone | The type is then chosen by rule 5                                                                                         |
| `vary`       | Always. The entries are appended                                                                                          |
| Nothing      | The pick stays                                                                                                            |

A change the request did not allow is dropped, so a hook cannot send a type the client refused. With `Accept: text/html, text/markdown;q=0`, a hook that returns `{ form: "markdown" }` changes nothing.

A hook that returns the pick it already has leaves `reason` alone. A hook that returns nothing is a place to log:

```ts
const log: Layer = {
  ask(ask, request) {
    console.log(ask.reason, ask.form, new URL(request.url).pathname);
  },
};
```

## Set the converter or strict

```ts
whoasks({ convert: false }); // no HTML to Markdown
whoasks({ strict: true }); // 406 from respond
```

See [Change the converter](https://whoasks.loadsheet.dev/guide/pages#change-the-converter) and [Refuse with 406](https://whoasks.loadsheet.dev/guide/api-routes#refuse-with-406).

## Wrap handle

`handle` returns a `Response`, so a wrapper can add to it. `site.ask(request)` tells the wrapper what was picked.

```ts [alternate.ts]
import { whoasks } from "whoasks";

const site = whoasks();

// Tell people's browsers and crawlers where the Markdown twin is.
export async function withAlternate(
  request: Request,
  app: (request: Request) => Response | Promise<Response>,
): Promise<Response> {
  const response = await site.handle(request, app);
  const ask = site.ask(request);
  if (ask.form !== "html") return response;
  const path = ask.url.pathname;
  const twin = path.endsWith("/") ? `${path}index.md` : `${path}.md`;
  const copy = new Response(response.body, response);
  copy.headers.append("link", `<${twin}>; rel="alternate"; type="text/markdown"`);
  return copy;
}
```

`/docs/guide` gets `Link: </docs/guide.md>; rel="alternate"; type="text/markdown"`, and `/` gets `</index.md>`.

A request that picked Markdown gets no `Link` header.

This wrapper adds the header to every response of a request that picked HTML, images included. Check the response's `Content-Type` if you want pages only.

## Build files from twins

A generator for `llms.txt` or a full-text file walks its own list of pages and asks `handle` for each twin.

```ts [build-llms.ts]
const origin = "https://example.com";
const pages = ["/docs/guide", "/docs/api"]; // your own page list
const parts: string[] = [];
for (const path of pages) {
  const response = await site.handle(new Request(origin + path + ".md"), app);
  parts.push(await response.text());
}
const full = parts.join("\n\n");
```

`site` is your site and `app` is the function you pass to `handle` as `next`.

whoasks has no page list and writes no file. Serving the result is a normal route in your app.

## Not included

| Left out                                               | How to build it                                                                                                                       |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| Adapters for Hono, Next, SvelteKit, Astro, Node `http` | Each is `site.handle(request, next)` with that framework's request and next. [Installation](https://whoasks.loadsheet.dev/guide/installation) has Hono and Workers |
| A Nuxt module                                          | A Nitro middleware from `whoasks/h3`, plus a `render.markdown` layer from the content module                                          |
| An agent text format, a size budget                    | A `markdown` value passed to `respond`                                                                                                |
| `llms.txt`, `sitemap.md`                               | A generator, as in the section above                                                                                                  |
| A User-Agent registry                                  | A hook, as in [Change the pick](https://whoasks.loadsheet.dev/guide/layers#change-the-pick). It sets `Vary: User-Agent` itself                                                  |
| `problem+json` errors                                  | A `status` in `respond`'s `init`, or a `problem` form, as in [Add a form](https://whoasks.loadsheet.dev/guide/layers#add-a-form)                                                |
| `Link: rel="alternate"` headers                        | A wrapper, as in [Wrap handle](https://whoasks.loadsheet.dev/guide/layers#wrap-handle)                                                                                          |
| Web Bot Auth, Markdown lint, a CLI, redirects          | Not planned                                                                                                                           |

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

- [Introduction](https://whoasks.loadsheet.dev/raw/guide.md)
- [Installation](https://whoasks.loadsheet.dev/raw/guide/installation.md)
- [Pages](https://whoasks.loadsheet.dev/raw/guide/pages.md)
- [API routes](https://whoasks.loadsheet.dev/raw/guide/api-routes.md)
- [Negotiation](https://whoasks.loadsheet.dev/raw/guide/negotiation.md)
- [Layers](https://whoasks.loadsheet.dev/raw/guide/layers.md) (this page)

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.
