import matter from "gray-matter"; import { assertValidSourceEntries, buildManifest, buildSearchIndex, compileSvelteContent, createDiagnostic, createDocsError, createSourceEntryId, createDocsSearchRuntime, normalizeProviderPath, toLegacyRawEntries, type CompiledContentArtifact, type DocsCollection, type DocsCompatPreset, type DocsConfig, type DocsContentProvider, type DocsManifest, type DocsSearchArtifact, type DocsSearchRuntime, type DocsSourceEntry, } from "@docsfn/core"; import { assertDocsBlogMount } from "./blog"; export interface DocsSiteSource { siteRoot: string; manifest: DocsManifest; searchArtifact: DocsSearchArtifact; siteTitle: string; canonicalUrl?: string; compatPreset: DocsCompatPreset; config: DocsConfig; } export interface DocsSiteCompiledCacheSummary { framework: "svelte"; compatPreset: DocsCompatPreset; pageKeys: string[]; postKeys: string[]; } interface DocsSiteCompiledContentCache { framework: "svelte"; compatPreset: DocsCompatPreset; pages: Map; posts: Map; pageKeysById: Record; postKeysById: Record; } interface DocsSiteServerState { source: DocsSiteSource; compiledCache: DocsSiteCompiledContentCache; } function createCompiledCacheKey(input: { kind: "page" | "post"; id: string; framework: "svelte"; compatPreset: DocsCompatPreset; }): string { return [input.kind, input.id, input.framework, input.compatPreset].join("|"); } function sortById(items: T[]): T[] { return [...items].sort((left, right) => left.id.localeCompare(right.id, "en", { sensitivity: "variant", numeric: true, }), ); } function createCompiledCache(input: { manifest: DocsManifest; compatPreset: DocsCompatPreset; }): DocsSiteCompiledContentCache { const framework = "svelte" as const; const pages = new Map(); const posts = new Map(); const pageKeysById: Record = {}; const postKeysById: Record = {}; for (const page of sortById(Object.values(input.manifest.pages))) { const key = createCompiledCacheKey({ kind: "page", id: page.id, framework, compatPreset: input.compatPreset, }); pageKeysById[page.id] = key; pages.set( key, compileSvelteContent({ source: page.body, sourcePath: page.id, compatPreset: input.compatPreset, }), ); } for (const post of sortById(Object.values(input.manifest.posts))) { const key = createCompiledCacheKey({ kind: "post", id: post.id, framework, compatPreset: input.compatPreset, }); postKeysById[post.id] = key; posts.set( key, compileSvelteContent({ source: post.body, sourcePath: post.id, compatPreset: input.compatPreset, }), ); } return { framework, compatPreset: input.compatPreset, pages, posts, pageKeysById, postKeysById, }; } function getCompiledArtifactOrThrow(input: { kind: "page" | "post"; id: string; cache: DocsSiteCompiledContentCache; }): CompiledContentArtifact { const keysById = input.kind === "page" ? input.cache.pageKeysById : input.cache.postKeysById; const entries = input.kind === "page" ? input.cache.pages : input.cache.posts; const key = keysById[input.id]; if (!key) { throw createDocsError({ code: "DOCS_ARTIFACT_INVALID", message: `compiled ${input.kind} cache key is missing for ${input.id}`, diagnostics: [ createDiagnostic({ code: "DOCS_ARTIFACT_INVALID", message: `compiled ${input.kind} cache key is missing for ${input.id}`, details: { kind: input.kind, id: input.id, }, }), ], }); } const compiled = entries.get(key); if (!compiled) { throw createDocsError({ code: "DOCS_ARTIFACT_INVALID", message: `compiled ${input.kind} artifact is missing for ${input.id}`, diagnostics: [ createDiagnostic({ code: "DOCS_ARTIFACT_INVALID", message: `compiled ${input.kind} artifact is missing for ${input.id}`, details: { kind: input.kind, id: input.id, key, }, }), ], }); } return compiled; } /** One independent cache per site; raw modules are supplied by the site's Vite glob. */ export function createDocsSiteRuntime( docsConfig: DocsConfig, bundledContent: Record, bundledStatic: Record, modulePrefix = "../../../", options: { mountBlogAtDocs?: boolean } = {}, ) { let serverStatePromise: Promise | null = null; async function loadDocsSiteServerState(): Promise { serverStatePromise ??= (async () => { const siteRoot = "."; const config = docsConfig satisfies DocsConfig; const provider = createBundledContentProvider(config); const manifest = await buildManifest(provider, config); if (options.mountBlogAtDocs) assertDocsBlogMount(manifest); const searchArtifact = await buildSearchIndex(manifest, { search: config.search, auth: config.auth, }); const compatPreset = config.compat?.preset ?? "none"; const compiledCache = createCompiledCache({ manifest, compatPreset, }); return { source: { siteRoot, manifest, searchArtifact, siteTitle: config.site.title, canonicalUrl: config.site.canonicalUrl, compatPreset, config, }, compiledCache, }; })().catch((error) => { serverStatePromise = null; throw error; }); return serverStatePromise; } async function loadDocsSiteSource(): Promise { const state = await loadDocsSiteServerState(); return state.source; } async function getCompiledDocsPage( pageId: string, ): Promise { const state = await loadDocsSiteServerState(); return getCompiledArtifactOrThrow({ kind: "page", id: pageId, cache: state.compiledCache, }); } async function getCompiledDocsPost( postId: string, ): Promise { const state = await loadDocsSiteServerState(); return getCompiledArtifactOrThrow({ kind: "post", id: postId, cache: state.compiledCache, }); } async function getDocsSiteCompiledCacheSummary(): Promise { const state = await loadDocsSiteServerState(); return { framework: state.compiledCache.framework, compatPreset: state.compiledCache.compatPreset, pageKeys: [...state.compiledCache.pages.keys()].sort((left, right) => left.localeCompare(right, "en", { sensitivity: "variant", numeric: true, }), ), postKeys: [...state.compiledCache.posts.keys()].sort((left, right) => left.localeCompare(right, "en", { sensitivity: "variant", numeric: true, }), ), }; } async function createDocsSiteSearchRuntime(): Promise { const state = await loadDocsSiteServerState(); return createDocsSearchRuntime({ artifact: state.source.searchArtifact, }); } function createBundledContentProvider( config: DocsConfig, ): DocsContentProvider { const modules = { ...normalizeBundledModules(bundledContent, modulePrefix), ...normalizeBundledModules(bundledStatic, modulePrefix), }; return { providerId: "bundled", async listEntries(input) { const entries = input.collections.flatMap((collection) => collectEntriesForCollection(collection, modules, config), ); return assertValidSourceEntries(entries); }, async loadEntry(input) { return input.entry; }, async list() { const entries = await this.listEntries({ config, collections: ["docs", "pages", "blog", "api", "assets"], }); return toLegacyRawEntries(entries); }, }; } return { loadDocsSiteSource, getCompiledDocsPage, getCompiledDocsPost, getDocsSiteCompiledCacheSummary, createDocsSiteSearchRuntime, }; } function normalizeBundledModules( modules: Record, prefix: string, ): Record { return Object.fromEntries( Object.entries(modules).map(([modulePath, source]) => [ normalizeProviderPath(modulePath.replace(prefix, "")), source, ]), ); } function isMarkdownCollection(collection: DocsCollection): collection is Extract { return ["docs", "pages", "blog"].includes(collection); } function collectEntriesForCollection( collection: DocsCollection, modules: Record, config: DocsConfig, ): DocsSourceEntry[] { const directory = collectionDirectory(collection, config); const entries: DocsSourceEntry[] = []; for (const [modulePath, source] of Object.entries(modules)) { if (modulePath !== directory && !modulePath.startsWith(`${directory}/`)) { continue; } const relativePath = normalizeProviderPath( modulePath.slice(directory.length + 1), ); if (!relativePath || relativePath === ".gitkeep") { continue; } const entry = createEntryForModule(collection, relativePath, source, modulePath, config); if (entry) entries.push(entry); } return entries.sort((left, right) => left.id.localeCompare(right.id, "en", { sensitivity: "variant", numeric: true, }), ); } // POSIX helpers keep the runtime free of Node built-ins on edge targets. function basename(relativePath: string): string { return relativePath.slice(relativePath.lastIndexOf("/") + 1); } function extname(relativePath: string): string { const name = basename(relativePath); const dot = name.lastIndexOf("."); return dot > 0 ? name.slice(dot) : ""; } function createEntryForModule( collection: DocsCollection, relativePath: string, source: string, modulePath: string, config: DocsConfig, ): DocsSourceEntry | undefined { const extension = extname(relativePath).toLowerCase(); const fileName = basename(relativePath).toLowerCase(); if (fileName === (config.content.metaFileName ?? "meta.json").toLowerCase()) { return createControlEntry(collection, relativePath, source, modulePath); } if (collection === "assets") { return createAssetEntry(relativePath, source, modulePath); } if (isMarkdownCollection(collection) && [".md", ".mdx"].includes(extension)) { return createMarkdownEntry(collection, relativePath, source, modulePath); } if (collection === "api" && [".json", ".yaml", ".yml"].includes(extension)) { return createApiEntry(relativePath, source, modulePath); } } function collectionDirectory( collection: DocsCollection, config: DocsConfig, ): string { const directory = collection === "docs" ? config.content.docsDir ?? "content/docs" : collection === "pages" ? config.content.pagesDir ?? "content/pages" : collection === "blog" ? config.content.blogDir ?? "content/blog" : collection === "api" ? config.content.apiDir ?? "content/api" : config.content.assetsDir ?? "static"; // Collection directories are relative to content.root, as in the filesystem provider. const normalizedRoot = normalizeProviderPath(config.content.root ?? "."); let root = normalizedRoot === "." ? "" : normalizedRoot.replace(/^\.\//, ""); while (root.endsWith("/")) root = root.slice(0, -1); return normalizeProviderPath(root ? `${root}/${directory}` : directory); } function createMarkdownEntry( collection: Extract, relativePath: string, source: string, sourcePath: string, ): DocsSourceEntry { const parsed = parseFrontmatter(source); return { id: createSourceEntryId(collection, relativePath), collection, relativePath, absolutePath: sourcePath, entryType: "content", body: parsed.body, frontmatter: { title: deriveTitleFromPath(relativePath), ...parsed.frontmatter, }, bytes: byteLength(source), meta: { extension: extname(relativePath).toLowerCase(), }, }; } function createControlEntry( collection: DocsCollection, relativePath: string, source: string, sourcePath: string, ): DocsSourceEntry { return { id: createSourceEntryId(collection, relativePath), collection, relativePath, absolutePath: sourcePath, entryType: "control", body: source, frontmatter: {}, bytes: byteLength(source), meta: { controlFile: true, parsed: parseJson(source), }, }; } function createApiEntry(relativePath: string, source: string, sourcePath: string): DocsSourceEntry { return { id: createSourceEntryId("api", relativePath), collection: "api", relativePath, absolutePath: sourcePath, entryType: "content", body: source, frontmatter: { title: deriveTitleFromPath(relativePath), }, bytes: byteLength(source), meta: { extension: extname(relativePath).toLowerCase(), }, }; } function createAssetEntry( relativePath: string, source: string, sourcePath: string, ): DocsSourceEntry { return { id: createSourceEntryId("assets", relativePath), collection: "assets", relativePath, absolutePath: sourcePath, entryType: "asset", frontmatter: {}, bytes: byteLength(source), }; } function parseFrontmatter(source: string): { body: string; frontmatter: Record; } { const parsed = matter(source); return { body: parsed.content, frontmatter: parsed.data }; } function parseJson(source: string): unknown { try { return JSON.parse(source); } catch { return null; } } function deriveTitleFromPath(relativePath: string): string { return basename(relativePath) .replace(/\.[^/.]+$/, "") .split(/[-_]/g) .map((segment) => segment.length > 0 ? `${segment.charAt(0).toUpperCase()}${segment.slice(1)}` : segment, ) .join(" "); } function byteLength(source: string): number { return new TextEncoder().encode(source).byteLength; }