# Plugin API

Write a plugin for Vuesho.

A plugin is an object with a `name` and hooks. Add it with `.plugins()` in `vuesho.config.ts`. This one adds a link to the navbar:

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

const docs = defineDocs();

export default createSite(docs.toSource()).plugins(recommendedPreset(), {
  name: "acme:blog-link",
  layoutProps({ lang }) {
    return { links: [{ text: "Blog", url: this.localizePath(lang, "/blog") }] }; // [!code highlight]
  },
});
```

Hooks run on the server and in the build, never in the browser. In most hooks, `this` is the [site context](#site-context), so write a hook that uses `this` as a method, not as an arrow function.

## Hooks [#hooks]

Every hook is optional. They run in this order:

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins({
  name: "acme:example",
  // When the site starts:
  init() {}, // Before the content loads, like to read a file that other hooks need.
  configureLoader(options) {}, // Returns options of the content loader.
  // Each time the content loads, also when a dynamic source is read again:
  transformStorage({ storage }) {}, // Adds, changes or removes content files.
  transformPageTree: {}, // Changes the nodes of the page tree, which the sidebar shows.
  // Once the content has loaded:
  configure() {}, // Like to check the content or to watch files.
  routes(fns) {}, // Creates API routes, data routes and views.
  deriveRoutes(fns, env) {}, // Creates routes from the pages of the other routes.
  // On each request to the server, before the routes and the pages:
  middleware: { handle: (request, next, env) => next() },
  // When a page renders:
  getPageBody(page) {}, // The content of a custom source's page.
  getPageToc(page) {}, // Its table of contents.
  getPageLastModified(page) {}, // When it last changed.
  getPageCreatedAt(page) {}, // When it was written.
  transformPage(data, env) {}, // Changes the page data that the browser receives.
  head(env) {}, // Tags of the page's `<head>`.
  layoutProps(env) {}, // Props of the layouts, like navbar links.
  rootProps(env) {}, // Options of the search dialog, the color mode and the image optimizer.
  // When search or an agent reads a page:
  getPageStructuredData(page) {}, // The headings and text that search indexes.
  getPageText(page) {}, // The page's text as Markdown.
  transformPageMarkdown(markdown, env) {}, // Changes `<page>.md` and `llms-full.txt`.
  // After `vuesho build` generates the public files:
  build(output) {}, // Reads the files, writes more, or fails the build.
  serverFiles: () => [], // Lists the files that the built server reads.
});
```

A plugin also has properties, which the site reads once when it starts:

```ts title="vuesho.config.ts"
import { z } from "zod";

createSite(docs.toSource()).plugins({
  name: "acme:example", // Names the plugin in errors.
  theme: "acme-example/theme", // The module of its components.
  stylesheet: "acme-example/css/example.css", // The sources of its classes, and CSS like theme variables.
  components: { Rating: "acme-example/components" }, // Components that pages use by name.
  translations: { ja: { "Rate(example)": "評価" } }, // The texts of its UI, by language.
  markdown: () => ({ markdownItPlugins: [] }), // Markdown syntax for every page.
  pageData: ["readingTime"], // Page data fields that its Markdown rules set.
  frontmatter: { status: z.enum(["beta", "deprecated"]) }, // Frontmatter fields that it reads.
  nitro: { traceDeps: ["sharp"] }, // Options of the Nitro server.
  vitePlugins: () => [], // Vite plugins for the site's modules.
});
```

These pages cover the hooks in depth:

<Cards>
<Card title="Routes" href="/routes">
API routes, data routes, views and middleware.
</Card>

<Card title="Content Hooks" href="/content-hooks">
The pages of a custom source, page data, frontmatter fields and the page tree.
</Card>

<Card title="Markdown Extensions" href="/markdown-extensions">
Markdown syntax, with markdown-it rules and Vue components.
</Card>
</Cards>

## Plugin UI [#plugin-ui]

