Skip to Content
Vuesho

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:

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

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

Hooks

Every hook is optional. They run in this order:

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:

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:

Plugin UI

A plugin's components go in its theme module. The module puts components in the 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

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

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", 
    translations: { ja: { "Good(feedback)": "良い", "Bad(feedback)": "悪い" } },
    routes({ createApi }) {
      createApi({
        path: "/api/feedback",
        POST: async (request) => Response.json({ received: await request.json() }),
      });
    },
  };
}

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 describes.

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

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

vuesho.config.ts
createSite(docs.toSource()).plugins(
  feedbackPlugin(), 
  { ...feedbackPlugin(), theme: "/src/feedback-theme.ts" }, 
);

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

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

Styles

The site's 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:

@source "../dist";

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

UI Components

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

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

Build Output

The build hook runs once vuesho build has generated the public files, and never in vuesho dev. This plugin builds a Pagefind index from the generated pages:

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); 
    }
    await pagefind.close();
  },
};

Prop

Type

Prop

Type

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:

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

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:

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

Failing a Build

An error thrown in build fails vuesho build, like the link validation of the recommended preset on a dead link. Throw VueshoError for a mistake the site can fix:

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

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

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

Server and Vite Options

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:

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], 
    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().

Nitro Options

nitro sets Nitro options 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:

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*"] }, 
  };
}

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:

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

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:

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

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

Content

The pages of your content sources, and the results of the content hooks:

Prop

Type

Rendering on Request

The render modes, and the dynamic sources that the server reads again while the site runs:

Prop

Type

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

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

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

Prop

Type

Languages

The languages of an i18n site, with the paths and texts of each:

Prop

Type

URLs

addBasePath() and absoluteUrl() apply the site's base path, hideLocale and trailingSlash:

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

Prop

Type

Theme and Site

Prop

Type

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:

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:

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

Outside Hooks

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

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

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.

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

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

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

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

Prop

Type

Packages

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

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.

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, with vuesho and virtual:vuesho/* external.

Testing

createFetchHandler() from vuesho/server serves a site without Vite, so a Vitest test can request its API routes, data routes and middleware:

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

  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:

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

export default defineConfig({});

Prop

Type

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