# Custom Formats

Build an API docs integration.

To document an API format that has no integration yet, build one on `@vuesho/api-docs`, the package behind the [OpenAPI](/api-docs/openapi), [GraphQL](/api-docs/graphql) and [AsyncAPI](/api-docs/asyncapi) integrations. It loads the documents, gives their pages as a content source, renders them, and has the UI for schemas and playgrounds.

## Package Structure [#package-structure]

This page builds `acme-protobuf`, an integration for [Protocol Buffers](https://protobuf.dev) services, with a page for each RPC:

```files
acme-protobuf
├── package.json
└── src
    ├── format.ts
    ├── server.ts
    ├── page.ts
    ├── theme.ts
    ├── translations.json
    └── index.ts
```

`format.ts` reads the format. Its `loadDocument()` parses a `.proto` file with a parser like [protobufjs](https://github.com/protobufjs/protobuf.js). For a format of JSON or YAML documents, `bundle()` from `@vuesho/api-docs/json-schema/bundle` embeds the files and URLs that a document's `$ref`s name.

- `format.ts` and `server.ts` run on the server.
- `page.ts` and `theme.ts` run in the app, so they import only types from the server modules, or import them under `import.meta.env.SSR`.

## Documents and Pages [#documents-and-pages]

`createAPIDocuments()` loads the documents and lists their pages, with the functions from `format.ts`:

```ts title="src/server.ts"
import { createAPIDocuments, type DocumentInput } from "@vuesho/api-docs/server";
import {
  entriesOf,
  loadDocument,
  methodsOf,
  streamingOf,
  type PageOptions,
  type ProtoFile,
} from "./format";

export function createProtobuf(options: { input: DocumentInput<ProtoFile> }) {
  return createAPIDocuments({
    // Names the plugin and its data routes
    name: "protobuf",
    kind: "Protobuf file", // Names a document in errors
    // A list of files and URLs, named by their file names, a record by ID,
    // or a function called once with `onRead`.
    input: options.input,
    // Calls `onRead` with each local file that it reads.
    // The server's output then gets the file.
    load: (input, _id, onRead) => loadDocument(input, onRead),
    // A document's entries. A `group` is a folder, like a service.
    // A `page` holds several items, and any other type is a page for one item, like an RPC.
    entries: (id, document, options: PageOptions) => entriesOf(document, options),
    // For each entry: its page component's props, and the `meta` of its badge in the page tree
    page: (entry, { id }) => ({
      props: { document: id, methods: methodsOf(entry) },
      meta: { streaming: streamingOf(entry) },
    }),
  });
}
```

The result has `staticSource()` and `dynamicSource()`, whose options extend `SourceOptions` from `@vuesho/api-docs/server`: `baseDir` and `meta`.

## Plugin [#plugin]

`apiDocumentsPlugin()` creates the plugin, which renders the pages of the sources with the same `name`, and serves each document from a [data route](/routes#data-routes) at `/_protobuf/<id>.json`:

```ts title="src/server.ts"
import type { AppShape, Plugin } from "vuesho/config";
import { apiDocumentsPlugin } from "@vuesho/api-docs/server";
import { markdownOf, staticDataOf, type ProtobufPageProps } from "./format";
import packs from "./translations.json";

export type ProtobufPluginTypes = { bodies: { protobuf: ProtobufPageProps } };

export function protobufPlugin<C extends AppShape>(): Plugin<C, ProtobufPluginTypes> {
  return apiDocumentsPlugin({
    name: "protobuf",
    theme: "acme-protobuf/theme",
    translations: packs,
    // The data route's value
    async data(id, document) {
      return { document };
    },
    // A page's table of contents and search data
    staticData: (props, document) => staticDataOf(props, document),
    // A page's Markdown, for `llms.txt` and the `.md` routes
    text: (props, document) => markdownOf(props, document),
  });
}
```

`theme` names a module of the package, so export `./theme` in its `package.json`.

## Page Component [#page-component]

`defineDocumentPage()` from `@vuesho/api-docs` creates the page component, which reads its document from the data route. `createPageComponents()`'s `Markdown` component renders a description:

```ts tab="src/page.ts"
import { h, type PropType } from "vue";
import { defineDocumentPage } from "@vuesho/api-docs";
import { createPageComponents } from "@vuesho/api-docs/ui/components/defaults";
import type { ProtobufDocumentData, ProtobufPageProps } from "./format";

const { Markdown } = createPageComponents({});

export const ProtobufPage = defineDocumentPage<ProtobufPageProps, ProtobufDocumentData>({
  name: "protobuf",
  label: "Protobuf",
  props: {
    document: { type: String, required: true },
    methods: Array as PropType<string[]>,
  },
  setup(props, data) {
    return () =>
      (props.methods ?? []).map((id) => {
        const method = data.value.document.methods[id];
        return h("section", { id }, [
          h("h2", method?.name ?? id),
          method?.comment && h(Markdown, { md: method.comment }),
        ]);
      });
  },
});
```

```ts tab="src/theme.ts"
import type { PluginTheme } from "vuesho/client";
import type { ProtobufPluginTypes } from "./server";

export default {
  bodies: { protobuf: () => import("./page").then((mod) => mod.ProtobufPage) },
} satisfies PluginTheme<ProtobufPluginTypes>;
```

```ts tab="src/index.ts"
export { createProtobuf, protobufPlugin } from "./server";
```

A page builds on the shared UI at `@vuesho/api-docs/ui/<module>`, like `components/schema` for a schema, `components/example` for examples and code samples, and `components/playground/*` for a playground.

To load the TypeScript generator only when a page needs it, import `generateTypeScriptDefinitions()` from `@vuesho/api-docs/json-schema/typescript` with `import()`.

## Using the Integration [#using-the-integration]

A site adds the source and the plugin to its config:

```ts title="vuesho.config.ts"
import { createSite, recommendedPreset } from "vuesho/config";
import { defineDocs } from "vuesho/content";
import { createProtobuf, protobufPlugin } from "acme-protobuf";

const protobuf = createProtobuf({ input: ["proto/greeter.proto"] });

const docs = defineDocs();

export default createSite({
  docs: docs.toSource(),
  protobuf: protobuf.staticSource({ baseDir: "rpc" }),
}).plugins(recommendedPreset(), protobufPlugin());
```
