# Local Files

A content source from local files.

`@vuesho/local-content` reads a folder on the server while the site runs, for files that change outside the repository, like generated reports. Files committed with the site belong in a [collection](/markdown/collections) instead.

## Reading a Folder [#reading-a-folder]

```npm
npm i @vuesho/local-content
```

`createLocalContent()` takes a function that parses each file, and the folder's options. `localContentPlugin()` serves the files that `files.serve` allows and reloads the page in development when the folder changes:

```ts title="vuesho.config.ts"
import { createLocalContent, localContentPlugin } from "@vuesho/local-content";
import { createSite, recommendedPreset } from "vuesho/config";

const releases = createLocalContent(
  // Runs for each file in `include`, and again once the file changes.
  async (file) => {
    const { version, notes } = JSON.parse(await file.read());
    return { type: "page", data: { title: `v${version}`, html: notes } };
  },
  {
    // The folder, relative to the project's root.
    dir: "releases",
    include: ["*.json"],
    // The route for the files that `serve` allows.
    files: { path: "/release-files", serve: (file) => /\.(png|jpe?g|svg)$/.test(file) },
  },
);

export default createSite({ changelog: releases.source({ baseDir: "changelog" }) }).plugins(
  recommendedPreset(),
  localContentPlugin(), // [!code highlight]
  {
    name: "site:changelog",
    getPageBody({ data }) {
      if ("html" in data && typeof data.html === "string") return { html: data.html };
    },
  },
);
```

```files
releases/
├── 0.1.0.json
├── 0.2.0.json
└── logo.png
```

