# AsyncAPI

Reference pages from AsyncAPI documents.

`@vuesho/asyncapi` generates reference pages for an event-driven API's operations from AsyncAPI 3 documents, with their messages, protocol bindings, code samples and a playground that connects to a channel. The [example](/api-docs/asyncapi/example/planets/subscribeToPlanetEvents) documents events on WebSocket, Kafka and MQTT.

## Setup [#setup]

### Install the Package [#install-the-package-step]

```npm
npm i @vuesho/asyncapi
```

### Add the Source and Plugin [#add-the-source-and-plugin-step]

`createAsyncAPI()` loads the documents, `staticSource()` returns their pages as a content source under `baseDir`, and `asyncapiPlugin()` renders the pages:

```ts title="vuesho.config.ts"
import { asyncapiPlugin, createAsyncAPI } from "@vuesho/asyncapi";
import { createSite, recommendedPreset } from "vuesho/config";
import { defineDocs } from "vuesho/content";

const docs = defineDocs();
// A path from the project root, or a URL.
const asyncapi = createAsyncAPI({ input: ["asyncapi.yaml"] });

export default createSite({
  docs: docs.toSource(),
  events: asyncapi.staticSource({ baseDir: "events" }), // [!code highlight]
}).plugins(recommendedPreset(), asyncapiPlugin());
```

Run `vuesho dev` and open a page under `/events`, like `/events/subscribeToPlanetEvents` for the operation `subscribeToPlanetEvents`.

### Name the Folder [#name-the-folder-step]

