docs-kit is the shared look and plumbing of WithMarfa's documentation sites. It
holds the Fumadocs layout, the MDX components, the styles, the agent-facing
routes (llms.txt, Markdown copies of pages, the sitemap), the search and the
Cloudflare Worker stages that docs.marfa.so and InkKit's docs both build on.
The package is @withmarfa/docs-kit. It is ESM only and written in
TypeScript.
docs-kit builds on a stack that your site already uses:
- Node 22 or later.
- A TanStack Start site on Cloudflare Workers, built with Vite and Tailwind CSS 4.
- Fumadocs:
fumadocs-coreandfumadocs-ui16.15.15 or later in version 16, andfumadocs-mdx15.4.5 or later in version 15.
The peer dependencies are react, react-dom, fumadocs-core, fumadocs-ui,
fumadocs-mdx, @tanstack/react-router and lucide-react. posthog-js is an
optional peer dependency: install it only if your site reports analytics.
The kit is published as prereleases. Until it has a stable version, each one is
also the latest version:
pnpm add -E @withmarfa/docs-kitIf your site uses pnpm's minimumReleaseAge, add @withmarfa/* to
minimumReleaseAgeExclude in pnpm-workspace.yaml, so a new kit release can
install at once.
| Import | What it holds |
|---|---|
@withmarfa/docs-kit |
The React components for pages, the header, errors and analytics, plus small helpers. |
@withmarfa/docs-kit/server |
Search, llms.txt, Markdown copies, the sitemap, robots.txt and the Worker stages. No React. |
@withmarfa/docs-kit/mdx |
The MDX components and the component map. Safe to import in the browser. |
@withmarfa/docs-kit/config |
The build-time options for source.config.ts: code highlighting, the Markdown copy and table labels. Node only. |
@withmarfa/docs-kit/vite |
Build-time helpers for vite.config.ts. |
@withmarfa/docs-kit/page-limits |
The page-limits check and a ready-made test suite. |
@withmarfa/docs-kit/styles.css |
The design tokens and the Fumadocs overrides. |
The steps below follow a site that has a src/lib/shared.ts with its name and
address, and a content/docs folder of MDX pages. Each step is one file.
Import the stylesheet first in your site's CSS, then add your own rules. The stylesheet imports Tailwind and the Fumadocs presets, and it tells Tailwind to scan the kit's components:
/* src/styles/app.css */
@import '@withmarfa/docs-kit/styles.css';
/* Your own rules follow. */The kit's body, link, code and table styles skip anything inside a not-prose
element, so a box that draws its own table, list or heading keeps its own
layout.
A table sits in a docs-kit-table box that getDocsKitMDXComponents draws
around it, so the box's width, not the screen's, decides the layout. A table of
up to five columns has fixed columns: the first takes 45% of a two-column table
and 30% of a three-column one, so tables on a page share their lines. Where the
box is narrower than 35rem, each row stacks as an entry. A site that registers
its own table component must keep that box (<div className="docs-kit-table relative my-6 overflow-auto prose-no-margin">) or its tables never stack.
A heading that is only a name in code, such as a member on a reference page,
draws as plain monospace text with no chip.
In source.config.ts, import from @withmarfa/docs-kit/config, not from /mdx: the config entry reaches Fumadocs's Node-only plugins, and /mdx stays free of them so a page can load it in the browser. Use codeOptions for code highlighting and
llmsOptions to write the Markdown copy of each page. llmsOptions already
writes the kit's own components (Callout, Cards, Steps, Terminal and the
others); give it a rewrite for each component that your site adds:
// source.config.ts
import { defineConfig, defineDocs } from 'fumadocs-mdx/config';
import { pageSchema } from 'fumadocs-core/source/schema';
import { codeOptions, llmsOptions, rehypeTableLabels } from '@withmarfa/docs-kit/config';
const llms = llmsOptions({
// Components whose children are the content: the copy keeps the children.
wrappers: ['ReferenceList'],
// Components that need their own text. Each rewrite returns Markdown.
rewrites: {
Icon: ({ attribute }) => attribute('markdown') ?? '',
},
});
export const docs = defineDocs({
dir: 'content/docs',
docs: {
schema: pageSchema,
postprocess: { includeProcessedMarkdown: llms },
},
});
export default defineConfig({
mdxOptions: {
rehypePlugins: (plugins) => [...plugins, rehypeTableLabels],
rehypeCodeOptions: codeOptions(),
},
});codeOptions takes the same options as Fumadocs's rehypeCodeOptions, such as
langs for a custom grammar. It keeps Fumadocs's notation comments, which
styles.css draws: end a line with // [!code highlight] for a quiet tint
and a bar on the left, or // [!code ++] and // [!code --] for lines a
change adds and removes. Use the comment syntax of the block's language. The
Markdown copy of the page drops the comments and keeps the code. rehypeTableLabels gives each table cell after the
first a data-label so that tables stack on a phone, and marks short inline code
data-short so that it stays on one line. Long inline code in a table cell
gets a break opportunity after each _, -, . and / and before a camelCase
capital, so it wraps at its own seams before it breaks inside a word. Copying
the code still gives its text unchanged.
buildDefines writes the build constants that your site reads, such as in its
/version.json route and its root route: __BUILD_COMMIT__, __BUILD_TIME__
and __POSTHOG_KEY__. prerenderFilter
keeps the routes that must stay on the Worker out of the prerendered files:
// vite.config.ts
import { buildDefines, prerenderFilter } from '@withmarfa/docs-kit/vite';
export default defineConfig({
define: buildDefines({ commitEnv: 'MY_BUILD_COMMIT', posthogKeyEnv: 'MY_POSTHOG_KEY' }),
plugins: [
// ...
tanstackStart({
prerender: {
enabled: true,
filter: prerenderFilter({ files: ['version.json'], trees: ['/api'], paths: ['/mcp'] }),
},
}),
],
});Declare the constants for TypeScript in a build-info.d.ts file:
declare const __BUILD_COMMIT__: string;
declare const __BUILD_TIME__: string;
declare const __POSTHOG_KEY__: string;The key is empty when the build has none, and then nothing loads and nothing is reported.
createSourceHelpers turns your Fumadocs source into the functions that the
routes below share:
// src/lib/source.ts
import { createSourceHelpers } from '@withmarfa/docs-kit/server';
export const {
markdownPathToSlugs,
findPage,
slugsToMarkdownPath,
hasMarkdown,
getLLMText,
markdownResponse,
pageForPath,
getLlmsFullText,
} = createSourceHelpers(source);The options docsRoute (the loader's baseUrl, empty by default),
transformText, preamble and inLlmsFull let a site move the docs under a
prefix, change a page's Markdown copy, add lines under its description or
leave a page out of llms-full.txt.
A site names itself once, in a Site value, and builds its top bar from that:
// src/components/site.tsx
import { createDocsHeaders, createSections, baseOptions, GitHubIcon } from '@withmarfa/docs-kit';
export const SECTIONS = createSections([
{ label: 'Home', href: '/' },
{ label: 'Guides', href: '/guides/start', prefix: '/guides' },
{ label: 'Reference', href: '/reference/api', prefix: '/reference' },
]);
export const { DocsHeader, DocsHomeHeader, sidebar } = createDocsHeaders({
title: 'My Docs',
logo: <img src="/mark.svg" alt="" className="size-5" />,
byline: 'by Example',
sections: SECTIONS,
links: [{ label: 'GitHub', href: 'https://github.com/example/docs', icon: <GitHubIcon /> }],
});
export const layoutOptions = () => baseOptions({ title: 'My Docs', githubUrl: 'https://github.com/example/docs' });A section with no prefix holds every page that no other section claims. When
no section claims a page, such as a landing page or the 404 page, no pill or
menu row shows as current; sectionFor(sections, pathname) returns undefined.
Call createDocsHeaders once, at module scope, so that each slot keeps one
identity.
logo and byline are optional. The logo draws before the title and the
byline after it, in the muted color and a step smaller, inside the same link to
href. The byline shows on phones too and hides only below 340px. Left out, the bar shows only the title.
The pills in the middle of the bar show from 1024px. Below that width the sections are reachable another way:
-
A page outside the docs layout (
DocsHomeHeader, such as a landing page or the 404 page) gets one menu button. It opens a panel under the bar with the sections, then the icon links and the appearance control at its foot. The panel closes on navigation, on Escape and on the button, and moves focus into itself and back. -
A page in the docs layout (
DocsHeader) lists the sections at the top of the phone drawer, and of the desktop sidebar below 1024px, when you pass thesidebarslot and turn off Fumadocs's own tabs, whose dropdown lists only the page tree's root folders:<DocsLayout {...layout} tabs={false} slots={{ ...layout.slots, header: DocsHeader, sidebar }} ...>
Without
sidebar, the drawer shows Fumadocs's tab dropdown as before.On a phone the drawer is the same pattern as the landing menu: it fills the screen under the bar, the bar's menu button turns into the close control where it was, the current section is bold and the current page keeps its pill, and the icon links and appearance control sit at the foot.
baseOptions puts the drawer's icon links in the order of the phone menu: the
githubUrl first, then the links you pass.
Render Analytics and PointerFocus in the root route. Analytics loads
PostHog after the page has hydrated, so the SDK is never in the entry chunk:
// src/routes/__root.tsx
import { Analytics, PointerFocus } from '@withmarfa/docs-kit';
<body>
<RootProvider i18n={{ translations }}>
<Outlet />
</RootProvider>
<Scripts />
<Analytics site="docs" posthogKey={__POSTHOG_KEY__} />
<PointerFocus />
</body>;translations is the kit's set of interface strings. Spread it into your own
set if you add strings:
import { translations as base } from '@withmarfa/docs-kit';
export const translations = { ...base };In the page route, use the kit's page components and pageHead, which sets the
title, description, canonical address and share card for a page:
// src/routes/$.tsx
import {
PageActions,
PageFooter,
PageTableOfContents,
PageTableOfContentsPopover,
fullTitles,
pageHead,
} from '@withmarfa/docs-kit';
export const Route = createFileRoute('/$')({
component: Page,
loader,
head: ({ loaderData }) => pageHead({ name: 'My Docs', url: 'https://docs.example.com' }, loaderData),
});Draw the top of the page with <PageHeader title={...} description={...} markdownUrl={...} githubUrl={...} />: the title with the Copy Markdown button
on its row, then the description as a lead. To draw your own header, use
pageTitleClass and pageDescriptionClass with Fumadocs's DocsTitle and
DocsDescription, and place <PageActions markdownUrl={...} githubUrl={...} />
in the title row. Pass <PageTableOfContents /> and <PageTableOfContentsPopover /> as the
component of the page's table of contents, and
<PageFooter titles={fullTitles(source.getPages())} /> as its footer.
Register the MDX components for the pages:
// src/components/mdx.tsx
import { getDocsKitMDXComponents } from '@withmarfa/docs-kit/mdx';
export const getMDXComponents = (components?: MDXComponents) =>
getDocsKitMDXComponents({ ...siteComponents, ...components });The components are Callout, Card, Cards, CodeBlockTabs, Terminal,
Step and Steps, and a code block that folds when it is long. A
component you pass wins over a kit component of the same name.
Steps numbers its steps down a rail. Write each step as a <Step>, or as a
### heading with its text under it, directly inside Steps; the two look the
same. Add paged to show one step at a time:
<Steps>
### Make a key
Open **Settings** and make a key.
### Sync
Run `sync`.
</Steps>The Markdown copy of a page keeps each step's heading and text, and writes no number.
A route at /{$}.md serves the Markdown copy of a page. It answers a missing
page with a plain 404, because the router's notFound() answers 200 from a
server handler:
// src/routes/{$}[.]md.ts
export const Route = createFileRoute('/{$}.md')({
server: {
handlers: {
GET: async ({ params }) => {
const page = findPage(markdownPathToSlugs(params._splat?.split('/') ?? []));
if (!page) {
return new Response('No such page.\n', {
status: 404,
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}
return markdownResponse(page);
},
},
},
});createIndexBuilders writes llms.txt and a one-fetch map of every page. You
give each a header, and it lists the pages by section and sidebar group:
// src/lib/docs-map.ts
import { createIndexBuilders } from '@withmarfa/docs-kit/server';
const index = createIndexBuilders({ source, siteUrl, slugsToMarkdownPath, hasMarkdown });
export const buildLlmsTxt = () => index.llmsTxt(['# My Docs', '', '> What the docs cover.', '']);
export const buildDocsMap = () => index.docsMap(['# My Docs map', '']);// src/routes/llms[.]txt.ts
export const Route = createFileRoute('/llms.txt')({
server: {
handlers: {
GET: async () => new Response(buildLlmsTxt(), { headers: { 'content-type': 'text/plain; charset=utf-8' } }),
},
},
});// src/routes/llms-full[.]txt.ts
export const Route = createFileRoute('/llms-full.txt')({
server: {
handlers: { GET: async () => new Response(await getLlmsFullText()) },
},
});// src/routes/sitemap[.]xml.ts
import { buildSitemap } from '@withmarfa/docs-kit/server';
export const Route = createFileRoute('/sitemap.xml')({
server: {
handlers: {
GET: async () => new Response(buildSitemap(siteUrl, source), { headers: { 'content-type': 'application/xml; charset=utf-8' } }),
},
},
});// src/routes/robots[.]txt.ts
import { robotsTxt } from '@withmarfa/docs-kit/server';
export const Route = createFileRoute('/robots.txt')({
server: {
handlers: {
GET: async () => new Response(robotsTxt(siteUrl), { headers: { 'content-type': 'text/plain; charset=utf-8' } }),
},
},
});createSearch builds one BM25 index over your pages with a tokenizer tuned for
documentation: flags, hyphenated names, codes and version numbers. You tell it
how your site ranks, and every field is optional:
// src/lib/docs-tools.ts
import { createSearch } from '@withmarfa/docs-kit/server';
export const { searchServer, searchDocs } = createSearch(source, {
kindOf: (page) => (page.path.startsWith('guides/') ? 'guide' : 'reference'),
kindWeights: { guide: 5, reference: 0 },
isConcept: (page) => page.path.startsWith('concepts/'),
lastResort: { url: '/changelog', asked: (query) => /changelog|release/i.test(query) },
});// src/routes/api/search.ts
export const Route = createFileRoute('/api/search')({
server: { handlers: { GET: async ({ request }) => searchServer.GET(request) } },
});searchDocs(query, limit?) returns { hits: [{ title, url, snippets }] }, so
the same index can serve a tool as well as the search box.
The route answers the search box with one row per page, then at most three
matches under it, each on a single line around the first match, ending in an
ellipsis where it is cut. A breadcrumb starts at the section, not at the site's
name. searchDocs keeps the full snippets. Below 768px the box's Escape chip
reads "Close", since a phone has no Escape key.
To show those rows, pass the kit's SearchDialog to Fumadocs's RootProvider.
links lists pages before anything is typed ([name, url], as Fumadocs's own
option); without it the box says what to type:
import { SearchDialog } from '@withmarfa/docs-kit';
<RootProvider
search={{
SearchDialog,
links: [
['Get started', '/guides/start'],
['API reference', '/reference/api'],
],
}}
>SearchDialog asks /api/search; pass a different route as api through a
small wrapper if yours differs.
createWorkerHandler composes the stages every docs Worker needs: it redirects
a trailing slash, answers a request that prefers Markdown with a page's
Markdown copy, and serves static files. Stages in before run first, so a site
can add its own, such as a rate limit:
// src/server.ts
import handler, { createServerEntry } from '@tanstack/react-start/server-entry';
import { env } from 'cloudflare:workers';
import { createWorkerHandler } from '@withmarfa/docs-kit/server';
export default createServerEntry({
fetch(request, opts) {
return createWorkerHandler({
assets: env.ASSETS,
app: async (forwarded) => handler.fetch(forwarded, opts),
pages: { pageForPath, markdownResponse },
before: [],
})(request);
},
});A stage is (request, next) => Response | Promise<Response>. compose and the
single stages markdownNegotiation, staticAssets and trailingSlash are
exported too, for a site that wants a different order.
The page-limits check keeps pages to a size and shape for their kind. A site
describes its limits in page-limits.json and runs the ready-made suite from
one test file:
// src/lib/page-limits.test.ts
import * as vitest from 'vitest';
import path from 'node:path';
import { definePageLimitsSuite, type Limits } from '@withmarfa/docs-kit/page-limits';
import config from './page-limits.json';
definePageLimitsSuite({
vitest,
contentDir: path.resolve('content/docs'),
limits: config as Limits,
});pnpm install
pnpm types:check
pnpm test
pnpm build
pnpm pack:checkpnpm pack:check packs the package and reads the tarball, so a file that is
missing from the published package fails here and not in a site's build.
To try a change in a site before you release it, pack the kit and add the tarball to the site:
pnpm build
pnpm pack --pack-destination /tmp/docs-kit
cd ../site && pnpm add file:/tmp/docs-kit/withmarfa-docs-kit-0.0.1-alpha.1.tgzDon't commit a file: dependency in a site.
Two sites build on the kit, so a breaking change needs a version bump and both
sites updated. Pushing a tag v<version> that matches package.json runs the release
workflow. It builds and tests the package, creates a GitHub release with the
tarball and publishes that tarball to npm through trusted publishing, with
provenance. A version with a hyphen is a prerelease. It is published under the latest
tag while npm has no stable version, and under the alpha tag after that.
Apache-2.0. See LICENSE.