UNPKG

fumadocs-core

Version:

The React.js library for building a documentation website

436 lines (435 loc) • 15.4 kB
import { markdownTable } from "./mdx-plugins/stringifier.js"; import { c as toHtmlTag } from "./code-output-BZYBFRsN.js"; import { isValidElement } from "react"; import { AsyncLocalStorage } from "node:async_hooks"; // src/server.ts const ROOT_STATE = { target: "markdown", pre: false, inline: false, heading: false }; const CLIENT_REFERENCE = Symbol.for("react.client.reference"); const REACT_LAZY = Symbol.for("react.lazy"); const REACT_MEMO = Symbol.for("react.memo"); const REACT_FORWARD_REF = Symbol.for("react.forward_ref"); const NOT_OPTED_IN = Symbol(); const store = new AsyncLocalStorage({ name: "fumadocs:markdown" }); /** * The target that the current component is being rendered into Markdown for, calling it opts the component in. */ function asMarkdown() { const frame = store.getStore(); if (!frame) return false; frame.optedIn = true; return frame.target; } /** * Render a React tree into a Markdown document. */ async function renderToMarkdown(node, { target = "markdown" } = {}) { return collapse(await walk(node, { ...ROOT_STATE, target, inline: target === "search" })).trim(); } /** * Render a page element into Markdown, `undefined` when its component doesn't call `asMarkdown()`. */ async function renderRoute(element) { if (typeof element.type !== "function") return; const result = await optIn(element.type, element.props, "markdown"); if (result !== NOT_OPTED_IN) return renderToMarkdown(result); } /** * The element types of `jsxComponents()`, each stands for a component under its MDX tag: a component kept as JSX is * named after its tag, as function names are minified in production builds and a component can have several tags. */ const tagged = /* @__PURE__ */ new WeakMap(); /** a missing component. Declared for its prototype: React reads it, and a proxy below would answer as a member tag */ function Missing() { return null; } /** * The element types of the tags under `prefix`, read from `target`: the type of a tag has the ones of its member tags, * like `<Tabs.Tab>`. */ function tagTypes(target, components, prefix = "") { return new Proxy(target, { get(target, key, receiver) { if (typeof key !== "string" || key in target) return Reflect.get(target, key, receiver); const type = components?.[key] ?? Missing; if (typeof type === "string") return type; const element = tagTypes(Missing, type, `${prefix}${key}.`); tagged.set(element, { tag: prefix + key, type }); return element; } }); } /** * Resolve the MDX components of a generated Markdown component (`remarkLLMs` with `output: 'function'`): * a missing component is serialized as JSX syntax by `renderToMarkdown`. */ function jsxComponents(components) { return tagTypes({}, components); } /** * Tagged template for Markdown, interpolated values can be strings, React nodes, promises, or arrays of them. * * Use `md\`${children}\`` inside a component to stringify its children before manipulating them, the result is not * trimmed so block-level output keeps its trailing blank line. * * Formatters (Prettier, oxfmt) format `md` templates as Markdown and may move the content onto its own indented lines, * so a leading empty line, the indentation before the closing backtick and the common indentation are removed. */ const md = Object.assign(async function md(strings, ...values) { const parts = dedent(strings); const resolved = await Promise.all(values.map(render)); let out = parts[0]; for (let i = 0; i < resolved.length; i++) out += resolved[i] + parts[i + 1]; return out; }, { linePrefix(prefix) { return async (strings, ...values) => { const text = (await md(strings, ...values)).trim(); return text.length === 0 ? "" : `\n${prefixLines(text, prefix)}\n\n`; }; }, indent(size = 2) { return md.linePrefix(" ".repeat(size)); } }); /** stands in for interpolations while dedenting, so their lines count as content */ const PLACEHOLDER = "\0"; function dedent(strings) { const lines = strings.join(PLACEHOLDER).split("\n"); if (lines.length === 1) return [...strings]; if (lines[0].trim().length === 0) lines.shift(); const last = lines[lines.length - 1]; if (lines.length > 1 && last.length > 0 && last.trim().length === 0) lines.pop(); let indent = Infinity; for (const line of lines) if (line.trim().length > 0) indent = Math.min(indent, /^[ \t]*/.exec(line)[0].length); let out = ""; for (let i = 0; i < lines.length; i++) { if (i > 0) out += "\n"; out += indent === Infinity ? lines[i] : lines[i].slice(Math.min(indent, lines[i].length)); } return out.split(PLACEHOLDER); } /** for the target of the component that renders it */ async function render(node) { const target = store.getStore()?.target ?? "markdown"; return collapse(await walk(node, { ...ROOT_STATE, target })); } /** * Prefix every line, empty lines receive the trimmed prefix (e.g. `>` instead of `> `). */ function prefixLines(text, prefix) { const empty = prefix.trimEnd(); return text.replace(/^.*$/gm, (line) => line.length === 0 ? empty : prefix + line); } function collapse(text) { return text.replace(/\n{3,}/g, "\n\n"); } /** * Render a component in its own frame, `NOT_OPTED_IN` when it never calls `asMarkdown()`. * * A component that throws before opting in (e.g. it needs a context that only exists on its own route) is treated the * same, it has no Markdown form. */ async function optIn(component, props, target) { const frame = { optedIn: false, target }; try { const result = await store.run(frame, () => component(props)); return frame.optedIn ? result : NOT_OPTED_IN; } catch (e) { if (frame.optedIn) throw e; return NOT_OPTED_IN; } } async function walk(node, state) { if (node === null || node === void 0 || typeof node === "boolean") return ""; if (typeof node === "string") return node; if (typeof node === "number" || typeof node === "bigint") return String(node); if (isThenable(node)) return walk(await node, state); if (isValidElement(node)) return element(node.type, node.props, state); if (typeof node === "object" && Symbol.iterator in node) return (await Promise.all(Array.from(node, (child) => walk(child, state)))).join(""); return ""; } async function element(type, props, state, tag) { const entry = tagged.get(type); if (entry) return element(entry.type, props, state, entry.tag); if (typeof type === "string") return host(type, props, state); if (isClientReference(type)) return jsx(tag ?? clientReferenceName(type.$$id), props, state); if (typeof type === "function") return component(type, props, state, tag); if (typeof type === "symbol") return walk(props.children, state); if (typeof type === "object" && type !== null) { const special = type; switch (special.$$typeof) { case REACT_LAZY: return element(await resolveLazy(special), props, state, tag); case REACT_MEMO: return element(special.type, props, state, tag); case REACT_FORWARD_REF: return component(special.render, props, state, tag); } } return ""; } async function component(fn, props, state, tag) { const result = await optIn(fn, props, state.target); if (result === NOT_OPTED_IN) return jsx(tag ?? componentName(fn), props, state); return walk(result, state); } function componentName(fn) { const { displayName, name } = fn; return typeof displayName === "string" && displayName ? displayName : name || "Component"; } async function resolveLazy(type) { for (;;) try { return type._init(type._payload); } catch (e) { if (!isThenable(e)) throw e; await e; } } /** * The export name of a client reference, or a PascalCase name from its file for default exports. */ function clientReferenceName(id) { if (typeof id !== "string") return "Component"; try { id = decodeURIComponent(id); } catch {} const hash = id.lastIndexOf("#"); const exportName = hash === -1 ? "" : id.slice(hash + 1); if (exportName && exportName !== "default") return exportName; const file = (hash === -1 ? id : id.slice(0, hash)).split(/[\\/]/).pop(); let name = ""; for (const part of file.replace(/\.[^.]+$/, "").split(/[^\w$]+/)) if (part) name += part[0].toUpperCase() + part.slice(1); return name || "Component"; } const MAX_ATTRIBUTE_LENGTH = 1024; const PRESENTATIONAL_PROPS = /* @__PURE__ */ new Set([ "children", "className", "style", "tabIndex" ]); /** * Serialize a component without a Markdown form: as JSX syntax, or for search as an HTML tag like search dialogs render. */ async function jsx(name, props, state) { if (state.target === "search") return toHtmlTag(name, props, (await walk(props.children, { ...state, inline: true })).trim()); let open = `<${name}`; for (const key in props) { if (PRESENTATIONAL_PROPS.has(key)) continue; const attr = attribute(key, props[key]); if (attr !== void 0) open += ` ${attr}`; } const children = await walk(props.children, state); if (state.inline) return children.trim().length === 0 ? `${open} />` : `${open}>${children}</${name}>`; const body = children.trim(); if (body.length === 0) return `\n${open} />\n\n`; return `\n${open}>\n${body}\n</${name}>\n\n`; } function attribute(key, value) { if (value === true) return key; if (value === false || value === null || value === void 0) return; if (typeof value === "string") return value.length > MAX_ATTRIBUTE_LENGTH ? void 0 : `${key}=${JSON.stringify(value)}`; if (typeof value === "number" || typeof value === "bigint") return `${key}={${value}}`; if (typeof value === "function" || typeof value === "symbol" || isValidElement(value)) return; try { const json = JSON.stringify(value, (_, v) => isValidElement(v) ? void 0 : v); if (json === void 0 || json.length > MAX_ATTRIBUTE_LENGTH) return; return `${key}={${json}}`; } catch { return; } } const ROW = ""; const CELL = ""; const INLINE_TAGS = /* @__PURE__ */ new Set([ "a", "abbr", "b", "cite", "code", "del", "em", "i", "kbd", "label", "mark", "q", "s", "small", "span", "strong", "sub", "sup", "time", "u" ]); const DROP_TAGS = /* @__PURE__ */ new Set([ "head", "link", "meta", "noscript", "script", "style", "svg", "template", "title" ]); async function host(tag, props, state) { if (DROP_TAGS.has(tag)) return ""; if (state.target === "search" && (tag === "img" || tag === "pre")) return ""; if (state.pre) { if (tag === "br") return "\n"; return walk(props.children, state); } const children = (override) => walk(props.children, { ...state, ...override }); switch (tag) { case "p": { const c = (await children({ inline: true })).trim(); return state.inline ? `${c} ` : `\n${c}\n\n`; } case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": { const c = (await children({ inline: true, heading: true })).trim().replace(/\s*\n\s*/g, " "); return `\n${"#".repeat(Number(tag[1]))} ${c}\n\n`; } case "a": { const href = typeof props.href === "string" ? props.href : void 0; const c = await children({ inline: true }); if (!href || state.target === "search" || state.heading && href.startsWith("#")) return c; const text = c.trim(); return text.length === 0 ? `<${href}>` : `[${text}](${href})`; } case "strong": case "b": return wrap(await children({ inline: true }), "**"); case "em": case "i": return wrap(await children({ inline: true }), "*"); case "del": case "s": return wrap(await children({ inline: true }), "~~"); case "code": case "kbd": { const c = await children({ inline: true }); if (c.includes("\n") && !state.inline) return codeFence(detectLang(props), c); return inlineCode(c); } case "pre": return codeFence(detectLang(props), await children({ pre: true })); case "blockquote": return `\n${prefixLines(collapse(await children({ inline: false })).trim(), "> ")}\n\n`; case "ul": case "ol": { const ordered = tag === "ol"; let index = typeof props.start === "number" ? props.start : 1; return `\n${(await Promise.all(flatten(props.children).map((child) => { if (!isValidElement(child)) return typeof child === "string" ? child.trim() : ""; return walk(child, { ...state, inline: false, list: { ordered, index: index++ } }); }))).join("")}\n`; } case "li": { const marker = state.list?.ordered ? `${state.list.index}. ` : "- "; return `${marker}${prefixLines((await children({ inline: false })).trim().replace(/\n{2,}(?=(?:[-*+] |\d+\. ))/g, "\n"), " ".repeat(marker.length)).slice(marker.length)}\n`; } case "img": { if (typeof props.src !== "string") return ""; const alt = typeof props.alt === "string" ? props.alt : ""; return state.inline ? `![${alt}](${props.src})` : `\n![${alt}](${props.src})\n\n`; } case "hr": return "\n---\n\n"; case "br": return "\n"; case "table": { const rows = []; for (const row of (await children({ inline: false })).split(ROW).slice(1)) rows.push(row.split(CELL).slice(1)); return rows.length === 0 ? "" : `\n${markdownTable(rows)}\n\n`; } case "tr": return `${ROW}${await children({ inline: false })}`; case "th": case "td": return `${CELL}${await children({ inline: true })}`; } if (INLINE_TAGS.has(tag)) return children({ inline: true }); const c = (await children({ inline: false })).trim(); return c.length === 0 ? "" : `\n${c}\n\n`; } function wrap(text, marker) { const [, lead, core, trail] = /^(\s*)([\s\S]*?)(\s*)$/.exec(text); return core ? `${lead}${marker}${core}${marker}${trail}` : text; } function codeFence(lang, code) { const text = code.replace(/\n$/, ""); const fence = "`".repeat(Math.max(3, longestRun(text, "`") + 1)); return `\n${fence}${lang}\n${text}\n${fence}\n\n`; } function inlineCode(text) { const fence = "`".repeat(longestRun(text, "`") + 1); const pad = text.startsWith("`") || text.endsWith("`") ? " " : ""; return `${fence}${pad}${text}${pad}${fence}`; } function longestRun(text, char) { let max = 0; let current = 0; for (const c of text) { current = c === char ? current + 1 : 0; if (current > max) max = current; } return max; } /** from `data-lang` or a `language-*` class name, of the element or its `<code>` child */ function detectLang(props) { const lang = props["data-lang"] ?? props.lang; if (typeof lang === "string" && lang.length > 0) return lang; const fromClass = (className) => typeof className === "string" ? /(?:^|\s)(?:language|lang)-([\w+#.-]+)/.exec(className)?.[1] : void 0; let out = fromClass(props.className); for (const child of flatten(props.children)) { if (out) break; if (isValidElement(child) && child.type === "code") out = fromClass(child.props.className); } return out ?? ""; } /** * Direct children, flattened through arrays and fragments. */ function flatten(node, out = []) { if (node === null || node === void 0 || typeof node === "boolean") return out; if (isValidElement(node)) { if (typeof node.type === "symbol") flatten(node.props.children, out); else out.push(node); } else if (typeof node === "object" && Symbol.iterator in node) for (const child of node) flatten(child, out); else out.push(node); return out; } function isClientReference(type) { return (typeof type === "function" || typeof type === "object" && type !== null) && type.$$typeof === CLIENT_REFERENCE; } function isThenable(value) { return typeof value === "object" && value !== null && typeof value.then === "function"; } export { asMarkdown, jsxComponents, md, renderRoute, renderToMarkdown };