The pages are in an `events` folder in the sidebar. To give the folder a title, add a [meta file](/navigation#folders) to the content folder:

```json title="content/events/meta.json"
{ "title": "Event Reference" }
```

<Callout title="AsyncAPI 2 Documents">
`createAsyncAPI()` reads only AsyncAPI 3. Convert an older document with the AsyncAPI CLI:

```bash
npx @asyncapi/cli convert asyncapi-2.yaml -o asyncapi.yaml
```
</Callout>

## Pages [#pages]

Each operation has a page named after its ID. The page and its icon in the sidebar show what the reader does, the opposite of the document's `action`:

| Action in the document | What the reader does  | Icon                               |
| ---------------------- | --------------------- | ---------------------------------- |
| `send`                 | Receives the messages | <DirectionIcon action="send" />    |
| `receive`              | Sends the messages    | <DirectionIcon action="receive" /> |

The generated pages are in search and `llms.txt`, like your other pages. `groupBy` puts the pages in folders, as the tabs show for the example:

<Tabs :items='["Default","groupBy: tag","groupBy: channel"]'>
<Tab value="Default">
```files
events
├── subscribeToPlanetEvents.md
├── subscribeToUserEvents.md
├── subscribeToSystemEvents.md
└── subscribeToCelestialBodyEvents.md
```
</Tab>

<Tab value="groupBy: tag">
```files
events
├── planets
│   └── subscribeToPlanetEvents.md
├── users
│   └── subscribeToUserEvents.md
├── system
│   └── subscribeToSystemEvents.md
└── celestial-bodies
    └── subscribeToCelestialBodyEvents.md
```
</Tab>

<Tab value="groupBy: channel">
```files
events
├── planetevents
│   └── subscribeToPlanetEvents.md
├── userevents
│   └── subscribeToUserEvents.md
├── systemevents
│   └── subscribeToSystemEvents.md
└── celestialbodyevents
    └── subscribeToCelestialBodyEvents.md
```
</Tab>
</Tabs>

`per: "tag"` puts each tag's operations on one page, and `per: "file"` puts each document on one page. `groupBy` groups the pages in folders, and `meta: true` orders them:

```ts title="vuesho.config.ts"
asyncapi.staticSource({
  baseDir: "events",
  groupBy: "tag",
  // Generates the folders' meta files.
  meta: true,
});
```

A tag's folder takes its title from `x-displayName` and its description from `description`, both set on the tag in `info.tags`. Operations without a tag go in an `unknown` folder:

```yaml title="asyncapi.yaml"
info:
  tags:
    - name: lighting
      description: Operations related to streetlights.
      x-displayName: Lighting # [!code highlight]
```

## Documents [#documents]

### Multiple Documents [#multiple-documents]

A document's ID is its file name, or the last segment of its URL, without the extension. To choose the IDs, pass a record. Its values can also be document objects, or functions that return a document:

```ts title="vuesho.config.ts"
const asyncapi = createAsyncAPI({
  input: {
    streetlights: "asyncapi/streetlights.yaml",
    chat: "https://api.example.com/asyncapi.json",
  },
});
```

To put each document in a separate folder, prefix the file name with `this.id` in `name`:

```ts title="vuesho.config.ts"
asyncapi.staticSource({
  baseDir: "events",
  per: "operation",
  name(output) {
    return `${this.id}/${output.item.id}`; // [!code highlight]
  },
});
```

<Callout type="warn" title="Trusted Documents Only">
The server reads the local files and the URLs that a document references with `$ref`, so load only documents you trust.
</Callout>

### `input` as a Function [#input-as-a-function]

`input` can be a function, called once with `onRead`. Call `onRead` with each local file it reads, like a config that lists the documents, so the built server gets those files too:

```ts title="vuesho.config.ts"
import { readFileSync } from "node:fs";

const asyncapi = createAsyncAPI({
  input(onRead) {
    onRead("api-config.json");
    const config: { documents: string[] } = JSON.parse(readFileSync("api-config.json", "utf8"));
    return config.documents;
  },
});
```

### Live Updates [#live-updates]

`staticSource()` reads the documents when the site starts, so restart `vuesho dev` after you edit one.

`dynamicSource()` reads the documents on the server, renders the pages on request, and reads the documents again after `staleTime`, like any [dynamic source](/dynamic-rendering#dynamic-sources):

```ts title="vuesho.config.ts"
createSite({
  docs: docs.toSource(),
  events: asyncapi.staticSource({ baseDir: "events" }), // [!code --]
  events: asyncapi.dynamicSource({ baseDir: "events", staleTime: 60_000 }), // [!code ++]
});
```

Deploy a local document with the server, since `dynamicSource()` reads it there.

## Playground [#playground]

The playground connects from the browser to one of the operation's servers. It sends messages as text, hex or Base64, and matches the messages it receives against the documented schemas. WebSocket, with the `ws` and `wss` protocols, is built in, and another protocol needs a [transport](#custom-transports).

<Callout title="WebSockets in the Browser">
A browser can't add headers or cross-site cookies to a WebSocket, so the playground sends only credentials that go in the query. A page served over HTTPS connects only to `wss`.
</Callout>

Configure the playground with the `playground` option of [`createAsyncAPIPage()`](#customization), or turn it off with `playground: { enabled: false }`.

### Server-Sent Events [#server-sent-events]

`sseTransport` connects to an `http` or `https` server that sends Server-Sent Events, which the reader can only receive. The transport sends an API key in a header or in the query, and a bearer or basic token in `Authorization`:

```ts title="src/asyncapi-page.ts"
import { createAsyncAPIPage } from "@vuesho/asyncapi/ui";
import { sseTransport } from "@vuesho/asyncapi/playground";

export const AsyncAPIPage = createAsyncAPIPage({
  playground: { transports: { http: sseTransport, https: sseTransport } }, // [!code highlight]
});
```

### Custom Transports [#custom-transports]

A transport connects the playground to another protocol's servers, with a client that runs in the browser. This transport connects to MQTT over WebSocket with [MQTT.js](https://github.com/mqttjs/MQTT.js):

```ts title="src/mqtt-transport.ts"
import mqtt from "mqtt";
import type { PlaygroundTransport } from "@vuesho/asyncapi/playground";

export const mqttTransport: PlaygroundTransport = {
  // The security schemes that the transport sends.
  auth: (scheme) => scheme.type === "userPassword",
  connect({ url, address, auth }, events) {
    const credentials = auth[0]?.value;
    const client = mqtt.connect(`ws://${new URL(url).host}`, {
      ...(typeof credentials === "object" && credentials),
      reconnectPeriod: 0,
    });

    client.on("connect", () =>
      client.subscribe(address, (error) => (error ? events.error(error.message) : events.open())),
    );
    client.on("message", (_topic, payload) => events.message(payload.toString()));
    client.on("error", (error) => events.error(error.message));
    client.on("close", () => events.close());

    return {
      // Left out for a transport that only receives.
      send: (data) =>
        client.publish(address, typeof data === "string" ? data : (new Uint8Array(data) as Buffer)),
      close: () => client.end(),
    };
  },
};
```

```ts title="src/asyncapi-page.ts"
import { createAsyncAPIPage } from "@vuesho/asyncapi/ui";
import { mqttTransport } from "./mqtt-transport";

