fumadocs-core
Version:
The React.js library for building a documentation website
74 lines (73 loc) • 2.62 kB
JavaScript
import { n as dirname, r as extname, t as basename } from "../../path-B8old5-F.js";
// src/source/plugins/slugs.ts
/**
* Generate slugs for pages if missing.
*/
function slugsPlugin(optsOrFn = {}) {
const prepended = /* @__PURE__ */ new WeakSet();
const { baseSlugs = [], slugs: slugFn } = typeof optsOrFn === "function" ? { slugs: optsOrFn } : optsOrFn;
function generateSlugs(path, file) {
const out = slugFn?.(file, () => getSlugs(path)) ?? getSlugs(path);
prepended.add(file);
return baseSlugs.length > 0 ? [...baseSlugs, ...out] : out;
}
return {
name: "fumadocs:slugs",
transformStorage({ storage }) {
const indexFiles = [];
const taken = /* @__PURE__ */ new Map();
for (const [path, file] of storage.files) {
if (file.format !== "page") continue;
if (file.slugs) {
if (baseSlugs.length > 0 && !prepended.has(file)) {
file.slugs = [...baseSlugs, ...file.slugs];
prepended.add(file);
}
continue;
}
if (basename(path, extname(path)) === "index") {
indexFiles.push(path);
continue;
}
file.slugs = generateSlugs(path, file);
const key = file.slugs.join("/");
if (taken.has(key)) throw new Error(`Duplicated slugs "${key}" of ${taken.get(key)} and ${path}`);
taken.set(key, path);
}
for (const path of indexFiles) {
const file = storage.read(path);
if (file?.format !== "page") continue;
file.slugs = generateSlugs(path, file);
if (taken.has(file.slugs.join("/"))) file.slugs = [...file.slugs, "index"];
const key = file.slugs.join("/");
if (taken.has(key)) throw new Error(`Duplicated slugs "${key}" of ${taken.get(key)} and ${path}`);
taken.set(key, path);
}
}
};
}
/**
* Generate slugs from file data (e.g. frontmatter).
*
* @param key - the property name in file data to generate slugs, default to `slug`.
*/
function slugsFromData(key = "slug") {
return (file) => {
const k = key;
if (k in file.data && typeof file.data[k] === "string") return file.data[k].split("/").filter((v) => v.length > 0);
};
}
const GroupRegex = /^\(.+\)$/;
/**
* Convert file path into slugs, also encode non-ASCII characters, so they can work in pathname
*/
function getSlugs(file) {
const dir = dirname(file);
const name = basename(file, extname(file));
const slugs = [];
for (const seg of dir.split("/")) if (seg.length > 0 && !GroupRegex.test(seg)) slugs.push(encodeURI(seg));
if (GroupRegex.test(name)) throw new Error(`Cannot use folder group in file names: ${file}`);
if (name !== "index") slugs.push(encodeURI(name));
return slugs;
}
export { getSlugs, slugsFromData, slugsPlugin };