From 32ba033f5f2e35cdf135346a95a1d002accec5df Mon Sep 17 00:00:00 2001 From: monarcode Date: Mon, 23 Nov 2026 11:33:35 +0100 Subject: [PATCH] docs(site): serve pages as Markdown, add llms.txt and versioned docs --- .oxfmtrc.json | 3 +- .oxlintrc.json | 3 +- AGENTS.md | 9 + CHANGELOG.md | 5 + README.md | 1 + package.json | 1 + scripts/reference-docs.mjs | 17 +- scripts/snapshot-docs.mjs | 233 ++++++++++++++++++ .../docs/(latest)/reference/fetch-test.mdx | 5 - .../content/docs/(latest)/reference/fetch.mdx | 48 ---- .../docs/(latest)/reference/plugins.mdx | 28 --- site/src/components/search.tsx | 9 +- site/src/lib/docs.ts | 7 +- site/src/lib/mdx-options.ts | 8 +- site/src/lib/shared.ts | 55 +++++ site/src/lib/source.ts | 126 +++++++++- site/src/routes/api/search.ts | 15 +- site/src/routes/docs/$.tsx | 74 +++++- site/src/routes/docs/{$}[.]md.ts | 22 ++ site/src/routes/llms-full[.]txt.ts | 17 ++ site/src/routes/llms[.]txt.ts | 27 ++ site/tsconfig.json | 2 +- site/vite.config.ts | 13 +- 23 files changed, 620 insertions(+), 108 deletions(-) create mode 100644 scripts/snapshot-docs.mjs create mode 100644 site/src/routes/docs/{$}[.]md.ts create mode 100644 site/src/routes/llms-full[.]txt.ts create mode 100644 site/src/routes/llms[.]txt.ts diff --git a/.oxfmtrc.json b/.oxfmtrc.json index ff98419..65cfcd3 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -23,7 +23,8 @@ "coverage", ".smoke", ".tanstack", - "routeTree.gen.ts" + "routeTree.gen.ts", + "site/versions" ], "sortImports": { "customGroups": [ diff --git a/.oxlintrc.json b/.oxlintrc.json index 8a1166a..1e6aa5a 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -11,7 +11,8 @@ "**/coverage/**", "**/.smoke/**", "**/.tanstack/**", - "**/routeTree.gen.ts" + "**/routeTree.gen.ts", + "site/versions/**" ], "rules": { "no-unused-vars": "off", diff --git a/AGENTS.md b/AGENTS.md index 2a601e7..e613663 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,6 +68,15 @@ to static files. It's a package in the pnpm workspace and isn't published. export or its docs, run `pnpm run docs:reference`. A new export needs a group in that script, and the docs check fails until it has one and the pages match. +- Older release lines in `site/content/docs//` are snapshots of + released docs, with that release's types in `site/versions//`. + Don't edit them, and don't update them when the API changes: the docs + check and Twoslash skip them. `pnpm run docs:snapshot ` writes one; + its header comment says when and how. +- Each page is also served as Markdown (`/docs/.md`), and + `/llms.txt` and `/llms-full.txt` list the current line's pages. Link + between pages with root-relative paths, which the Markdown turns into + full URLs. - `pnpm run check` doesn't build the site. After changing `site/`, run `pnpm run build:site`, which builds the package, then prerenders the site into `site/dist/client`. `pnpm --dir site run dev` serves it while you diff --git a/CHANGELOG.md b/CHANGELOG.md index e67e13d..e5fead8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ All notable changes to `@monarcode/effetch`, newest first. types. A [Compatibility](https://effetch.pages.dev/docs/reference/compatibility) page lists the supported Effect versions, runtimes and TypeScript settings. +- Each page of the site is also served as Markdown, from the page's + "Copy Markdown" button and its view options, and + [llms.txt](https://effetch.pages.dev/llms.txt) and + [llms-full.txt](https://effetch.pages.dev/llms-full.txt) list the pages + for LLMs. ### Changed diff --git a/README.md b/README.md index 29a005e..ed59de6 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,7 @@ pnpm run check | `pnpm run check` | All of the above, plus publint and attw. CI runs it on every push to `main` and every pull request. | | `pnpm run build:site` | Builds the package, then prerenders the docs site in `site/` to `site/dist/client`, failing on a type error in an example. `check` doesn't build the site; CI does. | | `pnpm run docs:reference` | Writes the site's API reference pages from the JSDoc. Run it after changing a public export or its docs. | +| `pnpm run docs:snapshot` | Freezes an older release line's docs into the site, such as `pnpm run docs:snapshot 0.1` when `0.2` starts. | To work on the docs site, run `pnpm run build`, then `pnpm --dir site run dev`. The site's type hovers and tables read the built package, so build again diff --git a/package.json b/package.json index 7af2e14..e19c2c2 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ "typecheck": "tsc --noEmit", "check:docs": "node scripts/check-docs.mjs", "docs:reference": "node scripts/reference-docs.mjs", + "docs:snapshot": "node scripts/snapshot-docs.mjs", "test": "vitest run", "test:watch": "vitest", "check:package": "publint --strict && attw --pack . --profile esm-only", diff --git a/scripts/reference-docs.mjs b/scripts/reference-docs.mjs index dadd4f9..ca36b68 100644 --- a/scripts/reference-docs.mjs +++ b/scripts/reference-docs.mjs @@ -314,7 +314,7 @@ ${importLine} entry, ...entry.members, ])) { - body += `\n### ${entry.name} [#${entry.id}]\n\n${summaryOf(entry.declaration, page, checker, targets)}\n`; + body += `\n### ${entry.name} [#${entry.id}]\n\n${summaryOf(entry, page, checker, targets)}\n`; if (entry.table) { const declared = entry.source .replace(/^src\//, "") @@ -327,10 +327,14 @@ ${importLine} } /** - * A declaration's first paragraph, with a list it introduces. A link to an - * export on the reference becomes a link to its entry; others become code. + * An entry's first paragraph, and the list after it, such as a type's + * values or a function's behavior. An entry with a type table keeps the list + * only when the paragraph leads into it ("…, and"), since the table lists the + * properties. A link to an export on the reference becomes a link to its + * entry; others become code. */ -function summaryOf(node, page, checker, targets) { +function summaryOf(entry, page, checker, targets) { + const node = entry.declaration; const doc = ts.getJSDocCommentsAndTags(node).filter(ts.isJSDoc).at(-1); const comment = doc?.comment; let text = ""; @@ -347,8 +351,9 @@ function summaryOf(node, page, checker, targets) { } const blocks = text.trim().split(/\n\s*\n/); const kept = [blocks[0] ?? ""]; - // A list right after the first paragraph finishes its sentence. - if (/^\s*- /.test(blocks[1] ?? "")) kept.push(blocks[1]); + const unfinished = !/[.!?]\s*$/.test(blocks[0] ?? ""); + if ((unfinished || !entry.table) && /^\s*- /.test(blocks[1] ?? "")) + kept.push(blocks[1]); return kept.map(toMarkdown).join("\n\n"); } diff --git a/scripts/snapshot-docs.mjs b/scripts/snapshot-docs.mjs new file mode 100644 index 0000000..9460472 --- /dev/null +++ b/scripts/snapshot-docs.mjs @@ -0,0 +1,233 @@ +#!/usr/bin/env node +// Freezes a release line's docs into the site, so readers can still open +// them once the next line is current. +// +// node scripts/snapshot-docs.mjs 0.1 +// +// Run it while preparing the first release of a new line (for `0.2.0-rc.0`, +// snapshot `0.1`), and again after a later patch to that line. It takes the +// pages from the line's newest release tag, not from `main`, which already +// documents the new line, and that release's types from npm, so the +// snapshot's type tables show the line's own API. +// +// Options: +// --tag v0.1.3 take the pages from this tag instead of the newest one +// --worktree take the pages from the working tree, to try the script +// before the line has a release (with --types) +// --types 0.1.3 take the types from this published version instead of +// the tag's + +import { execFileSync } from "node:child_process"; +import { + cpSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const docs = join(root, "site", "content", "docs"); +const LATEST = "(latest)"; +const PAGES = `site/content/docs/${LATEST}`; + +const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + tag: { type: "string" }, + worktree: { type: "boolean", default: false }, + types: { type: "string" }, + }, +}); +const [line] = positionals; +if (!line || !/^\d+\.\d+$/.test(line)) + fail("Usage: node scripts/snapshot-docs.mjs , such as 0.1"); +const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); +const current = pkg.version.split(".").slice(0, 2).join("."); +if (line === current && !values.worktree) + fail( + `${line} is the current line (package.json is ${pkg.version}). Snapshot a line once the next one has started.`, + ); + +if ( + values.tag !== undefined && + !new RegExp(`^v${line.replace(".", "\\.")}\\.\\d+(-[\\w.]+)?$`).test( + values.tag, + ) +) + fail(`--tag must be a v${line}.* release tag, such as v${line}.0`); +const tag = values.worktree ? undefined : (values.tag ?? newestTag(line)); +const typesVersion = values.types ?? tag?.slice(1); +if (!typesVersion) fail("--worktree needs --types "); + +const scratch = mkdtempSync(join(tmpdir(), "snapshot-docs-")); +try { + // Everything is built in the scratch folder first, so a failure, such as + // npm being offline, leaves the existing snapshot as it was. + const pages = join(scratch, "pages"); + const types = join(scratch, "types"); + copyPages(pages); + copyTypes(types); + const count = rewritePages(pages); + // Titled by the release it was taken from, such as 0.1.3. + setTitle(join(pages, "meta.json"), typesVersion); + + // Formatted like the rest of the pages, so `check` passes on the result. + // The scratch folder is outside the repository, so name the config. + execFileSync( + join(root, "node_modules", ".bin", "oxfmt"), + ["--config", join(root, ".oxfmtrc.json"), "--write", pages], + { + cwd: root, + stdio: "inherit", + }, + ); + + // Swapped in only once both are ready. + const target = join(docs, line); + const typesTarget = join(root, "site", "versions", line, "types"); + rmSync(target, { recursive: true, force: true }); + rmSync(typesTarget, { recursive: true, force: true }); + cpSync(pages, target, { recursive: true }); + cpSync(types, typesTarget, { recursive: true }); + console.log( + `✓ ${line}: ${count} pages from ${tag ?? "the working tree"}, types from ${pkg.name}@${typesVersion}`, + ); +} catch (error) { + console.error(`✗ ${error instanceof Error ? error.message : error}`); + process.exitCode = 1; +} finally { + rmSync(scratch, { recursive: true, force: true }); +} + +function fail(message) { + console.error(`✗ ${message}`); + process.exit(1); +} + +/** + * The line's newest release tag, by semver precedence: a release beats its + * own prereleases, and `rc.1` beats `rc.0` and `alpha.8`. + */ +function newestTag(line) { + const tags = execFileSync("git", ["tag", "--list", `v${line}.*`], { + cwd: root, + encoding: "utf8", + }) + .split("\n") + .filter((name) => /^v\d+\.\d+\.\d+(-[\w.]+)?$/.test(name)); + if (tags.length === 0) fail(`no v${line}.* tag: has ${line} been released?`); + return tags.sort(compareVersions).at(-1); +} + +function compareVersions(a, b) { + const [coreA, preA] = splitVersion(a); + const [coreB, preB] = splitVersion(b); + const patch = Number(coreA.split(".")[2]) - Number(coreB.split(".")[2]); + if (patch !== 0) return patch; + if (preA === undefined || preB === undefined) + return (preA === undefined ? 1 : 0) - (preB === undefined ? 1 : 0); + const partsA = preA.split("."); + const partsB = preB.split("."); + for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) { + const x = partsA[i]; + const y = partsB[i]; + // A shorter prerelease comes first: `rc` before `rc.0`. + if (x === undefined || y === undefined) return x === undefined ? -1 : 1; + const numeric = /^\d+$/.test(x) && /^\d+$/.test(y); + const order = numeric + ? Number(x) - Number(y) + : x < y + ? -1 + : x > y + ? 1 + : 0; + if (order !== 0) return order; + } + return 0; +} + +function splitVersion(tag) { + const dash = tag.indexOf("-"); + return dash === -1 + ? [tag.slice(1)] + : [tag.slice(1, dash), tag.slice(dash + 1)]; +} + +function copyPages(target) { + if (!tag) { + cpSync(join(docs, LATEST), target, { recursive: true }); + return; + } + const listed = execFileSync("git", ["ls-tree", "-d", tag, "--", PAGES], { + cwd: root, + encoding: "utf8", + }); + if (!listed.trim()) throw new Error(`${tag} has no ${PAGES}`); + const archive = execFileSync( + "git", + ["archive", "--format=tar", tag, PAGES], + { cwd: root, maxBuffer: 1 << 28 }, + ); + const extracted = join(scratch, "archive"); + mkdirSync(extracted, { recursive: true }); + execFileSync("tar", ["-x", "-C", extracted], { input: archive }); + cpSync(join(extracted, PAGES), target, { recursive: true }); +} + +/** The published `.d.ts` files of the line's release, from npm. */ +function copyTypes(types) { + const file = execFileSync( + "npm", + [ + "pack", + `${pkg.name}@${typesVersion}`, + "--pack-destination", + scratch, + // A cache of its own, so it doesn't depend on the machine's. + "--cache", + join(scratch, "npm-cache"), + "--silent", + ], + { cwd: scratch, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }, + ).trim(); + execFileSync("tar", ["-xzf", join(scratch, file), "-C", scratch]); + cpSync(join(scratch, "package", "dist"), types, { + recursive: true, + filter: (path) => !/\.(js|map)$/.test(path), + }); +} + +/** + * Points the snapshot at itself: links into the docs, and type tables at its + * own types. Its examples get no Twoslash hovers: the site adds them to + * `(latest)` pages only, as theirs would come from the current package. + */ +function rewritePages(target) { + let count = 0; + for (const name of readdirSync(target, { recursive: true })) { + if (!name.endsWith(".mdx")) continue; + const path = join(target, name); + const text = readFileSync(path, "utf8") + .replace(/\]\(\/docs(?=[/#)])/g, `](/docs/${line}`) + .replace(/href="\/docs(?=[/#"])/g, `href="/docs/${line}`) + .replace( + /path="node_modules\/@monarcode\/effetch\/dist\//g, + `path="versions/${line}/types/`, + ); + writeFileSync(path, text); + count++; + } + return count; +} + +function setTitle(path, title) { + const meta = JSON.parse(readFileSync(path, "utf8")); + writeFileSync(path, `${JSON.stringify({ ...meta, title }, null, "\t")}\n`); +} diff --git a/site/content/docs/(latest)/reference/fetch-test.mdx b/site/content/docs/(latest)/reference/fetch-test.mdx index 4e5c091..d217a6f 100644 --- a/site/content/docs/(latest)/reference/fetch-test.mdx +++ b/site/content/docs/(latest)/reference/fetch-test.mdx @@ -61,8 +61,6 @@ The services handler `H` needs to run: `R` for a `Handler`. For a union of ha Options for [`layer`](#layer). -- `baseUrl`: where the routes start, such as `"https://api.test/v1"`. With it, a request matches a route only when its URL is the `baseUrl`, then the route's path. Without it, a route matches the end of a request's path, whatever comes before it, so the fake backend works under any client's `baseUrl`. - ` with every request. Options for [`bearer`](#bearer). -- `token`: where the token comes from (see [`TokenSource`](#tokensource)). It's resolved for every request, inside that request's fiber, and never cached, so a refreshed or cleared token takes effect on the next request. -- `scheme`: the word before the token. Defaults to `"Bearer"`. -- `refresh`: where a new token comes from when the server answers `401` to a request that `bearer` sent a token with (see [`RefreshSource`](#refreshsource)). The request is then sent once more, with the new token. Without `refresh`, a `401` is returned as it is. - diff --git a/site/src/lib/docs.ts b/site/src/lib/docs.ts index 94cc6c5..2804e40 100644 --- a/site/src/lib/docs.ts +++ b/site/src/lib/docs.ts @@ -8,5 +8,10 @@ import { defineDocs } from "fumadocs-mdx/macro"; export const docs = defineDocs({ dir: "content/docs", // Pages are MDX only: the docs check and the prerender list read `.mdx`. - docs: { files: ["**/*.mdx"], async: true }, + docs: { + files: ["**/*.mdx"], + async: true, + // Each page's Markdown, for `llms.txt` and the `.md` routes. + postprocess: { includeProcessedMarkdown: true }, + }, }); diff --git a/site/src/lib/mdx-options.ts b/site/src/lib/mdx-options.ts index 1d61ea2..ff62ff4 100644 --- a/site/src/lib/mdx-options.ts +++ b/site/src/lib/mdx-options.ts @@ -54,12 +54,14 @@ function twoslashErrors(build: boolean) { } /** - * A hover's docs: their first paragraph, with a list right after it, which - * finishes its sentence. + * A hover's docs: their first paragraph, and a list after it when the + * paragraph doesn't end a sentence, as one ending in a colon doesn't. */ function firstParagraph(docs: string) { const [first = "", next = ""] = docs.split(/\n\s*\n/); - return /^\s*- /.test(next) ? `${first}\n\n${next}` : first; + return !/[.!?]\s*$/.test(first) && /^\s*- /.test(next) + ? `${first}\n\n${next}` + : first; } /** diff --git a/site/src/lib/shared.ts b/site/src/lib/shared.ts index 869b4df..e34d5ed 100644 --- a/site/src/lib/shared.ts +++ b/site/src/lib/shared.ts @@ -19,3 +19,58 @@ export const gitConfig = { repo: "effetch", branch: "main", }; + +/** Where the site is served. Link previews and `llms.txt` need full URLs. */ +export const SITE_URL = "https://effetch.pages.dev"; + +/** The URL of a page's Markdown, for LLMs and the copy button. */ +export function getPageMarkdownUrl(page: { slugs: string[] }) { + const segments = [...page.slugs]; + if (segments.length === 0) segments.push("index.md"); + else segments[segments.length - 1] += ".md"; + return { segments, url: [docsRoute, ...segments].join("/") }; +} + +/** The page slugs of a Markdown URL from {@link getPageMarkdownUrl}. */ +export function decodeMarkdownUrl(segments: string[]) { + if (segments.length === 0) return []; + const out = [...segments]; + out[out.length - 1] = out[out.length - 1]!.replace(/\.md$/, ""); + if (out.length === 1 && out[0] === "index") out.pop(); + return out; +} + +/** The search tag and version of the current release line's pages. */ +export const LATEST = "latest"; + +/** + * The version dropdown's label for a release: `0.1.0` once it's stable, and + * `0.1.0 prerelease` for an alpha, beta or release candidate of it. + */ +export function versionLabel(release: string): string { + const [stable, prerelease] = release.split("-", 2); + return prerelease ? `${stable} prerelease` : stable!; +} + +/** Set by `vite.config.ts` from the package's `package.json`. */ +declare const __PACKAGE_VERSION__: string; + +/** The current line's label, from the package's version as the site builds. */ +export function latestLabel(): string { + return versionLabel(__PACKAGE_VERSION__); +} + +/** + * The release line a page belongs to: its version folder (`0.1`), or + * {@link LATEST} for the current line in `(latest)`. + */ +export function versionOfPath(path: string): string { + const folder = path.split("/")[0]!; + return folder.startsWith("(") ? LATEST : folder; +} + +/** The release line a docs URL shows, such as `/docs/0.1/…`. */ +export function versionOfUrl(pathname: string): string { + const segment = /^\/docs\/([^/]+)/.exec(pathname)?.[1]; + return segment && /^\d+\.\d+$/.test(segment) ? segment : LATEST; +} diff --git a/site/src/lib/source.ts b/site/src/lib/source.ts index c70d6b6..323fb43 100644 --- a/site/src/lib/source.ts +++ b/site/src/lib/source.ts @@ -1,12 +1,132 @@ -import { loader } from "fumadocs-core/source"; +import { + flattenTree, + getPageTreeRoots, + type Folder, + type Item, +} from "fumadocs-core/page-tree"; +import { llms, loader } from "fumadocs-core/source"; import { lucideIconsPlugin } from "fumadocs-core/source/lucide-icons"; import { docs } from "./docs"; -import { docsRoute } from "./shared"; +import { + docsRoute, + getPageMarkdownUrl, + LATEST, + latestLabel, + SITE_URL, + versionOfPath, +} from "./shared"; /** The page tree and page lookup. Import it from server code only. */ export const source = loader({ source: docs.toFumadocsSource(), baseUrl: docsRoute, - plugins: [lucideIconsPlugin()], + plugins: [ + lucideIconsPlugin(), + { + // The current line is named by the package's version, so the label + // moves from "prerelease" to stable when the release ships. + transformPageTree: { + folder: (node, folderPath) => + node.root && versionOfPath(folderPath) === LATEST + ? { ...node, name: latestLabel() } + : node, + }, + }, + ], }); + +// Full URLs throughout: these files are read away from the site. +export const docsLlms = llms(source, { + renderUrl: (node: Item) => { + const page = source.getNodePage(node); + if (page) return SITE_URL + getPageMarkdownUrl(page).url; + return node.url.startsWith("/") ? SITE_URL + node.url : node.url; + }, + renderPage: async (page) => + `# ${page.data.title} (${SITE_URL}${page.url})\n\n${plainMarkdown(await page.data.getText("processed"), page.url)}`, +}); + +/** + * Rewrites what the processed Markdown keeps of the MDX, for a page at + * `url`, outside code blocks: headings lose their anchor IDs, comments go, a + * callout becomes a quote, an accordion's title becomes a bold line, a type + * table keeps only its table, and links into the site, the page's own + * anchors too, get its full URL. + */ +function plainMarkdown(text: string, url: string) { + return text + .split(/(^[ \t]*```[\s\S]*?^[ \t]*```[ \t]*$)/m) + .map((part, index) => (index % 2 ? part : plainProse(part, url))) + .join(""); +} + +function plainProse(text: string, url: string) { + return ( + text + .replace(/^(#+ .*) \[#[\w-]+\]$/gm, "$1") + .replace(/^\{\/\*[\s\S]*?\*\/\}\n+/gm, "") + .replace( + /^]*)>\n([\s\S]*?)\n<\/Callout>$/gm, + (_, attributes: string, body: string) => { + const title = /\btitle="([^"]*)"/.exec(attributes)?.[1]; + const quoted = title ? `**${title}**\n\n${body}` : body; + return quoted + .split("\n") + .map((line) => (line ? `> ${line}` : ">")) + .join("\n"); + }, + ) + .replace(/^<\/?Accordions>\n/gm, "") + .replace(/^$/gm, "**$1**\n") + .replace(/^<\/Accordion>\n/gm, "") + // A type table's Markdown repeats the entry's heading and docs + // before its table: `### Fetch.ClientConfig` … `### ClientConfig`. + .replace( + /^(### (?:\w+\.)*(\w+)\n(?:(?!^### )[\s\S])*?)^### \2\n(?:(?!^### )[\s\S])*?(?=^\| Prop )/gm, + "$1", + ) + .replace(/\]\(#/g, `](${SITE_URL}${url}#`) + .replace(/\]\(\/(?!\/)/g, `](${SITE_URL}/`) + ); +} + +/** + * The current release line's root folder in the sidebar. `llms.txt` lists + * only its pages, so readers and LLMs don't get an older line's API beside + * the current one. + */ +export function currentFolder(): Folder { + const folder = getPageTreeRoots(source.getPageTree()).find( + (root): root is Folder => { + if (root.type !== "folder") return false; + const first = flattenTree([root])[0]; + const page = first && source.getNodePage(first); + return versionOfPath(page?.path ?? "") === LATEST; + }, + ); + if (!folder) throw new Error("The docs have no current release line"); + return folder; +} + +/** + * The current release line's pages, in the sidebar's order. Fails on a page + * its `meta.json` doesn't list, which would be missing from `llms.txt`. + */ +export function currentPages() { + const pages = flattenTree([currentFolder()]).flatMap( + (node) => source.getNodePage(node) ?? [], + ); + const listed = new Set(pages.map((page) => page.path)); + const unlisted = source + .getPages() + .filter( + (page) => + versionOfPath(page.path) === LATEST && !listed.has(page.path), + ); + if (unlisted.length > 0) + throw new Error( + `Add these pages to their folder's meta.json: ${unlisted.map((page) => page.path).join(", ")}`, + ); + return pages; +} diff --git a/site/src/routes/api/search.ts b/site/src/routes/api/search.ts index c90bb13..d5769d1 100644 --- a/site/src/routes/api/search.ts +++ b/site/src/routes/api/search.ts @@ -1,9 +1,22 @@ import { createFileRoute } from "@tanstack/react-router"; import { createFromSource } from "fumadocs-core/search/server"; +import { versionOfPath } from "@/lib/shared"; import { source } from "@/lib/source"; -const server = createFromSource(source, { language: "english" }); +// Each page is tagged with its release line, so search looks only in the +// version being read. +const server = createFromSource(source, { + language: "english", + buildIndex: async (page) => ({ + id: page.url, + url: page.url, + title: page.data.title ?? "", + description: page.data.description, + structuredData: await page.data.structuredData(), + tag: versionOfPath(page.path), + }), +}); // Prerendered to a static index, which the search dialog downloads. export const Route = createFileRoute("/api/search")({ diff --git a/site/src/routes/docs/$.tsx b/site/src/routes/docs/$.tsx index 073ef69..c57a2d0 100644 --- a/site/src/routes/docs/$.tsx +++ b/site/src/routes/docs/$.tsx @@ -1,20 +1,30 @@ -import { createFileRoute, notFound } from "@tanstack/react-router"; +import { createFileRoute, Link, notFound } from "@tanstack/react-router"; import { createServerFn } from "@tanstack/react-start"; import { staticFunctionMiddleware } from "@tanstack/start-static-server-functions"; import { useFumadocsLoader } from "fumadocs-core/source/client"; +import { Callout } from "fumadocs-ui/components/callout"; import { DocsLayout } from "fumadocs-ui/layouts/docs"; import { DocsBody, DocsDescription, DocsPage, DocsTitle, + MarkdownCopyButton, + ViewOptionsPopover, } from "fumadocs-ui/layouts/docs/page"; import { Suspense, use } from "react"; import { useMDXComponents } from "@/components/mdx"; import { docs } from "@/lib/docs"; import { baseOptions } from "@/lib/layout.shared"; -import { pageMeta } from "@/lib/shared"; +import { + getPageMarkdownUrl, + gitConfig, + LATEST, + latestLabel, + pageMeta, + versionOfPath, +} from "@/lib/shared"; // Used only by the server function's handler, which the client build drops. import { source } from "@/lib/source"; @@ -28,7 +38,17 @@ export const Route = createFileRoute("/docs/$")({ }, head: ({ loaderData }) => ({ meta: loaderData - ? pageMeta(`${loaderData.title} | Effetch`, loaderData.description) + ? [ + ...pageMeta( + `${loaderData.title} | Effetch`, + loaderData.description, + ), + // Older lines stay out of search engines, which send readers + // to the current docs instead. + ...(loaderData.older + ? [{ name: "robots", content: "noindex" }] + : []), + ] : [], }), }); @@ -52,15 +72,36 @@ const loader = createServerFn({ method: "GET" }) .handler(async ({ data: slugs }) => { const page = source.getPage(slugs); if (!page) throw notFound(); + const version = versionOfPath(page.path); + const older = + version === LATEST + ? undefined + : { + version, + // The same page in the current line, or its first page. + latestUrl: source.getPage(slugs.slice(1))?.url ?? "/docs", + }; return { path: page.path, title: page.data.title ?? "", description: page.data.description ?? "", + markdownUrl: getPageMarkdownUrl(page).url, pageTree: await source.serializePageTree(source.getPageTree()), + older, }; }); -function Content({ path }: { path: string }) { +type Older = { version: string; latestUrl: string } | undefined; + +function Content({ + path, + markdownUrl, + older, +}: { + path: string; + markdownUrl: string; + older: Older; +}) { const page = docs.getPage(path); if (!page) throw new Error(`unknown page: ${path}`); @@ -69,8 +110,25 @@ function Content({ path }: { path: string }) { return ( + {older && ( + + These docs are for Effetch {older.version}. The latest is{" "} + {latestLabel()}:{" "} + + read this page there + + . + + )} {page.title} {page.description} +
+ + +
@@ -79,12 +137,16 @@ function Content({ path }: { path: string }) { } function Page() { - const { pageTree, path } = useFumadocsLoader(Route.useLoaderData()); + const { pageTree, path, markdownUrl, older } = useFumadocsLoader( + Route.useLoaderData(), + ); return ( + {/* For the prerender's crawler, which then writes every `.md` file. */} + - + ); diff --git a/site/src/routes/docs/{$}[.]md.ts b/site/src/routes/docs/{$}[.]md.ts new file mode 100644 index 0000000..d9f2a59 --- /dev/null +++ b/site/src/routes/docs/{$}[.]md.ts @@ -0,0 +1,22 @@ +import { createFileRoute, notFound } from "@tanstack/react-router"; + +import { decodeMarkdownUrl } from "@/lib/shared"; +import { docsLlms, source } from "@/lib/source"; + +// Each page as Markdown, for LLMs and the copy button. The docs page links +// to it, so the prerender finds every one. +export const Route = createFileRoute("/docs/{$}.md")({ + server: { + handlers: { + GET: async ({ params }) => { + const slugs = decodeMarkdownUrl(params._splat?.split("/") ?? []); + const page = source.getPage(slugs); + if (!page) throw notFound(); + + return new Response(await docsLlms.page(page), { + headers: { "Content-Type": "text/markdown; charset=utf-8" }, + }); + }, + }, + }, +}); diff --git a/site/src/routes/llms-full[.]txt.ts b/site/src/routes/llms-full[.]txt.ts new file mode 100644 index 0000000..ab0b637 --- /dev/null +++ b/site/src/routes/llms-full[.]txt.ts @@ -0,0 +1,17 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { currentPages, docsLlms } from "@/lib/source"; + +export const Route = createFileRoute("/llms-full.txt")({ + server: { + handlers: { + GET: async () => + new Response( + (await Promise.all(currentPages().map(docsLlms.page))).join( + "\n\n", + ), + { headers: { "Content-Type": "text/plain; charset=utf-8" } }, + ), + }, + }, +}); diff --git a/site/src/routes/llms[.]txt.ts b/site/src/routes/llms[.]txt.ts new file mode 100644 index 0000000..b4453bb --- /dev/null +++ b/site/src/routes/llms[.]txt.ts @@ -0,0 +1,27 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { SITE_URL } from "@/lib/shared"; +import { currentFolder, docsLlms } from "@/lib/source"; + +export const Route = createFileRoute("/llms.txt")({ + server: { + handlers: { + GET: () => { + const folder = currentFolder(); + return new Response( + [ + "# Effetch", + "", + "> Typed HTTP calls for Effect, without the boilerplate. You give Effetch a path and a schema. It fills in the path, builds the query, sends the request, checks the status and decodes the response. What you get back is an Effect that's typed end to end, errors included.", + "", + `Each link is a page as Markdown, in the order the docs read. [llms-full.txt](${SITE_URL}/llms-full.txt) has every page in one file. They cover the newest release of \`@monarcode/effetch\`.`, + "", + ...(folder.index ? [docsLlms.indexNode(folder.index)] : []), + ...folder.children.map((node) => docsLlms.indexNode(node)), + ].join("\n"), + { headers: { "Content-Type": "text/plain; charset=utf-8" } }, + ); + }, + }, + }, +}); diff --git a/site/tsconfig.json b/site/tsconfig.json index bb61d10..31ed5d9 100644 --- a/site/tsconfig.json +++ b/site/tsconfig.json @@ -1,6 +1,6 @@ { "include": ["**/*.ts", "**/*.tsx"], - "exclude": ["node_modules", "dist", ".tanstack"], + "exclude": ["node_modules", "dist", ".tanstack", "versions"], "compilerOptions": { "strict": true, "jsx": "react-jsx", diff --git a/site/vite.config.ts b/site/vite.config.ts index f00c023..b2f0b85 100644 --- a/site/vite.config.ts +++ b/site/vite.config.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import { glob } from "node:fs/promises"; import tailwindcss from "@tailwindcss/vite"; @@ -9,13 +10,19 @@ import { defineConfig } from "vite"; import { mdxOptions } from "./src/lib/mdx-options.ts"; -// Every docs page, so the prerender doesn't depend on the sidebar linking to -// each one. +// Every docs page, including older lines, which only the version dropdown +// links to, so the crawler wouldn't find them. const docsPages: { path: string }[] = []; for await (const entry of glob("**/*.mdx", { cwd: "content/docs" })) docsPages.push({ path: ["/docs", ...getSlugs(entry)].join("/") }); +// The package's version, which names the current docs in the version dropdown. +const { version } = JSON.parse( + readFileSync(new URL("../package.json", import.meta.url), "utf8"), +) as { version: string }; + export default defineConfig(({ command }) => ({ + define: { __PACKAGE_VERSION__: JSON.stringify(version) }, plugins: [ // The pages' MDX options run here, in the build, never in the browser. fumadocsMdx({ @@ -29,6 +36,8 @@ export default defineConfig(({ command }) => ({ pages: [ ...docsPages, { path: "/api/search" }, + { path: "/llms.txt" }, + { path: "/llms-full.txt" }, // Written to `404.html` at the output's root. { path: "/404", prerender: { autoSubfolderIndex: false } }, ],