export const AsyncAPIPage = createAsyncAPIPage({
  playground: { transports: { mqtt: mqttTransport } }, // [!code highlight]
});
```

`connect()` receives the connection's target and `events`. Report the connection's state with `events.open()`, `events.message(data)`, `events.close()` and `events.error(message)`. The target has these fields:

### ConnectTarget

| Prop      | Type                                                                                            | Description                                                                     |
| --------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `url`     | `string`                                                                                        | The server URL with the address and query, for protocols that connect to a URL. |
| `server`  | `ServerObject`                                                                                  | The selected AsyncAPI server.                                                   |
| `address` | `string`                                                                                        | The channel address with its parameters.                                        |
| `query`   | `Record<string, unknown>`                                                                       | Query parameters from the playground form and API key credentials.              |
| `auth`    | `{ scheme: SecuritySchemeObject; value: string \| { username: string; password: string; }; }[]` | The auth input values, for the schemes that `auth` accepts.                     |

## Customization [#customization]

Create the page component with your options in `createAsyncAPIPage()`, and set it as the `asyncapi` [page body](/theme#views-and-page-bodies) in your theme:

```ts title="src/asyncapi-page.ts"
import { createAsyncAPIPage } from "@vuesho/asyncapi/ui";

export const AsyncAPIPage = createAsyncAPIPage({
  schemaUI: { showExample: true },
});
```

```ts title="src/theme.ts"
import { defineTheme } from "vuesho/theme";
import defaultTheme from "vuesho/theme/default";
import type app from "../vuesho.config";

export default defineTheme<typeof app>({
  extends: defaultTheme,
  bodies: { asyncapi: () => import("./asyncapi-page").then((mod) => mod.AsyncAPIPage) }, // [!code highlight]
});
```

To use `<AsyncAPIPage>` in Markdown with the same options, re-export it from `src/components/content/`:

```ts title="src/components/content/AsyncAPIPage.ts"
export { AsyncAPIPage as default } from "../../asyncapi-page";
```

On a site with several sources, give it `source`, the key in `createSite()` of the AsyncAPI source.

### Code Samples [#code-samples]

An operation has samples in JavaScript and Python, with a client library for its protocol:

| Protocol                              | JavaScript                | Python            |
| ------------------------------------- | ------------------------- | ----------------- |
| WebSocket (`ws`, `wss`)               | `WebSocket`               | `websockets`      |
| MQTT (`mqtt`, `mqtts`, `secure-mqtt`) | `mqtt`                    | `paho-mqtt`       |
| Kafka (`kafka`, `kafka-secure`)       | `kafkajs`                 | `confluent-kafka` |
| AMQP (`amqp`, `amqps`)                | `amqplib`                 | `pika`            |
| NATS (`nats`)                         | `@nats-io/transport-node` | `nats-py`         |

`codeUsages` changes the languages for every operation. A generator returns `""` for a protocol it doesn't support:

```ts title="src/asyncapi-page.ts"
import {
  createAsyncAPIPage,
  createCodeUsageGeneratorRegistry,
  registerDefaultCodeUsages,
} from "@vuesho/asyncapi/ui";

const codeUsages = registerDefaultCodeUsages(createCodeUsageGeneratorRegistry());
codeUsages.add("websocat", {
  label: "websocat",
  lang: "bash",
  generate: ({ protocol }, { url }) =>
    protocol === "ws" || protocol === "wss" ? `websocat "${url}"` : "",
});

