UNPKG

fumadocs-core

Version:

The React.js library for building a documentation website

987 lines (986 loc) • 32 kB
import { a as normalize, i as joinPath, n as dirname, r as extname, t as basename } from "./path-B8old5-F.js"; import { r as normalizeUrl } from "./url-BF81yL4m.js"; import { slugsPlugin } from "./source/plugins/slugs.js"; import { t as iconPlugin } from "./icon-CDrAUvm5.js"; import { l as visit } from "./utils-D63kPQ77.js"; import { t as isEqualShallow } from "./is-equal-BuZW92e4.js"; import { cache } from "react"; // src/source/storage/file-system.ts /** * In memory file system. */ var FileSystem = class { constructor(inherit) { this.folders = /* @__PURE__ */ new Map(); this.files = new Map(inherit?.files); if (inherit) for (const [k, v] of inherit.folders) this.folders.set(k, [...v]); else this.folders.set("", []); } read(path) { return this.files.get(path); } /** * get the direct children of folder (in virtual file path) */ readDir(path) { return this.folders.get(path); } write(path, file) { if (!this.files.has(path)) { const dir = dirname(path); this.makeDir(dir); this.readDir(dir)?.push(path); } this.files.set(path, file); } /** * Delete files at specified path. * * @param path - the target path. * @param [recursive=false] - if set to `true`, it will also delete directories. */ delete(path, recursive = false) { if (this.files.delete(path)) return true; if (recursive) { const folder = this.folders.get(path); if (!folder) return false; this.folders.delete(path); for (const child of folder) this.delete(child); return true; } return false; } getFiles() { return Array.from(this.files.keys()); } makeDir(path) { if (this.folders.has(path)) return; const cur = []; let parentPath = ""; for (const seg of path.split("/")) { cur.push(seg); const curPath = cur.join("/"); if (!this.folders.has(curPath)) { this.folders.set(curPath, []); this.folders.get(parentPath).push(curPath); } parentPath = curPath; } } }; // src/source/source.ts /** * @deprecated you can directly pass a record of source objects to `loader()`. */ function multiple(sources) { const out = {}; for (const k in sources) out[k] = { ...sources[k], files: sources[k].files.map((file) => ({ ...file, data: { ...file.data, type: k } })) }; return out; } /** * update a **static** source object in-place. */ function update(source) { return { files(fn) { source.files = fn(source.files); return this; }, page(fn) { for (let i = 0; i < source.files.length; i++) { const file = source.files[i]; if (file.type === "page") source.files[i] = fn(file); } return this; }, meta(fn) { for (let i = 0; i < source.files.length; i++) { const file = source.files[i]; if (file.type === "meta") source.files[i] = fn(file); } return this; }, build() { return source; } }; } function isStaticSource(s) { return "files" in s && Array.isArray(s.files); } function isDynamicSource(s) { return "files" in s && typeof s.files === "function"; } // src/source/static-params.ts const segmentRegex = /^\[([^\]/]+)\]/; /** the names of the params in a path, like `framework` in `[framework]/docs` */ function segmentNames(path) { const names = []; for (const seg of path.split("/")) { const match = segmentRegex.exec(seg); if (match) names.push(match[1]); } return names; } /** whether a path has dynamic segments, like `[framework]/deploy.mdx` */ function isDynamicPath(path) { return path.includes("[") && path.split("/").some((seg) => segmentRegex.test(seg)); } /** * The params of each page that a file of a dynamic path makes, like `[framework]/deploy.mdx`: its own * `staticParams`, combined with those of the meta files in its folders by the names they share. `undefined` when the * path isn't dynamic or nothing lists them, the file is then a page at its literal path. * * The meta files of a language come first, like `meta.cn.json` for `deploy.cn.mdx`. * * @param file - the path of the file, relative to the content directory */ function getStaticParams(file, { staticParams, readStaticParams }) { if (!file.includes("[")) return; const names = segmentNames(file); if (names.length === 0) return; const segments = file.split("/"); const parts = segments.pop().split("."); const metaNames = parts.length > 2 ? [`meta.${parts.at(-2)}`, "meta"] : ["meta"]; let combinations = [{}]; let listed = false; const join = (list) => { if (!list?.some((entry) => names.some((name) => Object.hasOwn(entry, name)))) return; listed = true; const next = []; for (const combination of combinations) for (const entry of list) { let agrees = true; for (const k in entry) if (Object.hasOwn(combination, k) && combination[k] !== entry[k]) { agrees = false; break; } if (agrees) next.push({ ...combination, ...entry }); } combinations = next; }; const readFolder = (folder) => { for (const name of metaNames) { const list = readStaticParams(folder ? `${folder}/${name}` : name); if (list) return join(list); } }; let folder = ""; readFolder(folder); for (const seg of segments) readFolder(folder = folder ? `${folder}/${seg}` : seg); join(staticParams); if (!listed) return; const out = /* @__PURE__ */ new Map(); for (const combination of combinations) { const entries = []; for (const name of names) { if (!Object.hasOwn(combination, name)) throw new Error(`No value of "[${name}]" is listed for "${file}"`); entries.push([name, combination[name]]); } const params = Object.fromEntries(entries); out.set(JSON.stringify(params), params); } return [...out.values()]; } /** @internal */ function fillParams(file, params) { let out = ""; for (const seg of file.split("/")) { const match = segmentRegex.exec(seg); const value = match && Object.hasOwn(params, match[1]) ? params[match[1]] + seg.slice(match[0].length) : seg; out = out ? `${out}/${value}` : value; } return out; } // src/source/storage/content.ts const EmptyLang = Symbol(); /** * convert input files into virtual file system. * * in the storage, locale codes are removed from file paths, hence the same file will have same file paths in every storage. */ function createContentStorageBuilder(loaderConfig) { const { input, plugins, i18n } = loaderConfig; let parser = (path) => [path]; if (i18n && i18n.parser !== "none") { const langSet = new Set(i18n.languages); parser = (path) => { let locale; let rest; if (i18n.parser === "dir") { const slash = path.indexOf("/"); if (slash <= 0) return [path]; locale = path.slice(0, slash); rest = path.slice(slash + 1); } else { const ext = path.lastIndexOf("."); const dot = path.lastIndexOf(".", ext - 1); if (dot === -1 || dot < path.lastIndexOf("/")) return [path]; locale = path.slice(dot + 1, ext); rest = path.slice(0, dot) + path.slice(ext); } if (locale === "$" || langSet.has(locale)) return [rest, locale]; return [path]; }; } const fileMap = /* @__PURE__ */ new Map(); function add(storageKey, locale, file) { const entry = [storageKey, file]; if (i18n && locale === "$") for (const item of i18n.languages) pushMapList(fileMap, item, entry); else pushMapList(fileMap, locale, entry); } /** the meta files of dynamic folders that give their data at the params of each folder */ const metaDataAt = /* @__PURE__ */ new Map(); function scan(type, source) { const staticParams = /* @__PURE__ */ new Map(); const readStaticParams = (path) => staticParams.get(path); for (const inputFile of source.files) { if (inputFile.type !== "meta") continue; const path = normalize(source.baseDir ? `${source.baseDir}/${inputFile.path}` : inputFile.path); staticParams.set(path.slice(0, path.length - extname(path).length), inputFile.data.staticParams); } for (const inputFile of source.files) { let file; const path = normalize(source.baseDir ? `${source.baseDir}/${inputFile.path}` : inputFile.path); let files; if (inputFile.type === "page") { file = { format: "page", type, path, slugs: inputFile.slugs, data: inputFile.data, absolutePath: inputFile.absolutePath, dataAt: inputFile.dataAt }; const page = file; files = getStaticParams(path, { staticParams: inputFile.data.staticParams, readStaticParams })?.map((params) => ({ ...page, params, data: inputFile.dataAt?.(params) ?? page.data })); } else { file = { format: "meta", type, path, absolutePath: inputFile.absolutePath, data: inputFile.data }; if (inputFile.dataAt) metaDataAt.set(file, inputFile.dataAt); } const [key, locale = i18n ? i18n.defaultLanguage : EmptyLang] = i18n && inputFile.locale ? [inputFile.path, inputFile.locale] : parser(normalize(inputFile.path)); const storageKey = normalize(source.baseDir ? `${source.baseDir}/${key}` : key); if (files) for (const item of files) add(storageKey, locale, item); else add(storageKey, locale, file); } } if (isStaticSource(input)) scan(void 0, input); else for (const k in input) scan(k, input[k]); const folders = /* @__PURE__ */ new Map(); for (const list of fileMap.values()) for (const [path, file] of list) { if (file.format !== "page" || !file.params) continue; for (let folder = dirname(path); isDynamicPath(folder); folder = dirname(folder)) { let filled = folders.get(folder); if (!filled) folders.set(folder, filled = /* @__PURE__ */ new Map()); const target = fillParams(folder, file.params); if (filled.has(target)) continue; const params = {}; for (const name of segmentNames(folder)) params[name] = file.params[name]; filled.set(target, params); } } for (const [locale, list] of fileMap) { if (folders.size === 0 && !list.some(([path]) => isDynamicPath(path))) continue; fileMap.set(locale, route(list, folders, metaDataAt)); } function makeStorage(locale, inherit) { const storage = new FileSystem(inherit); for (const [storageKey, file] of fileMap.get(locale) ?? []) storage.write(storageKey, file); const context = { storage }; for (const plugin of plugins) plugin.transformStorage?.(context); return storage; } return { i18n() { const storages = {}; if (!i18n) return storages; const fallbackLang = i18n.fallbackLanguage !== null ? i18n.fallbackLanguage ?? i18n.defaultLanguage : null; function scan(lang) { if (storages[lang]) return storages[lang]; return storages[lang] = makeStorage(lang, fallbackLang && fallbackLang !== lang ? scan(fallbackLang) : void 0); } for (const lang of i18n.languages) scan(lang); return storages; }, single() { return makeStorage(EmptyLang); } }; } function pushMapList(map, k, v) { let list = map.get(k); if (!list) { list = []; map.set(k, list); } list.push(v); } /** * Route the files of dynamic paths: a page goes to the path its `params` fill, the meta file of a dynamic folder to * each folder that pages fill. Files at a static path win. */ function route(list, folders, metaDataAt) { const out = /* @__PURE__ */ new Map(); for (const [path, file] of list) if (!isDynamicPath(path)) out.set(path, file); /** the path of a page or meta file -> its dynamic file */ const made = /* @__PURE__ */ new Map(); for (const [path, file] of list) { if (!isDynamicPath(path)) continue; const targets = []; if (file.format === "page" && file.params) targets.push([fillParams(path, file.params), file]); if (file.format === "meta") { const dataAt = metaDataAt.get(file); for (const [folder, params] of folders.get(dirname(path)) ?? []) targets.push([`${folder}/${basename(path)}`, dataAt ? { ...file, data: dataAt(params) } : file]); } if (targets.length === 0) out.set(path, file); for (const [target, item] of targets) { const other = made.get(target); if (other) throw new Error(`"${other}" and "${path}" both go to "${target}"`); if (out.has(target)) continue; made.set(target, path); out.set(target, item); } } return [...out]; } // src/source/page-tree/builder.ts const group = /^\((?<name>.+)\)$/; const link = /^(?<external>external:)?(?:\[(?<icon>[^\]]+)])?\[(?<name>[^\]]+)]\((?<url>[^)]+)\)$/; const separator = /^---(?:\[(?<icon>[^\]]+)])?(?<name>.+)---|^---$/; function createPageTreeBuilder(storage, options, locale, storages) { const { idPrefix, transformers = [], sort = {} } = options; const byName = sort.by === "name"; const compare = sort.locales || sort.options ? new Intl.Collator(sort.locales, sort.options).compare : (a, b) => a.localeCompare(b); /** file or folder path -> entry */ const entries = /* @__PURE__ */ new Map(); const entryOf = /* @__PURE__ */ new Map(); const metaPaths = /* @__PURE__ */ new Set(); /** format -> file path without extension -> file path */ const flattenPaths = /* @__PURE__ */ new Map(); let nextId = 0; let usedPages = 0; for (const [path, file] of storage.files) { let paths = flattenPaths.get(file.format); if (!paths) flattenPaths.set(file.format, paths = /* @__PURE__ */ new Map()); paths.set(path.slice(0, path.length - extname(path).length), path); } const builder = { resolveFlattenPath, root }; const ctx = { transformers, builder, storage, storages, locale, custom: options.context, options }; function resolveFlattenPath(name, format) { return flattenPaths.get(format)?.get(name) ?? name; } function createId(localId = `_${nextId++}`) { if (locale) localId = `${locale}:${localId}`; return idPrefix ? `${idPrefix}:${localId}` : localId; } /** * claim a node for `folder`, a node referenced by multiple folders belongs to the highest priority: * `pagesIndex` (3) > path & extract (2) > rest & default index (0), the first one wins a tie. */ function own(folder, entry, priority) { if (!entry.done) return false; const prev = entry.owner; if (prev && prev !== folder) { if (entry.priority >= priority) return false; if (prev.node.index === entry.node) delete prev.node.index; else { const idx = prev.node.children.indexOf(entry.node); if (idx !== -1) prev.node.children.splice(idx, 1); } } entry.owner = folder; entry.priority = Math.max(entry.priority, priority); return true; } function buildFile(path) { const cached = entries.get(path); if (cached) return cached; const file = storage.read(path); if (file?.format !== "page") return; const { title, description, icon } = file.data; let node = { $id: createId(path), type: "page", name: title ?? pathToName(basename(path, extname(path))), description, icon, url: options.url(file.slugs, locale), $ref: path }; for (const t of transformers) if (t.file) node = t.file.call(ctx, node, path); const entry = { node, path, title, priority: 0, done: true }; entries.set(path, entry); entryOf.set(node, entry); usedPages++; return entry; } function buildFolder(path, isGlobalRoot = false) { const cached = entries.get(path); if (cached) return cached; const files = storage.readDir(path); if (!files) return; let metaPath = resolveFlattenPath(joinPath(path, "meta"), "meta"); const metaFile = storage.read(metaPath); let meta = {}; if (metaFile?.format === "meta") { meta = metaFile.data; metaPaths.add(metaPath); } else metaPath = void 0; const node = { type: "folder", name: null, root: meta.root, defaultOpen: meta.defaultOpen, description: meta.description, collapsible: meta.collapsible, children: [], $id: createId(path), $ref: { folder: path, meta: metaPath } }; const self = { node, path, priority: 0, done: false }; entries.set(path, self); const indexName = meta.pagesIndex || (meta.root ?? isGlobalRoot ? void 0 : "index"); const indexPage = indexName && buildFile(resolveFlattenPath(joinPath(path, indexName), "page")); let indexPath; if (indexPage && own(self, indexPage, meta.pagesIndex ? 3 : 0)) { node.index = indexPage.node; indexPath = indexPage.path; } else if (meta.pagesIndex) node.index = resolveLink(meta.pagesIndex); const items = []; const excluded = /* @__PURE__ */ new Set(); for (const item of meta.pages ?? ["..."]) { if (item === "..." || item === "z...a") { items.push(item); continue; } const inline = resolveSeparator(item) ?? resolveLink(item); if (inline) { items.push(inline); continue; } if (item.startsWith("!")) { const target = joinPath(path, item.slice(1)); excluded.add(target).add(resolveFlattenPath(target, "page")); continue; } if (item.startsWith("...")) { const folder = buildFolder(joinPath(path, item.slice(3))); if (!folder) continue; const { index, children } = folder.node; const owned = own(self, folder, 2); if (owned) excluded.add(folder.path); for (const child of index ? [index, ...children] : children) { const entry = entryOf.get(child); if (entry && owned) entry.owner = self; else if (entry && !own(self, entry, 2)) continue; items.push(child); } continue; } const target = joinPath(path, item); const entry = buildFolder(target) ?? buildFile(resolveFlattenPath(target, "page")); if (entry && own(self, entry, 2)) { items.push(entry.node); excluded.add(entry.path); } } if (indexPath) { if (excluded.has(indexPath)) delete node.index; else excluded.add(indexPath); } for (const item of items) { if (item === "..." || item === "z...a") { for (const entry of buildRest(files, excluded, item === "z...a")) if (own(self, entry, 0)) node.children.push(entry.node); continue; } const entry = entryOf.get(item); if (!entry || entry.owner === self) node.children.push(item); } node.icon = meta.icon ?? node.index?.icon; node.name = meta.title ?? node.index?.name; self.title = meta.title ?? (node.index && entryOf.get(node.index)?.title); if (!node.name) { const name = basename(path); node.name = pathToName(group.exec(name)?.[1] ?? name); } let result = node; for (const t of transformers) if (t.folder) result = t.folder.call(ctx, result, path, metaPath); self.node = result; self.done = true; entryOf.set(result, self); return self; } /** build the remaining items of a folder for `...` */ function buildRest(paths, excluded, reversed) { const out = []; let index; for (const path of paths) { if (excluded.has(path)) continue; const file = buildFile(path); if (file && !index && basename(path, extname(path)) === "index") index = file; const entry = file ?? buildFolder(path); if (entry) out.push(entry); } const factor = reversed ? -1 : 1; return out.sort((a, b) => { if (a === index) return -1; if (b === index) return 1; const type = Number(a.node.type === "folder") - Number(b.node.type === "folder"); return factor * (type || compare(byName && a.title || a.path, byName && b.title || b.path)); }); } function resolveLink(item) { const match = link.exec(item)?.groups; if (!match) return; let node = { $id: createId(), type: "page", icon: match.icon, name: match.name, url: match.url, external: match.external ? true : void 0 }; for (const t of transformers) if (t.file) node = t.file.call(ctx, node); return node; } function resolveSeparator(item) { const match = separator.exec(item)?.groups; if (!match) return; let node = { $id: createId(), type: "separator", icon: match.icon, name: match.name }; for (const t of transformers) if (t.separator) node = t.separator.call(ctx, node); return node; } function root(id = "root", path = "") { const folder = buildFolder(path, true)?.node; if (options.noRef) for (const { node } of entries.values()) delete node.$ref; let out = { type: "root", $ref: folder?.$ref, $id: createId(id), name: folder?.name || "Docs", description: folder?.description, children: folder ? folder.children : [] }; for (const t of transformers) if (t.root) out = t.root.call(ctx, out); if ((options.generateFallback ?? true) && usedPages + metaPaths.size < storage.files.size) { const unused = new FileSystem(); for (const [path, file] of storage.files) if (!entries.has(path) && !metaPaths.has(path)) unused.write(path, file); out.fallback = createPageTreeBuilder(unused, { ...options, idPrefix: idPrefix ? `fallback:${idPrefix}` : "fallback", generateFallback: false }, locale, storages).root(); } return out; } return builder; } /** * Get item name from file name * * @param name - file name */ function pathToName(name) { const [first = "", ...rest] = name; return first.toLocaleUpperCase() + rest.join("").replaceAll("-", " "); } // src/source/loader.ts /** decoded, generated slugs are URI encoded but some routers pass them decoded */ function slugsKey(slugs) { const key = slugs.join("/"); if (!key.includes("%")) return key; try { return decodeURI(key); } catch { return key; } } function createPageIndexer({ url }) { /** locale (empty without i18n) -> index */ const indexes = /* @__PURE__ */ new Map(); const binders = /* @__PURE__ */ new WeakMap(); return { scan(storage, lang) { const index = { pages: /* @__PURE__ */ new Map(), pathToPage: /* @__PURE__ */ new Map(), pathToMeta: /* @__PURE__ */ new Map(), urlToPage: /* @__PURE__ */ new Map() }; indexes.set(lang ?? "", index); for (const [path, item] of storage.files) { if (item.format === "meta") { index.pathToMeta.set(path, { type: item.type, path: item.path, absolutePath: item.absolutePath, data: item.data }); continue; } const page = { type: item.type, path: item.path, absolutePath: item.absolutePath, url: url(item.slugs, lang), slugs: item.slugs, data: item.data, params: item.params, locale: lang }; if (item.dataAt) binders.set(page, item.dataAt); index.pathToPage.set(path, page); index.pages.set(slugsKey(page.slugs), page); index.urlToPage.set(page.url, page); } }, getPage(path, lang = "") { return indexes.get(lang)?.pathToPage.get(path); }, getPageByUrl(url, lang = "") { return indexes.get(lang)?.urlToPage.get(url); }, getMeta(path, lang = "") { return indexes.get(lang)?.pathToMeta.get(path); }, getPageBySlugs(slugs, lang = "") { return indexes.get(lang)?.pages.get(slugsKey(slugs)); }, /** the page with props passed to its content, not cached */ withProps(page, props) { const bind = binders.get(page); return bind ? { ...page, data: bind(page.params ?? {}, { props, data: page.data }) } : page; }, /** do not filter by language if `lang` is not specified */ getPages(lang) { const out = []; for (const [key, index] of indexes) { if (lang !== void 0 && key !== lang) continue; for (const page of index.pages.values()) out.push(page); } return out; } }; } function createGetUrl(baseUrl, i18n) { const hideLocale = i18n?.hideLocale ?? "never"; let base = ""; for (const seg of baseUrl.split("/")) if (seg.length > 0) base += `/${seg}`; return (slugs, locale) => { const showLocale = hideLocale === "never" || hideLocale === "default-locale" && locale !== i18n?.defaultLanguage; let url = locale && showLocale ? `/${locale}${base}` : base; for (const slug of slugs) if (slug.length > 0) url += `/${slug}`; return url || "/"; }; } function loader(...args) { const loaderConfig = args.length === 2 ? resolveConfig(args[0], args[1]) : resolveConfig(args[0].source, args[0]); const { i18n } = loaderConfig; const storage = i18n ? createContentStorageBuilder(loaderConfig).i18n() : createContentStorageBuilder(loaderConfig).single(); const indexer = createPageIndexer(loaderConfig); if (storage instanceof FileSystem) indexer.scan(storage); else for (const locale in storage) indexer.scan(storage[locale], locale); let pageTrees; function getPageTrees() { if (pageTrees) return pageTrees; const { plugins, url, pageTree: pageTreeConfig } = loaderConfig; const transformers = []; if (pageTreeConfig?.transformers) transformers.push(...pageTreeConfig.transformers); for (const plugin of plugins) if (plugin.transformPageTree) transformers.push(plugin.transformPageTree); const options = { url, ...pageTreeConfig, transformers }; if (storage instanceof FileSystem) return pageTrees = createPageTreeBuilder(storage, options).root(); const out = {}; for (const locale in storage) out[locale] = createPageTreeBuilder(storage[locale], options, locale, storage).root(); return pageTrees = out; } const out = { _i18n: i18n, get pageTree() { return getPageTrees(); }, set pageTree(v) { pageTrees = v; }, getPageByHref(href, { dir = "", language = i18n?.defaultLanguage } = {}) { const [value, hash] = href.split("#", 2); let target; if (value.startsWith("./") || value.startsWith("../")) { let decoded = value; try { decoded = decodeURI(value); } catch {} const path = joinPath(dir, decoded); target = indexer.getPage(path, language); } else target = indexer.getPageByUrl(value, language); if (target) return { page: target, hash }; }, resolveHref(href, parent) { if (href.startsWith("./") || href.startsWith("../")) { const target = this.getPageByHref(href, { dir: dirname(parent.params ? fillParams(parent.path, parent.params) : parent.path), language: parent.locale }); if (target) return target.hash ? `${target.page.url}#${target.hash}` : target.page.url; } return href; }, getPages(language) { return indexer.getPages(language); }, getLanguages() { const list = []; if (!i18n) return list; for (const language of i18n.languages) list.push({ language, pages: this.getPages(language) }); return list; }, getPage(slugs = [], options) { const { language = i18n?.defaultLanguage, props } = typeof options === "object" ? options : { language: options }; const page = indexer.getPageBySlugs(slugs, language); return page && props ? indexer.withProps(page, props) : page; }, getPageByUrl(url, language) { if (language !== void 0 || !i18n) return indexer.getPageByUrl(url, language); for (const lang of i18n.languages) { const page = indexer.getPageByUrl(url, lang); if (page) return page; } }, getNodeMeta(node, language = i18n?.defaultLanguage) { const ref = node.$ref; if (!ref?.meta) return; return indexer.getMeta(ref.meta, language); }, getNodePage(node, language = i18n?.defaultLanguage) { const ref = node.$ref; if (!ref) return; return indexer.getPage(ref, language); }, getPageTree(locale) { if (i18n) { const trees = getPageTrees(); if (locale && trees[locale]) return trees[locale]; return trees[i18n.defaultLanguage]; } return getPageTrees(); }, generateParams(slug = "slug", lang = "lang") { const params = []; if (!i18n) { for (const page of this.getPages()) params.push({ [slug]: page.slugs }); return params; } for (const entry of this.getLanguages()) for (const page of entry.pages) params.push({ [slug]: page.slugs, [lang]: entry.language }); return params; }, async serializePageTree(tree) { const { renderToString } = await import("react-dom/server.edge"); return { $fumadocs_loader: "page-tree", data: visit(tree, (node) => { node = { ...node }; if ("icon" in node && node.icon) node.icon = renderToString(node.icon); if (node.name) node.name = renderToString(node.name); if ("children" in node) node.children = [...node.children]; return node; }) }; } }; if (isStaticSource(loaderConfig.input)) loaderConfig.input.configureStatic?.({ loader: out }); else for (const [k, v] of Object.entries(loaderConfig.input)) v.configureStatic?.({ loader: out, source: k }); return out; } function resolveConfig(input, { slugs, baseSlugs, icon, plugins = [], baseUrl, url, ...base }) { let config = { ...base, url: url ? (...args) => normalizeUrl(url(...args)) : createGetUrl(baseUrl, base.i18n), input, plugins: buildPlugins([ icon && iconPlugin(icon), ...typeof plugins === "function" ? plugins({ typedPlugin: (plugin) => plugin }) : plugins, slugsPlugin({ slugs, baseSlugs }) ]) }; for (const plugin of config.plugins) { const result = plugin.config?.(config); if (result) config = result; } return config; } const priorityMap = { pre: 1, default: 0, post: -1 }; function buildPlugins(plugins, sort = true) { const flatten = []; for (const plugin of plugins) if (Array.isArray(plugin)) flatten.push(...buildPlugins(plugin, false)); else if (plugin) flatten.push(plugin); if (sort) return flatten.sort((a, b) => priorityMap[b.enforce ?? "default"] - priorityMap[a.enforce ?? "default"]); return flatten; } // src/source/dynamic.ts /** content loader API for static & dynamic content sources, with in-memory cache. */ function dynamicLoader(input, options) { let cachedLoader; const memoryCache = /* @__PURE__ */ new Map(); async function resolveSources() { if (isStaticSource(input) || isDynamicSource(input)) return resolveSource(input); const entries = await Promise.all(Object.entries(input).map(async ([k, v]) => [k, await resolveSource(v)])); return Object.fromEntries(entries); } function resolveSource(v) { if (isStaticSource(v)) return v; const mapFiles = (files) => ({ baseDir: v.baseDir, files, configureStatic: v.configureStatic }); if (!v.cache || v.cache === "memory") { const cached = memoryCache.get(v); if (cached && (cached.expires === void 0 || Date.now() < cached.expires)) return cached.value; const value = Promise.resolve(v.files()).then(mapFiles).catch((e) => { if (memoryCache.get(v)?.value === value) memoryCache.delete(v); throw e; }); memoryCache.set(v, { value, expires: v.staleTime !== void 0 ? Date.now() + v.staleTime : void 0 }); return value; } return Promise.resolve(v.files()).then(mapFiles); } const dynamicLoader = { get: cache(async () => { const resolved = await resolveSources(); if (cachedLoader && isEqual(cachedLoader.input, resolved)) return cachedLoader.value; cachedLoader = { input: resolved, value: loader(resolved, options) }; return cachedLoader.value; }), $inferPage: void 0, $inferMeta: void 0, async revalidate(name) { dynamicLoader.invalidate(name); if (name === void 0) await resolveSources(); else if (!isStaticSource(input) && !isDynamicSource(input)) await resolveSource(input[name]); }, invalidate(name) { if (isStaticSource(input)) return; if (name === void 0) { memoryCache.clear(); if (isDynamicSource(input)) input.invalidate?.(); else for (const v of Object.values(input)) if (isDynamicSource(v)) v.invalidate?.(); return; } if (isDynamicSource(input)) return; const s = input[name]; if (!isDynamicSource(s)) return; memoryCache.delete(s); s.invalidate?.(); } }; if (isDynamicSource(input) || isStaticSource(input)) { input.configureDynamic?.({ loader: dynamicLoader }); if (isDynamicSource(input)) input.configure?.(dynamicLoader, {}); } else for (const [k, v] of Object.entries(input)) { v.configureDynamic?.({ loader: dynamicLoader, source: k }); if (isDynamicSource(v)) v.configure?.(dynamicLoader, { source: k }); } return dynamicLoader; } function isEqual(a, b) { if (isStaticSource(a) && isStaticSource(b)) return isEqualShallow(a.files, b.files); if (!isStaticSource(a) && !isStaticSource(b)) return Object.keys(b).every((k) => isEqualShallow(a[k].files, b[k].files)); return false; } export { isDynamicPath as a, FileSystem as c, getStaticParams as i, createGetUrl as n, multiple as o, loader as r, update as s, dynamicLoader as t };