A plugin's components go in its theme module. The module puts components in the [slots](/theme#slots) of the layouts, and names the components that render the plugin's views and bodies. Adding the plugin to a site also loads its theme module.

### Theme Module [#theme-module]

This plugin puts two buttons under each page, which post to the plugin's API route:

```ts tab="index.ts"
import type { AppShape, Plugin } from "vuesho/config";

export function feedbackPlugin<C extends AppShape>(): Plugin<
  C,
  { translations: "Good(feedback)" | "Bad(feedback)" }
> {
  return {
    name: "acme:feedback",
    theme: "acme-feedback/theme", // [!code highlight]
    translations: { ja: { "Good(feedback)": "良い", "Bad(feedback)": "悪い" } },
    routes({ createApi }) {
      createApi({
        path: "/api/feedback",
        POST: async (request) => Response.json({ received: await request.json() }),
      });
    },
  };
}
```

```ts tab="theme.ts"
import { defineAsyncComponent } from "vue";
import type { PluginTheme } from "vuesho/client";

export default {
  slots: { "page-bottom": defineAsyncComponent(() => import("./Feedback.vue")) }, // [!code highlight]
} satisfies PluginTheme;
```

```vue tab="Feedback.vue"
<script setup lang="ts">
import { addBasePath, usePage } from "vuesho/client";
import { useTranslations } from "vuesho/ui/translate";

const page = usePage();
const t = useTranslations({ note: "feedback" });

function send(opinion: "good" | "bad") {
  void fetch(addBasePath("/api/feedback"), {
    method: "POST",
    body: JSON.stringify({ url: page.value.url, opinion }),
  });
}
</script>

<template>
  <div>
    <button type="button" @click="send('good')">{{ t("Good") }}</button>
    <button type="button" @click="send('bad')">{{ t("Bad") }}</button>
  </div>
</template>
```