export const AsyncAPIPage = createAsyncAPIPage({ codeUsages });
```

To change one operation's samples, add `x-codeSamples` to the operation in the document. A sample replaces the default one for its `lang`, and `source: false` removes it:

```yaml title="asyncapi.yaml"
operations:
  receiveLightMeasurement:
    action: receive
    x-codeSamples:
      - lang: js
        label: SDK
        source: lights.onMeasured((event) => console.log(event));
      - lang: python
        source: false
```

### Components [#components]

`components` replaces parts of the page. A layout receives the parts as named slots, so it can reorder them:

```vue title="src/OperationLayout.vue"
<script setup lang="ts">
import type { OperationLayoutProps } from "@vuesho/asyncapi/client";

defineProps<OperationLayoutProps>();
</script>

<template>
  <div class="flex flex-col gap-6">
    <slot name="header" />
    <slot name="description" />
    <slot name="connection" />
    <slot name="auth-schemes" />
    <slot name="parameters" />
    <slot name="usage" />
    <slot name="messages" />
    <slot name="reply" />
    <slot name="bindings" />
  </div>
</template>
```

```ts title="src/asyncapi-page.ts"
import { createAsyncAPIPage } from "@vuesho/asyncapi/ui";
import OperationLayout from "./OperationLayout.vue";

export const AsyncAPIPage = createAsyncAPIPage({ components: { OperationLayout } });
```

To change a part freely, copy it into `src/ui/@vuesho/asyncapi/` with [`vuesho add`](/cli#vuesho-add):

```npm
npx vuesho add operation --from @vuesho/asyncapi
```

```ts title="src/asyncapi-page.ts"
import { createAsyncAPIPage } from "@vuesho/asyncapi/ui";
import { Operation } from "./ui/@vuesho/asyncapi/operation";

