fumadocs-mdx15.6.46.0 kB
import { statSync } from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { compileFunction } from "node:vm";
import { buildSync } from "esbuild";
import { Parser } from "acorn";
import acornJsx from "acorn-jsx";
import { fromMarkdown } from "mdast-util-from-markdown";
import { mdxFromMarkdown } from "mdast-util-mdx";
import { mdxjsEsm } from "micromark-extension-mdxjs-esm";
// ../shared/frontmatter-code.ts
/**
* The frontmatter in code of an ESM block, `export const frontmatter = ...`, as the module of `frontmatter(props = {})`:
* with the imports it reads and the exports before it in the block. `remove` is what to leave out of the content.
*
* @param imports - the imports of the document with their code, they are hoisted
*/
function frontmatterModule(source, block, imports, range) {
let body = "";
const declarations = [];
for (const statement of block) {
const { declaration } = statement;
if (statement.type !== "ExportNamedDeclaration" || !declaration) continue;
body += `${source.slice(...range(declaration))}\n`;
declarations.push(declaration);
const [first, second] = declaration.declarations ?? [];
if (first?.id.type !== "Identifier" || first.id.name !== "frontmatter") continue;
const names = /* @__PURE__ */ new Set();
collectNames(declarations, names);
let code = "";
for (const [item, text] of imports) if (item.specifiers?.some(({ local }) => local.name && names.has(local.name))) code += `${text}\n`;
return {
module: `${code}export const frontmatter = (props = {}) => {\n${body}return frontmatter;\n};`,
remove: second ? [range(first)[0], range(second)[0]] : range(statement)
};
}
}
function collectNames(node, out) {
if (typeof node !== "object" || node === null) return;
if ("type" in node && node.type === "Identifier" && "name" in node) out.add(node.name);
for (const value of Object.values(node)) collectNames(value, out);
}
/**
* The data of a meta file in code, like `meta.ts`, from its exports: the default export, which can be a function of
* the params of its folder, and the `staticParams` as a named export or in its data.
*/
function metaModule({ default: data, staticParams = data?.staticParams }) {
if (typeof data === "function") return {
data: { staticParams },
dataAt: data
};
return { data: {
...data,
staticParams
} };
}
// src/loaders/mdx/code.ts
const esm = mdxjsEsm({
acorn: Parser.extend(acornJsx()),
acornOptions: {
ecmaVersion: "latest",
sourceType: "module"
},
addResult: true
});
/** the last run of each module: its code, the modification times of the files it read, its exports */
const modules = /* @__PURE__ */ new Map();
/**
* Run a module in code synchronously, like a meta file in TypeScript. Every page of a dynamic folder reads its meta
* file, it runs again only when it or a file it reads changes.
*/
function runModule(file, contents, addDependency) {
const cached = modules.get(file);
if (cached?.contents === contents && cached.inputs.every(([input, time]) => mtime(input) === time)) {
for (const [input] of cached.inputs) addDependency(input);
return cached.exports;
}
const { outputFiles, metafile } = buildSync({
stdin: {
contents,
sourcefile: file,
resolveDir: path.dirname(file),
loader: file.endsWith(".mdx") ? "tsx" : "ts"
},
bundle: true,
format: "cjs",
platform: "node",
packages: "external",
write: false,
metafile: true
});
const inputs = [];
for (const input in metafile.inputs) {
if (input.startsWith("<")) continue;
const resolved = path.resolve(input);
addDependency(resolved);
inputs.push([resolved, mtime(resolved)]);
}
const module = { exports: {} };
compileFunction(outputFiles[0].text, [
"module",
"exports",
"require"
], { filename: file })(module, module.exports, createRequire(file));
modules.set(file, {
contents,
inputs,
exports: module.exports
});
return module.exports;
}
function mtime(file) {
return statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? -1;
}
/**
* The frontmatter in the code of a page, `export const frontmatter = {...}`. It runs at build time with the imports it
* reads, the statements before it in its ESM block and the params of a page as `props`, the content no longer has it.
*/
function frontmatterCode(filePath, content) {
if (!filePath.endsWith(".mdx") || !/^export const frontmatter\b/m.test(content)) return;
const tree = fromMarkdown(content, {
extensions: [esm],
mdastExtensions: [mdxFromMarkdown()]
});
const range = (node) => node.range;
const imports = [];
for (const node of tree.children) if (node.type === "mdxjsEsm") {
for (const statement of node.data?.estree?.body ?? []) if (statement.type === "ImportDeclaration") imports.push([statement, content.slice(...range(statement))]);
}
for (const node of tree.children) {
if (node.type !== "mdxjsEsm" || !node.data?.estree) continue;
const frontmatter = frontmatterModule(content, node.data.estree.body, imports, range);
if (!frontmatter) continue;
const [start, end] = frontmatter.remove;
return {
content: content.slice(0, start) + content.slice(start, end).replace(/[^\n]/g, "") + content.slice(end),
/** compile it into a function of the params */
compile(addDependency) {
return runModule(filePath, frontmatter.module, addDependency).frontmatter;
}
};
}
}
/**
* The frontmatter of a page, validated: the YAML with its frontmatter in code. A dynamic file has the frontmatter in
* code of each params in `_frontmatterAt`.
*
* @param listed - whether to run the frontmatter in code of a dynamic file
*/
async function resolveFrontmatter({ code, yaml, staticParams, validate, addDependency, listed = true }) {
if (!code || !staticParams) return await validate(code ? {
...yaml,
...code.compile(addDependency)()
} : yaml);
const frontmatterAt = {};
if (listed) {
const run = code.compile(addDependency);
for (const item of staticParams) frontmatterAt[JSON.stringify(item)] = await validate({
...yaml,
...run(item)
});
}
return {
...yaml,
_frontmatterAt: frontmatterAt
};
}
export { metaModule as i, resolveFrontmatter as n, runModule as r, frontmatterCode as t };
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.