`0.2.0.json` is the page `/changelog/0.2.0`, and the image is at `/release-files/logo.png`. The build copies a relative `dir` into the server output, while an absolute `dir` is read in place. For a host without a file system, like Cloudflare Workers, use a [static build](/deploying#static-hosting).

A file that fails to parse stops the server from starting, and fails the reload in development. On a running server, the server logs an error and keeps the file's last valid version, or leaves out a new file.

### Markdown Files [#markdown-files]

A folder of Markdown and `meta.json` files renders with markdown-it. Create `md` and `render()` in a module, as in [Rendering Markdown](/content-hooks#rendering-markdown):

```ts title="vuesho.config.ts"
import { createLocalContent, localContentPlugin, parseMeta } from "@vuesho/local-content";
import { createSite, getSiteContext, recommendedPreset } from "vuesho/config";
import { parseFrontmatter, extractStructuredData, buildToc } from "vuesho/markdown";
import { md, render } from "./src/server/markdown";
import { metaSchema, pageSchema } from "vuesho/schema";

const markdown = Symbol("markdown");
const markdownOf = (page: { data: object }) => (page.data as { [markdown]: string })[markdown];

const guides = createLocalContent(
  async (file) => {
    if (file.path.endsWith(".json")) return parseMeta(file, metaSchema);
    const { data, body } = parseFrontmatter(await file.read());
    const valid = await getSiteContext().validateFrontmatter(pageSchema, data);
    return { type: "page", data: { ...valid, [markdown]: body } }; // [!code highlight]
  },
  { dir: "guides", include: ["**/*.md", "**/meta.json"] },
);

export default createSite(guides.source()).plugins(recommendedPreset(), localContentPlugin(), {
  name: "site:guides",
  getPageBody: async (page) => ({ html: await render(markdownOf(page)) }), // [!code highlight]
  getPageToc: (page) => buildToc(md.parse(markdownOf(page), {})),
  getPageStructuredData: (page) => extractStructuredData(md.parse(markdownOf(page), {})),
  getPageText: (page) => markdownOf(page),
});
```

markdown-it keeps links and images as written, so put the guides' images in `public/`.

`pageSchema` and `metaSchema` extend like a [collection's](/markdown/collections#frontmatter-schema) schemas. Without Zod, `defaultPageSchema` and `defaultMetaSchema` from `vuesho/content` validate the same fields.

### Serving Files [#serving-files]

The files route serves a file only when `files.serve` returns `true` for it, and never a hidden file or a symbolic link. Without `files`, the folder has no route.

<Callout type="warn" title="Content Files">
Allow only media in `files.serve`, by their extensions. A content file that `files.serve` allows, like a Markdown draft, is public as source text.
</Callout>

An SVG file is sent with a `Content-Security-Policy` that blocks its scripts. On a static host, set the same header for the route's path:

```http
Content-Security-Policy: script-src 'none'; frame-src 'none'; sandbox;
```

## HTML Files [#html-files]

`@vuesho/local-html` publishes a folder of HTML documents, like exported reports, as pages with your site's theme and highlighted code.

### Install the Package [#install-the-package-step]

```npm
npm i @vuesho/local-html
```

### Connect the Folder [#connect-the-folder-step]

Put the HTML files in a separate folder, outside `content/`, and connect it in the config:

```ts title="vuesho.config.ts"
import { createLocalHtml, localHtmlPlugin } from "@vuesho/local-html";
import { createSite, recommendedPreset } from "vuesho/config";

const pages = createLocalHtml({ dir: "html" }); // [!code highlight]

export default createSite(pages.source()).plugins(
  recommendedPreset(),
  localHtmlPlugin(), // [!code highlight]
);
```

```files
html/
├── index.html
└── reports/
    ├── meta.json
    ├── q3.html
    └── chart.png
```

`reports/q3.html` is the page `/reports/q3`, and the image is at `/local-html-files/reports/chart.png`. The route serves the folder's other files, like images, but never HTML, JSON or YAML files or hidden files, and a relative URL in a document, like `<img src="chart.png">`, leads to it. To use the pages next to the Markdown in `content/`, give their source a `baseDir`, as in [Multiple Collections](/markdown/collections#multiple-collections).

`dir` follows the same rules as [`createLocalContent()`](#reading-a-folder).

### How a Document Renders [#how-a-document-renders]

The page's body is the document's only `<main>`, else its only `<article>`, else its `<body>`, which renders with the site's styles and [code themes](/markdown/code-blocks). Scripts, styles, iframes, forms, and the `<header>`, `<footer>`, `<nav>` and `<aside>` of `<body>` are removed. Link to another document by its URL, like `/reports/q3`, not by its `.html` file.

<Callout type="warn" title="Trusted HTML Only">
Removing scripts doesn't sanitize HTML, and a browser still loads the external resources a page refers to. Put only HTML that your team trusts in the folder.
</Callout>

A page's title is its `<title>`, or else its file name, and its description is `<meta name="description">`. `fumadocs:*` meta tags replace them and set the sidebar [icon](/navigation#icons):

```html
<meta name="fumadocs:title" content="Quarterly Report" />
<meta name="fumadocs:description" content="The numbers of Q3." />
<meta name="fumadocs:icon" content="ChartBar" />
```

`page.data.metadata` holds every `<meta name>` of the document, by name.

### Changing How Documents Render [#changing-how-documents-render]

`createLocalHtml()`'s options set the content element, the tags to remove, the styles and the highlighter. `selectContent` receives the document's [hast](https://github.com/syntax-tree/hast) tree, which `hast-util-select` queries:

```npm
npm i hast-util-select @pierre/highlights
```

```ts title="vuesho.config.ts"
import ayuLight from "@pierre/highlights/themes/ayu-light";
import dracula from "@pierre/highlights/themes/dracula";
import { select } from "hast-util-select";
import { createLocalHtml } from "@vuesho/local-html";
import { createHighlights } from "vuesho/highlight";

const pages = createLocalHtml({
  dir: "html",
  // The content element.
  selectContent: (root) => select("#content", root),
  // More tags to remove.
  exclude: ["figure"],
  // Keeps `class` and `style`.
  adaptStyles: false,
  highlighter: createHighlights({ themes: { light: ayuLight, dark: dracula } }),
});
```

To render the elements with other components, replace the `local-html` body in your [theme](/theme#views-and-page-bodies). The body receives the page as a hast tree in `tree`, and `toVNodes()` from `vuesho/ui/hast` renders the tree with the components you give it.

### Multiple Folders [#multiple-folders]

Give each folder a different `baseDir` and `files.path`:

```ts title="vuesho.config.ts"
import { createLocalHtml, localHtmlPlugin } from "@vuesho/local-html";

const reports = createLocalHtml({ dir: "reports", files: { path: "/report-files" } });
const decks = createLocalHtml({ dir: "decks", files: { path: "/deck-files" } });

createSite({
  docs: docs.toSource(),
  reports: reports.source({ baseDir: "reports" }),
  decks: decks.source({ baseDir: "decks" }),
}).plugins(recommendedPreset(), localHtmlPlugin()); // [!code highlight]
```

## Refreshing Content [#refreshing-content]

In development, editing a file reloads the page. In production, the server reads the folder again once `staleTime` passes, or when a webhook calls `revalidateLoader()`, as in [Dynamic Rendering](/dynamic-rendering#refreshing-content). Without `staleTime`, the files stay until a call to `revalidateLoader()`.

## Options [#options]

### `createLocalContent()` [#createlocalcontent]

### LocalContentOptions

| Prop      | Type                                                                                                                                                     | Description                                                                                                                                                                                                                                              |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dir`     | `string`                                                                                                                                                 | The folder, relative to the root of the project. The build copies the files of it that the server reads into a built server's output, while a folder outside the project, given by its absolute path, is read where it is.                               |
| `include` | `readonly string[]`                                                                                                                                      | Glob patterns for the content files, relative to `dir`. Files and folders starting with `.` are left out.                                                                                                                                                |
| `build?`  | `((entries: LocalEntry<unknown>[]) => SourceFile[]) \| undefined`                                                                                        | Builds the content source's files from the parsed files that match `include`. It runs again only when one of them changes, so the loader keeps its pages otherwise. Default: `` the page or meta file each one parsed to, and nothing for `undefined` `` |
| `files?`  | `{ path: string; serve: (file: string, entry: LocalEntry<unknown> \| undefined) => boolean; url?: (file: string) => string \| undefined; } \| undefined` | Serves the folder's files that `serve` allows, like the pages' images, never hidden ones, at the route `path`, through `localContentPlugin()`. A server reads them from the folder, and a build writes them. Without it, the folder serves no file.      |

### `source()` [#source]

### LocalSourceOptions

| Prop         | Type                  | Description                                                                                                                                                                                                                                   |
| ------------ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `baseDir?`   | `string \| undefined` | The folder for the pages in the site's file tree, which sets their URLs.                                                                                                                                                                      |
| `staleTime?` | `number \| undefined` | How long the server keeps what it read, in milliseconds. The first request after that reads the folder again and parses the changed files. In development, any change in the folder reads it again. Default: `` until `revalidateLoader()` `` |

### `createLocalHtml()` [#createlocalhtml]

### CreateLocalHtmlOptions

| Prop             | Type                                                          | Description                                                                                                                                                                                                                                              |
| ---------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dir`            | `string`                                                      | The folder of HTML files, relative to the root of the project. The build copies the files of it that the server reads into a built server's output, while a folder outside the project, given by its absolute path, is read where it is.                 |
| `include?`       | `string[] \| undefined`                                       | Glob patterns for the content's files, relative to `dir`: the HTML files, one page each, and the meta files. Files and folders starting with `.` are left out. Default: `["**\/*.{html,json}"]`                                                          |
| `metaSchema?`    | `StandardSchemaV1<unknown, MetaData> \| undefined`            | Validates each meta file. Default: `` the fields of `metaSchema` ``                                                                                                                                                                                      |
| `highlighter?`   | `false \| Highlighter \| undefined`                           | Highlights code blocks with a highlighter from `vuesho/highlight`, like `createHighlights({ themes })`, instead of the site's. `false` leaves them as they are. Default: ``the site's highlighter, which `highlight` of `markdown` of the config gives`` |
| `files?`         | `{ path: string; } \| undefined`                              | The route that serves the folder's other files, like the pages' images, and no other folder of the site. A server reads them from the folder, and a build writes them. Default: `` `{ path: "/local-html-files" }` ``                                    |
| `selectContent?` | `((root: Root) => Element \| Root \| undefined) \| undefined` | Picks the element that holds a page's content, from its document tree. Default: ``the only `<main>`, then the only `<article>`, then `<body>`, then the whole tree``                                                                                     |
| `exclude?`       | `readonly string[] \| undefined`                              | More tags to leave out of the content, besides scripts, styles and embedded documents.                                                                                                                                                                   |
| `adaptStyles?`   | `boolean \| undefined`                                        | Removes every element's `class` and `style`, so the content takes the docs' styles. A code block's `language-*` class stays, since it names the code's language. Default: `true`                                                                         |