export const AsyncAPIPage = createAsyncAPIPage({ components: { Operation } });
```

### Headless Usage [#headless-usage]

To build the page with a custom UI, use the headless entries:

- `@vuesho/asyncapi/client`: `createAsyncAPIRenderer()`, and composables for the document, its servers, an operation, its channel, messages and security
- `@vuesho/asyncapi/playground`: `usePlayground()`, a connection's state, its message log, and a function that sends a message

## Translations [#translations]

The generated pages are in each of your site's languages. The UI has language packs for `ja`, `zh-CN` and `zh-TW`, and [`ui.translations`](/i18n#ui-translations) replaces any of its texts:

```ts title="vuesho.config.ts"
createSite(sources, { i18n }).config({
  site: { languages: { cn: { lang: "zh-CN" } } },
  ui: { translations: { cn: { "Messages(operation page)": "消息" } } }, // [!code highlight]
});
```

## Options [#options]

### `staticSource()` and `dynamicSource()` [#staticsource-and-dynamicsource]

### AsyncAPISourceOptions

| Prop       | Type                                                                                                          | Description                                                                                                                                                                                      |
| ---------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `per?`     | `"operation" \| undefined`                                                                                    | Generates a page per operation, the default.                                                                                                                                                     |
| `groupBy?` | `"tag" \| "channel" \| "none" \| ((entry: DistributiveOmit<OperationOutput, "path">) => string) \| undefined` | Groups the pages in folders: - `tag`: `{tag}/{file}` - `channel`: `{channel key}/{file}` - `none`: `{file}` - a function that gives each entry its group name, the folder path Default: `'none'` |
| `name?`    | `NameFn<OperationOutput> \| NameFnOptions \| undefined`                                                       | Names each page's file.                                                                                                                                                                          |
| `slugify?` | `((name: string) => string) \| undefined`                                                                     | Turns names into file names. By default, it only escapes whitespace and uppercase English letters.                                                                                               |
| `baseDir?` | `string \| undefined`                                                                                         | The folder for the pages in the site's file tree, which sets their URLs.                                                                                                                         |
| `meta?`    | `boolean \| { folderStyle?: "folder" \| "separator"; } \| undefined`                                          | Generates meta files.                                                                                                                                                                            |

`per: "tag"` and `per: "file"` take the same options except `groupBy`. `per: "custom"` takes `toPages()` instead, which creates the pages.

### `createAsyncAPIPage()` [#createasyncapipage]

### CreateAsyncAPIPageOptions

| Prop                             | Type                                                                                                                        | Description                                                                                                                                                                                            |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `components?`                    | `Partial<Partial<PageComponents> & { SchemaUI: Component<SchemaUIOptions>; } & AsyncAPILayoutComponents> \| undefined`      | Replaces parts of the UI, like the ones copied with the CLI of Vuesho.                                                                                                                                 |
| `storageKeyPrefix?`              | `string \| undefined`                                                                                                       | The prefix for storage keys, which keeps the state of several AsyncAPI instances apart. Default: `` `vuesho-asyncapi-` ``                                                                              |
| `highlighter?`                   | `Highlighter \| (() => Highlighter \| PromiseLike<Highlighter>) \| undefined`                                               | The code block highlighter, or a function that loads it. Defaults to `getHighlighter()` from `vuesho/client`: the built-in highlighter with the site's code themes, loaded when a code block needs it. |
| `playground?`                    | `{ enabled?: boolean; transports?: Record<string, PlaygroundTransport>; } \| undefined`                                     | The interactive channel playground.                                                                                                                                                                    |
| `schemaUI?`                      | `{ showExample?: boolean; } \| undefined`                                                                                   | The UI that describes JSON schemas.                                                                                                                                                                    |
| `codeUsages?`                    | `CodeUsageGeneratorRegistry \| undefined`                                                                                   | The code sample generators for every operation. Defaults to JavaScript and Python.                                                                                                                     |
| `generateTypeScriptDefinitions?` | `false \| ((schema: JsonSchema, ctx: GenerateTypeScriptDefinitionsContext) => Awaitable<string \| undefined>) \| undefined` | Generates TypeScript definitions for message payloads and headers, which readers can copy. `false` turns them off.                                                                                     |

The parts that `components` replaces:

### AsyncAPIPageComponents

| Prop               | Type                                                     | Description                                                                                                                                             |
| ------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Markdown?`        | `Component<{ md: string; }> \| undefined`                | Renders Markdown text from the API specification.                                                                                                       |
| `CodeBlock?`       | `Component<CodeBlockProps> \| undefined`                 | Its slots `title`, `icon` and `actions` go in its title bar, like those of the code block of `vuesho`.                                                  |
| `Heading?`         | `Component<{ id: string; depth: number; }> \| undefined` | Its content is the default slot.                                                                                                                        |
| `SchemaUI?`        | `Component<SchemaUIOptions> \| undefined`                |                                                                                                                                                         |
| `Operation?`       | `Component<PageOperationProps> \| undefined`             | Renders one of the page's operations.                                                                                                                   |
| `Layout?`          | `Component<PageLayoutProps> \| undefined`                | Wraps the rendered operations, with `PageLayoutProps`.                                                                                                  |
| `OperationLayout?` | `Component<OperationLayoutProps> \| undefined`           | An operation's layout, with the slots `header`, `connection`, `description`, `usage`, `auth-schemes`, `parameters`, `messages`, `reply` and `bindings`. |

### `<AsyncAPIPage>` [#asyncapipage]

### AsyncAPIPageProps

| Prop               | Type                           | Description                                                                                                                                   |
| ------------------ | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `document`         | `string`                       | The ID of the document in `input`.                                                                                                            |
| `source?`          | `string \| undefined`          | The key in `createSite()` of the source whose pages have the document, which a page component in Markdown needs on a site of several sources. |
| `showTitle?`       | `boolean \| undefined`         | Renders each operation's title as a heading.                                                                                                  |
| `showDescription?` | `boolean \| undefined`         | Renders each operation's description as Markdown.                                                                                             |
| `operations?`      | `OperationItem[] \| undefined` | The document's operations to render on this page.                                                                                             |
