Skip to Content
Vuesho

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 documents events on WebSocket, Kafka and MQTT.

Setup

Install the Package

npm i @vuesho/asyncapi

Add the Source and Plugin

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

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" }), 
}).plugins(recommendedPreset(), asyncapiPlugin());

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

Name the Folder

The pages are in an events folder in the sidebar. To give the folder a title, add a meta file to the content folder:

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

AsyncAPI 2 Documents

createAsyncAPI() reads only AsyncAPI 3. Convert an older document with the AsyncAPI CLI:

npx @asyncapi/cli convert asyncapi-2.yaml -o asyncapi.yaml

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 documentWhat the reader doesIcon
sendReceives the messages
receiveSends the messages

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:

subscribeToPlanetEvents.md
subscribeToUserEvents.md
subscribeToSystemEvents.md
subscribeToCelestialBodyEvents.md

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:

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:

asyncapi.yaml
info:
  tags:
    - name: lighting
      description: Operations related to streetlights.
      x-displayName: Lighting 

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:

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:

vuesho.config.ts
asyncapi.staticSource({
  baseDir: "events",
  per: "operation",
  name(output) {
    return `${this.id}/${output.item.id}`; 
  },
});

Trusted Documents Only

The server reads the local files and the URLs that a document references with $ref, so load only documents you trust.

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:

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

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:

vuesho.config.ts
createSite({
  docs: docs.toSource(),
  events: asyncapi.staticSource({ baseDir: "events" }), 
  events: asyncapi.dynamicSource({ baseDir: "events", staleTime: 60_000 }), 
});

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

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.

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.

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

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:

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 } }, 
});

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:

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(),
    };
  },
};
src/asyncapi-page.ts
import { createAsyncAPIPage } from "@vuesho/asyncapi/ui";
import { mqttTransport } from "./mqtt-transport";

export const AsyncAPIPage = createAsyncAPIPage({
  playground: { transports: { mqtt: mqttTransport } }, 
});

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:

Prop

Type

Customization

Create the page component with your options in createAsyncAPIPage(), and set it as the asyncapi page body in your theme:

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

export const AsyncAPIPage = createAsyncAPIPage({
  schemaUI: { showExample: true },
});
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) }, 
});

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

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

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

ProtocolJavaScriptPython
WebSocket (ws, wss)WebSocketwebsockets
MQTT (mqtt, mqtts, secure-mqtt)mqttpaho-mqtt
Kafka (kafka, kafka-secure)kafkajsconfluent-kafka
AMQP (amqp, amqps)amqplibpika
NATS (nats)@nats-io/transport-nodenats-py

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

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:

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 replaces parts of the page. A layout receives the parts as named slots, so it can reorder them:

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>
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:

npx vuesho add operation --from @vuesho/asyncapi
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

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

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 replaces any of its texts:

vuesho.config.ts
createSite(sources, { i18n }).config({
  site: { languages: { cn: { lang: "zh-CN" } } },
  ui: { translations: { cn: { "Messages(operation page)": "消息" } } }, 
});

Options

staticSource() and dynamicSource()

Prop

Type

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

createAsyncAPIPage()

Prop

Type

The parts that components replaces:

Prop

Type

<AsyncAPIPage>

Prop

Type