`theme` is a package export, like `acme-feedback/theme`, or a path from the project root, like `/src/feedback/theme.ts`. The site's own theme overrides the plugin's, as [Theme Inheritance](/theme#theme-inheritance) describes.

A text's key is its English text with a note in parentheses, like `Good(feedback)`, and the site's [`ui.translations`](/i18n#ui-translations) override the plugin's texts.

To replace the whole UI of a plugin, a site gives it another `theme`:

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  feedbackPlugin(), // [!code --]
  { ...feedbackPlugin(), theme: "/src/feedback-theme.ts" }, // [!code ++]
);
```

A plugin that `.plugins()` receives as a function, like `sanityPlugin()`, needs a wrapper:

```ts title="vuesho.config.ts"
(site) => ({ ...sanityPlugin()(site), theme: "/src/sanity-theme.ts" }),
```

### Styles [#styles]

The site's [Tailwind CSS](/styling#tailwind-css) compiles the classes of a plugin's components, so a package ships no CSS for them. Tailwind CSS reads the files of the site, so a plugin in the site's project needs no setup.

A published package names the files with its classes in its `stylesheet`, with `@source` and a path relative to the stylesheet. Vuesho compiles the stylesheet with the site's, so it can add CSS too, like a theme variable that the classes use:

```css tab="css/feedback.css"
@source "../dist";

@theme {
  --color-feedback-positive: hsl(150, 60%, 40%); /* text-feedback-positive */
}
```

```ts tab="index.ts"
export function feedbackPlugin<C extends AppShape>(): Plugin<C> {
  return {
    name: "acme:feedback",
    theme: "acme-feedback/theme",
    stylesheet: "acme-feedback/css/feedback.css", // [!code ++]
  };
}
```

### UI Components [#ui-components]

A component can use the [UI components](/theme#ui-components) of `vuesho/ui/*`, the primitives of [Reka UI](https://reka-ui.com) and `cn()`. A package lists `reka-ui` and `cn` as dependencies, at ranges that include the versions `vuesho` depends on:

```ts
import { Callout } from "vuesho/ui/components/callout";
import { CollapsibleContent, CollapsibleRoot } from "reka-ui";
import { cn } from "cn";
```

## Build Output [#build-output]

The `build` hook runs once `vuesho build` has generated the public files, and never in `vuesho dev`. This plugin builds a [Pagefind](https://pagefind.app) index from the generated pages:

```ts title="pagefind-plugin.ts"
import * as pagefind from "pagefind";
import type { Plugin } from "vuesho/config";

export const pagefindPlugin: Plugin = {
  name: "acme:pagefind",
  async build({ files, emitFile }) {
    const { index } = await pagefind.createIndex();
    for (const file of files) {
      if (!file.file.endsWith(".html")) continue;
      await index!.addHTMLFile({ url: this.addBasePath(file.path), content: await file.text() });
    }
    for (const { path, content } of (await index!.getFiles()).files) {
      await emitFile(`pagefind/${path}`, content); // [!code highlight]
    }
    await pagefind.close();
  },
};
```

### BuildOutput

| Prop        | Type                                                                                        | Description                                                                                             |
| ----------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `emitFile`  | `(path: string, content: string \| Uint8Array) => Promise<void>`                            | Writes a file to the output. It fails at a path the output already serves or the route rules exclude.   |
| `files`     | `readonly BuildFile[]`                                                                      | Every file in the output, including those that earlier `build` hooks emitted.                           |
| `links`     | `readonly { href: string; fromPathname: string; }[]`                                        | The `href` of each `<a>` and `<area>` in the generated pages, with its page's path.                     |
| `negotiate` | `(file: BuildFile, alternate: BuildFile, when: { header: string; value: string; }) => void` | Serves `alternate` instead of `file` to a request whose `header` matches `value`, a regular expression. |

### BuildFile

| Prop    | Type                        | Description                                           |
| ------- | --------------------------- | ----------------------------------------------------- |
| `path`  | `string`                    | The URL without the base path, like `/docs/intro`.    |
| `file`  | `string`                    | The file in the output, like `docs/intro/index.html`. |
| `text`  | `() => Promise<string>`     | Reads the file as UTF-8 text.                         |
| `bytes` | `() => Promise<Uint8Array>` | Reads the file's raw bytes.                           |

### Content Negotiation [#content-negotiation]

A file of the output skips middleware. `negotiate()` serves another file of the output when a request header matches a regular expression, like a page's [Markdown version](/ai#content-negotiation):

```ts title="json-feed-plugin.ts"
import type { Plugin } from "vuesho/config";

export const jsonFeedPlugin: Plugin = {
  name: "acme:json-feed",
  build({ files, negotiate }) {
    const rss = files.find((file) => file.path === "/rss.xml");
    const json = files.find((file) => file.path === "/feed.json");
    if (rss && json) {
      negotiate(rss, json, { header: "Accept", value: ".*application/feed\\+json.*" }); // [!code highlight]
    }
  },
};
```

The regular expression matches the whole value of the header. A static host without header rules, like GitHub Pages, always serves the first file. To test the negotiation, build with the default preset, run `vuesho preview`, and request the file:

```bash
curl -i -H "Accept: application/feed+json" http://localhost:3000/rss.xml
```

### Failing a Build [#failing-a-build]

An error thrown in `build` fails `vuesho build`, like the [link validation](/markdown#link-validation) of the recommended preset on a dead link. Throw `VueshoError` for a mistake the site can fix:

```ts title="page-size-plugin.ts"
import { VueshoError, type Plugin } from "vuesho/config";

export const pageSizePlugin: Plugin = {
  name: "acme:page-size",
  async build({ files }) {
    for (const file of files) {
      if (!file.file.endsWith(".html")) continue;
      const size = (await file.bytes()).length;
      if (size > 200_000) throw new VueshoError(`${file.path} has ${size} bytes of HTML`); // [!code highlight]
    }
  },
};
```

When the mistake is in a source file, pass its location, and the message names it:

```ts
new VueshoError("No title.", { file: "content/a.md", line: 1 }); // [Vuesho] content/a.md:1: No title.
```

## Server and Vite Options [#server-and-vite-options]

### Server Files [#server-files]

A plugin reads a project file with `node:fs`, by its path from the project root. `serverFiles` lists the files that a built server reads, and the build copies them into the server's output:

```ts title="releases-plugin.ts"
import { readFileSync } from "node:fs";
import type { AppShape, Plugin } from "vuesho/config";

export function releasesPlugin<C extends AppShape>(file = "releases.json"): Plugin<C> {
  const releases: { version: string }[] = JSON.parse(readFileSync(file, "utf8"));
  return {
    name: "acme:releases",
    serverFiles: () => [file], // [!code highlight]
    routes({ createApi }) {
      createApi({ path: "/api/latest", GET: () => Response.json(releases[0]) });
    },
  };
}
```

The build calls `serverFiles` after it generates the pages, so a plugin can list the files it read for them. A site lists the files that its own code reads the same way, in a plugin of its config. An edge runtime, like Cloudflare Pages or Netlify Edge, gets none of the files, so bundle the data there with [`import.meta.glob()`](https://vite.dev/guide/features#glob-import).

### Nitro Options [#nitro-options]

`nitro` sets [Nitro options](https://nitro.build/config) of the built server: `routeRules`, `traceDeps`, and the options of the `vercel` and `netlify` presets. `traceDeps` lists the native packages that the server needs, and a `*` at the end of a name copies all files of the package:

```ts title="pdf-plugin.ts"
import type { AppShape, Plugin } from "vuesho/config";

export function pdfPlugin<C extends AppShape>(): Plugin<C> {
  return {
    name: "acme:pdf",
    nitro: { traceDeps: ["@napi-rs/canvas*"] }, // [!code highlight]
  };
}
```

Write the paths of a redirect without the base path, which the site adds. The route rules of `vite.config.ts` override a plugin's:

```ts title="moves-plugin.ts"
import type { Plugin } from "vuesho/config";

export const movesPlugin: Plugin = {
  name: "acme:moves",
  nitro: { routeRules: { "/old-guide": { redirect: { to: "/guide", status: 308 } } } },
};
```

### Vite Plugins [#vite-plugins]

`vitePlugins` returns Vite plugins for the site's modules, like a transform. Import them inside the hook, so a site without your plugin doesn't load them:

```ts title="acme-plugin.ts"
import type { Plugin } from "vuesho/config";

export const acmePlugin: Plugin = {
  name: "acme:define",
  async vitePlugins() {
    const { defineTransform } = await import("./transform");
    return defineTransform();
  },
};
```

These Vite plugins run in each environment of Vite, so they can use hooks like `transform` and `hotUpdate`, but not `config` or `configResolved`.

## Site Context [#site-context]

`this` in a hook is the site context. The config's `head` and `ui.layoutProps` functions have it as `this` too.

### Content [#content]

The pages of your [content sources](/content-sources), and the results of the content hooks:

### ContextContent

| Prop                    | Type                                                                                                                                                                         | Description                                                                                                                                                                                                                 |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getPages`              | `(lang?: string \| undefined) => Page<string \| undefined, SourcePageData>[]`                                                                                                | The content pages, in every language or in one, as the content was when the request started.                                                                                                                                |
| `getPage`               | `(path: string, options?: { props?: Record<string, unknown>; }) => (Page<string \| undefined, SourcePageData> & { readonly props?: Record<string, unknown>; }) \| undefined` | A content page by its URL without the base path, with `props` for its content and outputs.                                                                                                                                  |
| `getLoader`             | `() => LoaderOutput<{ page: Page<string \| undefined, SourcePageData>; meta: Meta<string \| undefined, MetaData>; i18n: I18nConfig<string> \| undefined; }>`                 | The Fumadocs content loader, whose pages are those of `getPages()`.                                                                                                                                                         |
| `getSources`            | `() => ReadonlyMap<string \| undefined, Source<SourceConfig>>`                                                                                                               | The content sources by key, each the object that `createSite()` was given, so a plugin finds the sources of its kind by their own fields, also a source without a page. A site of one source has it at the key `undefined`. |
| `getPageTree`           | `(lang?: string \| undefined) => PageTree.Root`                                                                                                                              | A language's page tree, which is a new object only when the content changed. Default: `the default language`                                                                                                                |
| `getPageBody`           | `(page: Page<string \| undefined, SourcePageData>) => Promise<PageBody<any> \| undefined>`                                                                                   | The result of the latest plugin whose `getPageBody` gives one, like each `getPage*` content hook below.                                                                                                                     |
| `getPageToc`            | `(page: Page<string \| undefined, SourcePageData>) => Promise<TOCEntry[] \| undefined>`                                                                                      | A content page's table of contents.                                                                                                                                                                                         |
| `getPageText`           | `(page: Page<string \| undefined, SourcePageData>) => Promise<string \| undefined>`                                                                                          | A content page's Markdown.                                                                                                                                                                                                  |
| `getPageStructuredData` | `(page: Page<string \| undefined, SourcePageData>) => Promise<StructuredData \| undefined>`                                                                                  | A content page's search data: its headings and the text under them.                                                                                                                                                         |
| `getPageLastModified`   | `(page: Page<string \| undefined, SourcePageData>) => Promise<Date \| undefined>`                                                                                            | When a content page last changed.                                                                                                                                                                                           |
| `getPageCreatedAt`      | `(page: Page<string \| undefined, SourcePageData>) => Promise<Date \| undefined>`                                                                                            | When a content page was written.                                                                                                                                                                                            |
| `getPageFile`           | `(page: Page<string \| undefined, SourcePageData>) => Promise<string \| undefined>`                                                                                          | A content page's source file, relative to the project root.                                                                                                                                                                 |
| `getPageData`           | `{ (page: Page<string \| undefined, SourcePageData>): Promise<PageData>; (route: PageRoute<AppShape>, path: string): Promise<PageData>; }`                                   | The page data the browser receives for a page, after the `transformPage` hooks.                                                                                                                                             |
| `validateFrontmatter`   | `<Output extends object>(schema: StandardSchemaV1<unknown, Output>, frontmatter: Record<string, unknown>) => Promise<Output & Record<string, unknown>>`                      | A page's data from its frontmatter: the output of `schema`, with the plugins' frontmatter fields.                                                                                                                           |

### Rendering on Request [#rendering-on-request]

The render modes, and the [dynamic sources](/dynamic-rendering#dynamic-sources) that the server reads again while the site runs:

### ContextDynamic

| Prop               | Type                                                                               | Description                                                                          |
| ------------------ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `getPageRender`    | `(path: string) => RenderMode \| undefined`                                        | How the page at a path renders, or none when the path has no page.                   |
| `getContentRender` | `(source?: string \| readonly (string \| undefined)[] \| undefined) => RenderMode` | How a route renders when it reads the content of every source, or of the given ones. |
| `getCacheControl`  | `(page: Page<string \| undefined, SourcePageData>) => string \| undefined`         | The `Cache-Control` for a response rendered on request from a page.                  |
| `revalidateLoader` | `(source?: string \| undefined) => Promise<void>`                                  | Reads the dynamic sources again now, in this server instance.                        |
| `invalidateLoader` | `(source?: string \| undefined) => void`                                           | Marks the dynamic sources stale, so the next request reads them again.               |

A plugin that watches files passes `this.signal`, which aborts when the site restarts, like after an edit of the config:

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

createSite({ docs: docs.toSource(), notes }).plugins({
  name: "acme:notes",
  configure() {
    // Reads the `notes` source again when a file in its folder changes.
    watch("notes", { recursive: true, signal: this.signal }, () => this.invalidateLoader("notes"));
  },
});
```

### Routes and Pages [#routes-and-pages]

Pages of every kind, by URL. For a page rendered on request, the `request` argument holds its cookies and headers:

### ContextRoutes

| Prop              | Type                                                                           | Description                                                                                                 |
| ----------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| `getPageRoutes`   | `() => readonly PageRoute<AppShape>[]`                                         | The custom pages, views and not found pages, one route per language. Throws in `routes`.                    |
| `getContent`      | `(path: string, request?: Request) => Promise<PageContent \| undefined>`       | What the browser receives for a URL, or none for a 404.                                                     |
| `getPageEnv`      | `(path: string, request?: Request) => Promise<HeadEnv<AppShape> \| undefined>` | The page at a URL as hooks receive it, its content page or its route with its page data, or none for a 404. |
| `getPageMarkdown` | `(path: string, request?: Request) => Promise<string \| undefined>`            | The page at a URL as Markdown: its title, its description, then its text.                                   |

### Languages [#languages]

The languages of an [i18n](/i18n) site, with the paths and texts of each:

### ContextLanguages

| Prop                | Type                                                                                                                                                                     | Description                                                                                                                                                                       |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `i18n?`             | `I18nConfig<string> \| undefined`                                                                                                                                        | The `i18n` option of `createSite()`, when the site sets it.                                                                                                                       |
| `languages`         | `readonly string[]`                                                                                                                                                      | The site's languages, or the one from `site.lang` without `i18n`.                                                                                                                 |
| `defaultLanguage`   | `string`                                                                                                                                                                 | The language of a path without one.                                                                                                                                               |
| `getLanguage`       | `(path: string) => string`                                                                                                                                               | The language of a site path.                                                                                                                                                      |
| `localizePath`      | `(lang: string, path: string) => string`                                                                                                                                 | A path in a language, with its prefix unless `hideLocale` hides it.                                                                                                               |
| `getHomeUrl`        | `(lang: string) => string`                                                                                                                                               | A language's home: its root when a page is there, or else the first page in its page tree.                                                                                        |
| `getPageAlternates` | `{ (page: Page<string \| undefined, SourcePageData>): { lang: string; url: string; }[]; (route: PageRoute<AppShape>, path: string): { lang: string; url: string; }[]; }` | The page in every language it has a file in, itself included, or none without a translation. For a route, it's the route's page at `path`, with the translations the route lists. |
| `getFallbackOrigin` | `(page: Page<string \| undefined, SourcePageData>) => Page<string \| undefined, SourcePageData> \| undefined`                                                            | The fallback language's page that a page without its own file shows.                                                                                                              |
| `translations`      | `Readonly<Record<string, Readonly<Record<string, string>>>>`                                                                                                             | Each language's texts, by key.                                                                                                                                                    |

### URLs [#urls]

`addBasePath()` and `absoluteUrl()` apply the site's [base path](/deploying#base-path), `hideLocale` and `trailingSlash`:

```ts
// A site at https://acme.dev with the base path "/docs/":
this.addBasePath("/guide"); // "/docs/guide"
this.absoluteUrl("/guide"); // "https://acme.dev/docs/guide"
```

### ContextUrls

| Prop          | Type                                    | Description                                                                                  |
| ------------- | --------------------------------------- | -------------------------------------------------------------------------------------------- |
| `base`        | `string`                                | The base path, with a trailing slash.                                                        |
| `addBasePath` | `(path: string) => string`              | Adds the base path to a site path and encodes it, like `addBasePath()` from `vuesho/client`. |
| `absoluteUrl` | `(path: string) => string`              | A path's full URL from `site.baseUrl`, or else the path with the base path.                  |
| `getFileUrl`  | `(file: string) => string \| undefined` | A file's URL on the `site.git` host, with `file` from the project root.                      |

### Theme and Site [#theme-and-site]

### ContextSite

| Prop             | Type                                                                                          | Description                                                                                                                                                                     |
| ---------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getLayoutProps` | `(env: LangEnv<AppShape>) => Promise<LayoutProps>`                                            | The props every layout shares in a language.                                                                                                                                    |
| `getRootProps`   | `(env: LangEnv<AppShape>) => Promise<RootProps & { colorMode: Required<ColorModeOptions>; }>` | The root component's props in a language, with `ui.colorMode` over the plugins' color mode.                                                                                     |
| `getBodyHtml`    | `(body: { type: string; props: object; }) => Promise<string>`                                 | Renders the component that the theme's `bodies` names `type` alone to HTML, with `props` as JSON.                                                                               |
| `site`           | `SiteConfig<string>`                                                                          | The `site` option of `.config()`. `getSite()` gives it for a language.                                                                                                          |
| `getSite`        | `(lang: string) => SiteOfLanguage & { label: string; }`                                       | The site in a language, with what `site.languages` sets for it.                                                                                                                 |
| `markdown?`      | `MarkdownOptions \| undefined`                                                                | The config's `markdown`, which the server compiles Markdown with.                                                                                                               |
| `nitroPreset?`   | `string \| undefined`                                                                         | The Nitro preset the site runs with, like `vercel`.                                                                                                                             |
| `signal`         | `AbortSignal`                                                                                 | Aborted when another start of the site replaces this one, like after an edit of the config in development, when the dev server stops, and when a build has generated its files. |

### Caching [#caching]

`createCache()` keeps the values that a plugin computes from the content. Key them on `this.getLoader()`, which is a new object only when the content changes:

```ts title="glossary-plugin.ts"
import { createCache, type AppShape, type Context, type Plugin } from "vuesho/config";

export function glossaryPlugin<C extends AppShape>(): Plugin<C> {
  const glossaries = createCache<Promise<string[]>>();
  const glossaryOf = (ctx: Context<C>, lang?: C["lang"]) =>
    glossaries([ctx.getLoader(), lang], async () =>
      ctx.getPages(lang).flatMap((page) => page.data.title ?? []),
    );

  return {
    name: "acme:glossary",
    routes({ createApi }) {
      createApi({ path: "/api/glossary", GET: async () => Response.json(await glossaryOf(this)) });
    },
  };
}
```

With `persistIn`, the cache keeps its values in a folder instead of in memory, so the next build reuses them. Its keys and values are JSON:

```ts
const highlighted = createCache<string>({ persistIn: "node_modules/.vuesho/acme" });
const html = highlighted([code, lang], () => highlight(code, lang));
```

### Outside Hooks [#outside-hooks]

A helper function that hooks call takes the context as a `Context<C>` argument:

```ts title="src/blog-link.ts"
import type { AppShape, Context } from "vuesho/config";

export function blogLink<C extends AppShape>(ctx: Context<C>, lang: C["lang"]) {
  return { text: "Blog", url: ctx.localizePath(lang, "/blog") };
}
```

Server code outside a hook, like the loader of a [custom page](/custom-pages#reading-content), reads the context with `getSiteContext()`. Type it with a type import of your config, which `vuesho.config.ts` itself can't import, since the import would be circular:

```ts title="src/server/pages.ts"
import { getSiteContext } from "vuesho/config";
import type app from "../../vuesho.config";

export function pageUrls(): string[] {
  return getSiteContext<typeof app>()
    .getPages()
    .map((page) => page.url);
}
```

`getSiteContext()` works on the server once the site has started, so call it in a handler or a loader, not at the top of a module. A script reads it with [`vuesho run`](/cli#running-a-script).

## Plugin Order [#plugin-order]

The built-in plugins run first, then the site's plugins in their order in `.plugins()`. When two plugins set the same value, like a field of the page data, the later plugin's value wins, and the site's own options win over every plugin. Hooks that change a value, like `transformPage` and `transformPageTree`, run in order, each on the result of the one before.

## Publishing [#publishing]

A plugin for other sites is a function that returns `Plugin<C>`, where `C` is inferred from the site that adds it:

```ts title="status-plugin.ts"
import type { AppShape, Plugin } from "vuesho/config";

interface StatusOptions<C extends AppShape> {
  path?: string;
  /** The pages it counts. */
  filter?: (page: C["page"]) => boolean;
}

export function statusPlugin<C extends AppShape>(
  // `NoInfer` keeps `C` from being inferred from the options.
  options: StatusOptions<NoInfer<C>> = {},
): Plugin<C> {
  const { path = "/api/status.json", filter = () => true } = options;
  return {
    name: "acme:status",
    routes({ createApi }) {
      createApi({
        path,
        // Generated at build time, unless a content source renders on request.
        render: this.getContentRender(),
        GET: () => Response.json({ pages: this.getPages().filter(filter).length }),
      });
    },
  };
}
```

To type an option that receives any page, whether a content page, a custom page or a view, use `PageEnv<C>` from `vuesho/config`. The names of the built-in plugins start with `core:`, so give yours another prefix, like `acme:`.

### Plugin Types [#plugin-types]

The second type argument of `Plugin<C, T>` declares what the plugin adds to a site, like the texts of the [feedback plugin](#theme-module), so the site's theme and config get their types:

### PluginTypes

| Prop            | Type                  | Description                                           |
| --------------- | --------------------- | ----------------------------------------------------- |
| `views?`        | `object \| undefined` | The props for each view, by type.                     |
| `bodies?`       | `object \| undefined` | The props for each body, by type.                     |
| `translations?` | `string \| undefined` | The keys of the plugin's texts.                       |
| `frontmatter?`  | `object \| undefined` | The frontmatter fields the plugin reads.              |
| `pageData?`     | `object \| undefined` | The fields its `transformPage` adds to the page data. |

### Packages [#packages]

A package exports its plugin, its theme module and its CSS, and lists `vuesho` as a peer dependency:

```json title="package.json"
{
  "name": "acme-feedback",
  "type": "module",
  "exports": {
    ".": "./index.ts",
    "./theme": "./theme.ts",
    "./css/*": "./css/*"
  },
  "peerDependencies": {
    "vuesho": "*"
  }
}
```

Vuesho compiles any dependency that has `vuesho` as a peer, so a package can ship `.ts` and `.vue` files.

<Callout title="Props Typed in Another File">
Vue's compiler needs TypeScript to read a `defineProps()` type imported from another file, which a site may not have. Compile those components with [tsdown and `unplugin-vue`](https://tsdown.dev/recipes/vue-support), with `vuesho` and `virtual:vuesho/*` external.
</Callout>

### Testing [#testing]

`createFetchHandler()` from `vuesho/server` serves a site without Vite, so a [Vitest](https://vitest.dev) test can request its API routes, data routes and middleware:

```ts title="status-plugin.test.ts"
import { createSite } from "vuesho/config";
import { createFetchHandler } from "vuesho/server";
import { expect, test } from "vitest";
import { statusPlugin } from "./status-plugin";

test("returns the page count", async () => {
  // `defineDocs()` needs Vite, so the test site has a source of its own.
  const site = createSite({
    files: [
      { type: "page", path: "index.md", data: { title: "Home" } },
      { type: "page", path: "guide.md", data: { title: "Guide" } },
    ],
  }).plugins(statusPlugin());
  const fetch = createFetchHandler({ site }); // [!code highlight]

  const response = await fetch(new Request("http://localhost/api/status.json"));
  expect(await response.json()).toEqual({ pages: 2 });
});
```

Give Vitest a config of its own, so it doesn't load `vuesho()` from `vite.config.ts`:

```ts title="vitest.config.ts"
import { defineConfig } from "vitest/config";

export default defineConfig({});
```

### HandlerOptions

| Prop           | Type                                                           | Description                                                                                     |
| -------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `site`         | `Site<AppShape, PluginTypes>`                                  | The site, as `createSite()` returns it.                                                         |
| `render?`      | `((env: PageRenderEnv) => Promise<RenderOutput>) \| undefined` | Renders the app at a URL to HTML. Default: `an empty body, for a test of routes and middleware` |
| `nitroPreset?` | `string \| undefined`                                          | The Nitro preset the site runs with, like `vercel`.                                             |

To test the rendered HTML and the app, run `vuesho build` on a fixture site.
