@ox-content/vite-plugin 3.0.0-alpha.1 → 3.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["importNapiModuleSync","rehypeParse","interopDefault","rehypeParsePlugin","rehypeStringify","rehypeStringifyPlugin","importNapiModule","join","dirname","existsSync","createRequire","importNapiModule","getTabGroupCounter","importNapiModule","path","access","mkdir","writeFile","readFile","escapeHtml","resolveTwitterEmbedOptions","path","importNapiModule","defaultOptions","Buffer","defaultOptions","getAttribute","createFallbackCard","rehypeParse","interopDefault","rehypeParsePlugin","rehypeStringify","rehypeStringifyPlugin","createFallbackCard","defaultOptions","rehypeParse","interopDefault","rehypeParsePlugin","rehypeStringify","rehypeStringifyPlugin","getAttribute","promisify","execFile","importNapiModule","mkdtemp","join","tmpdir","writeFile","rm","importNapiModule","importNapiModule","importNapiModuleSync","readFileSync","path","escapeHtml","fs","interopDefault","rehypeParsePlugin","rehypeStringifyPlugin","resolveLocaleLabel","raw","renderToString","join","mkdir","dirname","writeFile","escapeHtml","MISSING_SITE_URL","hasSiteUrl","fs","path","escapeXml","importNapiModuleSync","importNapiModuleSync","path","normalizePath","fs","path","escapeHtml","path","importNapiModule","path","fs","path","siteHref","escapeHtml","path","siteHref","oxContent","importNapiModule","importNapiModuleSync","path","siteHref","fs","resolveTheme","resolvePageChromeOption","extractTitle","importNapiModuleSync","importNapiModule","themeToNapi","fs","getUrlPath","resolveSiteName","normalizeVitePressFrontmatter","parsePageChromeFlags","fs","renderPage","normalizeVitePressFrontmatter","extractTitle","getUrlPath","parsePageChromeFlags","normalizeVitePressFrontmatter","importNapiModule","#native","#includePendingAst","#completeInline","importNapiModuleSync","#renderPending","importNapiModuleSync","path","normalizePath","fs","spawn","require","createRequire","createEmptyLintResult","path","fs","path"],"sources":["../src/markdown.ts","../src/environment.ts","../src/highlight-native.ts","../src/highlight.ts","../src/plugins/mermaid.ts","../src/plugins/pm.ts","../src/plugins/youtube.ts","../src/plugins/twitter/url.ts","../src/plugins/twitter/fetch.ts","../src/plugins/twitter/render.ts","../src/plugins/twitter/transform.ts","../src/plugins/media.ts","../src/plugins/github/validation.ts","../src/plugins/github/source.ts","../src/plugins/github/types.ts","../src/plugins/github/api.ts","../src/plugins/github/attributes.ts","../src/plugins/github/fallback-card.ts","../src/plugins/github/repo-card.ts","../src/plugins/github/source-card.ts","../src/plugins/github/transform.ts","../src/plugins/github.ts","../src/plugins/ogp.ts","../src/plugins/index.ts","../src/plugins/mermaid-protect.ts","../src/code-blocks.ts","../src/transform.ts","../src/docs.ts","../src/og-image/renderer.ts","../src/og-image/browser.ts","../src/og-image/template.ts","../src/og-image/cache.ts","../src/og-image/index.ts","../src/island/parse.ts","../src/locale-switcher.ts","../src/locale-nav.ts","../src/page-context.ts","../src/theme-renderer.ts","../src/site-maps.ts","../src/publish-state.ts","../src/permalinks.ts","../src/apply-permalinks.ts","../src/redirects.ts","../src/not-found.ts","../src/collections-runtime.ts","../src/collections.ts","../src/feed-format.ts","../src/feeds.ts","../src/taxonomies-html.ts","../src/taxonomies.ts","../src/team.ts","../src/search-provider.ts","../src/search.ts","../src/versions-html.ts","../src/versions.ts","../src/version-navigation.ts","../src/ssg.ts","../src/dev-server.ts","../src/og-viewer.ts","../src/i18n.ts","../src/resolve-image-options.ts","../src/card-options.ts","../src/file-tree-options.ts","../src/include-options.ts","../src/step-options.ts","../src/incremental.ts","../src/framework.ts","../src/docs-tests.ts","../src/lint.ts","../src/lint-files.ts","../src/index.ts"],"sourcesContent":["import * as path from \"path\";\n\nexport const DEFAULT_MARKDOWN_EXTENSIONS = [\".md\", \".markdown\", \".mdx\"] as const;\n\nexport function normalizeMarkdownExtensions(extensions?: readonly string[]): string[] {\n const values = extensions?.length ? extensions : DEFAULT_MARKDOWN_EXTENSIONS;\n const seen = new Set<string>();\n const normalized: string[] = [];\n\n for (const extension of values) {\n const value = extension.startsWith(\".\") ? extension : `.${extension}`;\n const key = value.toLowerCase();\n if (!seen.has(key)) {\n seen.add(key);\n normalized.push(value);\n }\n }\n\n return normalized;\n}\n\nexport function isMarkdownFilePath(\n filePath: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n): boolean {\n const pathname = filePath.split(\"?\")[0].split(\"#\")[0].toLowerCase();\n return extensions.some((extension) => pathname.endsWith(extension.toLowerCase()));\n}\n\n/** Returns true when a resource id points at an MDX source file. */\nexport function isMdxFilePath(filePath: string): boolean {\n const pathname = filePath.split(\"?\")[0].split(\"#\")[0];\n return pathname.toLowerCase().endsWith(\".mdx\");\n}\n\n/** Explicit configuration wins; otherwise MDX follows the source extension. */\nexport function resolveMdxForFilePath(filePath: string, configured?: boolean): boolean {\n return configured ?? isMdxFilePath(filePath);\n}\n\nexport function stripMarkdownExtension(\n filePath: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n): string {\n const match = [...extensions]\n .sort((left, right) => right.length - left.length)\n .find((extension) => filePath.toLowerCase().endsWith(extension.toLowerCase()));\n\n return match ? filePath.slice(0, -match.length) : filePath;\n}\n\nexport function markdownGlobPattern(srcDir: string, extensions: readonly string[]): string {\n const suffixes = extensions.map((extension) => extension.replace(/^\\./, \"\"));\n if (suffixes.length === 1) {\n return path.join(srcDir, `**/*.${suffixes[0]}`);\n }\n return path.join(srcDir, `**/*.{${suffixes.join(\",\")}}`);\n}\n","/**\n * Vite Environment API integration for Ox Content.\n *\n * Creates a dedicated environment for Markdown processing,\n * enabling SSG-style rendering with separate client/server contexts.\n */\n\nimport type { EnvironmentOptions } from \"vite\";\nimport type { ResolvedOptions } from \"./types\";\nimport { isMarkdownFilePath } from \"./markdown\";\n\n/**\n * Creates the Markdown processing environment configuration.\n *\n * This environment is used for:\n * - Server-side rendering of Markdown files\n * - Static site generation\n * - Pre-rendering at build time\n *\n * @example\n * ```ts\n * // In your vite.config.ts\n * export default defineConfig({\n * environments: {\n * markdown: createMarkdownEnvironment({\n * srcDir: 'content',\n * gfm: true,\n * }),\n * },\n * });\n * ```\n */\nexport function createMarkdownEnvironment(options: ResolvedOptions): EnvironmentOptions {\n return {\n // Consumer type for this environment\n consumer: \"server\",\n\n // Build configuration\n build: {\n // Output to a separate directory\n outDir: `${options.outDir}/.markdown`,\n\n // Emit assets for SSG\n emitAssets: true,\n\n // Create manifest for asset tracking\n manifest: true,\n\n // SSR-like externalization\n rollupOptions: {\n external: [\n // Externalize Node.js built-ins\n /^node:/,\n // Externalize native modules\n /\\.node$/,\n ],\n },\n },\n\n // Resolve configuration\n resolve: {\n // Handle Markdown-like files\n extensions: options.extensions,\n\n // Conditions for module resolution\n conditions: [\"markdown\", \"node\", \"import\"],\n\n // Don't dedupe - each environment gets its own modules\n dedupe: [],\n },\n\n // Optimize dependencies\n optimizeDeps: {\n // Include ox-content dependencies\n include: [],\n // Exclude native modules\n exclude: [\"@ox-content/napi\"],\n },\n };\n}\n\n/**\n * Environment-specific module transformer.\n *\n * This is called during the transform phase to process\n * Markdown files within the environment context.\n */\nexport interface EnvironmentTransformContext {\n /**\n * Current environment name.\n */\n environment: string;\n\n /**\n * Whether we're in development mode.\n */\n isDev: boolean;\n\n /**\n * Whether this is a server-side render.\n */\n isSSR: boolean;\n\n /**\n * The resolved Vite config.\n */\n config: unknown;\n}\n\n/**\n * Creates environment-aware transform options.\n */\nexport function createTransformOptions(\n ctx: EnvironmentTransformContext,\n options: ResolvedOptions,\n): ResolvedOptions {\n return {\n ...options,\n // Adjust options based on environment\n highlight: ctx.isSSR ? options.highlight : false,\n ogImage: ctx.isSSR ? options.ogImage : false,\n };\n}\n\n/**\n * Runs pre-render for SSG.\n *\n * This function is called during build to pre-render all Markdown files.\n */\nexport async function prerender(\n files: string[],\n _options: ResolvedOptions,\n): Promise<Map<string, string>> {\n const results = new Map<string, string>();\n\n for (const file of files) {\n // In production, this would use the Ox Content parser\n // For now, we just mark the file as needing processing\n results.set(file, `/* Pre-rendered: ${file} */`);\n }\n\n return results;\n}\n\n/**\n * Environment plugin factory.\n *\n * Creates plugins specific to the Markdown environment.\n */\nexport function createEnvironmentPlugins(options: ResolvedOptions) {\n return [\n {\n name: \"ox-content:markdown-env\",\n\n // Only apply to markdown environment\n applyToEnvironment(name: string) {\n return name === \"markdown\";\n },\n\n // Transform within the environment\n transform(code: string, id: string) {\n if (!isMarkdownFilePath(id, options.extensions)) {\n return null;\n }\n\n // Environment-specific transformation\n return {\n code: `\n // Transformed in markdown environment\n ${code}\n `,\n };\n },\n },\n ];\n}\n","/**\n * The native tree-sitter highlighting path, plus the small hast helpers the\n * per-block walk uses when the document pass cannot read the markup.\n */\n\nimport type { Root, Element } from \"hast\";\n\nimport { importNapiModuleSync } from \"./napi\";\n\n/**\n * Extract text content from a hast node.\n */\nexport function getTextContent(node: Element | Root): string {\n let text = \"\";\n\n if (\"children\" in node) {\n for (const child of node.children) {\n if (child.type === \"text\") {\n text += child.value;\n } else if (child.type === \"element\") {\n text += getTextContent(child);\n }\n }\n }\n\n return text;\n}\n\nexport function normalizeClassName(className: unknown): string[] {\n if (Array.isArray(className)) {\n return className.filter((value): value is string => typeof value === \"string\");\n }\n\n if (typeof className === \"string\" && className) {\n return className.split(/\\s+/).filter(Boolean);\n }\n\n return [];\n}\n\n/**\n * Highlights with the native tree-sitter engine, or `null` when it has no\n * grammar for `lang`.\n *\n * It emits `--octc-shiki-*` markup (the `shiki` prefix is historical) so\n * theme-color packages keep working.\n */\nexport function highlightNatively(code: string, lang: string): string | null {\n try {\n return importNapiModuleSync().highlightCodeBlock(code, lang);\n } catch {\n return null;\n }\n}\n\n/**\n * Highlights every code block in a rendered document in one native call.\n *\n * Returns the rewritten HTML and the languages it declined. Pending languages\n * stay unhighlighted. Returns `null` when the native module is unavailable.\n */\nexport async function highlightDocumentNatively(html: string): Promise<NativeDocument | null> {\n try {\n return await importNapiModuleSync().highlightHtmlCodeBlocksAsync(html);\n } catch {\n return null;\n }\n}\n\n/** A block the native pass left unhighlighted (no grammar). */\nexport interface PendingBlock {\n language: string;\n source: string;\n}\n\n/** What {@link highlightDocumentNatively} produced for a page. */\nexport interface NativeDocument {\n html: string;\n /**\n * Languages of elements the native pass could not read. Non-empty means the\n * page has to be produced by the per-block walk instead.\n */\n skipped: string[];\n /** Well-formed blocks whose language has no native grammar, in order. */\n pending: PendingBlock[];\n}\n","/**\n * Syntax highlighting with the native tree-sitter engine.\n *\n * Markup keeps the historical `<pre class=\"shiki css-variables\">` wrapper and\n * `--octc-shiki-*` custom properties so theme-color packages keep working.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\nimport { interopDefault } from \"./interop\";\nimport {\n getTextContent,\n highlightDocumentNatively,\n highlightNatively,\n normalizeClassName,\n} from \"./highlight-native\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\n/**\n * Per-block walk used when the native document pass cannot read the markup.\n * Unknown languages stay as the original `<pre><code>`.\n */\nfunction rehypeNativeHighlight() {\n return (tree: Root) => {\n const highlightBlockCode = (codeElement: Element): Element | null => {\n let lang = \"text\";\n const originalCodeClasses = normalizeClassName(codeElement.properties?.className);\n\n const langClass = originalCodeClasses.find((value) => value.startsWith(\"language-\"));\n if (langClass) {\n lang = langClass.replace(\"language-\", \"\");\n }\n\n const highlighted = highlightNatively(getTextContent(codeElement), lang);\n if (!highlighted) {\n return null;\n }\n\n try {\n const parsed = unified().use(rehypeParse, { fragment: true }).parse(highlighted);\n\n if (parsed.children[0]?.type === \"element\") {\n const highlightedPre = parsed.children[0];\n highlightedPre.properties ??= {};\n highlightedPre.properties[\"data-language\"] = lang;\n return highlightedPre;\n }\n } catch {\n // If highlighting fails, keep the original\n }\n\n return null;\n };\n\n const highlightInlineCode = (codeElement: Element): Element | null => {\n const originalCodeClasses = normalizeClassName(codeElement.properties?.className);\n\n const langClass = originalCodeClasses.find((value) => value.startsWith(\"language-\"));\n if (!langClass) {\n return null;\n }\n\n const lang = langClass.replace(\"language-\", \"\");\n const highlighted = highlightNatively(getTextContent(codeElement), lang);\n if (!highlighted) {\n return null;\n }\n\n try {\n const parsed = unified().use(rehypeParse, { fragment: true }).parse(highlighted);\n\n if (parsed.children[0]?.type === \"element\") {\n const highlightedPre = parsed.children[0];\n const highlightedCode = highlightedPre.children.find(\n (child): child is Element => child.type === \"element\" && child.tagName === \"code\",\n );\n\n if (highlightedCode) {\n highlightedCode.properties ??= {};\n const highlightedClasses = normalizeClassName(highlightedCode.properties.className);\n highlightedCode.properties.className = [\n ...new Set([...originalCodeClasses, ...highlightedClasses, \"shiki-inline\"]),\n ];\n highlightedCode.properties[\"data-language\"] = lang;\n return highlightedCode;\n }\n }\n } catch {\n // If highlighting fails, keep the original\n }\n\n return null;\n };\n\n const visit = (node: Root | Element) => {\n if (!(\"children\" in node)) {\n return;\n }\n\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\" && child.tagName === \"pre\") {\n const codeElement = child.children.find(\n (c): c is Element => c.type === \"element\" && c.tagName === \"code\",\n );\n\n const alreadyHighlighted = normalizeClassName(child.properties?.className).includes(\n \"shiki\",\n );\n\n if (codeElement && !alreadyHighlighted) {\n const highlightedPre = highlightBlockCode(codeElement);\n if (highlightedPre) {\n node.children[i] = highlightedPre;\n }\n }\n } else if (child.type === \"element\" && child.tagName === \"code\") {\n const highlightedCode = highlightInlineCode(child);\n if (highlightedCode) {\n node.children[i] = highlightedCode;\n }\n } else if (child.type === \"element\") {\n visit(child);\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Apply native tree-sitter highlighting to HTML.\n *\n * Tries the document pass first. If that pass skips unreadable markup, falls\n * back to a native-only per-block walk. Languages with no native grammar stay\n * as the original `<pre><code>`.\n */\nexport async function highlightCode(html: string): Promise<string> {\n const native = await highlightDocumentNatively(html);\n if (native && native.skipped.length === 0) {\n return native.html;\n }\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeNativeHighlight)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n","/**\n * Mermaid Plugin - Native Rust renderer via NAPI\n *\n * Renders mermaid code blocks to SVG using the native Rust renderer\n * via NAPI. Delegates to the NAPI `transformMermaid` function which\n * extracts mermaid code blocks from HTML and renders them using mmdc.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { importNapiModule } from \"../napi\";\n\nexport interface MermaidOptions {\n /**\n * Mermaid theme used by the CLI renderer.\n * @default 'neutral'\n */\n theme?: \"default\" | \"dark\" | \"forest\" | \"neutral\" | \"base\";\n}\n\n/** Cached NAPI bindings */\nlet napiBindings: {\n transformMermaid: (html: string, mmdcPath: string) => { html: string; errors: string[] };\n} | null = null;\n\nlet napiLoadAttempted = false;\n\nasync function loadNapi() {\n if (napiLoadAttempted) return napiBindings;\n napiLoadAttempted = true;\n try {\n const binding = (await importNapiModule()) as unknown as NonNullable<typeof napiBindings>;\n if (typeof binding.transformMermaid !== \"function\") {\n napiBindings = null;\n return null;\n }\n napiBindings = binding;\n return binding;\n } catch {\n napiBindings = null;\n return null;\n }\n}\n\nlet cachedMmdcPath: string | null | undefined;\nlet missingMmdcWarned = false;\n\nfunction resolveMmdcPath(): string | null {\n if (cachedMmdcPath !== undefined) return cachedMmdcPath;\n\n for (const resolver of createMmdcResolvers()) {\n try {\n const entry = resolver.resolve(\"@mermaid-js/mermaid-cli\");\n const cliPath = join(dirname(entry), \"cli.js\");\n if (existsSync(cliPath)) {\n cachedMmdcPath = cliPath;\n return cachedMmdcPath;\n }\n } catch {\n // Try the next resolver.\n }\n }\n\n // Fallback: node_modules/.bin/mmdc relative to cwd\n const binPath = join(process.cwd(), \"node_modules\", \".bin\", \"mmdc\");\n if (existsSync(binPath)) {\n cachedMmdcPath = binPath;\n return cachedMmdcPath;\n }\n\n cachedMmdcPath = null;\n return null;\n}\n\nfunction createMmdcResolvers(): NodeJS.Require[] {\n // Resolve from the consumer first, then from this package. The second lookup\n // matters under pnpm strict linking: docs apps can depend on the plugin\n // without directly depending on mermaid-cli.\n const consumerRequire = createRequire(join(process.cwd(), \"noop.js\"));\n const resolvers = [consumerRequire];\n\n try {\n resolvers.push(createRequire(consumerRequire.resolve(\"@ox-content/vite-plugin\")));\n } catch {\n // If the package is used from source without its package name resolvable,\n // the consumer resolver and bin fallback still cover direct installs.\n }\n\n return resolvers;\n}\n\n/**\n * Transforms mermaid code blocks in HTML to rendered SVG diagrams.\n * Uses the native Rust NAPI transformMermaid function.\n */\nexport async function transformMermaidStatic(\n html: string,\n _options?: MermaidOptions,\n): Promise<string> {\n const napi = await loadNapi();\n if (!napi) {\n return html;\n }\n\n const mmdcPath = resolveMmdcPath();\n if (!mmdcPath) {\n warnMissingMmdcOnce();\n return html;\n }\n\n try {\n const result = napi.transformMermaid(html, mmdcPath);\n for (const error of result.errors) {\n console.warn(\"[ox-content] Mermaid render error:\", error);\n }\n return result.html;\n } catch (err) {\n console.warn(\"[ox-content] Mermaid transform error:\", err);\n return html;\n }\n}\n\nfunction warnMissingMmdcOnce(): void {\n if (missingMmdcWarned) {\n return;\n }\n\n missingMmdcWarned = true;\n console.warn(\"[ox-content] mmdc not found; skipping Mermaid rendering.\");\n}\n\n/**\n * @deprecated No longer used. Mermaid rendering is now done at build time via NAPI.\n */\nexport const mermaidClientScript = \"\";\n","/**\n * Package Manager Tabs Plugin\n *\n * Transforms <pm>npm install …</pm> blocks into a tab group with one tab per\n * package manager (npm/pnpm/yarn/bun). The single npm-style command is converted\n * to each package manager's equivalent natively in Rust (`transformPmEmbeds` in\n * @ox-content/napi), and the result reuses the same `ox-tabs` widget markup as\n * the generic `<tabs>` plugin so styling and keyboard navigation are consistent.\n *\n * Syncing is opt-in (off by default): when enabled, the rendered group carries a\n * `data-ox-tab-group=\"pkg-manager\"` attribute so the client runtime can keep\n * every package-manager group on the page in sync via localStorage.\n *\n * Package-manager groups share the tab-group counter with the `<tabs>` plugin so\n * `data-group` ids (and the CSS produced by `generateTabsCSS`) stay unique.\n */\n\nimport { importNapiModule } from \"../napi\";\nimport { getTabGroupCounter, setTabGroupCounter } from \"./tabs\";\n\n/** Options for {@link transformPm}. */\nexport interface PmOptions {\n /**\n * Enable opt-in synced package-manager tab groups. When `true`, a\n * `data-ox-tab-group=\"pkg-manager\"` attribute is emitted so the client runtime\n * syncs the active package manager across every pm group on the page and\n * persists the choice in localStorage.\n * @default false\n */\n sync?: boolean;\n}\n\n/**\n * Transform `<pm>` package-manager blocks in HTML into install tabs.\n *\n * @param html - Rendered HTML potentially containing `<pm>` blocks.\n * @param options - Package-manager tab options (syncing is opt-in).\n * @returns The rewritten HTML.\n */\nexport async function transformPm(html: string, options?: PmOptions): Promise<string> {\n // Cheap marker check: skip the NAPI call entirely when there's no `<pm>`\n // element. The Rust side guards the same way, but short-circuiting here avoids\n // marshalling the whole document across the boundary.\n if (!/<pm[\\s/>]/i.test(html)) {\n return html;\n }\n\n const mod = await importNapiModule();\n const startGroup = getTabGroupCounter();\n const result = mod.transformPmEmbeds(html, startGroup, {\n sync: options?.sync ?? false,\n });\n setTabGroupCounter(startGroup + result.groupCount);\n return result.html;\n}\n","/**\n * YouTube Plugin - Privacy-enhanced iframe embedding\n *\n * Transforms <YouTube> components into responsive iframe embeds using\n * youtube-nocookie.com for enhanced privacy.\n *\n * The HTML rewrite is performed in Rust (`transformYoutubeEmbeds` in\n * @ox-content/napi), replacing the previous rehype parse/stringify\n * round-trip. This module keeps the public TS surface and a cheap marker\n * check so pages without a `<youtube>` element never cross the NAPI boundary.\n */\n\nimport { importNapiModule } from \"../napi\";\n\nexport interface YouTubeOptions {\n /**\n * Use privacy-enhanced mode (`youtube-nocookie.com`).\n * @default true\n */\n privacyEnhanced?: boolean;\n\n /**\n * Default iframe aspect ratio.\n * @default '16/9'\n */\n aspectRatio?: string;\n\n /**\n * Allow fullscreen playback.\n * @default true\n */\n allowFullscreen?: boolean;\n\n /**\n * Lazy load the iframe.\n * @default true\n */\n lazyLoad?: boolean;\n}\n\n/**\n * Extract YouTube video ID from various URL formats.\n */\nexport function extractVideoId(input: string): string | null {\n // Already a video ID (11 characters, alphanumeric + _ -)\n if (/^[a-zA-Z0-9_-]{11}$/.test(input)) {\n return input;\n }\n\n // Full URL patterns\n const patterns = [\n /(?:youtube\\.com\\/watch\\?v=|youtu\\.be\\/|youtube\\.com\\/embed\\/|youtube\\.com\\/v\\/)([a-zA-Z0-9_-]{11})/,\n /youtube\\.com\\/shorts\\/([a-zA-Z0-9_-]{11})/,\n ];\n\n for (const pattern of patterns) {\n const match = input.match(pattern);\n if (match) return match[1];\n }\n\n return null;\n}\n\n/**\n * Transform YouTube components in HTML.\n */\nexport async function transformYouTube(html: string, options?: YouTubeOptions): Promise<string> {\n // Cheap marker check: skip the NAPI call entirely when there's no\n // `<youtube>` element (the common case). The Rust side guards the same way,\n // but short-circuiting here avoids marshalling the whole document across\n // the boundary.\n if (!/<youtube/i.test(html)) {\n return html;\n }\n\n const mod = await importNapiModule();\n return mod.transformYoutubeEmbeds(html, options);\n}\n","import type { TweetReference } from \"./types\";\n\nconst STATUS_PATH = /^\\/(?:[^/]+|i\\/web)\\/status\\/(\\d+)(?:\\/.*)?$/;\n\nexport function createSyndicationToken(id: string): string {\n return ((Number(id) / 1e15) * Math.PI).toString(36).replaceAll(/(0+|\\.)/g, \"\");\n}\n\nexport function parseTweetReference(value: string): TweetReference | null {\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) {\n return { id: trimmed, url: `https://x.com/i/web/status/${trimmed}` };\n }\n\n try {\n const url = new URL(trimmed);\n const hostname = url.hostname.toLowerCase().replace(/^(?:www\\.|mobile\\.)/, \"\");\n if (url.protocol !== \"https:\" || (hostname !== \"x.com\" && hostname !== \"twitter.com\")) {\n return null;\n }\n\n const match = url.pathname.match(STATUS_PATH);\n if (!match) return null;\n const screenName = url.pathname.startsWith(\"/i/web/status/\")\n ? \"i/web\"\n : url.pathname.split(\"/\")[1];\n return {\n id: match[1],\n url: `https://x.com/${screenName}/status/${match[1]}`,\n };\n } catch {\n return null;\n }\n}\n\nexport function referenceFromAttributes(attributes: string): TweetReference | null {\n const values = new Map<string, string>();\n const pattern = /\\b(url|href|id)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi;\n for (const match of attributes.matchAll(pattern)) {\n values.set(match[1].toLowerCase(), match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n return parseTweetReference(values.get(\"url\") ?? values.get(\"href\") ?? values.get(\"id\") ?? \"\");\n}\n","import { access, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createSyndicationToken } from \"./url\";\nimport type { ResolvedTwitterEmbedOptions, TweetAssets, TweetData, TweetMedia } from \"./types\";\n\nconst tweetCache = new Map<string, TweetData>();\n\nexport function clearTweetCache(): void {\n tweetCache.clear();\n}\n\nexport async function fetchTweetData(\n id: string,\n options: ResolvedTwitterEmbedOptions,\n): Promise<TweetData | null> {\n const key = `${id}-${sanitizeSegment(options.lang)}`;\n if (options.cache) {\n const memory = tweetCache.get(key);\n if (memory) return memory;\n const disk = await readCachedTweet(key, options.cacheDir);\n if (disk) {\n tweetCache.set(key, disk);\n return disk;\n }\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), options.timeout);\n const endpoint = new URL(\"https://cdn.syndication.twimg.com/tweet-result\");\n endpoint.searchParams.set(\"id\", id);\n endpoint.searchParams.set(\"lang\", options.lang);\n endpoint.searchParams.set(\"token\", createSyndicationToken(id));\n\n try {\n const response = await fetch(endpoint, {\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n });\n if (!response.ok) return null;\n const data: unknown = await response.json();\n if (!isTweetData(data)) return null;\n if (options.cache) {\n tweetCache.set(key, data);\n await writeCachedTweet(key, data, options.cacheDir);\n }\n return data;\n } catch {\n return null;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport async function materializeTweetAssets(\n id: string,\n data: TweetData,\n options: ResolvedTwitterEmbedOptions,\n): Promise<TweetAssets> {\n const assets: TweetAssets = { media: [] };\n const avatarUrl = data.user.profile_image_url_https?.replace(/_normal(?=\\.[^.]+$)/, \"_bigger\");\n if (avatarUrl) {\n assets.avatar = await downloadAsset(avatarUrl, `${id}-avatar`, options);\n }\n\n const media = data.mediaDetails ?? data.entities?.media ?? [];\n for (const [index, item] of media.entries()) {\n if (item.type && item.type !== \"photo\") continue;\n if (!item.media_url_https) continue;\n const src = await downloadAsset(item.media_url_https, `${id}-media-${index + 1}`, options);\n if (src) assets.media.push(assetRecord(src, item));\n }\n return assets;\n}\n\nasync function downloadAsset(\n source: string,\n basename: string,\n options: ResolvedTwitterEmbedOptions,\n): Promise<string | undefined> {\n let url: URL;\n try {\n url = new URL(source);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" || url.hostname.toLowerCase() !== \"pbs.twimg.com\") {\n return undefined;\n }\n\n const extension = extensionFromUrl(url);\n const filename = `${basename}${extension}`;\n const output = path.join(options.mediaOutputDir, filename);\n try {\n await access(output);\n return joinPublicPath(options.mediaPublicPath, filename);\n } catch {\n // Download the missing asset below.\n }\n\n try {\n const response = await fetch(url, { headers: { Accept: \"image/*\" } });\n if (!response.ok) return undefined;\n await mkdir(options.mediaOutputDir, { recursive: true });\n await writeFile(output, new Uint8Array(await response.arrayBuffer()));\n return joinPublicPath(options.mediaPublicPath, filename);\n } catch {\n return undefined;\n }\n}\n\nasync function readCachedTweet(key: string, directory: string): Promise<TweetData | null> {\n try {\n const data: unknown = JSON.parse(await readFile(path.join(directory, `${key}.json`), \"utf8\"));\n return isTweetData(data) ? data : null;\n } catch {\n return null;\n }\n}\n\nasync function writeCachedTweet(key: string, data: TweetData, directory: string): Promise<void> {\n try {\n await mkdir(directory, { recursive: true });\n await writeFile(path.join(directory, `${key}.json`), `${JSON.stringify(data)}\\n`);\n } catch {\n // A read-only cache directory must not fail the build.\n }\n}\n\nfunction isTweetData(data: unknown): data is TweetData {\n if (!data || typeof data !== \"object\") return false;\n const value = data as Partial<TweetData>;\n return (\n typeof value.text === \"string\" &&\n Boolean(value.user) &&\n typeof value.user?.name === \"string\" &&\n typeof value.user.screen_name === \"string\"\n );\n}\n\nfunction extensionFromUrl(url: URL): string {\n const match = url.pathname.match(/\\.(jpe?g|png|webp|gif)$/i);\n return match ? `.${match[1].toLowerCase().replace(\"jpeg\", \"jpg\")}` : \".jpg\";\n}\n\nfunction joinPublicPath(prefix: string, filename: string): string {\n return `${prefix.replace(/\\/$/, \"\")}/${filename}`;\n}\n\nfunction sanitizeSegment(value: string): string {\n return value.replaceAll(/[^a-zA-Z0-9_-]/g, \"-\");\n}\n\nfunction assetRecord(src: string, media: TweetMedia): TweetAssets[\"media\"][number] {\n return {\n src,\n alt: media.ext_alt_text,\n width: media.original_info?.width,\n height: media.original_info?.height,\n };\n}\n","import type { ResolvedTwitterEmbedOptions, TweetAssets, TweetData, TweetEntity } from \"./types\";\n\nexport function renderFetchedTweet(\n permalink: string,\n data: TweetData,\n assets: TweetAssets,\n options: ResolvedTwitterEmbedOptions,\n): string {\n const profile = `https://x.com/${encodeURIComponent(data.user.screen_name)}`;\n const author = escapeHtml(data.user.name);\n const handle = escapeHtml(data.user.screen_name);\n const avatar = assets.avatar\n ? `<img class=\"ox-tweet__avatar\" src=\"${escapeAttribute(assets.avatar)}\" alt=\"\" width=\"48\" height=\"48\" loading=\"lazy\" decoding=\"async\">`\n : \"\";\n const media = renderMedia(assets);\n const footer = renderFooter(permalink, data.created_at, options.lang);\n\n return [\n '<figure class=\"ox-tweet ox-tweet--fetched\">',\n '<header class=\"ox-tweet__header\">',\n `<a class=\"ox-tweet__profile\" href=\"${escapeAttribute(profile)}\" target=\"_blank\" rel=\"noopener noreferrer\">`,\n avatar,\n `<span class=\"ox-tweet__author-name\">${author}</span>`,\n `<span class=\"ox-tweet__author-handle\">@${handle}</span>`,\n \"</a></header>\",\n `<div class=\"ox-tweet__body\">${renderTweetText(data)}</div>`,\n media,\n footer,\n \"</figure>\",\n ].join(\"\");\n}\n\nexport function renderTweetText(data: TweetData): string {\n const [start, end] = data.display_text_range ?? [0, data.text.length];\n const entities = collectEntities(data)\n .filter((entity) => validRange(entity.indices, start, end))\n .sort((left, right) => left.indices![0] - right.indices![0]);\n\n let cursor = start;\n let output = \"\";\n for (const entity of entities) {\n const [entityStart, entityEnd] = entity.indices!;\n if (entityStart < cursor) continue;\n output += escapeText(data.text.slice(cursor, entityStart));\n if (entity.kind === \"url\") {\n const href = entity.expanded_url ?? entity.url;\n const label = entity.display_url ?? href;\n output += `<a href=\"${escapeAttribute(href)}\" target=\"_blank\" rel=\"noopener noreferrer\">${escapeHtml(label)}</a>`;\n }\n cursor = entityEnd;\n }\n output += escapeText(data.text.slice(cursor, end));\n return output.trim();\n}\n\nfunction collectEntities(data: TweetData): Array<TweetEntity & { kind: \"url\" | \"media\" }> {\n return [\n ...(data.entities?.urls ?? []).map((entity) => ({ ...entity, kind: \"url\" as const })),\n ...(data.entities?.media ?? []).map((entity) => ({ ...entity, kind: \"media\" as const })),\n ];\n}\n\nfunction validRange(\n indices: [number, number] | undefined,\n start: number,\n end: number,\n): indices is [number, number] {\n return Boolean(indices && indices[0] >= start && indices[1] <= end && indices[0] < indices[1]);\n}\n\nfunction renderMedia(assets: TweetAssets): string {\n if (assets.media.length === 0) return \"\";\n const images = assets.media\n .map((item) => {\n const size = [\n item.width ? ` width=\"${item.width}\"` : \"\",\n item.height ? ` height=\"${item.height}\"` : \"\",\n ].join(\"\");\n return `<img class=\"ox-tweet__media-item\" src=\"${escapeAttribute(item.src)}\" alt=\"${escapeAttribute(item.alt ?? \"\")}\"${size} loading=\"lazy\" decoding=\"async\">`;\n })\n .join(\"\");\n return `<div class=\"ox-tweet__media\" data-count=\"${assets.media.length}\">${images}</div>`;\n}\n\nfunction renderFooter(permalink: string, createdAt: string | undefined, lang: string): string {\n if (!createdAt) {\n return `<footer class=\"ox-tweet__footer\"><a class=\"ox-tweet__permalink\" href=\"${escapeAttribute(permalink)}\" target=\"_blank\" rel=\"noopener noreferrer\">View on X</a></footer>`;\n }\n const date = new Date(createdAt);\n if (Number.isNaN(date.valueOf())) return renderFooter(permalink, undefined, lang);\n const iso = date.toISOString();\n let label: string;\n try {\n label = new Intl.DateTimeFormat(lang, { dateStyle: \"medium\", timeZone: \"UTC\" }).format(date);\n } catch {\n label = new Intl.DateTimeFormat(\"en\", { dateStyle: \"medium\", timeZone: \"UTC\" }).format(date);\n }\n return `<footer class=\"ox-tweet__footer\"><a class=\"ox-tweet__permalink\" href=\"${escapeAttribute(permalink)}\" target=\"_blank\" rel=\"noopener noreferrer\"><time datetime=\"${iso}\">${escapeHtml(label)}</time></a></footer>`;\n}\n\nfunction escapeText(value: string): string {\n return escapeHtml(value).replaceAll(\"\\n\", \"<br>\");\n}\n\nfunction escapeAttribute(value: string): string {\n return escapeHtml(value).replaceAll(\"`\", \"&#96;\");\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n","import path from \"node:path\";\nimport { fetchTweetData, materializeTweetAssets } from \"./fetch\";\nimport { renderFetchedTweet } from \"./render\";\nimport type { ResolvedTwitterEmbedOptions, TwitterEmbedOptions } from \"./types\";\nimport { referenceFromAttributes } from \"./url\";\n\nconst TWEET_ELEMENT = /<(tweet|xpost)\\b([^>]*?)(?:\\/\\s*>|>[\\s\\S]*?<\\/\\1\\s*>)/gi;\n\nexport function resolveTwitterEmbedOptions(\n options: TwitterEmbedOptions,\n): ResolvedTwitterEmbedOptions {\n return {\n fetch: options.fetch ?? false,\n lang: options.lang ?? \"en\",\n timeout: options.timeout ?? 10000,\n cache: options.cache ?? true,\n cacheDir: path.resolve(options.cacheDir ?? \".cache/ox-content/twitter\"),\n mediaOutputDir: path.resolve(options.mediaOutputDir ?? \"public/ox-content/twitter\"),\n mediaPublicPath: options.mediaPublicPath ?? \"/ox-content/twitter\",\n };\n}\n\nexport async function transformFetchedTweets(\n html: string,\n options: TwitterEmbedOptions,\n): Promise<string> {\n const resolved = resolveTwitterEmbedOptions(options);\n if (!resolved.fetch) return html;\n\n let output = \"\";\n let cursor = 0;\n for (const match of html.matchAll(TWEET_ELEMENT)) {\n const index = match.index ?? 0;\n output += html.slice(cursor, index);\n const reference = referenceFromAttributes(match[2]);\n if (!reference) {\n output += match[0];\n cursor = index + match[0].length;\n continue;\n }\n\n const data = await fetchTweetData(reference.id, resolved);\n if (!data) {\n output += match[0];\n cursor = index + match[0].length;\n continue;\n }\n\n const assets = await materializeTweetAssets(reference.id, data, resolved);\n output += renderFetchedTweet(reference.url, data, assets, resolved);\n cursor = index + match[0].length;\n }\n return output + html.slice(cursor);\n}\n","import { importNapiModule } from \"../napi\";\nimport { transformFetchedTweets } from \"./twitter\";\nimport type { TwitterEmbedOptions } from \"./twitter\";\n\nexport interface MediaEmbedOptions {\n /**\n * Render `<Spotify>` embeds.\n * @default false\n */\n spotify?: boolean;\n\n /**\n * Render `<StackBlitz>` embeds.\n * @default false\n */\n stackBlitz?: boolean;\n\n /**\n * Render `<Tweet>` / `<XPost>` static cards. Pass `{ fetch: true }` to\n * resolve the post content and self-host its media at build time.\n * @default false\n */\n twitter?: boolean | TwitterEmbedOptions;\n\n /**\n * Render `<Bluesky>` static cards.\n * @default false\n */\n bluesky?: boolean;\n\n /**\n * Render `<WebContainer>` lazy placeholder blocks.\n * @default false\n */\n webContainer?: boolean;\n}\n\nexport async function transformMediaEmbeds(\n html: string,\n options: MediaEmbedOptions,\n): Promise<string> {\n if (!hasEnabledMediaEmbed(options) || !hasMediaMarker(html)) {\n return html;\n }\n\n let result = html;\n if (typeof options.twitter === \"object\") {\n result = await transformFetchedTweets(result, options.twitter);\n }\n if (!hasMediaMarker(result)) return result;\n\n const mod = await importNapiModule();\n return mod.transformMediaEmbeds(result, {\n spotify: options.spotify,\n stackBlitz: options.stackBlitz,\n twitter: Boolean(options.twitter),\n bluesky: options.bluesky,\n webContainer: options.webContainer,\n });\n}\n\nfunction hasEnabledMediaEmbed(options: MediaEmbedOptions): boolean {\n return Boolean(\n options.spotify ||\n options.stackBlitz ||\n options.twitter ||\n options.bluesky ||\n options.webContainer,\n );\n}\n\nfunction hasMediaMarker(html: string): boolean {\n return /<(spotify|stackblitz|tweet|xpost|bluesky|webcontainer)[\\s/>]/i.test(html);\n}\n","const GITHUB_REPO_RE = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/;\n\nfunction hasControlChar(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || code === 0x7f) {\n return true;\n }\n }\n return false;\n}\n\nexport function isSafeGitHubRepo(repo: string): boolean {\n return (\n GITHUB_REPO_RE.test(repo) && !repo.split(\"/\").some((part) => part === \".\" || part === \"..\")\n );\n}\n\nexport function isSafeGitHubRef(ref: string): boolean {\n return Boolean(ref) && !hasControlChar(ref) && !hasUnsafePathSegment(ref);\n}\n\nexport function isSafeGitHubPath(path: string): boolean {\n return Boolean(path) && !hasControlChar(path) && !hasUnsafePathSegment(path);\n}\n\nfunction hasUnsafePathSegment(value: string): boolean {\n return value\n .split(\"/\")\n .some((part) => !part || part === \".\" || part === \"..\" || part.includes(\"\\\\\"));\n}\n\nexport function encodePath(path: string): string {\n return path.split(\"/\").map(encodeURIComponent).join(\"/\");\n}\n","import type { GitHubLineRange, GitHubSourceRef } from \"./types\";\nimport { encodePath, isSafeGitHubPath, isSafeGitHubRef, isSafeGitHubRepo } from \"./validation\";\n\nconst EXTENSION_LANGUAGE_MAP = new Map<string, string>([\n [\"cjs\", \"javascript\"],\n [\"css\", \"css\"],\n [\"go\", \"go\"],\n [\"html\", \"html\"],\n [\"js\", \"javascript\"],\n [\"json\", \"json\"],\n [\"jsx\", \"jsx\"],\n [\"md\", \"markdown\"],\n [\"mdx\", \"mdx\"],\n [\"mjs\", \"javascript\"],\n [\"py\", \"python\"],\n [\"rb\", \"ruby\"],\n [\"rs\", \"rust\"],\n [\"sh\", \"shell\"],\n [\"svelte\", \"svelte\"],\n [\"toml\", \"toml\"],\n [\"ts\", \"typescript\"],\n [\"tsx\", \"tsx\"],\n [\"vue\", \"vue\"],\n [\"yaml\", \"yaml\"],\n [\"yml\", \"yaml\"],\n]);\n\nexport function sourceKey(source: GitHubSourceRef): string {\n return `${source.repo}@${source.ref}:${source.path}`;\n}\n\nexport function formatLineRange(lines: GitHubLineRange): string {\n return lines.start === lines.end ? `L${lines.start}` : `L${lines.start}-L${lines.end}`;\n}\n\nexport function parseGitHubLineRange(value: string | undefined): GitHubLineRange | undefined {\n if (!value) return undefined;\n const match = value.trim().match(/^#?L?(\\d+)(?:-L?(\\d+))?$/i);\n if (!match) return undefined;\n\n const start = Number.parseInt(match[1], 10);\n const end = match[2] ? Number.parseInt(match[2], 10) : start;\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end < start) {\n return undefined;\n }\n\n return { start, end };\n}\n\nexport function createGitHubPermalink(source: Omit<GitHubSourceRef, \"permalink\">): string {\n const fragment = source.lines ? `#${formatLineRange(source.lines)}` : \"\";\n return `https://github.com/${source.repo}/blob/${encodeURIComponent(source.ref)}/${encodePath(\n source.path,\n )}${fragment}`;\n}\n\nexport function parseGitHubPermalink(value: string): GitHubSourceRef | null {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n\n if (url.protocol !== \"https:\" || url.hostname !== \"github.com\") {\n return null;\n }\n\n let parts: string[];\n try {\n parts = url.pathname\n .split(\"/\")\n .filter(Boolean)\n .map((part) => decodeURIComponent(part));\n } catch {\n return null;\n }\n\n if (parts.length < 5 || parts[2] !== \"blob\") {\n return null;\n }\n\n const repo = `${parts[0]}/${parts[1]}`;\n const ref = parts[3];\n const path = parts.slice(4).join(\"/\");\n if (!isSafeGitHubRepo(repo) || !isSafeGitHubRef(ref) || !isSafeGitHubPath(path)) {\n return null;\n }\n\n const lines = parseGitHubLineRange(url.hash);\n const source = { repo, ref, path, lines };\n return {\n ...source,\n permalink: createGitHubPermalink(source),\n };\n}\n\nexport function inferLanguage(path: string): string | null {\n const fileName = path.split(\"/\").at(-1)?.toLowerCase() ?? \"\";\n if (fileName === \"dockerfile\") return \"dockerfile\";\n if (fileName === \"makefile\") return \"makefile\";\n\n const extension = fileName.includes(\".\") ? fileName.split(\".\").at(-1) : undefined;\n return extension ? (EXTENSION_LANGUAGE_MAP.get(extension) ?? extension) : null;\n}\n","export interface GitHubRepoData {\n name: string;\n full_name: string;\n description: string | null;\n html_url: string;\n stargazers_count: number;\n forks_count: number;\n language: string | null;\n owner: {\n login: string;\n avatar_url: string;\n };\n}\n\nexport interface GitHubLineRange {\n start: number;\n end: number;\n}\n\nexport interface GitHubSourceRef {\n repo: string;\n ref: string;\n path: string;\n permalink: string;\n lines?: GitHubLineRange;\n}\n\nexport interface GitHubSourceData {\n repo: string;\n ref: string;\n path: string;\n permalink: string;\n content: string;\n size: number;\n html_url: string;\n language: string | null;\n}\n\nexport interface GitHubOptions {\n /**\n * GitHub API token used for higher rate limits and private repository access.\n * @default ''\n */\n token?: string;\n\n /**\n * Cache fetched repository and source data in memory for the current process.\n * @default true\n */\n cache?: boolean;\n\n /**\n * Cache TTL in milliseconds.\n * @default 3600000\n */\n cacheTTL?: number;\n\n /**\n * Maximum source file size to inline in bytes.\n * @default 200000\n */\n maxSourceBytes?: number;\n\n /**\n * Maximum source lines to inline when no line range is specified.\n * @default 120\n */\n maxSourceLines?: number;\n}\n\nexport const defaultOptions: Required<GitHubOptions> = {\n token: \"\",\n cache: true,\n cacheTTL: 3600000,\n maxSourceBytes: 200000,\n maxSourceLines: 120,\n};\n","import { Buffer } from \"node:buffer\";\nimport { inferLanguage, sourceKey } from \"./source\";\nimport {\n defaultOptions,\n type GitHubOptions,\n type GitHubRepoData,\n type GitHubSourceData,\n type GitHubSourceRef,\n} from \"./types\";\nimport { encodePath, isSafeGitHubPath, isSafeGitHubRef, isSafeGitHubRepo } from \"./validation\";\n\nconst repoCache = new Map<string, { data: GitHubRepoData; timestamp: number }>();\nconst sourceCache = new Map<string, { data: GitHubSourceData; timestamp: number }>();\n\ninterface GitHubContentApiFile {\n type: string;\n encoding?: string;\n content?: string;\n size?: number;\n html_url?: string;\n}\n\nfunction githubHeaders(options: Required<GitHubOptions>): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: \"application/vnd.github.v3+json\",\n \"User-Agent\": \"ox-content-github-plugin\",\n };\n\n if (options.token) {\n headers.Authorization = `Bearer ${options.token}`;\n }\n\n return headers;\n}\n\n/**\n * Fetch repository data from GitHub API.\n */\nexport async function fetchRepoData(\n repo: string,\n options: Required<GitHubOptions>,\n): Promise<GitHubRepoData | null> {\n if (!isSafeGitHubRepo(repo)) {\n return null;\n }\n\n if (options.cache) {\n const cached = repoCache.get(repo);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const response = await fetch(`https://api.github.com/repos/${repo}`, {\n headers: githubHeaders(options),\n });\n\n if (!response.ok) {\n console.warn(`Failed to fetch GitHub repo ${repo}: ${response.status}`);\n return null;\n }\n\n const data = (await response.json()) as GitHubRepoData;\n if (options.cache) {\n repoCache.set(repo, { data, timestamp: Date.now() });\n }\n\n return data;\n } catch (error) {\n console.warn(`Error fetching GitHub repo ${repo}:`, error);\n return null;\n }\n}\n\n/**\n * Fetch source file data from GitHub API.\n */\nexport async function fetchGitHubSource(\n source: GitHubSourceRef,\n options: Required<GitHubOptions>,\n): Promise<GitHubSourceData | null> {\n if (\n !isSafeGitHubRepo(source.repo) ||\n !isSafeGitHubRef(source.ref) ||\n !isSafeGitHubPath(source.path)\n ) {\n return null;\n }\n\n const key = sourceKey(source);\n if (options.cache) {\n const cached = sourceCache.get(key);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const apiUrl = `https://api.github.com/repos/${source.repo}/contents/${encodePath(\n source.path,\n )}?ref=${encodeURIComponent(source.ref)}`;\n const response = await fetch(apiUrl, { headers: githubHeaders(options) });\n\n if (!response.ok) {\n console.warn(`Failed to fetch GitHub source ${source.permalink}: ${response.status}`);\n return null;\n }\n\n const data = (await response.json()) as GitHubContentApiFile;\n if (\n data.type !== \"file\" ||\n data.encoding !== \"base64\" ||\n !data.content ||\n (data.size ?? 0) > options.maxSourceBytes\n ) {\n return null;\n }\n\n const content = Buffer.from(data.content.replace(/\\s/g, \"\"), \"base64\").toString(\"utf8\");\n if (Buffer.byteLength(content) > options.maxSourceBytes) {\n return null;\n }\n\n const sourceData: GitHubSourceData = {\n repo: source.repo,\n ref: source.ref,\n path: source.path,\n permalink: source.permalink,\n content,\n size: data.size ?? Buffer.byteLength(content),\n html_url: data.html_url ?? source.permalink,\n language: inferLanguage(source.path),\n };\n\n if (options.cache) {\n sourceCache.set(key, { data: sourceData, timestamp: Date.now() });\n }\n\n return sourceData;\n } catch (error) {\n console.warn(`Error fetching GitHub source ${source.permalink}:`, error);\n return null;\n }\n}\n\n/**\n * Pre-fetch all GitHub repos data.\n */\nexport async function prefetchGitHubRepos(\n repos: string[],\n options?: GitHubOptions,\n): Promise<Map<string, GitHubRepoData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, GitHubRepoData | null>();\n\n await Promise.all(\n Array.from(new Set(repos)).map(async (repo) => {\n const data = await fetchRepoData(repo, mergedOptions);\n results.set(repo, data);\n }),\n );\n\n return results;\n}\n\n/**\n * Pre-fetch all GitHub source files.\n */\nexport async function prefetchGitHubSources(\n sources: GitHubSourceRef[],\n options?: GitHubOptions,\n): Promise<Map<string, GitHubSourceData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, GitHubSourceData | null>();\n const uniqueSources = Array.from(\n new Map(sources.map((source) => [sourceKey(source), source])).values(),\n );\n\n await Promise.all(\n uniqueSources.map(async (source) => {\n const data = await fetchGitHubSource(source, mergedOptions);\n results.set(sourceKey(source), data);\n }),\n );\n\n return results;\n}\n","import type { Element } from \"hast\";\nimport { createGitHubPermalink, parseGitHubLineRange, parseGitHubPermalink } from \"./source\";\nimport type { GitHubSourceRef } from \"./types\";\nimport { isSafeGitHubPath, isSafeGitHubRef, isSafeGitHubRepo } from \"./validation\";\n\nconst GITHUB_COMPONENT_RE = /<github\\b([^>]*)>/gi;\nconst ATTRIBUTE_RE = /([:\\w-]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'>/]+)))?/g;\n\n/**\n * Collect all GitHub repos from HTML for pre-fetching.\n */\nexport async function collectGitHubRepos(html: string): Promise<string[]> {\n const repos: string[] = [];\n\n GITHUB_COMPONENT_RE.lastIndex = 0;\n let match;\n while ((match = GITHUB_COMPONENT_RE.exec(html)) !== null) {\n const attrs = parseAttributes(match[1]);\n if (attrs.path || attrs.file || attrs.permalink || attrs.url || attrs.href) {\n continue;\n }\n\n const repo = attrs.repo;\n if (repo && isSafeGitHubRepo(repo)) {\n repos.push(repo);\n }\n }\n\n return repos;\n}\n\n/**\n * Collect all GitHub source references from HTML for pre-fetching.\n */\nexport async function collectGitHubSources(html: string): Promise<GitHubSourceRef[]> {\n const sources: GitHubSourceRef[] = [];\n\n GITHUB_COMPONENT_RE.lastIndex = 0;\n let match;\n while ((match = GITHUB_COMPONENT_RE.exec(html)) !== null) {\n const source = sourceRefFromAttributes(parseAttributes(match[1]));\n if (source) {\n sources.push(source);\n }\n }\n\n return sources;\n}\n\nfunction parseAttributes(raw: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n ATTRIBUTE_RE.lastIndex = 0;\n let match;\n\n while ((match = ATTRIBUTE_RE.exec(raw)) !== null) {\n attrs[match[1].toLowerCase()] = match[2] ?? match[3] ?? match[4] ?? \"\";\n }\n\n return attrs;\n}\n\nexport function attributesFromElement(el: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const name of [\n \"permalink\",\n \"url\",\n \"href\",\n \"repo\",\n \"path\",\n \"file\",\n \"ref\",\n \"sha\",\n \"branch\",\n \"loc\",\n \"lines\",\n \"line\",\n ]) {\n const value = getAttribute(el, name);\n if (value !== undefined) {\n attrs[name] = value;\n }\n }\n return attrs;\n}\n\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\nexport function sourceRefFromAttributes(attrs: Record<string, string>): GitHubSourceRef | null {\n const permalink = attrs.permalink ?? attrs.url ?? attrs.href;\n if (permalink) {\n return parseGitHubPermalink(permalink);\n }\n\n const repo = attrs.repo;\n const path = attrs.path ?? attrs.file;\n if (!repo || !path || !isSafeGitHubRepo(repo) || !isSafeGitHubPath(path)) {\n return null;\n }\n\n const ref = attrs.ref ?? attrs.sha ?? attrs.branch ?? \"main\";\n if (!isSafeGitHubRef(ref)) {\n return null;\n }\n\n const lines = parseGitHubLineRange(attrs.loc ?? attrs.lines ?? attrs.line);\n const source = { repo, ref, path, lines };\n return {\n ...source,\n permalink: createGitHubPermalink(source),\n };\n}\n","import type { Element } from \"hast\";\nimport { isSafeGitHubRepo } from \"./validation\";\n\n/**\n * Create fallback element when repo data is unavailable.\n */\nexport function createFallbackCard(repo: string): Element {\n const href = isSafeGitHubRepo(repo) ? `https://github.com/${repo}` : \"#\";\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-github-card\", \"error\"],\n href,\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-github-header\"] },\n children: [\n {\n type: \"element\",\n tagName: \"svg\",\n properties: {\n className: [\"ox-github-icon\"],\n viewBox: \"0 0 16 16\",\n fill: \"currentColor\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"path\",\n properties: {\n d: \"M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z\",\n },\n children: [],\n },\n ],\n },\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-repo\"] },\n children: [{ type: \"text\", value: repo }],\n },\n ],\n },\n ],\n };\n}\n","import type { Element } from \"hast\";\nimport type { GitHubRepoData } from \"./types\";\n\nfunction formatNumber(num: number): string {\n if (num >= 1000000) {\n return `${(num / 1000000).toFixed(1)}M`;\n }\n if (num >= 1000) {\n return `${(num / 1000).toFixed(1)}k`;\n }\n return String(num);\n}\n\nfunction iconPath(d: string): Element {\n return {\n type: \"element\",\n tagName: \"svg\",\n properties: { viewBox: \"0 0 16 16\", fill: \"currentColor\" },\n children: [{ type: \"element\", tagName: \"path\", properties: { d }, children: [] }],\n };\n}\n\nfunction createStatsChildren(repoData: GitHubRepoData): Element[\"children\"] {\n const statsChildren: Element[\"children\"] = [];\n\n if (repoData.language) {\n statsChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-language\"] },\n children: [\n {\n type: \"element\",\n tagName: \"span\",\n properties: {\n className: [\"ox-github-language-color\"],\n \"data-lang\": repoData.language.toLowerCase(),\n },\n children: [],\n },\n { type: \"text\", value: repoData.language },\n ],\n });\n }\n\n statsChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-stat\"] },\n children: [\n iconPath(\n \"M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Z\",\n ),\n { type: \"text\", value: formatNumber(repoData.stargazers_count) },\n ],\n });\n\n statsChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-stat\"] },\n children: [\n iconPath(\n \"M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z\",\n ),\n { type: \"text\", value: formatNumber(repoData.forks_count) },\n ],\n });\n\n return statsChildren;\n}\n\n/**\n * Create GitHub card element from repo data.\n */\nexport function createGitHubCard(repoData: GitHubRepoData): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-github-card\"],\n href: repoData.html_url,\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-github-header\"] },\n children: [\n {\n ...iconPath(\n \"M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z\",\n ),\n properties: {\n className: [\"ox-github-icon\"],\n viewBox: \"0 0 16 16\",\n fill: \"currentColor\",\n },\n },\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-repo\"] },\n children: [{ type: \"text\", value: repoData.full_name }],\n },\n ],\n },\n ...(repoData.description\n ? [\n {\n type: \"element\" as const,\n tagName: \"p\",\n properties: { className: [\"ox-github-description\"] },\n children: [{ type: \"text\" as const, value: repoData.description }],\n },\n ]\n : []),\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-github-stats\"] },\n children: createStatsChildren(repoData),\n },\n ],\n };\n}\n","import type { Element } from \"hast\";\nimport { formatLineRange } from \"./source\";\nimport type { GitHubLineRange, GitHubOptions, GitHubSourceData } from \"./types\";\n\nfunction normalizeSourceLines(content: string): string[] {\n const lines = content.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n if (lines.length > 1 && lines.at(-1) === \"\") {\n lines.pop();\n }\n return lines.length > 0 ? lines : [\"\"];\n}\n\nexport function createGitHubSourceCard(\n source: GitHubSourceData,\n lines: GitHubLineRange | undefined,\n options: Required<GitHubOptions>,\n): Element {\n const allLines = normalizeSourceLines(source.content);\n const start = Math.min(lines?.start ?? 1, allLines.length);\n const end = lines\n ? Math.min(lines.end, allLines.length)\n : Math.min(allLines.length, options.maxSourceLines);\n const selectedLines = allLines.slice(start - 1, end);\n const lineRange = { start, end };\n const loc = selectedLines.length;\n const rangeLabel = formatLineRange(lineRange);\n const locLabel =\n !lines && end < allLines.length\n ? `${rangeLabel} of ${allLines.length} LOC`\n : `${rangeLabel} - ${loc} LOC`;\n const languageClass = source.language ? [`language-${source.language}`] : [];\n\n return {\n type: \"element\",\n tagName: \"figure\",\n properties: {\n className: [\"ox-github-code\"],\n \"data-loc\": String(loc),\n \"data-source\": source.permalink,\n },\n children: [\n {\n type: \"element\",\n tagName: \"figcaption\",\n properties: { className: [\"ox-github-code-header\"] },\n children: [\n {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-github-code-title\"],\n href: source.permalink,\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [{ type: \"text\", value: `${source.repo}/${source.path}` }],\n },\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-code-loc\"] },\n children: [{ type: \"text\", value: locLabel }],\n },\n ],\n },\n {\n type: \"element\",\n tagName: \"pre\",\n properties: {\n className: [\"ox-github-code-block\", ...languageClass],\n ...(source.language ? { \"data-language\": source.language } : {}),\n },\n children: [\n {\n type: \"element\",\n tagName: \"code\",\n properties: { className: languageClass },\n children: selectedLines.map((line, index) => {\n const lineNumber = start + index;\n return {\n type: \"element\" as const,\n tagName: \"span\",\n properties: {\n className: [\"line\", \"ox-github-code-line\"],\n \"data-line\": String(lineNumber),\n },\n children: [\n {\n type: \"element\" as const,\n tagName: \"span\",\n properties: { className: [\"ox-github-code-line-number\"] },\n children: [{ type: \"text\" as const, value: String(lineNumber) }],\n },\n {\n type: \"element\" as const,\n tagName: \"span\",\n properties: { className: [\"ox-github-code-line-content\"] },\n children: [{ type: \"text\" as const, value: line || \" \" }],\n },\n ],\n };\n }),\n },\n ],\n },\n ],\n };\n}\n","import type { Element, Root } from \"hast\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport { unified } from \"unified\";\nimport { interopDefault } from \"../../interop\";\nimport { prefetchGitHubRepos, prefetchGitHubSources } from \"./api\";\nimport {\n attributesFromElement,\n collectGitHubRepos,\n collectGitHubSources,\n sourceRefFromAttributes,\n} from \"./attributes\";\nimport { createFallbackCard } from \"./fallback-card\";\nimport { createGitHubCard } from \"./repo-card\";\nimport { sourceKey } from \"./source\";\nimport { createGitHubSourceCard } from \"./source-card\";\nimport {\n defaultOptions,\n type GitHubOptions,\n type GitHubRepoData,\n type GitHubSourceData,\n} from \"./types\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\n/**\n * Rehype plugin to transform GitHub components.\n */\nfunction rehypeGitHub(\n repoDataMap: Map<string, GitHubRepoData | null>,\n sourceDataMap: Map<string, GitHubSourceData | null>,\n options: Required<GitHubOptions>,\n) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type !== \"element\") {\n continue;\n }\n\n if (child.tagName.toLowerCase() !== \"github\") {\n visit(child);\n continue;\n }\n\n const attrs = attributesFromElement(child);\n const source = sourceRefFromAttributes(attrs);\n\n if (source) {\n const sourceData = sourceDataMap.get(sourceKey(source));\n node.children[i] = sourceData\n ? createGitHubSourceCard(sourceData, source.lines, options)\n : createFallbackCard(source.permalink);\n continue;\n }\n\n const repo = attrs.repo;\n if (repo) {\n const repoData = repoDataMap.get(repo);\n node.children[i] = repoData ? createGitHubCard(repoData) : createFallbackCard(repo);\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform GitHub components in HTML.\n */\nexport async function transformGitHub(\n html: string,\n repoDataMap?: Map<string, GitHubRepoData | null>,\n options?: GitHubOptions,\n): Promise<string> {\n const mergedOptions = { ...defaultOptions, ...options };\n let dataMap = repoDataMap;\n if (!dataMap) {\n const repos = await collectGitHubRepos(html);\n dataMap = await prefetchGitHubRepos(repos, mergedOptions);\n }\n const sources = await collectGitHubSources(html);\n const sourceDataMap = await prefetchGitHubSources(sources, mergedOptions);\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeGitHub, dataMap, sourceDataMap, mergedOptions)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n","export {\n fetchGitHubSource,\n fetchRepoData,\n prefetchGitHubRepos,\n prefetchGitHubSources,\n} from \"./github/api\";\nexport { collectGitHubRepos, collectGitHubSources } from \"./github/attributes\";\nexport { createGitHubPermalink, parseGitHubLineRange, parseGitHubPermalink } from \"./github/source\";\nexport { transformGitHub } from \"./github/transform\";\nexport type {\n GitHubLineRange,\n GitHubOptions,\n GitHubRepoData,\n GitHubSourceData,\n GitHubSourceRef,\n} from \"./github/types\";\nexport { isSafeGitHubRepo } from \"./github/validation\";\n","/**\n * OGP Card Plugin - Link card embedding\n *\n * Transforms <OgCard> components into static link preview cards\n * by fetching OGP metadata at build time.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\nimport { interopDefault } from \"../interop\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\nexport interface OgpData {\n url: string;\n title: string;\n description?: string;\n image?: string;\n siteName?: string;\n favicon?: string;\n}\n\nexport interface OgpOptions {\n /**\n * Request timeout in milliseconds.\n * @default 10000\n */\n timeout?: number;\n\n /**\n * Cache fetched Open Graph metadata in memory for the current process.\n * @default true\n */\n cache?: boolean;\n\n /**\n * Cache TTL in milliseconds.\n * @default 3600000\n */\n cacheTTL?: number;\n\n /**\n * User agent sent with metadata fetch requests.\n * @default 'ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei-prod/ox-content)'\n */\n userAgent?: string;\n}\n\nconst defaultOptions: Required<OgpOptions> = {\n timeout: 10000,\n cache: true,\n cacheTTL: 3600000,\n userAgent: \"ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei-prod/ox-content)\",\n};\n\n// Simple in-memory cache\nconst ogpCache = new Map<string, { data: OgpData; timestamp: number }>();\n\nfunction isPrivateIPv4(hostname: string): boolean {\n const parts = hostname.split(\".\").map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n const [a, b] = parts;\n return (\n a === 10 ||\n a === 127 ||\n a === 0 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 169 && b === 254)\n );\n}\n\nexport function isSafeOgpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n const host = url.hostname.toLowerCase();\n const ipv6 = host.replace(/^\\[|\\]$/g, \"\");\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n if (host === \"localhost\" || host.endsWith(\".localhost\")) return false;\n if (\n ipv6.includes(\":\") &&\n (ipv6 === \"::1\" || ipv6.startsWith(\"fc\") || ipv6.startsWith(\"fd\") || ipv6.startsWith(\"fe80\"))\n )\n return false;\n return !isPrivateIPv4(host);\n } catch {\n return false;\n }\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Extract domain from URL.\n */\nfunction extractDomain(url: string): string {\n try {\n const urlObj = new URL(url);\n return urlObj.hostname;\n } catch {\n return url;\n }\n}\n\n/**\n * Get favicon URL for a domain.\n */\nfunction getFaviconUrl(url: string): string {\n try {\n const urlObj = new URL(url);\n // Use Google's favicon service as fallback\n return `https://www.google.com/s2/favicons?domain=${urlObj.hostname}&sz=32`;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Parse OGP metadata from HTML.\n */\nfunction parseOgpFromHtml(html: string, url: string): OgpData {\n const result: OgpData = {\n url,\n title: \"\",\n };\n\n // Extract title\n const titleMatch = html.match(/<title[^>]*>([^<]+)<\\/title>/i);\n const ogTitleMatch =\n html.match(/<meta[^>]*property=[\"']og:title[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:title[\"']/i);\n\n result.title = ogTitleMatch?.[1] || titleMatch?.[1] || extractDomain(url);\n\n // Extract description\n const descMatch =\n html.match(/<meta[^>]*property=[\"']og:description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:description[\"']/i) ||\n html.match(/<meta[^>]*name=[\"']description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*name=[\"']description[\"']/i);\n\n if (descMatch) {\n result.description = descMatch[1];\n }\n\n // Extract image\n const imageMatch =\n html.match(/<meta[^>]*property=[\"']og:image[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:image[\"']/i);\n\n if (imageMatch) {\n let imageUrl = imageMatch[1];\n // Handle relative URLs\n if (imageUrl.startsWith(\"/\")) {\n try {\n const urlObj = new URL(url);\n imageUrl = `${urlObj.protocol}//${urlObj.host}${imageUrl}`;\n } catch {\n // Keep as is\n }\n }\n result.image = imageUrl;\n }\n\n // Extract site name\n const siteNameMatch =\n html.match(/<meta[^>]*property=[\"']og:site_name[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:site_name[\"']/i);\n\n if (siteNameMatch) {\n result.siteName = siteNameMatch[1];\n }\n\n // Get favicon\n result.favicon = getFaviconUrl(url);\n\n return result;\n}\n\n/**\n * Fetch OGP data for a URL.\n */\nexport async function fetchOgpData(\n url: string,\n options: Required<OgpOptions>,\n): Promise<OgpData | null> {\n if (!isSafeOgpUrl(url)) {\n return null;\n }\n\n // Check cache\n if (options.cache) {\n const cached = ogpCache.get(url);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n\n const response = await fetch(url, {\n headers: {\n \"User-Agent\": options.userAgent,\n Accept: \"text/html,application/xhtml+xml\",\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`Failed to fetch OGP for ${url}: ${response.status}`);\n return null;\n }\n\n const html = await response.text();\n const data = parseOgpFromHtml(html, url);\n\n // Cache the result\n if (options.cache) {\n ogpCache.set(url, { data, timestamp: Date.now() });\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n console.warn(`Timeout fetching OGP for ${url}`);\n } else {\n console.warn(`Error fetching OGP for ${url}:`, error);\n }\n return null;\n }\n}\n\n/**\n * Create OGP card element.\n */\nfunction createOgpCard(data: OgpData): Element {\n const children: Element[\"children\"] = [];\n\n // Content section\n const contentChildren: Element[\"children\"] = [];\n\n // Title\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-title\"] },\n children: [{ type: \"text\", value: data.title }],\n });\n\n // Description\n if (data.description) {\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-description\"] },\n children: [{ type: \"text\", value: data.description }],\n });\n }\n\n // Meta (favicon + domain)\n const metaChildren: Element[\"children\"] = [];\n\n if (data.favicon) {\n metaChildren.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-favicon\"],\n src: data.favicon,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n metaChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-ogp-domain\"] },\n children: [{ type: \"text\", value: data.siteName || extractDomain(data.url) }],\n });\n\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-meta\"] },\n children: metaChildren,\n });\n\n children.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-content\"] },\n children: contentChildren,\n });\n\n // Image\n if (data.image) {\n children.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-image\"],\n src: data.image,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-card\"],\n href: isSafeOgpUrl(data.url) ? data.url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children,\n };\n}\n\n/**\n * Create fallback element when OGP data is unavailable.\n */\nfunction createFallbackCard(url: string): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-simple\"],\n href: isSafeOgpUrl(url) ? url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"svg\",\n properties: {\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n \"stroke-width\": \"2\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"path\",\n properties: {\n d: \"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3\",\n },\n children: [],\n },\n ],\n },\n { type: \"text\", value: extractDomain(url) },\n ],\n };\n}\n\n/**\n * Collect all OGP URLs from HTML for pre-fetching.\n */\nexport async function collectOgpUrls(html: string): Promise<string[]> {\n const urls: string[] = [];\n const urlPattern = /<ogcard[^>]*\\s+url=[\"']([^\"']+)[\"']/gi;\n\n let match;\n while ((match = urlPattern.exec(html)) !== null) {\n if (isSafeOgpUrl(match[1])) {\n urls.push(match[1]);\n }\n }\n\n return urls;\n}\n\n/**\n * Pre-fetch all OGP data.\n */\nexport async function prefetchOgpData(\n urls: string[],\n options?: OgpOptions,\n): Promise<Map<string, OgpData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, OgpData | null>();\n\n await Promise.all(\n urls.map(async (url) => {\n const data = await fetchOgpData(url, mergedOptions);\n results.set(url, data);\n }),\n );\n\n return results;\n}\n\n/**\n * Rehype plugin to transform OgCard components.\n */\nfunction rehypeOgp(ogpDataMap: Map<string, OgpData | null>) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <OgCard> component\n if (child.tagName.toLowerCase() === \"ogcard\") {\n const url = getAttribute(child, \"url\");\n\n if (url) {\n const ogpData = ogpDataMap.get(url);\n const cardElement = ogpData ? createOgpCard(ogpData) : createFallbackCard(url);\n node.children[i] = cardElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform OgCard components in HTML.\n */\nexport async function transformOgp(\n html: string,\n ogpDataMap?: Map<string, OgpData | null>,\n options?: OgpOptions,\n): Promise<string> {\n // If no pre-fetched data, collect and fetch\n let dataMap = ogpDataMap;\n if (!dataMap) {\n const urls = await collectOgpUrls(html);\n dataMap = await prefetchOgpData(urls, options);\n }\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeOgp, dataMap)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n","/**\n * ox-content Built-in Plugins\n *\n * All plugins are designed with No-JavaScript-First principle.\n * They generate static HTML at build time and require no client-side JS.\n */\n\nimport type { GitHubOptions } from \"./github\";\nimport type { MediaEmbedOptions } from \"./media\";\nimport type { TwitterEmbedOptions } from \"./twitter\";\nimport type { OgpOptions } from \"./ogp\";\nimport type { PmOptions } from \"./pm\";\n\nexport {\n transformTabs,\n generateTabsCSS,\n resetTabGroupCounter,\n getTabGroupCounter,\n setTabGroupCounter,\n} from \"./tabs\";\n\nexport { transformPm, type PmOptions } from \"./pm\";\n\nexport { transformYouTube, extractVideoId, type YouTubeOptions } from \"./youtube\";\nexport { transformMediaEmbeds, type MediaEmbedOptions } from \"./media\";\nexport {\n createSyndicationToken,\n parseTweetReference,\n type TweetData,\n type TwitterEmbedOptions,\n} from \"./twitter\";\n\nexport {\n transformGitHub,\n fetchRepoData,\n fetchGitHubSource,\n collectGitHubRepos,\n collectGitHubSources,\n prefetchGitHubRepos,\n prefetchGitHubSources,\n parseGitHubPermalink,\n parseGitHubLineRange,\n type GitHubRepoData,\n type GitHubSourceData,\n type GitHubSourceRef,\n type GitHubLineRange,\n type GitHubOptions,\n} from \"./github\";\n\nexport {\n transformOgp,\n fetchOgpData,\n collectOgpUrls,\n prefetchOgpData,\n type OgpData,\n type OgpOptions,\n} from \"./ogp\";\n\nexport { transformMermaidStatic, mermaidClientScript, type MermaidOptions } from \"./mermaid\";\n\nconst SELF_CLOSING_EMBED_TAG =\n /<(GitHub|OgCard|Tweet|XPost|Bluesky|Spotify|StackBlitz|WebContainer|YouTube)((?:[^>\"']|\"[^\"]*\"|'[^']*')*?)\\s*\\/>/gi;\n\n/**\n * Custom embed tags are not HTML void elements, so a self-closing authoring\n * form like `<GitHub ... />` reaches the HTML re-parsers (Shiki highlighting,\n * embed transforms) as an unclosed element that swallows the rest of the\n * document. Normalize to an explicit open/close pair before any rehype pass\n * runs.\n */\nexport function normalizeSelfClosingEmbeds(html: string): string {\n return html.replace(SELF_CLOSING_EMBED_TAG, (_match, tag: string, attrs: string) => {\n return `<${tag}${attrs}></${tag}>`;\n });\n}\n\n/**\n * Transform all plugin components in HTML.\n * Call this during SSG build to process all plugins at once.\n */\nexport interface TransformAllOptions {\n tabs?: boolean;\n /**\n * Expand `<pm>` package-manager blocks into install tabs. Pass an object to\n * opt in to synced groups (`{ sync: true }`); syncing is off by default.\n * @default false\n */\n pm?: boolean | PmOptions;\n youtube?: boolean;\n github?: boolean | GitHubOptions;\n ogp?: boolean | OgpOptions;\n openGraph?: boolean | OgpOptions;\n mermaid?: boolean;\n githubToken?: string;\n spotify?: boolean;\n stackBlitz?: boolean;\n twitter?: boolean | TwitterEmbedOptions;\n bluesky?: boolean;\n webContainer?: boolean;\n}\n\n/**\n * Transform all enabled plugins in HTML content.\n */\nexport async function transformAllPlugins(\n html: string,\n options: TransformAllOptions = {},\n): Promise<string> {\n const {\n tabs = true,\n pm = false,\n youtube = true,\n github = true,\n ogp,\n openGraph,\n mermaid = true,\n githubToken,\n spotify = false,\n stackBlitz = false,\n twitter = false,\n bluesky = false,\n webContainer = false,\n } = options;\n\n let result = normalizeSelfClosingEmbeds(html);\n const ogpOptions = openGraph ?? ogp ?? true;\n\n // Order matters: process in dependency order\n\n // 1. Tabs (no external dependencies)\n if (tabs) {\n const { transformTabs } = await import(\"./tabs\");\n result = await transformTabs(result);\n }\n\n // 1b. Package-manager tabs (no external dependencies). Shares the tab-group\n // counter with the tabs transform, so it runs right after it. Syncing is\n // opt-in via `{ pm: { sync: true } }` and off by default.\n if (pm) {\n const { transformPm } = await import(\"./pm\");\n result = await transformPm(result, typeof pm === \"object\" ? pm : {});\n }\n\n // 2. YouTube (no external dependencies)\n if (youtube) {\n const { transformYouTube } = await import(\"./youtube\");\n result = await transformYouTube(result);\n }\n\n // 3. GitHub (requires API calls)\n if (github !== false) {\n const { transformGitHub } = await import(\"./github\");\n const options = typeof github === \"object\" ? github : {};\n result = await transformGitHub(result, undefined, { token: githubToken, ...options });\n }\n\n // 4. OGP (requires fetch calls)\n if (ogpOptions !== false) {\n const { transformOgp } = await import(\"./ogp\");\n result = await transformOgp(\n result,\n undefined,\n typeof ogpOptions === \"object\" ? ogpOptions : {},\n );\n }\n\n const mediaOptions = { spotify, stackBlitz, twitter, bluesky, webContainer };\n if (Object.values(mediaOptions).some(Boolean)) {\n const { transformMediaEmbeds } = await import(\"./media\");\n result = await transformMediaEmbeds(result, mediaOptions);\n }\n\n // 5. Mermaid (requires mermaid library)\n if (mermaid) {\n const { transformMermaidStatic } = await import(\"./mermaid\");\n result = await transformMermaidStatic(result);\n }\n\n return result;\n}\n\n/**\n * Transform built-in embed components in HTML content.\n */\nexport async function transformBuiltinEmbeds(\n html: string,\n options: {\n github: GitHubOptions | false;\n openGraph: OgpOptions | false;\n pm?: PmOptions | false;\n spotify?: boolean;\n stackBlitz?: boolean;\n twitter?: boolean | TwitterEmbedOptions;\n bluesky?: boolean;\n webContainer?: boolean;\n },\n): Promise<string> {\n let result = normalizeSelfClosingEmbeds(html);\n\n if (options.github) {\n const { transformGitHub } = await import(\"./github\");\n result = await transformGitHub(result, undefined, {\n token: process.env.GITHUB_TOKEN,\n ...options.github,\n });\n }\n\n if (options.openGraph) {\n const { transformOgp } = await import(\"./ogp\");\n result = await transformOgp(result, undefined, options.openGraph);\n }\n\n if (options.pm) {\n const { transformPm } = await import(\"./pm\");\n result = await transformPm(result, typeof options.pm === \"object\" ? options.pm : {});\n }\n\n const mediaOptions: MediaEmbedOptions = {\n spotify: options.spotify,\n stackBlitz: options.stackBlitz,\n twitter: options.twitter,\n bluesky: options.bluesky,\n webContainer: options.webContainer,\n };\n if (Object.values(mediaOptions).some(Boolean)) {\n const { transformMediaEmbeds } = await import(\"./media\");\n result = await transformMediaEmbeds(result, mediaOptions);\n }\n\n return result;\n}\n","/**\n * Protects mermaid SVG content from rehype HTML5 parser corruption.\n *\n * rehypeParse + rehypeStringify converts `<br />` in SVG foreignObject\n * to `<br></br>`, which HTML5 interprets as 2 <br> elements.\n * Each rehype pass doubles them: 1 → 2 → 4 → 8 → 16.\n *\n * This module extracts ox-mermaid SVG blocks into placeholders before\n * rehype processing and restores them after.\n */\n\nexport interface MermaidSvgProtection {\n html: string;\n svgs: Map<string, string>;\n}\n\n/**\n * Extract `<div class=\"ox-mermaid\">...</div>` blocks and replace\n * with HTML comment placeholders that rehype will preserve.\n */\nexport function protectMermaidSvgs(html: string): MermaidSvgProtection {\n const svgs = new Map<string, string>();\n let result = html;\n let idx = 0;\n\n while (true) {\n const marker = `<div class=\"ox-mermaid\">`;\n const start = result.indexOf(marker, idx);\n if (start === -1) break;\n\n // Find the matching </div> by counting nested divs\n let depth = 0;\n let pos = start;\n let endPos = -1;\n\n while (pos < result.length) {\n const openIdx = result.indexOf(\"<div\", pos);\n const closeIdx = result.indexOf(\"</div>\", pos);\n if (closeIdx === -1) break;\n\n if (openIdx !== -1 && openIdx < closeIdx) {\n depth++;\n pos = openIdx + 4;\n } else {\n depth--;\n if (depth === 0) {\n endPos = closeIdx + 6;\n break;\n }\n pos = closeIdx + 6;\n }\n }\n\n if (endPos === -1) break;\n\n const svgContent = result.substring(start, endPos);\n const placeholder = `<!--ox-mermaid-${svgs.size}-->`;\n svgs.set(placeholder, svgContent);\n result = result.substring(0, start) + placeholder + result.substring(endPos);\n idx = start + placeholder.length;\n }\n\n return { html: result, svgs };\n}\n\n/**\n * Restore protected mermaid SVG blocks from placeholders.\n */\nexport function restoreMermaidSvgs(html: string, svgs: Map<string, string>): string {\n if (svgs.size === 0) {\n return html;\n }\n // Single pass over the HTML instead of one full `String.replace` scan per\n // placeholder (O(svgs × html) → O(html)). The function replacer also avoids\n // the `$`-pattern interpretation that the string form of `replace` applies\n // to the SVG replacement content.\n return html.replace(/<!--ox-mermaid-\\d+-->/g, (placeholder) => {\n const content = svgs.get(placeholder);\n return content !== undefined ? content : placeholder;\n });\n}\n","import { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { execFile } from \"node:child_process\";\nimport { importNapiModule } from \"./napi\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface ExtractedCodeBlock {\n language: string;\n meta: string;\n code: string;\n startLine: number;\n endLine: number;\n}\n\nexport interface CodeBlockDiagnostic {\n ruleId: string;\n severity: \"error\" | \"warning\" | \"info\";\n message: string;\n line: number;\n column: number;\n endLine: number;\n endColumn: number;\n language?: string;\n}\n\nexport interface CodeBlockLintOptions {\n /**\n * Languages to lint. Omit to lint every fenced block language.\n * @default undefined\n */\n languages?: string[];\n\n /**\n * Report fences without a language identifier.\n * @default false\n */\n requireLanguage?: boolean;\n\n /**\n * Report trailing whitespace in code block lines.\n * @default true\n */\n trailingSpaces?: boolean;\n}\n\nexport interface DocsTestOptions {\n /**\n * Fence languages to collect as runnable examples.\n * @default ['js', 'jsx', 'ts', 'tsx', 'mjs', 'mts']\n */\n languages?: string[];\n\n /**\n * Require fence meta such as `test`, `runnable`, `vitest`, or `docs-test`.\n * @default true\n */\n requireMeta?: boolean;\n}\n\nexport interface TypecheckCodeBlockOptions {\n /**\n * Fence languages to type-check.\n * @default ['ts', 'tsx']\n */\n languages?: string[];\n\n /**\n * Require fence meta such as `typecheck`, `twoslash`, or `typecheck=...`.\n * @default true\n */\n requireMeta?: boolean;\n\n /**\n * Command used to run the TypeScript checker.\n * @default 'tsgo'\n */\n tsgoCommand?: string;\n}\n\nexport async function extractCodeBlocks(source: string): Promise<ExtractedCodeBlock[]> {\n const mod = await importNapiModule();\n return mod.extractCodeBlocks(source).map(normalizeBlock);\n}\n\nexport async function lintCodeBlocks(\n source: string,\n options: CodeBlockLintOptions = {},\n): Promise<CodeBlockDiagnostic[]> {\n const mod = await importNapiModule();\n return mod\n .lintCodeBlocks(source, {\n enabled: true,\n languages: options.languages,\n requireLanguage: options.requireLanguage,\n trailingSpaces: options.trailingSpaces,\n })\n .map(normalizeDiagnostic);\n}\n\nexport async function extractDocsTests(\n source: string,\n options: DocsTestOptions = {},\n): Promise<ExtractedCodeBlock[]> {\n const mod = await importNapiModule();\n return mod\n .extractDocsTests(source, {\n enabled: true,\n languages: options.languages,\n requireMeta: options.requireMeta,\n })\n .map(normalizeBlock);\n}\n\nexport async function typecheckCodeBlocks(\n source: string,\n options: TypecheckCodeBlockOptions = {},\n): Promise<CodeBlockDiagnostic[]> {\n if (!source.includes(\"```\")) {\n return [];\n }\n\n const languages = new Set(\n (options.languages ?? [\"ts\", \"tsx\"]).map((language) => language.toLowerCase()),\n );\n const blocks = (await extractCodeBlocks(source)).filter((block) => {\n if (!languages.has(block.language.toLowerCase())) {\n return false;\n }\n return options.requireMeta === false || hasTypecheckMeta(block.meta);\n });\n if (blocks.length === 0) {\n return [];\n }\n\n const temp = await mkdtemp(join(tmpdir(), \"ox-content-code-blocks-\"));\n try {\n const files: string[] = [];\n await Promise.all(\n blocks.map(async (block, index) => {\n const extension = block.language.toLowerCase() === \"tsx\" ? \"tsx\" : \"ts\";\n const file = join(temp, `snippet-${index}.${extension}`);\n files.push(file);\n await writeFile(file, block.code);\n }),\n );\n\n try {\n await execFileAsync(\n options.tsgoCommand ?? \"tsgo\",\n [\"--noEmit\", \"--pretty\", \"false\", ...files],\n {\n cwd: process.cwd(),\n maxBuffer: 1024 * 1024 * 4,\n },\n );\n return [];\n } catch (error) {\n const output = commandOutput(error);\n return [\n {\n ruleId: \"code-block-typecheck\",\n severity: \"error\",\n message: output || \"TypeScript code block type-checking failed.\",\n line: blocks[0]?.startLine ?? 1,\n column: 1,\n endLine: blocks[0]?.startLine ?? 1,\n endColumn: 1,\n language: \"ts\",\n },\n ];\n }\n } finally {\n await rm(temp, { recursive: true, force: true });\n }\n}\n\nfunction hasTypecheckMeta(meta: string): boolean {\n return meta\n .split(/\\s+/)\n .some(\n (token) => token === \"typecheck\" || token === \"twoslash\" || token.startsWith(\"typecheck=\"),\n );\n}\n\nfunction commandOutput(error: unknown): string {\n if (!error || typeof error !== \"object\") {\n return \"\";\n }\n const value = error as { stdout?: unknown; stderr?: unknown; message?: unknown };\n return [value.stdout, value.stderr, value.message]\n .filter((part): part is string => typeof part === \"string\" && part.trim().length > 0)\n .join(\"\\n\")\n .trim();\n}\n\nfunction normalizeBlock(block: {\n language: string;\n meta: string;\n code: string;\n startLine: number;\n endLine: number;\n}): ExtractedCodeBlock {\n return block;\n}\n\nfunction normalizeDiagnostic(diagnostic: {\n ruleId: string;\n severity: string;\n message: string;\n line: number;\n column: number;\n endLine: number;\n endColumn: number;\n language?: string;\n}): CodeBlockDiagnostic {\n return {\n ...diagnostic,\n severity:\n diagnostic.severity === \"error\" || diagnostic.severity === \"info\"\n ? diagnostic.severity\n : \"warning\",\n };\n}\n","/**\n * Markdown Transformation Engine\n *\n * This module handles the complete transformation pipeline for Markdown files,\n * converting raw Markdown content into JavaScript modules that can be imported\n * by web applications. The transformation process includes:\n *\n * 1. **Parsing**: Uses Rust-based parser via NAPI bindings for high performance\n * 2. **Rendering**: Converts parsed AST to semantic HTML\n * 3. **Enhancement**: Applies syntax highlighting, Mermaid diagram rendering, etc.\n * 4. **Code Generation**: Generates JavaScript/TypeScript module code\n *\n * The generated modules export:\n * - `html`: Rendered HTML content\n * - `frontmatter`: Parsed YAML metadata\n * - `toc`: Hierarchical table of contents\n * - `render`: Client-side render function for dynamic updates\n *\n * @example\n * ```typescript\n * import { transformMarkdown } from './transform';\n *\n * const content = await transformMarkdown(\n * '# Hello\\n\\nWorld',\n * 'path/to/file.md',\n * resolvedOptions\n * );\n *\n * console.log(content.html); // '<h1>Hello</h1><p>World</p>'\n * console.log(content.toc); // [{ depth: 1, text: 'Hello', slug: 'hello', children: [] }]\n * ```\n */\n\nimport type { ResolvedOptions, TransformResult, TocEntry } from \"./types\";\nimport { highlightCode } from \"./highlight\";\nimport { highlightDocumentNatively } from \"./highlight-native\";\nimport { importNapiModule } from \"./napi\";\nimport { transformMermaidStatic } from \"./plugins/mermaid\";\nimport { normalizeSelfClosingEmbeds, transformBuiltinEmbeds } from \"./plugins\";\nimport { protectMermaidSvgs, restoreMermaidSvgs } from \"./plugins/mermaid-protect\";\nimport { typecheckCodeBlocks } from \"./code-blocks\";\nimport { resolveMdxForFilePath } from \"./markdown\";\n\n/**\n * NAPI bindings for Rust-based Markdown processing.\n *\n * Provides access to compiled Rust functions for high-performance\n * Markdown parsing and rendering operations.\n */\ninterface NapiBindings {\n /**\n * Simple Markdown parser and renderer in one step.\n * Faster for simple use cases but lacks advanced features.\n *\n * @param source - Raw Markdown content\n * @param options - Parser configuration (GFM flag)\n * @returns Rendered HTML and parsing errors\n */\n parseAndRender: (\n source: string,\n options?: { gfm?: boolean },\n ) => { html: string; errors: string[] };\n\n /**\n * Full-featured Markdown transformation pipeline.\n * Handles frontmatter extraction, TOC generation, and advanced parsing.\n *\n * @param source - Raw Markdown content (may include frontmatter)\n * @param options - Comprehensive transformation options\n * @returns Transformed result with HTML, metadata, and TOC\n */\n transform: (\n source: string,\n options?: JsTransformOptions,\n ) => {\n html: string;\n frontmatter: string;\n toc: Array<{ depth: number; text: string; slug: string; children?: TocEntry[] }>;\n errors: string[];\n };\n\n /**\n * Generates an OG image as SVG.\n *\n * @param data - OG image data (title, description, etc.)\n * @param config - Optional OG image configuration\n * @returns SVG string\n */\n generateOgImageSvg: (data: OgImageData, config?: OgImageConfig) => string;\n\n /**\n * Restores code block metadata after JavaScript-side syntax highlighting.\n *\n * @param originalHtml - HTML before syntax highlighting\n * @param highlightedHtml - HTML after native highlighting\n * @returns Highlighted HTML with original code block metadata reapplied\n */\n mergeHighlightedCodeBlocks: (originalHtml: string, highlightedHtml: string) => string;\n\n sanitizeHtml: (html: string, options?: JsSanitizeOptions) => string;\n\n lintCodeBlocks: (source: string, options?: JsCodeBlockLintOptions) => JsCodeBlockDiagnostic[];\n}\n\n/**\n * OG image data for generating social media preview images.\n */\nexport interface OgImageData {\n /** Page title */\n title: string;\n /** Page description */\n description?: string;\n /** Site name */\n siteName?: string;\n /** Author name */\n author?: string;\n}\n\n/**\n * OG image configuration.\n */\nexport interface OgImageConfig {\n /** Image width in pixels */\n width?: number;\n /** Image height in pixels */\n height?: number;\n /** Background color (hex) */\n backgroundColor?: string;\n /** Text color (hex) */\n textColor?: string;\n /** Title font size */\n titleFontSize?: number;\n /** Description font size */\n descriptionFontSize?: number;\n}\n\n/**\n * Options for Rust-based Markdown transformation.\n *\n * Controls which Markdown extensions and features are enabled\n * during parsing and rendering.\n */\ninterface JsTransformOptions {\n /**\n * Enable GitHub Flavored Markdown extensions.\n * Includes tables, task lists, strikethrough, and autolinks.\n * @default false\n */\n gfm?: boolean;\n\n /**\n * Enable MDX JSX, ESM, and expression nodes.\n * @default false\n */\n mdx?: boolean;\n\n /**\n * Enable footnotes syntax ([^1]: definition).\n * @default false\n */\n footnotes?: boolean;\n\n /**\n * Enable task list syntax (- [ ] unchecked, - [x] checked).\n * @default false\n */\n taskLists?: boolean;\n\n /**\n * Enable table rendering (GFM extension).\n * Requires GFM to be enabled for full functionality.\n * @default false\n */\n tables?: boolean;\n\n /**\n * Enable strikethrough syntax (~~text~~).\n * Requires GFM to be enabled.\n * @default false\n */\n strikethrough?: boolean;\n\n /**\n * Enable automatic link conversion (URLs become clickable).\n * @default false\n */\n autolinks?: boolean;\n\n /**\n * Linkify bare URLs while rendering.\n * @default true\n */\n autolinkUrls?: boolean;\n\n /**\n * Parse YAML frontmatter before transforming.\n * @default true\n */\n frontmatter?: boolean;\n\n /**\n * Maximum heading depth for table of contents.\n * Headings deeper than this level are excluded from TOC.\n * @default 3\n * @min 1\n * @max 6\n */\n tocMaxDepth?: number;\n\n /**\n * Convert `.md` links to `.html` links for SSG output.\n * @default false\n */\n convertMdLinks?: boolean;\n\n /**\n * Base URL for absolute link conversion (e.g., \"/\" or \"/docs/\").\n * @default \"/\"\n */\n baseUrl?: string;\n\n /**\n * Source file path for relative link resolution.\n * Used to determine if the current file is an index file.\n */\n sourcePath?: string;\n\n /**\n * Enable line annotations for code blocks using fence meta.\n * @default false\n */\n codeAnnotations?: boolean;\n\n /**\n * Fence meta key used to read code annotations.\n * @default \"annotate\"\n */\n codeAnnotationMetaKey?: string;\n\n /**\n * Code annotation syntax mode.\n * @default \"attribute\"\n */\n codeAnnotationSyntax?: \"attribute\" | \"vitepress\" | \"both\";\n\n /**\n * Enable line numbers for all code blocks by default.\n * @default false\n */\n codeAnnotationDefaultLineNumbers?: boolean;\n\n wikiLinks?: {\n enabled?: boolean;\n baseUrl?: string;\n };\n\n emojiShortcodes?: {\n enabled?: boolean;\n custom?: Record<string, string>;\n };\n\n attributes?: {\n enabled?: boolean;\n };\n\n badges?: {\n enabled?: boolean;\n };\n\n containers?: {\n enabled?: boolean;\n types?: Record<string, { title?: string; tag?: string }>;\n };\n\n images?: {\n enabled?: boolean;\n lazy?: boolean;\n };\n\n cjkEmphasis?: boolean;\n\n codeImports?: {\n enabled?: boolean;\n rootDir?: string;\n };\n\n includes?: {\n enabled?: boolean;\n rootDir?: string;\n };\n\n cards?: {\n enabled?: boolean;\n };\n\n steps?: {\n enabled?: boolean;\n };\n\n fileTree?: {\n enabled?: boolean;\n };\n\n sanitize?: JsSanitizeOptions;\n\n editThisPage?: {\n enabled?: boolean;\n repoUrl?: string;\n branch?: string;\n rootDir?: string;\n label?: string;\n };\n\n /**\n * Opt-in `$…$` inline and `$$…$$` block math.\n *\n * Omitted or `false` leaves `$` literal. `true` or `{}` enables defaults;\n * `{ enabled: false }` disables math.\n *\n * @default false\n */\n math?:\n | boolean\n | {\n enabled?: boolean;\n };\n}\n\ninterface JsSanitizeOptions {\n enabled?: boolean;\n allowedTags?: string[];\n allowedAttributes?: string[];\n allowedUrlSchemes?: string[];\n}\n\ninterface JsCodeBlockLintOptions {\n enabled?: boolean;\n languages?: string[];\n requireLanguage?: boolean;\n trailingSpaces?: boolean;\n}\n\ninterface JsCodeBlockDiagnostic {\n ruleId: string;\n severity: string;\n message: string;\n line: number;\n column: number;\n endLine: number;\n endColumn: number;\n language?: string;\n}\n\n/**\n * The NAPI load, cached as the promise rather than as its result.\n *\n * The load yields, and a caller arriving during that yield has to wait for it\n * rather than read a result that is not there yet. Holding the promise is what\n * makes every caller wait for the same load; holding an \"already attempted\"\n * flag beside an unset result meant the first page to arrive loaded the module\n * and every page behind it concluded there were no bindings at all.\n *\n * @internal\n */\nlet napiLoad: Promise<NapiBindings | null> | undefined;\n\n/**\n * Lazily loads and caches NAPI bindings.\n *\n * This function uses lazy loading to defer the import of NAPI bindings\n * until they're actually needed. The bindings are loaded only once and\n * cached for subsequent uses, including by callers that ask for them while\n * that first load is still in flight. If loading fails (e.g., bindings not\n * built), the failure is cached to avoid repeated load attempts.\n *\n * ## Performance Considerations\n *\n * The first call to this function may have a slight performance penalty\n * due to module loading. Subsequent calls use the cached result and are\n * essentially zero-cost.\n *\n * ## Error Handling\n *\n * If NAPI bindings are not available (not built, wrong architecture, etc.),\n * this function returns `null`. The caller should handle this gracefully\n * or provide fallback behavior.\n *\n * @returns Promise resolving to NAPI bindings or null if unavailable\n *\n * @example\n * ```typescript\n * // Simple check with fallback\n * const napi = await loadNapiBindings();\n * if (!napi) {\n * console.warn('NAPI bindings not available, using fallback');\n * return fallbackRender(content);\n * }\n *\n * // Use Rust implementation\n * const result = napi.transform(content, { gfm: true });\n * ```\n *\n * @internal\n */\nfunction loadNapiBindings(): Promise<NapiBindings | null> {\n // Started once; everyone after that awaits the same load, including the\n // callers that arrive while it is still in flight.\n napiLoad ??= importNapiModule().catch((error: unknown) => {\n // NAPI not available (not built, missing dependencies, etc.)\n // Log for debugging but don't throw - allow graceful degradation.\n // The rejection is settled here, so the failure is cached too.\n if (process.env.DEBUG) {\n console.debug(\"[ox-content] NAPI bindings load failed:\", error);\n }\n return null;\n });\n\n return napiLoad;\n}\n\n/**\n * Transforms Markdown content into a JavaScript module.\n *\n * This is the primary entry point for transforming Markdown files. It handles\n * the complete transformation pipeline including parsing, rendering, syntax\n * highlighting, and code generation.\n *\n * ## Pipeline Steps\n *\n * 1. **Parse & Render**: Uses Rust-based parser via NAPI for high performance\n * 2. **Extract Metadata**: Parses YAML frontmatter and generates table of contents\n * 3. **Enhance HTML**: Applies syntax highlighting and Mermaid diagram rendering\n * 4. **Generate Code**: Creates importable JavaScript module\n *\n * ## Generated Module Exports\n *\n * - `html` (string): Rendered HTML content with all enhancements applied\n * - `frontmatter` (object): Parsed YAML frontmatter as JavaScript object\n * - `toc` (array): Hierarchical table of contents entries\n * - `render` (function): Client-side render function for dynamic updates\n *\n * ## Markdown Features Supported\n *\n * The supported features depend on parser options:\n * - **Commonmark**: Headings, paragraphs, lists, code blocks, links, images\n * - **GFM Extensions**: Tables, task lists, strikethrough, autolinks\n * - **Enhancements**: Syntax highlighting, Mermaid diagrams, TOC generation\n * - **Metadata**: YAML frontmatter parsing\n *\n * ## Performance\n *\n * Uses Rust-based parsing via NAPI bindings for optimal performance. Falls back\n * gracefully if Rust bindings are unavailable.\n *\n * @param source - Raw Markdown source code (may include YAML frontmatter)\n * @param filePath - File path for source attribution and relative link resolution\n * @param options - Resolved plugin options controlling transformation behavior\n *\n * @returns Promise resolving to transformation result with HTML and metadata\n *\n * @throws Error if NAPI bindings are unavailable (can be handled gracefully)\n *\n * @example\n * ```typescript\n * import { transformMarkdown } from './transform';\n * import { resolveOptions } from './index';\n *\n * // Transform a Markdown file with YAML frontmatter\n * const markdown = `---\n * title: Getting Started\n * author: john\n * ---\n *\n * # Getting Started\n *\n * Welcome! This guide explains [transformMarkdown] function.\n *\n * ## Installation\n *\n * \\`\\`\\`bash\n * npm install @ox-content/vite-plugin\n * \\`\\`\\`\n * `;\n *\n * const options = resolveOptions({\n * highlight: true,\n * toc: true,\n * gfm: true,\n * mermaid: true,\n * });\n *\n * const result = await transformMarkdown(markdown, 'docs/getting-started.md', options);\n *\n * // Generated module exports\n * console.log(result.html); // Rendered HTML with syntax highlighting\n * console.log(result.frontmatter); // { title: 'Getting Started', author: 'john' }\n * console.log(result.toc); // [{ depth: 1, text: 'Getting Started', ... }]\n * console.log(result.code); // ES module export statement\n * ```\n */\n/**\n * SSG-specific transform options.\n */\nexport interface SsgTransformOptions {\n /** Convert `.md` links to `.html` links */\n convertMdLinks?: boolean;\n /** Base URL for absolute link conversion */\n baseUrl?: string;\n /** Source file path for relative link resolution */\n sourcePath?: string;\n}\n\nexport async function transformMarkdown(\n source: string,\n filePath: string,\n options: ResolvedOptions,\n ssgOptions?: SsgTransformOptions,\n): Promise<TransformResult> {\n const napi = await loadNapiBindings();\n\n if (!napi) {\n throw new Error(\n \"[ox-content] NAPI bindings not available. Please ensure @ox-content/napi is built.\",\n );\n }\n\n // Use Rust-based transformation, including frontmatter preparation.\n runCodeBlockLint(source, napi, options);\n await runCodeBlockTypecheck(source, options);\n\n const result = napi.transform(source, {\n gfm: options.gfm,\n mdx: resolveMdxForFilePath(filePath, options.mdx),\n footnotes: options.footnotes,\n taskLists: options.taskLists,\n tables: options.tables,\n strikethrough: options.strikethrough,\n autolinks: options.autolinks,\n autolinkUrls: options.autolinks,\n frontmatter: options.frontmatter,\n tocMaxDepth: options.tocMaxDepth,\n convertMdLinks: ssgOptions?.convertMdLinks,\n baseUrl: ssgOptions?.baseUrl,\n sourcePath: ssgOptions?.sourcePath ?? filePath,\n codeAnnotations: options.codeAnnotations?.enabled ?? false,\n codeAnnotationMetaKey: options.codeAnnotations?.metaKey ?? \"annotate\",\n codeAnnotationSyntax: options.codeAnnotations?.notation ?? \"attribute\",\n codeAnnotationDefaultLineNumbers: options.codeAnnotations?.defaultLineNumbers ?? false,\n wikiLinks: options.wikiLinks?.enabled\n ? {\n enabled: true,\n baseUrl: options.wikiLinks.baseUrl,\n }\n : undefined,\n emojiShortcodes: options.emojiShortcodes?.enabled\n ? {\n enabled: true,\n custom: options.emojiShortcodes.custom,\n }\n : undefined,\n attributes: options.attrs?.enabled ? { enabled: true } : undefined,\n badges: options.badges?.enabled ? { enabled: true } : undefined,\n containers: options.containers?.enabled\n ? {\n enabled: true,\n types: options.containers.types,\n }\n : undefined,\n images: options.images?.enabled\n ? {\n enabled: true,\n lazy: options.images.lazy,\n }\n : undefined,\n cjkEmphasis: options.cjkEmphasis ?? false,\n codeImports: options.codeImports?.enabled\n ? {\n enabled: true,\n rootDir: options.codeImports.rootDir,\n }\n : undefined,\n includes: options.includes?.enabled\n ? {\n enabled: true,\n rootDir: options.includes.rootDir,\n }\n : undefined,\n cards: options.cards?.enabled ? { enabled: true } : undefined,\n steps: options.steps?.enabled ? { enabled: true } : undefined,\n fileTree: options.fileTree?.enabled ? { enabled: true } : undefined,\n // Sanitize once at the end of the JS pipeline so opt-in embeds can be\n // expanded before the allow-list is applied.\n sanitize: undefined,\n editThisPage: options.editThisPage?.enabled\n ? {\n enabled: true,\n repoUrl: options.editThisPage.repoUrl,\n branch: options.editThisPage.branch,\n rootDir: options.editThisPage.rootDir,\n label: options.editThisPage.label,\n }\n : undefined,\n math: isMathEnabled(options.math),\n });\n\n if (result.errors.length > 0) {\n console.warn(\"[ox-content] Transform warnings:\", result.errors);\n }\n\n // Normalize before the first rehype pass (highlighting), which would\n // otherwise reparse a self-closing embed tag as an unclosed element.\n let html = normalizeSelfClosingEmbeds(result.html);\n const frontmatter = parseFrontmatterJson(result.frontmatter);\n\n const toc = options.toc ? result.toc.map(normalizeTocEntry) : [];\n\n // Transform mermaid diagrams before highlighting to avoid entity re-encoding\n if (options.mermaid) {\n html = await transformMermaidStatic(html);\n }\n\n // Protect mermaid SVGs from rehype processing (which corrupts <br /> in foreignObjects)\n const { html: protectedHtml, svgs } = protectMermaidSvgs(html);\n html = protectedHtml;\n\n // Apply syntax highlighting if enabled\n if (options.highlight) {\n // The native document pass handles the whole page without an HTML parser\n // in the loop. Languages with no native grammar stay as the original\n // `<pre><code>`. Only markup the pass cannot read — where a text scan and\n // a real HTML parser would disagree — falls back to a native-only\n // per-block walk.\n const native = await highlightDocumentNatively(html);\n\n if (native && native.skipped.length === 0) {\n html = native.html;\n } else {\n const originalHtml = html;\n const highlightedHtml = await highlightCode(html);\n html = napi.mergeHighlightedCodeBlocks(originalHtml, highlightedHtml);\n }\n }\n\n // Render static built-in embeds while Mermaid SVG placeholders are protected.\n html = await transformBuiltinEmbeds(\n html,\n options.embeds ?? {\n github: {},\n openGraph: {},\n },\n );\n\n // Restore protected SVGs\n html = restoreMermaidSvgs(html, svgs);\n\n if (options.sanitize?.enabled) {\n html = napi.sanitizeHtml(html, toJsSanitizeOptions(options.sanitize));\n }\n\n // Generate JavaScript module code\n const code = generateModuleCode(html, frontmatter, toc, filePath, options);\n\n return {\n code,\n html,\n frontmatter,\n toc,\n };\n}\n\nasync function runCodeBlockTypecheck(source: string, options: ResolvedOptions): Promise<void> {\n const typecheck = options.codeBlockTypecheck;\n if (!typecheck?.enabled || !source.includes(\"```\")) {\n return;\n }\n\n const diagnostics = await typecheckCodeBlocks(source, {\n languages: typecheck.languages,\n requireMeta: typecheck.requireMeta,\n tsgoCommand: typecheck.tsgoCommand,\n });\n if (diagnostics.length === 0) {\n return;\n }\n\n const message = diagnostics\n .slice(0, 3)\n .map((diagnostic) => `${diagnostic.ruleId} at ${diagnostic.line}: ${diagnostic.message}`)\n .join(\"\\n\");\n if (typecheck.mode === \"error\") {\n throw new Error(`[ox-content] Code block type-checking failed:\\n${message}`);\n }\n console.warn(`[ox-content] Code block type-checking warnings:\\n${message}`);\n}\n\nfunction runCodeBlockLint(source: string, napi: NapiBindings, options: ResolvedOptions): void {\n const lint = options.codeBlockLint;\n if (!lint?.enabled || !source.includes(\"```\")) {\n return;\n }\n\n const diagnostics = napi.lintCodeBlocks(source, {\n enabled: true,\n languages: lint.languages,\n requireLanguage: lint.requireLanguage,\n trailingSpaces: lint.trailingSpaces,\n });\n if (diagnostics.length === 0) {\n return;\n }\n\n const message = diagnostics\n .slice(0, 5)\n .map((diagnostic) => {\n return `${diagnostic.ruleId} at ${diagnostic.line}:${diagnostic.column} ${diagnostic.message}`;\n })\n .join(\"\\n\");\n if (lint.mode === \"error\") {\n throw new Error(`[ox-content] Code block lint failed:\\n${message}`);\n }\n console.warn(`[ox-content] Code block lint warnings:\\n${message}`);\n}\n\nfunction toJsSanitizeOptions(options: ResolvedOptions[\"sanitize\"]): JsSanitizeOptions {\n return {\n enabled: true,\n allowedTags: options.allowedTags,\n allowedAttributes: options.allowedAttributes,\n allowedUrlSchemes: options.allowedUrlSchemes,\n };\n}\n\nfunction parseFrontmatterJson(json: string): Record<string, unknown> {\n if (!json) {\n return {};\n }\n\n try {\n const value = JSON.parse(json);\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction normalizeTocEntry(entry: {\n depth: number;\n text: string;\n slug: string;\n children?: TocEntry[];\n}): TocEntry {\n return {\n depth: entry.depth,\n text: entry.text,\n slug: entry.slug,\n children: (entry.children ?? []).map(normalizeTocEntry),\n };\n}\n\n/**\n * Generates the JavaScript module code.\n */\nfunction generateModuleCode(\n html: string,\n frontmatter: Record<string, unknown>,\n toc: TocEntry[],\n filePath: string,\n _options: ResolvedOptions,\n): string {\n const htmlJson = JSON.stringify(html);\n const frontmatterJson = JSON.stringify(frontmatter);\n const tocJson = JSON.stringify(toc);\n\n return `\n// Generated by @ox-content/vite-plugin\n// Source: ${filePath}\n\n/**\n * Rendered HTML content.\n */\nexport const html = ${htmlJson};\n\n/**\n * Parsed frontmatter.\n */\nexport const frontmatter = ${frontmatterJson};\n\n/**\n * Table of contents.\n */\nexport const toc = ${tocJson};\n\n/**\n * Default export with all data.\n */\nexport default {\n html,\n frontmatter,\n toc,\n};\n\n// HMR support\nif (import.meta.hot) {\n import.meta.hot.accept((newModule) => {\n if (newModule) {\n // Trigger re-render with new content\n import.meta.hot.invalidate();\n }\n });\n}\n`;\n}\n\n/**\n * Extracts imports from Markdown content.\n *\n * Supports importing components for interactive islands.\n */\nexport function extractImports(content: string): string[] {\n const importRegex = /^import\\s+.+\\s+from\\s+['\"](.+)['\"]/gm;\n const imports: string[] = [];\n let match;\n\n while ((match = importRegex.exec(content)) !== null) {\n imports.push(match[1]);\n }\n\n return imports;\n}\n\n/**\n * Generates an OG image SVG using the Rust-based generator.\n *\n * This function uses the Rust NAPI bindings to generate SVG-based\n * OG images for social media previews. The SVG can be served directly\n * or converted to PNG/JPEG for broader compatibility.\n *\n * In the future, custom JS templates can be provided to override\n * the default Rust-based template.\n *\n * @param data - OG image data (title, description, etc.)\n * @param config - Optional OG image configuration\n * @returns SVG string or null if NAPI bindings are unavailable\n */\nexport async function generateOgImageSvg(\n data: OgImageData,\n config?: OgImageConfig,\n): Promise<string | null> {\n const napi = await loadNapiBindings();\n if (!napi) {\n return null;\n }\n\n // Convert config to NAPI format (camelCase to snake_case)\n const napiConfig = config\n ? {\n width: config.width,\n height: config.height,\n backgroundColor: config.backgroundColor,\n textColor: config.textColor,\n titleFontSize: config.titleFontSize,\n descriptionFontSize: config.descriptionFontSize,\n }\n : undefined;\n\n return napi.generateOgImageSvg(data, napiConfig);\n}\n\nfunction isMathEnabled(math: boolean | { enabled?: boolean } | undefined): boolean {\n if (math === true) return true;\n if (math === false || math == null) return false;\n return math.enabled !== false;\n}\n","/**\n * Source Documentation Extraction and Generation\n *\n * This module provides comprehensive tools for extracting JSDoc/TSDoc comments\n * from TypeScript/JavaScript source files and automatically generating Markdown\n * documentation.\n *\n * ## Features\n *\n * - **Automatic Extraction**: Parses JSDoc comments from functions, classes, interfaces, and types\n * - **Flexible Filtering**: Include/exclude patterns for selective documentation\n * - **Markdown Generation**: Converts extracted docs to organized Markdown files\n * - **Navigation Generation**: Auto-generates sidebar navigation metadata\n * - **GitHub Links**: Includes clickable links to source code on GitHub\n *\n * ## Supported JSDoc Tags\n *\n * - `@param {type} name - description` - Function parameter documentation\n * - `@returns {type} description` - Return value documentation\n * - `@example` - Code examples (multi-line blocks)\n * - `@private` - Mark item as private (excluded from docs if private=false)\n * - `@default value` - Default parameter value\n * - Custom tags are preserved in the `tags` field\n *\n * ## Usage Flow\n *\n * 1. Call `extractDocs()` to parse source files\n * 2. Call `generateMarkdown()` to create Markdown content\n * 3. Call `writeDocs()` to write files to output directory\n * 4. Generated nav.ts can be imported for sidebar navigation\n *\n * @example\n * ```typescript\n * import { extractDocs, generateMarkdown, writeDocs } from './docs';\n *\n * const docsOptions = {\n * enabled: true,\n * src: ['./src'],\n * out: './docs/api',\n * include: ['**\\/*.ts'],\n * exclude: ['**\\/*.test.ts'],\n * groupBy: 'file',\n * githubUrl: 'https://github.com/user/project',\n * };\n *\n * const extracted = await extractDocs(['./src'], docsOptions);\n * const markdown = generateMarkdown(extracted, docsOptions);\n * await writeDocs(markdown, './docs/api', extracted, docsOptions);\n * ```\n */\n\nimport { readFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport type {\n ResolvedDocsOptions,\n ExtractedDocs,\n DocEntry,\n ResolvedDocsEntryPoint,\n DocsOptions,\n} from \"./types\";\nimport { importNapiModule, importNapiModuleSync } from \"./napi\";\n\ntype NapiMarkdownTag = { tag: string; value: string };\n\nconst DEFAULT_DOCS_INCLUDE = [\n \"**/*.ts\",\n \"**/*.tsx\",\n \"**/*.js\",\n \"**/*.jsx\",\n \"**/*.mts\",\n \"**/*.mjs\",\n \"**/*.cts\",\n \"**/*.cjs\",\n];\n\n/**\n * Extracts JSDoc documentation from source files in specified directories.\n *\n * This function recursively searches directories for source files matching\n * the include/exclude patterns, then extracts all documented items (functions,\n * classes, interfaces, types) from those files.\n *\n * ## Process\n *\n * 1. **File Discovery**: Recursively walks directories, applying filters\n * 2. **File Reading**: Loads each matching file's content\n * 3. **JSDoc Extraction**: Parses JSDoc comments using the native parser\n * 4. **Declaration Matching**: Pairs JSDoc comments with source declarations\n * 5. **Result Collection**: Aggregates extracted documentation by file\n *\n * ## Include/Exclude Patterns\n *\n * Patterns support:\n * - `**` - Match any directory structure\n * - `*` - Match any filename\n * - Standard glob patterns (e.g., `**\\/*.test.ts`)\n *\n * ## Performance Considerations\n *\n * - Uses filesystem I/O which can be slow for large codebases\n * - Consider using more specific include patterns to reduce file scanning\n * - Results are not cached; call once per build/dev session\n *\n * @param srcDirs - Array of source directory paths to scan\n * @param options - Documentation extraction options (filters, grouping, etc.)\n *\n * @returns Promise resolving to array of extracted documentation by file.\n * Each ExtractedDocs object contains file path and array of DocEntry items.\n *\n * @example\n * ```typescript\n * const docs = await extractDocs(\n * ['./packages/vite-plugin/src'],\n * {\n * enabled: true,\n * src: [],\n * out: 'docs',\n * include: ['**\\/*.ts'],\n * exclude: ['**\\/*.test.ts', '**\\/*.spec.ts'],\n * format: 'markdown',\n * private: false,\n * toc: true,\n * groupBy: 'file',\n * generateNav: true,\n * }\n * );\n *\n * // Returns:\n * // [\n * // {\n * // file: '/path/to/transform.ts',\n * // entries: [\n * // { name: 'transformMarkdown', kind: 'function', ... },\n * // { name: 'loadNapiBindings', kind: 'function', ... },\n * // ]\n * // },\n * // ...\n * // ]\n * ```\n */\nexport async function extractDocs(\n srcDirs: string[],\n options: ResolvedDocsOptions,\n): Promise<ExtractedDocs[]> {\n const napi = await importNapiModule();\n\n if (options.entryPoints?.length) {\n const extractDocsFromEntryPoints = (\n napi as {\n extractDocsFromEntryPoints?: (\n entryPoints: ResolvedDocsEntryPoint[],\n options?: {\n root?: string;\n private?: boolean;\n internal?: boolean;\n typeParameters?: boolean;\n },\n ) => Array<{\n file: string;\n description?: string;\n sourcePath?: string;\n examples?: string[];\n tags?: NapiMarkdownTag[];\n entries: DocEntry[];\n }>;\n }\n ).extractDocsFromEntryPoints;\n\n if (!extractDocsFromEntryPoints) {\n throw new Error(\n \"[ox-content] extractDocsFromEntryPoints is not available from @ox-content/napi.\",\n );\n }\n\n return extractDocsFromEntryPoints(options.entryPoints, {\n root: process.cwd(),\n private: options.private,\n internal: options.internal,\n typeParameters: options.typeParameters,\n }).map((doc) => ({\n file: doc.file,\n description: doc.description,\n sourcePath: doc.sourcePath,\n examples: doc.examples,\n tags: toTagRecord(doc.tags),\n entries: doc.entries,\n }));\n }\n\n const extractDocsFromDirectories = (\n napi as {\n extractDocsFromDirectories?: (\n srcDirs: string[],\n include: string[],\n exclude: string[],\n includePrivate?: boolean,\n includeInternal?: boolean,\n typeParameters?: boolean,\n ) => Array<{ file: string; entries: DocEntry[] }>;\n }\n ).extractDocsFromDirectories;\n\n if (!extractDocsFromDirectories) {\n throw new Error(\n \"[ox-content] extractDocsFromDirectories is not available from @ox-content/napi.\",\n );\n }\n\n return extractDocsFromDirectories(\n srcDirs,\n options.include,\n options.exclude,\n options.private,\n options.internal,\n options.typeParameters,\n ).map((doc) => ({ file: doc.file, entries: doc.entries }));\n}\n\n/**\n * Generates Markdown documentation from extracted docs.\n */\nexport function generateMarkdown(\n docs: ExtractedDocs[],\n options: ResolvedDocsOptions,\n): Record<string, string> {\n const napi = importNapiModuleSync();\n\n if (typeof napi.generateDocsMarkdown !== \"function\") {\n throw new Error(\n \"[ox-content] generateDocsMarkdown is not available from @ox-content/napi. Please rebuild the NAPI package.\",\n );\n }\n\n return napi.generateDocsMarkdown(toRustDocsModules(docs), {\n groupBy: options.groupBy,\n githubUrl: options.githubUrl,\n linkStyle: options.linkStyle,\n basePath: options.basePath,\n pathStrategy: options.pathStrategy,\n renderStyle: options.renderStyle,\n indexFormat: options.indexFormat,\n parametersFormat: options.parametersFormat,\n interfacePropertiesFormat: options.interfacePropertiesFormat,\n classPropertiesFormat: options.classPropertiesFormat,\n typeAliasPropertiesFormat: options.typeAliasPropertiesFormat,\n enumMembersFormat: options.enumMembersFormat,\n propertyMembersFormat: options.propertyMembersFormat,\n typeDeclarationFormat: options.typeDeclarationFormat,\n renderStats: options.renderStats,\n renderGeneratedBy: options.renderGeneratedBy,\n groupOrder: options.groupOrder,\n sort: options.sort,\n sortEntryPoints: options.sortEntryPoints,\n kindSortOrder: options.kindSortOrder,\n singleEntryRoot: options.singleEntryRoot,\n });\n}\n\n/**\n * Writes generated documentation to the output directory.\n */\nexport async function writeDocs(\n docs: Record<string, string>,\n outDir: string,\n extractedDocs?: ExtractedDocs[],\n options?: ResolvedDocsOptions,\n): Promise<void> {\n const napi = importNapiModuleSync();\n\n if (typeof napi.writeGeneratedDocs !== \"function\") {\n throw new Error(\n \"[ox-content] writeGeneratedDocs is not available from @ox-content/napi. Please rebuild the NAPI package.\",\n );\n }\n\n napi.writeGeneratedDocs(\n docs,\n outDir,\n extractedDocs ? toRustDocsModules(extractedDocs) : undefined,\n {\n generateNav: options?.generateNav ?? false,\n groupBy: options?.groupBy ?? \"file\",\n generatedAt: existingGeneratedAt(outDir) ?? new Date().toISOString(),\n basePath: options?.basePath,\n pathStrategy: options?.pathStrategy,\n groupOrder: options?.groupOrder,\n sort: options?.sort,\n sortEntryPoints: options?.sortEntryPoints,\n kindSortOrder: options?.kindSortOrder,\n singleEntryRoot: options?.singleEntryRoot,\n },\n );\n}\n\n/** Keep `docs.json`'s timestamp stable across regenerations of the same tree. */\nfunction existingGeneratedAt(outDir: string): string | undefined {\n try {\n const parsed = JSON.parse(readFileSync(path.join(outDir, \"docs.json\"), \"utf8\")) as {\n generatedAt?: unknown;\n };\n return typeof parsed.generatedAt === \"string\" && parsed.generatedAt.length > 0\n ? parsed.generatedAt\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function toRustDocsModules(docs: ExtractedDocs[]) {\n return docs.map((doc) => ({\n file: doc.file,\n description: doc.description,\n sourcePath: doc.sourcePath,\n examples: doc.examples,\n tags: doc.tags ? Object.entries(doc.tags).map(([tag, value]) => ({ tag, value })) : undefined,\n entries: doc.entries.map((entry) => ({\n name: entry.name,\n kind: entry.kind,\n description: entry.description,\n params: entry.params,\n returns: entry.returns,\n examples: entry.examples,\n tags: entry.tags\n ? Object.entries(entry.tags).map(([tag, value]) => ({ tag, value }))\n : undefined,\n private: entry.private ?? false,\n file: entry.file,\n line: entry.line,\n endLine: entry.endLine,\n signature: entry.signature,\n members: entry.members,\n })),\n }));\n}\n\nfunction toTagRecord(tags: NapiMarkdownTag[] | undefined) {\n if (!tags?.length) {\n return undefined;\n }\n return Object.fromEntries(tags.map(({ tag, value }) => [tag, value]));\n}\n\n/**\n * Resolves docs options with defaults.\n */\nexport function resolveDocsOptions(options: false): false;\nexport function resolveDocsOptions(options?: DocsOptions): ResolvedDocsOptions;\nexport function resolveDocsOptions(\n options: DocsOptions | false | undefined,\n): ResolvedDocsOptions | false;\nexport function resolveDocsOptions(\n options: DocsOptions | false | undefined,\n): ResolvedDocsOptions | false {\n if (options === false) {\n return false;\n }\n\n const opts = options || {};\n\n return {\n enabled: opts.enabled ?? true,\n src: opts.src ?? [\"./src\"],\n out: opts.out ?? \"docs/api\",\n include: opts.include ?? DEFAULT_DOCS_INCLUDE,\n exclude: opts.exclude ?? [\"**/*.test.*\", \"**/*.spec.*\", \"node_modules\"],\n entryPoints: opts.entryPoints?.map((entryPoint) =>\n typeof entryPoint === \"string\" ? { path: entryPoint } : entryPoint,\n ),\n format: opts.format ?? \"markdown\",\n private: opts.private ?? false,\n internal: opts.internal ?? false,\n toc: false,\n groupBy: opts.groupBy ?? \"file\",\n githubUrl: opts.githubUrl,\n linkStyle: opts.linkStyle ?? \"markdown\",\n basePath: opts.basePath,\n pathStrategy: opts.pathStrategy ?? \"flat\",\n renderStyle: opts.renderStyle ?? \"html\",\n indexFormat: opts.indexFormat ?? \"none\",\n parametersFormat: opts.parametersFormat ?? \"none\",\n interfacePropertiesFormat: opts.interfacePropertiesFormat ?? \"none\",\n classPropertiesFormat: opts.classPropertiesFormat ?? \"none\",\n typeAliasPropertiesFormat: opts.typeAliasPropertiesFormat ?? \"none\",\n enumMembersFormat: opts.enumMembersFormat ?? \"none\",\n propertyMembersFormat: opts.propertyMembersFormat ?? \"none\",\n typeDeclarationFormat: opts.typeDeclarationFormat ?? \"none\",\n typeParameters: opts.typeParameters ?? false,\n renderStats: opts.renderStats ?? true,\n renderGeneratedBy: opts.renderGeneratedBy ?? true,\n groupOrder: opts.groupOrder,\n sort: opts.sort,\n sortEntryPoints: opts.sortEntryPoints ?? true,\n kindSortOrder: opts.kindSortOrder,\n singleEntryRoot: opts.singleEntryRoot ?? \"preserve\",\n generateNav: opts.generateNav ?? true,\n };\n}\n","/**\n * HTML → PNG renderer using Chromium screenshots via Playwright.\n */\n\nimport * as path from \"path\";\nimport type { Page } from \"playwright\";\n\n/**\n * Wraps template HTML in a minimal document with viewport locked to given dimensions.\n */\nfunction wrapHtml(bodyHtml: string, width: number, height: number, useBaseUrl: boolean): string {\n const baseTag = useBaseUrl ? `\\n<base href=\"http://localhost/\">` : \"\";\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">${baseTag}\n<style>\n* { margin: 0; padding: 0; box-sizing: border-box; }\nhtml, body { width: ${width}px; height: ${height}px; overflow: hidden; }\n</style>\n</head>\n<body>${bodyHtml}</body>\n</html>`;\n}\n\n/**\n * Renders an HTML string to a PNG buffer using Chromium.\n *\n * @param page - Playwright page instance\n * @param html - HTML string from template function\n * @param width - Image width\n * @param height - Image height\n * @param publicDir - Optional public directory for serving local assets (images, fonts, etc.)\n * @returns PNG buffer\n */\nexport async function renderHtmlToPng(\n page: Page,\n html: string,\n width: number,\n height: number,\n publicDir?: string,\n): Promise<Buffer> {\n await page.setViewportSize({ width, height });\n\n // Serve local assets from the public directory\n if (publicDir) {\n const fs = await import(\"fs/promises\");\n await page.route(\"**/*\", async (route) => {\n const url = new URL(route.request().url());\n // Only intercept paths that look like local assets (not data: or blob:)\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n await route.continue();\n return;\n }\n const filePath = path.join(publicDir, url.pathname);\n try {\n const body = await fs.readFile(filePath);\n const ext = path.extname(filePath).toLowerCase();\n const mimeTypes: Record<string, string> = {\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".css\": \"text/css\",\n \".js\": \"application/javascript\",\n };\n await route.fulfill({\n body,\n contentType: mimeTypes[ext] || \"application/octet-stream\",\n });\n } catch {\n await route.continue();\n }\n });\n }\n\n const fullHtml = wrapHtml(html, width, height, !!publicDir);\n await page.setContent(fullHtml, { waitUntil: \"networkidle\" });\n\n const screenshot = await page.screenshot({\n type: \"png\",\n clip: { x: 0, y: 0, width, height },\n });\n\n return Buffer.from(screenshot);\n}\n","/**\n * Chromium browser session with automatic cleanup via Explicit Resource Management.\n *\n * Usage:\n * await using session = await openBrowser();\n * const png = await session.renderPage(html, 1200, 630);\n * // browser.close() is called automatically when session goes out of scope\n */\n\nimport type { Page } from \"playwright\";\nimport { renderHtmlToPng } from \"./renderer\";\n\nconst PLAYWRIGHT_BROWSER_INSTALL_HINT =\n \"Install Playwright browsers with `npx playwright install chromium` to enable OG image generation.\";\n\nlet chromiumUnavailableWarned = false;\n\n/**\n * A browser session that can render HTML pages to PNG.\n * Implements AsyncDisposable for automatic cleanup via `await using`.\n */\nexport interface OgBrowserSession extends AsyncDisposable {\n renderPage(html: string, width: number, height: number, publicDir?: string): Promise<Buffer>;\n}\n\n/**\n * Opens a Chromium browser and returns a session for rendering OG images.\n * Returns null if Playwright/Chromium is not available.\n *\n * The session implements AsyncDisposable — use `await using` for automatic cleanup:\n * ```ts\n * await using session = await openBrowser();\n * if (!session) return;\n * const png = await session.renderPage(html, 1200, 630);\n * ```\n */\nexport async function openBrowser(): Promise<OgBrowserSession | null> {\n try {\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch({\n headless: true,\n args: [\n \"--no-sandbox\",\n \"--disable-setuid-sandbox\",\n \"--disable-dev-shm-usage\",\n \"--disable-gpu\",\n ],\n });\n\n return {\n async renderPage(\n html: string,\n width: number,\n height: number,\n publicDir?: string,\n ): Promise<Buffer> {\n const page: Page = await browser.newPage();\n try {\n return await renderHtmlToPng(page, html, width, height, publicDir);\n } finally {\n await page.close();\n }\n },\n\n async [Symbol.asyncDispose]() {\n try {\n await browser.close();\n } catch {\n // Ignore close errors\n }\n },\n };\n } catch (err) {\n warnChromiumUnavailableOnce(err);\n return null;\n }\n}\n\nfunction warnChromiumUnavailableOnce(err: unknown): void {\n if (chromiumUnavailableWarned) {\n return;\n }\n\n chromiumUnavailableWarned = true;\n console.warn(\n `[ox-content:og-image] Chromium not available, skipping OG image generation. ${formatChromiumUnavailableDetail(\n err,\n )}`,\n );\n}\n\nfunction formatChromiumUnavailableDetail(err: unknown): string {\n const message = err instanceof Error ? err.message : String(err);\n\n if (\n message.includes(\"Executable doesn't exist\") ||\n message.includes(\"Please run the following command to download new browsers\")\n ) {\n return PLAYWRIGHT_BROWSER_INSTALL_HINT;\n }\n\n return (\n message\n .split(/\\r?\\n/)\n .find((line) => line.trim())\n ?.trim() ?? \"Unknown launch error.\"\n );\n}\n","/**\n * Default OG image template.\n *\n * Uses inline HTML/CSS for a flat, low-color brand card with title,\n * description, siteName, and tags. No external dependencies required.\n */\n\nimport type { OgImageTemplateFn, OgImageTemplateProps } from \"./types\";\n\n/**\n * Escapes HTML special characters.\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nfunction normalizeBrandValue(str: string): string {\n return str.replace(/\\s+/g, \"\").toLowerCase();\n}\n\nfunction renderWordmarkSvg(): string {\n return `<svg width=\"430\" height=\"102\" viewBox=\"0 0 270 64\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <linearGradient id=\"ogWordmarkGradient\" x1=\"286\" y1=\"10\" x2=\"320\" y2=\"54\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0%\" stop-color=\"#355cff\"/>\n <stop offset=\"100%\" stop-color=\"#74c7ff\"/>\n </linearGradient>\n </defs>\n <text\n x=\"2\"\n y=\"43\"\n fill=\"#eff6ff\"\n font-family=\"IBM Plex Sans, IBM Plex Mono, Avenir Next, Segoe UI, sans-serif\"\n font-size=\"34\"\n font-weight=\"700\"\n letter-spacing=\"-1.4\"\n >\n OXCONTENT\n </text>\n <text\n x=\"213\"\n y=\"43.5\"\n fill=\"#eff6ff\"\n font-family=\"IBM Plex Sans, IBM Plex Mono, Avenir Next, Segoe UI, sans-serif\"\n font-size=\"40\"\n font-weight=\"400\"\n >\n (\n </text>\n <g transform=\"translate(216 9) scale(0.089) rotate(-7 256 256)\">\n <path\n d=\"M161 96H286C298 96 309 101 318 110L352 144C361 153 366 164 366 176V386C366 399 355 410 342 410H161C148 410 138 399 138 386V120C138 107 148 96 161 96Z\"\n fill=\"url(#ogWordmarkGradient)\"\n />\n </g>\n <text\n x=\"252\"\n y=\"43.5\"\n fill=\"#eff6ff\"\n font-family=\"IBM Plex Sans, IBM Plex Mono, Avenir Next, Segoe UI, sans-serif\"\n font-size=\"40\"\n font-weight=\"400\"\n >\n )\n </text>\n</svg>`;\n}\n\n/**\n * Returns the built-in default template function.\n */\nexport function getDefaultTemplate(): OgImageTemplateFn {\n return function defaultTemplate(props: OgImageTemplateProps): string {\n const { title, description, siteName } = props;\n const rawBrand = siteName?.trim() ? siteName : \"Ox Content\";\n const isBrandCard = normalizeBrandValue(title) === normalizeBrandValue(rawBrand);\n\n const heroTitle = isBrandCard ? \"High-performance Markdown toolkit\" : title;\n const heroDescription = isBrandCard\n ? \"Rust-powered docs and high-performance Markdown tooling.\"\n : description && description.trim().length > 0\n ? description\n : \"Rust-powered docs and Markdown tooling.\";\n const descriptionHtml =\n heroDescription.trim().length > 0\n ? `<p style=\"max-width:760px;font-size:28px;color:#93a4c3;line-height:1.45;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;\">${escapeHtml(heroDescription)}</p>`\n : \"\";\n\n return `<div style=\"width:100%;height:100%;position:relative;overflow:hidden;box-sizing:border-box;padding:56px 64px 52px;background:#0b1220;font-family:'IBM Plex Sans','Avenir Next','Segoe UI',system-ui,sans-serif;color:#eff6ff;border:1px solid #223252;border-top:4px solid #4f6fae;\">\n <div style=\"position:relative;z-index:1;display:flex;flex-direction:column;height:100%;\">\n <div style=\"display:flex;align-items:flex-start;\">${renderWordmarkSvg()}</div>\n <div style=\"display:flex;flex-direction:column;justify-content:center;gap:24px;max-width:860px;flex:1;padding:22px 0 0;\">\n <h1 style=\"font-size:78px;font-weight:700;color:#eff6ff;line-height:1.02;letter-spacing:-0.055em;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;\">${escapeHtml(heroTitle)}</h1>\n ${descriptionHtml}\n </div>\n </div>\n</div>`;\n };\n}\n","/**\n * Content-hash based caching for OG images.\n *\n * Uses SHA256 of (template source + props + options) to determine\n * if a re-render is needed. Cache dir: .cache/og-images\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport * as crypto from \"crypto\";\n\n/**\n * Computes a cache key from template + props + options.\n */\nexport function computeCacheKey(\n templateSource: string,\n props: Record<string, unknown>,\n width: number,\n height: number,\n): string {\n const data = JSON.stringify({ templateSource, props, width, height });\n return crypto.createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\n/**\n * Checks if a cached PNG exists for the given key.\n * Returns the cached file path if found, null otherwise.\n */\nexport async function getCached(cacheDir: string, key: string): Promise<Buffer | null> {\n const filePath = path.join(cacheDir, `${key}.png`);\n try {\n return await fs.readFile(filePath);\n } catch {\n return null;\n }\n}\n\n/**\n * Writes a PNG buffer to the cache.\n */\nexport async function writeCache(cacheDir: string, key: string, png: Buffer): Promise<void> {\n await fs.mkdir(cacheDir, { recursive: true });\n const filePath = path.join(cacheDir, `${key}.png`);\n await fs.writeFile(filePath, png);\n}\n","/**\n * Public API for Chromium-based OG image generation.\n *\n * Orchestrates browser lifecycle, template resolution, caching,\n * and batch rendering with concurrency control.\n */\nimport * as path from \"path\";\nimport * as crypto from \"crypto\";\nimport { openBrowser } from \"./browser\";\nimport type { OgBrowserSession } from \"./browser\";\nimport { getDefaultTemplate } from \"./template\";\nimport { computeCacheKey, getCached, writeCache } from \"./cache\";\nimport type {\n OgImageOptions,\n ResolvedOgImageOptions,\n OgImageTemplateProps,\n OgImageTemplateFn,\n} from \"./types\";\n\nexport type {\n OgImageOptions,\n ResolvedOgImageOptions,\n OgImageTemplateProps,\n OgImageTemplateFn,\n} from \"./types\";\n\nexport type { OgBrowserSession } from \"./browser\";\n\n/**\n * Resolves user-provided OG image options with defaults.\n */\nexport function resolveOgImageOptions(options: OgImageOptions | undefined): ResolvedOgImageOptions {\n return {\n template: options?.template,\n vuePlugin: options?.vuePlugin ?? \"vitejs\",\n width: options?.width ?? 1200,\n height: options?.height ?? 630,\n cache: options?.cache ?? true,\n concurrency: options?.concurrency ?? 1,\n };\n}\n\n/**\n * A single page entry for batch OG image generation.\n */\nexport interface OgImagePageEntry {\n /** Props to pass to the template */\n props: OgImageTemplateProps;\n /** Absolute path to write the output PNG */\n outputPath: string;\n}\n\n/**\n * Result of OG image generation for a single page.\n */\nexport interface OgImageResult {\n outputPath: string;\n cached: boolean;\n error?: string;\n}\n\n/**\n * Resolves the template function from options.\n *\n * Dispatches by file extension:\n * - `.vue` → Vue SFC (SSR via vue/server-renderer)\n * - `.svelte` → Svelte SFC (SSR via svelte/server)\n * - `.tsx`/`.jsx` → React Server Component (SSR via react-dom/server)\n * - others → TypeScript template (direct function export)\n */\nasync function resolveTemplate(\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageTemplateFn> {\n if (!options.template) {\n return getDefaultTemplate();\n }\n\n const templatePath = path.resolve(root, options.template);\n\n // Verify file exists\n const fs = await import(\"fs/promises\");\n try {\n await fs.access(templatePath);\n } catch {\n throw new Error(`[ox-content:og-image] Template file not found: ${templatePath}`);\n }\n\n const ext = path.extname(templatePath).toLowerCase();\n\n switch (ext) {\n case \".vue\":\n return resolveVueTemplate(templatePath, options, root);\n case \".svelte\":\n return resolveSvelteTemplate(templatePath, root);\n case \".tsx\":\n case \".jsx\":\n return resolveReactTemplate(templatePath, root);\n default:\n return resolveTsTemplate(templatePath, options, root);\n }\n}\n\n/**\n * Matches this package and every subpath it exports.\n *\n * A template's natural runtime is whatever renders it, and for the\n * framework-less kinds that is this package: `renderToString`, `raw`, `when`\n * and `each` live at its root, and the JSX runtime under `./jsx-runtime`.\n * Inlining them instead drags the entire plugin — chokidar, fsevents and all\n * — into the template bundle, which is what made importing it fail outright.\n */\nconst OX_CONTENT_PACKAGE = /^@ox-content\\/vite-plugin(\\/.*)?$/;\n\n/**\n * Whether `id` is a bare specifier, and so resolvable at runtime rather than\n * something the template bundle has to inline.\n *\n * Template bundles are written to `<root>/.cache/og-images/` and imported\n * from there, so Node resolves anything left external against the project's\n * own `node_modules`. Relative and absolute imports still bundle, which is\n * what a template actually needs — its own components travel with it.\n */\nexport function isBareSpecifier(id: string): boolean {\n if (id.startsWith(\".\") || id.startsWith(\"/\") || id.startsWith(\"\\0\")) {\n return false;\n }\n // Windows drive letters and rolldown's virtual-module prefixes.\n return !/^[a-zA-Z]:[\\\\/]/.test(id);\n}\n\n/**\n * Rolldown input options for a `.ts` template bundle.\n *\n * A `.ts` template is the framework-less kind, so it has no single runtime to\n * externalize the way the `.vue`, `.svelte` and `.tsx` paths do — anything\n * from `node_modules` is better resolved at import time than inlined. Nothing\n * on this path has a compiler plugin, so nothing here needed bundling to be\n * loadable in the first place.\n */\nexport function tsTemplateBundleOptions(templatePath: string) {\n return {\n input: templatePath,\n platform: \"node\" as const,\n external: (id: string) => isBareSpecifier(id),\n };\n}\n\n/**\n * Resolves a plain TypeScript template (existing behavior).\n */\nasync function resolveTsTemplate(\n templatePath: string,\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template.mjs\");\n\n const bundle = await rolldown(tsTemplateBundleOptions(templatePath));\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const templateFn = mod.default;\n\n if (typeof templateFn !== \"function\") {\n throw new Error(\n `[ox-content:og-image] Template must default-export a function: ${options.template}`,\n );\n }\n\n return templateFn as OgImageTemplateFn;\n}\n\n/**\n * Resolves a Vue SFC template via SSR.\n *\n * Compiles the SFC with @vue/compiler-sfc (or @vizejs/vite-plugin),\n * bundles with rolldown, then wraps with createSSRApp + renderToString.\n */\nasync function resolveVueTemplate(\n templatePath: string,\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template_vue.mjs\");\n\n const plugins =\n options.vuePlugin === \"vizejs\" ? await getVizejsPlugin() : [createVueCompilerPlugin()];\n\n const bundle = await rolldown({\n input: templatePath,\n platform: \"node\",\n external: [\"vue\", \"vue/server-renderer\", OX_CONTENT_PACKAGE],\n plugins,\n });\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const Component = mod.default;\n\n if (!Component) {\n throw new Error(\n `[ox-content:og-image] Vue template must have a default export: ${templatePath}`,\n );\n }\n\n // Extract CSS from SFC <style> blocks (Vue SSR does not include styles).\n // OG image templates render in complete isolation, so scoping is unnecessary.\n // We use raw CSS content to avoid scope ID mismatches between compilers\n // (e.g., vizejs and @vue/compiler-sfc may produce different scope hashes).\n let extractedCss = ((mod as Record<string, unknown>).__vize_css__ as string) || \"\";\n if (!extractedCss) {\n try {\n let compilerSfc: typeof import(\"@vue/compiler-sfc\");\n try {\n compilerSfc = await import(\"@vue/compiler-sfc\");\n } catch {\n compilerSfc = null as never;\n }\n if (compilerSfc) {\n const sfcSource = await fs.readFile(templatePath, \"utf-8\");\n const { descriptor } = compilerSfc.parse(sfcSource, { filename: templatePath });\n for (const style of descriptor.styles) {\n extractedCss += style.content;\n }\n }\n } catch {\n // CSS extraction is best-effort\n }\n }\n\n // Import Vue SSR utilities\n const { createSSRApp } = await import(\"vue\");\n const { renderToString } = await import(\"vue/server-renderer\");\n\n return async (props) => {\n const app = createSSRApp(Component, props);\n const html = await renderToString(app);\n if (extractedCss) {\n return `<style>${extractedCss}</style>${html}`;\n }\n return html;\n };\n}\n\n/**\n * Creates a rolldown plugin that compiles Vue SFCs using @vue/compiler-sfc.\n */\nfunction createVueCompilerPlugin(): import(\"rolldown\").Plugin {\n return {\n name: \"ox-content-vue-sfc\",\n async transform(code, id) {\n if (!id.endsWith(\".vue\")) return null;\n\n let compilerSfc: typeof import(\"@vue/compiler-sfc\");\n try {\n compilerSfc = await import(\"@vue/compiler-sfc\");\n } catch {\n throw new Error(\n \"[ox-content:og-image] @vue/compiler-sfc is required for .vue templates. \" +\n \"Install it with: pnpm add -D @vue/compiler-sfc\",\n );\n }\n\n const { descriptor } = compilerSfc.parse(code, { filename: id });\n\n // Compile <script setup> or <script>\n let scriptCode: string;\n if (descriptor.scriptSetup || descriptor.script) {\n const compiled = compilerSfc.compileScript(descriptor, {\n id,\n inlineTemplate: true,\n });\n scriptCode = compiled.content;\n } else {\n // Template-only SFC: compile template separately\n if (!descriptor.template) {\n throw new Error(\n `[ox-content:og-image] Vue SFC must have a <template> or <script>: ${id}`,\n );\n }\n const templateResult = compilerSfc.compileTemplate({\n source: descriptor.template.content,\n filename: id,\n id,\n });\n if (templateResult.errors.length > 0) {\n throw new Error(\n `[ox-content:og-image] Vue template compilation errors in ${id}: ${templateResult.errors.map(String).join(\", \")}`,\n );\n }\n scriptCode = `${templateResult.code}\\nexport default { render }`;\n }\n\n // Determine if the compiled output contains TypeScript\n const isTs = !!(descriptor.scriptSetup?.lang === \"ts\" || descriptor.script?.lang === \"ts\");\n\n return { code: scriptCode, moduleType: isTs ? \"ts\" : \"js\" };\n },\n };\n}\n\n/**\n * Loads @vizejs/vite-plugin as a rolldown plugin for Vue SFC compilation.\n */\nasync function getVizejsPlugin(): Promise<import(\"rolldown\").Plugin[]> {\n try {\n const vizejs = await import(\"@vizejs/vite-plugin\");\n const plugin = vizejs.default?.() ?? vizejs;\n return Array.isArray(plugin) ? plugin : [plugin];\n } catch {\n throw new Error(\n \"[ox-content:og-image] @vizejs/vite-plugin is required when vuePlugin is 'vizejs'. \" +\n \"Install it with: pnpm add -D @vizejs/vite-plugin\",\n );\n }\n}\n\n/**\n * Resolves a Svelte SFC template via SSR.\n *\n * Compiles the SFC with svelte/compiler (server mode + runes),\n * bundles with rolldown, then wraps with svelte/server render().\n */\nasync function resolveSvelteTemplate(\n templatePath: string,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template_svelte.mjs\");\n\n const bundle = await rolldown({\n input: templatePath,\n platform: \"node\",\n external: [\n \"svelte\",\n \"svelte/server\",\n \"svelte/internal\",\n \"svelte/internal/server\",\n OX_CONTENT_PACKAGE,\n ],\n plugins: [createSvelteCompilerPlugin()],\n });\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const Component = mod.default;\n\n if (!Component) {\n throw new Error(\n `[ox-content:og-image] Svelte template must have a default export: ${templatePath}`,\n );\n }\n\n // Import Svelte SSR utility\n const { render } = (await import(\"svelte/server\")) as {\n render: (component: unknown, options: { props: Record<string, unknown> }) => { body: string };\n };\n\n return async (props) => {\n const { body } = render(Component, { props });\n return body;\n };\n}\n\n/**\n * Creates a rolldown plugin that compiles Svelte SFCs using svelte/compiler.\n */\nfunction createSvelteCompilerPlugin(): import(\"rolldown\").Plugin {\n return {\n name: \"ox-content-svelte-sfc\",\n async transform(code, id) {\n if (!id.endsWith(\".svelte\")) return null;\n\n let svelteCompiler: typeof import(\"svelte/compiler\");\n try {\n svelteCompiler = await import(\"svelte/compiler\");\n } catch {\n throw new Error(\n \"[ox-content:og-image] svelte is required for .svelte templates. \" +\n \"Install it with: pnpm add -D svelte\",\n );\n }\n\n const result = svelteCompiler.compile(code, {\n generate: \"server\",\n runes: true,\n filename: id,\n });\n\n return { code: result.js.code };\n },\n };\n}\n\n/**\n * Resolves a React (.tsx/.jsx) template via SSR.\n *\n * Bundles with rolldown (JSX transform), then wraps with\n * react-dom/server renderToReadableStream for async Server Component support.\n */\nasync function resolveReactTemplate(\n templatePath: string,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template_react.mjs\");\n\n const bundle = await rolldown({\n input: templatePath,\n platform: \"node\",\n external: [\n \"react\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n \"react-dom\",\n \"react-dom/server\",\n OX_CONTENT_PACKAGE,\n ],\n transform: {\n jsx: \"react-jsx\",\n },\n });\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const Component = mod.default;\n\n if (!Component) {\n throw new Error(\n `[ox-content:og-image] React template must have a default export: ${templatePath}`,\n );\n }\n\n // Import React SSR utilities\n let React: typeof import(\"react\");\n let ReactDOMServer: typeof import(\"react-dom/server\");\n try {\n React = await import(\"react\");\n ReactDOMServer = await import(\"react-dom/server\");\n } catch {\n throw new Error(\n \"[ox-content:og-image] react and react-dom are required for .tsx/.jsx templates. \" +\n \"Install them with: pnpm add -D react react-dom\",\n );\n }\n\n return async (props) => {\n const element = React.createElement(Component, props);\n // Use renderToReadableStream for async Server Component support\n const stream = await ReactDOMServer.renderToReadableStream(element);\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n const decoder = new TextDecoder();\n return (\n chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join(\"\") + decoder.decode()\n );\n };\n}\n\n/**\n * Computes a stable template source identifier for cache keys.\n *\n * For custom templates, hashes the file content so cache invalidates\n * when the template changes. For the default template, returns a fixed string.\n */\nasync function computeTemplateSource(\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<string> {\n if (!options.template) {\n return \"__default__\";\n }\n\n const fs = await import(\"fs/promises\");\n const templatePath = path.resolve(root, options.template);\n const content = await fs.readFile(templatePath, \"utf-8\");\n return crypto.createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/**\n * Generates OG images for a batch of pages.\n *\n * Manages the full lifecycle: resolve template → launch browser (with `using`) →\n * render each page (with caching and concurrency).\n *\n * All errors are non-fatal: failures are reported in results but never throw.\n */\nexport async function generateOgImages(\n pages: OgImagePageEntry[],\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageResult[]> {\n if (pages.length === 0) return [];\n\n // Resolve template\n const templateFn = await resolveTemplate(options, root);\n\n // Compute template source for cache key\n const templateSource = await computeTemplateSource(options, root);\n\n // Cache directory\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n\n // Try to serve all from cache first if caching is enabled\n if (options.cache) {\n const allCached = await tryServeAllFromCache(pages, templateSource, options, cacheDir);\n if (allCached) return allCached;\n }\n\n // Launch browser\n await using session = await openBrowser();\n if (!session) {\n return pages.map((p) => ({\n outputPath: p.outputPath,\n cached: false,\n error: \"Chromium not available\",\n }));\n }\n\n const results: OgImageResult[] = [];\n\n // Resolve public directory for serving local assets in templates\n const publicDir = path.join(root, \"public\");\n\n // Process pages with concurrency control\n const concurrency = Math.max(1, options.concurrency);\n\n for (let i = 0; i < pages.length; i += concurrency) {\n const batch = pages.slice(i, i + concurrency);\n const batchResults = await Promise.all(\n batch.map((entry) =>\n renderSinglePage(entry, templateFn, templateSource, options, cacheDir, session, publicDir),\n ),\n );\n results.push(...batchResults);\n }\n\n return results;\n}\n\n/**\n * Tries to serve all pages from cache.\n * Returns results if ALL pages are cached, null otherwise.\n */\nasync function tryServeAllFromCache(\n pages: OgImagePageEntry[],\n templateSource: string,\n options: ResolvedOgImageOptions,\n cacheDir: string,\n): Promise<OgImageResult[] | null> {\n const fs = await import(\"fs/promises\");\n const results: OgImageResult[] = [];\n\n for (const entry of pages) {\n const key = computeCacheKey(\n templateSource,\n entry.props as unknown as Record<string, unknown>,\n options.width,\n options.height,\n );\n const cached = await getCached(cacheDir, key);\n if (!cached) return null; // At least one miss, need browser\n\n // Write cached file to output\n await fs.mkdir(path.dirname(entry.outputPath), { recursive: true });\n await fs.writeFile(entry.outputPath, cached);\n results.push({ outputPath: entry.outputPath, cached: true });\n }\n\n return results;\n}\n\n/**\n * Renders a single page to PNG, with cache support.\n */\nasync function renderSinglePage(\n entry: OgImagePageEntry,\n templateFn: OgImageTemplateFn,\n templateSource: string,\n options: ResolvedOgImageOptions,\n cacheDir: string,\n session: OgBrowserSession,\n publicDir?: string,\n): Promise<OgImageResult> {\n const fs = await import(\"fs/promises\");\n\n try {\n // Check cache\n if (options.cache) {\n const key = computeCacheKey(\n templateSource,\n entry.props as unknown as Record<string, unknown>,\n options.width,\n options.height,\n );\n const cached = await getCached(cacheDir, key);\n if (cached) {\n await fs.mkdir(path.dirname(entry.outputPath), { recursive: true });\n await fs.writeFile(entry.outputPath, cached);\n return { outputPath: entry.outputPath, cached: true };\n }\n }\n\n // Render template to HTML (may be async for SFC templates)\n const html = await templateFn(entry.props);\n\n // Render HTML to PNG via session (page create/close handled internally)\n const png = await session.renderPage(html, options.width, options.height, publicDir);\n\n // Write output\n await fs.mkdir(path.dirname(entry.outputPath), { recursive: true });\n await fs.writeFile(entry.outputPath, png);\n\n // Write cache\n if (options.cache) {\n const key = computeCacheKey(\n templateSource,\n entry.props as unknown as Record<string, unknown>,\n options.width,\n options.height,\n );\n await writeCache(cacheDir, key, png);\n }\n\n return { outputPath: entry.outputPath, cached: false };\n } catch (err) {\n return {\n outputPath: entry.outputPath,\n cached: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n","/**\n * Island Parser\n *\n * Detects <Island> components in HTML and transforms them\n * into hydration-ready elements with data attributes.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\nimport { interopDefault } from \"../interop\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\nexport type LoadStrategy = \"eager\" | \"idle\" | \"visible\" | \"media\";\n\nexport interface IslandInfo {\n component: string;\n load: LoadStrategy;\n mediaQuery?: string;\n props: Record<string, unknown>;\n}\n\nexport interface ParseIslandsResult {\n html: string;\n islands: IslandInfo[];\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Parse JSX-style props from attributes.\n */\nfunction parseProps(el: Element): Record<string, unknown> {\n const props: Record<string, unknown> = {};\n\n if (!el.properties) return props;\n\n for (const [key, value] of Object.entries(el.properties)) {\n // Skip special attributes\n if ([\"load\", \"media\", \"className\", \"class\"].includes(key)) continue;\n\n // Handle JSX-style props like {0} or {true}\n if (typeof value === \"string\") {\n // Try to parse as JSON/JS value if it looks like one\n const trimmed = value.trim();\n if (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n const inner = trimmed.slice(1, -1);\n try {\n // Try JSON parse first\n props[key] = JSON.parse(inner);\n } catch {\n // Try evaluating simple expressions\n if (inner === \"true\") props[key] = true;\n else if (inner === \"false\") props[key] = false;\n else if (inner === \"null\") props[key] = null;\n else if (!Number.isNaN(Number(inner))) props[key] = Number(inner);\n else props[key] = value;\n }\n } else {\n props[key] = value;\n }\n } else if (typeof value === \"number\" || typeof value === \"boolean\") {\n props[key] = value;\n } else if (Array.isArray(value)) {\n props[key] = value;\n }\n }\n\n return props;\n}\n\n/**\n * Find the component element inside <Island>.\n */\nfunction findComponentElement(children: Element[\"children\"]): Element | null {\n for (const child of children) {\n if (child.type === \"element\") {\n // Skip text/whitespace, look for actual component\n if (child.tagName !== \"br\" && child.tagName !== \"span\") {\n return child;\n }\n }\n }\n return null;\n}\n\n/**\n * Get component name from child element.\n */\nfunction getComponentName(el: Element): string {\n // PascalCase tag names are components\n const tagName = el.tagName;\n if (tagName && /^[A-Z]/.test(tagName)) {\n return tagName;\n }\n // Check for data-component attribute\n return getAttribute(el, \"data-component\") || tagName;\n}\n\nlet islandCounter = 0;\n\n/**\n * Reset island counter (for testing).\n */\nexport function resetIslandCounter(): void {\n islandCounter = 0;\n}\n\n/**\n * Rehype plugin to transform Island components.\n */\nfunction rehypeIslands(collectedIslands: IslandInfo[]) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <Island> component\n if (child.tagName.toLowerCase() === \"island\") {\n const load = (getAttribute(child, \"load\") as LoadStrategy) || \"eager\";\n const mediaQuery = getAttribute(child, \"media\");\n\n // Find the component inside\n const componentEl = findComponentElement(child.children);\n\n if (componentEl) {\n const componentName = getComponentName(componentEl);\n const componentProps = parseProps(componentEl);\n\n // Collect island info\n const islandInfo: IslandInfo = {\n component: componentName,\n load,\n mediaQuery,\n props: componentProps,\n };\n collectedIslands.push(islandInfo);\n\n // Create island wrapper with data attributes\n const islandId = `ox-island-${islandCounter++}`;\n\n const islandElement: Element = {\n type: \"element\",\n tagName: \"div\",\n properties: {\n id: islandId,\n \"data-ox-island\": componentName,\n \"data-ox-load\": load,\n ...(mediaQuery && { \"data-ox-media\": mediaQuery }),\n \"data-ox-props\": JSON.stringify(componentProps),\n className: [\"ox-island\"],\n },\n children: [\n // Keep original content as fallback/placeholder\n ...componentEl.children,\n ],\n };\n\n node.children[i] = islandElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform Island components in HTML.\n *\n * Converts:\n * ```html\n * <Island load=\"visible\">\n * <Counter initial={0} />\n * </Island>\n * ```\n *\n * To:\n * ```html\n * <div id=\"ox-island-0\"\n * data-ox-island=\"Counter\"\n * data-ox-load=\"visible\"\n * data-ox-props='{\"initial\":0}'\n * class=\"ox-island\">\n * <!-- fallback content -->\n * </div>\n * ```\n */\nexport async function transformIslands(html: string): Promise<ParseIslandsResult> {\n const islands: IslandInfo[] = [];\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeIslands, islands)\n .use(rehypeStringify)\n .process(html);\n\n return {\n html: String(result),\n islands,\n };\n}\n\n/**\n * Check if HTML contains any Island components.\n */\nexport function hasIslands(html: string): boolean {\n return /<island[\\s>]/i.test(html);\n}\n\n/**\n * Extract island info without transforming HTML.\n * Useful for analysis/bundling purposes.\n */\nexport async function extractIslandInfo(html: string): Promise<IslandInfo[]> {\n const { islands } = await transformIslands(html);\n return islands;\n}\n\n/**\n * Generate client-side hydration script.\n * This is a minimal script that imports and initializes islands.\n */\nexport function generateHydrationScript(components: string[]): string {\n if (components.length === 0) return \"\";\n\n const imports = components.map((name) => `import ${name} from './${name}';`).join(\"\\n\");\n\n return `\nimport { initIslands } from '@ox-content/islands';\n${imports}\n\nconst components = {\n ${components.join(\",\\n \")}\n};\n\n// Initialize with your framework's hydration\n// This example uses Vue, adapt for React/Svelte/etc.\nimport { createApp, h } from 'vue';\n\ninitIslands((el, props) => {\n const name = el.dataset.oxIsland;\n const Component = components[name];\n if (!Component) {\n console.warn(\\`[ox-islands] Unknown component: \\${name}\\`);\n return;\n }\n\n const app = createApp({ render: () => h(Component, props) });\n app.mount(el);\n\n return () => app.unmount();\n});\n`;\n}\n","import type { LocaleConfig } from \"./types\";\n\n/**\n * Sibling page or locale-root href for one locale in the default-theme switcher.\n */\nexport interface SsgLocalePath {\n code: string;\n href?: string;\n root?: string;\n}\n\n/**\n * Resolves `ssg.localeSwitcher`. Omitted / `false` stay off. `true` or an\n * object enables the control.\n */\nexport function resolveLocaleSwitcherOption(\n value: boolean | Record<string, unknown> | undefined,\n): boolean {\n return value === true || (typeof value === \"object\" && value !== null);\n}\n\nexport function normalizeLocalePath(path: string): string {\n return path.replaceAll(\"\\\\\", \"/\").replace(/^\\/+|\\/+$/g, \"\");\n}\n\nexport function remainderPath(urlPath: string, locale: string): string {\n const normalized = normalizeLocalePath(urlPath);\n if (normalized === locale) {\n return \"\";\n }\n const prefix = `${locale}/`;\n if (normalized.startsWith(prefix)) {\n return normalized.slice(prefix.length);\n }\n return normalized;\n}\n\nexport function pathForLocale(\n remainder: string,\n locale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean,\n): string {\n if (hideDefaultLocale && locale === defaultLocale) {\n return remainder;\n }\n return remainder ? `${locale}/${remainder}` : locale;\n}\n\nexport function defaultLocaleRoot(base: string, locale: string): string {\n const prefix = base.endsWith(\"/\") ? base : `${base}/`;\n return `${prefix}${locale}/`;\n}\n\nexport function buildLocalePaths(options: {\n currentPath: string;\n locales: LocaleConfig[];\n defaultLocale: string;\n hideDefaultLocale: boolean;\n pages: Array<{ path: string; href: string }>;\n base: string;\n roots?: Record<string, string>;\n}): SsgLocalePath[] {\n const currentLocale =\n options.locales.find((locale) => {\n const normalized = normalizeLocalePath(options.currentPath);\n return normalized === locale.code || normalized.startsWith(`${locale.code}/`);\n })?.code ?? options.defaultLocale;\n const remainder = remainderPath(options.currentPath, currentLocale);\n const existing = new Map(\n options.pages.map((page) => [normalizeLocalePath(page.path), page.href]),\n );\n\n return options.locales.map((locale) => {\n const sibling = pathForLocale(\n remainder,\n locale.code,\n options.defaultLocale,\n options.hideDefaultLocale,\n );\n const href = existing.get(normalizeLocalePath(sibling));\n const configuredRoot = options.roots?.[locale.code];\n const root =\n configuredRoot ??\n (options.hideDefaultLocale && locale.code === options.defaultLocale\n ? options.base.endsWith(\"/\")\n ? options.base\n : `${options.base}/`\n : defaultLocaleRoot(options.base, locale.code));\n return { code: locale.code, href, root };\n });\n}\n","/**\n * Rewrites default-theme nav hrefs to the current locale sibling when it exists.\n */\n\nimport { resolveLocaleLabel, type HeaderNavItem, type LocaleLabel } from \"./header-chrome\";\nimport { normalizeLocalePath, pathForLocale, remainderPath } from \"./locale-switcher\";\nimport type { SidebarItem } from \"./theme\";\nimport type { LocaleConfig } from \"./types\";\n\n/** @internal Label metadata kept off the serializable navigation shape. */\nconst localizedNavTitle: unique symbol = Symbol(\"ox-content.localized-nav-title\");\n\nexport interface LocalePageRef {\n path: string;\n href: string;\n /** Alternate source/permalink paths that resolve to this canonical page. */\n aliases?: readonly string[];\n}\n\nexport interface LocalizeNavOptions {\n locale: string;\n locales: readonly Pick<LocaleConfig, \"code\">[];\n defaultLocale: string;\n hideDefaultLocale: boolean;\n pages: readonly LocalePageRef[];\n base: string;\n}\n\nexport interface LocalizableNavItem {\n title: string;\n path: string;\n href: string;\n children?: LocalizableNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\nexport interface LocalizableNavGroup {\n title: string;\n items: LocalizableNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\ntype LocalizedNavItem = LocalizableNavItem & {\n [localizedNavTitle]?: LocaleLabel;\n children?: LocalizedNavItem[];\n};\n\ntype LocalizedNavGroup = LocalizableNavGroup & {\n [localizedNavTitle]?: LocaleLabel;\n items: LocalizedNavItem[];\n};\n\ninterface ResolvedSidebarItem {\n text?: string;\n link?: string;\n items?: ResolvedSidebarItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/** @internal Flattens sidebar locale maps before crossing the string-only NAPI boundary. */\nexport function resolveSidebarItems(\n sidebar: readonly SidebarItem[],\n locale?: string,\n defaultLocale?: string,\n): ResolvedSidebarItem[] {\n return sidebar.map((item) => ({\n text:\n item.text === undefined ? undefined : resolveLocaleLabel(item.text, locale, defaultLocale),\n link: item.link,\n items: item.items ? resolveSidebarItems(item.items, locale, defaultLocale) : undefined,\n collapsed: item.collapsed,\n stickyCollapsed: item.stickyCollapsed,\n }));\n}\n\n/** @internal Associates rendered nav nodes with authored locale maps by tree position. */\nexport function attachSidebarLabels<T extends LocalizableNavGroup>(\n groups: T[],\n sidebar: readonly SidebarItem[],\n): T[] {\n const sources = sidebarGroupSources(sidebar);\n return groups.map((group, index) => {\n const source = sources[index];\n return {\n ...group,\n ...(source?.title === undefined ? {} : { [localizedNavTitle]: source.title }),\n items: attachItemLabels(group.items, source?.items ?? []),\n } as T;\n });\n}\n\nfunction sidebarGroupSources(sidebar: readonly SidebarItem[]): Array<{\n title?: LocaleLabel;\n items: readonly SidebarItem[];\n}> {\n const groups: Array<{ title?: LocaleLabel; items: readonly SidebarItem[] }> = [];\n let loose: SidebarItem[] = [];\n const flushLoose = () => {\n if (loose.length > 0) {\n groups.push({ items: loose });\n loose = [];\n }\n };\n for (const item of sidebar) {\n if ((item.items?.length ?? 0) > 0 && item.link === undefined) {\n flushLoose();\n groups.push({ title: item.text, items: item.items ?? [] });\n } else {\n loose.push(item);\n }\n }\n flushLoose();\n return groups;\n}\n\nfunction attachItemLabels<T extends LocalizableNavItem>(\n items: T[],\n sources: readonly SidebarItem[],\n): T[] {\n return items.map((item, index) => {\n const source = sources[index];\n return {\n ...item,\n ...(source?.text === undefined ? {} : { [localizedNavTitle]: source.text }),\n children: attachItemLabels(item.children ?? [], source?.items ?? []),\n };\n });\n}\n\n/**\n * Resolves authored sidebar label maps and prefixes hrefs/paths with the\n * current locale when that page exists. Missing siblings stay as authored.\n */\nexport function localizeNavGroups<T extends LocalizableNavGroup>(\n groups: T[],\n options: LocalizeNavOptions,\n): T[] {\n const lookup = pageLookup(options);\n if (!lookup && !hasLocalizedTitles(groups)) {\n return groups;\n }\n return groups.map((group) => ({\n ...group,\n title: resolveNavTitle(group, options),\n items: group.items.map((item) => localizeNavItem(item, options, lookup)),\n }));\n}\n\n/**\n * Resolves header labels and rewrites `link` values the same way as the sidebar.\n */\nexport function localizeHeaderNavItems(\n items: HeaderNavItem[] | undefined,\n options: LocalizeNavOptions,\n): HeaderNavItem[] | undefined {\n if (!items?.length) {\n return items;\n }\n const lookup = pageLookup(options);\n return items.map((item) => ({\n ...item,\n text: resolveLocaleLabel(item.text, options.locale, options.defaultLocale),\n link: item.link && lookup ? localizeHref(item.link, options, lookup) : item.link,\n items: localizeHeaderNavItems(item.items, options),\n }));\n}\n\nexport function localizeHref(\n href: string,\n options: LocalizeNavOptions,\n lookup = pageLookup(options),\n): string {\n if (!lookup) {\n return href;\n }\n const hash = href.includes(\"#\") ? href.slice(href.indexOf(\"#\")) : \"\";\n const sitePath = sitePathFromHref(href, options.base);\n if (sitePath === undefined) {\n return href;\n }\n const remainder = stripLocalePrefix(sitePath, options.locales);\n const siblingPath = pathForLocale(\n remainder,\n options.locale,\n options.defaultLocale,\n options.hideDefaultLocale,\n );\n const sibling = lookup.get(normalizeLocalePath(siblingPath));\n return sibling ? `${sibling.href}${hash}` : href;\n}\n\nexport function sitePathFromHref(href: string, base: string): string | undefined {\n const trimmed = href.trim();\n if (!trimmed || trimmed.startsWith(\"#\") || trimmed.startsWith(\"//\")) {\n return undefined;\n }\n const noHash = trimmed.split(\"#\")[0]?.split(\"?\")[0] ?? \"\";\n const compact = noHash.replace(/\\s+/g, \"\").toLowerCase();\n if (\n compact.startsWith(\"javascript:\") ||\n compact.startsWith(\"data:\") ||\n compact.startsWith(\"vbscript:\")\n ) {\n return undefined;\n }\n if (/^[a-z][a-z0-9+.-]*:/i.test(noHash)) {\n return undefined;\n }\n const normalizedBase = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n let path = noHash;\n if (normalizedBase !== \"/\" && path.startsWith(normalizedBase)) {\n path = path.slice(normalizedBase.length);\n } else if (path.startsWith(\"/\")) {\n path = path.slice(1);\n } else {\n return undefined;\n }\n path = path\n .replace(/\\/index\\.html$/i, \"\")\n .replace(/\\.html$/i, \"\")\n .replace(/\\.(mdx|markdown|md)$/i, \"\")\n .replace(/\\/+$/g, \"\");\n if (path === \"index\") {\n return \"\";\n }\n return path;\n}\n\nfunction localizeNavItem<T extends LocalizableNavItem>(\n item: T,\n options: LocalizeNavOptions,\n lookup: Map<string, LocalePageRef> | undefined,\n): T {\n if (!lookup) {\n return {\n ...item,\n title: resolveNavTitle(item, options),\n children: (item.children ?? []).map((child) => localizeNavItem(child, options, lookup)),\n };\n }\n const hash = item.href.includes(\"#\") ? item.href.slice(item.href.indexOf(\"#\")) : \"\";\n const sitePath = sitePathFromHref(item.href, options.base) ?? normalizeLocalePath(item.path);\n const remainder = stripLocalePrefix(sitePath, options.locales);\n const siblingPath = pathForLocale(\n remainder,\n options.locale,\n options.defaultLocale,\n options.hideDefaultLocale,\n );\n const sibling = lookup.get(normalizeLocalePath(siblingPath));\n return {\n ...item,\n title: resolveNavTitle(item, options),\n href: sibling ? `${sibling.href}${hash}` : item.href,\n path: sibling ? sibling.path : item.path,\n children: (item.children ?? []).map((child) => localizeNavItem(child, options, lookup)),\n };\n}\n\nfunction resolveNavTitle(\n item: LocalizableNavItem | LocalizableNavGroup,\n options: LocalizeNavOptions,\n): string {\n const label = (item as LocalizedNavItem | LocalizedNavGroup)[localizedNavTitle];\n return label === undefined\n ? item.title\n : resolveLocaleLabel(label, options.locale, options.defaultLocale);\n}\n\nfunction hasLocalizedTitles(groups: readonly LocalizableNavGroup[]): boolean {\n return groups.some(\n (group) =>\n (group as LocalizedNavGroup)[localizedNavTitle] !== undefined ||\n hasLocalizedItemTitles(group.items),\n );\n}\n\nfunction hasLocalizedItemTitles(items: readonly LocalizableNavItem[]): boolean {\n return items.some(\n (item) =>\n (item as LocalizedNavItem)[localizedNavTitle] !== undefined ||\n hasLocalizedItemTitles(item.children ?? []),\n );\n}\n\nfunction pageLookup(options: LocalizeNavOptions): Map<string, LocalePageRef> | undefined {\n if (!options.locale || options.pages.length === 0) {\n return undefined;\n }\n if (options.hideDefaultLocale && options.locale === options.defaultLocale) {\n return undefined;\n }\n const lookup = new Map<string, LocalePageRef>();\n for (const page of options.pages) {\n lookup.set(normalizeLocalePath(page.path), page);\n for (const alias of page.aliases ?? []) {\n const key = normalizeLocalePath(alias);\n if (!lookup.has(key)) {\n lookup.set(key, page);\n }\n }\n }\n return lookup;\n}\n\nfunction stripLocalePrefix(\n sitePath: string,\n locales: readonly Pick<LocaleConfig, \"code\">[],\n): string {\n const normalized = normalizeLocalePath(sitePath);\n const codes = locales.map((locale) => locale.code).sort((a, b) => b.length - a.length);\n for (const code of codes) {\n if (normalized === code || normalized.startsWith(`${code}/`)) {\n return remainderPath(normalized, code);\n }\n }\n return normalized;\n}\n","/**\n * Page Context for Static HTML Generation\n *\n * Provides a way to access page props (frontmatter, content, etc.)\n * from theme components during static rendering.\n *\n * @example\n * ```tsx\n * // theme/Layout.tsx\n * import { usePageProps, PageProps } from '@ox-content/vite-plugin';\n *\n * export function Layout({ children }: { children: JSX.Element }) {\n * const page = usePageProps<MyPageProps>();\n * return (\n * <html>\n * <head>\n * <title>{page.title}</title>\n * </head>\n * <body>\n * <header>{page.title}</header>\n * <main>{children}</main>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\n\nimport type { TocEntry } from \"./types\";\n\n/**\n * Base page props available for all pages.\n */\nexport interface BasePageProps {\n /** Page title from frontmatter or first heading */\n title: string;\n /** Page description from frontmatter */\n description?: string;\n /** Rendered HTML content */\n html: string;\n /** Table of contents entries */\n toc: TocEntry[];\n /** Last git commit timestamp in milliseconds */\n lastUpdated?: number;\n /** Source file path (relative to docs root) */\n path: string;\n /** Output URL path */\n url: string;\n /** Raw frontmatter object */\n frontmatter: Record<string, unknown>;\n /** Layout name from frontmatter */\n layout?: string;\n}\n\n/**\n * Extended page props with custom frontmatter.\n */\nexport type PageProps<T extends Record<string, unknown> = Record<string, unknown>> =\n BasePageProps & {\n /** Custom frontmatter fields */\n frontmatter: T & Record<string, unknown>;\n };\n\n/**\n * Site-wide configuration available in context.\n */\nexport interface SiteConfig {\n /** Site name */\n name: string;\n /** Base URL path */\n base: string;\n /** All pages in the site */\n pages: BasePageProps[];\n /** Navigation groups */\n nav: NavGroup[];\n}\n\n/**\n * Navigation group.\n */\nexport interface NavGroup {\n title: string;\n items: NavItem[];\n}\n\n/**\n * Navigation item.\n */\nexport interface NavItem {\n title: string;\n path: string;\n href: string;\n}\n\n/**\n * Complete render context.\n */\nexport interface RenderContext<T extends Record<string, unknown> = Record<string, unknown>> {\n /** Current page props */\n page: PageProps<T>;\n /** Site configuration */\n site: SiteConfig;\n}\n\n// Internal context storage (set during render)\nlet currentContext: RenderContext | null = null;\n\n/**\n * Sets the current render context.\n * Called internally during page rendering.\n * @internal\n */\nexport function setRenderContext(ctx: RenderContext): void {\n currentContext = ctx;\n}\n\n/**\n * Clears the current render context.\n * Called internally after page rendering.\n * @internal\n */\nexport function clearRenderContext(): void {\n currentContext = null;\n}\n\n/**\n * Gets the current page props.\n *\n * @returns The current page props\n * @throws Error if called outside of a render context\n *\n * @example\n * ```tsx\n * function PageTitle() {\n * const page = usePageProps();\n * return <h1>{page.title}</h1>;\n * }\n * ```\n */\nexport function usePageProps<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(): PageProps<T> {\n if (!currentContext) {\n throw new Error(\n \"[ox-content] usePageProps() must be called during page rendering. \" +\n \"Make sure you are using it inside a theme component.\",\n );\n }\n return currentContext.page as PageProps<T>;\n}\n\n/**\n * Gets the site configuration.\n *\n * @returns The site configuration\n * @throws Error if called outside of a render context\n *\n * @example\n * ```tsx\n * function SiteHeader() {\n * const site = useSiteConfig();\n * return <header>{site.name}</header>;\n * }\n * ```\n */\nexport function useSiteConfig(): SiteConfig {\n if (!currentContext) {\n throw new Error(\n \"[ox-content] useSiteConfig() must be called during page rendering. \" +\n \"Make sure you are using it inside a theme component.\",\n );\n }\n return currentContext.site;\n}\n\n/**\n * Gets the full render context.\n *\n * @returns The complete render context\n * @throws Error if called outside of a render context\n *\n * @example\n * ```tsx\n * function Layout({ children }) {\n * const ctx = useRenderContext();\n * return (\n * <html>\n * <head><title>{ctx.page.title} - {ctx.site.name}</title></head>\n * <body>{children}</body>\n * </html>\n * );\n * }\n * ```\n */\nexport function useRenderContext<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(): RenderContext<T> {\n if (!currentContext) {\n throw new Error(\n \"[ox-content] useRenderContext() must be called during page rendering. \" +\n \"Make sure you are using it inside a theme component.\",\n );\n }\n return currentContext as RenderContext<T>;\n}\n\n/**\n * Gets the navigation groups.\n *\n * @example\n * ```tsx\n * function Sidebar() {\n * const nav = useNav();\n * return (\n * <nav>\n * {each(nav, (group) => (\n * <div>\n * <h3>{group.title}</h3>\n * <ul>\n * {each(group.items, (item) => (\n * <li><a href={item.href}>{item.title}</a></li>\n * ))}\n * </ul>\n * </div>\n * ))}\n * </nav>\n * );\n * }\n * ```\n */\nexport function useNav(): NavGroup[] {\n return useSiteConfig().nav;\n}\n\n/**\n * Checks if the given path is the current page.\n *\n * @example\n * ```tsx\n * function NavLink({ href, children }) {\n * const isActive = useIsActive(href);\n * return <a href={href} class={isActive ? 'active' : ''}>{children}</a>;\n * }\n * ```\n */\nexport function useIsActive(path: string): boolean {\n const page = usePageProps();\n return page.path === path || page.url === path;\n}\n\n// Type generation helpers\n\n/**\n * Schema for frontmatter type generation.\n */\nexport interface FrontmatterSchema {\n /** Field name */\n name: string;\n /** TypeScript type */\n type: string;\n /** Whether the field is optional */\n optional: boolean;\n /** JSDoc description */\n description?: string;\n}\n\n/**\n * Infers TypeScript types from frontmatter values.\n */\nexport function inferType(value: unknown): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (typeof value === \"string\") return \"string\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"boolean\") return \"boolean\";\n if (Array.isArray(value)) {\n if (value.length === 0) return \"unknown[]\";\n const itemTypes = [...new Set(value.map(inferType))];\n if (itemTypes.length === 1) return `${itemTypes[0]}[]`;\n return `(${itemTypes.join(\" | \")})[]`;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) return \"Record<string, unknown>\";\n const props = entries.map(([k, v]) => `${k}: ${inferType(v)}`).join(\"; \");\n return `{ ${props} }`;\n }\n return \"unknown\";\n}\n\n/**\n * Generates TypeScript interface from frontmatter samples.\n */\nexport function generateFrontmatterTypes(\n samples: Record<string, unknown>[],\n interfaceName = \"PageFrontmatter\",\n): string {\n // Collect all fields and their types across all samples\n const fields = new Map<string, { types: Set<string>; count: number }>();\n\n for (const sample of samples) {\n for (const [key, value] of Object.entries(sample)) {\n const existing = fields.get(key) ?? { types: new Set(), count: 0 };\n existing.types.add(inferType(value));\n existing.count++;\n fields.set(key, existing);\n }\n }\n\n // Generate interface\n const lines: string[] = [\n \"/**\",\n \" * Auto-generated frontmatter type based on your pages.\",\n \" * DO NOT EDIT - this file is generated by ox-content.\",\n \" */\",\n \"\",\n `export interface ${interfaceName} {`,\n ];\n\n for (const [name, { types, count }] of fields) {\n const isOptional = count < samples.length;\n const typeStr = [...types].join(\" | \");\n const optionalMark = isOptional ? \"?\" : \"\";\n lines.push(` ${name}${optionalMark}: ${typeStr};`);\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n lines.push(\n `export type PageProps = import('@ox-content/vite-plugin').PageProps<${interfaceName}>;`,\n );\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Theme Renderer for Static HTML Generation\n *\n * Renders JSX theme components to static HTML strings.\n * No client-side JavaScript is included by default.\n */\n\nimport { renderToString, raw, type JSXNode } from \"./jsx-html\";\nimport {\n setRenderContext,\n clearRenderContext,\n generateFrontmatterTypes,\n usePageProps,\n type RenderContext,\n type PageProps,\n type SiteConfig,\n type NavGroup,\n} from \"./page-context\";\nimport type { TocEntry } from \"./types\";\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * Theme component type.\n */\nexport type ThemeComponent = (props: ThemeProps) => JSXNode;\n\n/**\n * Props passed to the theme component.\n */\nexport interface ThemeProps {\n /** Rendered page content as JSX */\n children: JSXNode;\n}\n\n/**\n * Page data for rendering.\n */\nexport interface PageData {\n /** Page title */\n title: string;\n /** Page description */\n description?: string;\n /** Rendered HTML content */\n html: string;\n /** Table of contents */\n toc: TocEntry[];\n /** Last git commit timestamp in milliseconds */\n lastUpdated?: number;\n /** Source file path */\n path: string;\n /** Output URL path */\n url: string;\n /** Frontmatter */\n frontmatter: Record<string, unknown>;\n /** Layout name */\n layout?: string;\n}\n\n/**\n * Theme render options.\n */\nexport interface ThemeRenderOptions {\n /** Theme component to use */\n theme: ThemeComponent;\n /** Site name */\n siteName: string;\n /** Base URL path */\n base: string;\n /** Navigation groups */\n nav: NavGroup[];\n /** All pages (for site context) */\n pages: PageData[];\n /** Output directory for type definitions */\n typesOutDir?: string;\n}\n\n/**\n * Renders a page using the theme component.\n *\n * @param page - Page data to render\n * @param options - Theme render options\n * @returns Rendered HTML string\n */\nexport function renderPage(page: PageData, options: ThemeRenderOptions): string {\n const { theme, siteName, base, nav, pages } = options;\n\n // Build page props\n const pageProps: PageProps = {\n title: page.title,\n description: page.description,\n html: page.html,\n toc: page.toc,\n lastUpdated: page.lastUpdated,\n path: page.path,\n url: page.url,\n frontmatter: page.frontmatter,\n layout: page.layout,\n };\n\n // Build site config\n const siteConfig: SiteConfig = {\n name: siteName,\n base,\n nav,\n pages: pages.map((p) => ({\n title: p.title,\n description: p.description,\n html: p.html,\n toc: p.toc,\n lastUpdated: p.lastUpdated,\n path: p.path,\n url: p.url,\n frontmatter: p.frontmatter,\n layout: p.layout,\n })),\n };\n\n // Set render context\n const context: RenderContext = {\n page: pageProps,\n site: siteConfig,\n };\n\n setRenderContext(context);\n\n try {\n // Render theme with page content\n const contentNode = raw(page.html);\n const result = theme({ children: contentNode });\n\n // Get HTML string\n const html = renderToString(result);\n\n // Add doctype if not present\n if (!html.trimStart().toLowerCase().startsWith(\"<!doctype\")) {\n return `<!DOCTYPE html>\\n${html}`;\n }\n\n return html;\n } finally {\n clearRenderContext();\n }\n}\n\n/**\n * Renders all pages and generates type definitions.\n *\n * @param pages - All pages to render\n * @param options - Theme render options\n * @returns Map of output paths to rendered HTML\n */\nexport async function renderAllPages(\n pages: PageData[],\n options: ThemeRenderOptions,\n): Promise<Map<string, string>> {\n const results = new Map<string, string>();\n\n // Render each page\n for (const page of pages) {\n const html = renderPage(page, { ...options, pages });\n results.set(page.url, html);\n }\n\n // Generate type definitions if output directory is specified\n if (options.typesOutDir) {\n await generateTypes(pages, options.typesOutDir);\n }\n\n return results;\n}\n\n/**\n * Generates TypeScript type definitions from page frontmatter.\n *\n * @param pages - All pages\n * @param outDir - Output directory for types\n */\nexport async function generateTypes(pages: PageData[], outDir: string): Promise<void> {\n // Collect all frontmatter samples\n const samples = pages.map((p) => p.frontmatter);\n\n // Generate types\n const types = generateFrontmatterTypes(samples);\n\n // Write to file\n const typesPath = join(outDir, \"page-props.d.ts\");\n await mkdir(dirname(typesPath), { recursive: true });\n await writeFile(typesPath, types, \"utf-8\");\n}\n\n/**\n * Default theme component.\n * A minimal theme that renders page content with basic styling.\n */\nexport function DefaultTheme({ children }: ThemeProps): JSXNode {\n // Use hooks inside the component\n const { usePageProps, useSiteConfig } = require(\"./page-context\");\n const page = usePageProps();\n const site = useSiteConfig();\n\n return {\n __html: `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(page.title)} - ${escapeHtml(site.name)}</title>\n ${page.description ? `<meta name=\"description\" content=\"${escapeHtml(page.description)}\">` : \"\"}\n <style>\n :root {\n --octc-color-primary: #4f6fae;\n --octc-color-text: #131a30;\n --octc-color-bg: #ffffff;\n --octc-color-bg-alt: #f5f7fb;\n --octc-color-text-muted: #4f607b;\n --octc-color-border: #d2dbea;\n }\n body {\n font-family: \"IBM Plex Sans\", \"Avenir Next\", \"Segoe UI Variable\", \"Segoe UI\", sans-serif;\n line-height: 1.7;\n color: var(--octc-color-text);\n background: var(--octc-color-bg);\n max-width: 800px;\n margin: 0 auto;\n padding: 2rem;\n }\n a { color: var(--octc-color-primary); }\n </style>\n</head>\n<body>\n <header>\n <h1>${escapeHtml(site.name)}</h1>\n </header>\n <main>\n ${children.__html}\n </main>\n</body>\n</html>`,\n };\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\n/**\n * Creates a theme with layout switching support.\n *\n * @example\n * ```tsx\n * import { createTheme } from '@ox-content/vite-plugin';\n * import { DefaultLayout } from './layouts/Default';\n * import { EntryLayout } from './layouts/Entry';\n *\n * export default createTheme({\n * layouts: {\n * default: DefaultLayout,\n * entry: EntryLayout,\n * },\n * });\n * ```\n */\nexport function createTheme(config: {\n layouts: Record<string, ThemeComponent>;\n defaultLayout?: string;\n}): ThemeComponent {\n const { layouts, defaultLayout = \"default\" } = config;\n\n return function ThemeWithLayouts({ children }: ThemeProps): JSXNode {\n // `page-context` is already imported statically above, so there is no\n // cycle to dodge here. The lazy `require` this replaces threw\n // \"Cannot find module\" outright once the package shipped as ESM, which\n // is what made `createTheme` unusable.\n const page = usePageProps();\n\n // Get layout from frontmatter or use default\n const layoutName = page.layout ?? defaultLayout;\n const Layout = layouts[layoutName] ?? layouts[defaultLayout];\n\n if (!Layout) {\n throw new Error(\n `[ox-content] Layout \"${layoutName}\" not found. ` +\n `Available layouts: ${Object.keys(layouts).join(\", \")}`,\n );\n }\n\n return Layout({ children });\n };\n}\n","/**\n * Opt-in sitemap.xml / robots.txt / llms.txt helpers.\n *\n * String bodies follow `ox_content_ssg::generate_site_maps`. The Vite plugin\n * writes those files during SSG without adding a NAPI surface.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { ResolvedSiteMapsOptions, SiteMapsOptions } from \"./types\";\n\nconst MISSING_SITE_URL =\n \"[ox-content] siteMaps is enabled but ssg.siteUrl is not set; sitemap.xml, robots.txt, and llms.txt were not written\";\n\n/** One page considered for crawl manifests. */\nexport interface SiteMapPageInput {\n loc: string;\n title: string;\n description?: string;\n draft?: boolean;\n unlisted?: boolean;\n}\n\n/** Inputs for rendering crawl-manifest bodies. */\nexport interface SiteMapsRenderInput {\n options?: ResolvedSiteMapsOptions | null;\n siteUrl?: string;\n sitemapLoc?: string;\n siteName?: string;\n siteDescription?: string;\n pages: readonly SiteMapPageInput[];\n}\n\n/** Rendered crawl-manifest bodies, or a skip warning. */\nexport interface SiteMapsRenderResult {\n sitemapXml?: string;\n robotsTxt?: string;\n llmsTxt?: string;\n warning?: string;\n}\n\n/** Inputs for writing crawl manifests next to generated HTML. */\nexport interface WriteSiteMapFilesInput {\n outDir: string;\n siteUrl?: string;\n base: string;\n siteName?: string;\n siteDescription?: string;\n options?: ResolvedSiteMapsOptions;\n pages: readonly SiteMapPageInput[];\n}\n\n/**\n * Resolves `siteMaps` with defaults.\n *\n * `false` / omitted stays off. `true` enables all three files. An object\n * enables the feature and overrides only the fields the site set.\n */\nexport function resolveSiteMapsOptions(\n value: boolean | SiteMapsOptions | undefined,\n): ResolvedSiteMapsOptions {\n if (!value) {\n return { enabled: false, robots: true, llms: true };\n }\n if (value === true) {\n return { enabled: true, robots: true, llms: true };\n }\n return {\n enabled: true,\n robots: value.robots ?? true,\n llms: value.llms ?? true,\n };\n}\n\n/** Builds sitemap / robots / llms bodies without writing files. */\nexport function generateSiteMaps(input: SiteMapsRenderInput): SiteMapsRenderResult {\n if (!input.options?.enabled) {\n return {};\n }\n if (!hasSiteUrl(input.siteUrl)) {\n return { warning: MISSING_SITE_URL };\n }\n\n const published = input.pages\n .filter((page) => !page.draft && !page.unlisted && page.loc.length > 0)\n .slice()\n .sort((left, right) => (left.loc < right.loc ? -1 : left.loc > right.loc ? 1 : 0));\n\n const result: SiteMapsRenderResult = {\n sitemapXml: generateSitemapXml(published),\n };\n if (input.options.robots) {\n result.robotsTxt = generateRobotsTxt(input.sitemapLoc ?? \"\");\n }\n if (input.options.llms) {\n result.llmsTxt = generateLlmsTxt(input, published);\n }\n return result;\n}\n\n/** Writes enabled crawl manifests into `outDir`. */\nexport async function writeSiteMapFiles(\n input: WriteSiteMapFilesInput,\n): Promise<{ files: string[]; warning?: string }> {\n const generated = generateSiteMaps({\n options: input.options,\n siteUrl: input.siteUrl,\n sitemapLoc: absoluteSitemapUrl(input.siteUrl, input.base),\n siteName: input.siteName,\n siteDescription: input.siteDescription,\n pages: input.pages,\n });\n if (generated.warning) {\n return { files: [], warning: generated.warning };\n }\n\n const outputs: Array<[string, string]> = [\n [generated.sitemapXml, \"sitemap.xml\"],\n [generated.robotsTxt, \"robots.txt\"],\n [generated.llmsTxt, \"llms.txt\"],\n ].filter((entry): entry is [string, string] => entry[0] != null);\n if (outputs.length === 0) {\n return { files: [] };\n }\n\n await fs.mkdir(input.outDir, { recursive: true });\n const files: string[] = [];\n for (const [body, name] of outputs) {\n const outputPath = path.join(input.outDir, name);\n await fs.writeFile(outputPath, body, \"utf8\");\n files.push(outputPath);\n }\n return { files };\n}\n\nfunction hasSiteUrl(siteUrl: string | undefined): boolean {\n return Boolean(siteUrl && siteUrl.trim());\n}\n\nfunction absoluteSitemapUrl(siteUrl: string | undefined, base: string): string {\n if (!hasSiteUrl(siteUrl)) {\n return \"\";\n }\n const origin = (siteUrl ?? \"\").trim().replace(/\\/+$/, \"\");\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return `${origin}${prefix}sitemap.xml`;\n}\n\nfunction generateSitemapXml(pages: readonly SiteMapPageInput[]): string {\n let xml =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\\n';\n for (const page of pages) {\n xml += \" <url>\\n <loc>\";\n xml += escapeXml(page.loc);\n xml += \"</loc>\\n </url>\\n\";\n }\n xml += \"</urlset>\\n\";\n return xml;\n}\n\nfunction generateRobotsTxt(sitemapLoc: string): string {\n let loc = \"\";\n for (const ch of sitemapLoc) {\n if (ch !== \"\\n\" && ch !== \"\\r\") {\n loc += ch;\n }\n }\n return `User-agent: *\\nAllow: /\\n\\nSitemap: ${loc}\\n`;\n}\n\nfunction generateLlmsTxt(input: SiteMapsRenderInput, pages: readonly SiteMapPageInput[]): string {\n let text = `# ${escapeLlmsText(input.siteName ?? \"\")}\\n\\n`;\n const siteDescription = input.siteDescription?.trim();\n if (siteDescription) {\n text += `> ${escapeLlmsText(siteDescription)}\\n\\n`;\n }\n text += \"## Pages\\n\\n\";\n for (const page of pages) {\n text += `- [${escapeLlmsText(page.title)}](${escapeLlmsUrl(page.loc)})`;\n const description = page.description?.trim();\n if (description) {\n text += `: ${escapeLlmsText(description)}`;\n }\n text += \"\\n\";\n }\n return text;\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n\nfunction flattenText(value: string): string {\n return value.split(/\\s+/u).filter(Boolean).join(\" \");\n}\n\nfunction escapeLlmsText(value: string): string {\n return flattenText(value).replace(/[\\\\[\\]()<>&\"]/g, (ch) => {\n switch (ch) {\n case \"\\\\\":\n return \"\\\\\\\\\";\n case \"[\":\n return \"\\\\[\";\n case \"]\":\n return \"\\\\]\";\n case \"(\":\n return \"\\\\(\";\n case \")\":\n return \"\\\\)\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case \"&\":\n return \"&amp;\";\n default:\n return \"&quot;\";\n }\n });\n}\n\nfunction escapeLlmsUrl(value: string): string {\n let escaped = \"\";\n for (const ch of value) {\n if (ch === \" \") {\n escaped += \"%20\";\n } else if (ch === \"(\") {\n escaped += \"%28\";\n } else if (ch === \")\") {\n escaped += \"%29\";\n } else if (ch !== \"\\n\" && ch !== \"\\r\" && ch !== \"\\t\") {\n escaped += ch;\n }\n }\n return escaped;\n}\n","/**\n * Opt-in draft / unlisted / scheduled page classification.\n */\n\nimport { importNapiModuleSync } from \"./napi\";\nimport type { PublishStateOptions, ResolvedPublishStateOptions } from \"./types\";\n\ninterface NavItemLike {\n title: string;\n path: string;\n href: string;\n children?: NavItemLike[];\n}\n\ninterface NavGroupLike {\n title: string;\n items: NavItemLike[];\n}\n\n/** One page considered for publish-state filtering. */\nexport interface PublishStatePage {\n inputPath: string;\n title: string;\n frontmatter: Record<string, unknown>;\n routePaths: {\n href: string;\n urlPath: string;\n };\n}\n\n/** Split pages into production output vs listing surfaces. */\nexport interface PartitionedPages<T> {\n output: T[];\n listed: T[];\n}\n\n/**\n * Resolves `publishState` with defaults.\n *\n * `false` / omitted stays off. `true` enables production filtering. An object\n * enables the feature and overrides only the fields the site set.\n */\nexport function resolvePublishStateOptions(\n value: boolean | PublishStateOptions | undefined,\n): ResolvedPublishStateOptions {\n if (!value) {\n return { enabled: false, includeDrafts: false };\n }\n if (value === true) {\n return { enabled: true, includeDrafts: false };\n }\n return {\n enabled: value.enabled ?? true,\n now: value.now,\n includeDrafts: value.includeDrafts ?? false,\n };\n}\n\n/** Classifies one frontmatter object. Never throws. */\nexport function classifyPublishState(\n frontmatter: Record<string, unknown>,\n options: ResolvedPublishStateOptions | undefined,\n): { output: boolean; listed: boolean } {\n try {\n return importNapiModuleSync().classifyPublishState(\n JSON.stringify(frontmatter ?? {}),\n toNapiPublishState(options),\n );\n } catch {\n return { output: true, listed: true };\n }\n}\n\n/** Splits pages into those that write HTML and those that appear in listings. */\nexport function partitionPublishedPages<T extends { frontmatter: Record<string, unknown> }>(\n pages: readonly T[],\n options: ResolvedPublishStateOptions | undefined,\n): PartitionedPages<T> {\n if (!options?.enabled) {\n return { output: [...pages], listed: [...pages] };\n }\n const output: T[] = [];\n const listed: T[] = [];\n for (const page of pages) {\n const decision = classifyPublishState(page.frontmatter, options);\n if (decision.output) {\n output.push(page);\n }\n if (decision.listed) {\n listed.push(page);\n }\n }\n return { output, listed };\n}\n\n/** Drops nav items that resolve to hidden (unpublished or unlisted) pages. */\nexport function filterNavGroups<T extends NavGroupLike>(\n groups: T[],\n hidden: ReadonlySet<string>,\n): T[] {\n return groups\n .map((group) => ({\n ...group,\n items: filterNavItems(group.items, hidden),\n }))\n .filter((group) => group.items.length > 0);\n}\n\nfunction filterNavItems<T extends NavItemLike>(items: T[], hidden: ReadonlySet<string>): T[] {\n const kept: SsgNavItem[] = [];\n for (const item of items) {\n if (isHiddenNavTarget(item, hidden)) {\n continue;\n }\n const children = item.children?.length ? filterNavItems(item.children, hidden) : item.children;\n kept.push(children === item.children ? item : { ...item, children });\n }\n return kept;\n}\n\nfunction isHiddenNavTarget(item: NavItemLike, hidden: ReadonlySet<string>): boolean {\n return hidden.has(item.path) || hidden.has(item.href);\n}\n\n/** Keys used to match a page against generated nav items. */\nexport function hiddenNavKeys(\n pages: readonly PublishStatePage[],\n listed: readonly PublishStatePage[],\n): Set<string> {\n const listedPaths = new Set(listed.map((page) => page.inputPath));\n const hidden = new Set<string>();\n for (const page of pages) {\n if (listedPaths.has(page.inputPath)) {\n continue;\n }\n hidden.add(page.routePaths.urlPath);\n hidden.add(page.routePaths.href);\n }\n return hidden;\n}\n\nexport function toNapiPublishState(\n options: ResolvedPublishStateOptions | undefined,\n): { enabled?: boolean; now?: string; includeDrafts?: boolean } | undefined {\n if (!options) {\n return undefined;\n }\n return {\n enabled: options.enabled,\n now: options.now,\n includeDrafts: options.includeDrafts,\n };\n}\n","/**\n * Opt-in permalink / slug routing and `_index` frontmatter cascade.\n *\n * Resolution follows `ox_content_ssg::resolve_page_routes`. The Vite plugin\n * applies those URLs during SSG and collection manifest builds.\n */\n\nimport type {\n CascadeOptions,\n PermalinksOptions,\n ResolvedCascadeOptions,\n ResolvedPermalinksOptions,\n} from \"./types\";\n\nconst RESERVED_CASCADE_KEYS = new Set([\"permalink\", \"slug\"]);\n\n/** One page considered for cascade and permalink resolution. */\nexport interface RoutePageInput {\n source: string;\n fileUrl: string;\n frontmatter: Record<string, unknown>;\n}\n\n/** A page after cascade and optional permalink / slug rewriting. */\nexport interface ResolvedRoutePage {\n source: string;\n urlPath: string;\n frontmatter: Record<string, unknown>;\n}\n\n/** Resolved pages plus collision / rejection errors. */\nexport interface RouteResolveOutput {\n pages: ResolvedRoutePage[];\n errors: string[];\n}\n\n/** Resolves `permalinks`. `false` / omitted stays off. `true` / `{}` enables. */\nexport function resolvePermalinksOptions(\n value: boolean | PermalinksOptions | undefined,\n): ResolvedPermalinksOptions {\n return resolveFlag(value);\n}\n\n/** Resolves `cascade`. `false` / omitted stays off. `true` / `{}` enables. */\nexport function resolveCascadeOptions(\n value: boolean | CascadeOptions | undefined,\n): ResolvedCascadeOptions {\n return resolveFlag(value);\n}\n\n/**\n * Applies cascade (when on) then permalink / slug rewriting (when on).\n *\n * Collisions skip the later page and keep the first. Rejected permalinks stay\n * on the file-tree URL. Hostile non-string values are ignored.\n */\nexport function resolvePageRoutes(input: {\n pages: readonly RoutePageInput[];\n permalinks?: ResolvedPermalinksOptions | null;\n cascade?: ResolvedCascadeOptions | null;\n}): RouteResolveOutput {\n const cascaded = applyCascade(input.pages, input.cascade);\n if (!input.permalinks?.enabled) {\n return {\n pages: cascaded.map((page) => ({\n source: page.source,\n urlPath: normalizeUrlPath(page.fileUrl),\n frontmatter: page.frontmatter,\n })),\n errors: [],\n };\n }\n\n const pages: ResolvedRoutePage[] = [];\n const errors: string[] = [];\n const claimed = new Map<string, string>();\n for (const page of cascaded) {\n const { urlPath, error } = resolveOne(page);\n if (error) {\n errors.push(error);\n }\n const owner = claimed.get(urlPath);\n if (owner) {\n errors.push(\n `[ox-content] URL collision at \"${urlPath}\": ${owner} kept, ${page.source} skipped`,\n );\n continue;\n }\n claimed.set(urlPath, page.source);\n pages.push({ source: page.source, urlPath, frontmatter: page.frontmatter });\n }\n return { pages, errors };\n}\n\n/** Escapes a value for use in an HTML attribute. */\nexport function escapeAttribute(value: string): string {\n return value.replace(/[&<>\"']/gu, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n\nexport function normalizeUrlPath(value: string): string {\n const segments = pathSegments(value);\n return segments.length === 0 ? \"/\" : segments.join(\"/\");\n}\n\nfunction resolveFlag(value: boolean | { enabled?: boolean } | undefined): { enabled: boolean } {\n if (!value) {\n return { enabled: false };\n }\n if (value === true) {\n return { enabled: true };\n }\n return { enabled: value.enabled !== false };\n}\n\nfunction applyCascade(\n pages: readonly RoutePageInput[],\n options?: ResolvedCascadeOptions | null,\n): RoutePageInput[] {\n if (!options?.enabled) {\n return pages.map((page) => ({ ...page, frontmatter: { ...page.frontmatter } }));\n }\n const indexes = new Map<string, Record<string, unknown>>();\n for (const page of pages) {\n const source = normalizeSeparators(page.source);\n if (isIndexFile(source)) {\n indexes.set(directoryOf(source), { ...page.frontmatter });\n }\n }\n return pages.map((page) => {\n const source = normalizeSeparators(page.source);\n const frontmatter = { ...page.frontmatter };\n for (const dir of ancestorDirs(source)) {\n const defaults = indexes.get(dir);\n if (!defaults || (isIndexFile(source) && directoryOf(source) === dir)) {\n continue;\n }\n for (const [key, value] of Object.entries(defaults)) {\n if (!RESERVED_CASCADE_KEYS.has(key) && !(key in frontmatter)) {\n frontmatter[key] = value;\n }\n }\n }\n return { ...page, frontmatter };\n });\n}\n\nfunction resolveOne(page: RoutePageInput): { urlPath: string; error?: string } {\n const fileUrl = normalizeUrlPath(page.fileUrl);\n const permalink = readString(page.frontmatter.permalink);\n if (permalink !== undefined) {\n const url = isSafePermalink(permalink) ? normalizeUrlPath(permalink) : undefined;\n return url\n ? { urlPath: url }\n : {\n urlPath: fileUrl,\n error: `[ox-content] rejected permalink ${JSON.stringify(permalink)} on ${page.source} (path escape); using the file-tree URL`,\n };\n }\n const slug = readString(page.frontmatter.slug);\n if (slug !== undefined) {\n const url = rewriteSlug(fileUrl, slug);\n return url\n ? { urlPath: url }\n : {\n urlPath: fileUrl,\n error: `[ox-content] rejected slug ${JSON.stringify(slug)} on ${page.source} (path escape); using the file-tree URL`,\n };\n }\n return { urlPath: fileUrl };\n}\n\nfunction rewriteSlug(fileUrl: string, slug: string): string | undefined {\n const trimmed = slug.trim();\n if (trimmed.includes(\"/\") || !isSafePermalink(trimmed)) {\n return undefined;\n }\n const normalized = normalizeUrlPath(trimmed);\n if (normalized === \"/\") {\n return undefined;\n }\n if (fileUrl === \"/\") {\n return normalized;\n }\n const segments = fileUrl.split(\"/\").filter(Boolean);\n segments.pop();\n segments.push(normalized);\n return segments.join(\"/\");\n}\n\nfunction isSafePermalink(value: string): boolean {\n const trimmed = value.trim();\n if (!trimmed || /[\\n\\r\\0]/u.test(trimmed) || trimmed.includes(\"\\\\\") || trimmed.startsWith(\"//\")) {\n return false;\n }\n if (/^[A-Za-z]:/u.test(trimmed)) {\n return false;\n }\n const lower = trimmed.toLowerCase();\n if (\n lower.includes(\"javascript:\") ||\n lower.includes(\"data:\") ||\n lower.includes(\"vbscript:\") ||\n lower.includes(\"file:\") ||\n lower.includes(\"://\")\n ) {\n return false;\n }\n return pathSegments(trimmed).every((segment) => segment !== \"..\" && segment !== \".\");\n}\n\nfunction pathSegments(value: string): string[] {\n return value\n .trim()\n .replace(/^\\/+|\\/+$/gu, \"\")\n .split(\"/\")\n .filter(Boolean);\n}\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction normalizeSeparators(value: string): string {\n return value.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction isIndexFile(source: string): boolean {\n const name = source.split(\"/\").pop() ?? source;\n const stem = name.includes(\".\") ? name.slice(0, name.lastIndexOf(\".\")) : name;\n return stem.toLowerCase() === \"_index\";\n}\n\nfunction directoryOf(source: string): string {\n const index = source.lastIndexOf(\"/\");\n return index === -1 ? \"\" : source.slice(0, index);\n}\n\nfunction ancestorDirs(source: string): string[] {\n const dir = directoryOf(source);\n const dirs = [\"\"];\n if (!dir) {\n return dirs;\n }\n let acc = \"\";\n for (const segment of dir.split(\"/\")) {\n acc = acc ? `${acc}/${segment}` : segment;\n dirs.push(acc);\n }\n return dirs;\n}\n","/**\n * Applies resolved permalinks / cascade to SSG pages and collection entries.\n */\n\nimport * as path from \"node:path\";\nimport { importNapiModuleSync } from \"./napi\";\nimport { normalizeUrlPath, resolvePageRoutes } from \"./permalinks\";\nimport type {\n CollectionManifest,\n ResolvedCascadeOptions,\n ResolvedPermalinksOptions,\n} from \"./types\";\n\n/** SSG page shape that can have its `routePaths` rewritten. */\nexport interface SsgRoutablePage {\n inputPath: string;\n routePaths: {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n };\n frontmatter: Record<string, unknown>;\n}\n\ninterface NavItem {\n title: string;\n path: string;\n href: string;\n children?: NavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\ninterface NavGroup {\n title: string;\n items: NavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/** Rewrites SSG `routePaths` from resolved permalinks / slugs. */\nexport function applySsgPageRoutes(input: {\n pages: readonly SsgRoutablePage[];\n permalinks?: ResolvedPermalinksOptions | null;\n cascade?: ResolvedCascadeOptions | null;\n srcDir: string;\n outDir: string;\n base: string;\n extension: string;\n siteUrl?: string;\n}): { pages: SsgRoutablePage[]; errors: string[] } {\n const resolved = resolvePageRoutes({\n pages: input.pages.map((page) => ({\n source: page.inputPath,\n fileUrl: page.routePaths.urlPath,\n frontmatter: page.frontmatter,\n })),\n permalinks: input.permalinks,\n cascade: input.cascade,\n });\n const bySource = new Map(resolved.pages.map((page) => [page.source, page]));\n const pages: SsgRoutablePage[] = [];\n for (const page of input.pages) {\n const hit = bySource.get(page.inputPath);\n if (!hit) {\n continue;\n }\n pages.push({\n ...page,\n frontmatter: hit.frontmatter,\n routePaths: routePathsFromUrl(\n hit.urlPath,\n input.srcDir,\n input.outDir,\n input.base,\n input.extension,\n input.siteUrl,\n ),\n });\n }\n return { pages, errors: resolved.errors };\n}\n\n/** Rewrites collection `path` / `stem` / inherited frontmatter. */\nexport function applyCollectionRoutes(\n manifest: CollectionManifest,\n permalinks?: ResolvedPermalinksOptions | null,\n cascade?: ResolvedCascadeOptions | null,\n): { manifest: CollectionManifest; errors: string[] } {\n if (!permalinks?.enabled && !cascade?.enabled) {\n return { manifest, errors: [] };\n }\n const errors: string[] = [];\n const collections: CollectionManifest[\"collections\"] = {};\n for (const [name, entries] of Object.entries(manifest.collections)) {\n const resolved = resolvePageRoutes({\n pages: entries.map((entry) => ({\n source: entry.source,\n fileUrl: entry.path,\n frontmatter: { ...entry.frontmatter },\n })),\n permalinks,\n cascade,\n });\n errors.push(...resolved.errors);\n const bySource = new Map(resolved.pages.map((page) => [page.source, page]));\n collections[name] = entries.flatMap((entry) => {\n const hit = bySource.get(entry.source);\n if (!hit) {\n return [];\n }\n const urlPath = hit.urlPath;\n const pathValue = urlPath === \"/\" ? \"/\" : `/${urlPath.replace(/^\\/+/u, \"\")}`;\n return [\n {\n ...entry,\n ...pickInherited(hit.frontmatter),\n path: pathValue,\n stem: pathValue === \"/\" ? \"\" : pathValue.slice(1),\n frontmatter: hit.frontmatter,\n },\n ];\n });\n }\n return { manifest: { collections }, errors };\n}\n\n/** Updates auto-nav hrefs after permalinks change a page URL. */\nexport function remapNavGroups<T extends NavGroup>(\n nav: T[],\n kept: readonly { fileUrl: string; urlPath: string; href: string }[],\n skippedFileUrls: readonly string[],\n): T[] {\n const skipped = new Set(skippedFileUrls.map(normalizeUrlPath));\n const byFile = new Map(kept.map((page) => [normalizeUrlPath(page.fileUrl), page]));\n return nav\n .map((group) => ({ ...group, items: remapNavItems(group.items, byFile, skipped) }))\n .filter((group) => group.items.length > 0);\n}\n\nfunction routePathsFromUrl(\n urlPath: string,\n srcDir: string,\n outDir: string,\n base: string,\n extension: string,\n siteUrl?: string,\n) {\n const relative =\n urlPath === \"/\" || !urlPath ? \"index.md\" : `${urlPath.replace(/^\\/+|\\/+$/gu, \"\")}.md`;\n return importNapiModuleSync().resolveSsgRoutePaths(\n path.join(srcDir, relative),\n srcDir,\n outDir,\n base,\n extension,\n siteUrl,\n );\n}\n\nfunction remapNavItems<T extends NavItem>(\n items: T[],\n byFile: Map<string, { urlPath: string; href: string }>,\n skipped: Set<string>,\n): T[] {\n return items.flatMap((item) => {\n const key = normalizeUrlPath(item.path);\n if (skipped.has(key)) {\n return [];\n }\n const hit = byFile.get(key);\n const children = item.children ? remapNavItems(item.children, byFile, skipped) : undefined;\n return [{ ...item, path: hit?.urlPath ?? item.path, href: hit?.href ?? item.href, children }];\n });\n}\n\nfunction pickInherited(frontmatter: Record<string, unknown>): Record<string, unknown> {\n const skip = new Set([\"id\", \"collection\", \"path\", \"stem\", \"source\", \"extension\", \"frontmatter\"]);\n const picked: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(frontmatter)) {\n if (!skip.has(key)) {\n picked[key] = value;\n }\n }\n return picked;\n}\n","/**\n * Opt-in static redirects / aliases.\n *\n * HTML bodies follow `ox_content_ssg::generate_redirects`. The Vite plugin\n * writes those files during SSG without adding a NAPI surface.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { RedirectsOptions, ResolvedRedirectsOptions } from \"./types\";\n\nconst OPTION_KEYS = new Set([\"map\", \"netlify\", \"headers\", \"json\", \"allowExternal\"]);\n\n/** One page that may declare aliases or a single `redirect` source. */\nexport interface RedirectPageInput {\n dest: string;\n aliases?: unknown;\n redirect?: unknown;\n}\n\n/** Inputs for planning redirect files. */\nexport interface RedirectPlanInput {\n options?: ResolvedRedirectsOptions | null;\n base?: string;\n pages: readonly RedirectPageInput[];\n}\n\n/** One planned static HTML redirect. */\nexport interface RedirectFilePlan {\n from: string;\n to: string;\n relativePath: string;\n html: string;\n}\n\n/** Planned redirect files and optional host / JSON bodies. */\nexport interface RedirectPlan {\n files: RedirectFilePlan[];\n netlify?: string;\n headers?: string;\n json?: string;\n}\n\n/** Inputs for writing redirect files next to generated HTML. */\nexport interface WriteRedirectFilesInput {\n outDir: string;\n base?: string;\n options?: ResolvedRedirectsOptions;\n pages: readonly RedirectPageInput[];\n}\n\n/**\n * Resolves `redirects` with defaults.\n *\n * `false` / omitted stays off. `true` or `{}` enables empty defaults.\n * A path map (`{ \"/old\": \"/new\" }`) enables the feature with that map.\n * `{ map, netlify, headers, json, allowExternal }` overrides only set fields.\n */\nexport function resolveRedirectsOptions(\n value: boolean | RedirectsOptions | Record<string, string> | undefined,\n): ResolvedRedirectsOptions {\n if (!value) {\n return {\n enabled: false,\n map: {},\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n map: {},\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n };\n }\n if (isOptionsObject(value)) {\n return {\n enabled: true,\n map: { ...value.map },\n netlify: value.netlify ?? false,\n headers: value.headers ?? false,\n json: value.json ?? false,\n allowExternal: value.allowExternal ?? false,\n };\n }\n return {\n enabled: true,\n map: { ...value },\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n };\n}\n\n/** Plans redirect HTML files without writing them. */\nexport function planRedirectFiles(input: RedirectPlanInput): RedirectPlan {\n if (!input.options?.enabled) {\n return { files: [] };\n }\n\n const occupied = new Set<string>();\n for (const page of input.pages) {\n const dest = normalizePath(page.dest);\n if (dest) {\n occupied.add(dest);\n }\n }\n\n const files: RedirectFilePlan[] = [];\n const index = new Map<string, number>();\n\n for (const page of input.pages) {\n const to = normalizeDest(page.dest, input.options.allowExternal);\n if (!to) {\n continue;\n }\n for (const alias of readStringList(page.aliases)) {\n upsert(files, index, occupied, alias, to, input.base);\n }\n if (typeof page.redirect === \"string\") {\n upsert(files, index, occupied, page.redirect, to, input.base);\n }\n }\n for (const [from, to] of Object.entries(input.options.map)) {\n const dest = normalizeDest(to, input.options.allowExternal);\n if (!dest) {\n continue;\n }\n upsert(files, index, occupied, from, dest, input.base);\n }\n\n if (files.length === 0) {\n return { files: [] };\n }\n\n const plan: RedirectPlan = { files };\n if (input.options.netlify) {\n plan.netlify = files.map((file) => `${file.from} ${file.to} 301`).join(\"\\n\") + \"\\n\";\n }\n if (input.options.headers) {\n plan.headers = files.map((file) => `${file.from}\\n Location: ${file.to}`).join(\"\\n\") + \"\\n\";\n }\n if (input.options.json) {\n plan.json = JSON.stringify(files.map((file) => ({ from: file.from, to: file.to })));\n }\n return plan;\n}\n\n/** Writes planned redirect HTML (and optional host files) into `outDir`. */\nexport async function writeRedirectFiles(\n input: WriteRedirectFilesInput,\n): Promise<{ files: string[] }> {\n const plan = planRedirectFiles(input);\n if (plan.files.length === 0 && !plan.netlify && !plan.headers && !plan.json) {\n return { files: [] };\n }\n\n await fs.mkdir(input.outDir, { recursive: true });\n const files: string[] = [];\n for (const entry of plan.files) {\n const outputPath = path.join(input.outDir, entry.relativePath);\n try {\n await fs.access(outputPath);\n continue;\n } catch {\n await fs.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.writeFile(outputPath, entry.html, \"utf8\");\n files.push(outputPath);\n }\n }\n for (const [body, name] of [\n [plan.netlify, \"_redirects\"],\n [plan.headers, \"_headers\"],\n [plan.json, \"redirects.json\"],\n ] as const) {\n if (!body) {\n continue;\n }\n const outputPath = path.join(input.outDir, name);\n await fs.writeFile(outputPath, body, \"utf8\");\n files.push(outputPath);\n }\n return { files };\n}\n\n/** Static HTML redirect body. `dest` is escaped. */\nexport function generateRedirectHtml(dest: string): string {\n const escaped = escapeHtml(dest);\n return `\\\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta http-equiv=\"refresh\" content=\"0;url=${escaped}\">\n<link rel=\"canonical\" href=\"${escaped}\">\n<title>Redirecting</title>\n</head>\n<body>\n<p>Redirecting to <a href=\"${escaped}\">${escaped}</a>.</p>\n</body>\n</html>\n`;\n}\n\n/** Same-origin path: leading `/`, not `//`, and no scheme. */\nexport function isSafeDest(value: string): boolean {\n return isAllowedDest(value, false);\n}\n\n/** Strips a trailing slash except for `/`. Unsafe values become `null`. */\nexport function normalizePath(value: string): string | null {\n return normalizeDest(value, false);\n}\n\nfunction normalizeDest(value: string, allowExternal: boolean): string | null {\n if (!isAllowedDest(value, allowExternal)) {\n return null;\n }\n const trimmed = value.trim();\n if (isHttpUrl(trimmed)) {\n return trimmed;\n }\n if (trimmed === \"/\") {\n return \"/\";\n }\n return trimmed.replace(/\\/+$/u, \"\");\n}\n\nfunction isAllowedDest(value: string, allowExternal: boolean): boolean {\n const trimmed = value.trim();\n if (!trimmed || hasDisallowedDestChars(trimmed)) {\n return false;\n }\n if (isHttpUrl(trimmed)) {\n return allowExternal;\n }\n if (!trimmed.startsWith(\"/\") || trimmed.startsWith(\"//\") || hasUnsafePathSegments(trimmed)) {\n return false;\n }\n const lower = trimmed.toLowerCase();\n return !lower.includes(\"javascript:\") && !lower.includes(\"data:\") && !lower.includes(\"://\");\n}\n\nfunction hasDisallowedDestChars(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || code === 0x7f || code === 0x3b) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasUnsafePathSegments(value: string): boolean {\n return (\n value.includes(\"\\\\\") || value.split(\"/\").some((segment) => segment === \".\" || segment === \"..\")\n );\n}\n\nfunction isHttpUrl(value: string): boolean {\n const lower = value.toLowerCase();\n return lower.startsWith(\"https://\") || lower.startsWith(\"http://\");\n}\n\nfunction isOptionsObject(\n value: RedirectsOptions | Record<string, string>,\n): value is RedirectsOptions {\n return Object.keys(value).some((key) => OPTION_KEYS.has(key));\n}\n\nfunction readStringList(value: unknown): string[] {\n if (typeof value === \"string\") {\n return [value];\n }\n if (!Array.isArray(value)) {\n return [];\n }\n return value.filter((entry): entry is string => typeof entry === \"string\");\n}\n\nfunction applyBase(dest: string, base: string | undefined): string {\n if (isHttpUrl(dest) || !base || base === \"/\") {\n return dest;\n }\n const prefix = base.replace(/\\/+$/u, \"\");\n return dest === \"/\" ? `${prefix}/` : `${prefix}${dest}`;\n}\n\nfunction upsert(\n files: RedirectFilePlan[],\n index: Map<string, number>,\n occupied: Set<string>,\n from: string,\n to: string,\n base: string | undefined,\n): void {\n const source = normalizePath(from);\n if (!source || source === to || occupied.has(source)) {\n return;\n }\n const href = applyBase(to, base);\n const html = generateRedirectHtml(href);\n const relativePath = source === \"/\" ? \"index.html\" : `${source.slice(1)}/index.html`;\n const slot = index.get(source);\n if (slot !== undefined) {\n files[slot] = { from: source, to, relativePath, html };\n return;\n }\n index.set(source, files.length);\n files.push({ from: source, to, relativePath, html });\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n","/**\n * Opt-in custom 404 page helpers.\n *\n * Resolution and path rules live here. The Vite plugin writes the themed HTML\n * during SSG and omits the page from the search index and sitemap.\n */\n\nimport * as path from \"node:path\";\nimport type { NotFoundOptions, ResolvedNotFoundOptions } from \"./types\";\nimport { stripMarkdownExtension } from \"./markdown\";\n\nexport const DEFAULT_NOT_FOUND_SOURCE = \"404.md\";\nexport const DEFAULT_NOT_FOUND_OUTPUT = \"404.html\";\nexport const FALLBACK_NOT_FOUND_TITLE = \"Page not found\";\n\n/** Built-in Markdown used when the configured source file is missing. */\nexport const FALLBACK_NOT_FOUND_MARKDOWN = `---\ntitle: ${FALLBACK_NOT_FOUND_TITLE}\n---\n\n# ${FALLBACK_NOT_FOUND_TITLE}\n\nThe page you requested does not exist. Use search or the navigation to find what you need.\n`;\n\n/**\n * Resolves `ssg.notFound` with defaults.\n *\n * `false` / omitted stays off. `true` enables `404.md` → `404.html`. An object\n * enables the feature and overrides only the fields the site set.\n */\nexport function resolveNotFoundOptions(\n value: boolean | NotFoundOptions | undefined,\n): ResolvedNotFoundOptions {\n if (!value) {\n return {\n enabled: false,\n source: DEFAULT_NOT_FOUND_SOURCE,\n output: DEFAULT_NOT_FOUND_OUTPUT,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n source: DEFAULT_NOT_FOUND_SOURCE,\n output: DEFAULT_NOT_FOUND_OUTPUT,\n };\n }\n return {\n enabled: true,\n source: value.source ?? DEFAULT_NOT_FOUND_SOURCE,\n output: value.output ?? DEFAULT_NOT_FOUND_OUTPUT,\n };\n}\n\n/** Absolute source path, confined to `srcDir`. */\nexport function resolveNotFoundSourcePath(srcDir: string, source: string): string {\n return resolveContainedPath(srcDir, source, DEFAULT_NOT_FOUND_SOURCE);\n}\n\n/** Absolute output path, confined to `outDir`. */\nexport function resolveNotFoundOutputPath(outDir: string, output: string): string {\n return resolveContainedPath(outDir, output, DEFAULT_NOT_FOUND_OUTPUT);\n}\n\n/** True when `filePath` is the enabled not-found source. */\nexport function isNotFoundSourceFile(\n filePath: string,\n srcDir: string,\n options?: ResolvedNotFoundOptions,\n): boolean {\n if (!options?.enabled) {\n return false;\n }\n return path.resolve(filePath) === resolveNotFoundSourcePath(srcDir, options.source);\n}\n\n/** Search document id for a not-found source path. */\nexport function notFoundSearchDocumentId(source: string): string {\n const normalized = source.replaceAll(\"\\\\\", \"/\").replace(/^\\.?\\//, \"\");\n return stripMarkdownExtension(normalized);\n}\n\n/** Search document ids that must not be indexed when the feature is on. */\nexport function notFoundSearchExcludeIds(options?: ResolvedNotFoundOptions): string[] {\n if (!options?.enabled) {\n return [];\n }\n return [notFoundSearchDocumentId(options.source)];\n}\n\nfunction resolveContainedPath(rootDir: string, relativePath: string, fallback: string): string {\n const root = path.resolve(rootDir);\n const resolved = path.resolve(root, relativePath);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved === root || resolved.startsWith(prefix)) {\n return resolved;\n }\n return path.join(root, fallback);\n}\n","import type { CollectionManifest } from \"./types\";\n\nconst runtime = String.raw`\nfunction getValue(row, field) {\n if (field in row) return row[field];\n return String(field)\n .split(\".\")\n .reduce((value, key) => (value == null ? undefined : value[key]), row);\n}\n\nfunction normalizePath(value) {\n const path = String(value || \"/\");\n if (path === \"/\") return path;\n return path.startsWith(\"/\") ? path.replace(/\\/+$/, \"\") : \"/\" + path.replace(/\\/+$/, \"\");\n}\n\nfunction likePattern(value) {\n const escaped = String(value).replace(/[\\\\^$.*+?()[\\]{}|]/g, \"\\\\$&\");\n return new RegExp(\"^\" + escaped.replace(/%/g, \".*\").replace(/_/g, \".\") + \"$\", \"i\");\n}\n\nfunction compare(left, right) {\n if (left == null && right == null) return 0;\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === \"number\" && typeof right === \"number\") return left - right;\n if (left instanceof Date || right instanceof Date) {\n return new Date(left).getTime() - new Date(right).getTime();\n }\n return String(left).localeCompare(String(right), undefined, {\n numeric: true,\n sensitivity: \"base\",\n });\n}\n\nfunction createPredicate(field, operator, value) {\n let op = String(operator ?? \"=\").toUpperCase();\n let expected = value;\n if (arguments.length === 2) {\n op = \"=\";\n expected = operator;\n }\n\n return (row) => {\n const actual = getValue(row, field);\n switch (op) {\n case \"=\":\n case \"==\":\n return actual === expected;\n case \"!=\":\n case \"<>\":\n return actual !== expected;\n case \">\":\n return compare(actual, expected) > 0;\n case \">=\":\n return compare(actual, expected) >= 0;\n case \"<\":\n return compare(actual, expected) < 0;\n case \"<=\":\n return compare(actual, expected) <= 0;\n case \"IN\":\n return Array.isArray(expected) && expected.includes(actual);\n case \"NOT IN\":\n return Array.isArray(expected) && !expected.includes(actual);\n case \"BETWEEN\":\n return Array.isArray(expected) && expected.length >= 2\n ? compare(actual, expected[0]) >= 0 && compare(actual, expected[1]) <= 0\n : false;\n case \"NOT BETWEEN\":\n return Array.isArray(expected) && expected.length >= 2\n ? compare(actual, expected[0]) < 0 || compare(actual, expected[1]) > 0\n : false;\n case \"IS NULL\":\n return actual == null;\n case \"IS NOT NULL\":\n return actual != null;\n case \"LIKE\":\n return likePattern(expected).test(String(actual ?? \"\"));\n case \"NOT LIKE\":\n return !likePattern(expected).test(String(actual ?? \"\"));\n default:\n throw new Error(\"Unsupported collection query operator: \" + op);\n }\n };\n}\n\nclass QueryGroup {\n constructor(rows) {\n this.rows = rows;\n this.conditions = [];\n }\n\n where(field, operator, value) {\n const test =\n arguments.length === 2\n ? createPredicate(field, operator)\n : createPredicate(field, operator, value);\n this.conditions.push({ join: \"and\", test });\n return this;\n }\n\n andWhere(factory) {\n const group = new QueryGroup(this.rows);\n factory(group);\n this.conditions.push({ join: \"and\", test: (row) => group.test(row) });\n return this;\n }\n\n orWhere(factory) {\n const group = new QueryGroup(this.rows);\n factory(group);\n this.conditions.push({ join: \"or\", test: (row) => group.test(row) });\n return this;\n }\n\n test(row) {\n let matched = true;\n for (const condition of this.conditions) {\n matched =\n condition.join === \"or\" ? matched || condition.test(row) : matched && condition.test(row);\n }\n return matched;\n }\n}\n\nclass CollectionQueryBuilder extends QueryGroup {\n constructor(rows) {\n super(rows);\n this.orders = [];\n this.selected = undefined;\n this.offset = 0;\n this.max = undefined;\n }\n\n path(path) {\n return this.where(\"path\", \"=\", normalizePath(path));\n }\n\n select(...fields) {\n this.selected = fields;\n return this;\n }\n\n order(field, direction = \"ASC\") {\n this.orders.push({ field, direction: String(direction).toUpperCase() });\n return this;\n }\n\n limit(limit) {\n this.max = Math.max(0, Number(limit) || 0);\n return this;\n }\n\n skip(skip) {\n this.offset = Math.max(0, Number(skip) || 0);\n return this;\n }\n\n materialize() {\n let rows = this.conditions.length ? this.rows.filter((row) => this.test(row)) : this.rows;\n if (this.orders.length) {\n rows = [...rows].sort((left, right) => {\n for (const order of this.orders) {\n const result = compare(getValue(left, order.field), getValue(right, order.field));\n if (result !== 0) return order.direction === \"DESC\" ? -result : result;\n }\n return 0;\n });\n }\n if (this.offset || this.max !== undefined) {\n rows = rows.slice(this.offset, this.max === undefined ? undefined : this.offset + this.max);\n }\n if (!this.selected) return rows;\n return rows.map((row) => {\n const selected = {};\n for (const field of this.selected) selected[field] = getValue(row, field);\n return selected;\n });\n }\n\n async all() {\n return this.materialize();\n }\n\n async first() {\n return this.materialize()[0] ?? null;\n }\n\n async count() {\n return this.conditions.length\n ? this.rows.filter((row) => this.test(row)).length\n : this.rows.length;\n }\n}\n\nexport function getCollection(name) {\n return collections[name] ? [...collections[name]] : [];\n}\n\nexport function queryCollection(name) {\n return new CollectionQueryBuilder(collections[name] || []);\n}\n\nexport const collectionNames = Object.keys(collections);\nexport { CollectionQueryBuilder };\nexport default { collections, collectionNames, getCollection, queryCollection };\n`;\n\nexport function generateCollectionsModule(manifest: CollectionManifest): string {\n return `const collections = ${JSON.stringify(manifest.collections)};\\n${runtime}`;\n}\n","import * as path from \"node:path\";\nimport { applyCollectionRoutes } from \"./apply-permalinks\";\nimport { generateCollectionsModule } from \"./collections-runtime\";\nimport { importNapiModule } from \"./napi\";\nimport type {\n CollectionManifest,\n CollectionOptions,\n CollectionsOptions,\n ResolvedCollectionsOptions,\n ResolvedOptions,\n} from \"./types\";\n\nconst DEFAULT_COLLECTION_NAME = \"content\";\nconst DEFAULT_COLLECTION_SOURCE = \"**/*\";\n\ntype NativeCollectionDefinition = {\n name: string;\n source: string[];\n include: string[];\n};\n\ntype NativeTransformOptions = {\n gfm?: boolean;\n footnotes?: boolean;\n taskLists?: boolean;\n tables?: boolean;\n strikethrough?: boolean;\n autolinks?: boolean;\n autolinkUrls?: boolean;\n frontmatter?: boolean;\n tocMaxDepth?: number;\n codeAnnotations?: boolean;\n codeAnnotationMetaKey?: string;\n codeAnnotationSyntax?: string;\n codeAnnotationDefaultLineNumbers?: boolean;\n wikiLinks?: { enabled?: boolean; baseUrl?: string };\n emojiShortcodes?: { enabled?: boolean; custom?: Record<string, string> };\n attributes?: { enabled?: boolean };\n badges?: { enabled?: boolean };\n containers?: {\n enabled?: boolean;\n types?: Record<string, { title?: string; tag?: string }>;\n };\n images?: { enabled?: boolean; lazy?: boolean };\n cjkEmphasis?: boolean;\n codeImports?: { enabled?: boolean; rootDir?: string };\n includes?: { enabled?: boolean; rootDir?: string };\n steps?: { enabled?: boolean };\n fileTree?: { enabled?: boolean };\n editThisPage?: {\n enabled?: boolean;\n repoUrl?: string;\n branch?: string;\n rootDir?: string;\n label?: string;\n };\n math?: boolean | { enabled?: boolean };\n};\n\ntype BuildCollectionManifestNapi = {\n buildCollectionManifest: (options: {\n srcDir: string;\n extensions: string[];\n frontmatter?: boolean;\n collections: NativeCollectionDefinition[];\n transformOptions?: NativeTransformOptions;\n }) => string;\n};\n\nexport function defineCollection<T extends CollectionOptions>(collection: T): T {\n return collection;\n}\n\nexport function defineCollections<T extends CollectionsOptions>(collections: T): T {\n return collections;\n}\n\nexport function resolveCollectionsOptions(\n options: CollectionsOptions | boolean | undefined,\n): ResolvedCollectionsOptions {\n if (options === false) {\n return { enabled: false, collections: {} };\n }\n\n const source = options === true || options === undefined ? defaultCollections() : options;\n const collections: ResolvedCollectionsOptions[\"collections\"] = {};\n\n for (const [name, value] of Object.entries(source)) {\n const collection = normalizeCollectionOptions(value);\n collections[name] = {\n name,\n source: normalizeSourcePatterns(collection.source),\n include: [...new Set(collection.include ?? [])],\n };\n }\n\n return { enabled: true, collections };\n}\n\nexport async function buildCollectionManifest(\n root: string,\n options: ResolvedOptions,\n): Promise<CollectionManifest> {\n if (!options.collections.enabled) {\n return { collections: {} };\n }\n\n const napi = (await importNapiModule()) as unknown as BuildCollectionManifestNapi;\n const manifestJson = napi.buildCollectionManifest({\n srcDir: path.resolve(root, options.srcDir),\n extensions: [...options.extensions],\n frontmatter: options.frontmatter,\n collections: Object.values(options.collections.collections).map((collection) => ({\n name: collection.name,\n source: collection.source,\n include: collection.include,\n })),\n transformOptions: createNativeTransformOptions(options),\n });\n\n const { manifest, errors } = applyCollectionRoutes(\n parseCollectionManifest(manifestJson),\n options.permalinks,\n options.cascade,\n );\n for (const error of errors) {\n console.warn(error);\n }\n return manifest;\n}\n\nexport async function generateCollectionsVirtualModule(\n root: string,\n options: ResolvedOptions,\n): Promise<string> {\n return generateCollectionsModule(await buildCollectionManifest(root, options));\n}\n\nfunction normalizeCollectionOptions(\n options: CollectionOptions | string | readonly string[],\n): CollectionOptions {\n if (typeof options === \"string\" || Array.isArray(options)) {\n return { source: options };\n }\n return options as CollectionOptions;\n}\n\nfunction normalizeSourcePatterns(source: CollectionOptions[\"source\"]): string[] {\n const values = Array.isArray(source) ? source : [source ?? DEFAULT_COLLECTION_SOURCE];\n return values.map((value) => value || DEFAULT_COLLECTION_SOURCE);\n}\n\nfunction parseCollectionManifest(json: string): CollectionManifest {\n const value = JSON.parse(json) as unknown;\n if (!value || typeof value !== \"object\" || !(\"collections\" in value)) {\n throw new Error(\"[ox-content] Native collection manifest returned an invalid payload.\");\n }\n return value as CollectionManifest;\n}\n\nfunction createNativeTransformOptions(options: ResolvedOptions): NativeTransformOptions {\n return {\n gfm: options.gfm,\n footnotes: options.footnotes,\n taskLists: options.taskLists,\n tables: options.tables,\n strikethrough: options.strikethrough,\n autolinks: options.autolinks,\n autolinkUrls: options.autolinks,\n frontmatter: options.frontmatter,\n tocMaxDepth: options.tocMaxDepth,\n codeAnnotations: options.codeAnnotations?.enabled ?? false,\n codeAnnotationMetaKey: options.codeAnnotations?.metaKey ?? \"annotate\",\n codeAnnotationSyntax: options.codeAnnotations?.notation ?? \"attribute\",\n codeAnnotationDefaultLineNumbers: options.codeAnnotations?.defaultLineNumbers ?? false,\n wikiLinks: options.wikiLinks?.enabled\n ? {\n enabled: true,\n baseUrl: options.wikiLinks.baseUrl,\n }\n : undefined,\n emojiShortcodes: options.emojiShortcodes?.enabled\n ? {\n enabled: true,\n custom: options.emojiShortcodes.custom,\n }\n : undefined,\n attributes: options.attrs?.enabled ? { enabled: true } : undefined,\n badges: options.badges?.enabled ? { enabled: true } : undefined,\n containers: options.containers?.enabled\n ? {\n enabled: true,\n types: options.containers.types,\n }\n : undefined,\n images: options.images?.enabled\n ? {\n enabled: true,\n lazy: options.images.lazy,\n }\n : undefined,\n cjkEmphasis: options.cjkEmphasis ?? false,\n codeImports: options.codeImports?.enabled\n ? {\n enabled: true,\n rootDir: options.codeImports.rootDir,\n }\n : undefined,\n includes: options.includes?.enabled\n ? {\n enabled: true,\n rootDir: options.includes.rootDir,\n }\n : undefined,\n cards: options.cards?.enabled ? { enabled: true } : undefined,\n steps: options.steps?.enabled ? { enabled: true } : undefined,\n fileTree: options.fileTree?.enabled ? { enabled: true } : undefined,\n editThisPage: options.editThisPage?.enabled\n ? {\n enabled: true,\n repoUrl: options.editThisPage.repoUrl,\n branch: options.editThisPage.branch,\n rootDir: options.editThisPage.rootDir,\n label: options.editThisPage.label,\n }\n : undefined,\n math: options.math?.enabled ?? false,\n };\n}\n\nfunction defaultCollections(): CollectionsOptions {\n return {\n [DEFAULT_COLLECTION_NAME]: {\n source: DEFAULT_COLLECTION_SOURCE,\n },\n };\n}\n","/** RSS / Atom / JSON Feed string bodies used by `feeds.ts`. */\n\nexport interface ParsedDate {\n unix: number;\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n}\n\nexport interface FeedDocument {\n siteName: string;\n siteDescription?: string;\n home: string;\n atomUrl: string;\n jsonUrl: string;\n}\n\nexport interface FeedEntry {\n title: string;\n description?: string;\n loc: string;\n date?: ParsedDate;\n}\n\nexport function generateRss(doc: FeedDocument, items: readonly FeedEntry[]): string {\n let xml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<rss version=\"2.0\">\\n <channel>\\n <title>';\n xml += escapeXml(doc.siteName);\n xml += \"</title>\\n <link>\";\n xml += escapeXml(doc.home);\n xml += \"</link>\\n <description>\";\n xml += escapeXml(channelDescription(doc));\n xml += \"</description>\\n\";\n for (const item of items) {\n xml += \" <item>\\n <title>\";\n xml += escapeXml(item.title);\n xml += \"</title>\\n <link>\";\n xml += escapeXml(item.loc);\n xml += \"</link>\\n <guid>\";\n xml += escapeXml(item.loc);\n xml += \"</guid>\\n\";\n if (item.description) {\n xml += \" <description>\";\n xml += escapeXml(item.description);\n xml += \"</description>\\n\";\n }\n if (item.date) {\n xml += ` <pubDate>${formatRfc822(item.date)}</pubDate>\\n`;\n }\n xml += \" </item>\\n\";\n }\n xml += \" </channel>\\n</rss>\\n\";\n return xml;\n}\n\nexport function generateAtom(doc: FeedDocument, items: readonly FeedEntry[]): string {\n const updated = items[0]?.date ? formatRfc3339(items[0].date) : \"1970-01-01T00:00:00Z\";\n let xml =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\\n <title>';\n xml += escapeXml(doc.siteName);\n xml += '</title>\\n <link href=\"';\n xml += escapeXml(doc.atomUrl);\n xml += '\" rel=\"self\"/>\\n <link href=\"';\n xml += escapeXml(doc.home);\n xml += '\" rel=\"alternate\"/>\\n <id>';\n xml += escapeXml(doc.home);\n xml += `</id>\\n <updated>${updated}</updated>\\n`;\n if (doc.siteDescription?.trim()) {\n xml += \" <subtitle>\";\n xml += escapeXml(doc.siteDescription);\n xml += \"</subtitle>\\n\";\n }\n for (const item of items) {\n xml += \" <entry>\\n <title>\";\n xml += escapeXml(item.title);\n xml += '</title>\\n <link href=\"';\n xml += escapeXml(item.loc);\n xml += '\"/>\\n <id>';\n xml += escapeXml(item.loc);\n xml += `</id>\\n <updated>${item.date ? formatRfc3339(item.date) : updated}</updated>\\n`;\n if (item.description) {\n xml += \" <summary>\";\n xml += escapeXml(item.description);\n xml += \"</summary>\\n\";\n }\n xml += \" </entry>\\n\";\n }\n xml += \"</feed>\\n\";\n return xml;\n}\n\nexport function generateJson(doc: FeedDocument, items: readonly FeedEntry[]): string {\n let json = '{\\n \"version\": \"https://jsonfeed.org/version/1.1\",\\n \"title\": ';\n json += jsonString(doc.siteName);\n json += ',\\n \"home_page_url\": ';\n json += jsonString(doc.home);\n json += ',\\n \"feed_url\": ';\n json += jsonString(doc.jsonUrl);\n if (doc.siteDescription?.trim()) {\n json += ',\\n \"description\": ';\n json += jsonString(doc.siteDescription);\n }\n json += ',\\n \"items\": [';\n items.forEach((item, index) => {\n if (index > 0) {\n json += \",\";\n }\n json += '\\n {\\n \"id\": ';\n json += jsonString(item.loc);\n json += ',\\n \"url\": ';\n json += jsonString(item.loc);\n json += ',\\n \"title\": ';\n json += jsonString(item.title);\n if (item.description) {\n json += ',\\n \"content_text\": ';\n json += jsonString(item.description);\n }\n if (item.date) {\n json += ',\\n \"date_published\": ';\n json += jsonString(formatRfc3339(item.date));\n }\n json += \"\\n }\";\n });\n json += \"\\n ]\\n}\\n\";\n return json;\n}\n\nexport function parseDate(value: string | undefined): ParsedDate | undefined {\n if (!value) {\n return undefined;\n }\n if (/^\\d+$/.test(value)) {\n const n = Number(value);\n return unixToDate(value.length >= 13 ? Math.trunc(n / 1000) : n);\n }\n return parseCivilDate(value);\n}\n\nfunction channelDescription(doc: FeedDocument): string {\n const description = doc.siteDescription?.trim();\n return description ? description : doc.siteName;\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n\nfunction jsonString(value: string): string {\n let escaped = '\"';\n for (const ch of value) {\n const code = ch.codePointAt(0) ?? 0;\n if (ch === '\"') {\n escaped += '\\\\\"';\n } else if (ch === \"\\\\\") {\n escaped += \"\\\\\\\\\";\n } else if (ch === \"\\n\") {\n escaped += \"\\\\n\";\n } else if (ch === \"\\r\") {\n escaped += \"\\\\r\";\n } else if (ch === \"\\t\") {\n escaped += \"\\\\t\";\n } else if (ch === \"<\") {\n escaped += \"\\\\u003c\";\n } else if (ch === \">\") {\n escaped += \"\\\\u003e\";\n } else if (ch === \"&\") {\n escaped += \"\\\\u0026\";\n } else if (code < 0x20) {\n escaped += `\\\\u${code.toString(16).padStart(4, \"0\")}`;\n } else {\n escaped += ch;\n }\n }\n escaped += '\"';\n return escaped;\n}\n\nfunction formatRfc3339(date: ParsedDate): string {\n return `${pad(date.year, 4)}-${pad(date.month, 2)}-${pad(date.day, 2)}T${pad(date.hour, 2)}:${pad(date.minute, 2)}:${pad(date.second, 2)}Z`;\n}\n\nfunction formatRfc822(date: ParsedDate): string {\n const weekdays = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const months = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n ];\n return `${weekdays[weekdayUtc(date.year, date.month, date.day)]}, ${pad(date.day, 2)} ${months[date.month - 1]} ${pad(date.year, 4)} ${pad(date.hour, 2)}:${pad(date.minute, 2)}:${pad(date.second, 2)} +0000`;\n}\n\nfunction pad(value: number, width: number): string {\n return String(value).padStart(width, \"0\");\n}\n\nfunction parseCivilDate(value: string): ParsedDate | undefined {\n if (value.length < 10 || value[4] !== \"-\" || value[7] !== \"-\") {\n return undefined;\n }\n const year = Number(value.slice(0, 4));\n const month = Number(value.slice(5, 7));\n const day = Number(value.slice(8, 10));\n let hour = 0;\n let minute = 0;\n let second = 0;\n let offset = 0;\n if (value.length > 10) {\n const rest = value.slice(10);\n const time = rest.startsWith(\"T\") || rest.startsWith(\" \") ? rest.slice(1) : \"\";\n if (time.length < 8 || time[2] !== \":\" || time[5] !== \":\") {\n return undefined;\n }\n hour = Number(time.slice(0, 2));\n minute = Number(time.slice(3, 5));\n second = Number(time.slice(6, 8));\n const parsedOffset = parseOffset(timezoneSuffix(time));\n if (parsedOffset == null) {\n return undefined;\n }\n offset = parsedOffset;\n }\n const unix = civilToUnix(year, month, day, hour, minute, second);\n return unix == null ? undefined : unixToDate(unix - offset);\n}\n\nfunction timezoneSuffix(rest: string): string {\n const afterTime = rest.slice(8);\n if (afterTime.startsWith(\".\")) {\n const index = afterTime.search(/[Z+-]/);\n return index === -1 ? \"\" : afterTime.slice(index);\n }\n return afterTime;\n}\n\nfunction parseOffset(tz: string): number | undefined {\n if (!tz || tz === \"Z\") {\n return 0;\n }\n if (tz.length < 6) {\n return undefined;\n }\n const sign = tz[0] === \"+\" ? 1 : tz[0] === \"-\" ? -1 : 0;\n if (!sign) {\n return undefined;\n }\n return sign * (Number(tz.slice(1, 3)) * 3600 + Number(tz.slice(4, 6)) * 60);\n}\n\nfunction civilToUnix(\n year: number,\n month: number,\n day: number,\n hour: number,\n minute: number,\n second: number,\n): number | undefined {\n if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 60) {\n return undefined;\n }\n let y = year;\n if (month <= 2) {\n y -= 1;\n }\n const era = Math.trunc((y >= 0 ? y : y - 399) / 400);\n const yoe = y - era * 400;\n const shifted = month + (month > 2 ? -3 : 9);\n const doy = Math.trunc((153 * shifted + 2) / 5) + day - 1;\n const doe = yoe * 365 + Math.trunc(yoe / 4) - Math.trunc(yoe / 100) + doy;\n const days = era * 146097 + doe - 719468;\n return days * 86400 + hour * 3600 + minute * 60 + second;\n}\n\nfunction unixToDate(unix: number): ParsedDate | undefined {\n const days = Math.floor(unix / 86400);\n const tod = ((unix % 86400) + 86400) % 86400;\n const z = days + 719468;\n const era = Math.trunc((z >= 0 ? z : z - 146096) / 146097);\n const doe = z - era * 146097;\n const yoe = Math.trunc(\n (doe - Math.trunc(doe / 1460) + Math.trunc(doe / 36524) - Math.trunc(doe / 146096)) / 365,\n );\n const year = yoe + era * 400;\n const doy = doe - (365 * yoe + Math.trunc(yoe / 4) - Math.trunc(yoe / 100));\n const mp = Math.trunc((5 * doy + 2) / 153);\n const day = doy - Math.trunc((153 * mp + 2) / 5) + 1;\n const month = mp < 10 ? mp + 3 : mp - 9;\n return {\n unix,\n year: year + (month <= 2 ? 1 : 0),\n month,\n day,\n hour: Math.trunc(tod / 3600),\n minute: Math.trunc((tod % 3600) / 60),\n second: tod % 60,\n };\n}\n\nfunction weekdayUtc(year: number, month: number, day: number): number {\n const table = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];\n const y = month < 3 ? year - 1 : year;\n return (\n (((y + Math.trunc(y / 4) - Math.trunc(y / 100) + Math.trunc(y / 400) + table[month - 1] + day) %\n 7) +\n 7) %\n 7\n );\n}\n","/**\n * Opt-in RSS / Atom / JSON Feed helpers.\n *\n * String bodies follow `ox_content_ssg::generate_feeds`. The Vite plugin\n * writes those files during SSG without adding a NAPI surface.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { generateAtom, generateJson, generateRss, parseDate } from \"./feed-format\";\nimport type { FeedDocument, FeedEntry } from \"./feed-format\";\nimport { classifyPublishState } from \"./publish-state\";\nimport type {\n FeedFormat,\n FeedsOptions,\n ResolvedFeedsOptions,\n ResolvedPublishStateOptions,\n} from \"./types\";\n\nconst MISSING_SITE_URL =\n \"[ox-content] feeds is enabled but ssg.siteUrl is not set; RSS, Atom, and JSON feeds were not written\";\n\nconst DEFAULT_FORMATS: FeedFormat[] = [\"rss\", \"atom\", \"json\"];\nconst DEFAULT_LIMIT = 20;\nconst DEFAULT_PATH = \"/\";\n\n/** One collection entry considered for a feed. */\nexport interface FeedItemInput {\n title?: string;\n description?: string;\n path?: string;\n loc?: string;\n date?: unknown;\n lastUpdated?: unknown;\n draft?: unknown;\n unlisted?: unknown;\n frontmatter?: Record<string, unknown>;\n}\n\n/** Inputs for rendering feed bodies. */\nexport interface FeedsRenderInput {\n options?: ResolvedFeedsOptions | null;\n siteUrl?: string;\n siteName?: string;\n siteDescription?: string;\n base?: string;\n collections?: Record<string, readonly FeedItemInput[]>;\n collectionNames?: readonly string[];\n items?: readonly FeedItemInput[];\n publishState?: ResolvedPublishStateOptions;\n}\n\n/** Rendered feed bodies, or a skip warning. */\nexport interface FeedsRenderResult {\n rssXml?: string;\n atomXml?: string;\n jsonFeed?: string;\n warning?: string;\n}\n\n/** Inputs for writing feeds next to generated HTML. */\nexport interface WriteFeedFilesInput extends FeedsRenderInput {\n outDir: string;\n base: string;\n}\n\n/**\n * Resolves `feeds` with defaults.\n *\n * `false` / omitted stays off. `true` enables all three formats with\n * collection `content` (or the first configured collection) and limit 20.\n * An object enables the feature and overrides only the fields the site set.\n */\nexport function resolveFeedsOptions(\n value: boolean | FeedsOptions | undefined,\n): ResolvedFeedsOptions {\n if (!value) {\n return {\n enabled: false,\n formats: [...DEFAULT_FORMATS],\n limit: DEFAULT_LIMIT,\n path: DEFAULT_PATH,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n formats: [...DEFAULT_FORMATS],\n limit: DEFAULT_LIMIT,\n path: DEFAULT_PATH,\n };\n }\n return {\n enabled: true,\n formats: normalizeFormats(value.formats),\n collection: value.collection,\n limit: value.limit ?? DEFAULT_LIMIT,\n path: value.path ?? DEFAULT_PATH,\n };\n}\n\n/** Picks `content`, else the first configured collection name. */\nexport function resolveFeedCollectionName(\n requested: string | undefined,\n collectionNames: readonly string[],\n): string | undefined {\n if (requested) {\n return requested;\n }\n if (collectionNames.includes(\"content\")) {\n return \"content\";\n }\n return collectionNames[0];\n}\n\n/** Builds RSS / Atom / JSON Feed bodies without writing files. */\nexport function generateFeeds(input: FeedsRenderInput): FeedsRenderResult {\n if (!input.options?.enabled) {\n return {};\n }\n if (!hasSiteUrl(input.siteUrl)) {\n return { warning: MISSING_SITE_URL };\n }\n\n const published = publishedItems(input);\n const doc = feedDocument(input);\n const result: FeedsRenderResult = {};\n if (input.options.formats.includes(\"rss\")) {\n result.rssXml = generateRss(doc, published);\n }\n if (input.options.formats.includes(\"atom\")) {\n result.atomXml = generateAtom(doc, published);\n }\n if (input.options.formats.includes(\"json\")) {\n result.jsonFeed = generateJson(doc, published);\n }\n return result;\n}\n\n/** Writes enabled feed files into `outDir`. */\nexport async function writeFeedFiles(\n input: WriteFeedFilesInput,\n): Promise<{ files: string[]; warning?: string }> {\n const generated = generateFeeds(input);\n if (generated.warning) {\n return { files: [], warning: generated.warning };\n }\n\n const outputs: Array<[string, string]> = [\n [generated.rssXml, \"feed.xml\"],\n [generated.atomXml, \"atom.xml\"],\n [generated.jsonFeed, \"feed.json\"],\n ].filter((entry): entry is [string, string] => entry[0] != null);\n if (outputs.length === 0) {\n return { files: [] };\n }\n\n const dest = outputDir(input.outDir, input.options?.path ?? DEFAULT_PATH);\n await fs.mkdir(dest, { recursive: true });\n const files: string[] = [];\n for (const [body, name] of outputs) {\n const outputPath = path.join(dest, name);\n await fs.writeFile(outputPath, body, \"utf8\");\n files.push(outputPath);\n }\n return { files };\n}\n\nfunction normalizeFormats(formats: FeedFormat[] | undefined): FeedFormat[] {\n if (!formats) {\n return [...DEFAULT_FORMATS];\n }\n const seen = new Set<FeedFormat>();\n const resolved: FeedFormat[] = [];\n for (const format of formats) {\n if ((format === \"rss\" || format === \"atom\" || format === \"json\") && !seen.has(format)) {\n seen.add(format);\n resolved.push(format);\n }\n }\n return resolved;\n}\n\nfunction hasSiteUrl(siteUrl: string | undefined): boolean {\n return Boolean(siteUrl && siteUrl.trim());\n}\n\nfunction homePageUrl(siteUrl: string | undefined, base = \"/\"): string {\n const origin = (siteUrl ?? \"\").trim().replace(/\\/+$/, \"\");\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return `${origin}${prefix}`;\n}\n\nfunction feedDocument(input: FeedsRenderInput): FeedDocument {\n const home = homePageUrl(input.siteUrl, input.base);\n const dir = (input.options?.path ?? DEFAULT_PATH).replace(/^\\/+|\\/+$/g, \"\");\n const prefix = dir ? `${home}${dir}/` : home;\n return {\n siteName: input.siteName ?? \"\",\n siteDescription: input.siteDescription,\n home,\n atomUrl: `${prefix}atom.xml`,\n jsonUrl: `${prefix}feed.json`,\n };\n}\n\nfunction outputDir(outDir: string, feedPath: string): string {\n const relative = feedPath.replace(/^\\/+|\\/+$/g, \"\");\n return relative ? path.join(outDir, relative) : outDir;\n}\n\nfunction rawItems(input: FeedsRenderInput): readonly FeedItemInput[] {\n if (input.items) {\n return input.items;\n }\n const names = input.collectionNames ?? Object.keys(input.collections ?? {});\n const name = resolveFeedCollectionName(input.options?.collection, names);\n return name ? (input.collections?.[name] ?? []) : [];\n}\n\nfunction publishedItems(input: FeedsRenderInput): FeedEntry[] {\n const published = rawItems(input)\n .filter((item) => !isExcludedFromFeed(item, input.publishState))\n .map((item) => normalizeItem(item, input))\n .filter((item) => item.loc.length > 0);\n published.sort((left, right) => {\n const dateCmp =\n (right.date?.unix ?? Number.NEGATIVE_INFINITY) -\n (left.date?.unix ?? Number.NEGATIVE_INFINITY);\n return dateCmp !== 0 ? dateCmp : left.loc < right.loc ? -1 : left.loc > right.loc ? 1 : 0;\n });\n return published.slice(0, input.options?.limit ?? DEFAULT_LIMIT);\n}\n\nfunction isExcludedFromFeed(\n item: FeedItemInput,\n publishState: ResolvedPublishStateOptions | undefined,\n): boolean {\n const frontmatter = item.frontmatter ?? {};\n if (item.draft === true || frontmatter.draft === true) {\n return true;\n }\n if (item.unlisted === true || frontmatter.unlisted === true) {\n return true;\n }\n if (!publishState?.enabled) {\n return false;\n }\n return !classifyPublishState(\n {\n ...frontmatter,\n ...(item.draft === true ? { draft: true } : {}),\n ...(item.unlisted === true ? { unlisted: true } : {}),\n },\n publishState,\n ).listed;\n}\n\nfunction normalizeItem(item: FeedItemInput, input: FeedsRenderInput): FeedEntry {\n return {\n title: item.title ?? \"\",\n description: typeof item.description === \"string\" ? item.description : undefined,\n loc: item.loc || itemLoc(input, item),\n date:\n parseDate(dateField(item.date ?? item.frontmatter?.date)) ??\n parseDate(dateField(item.lastUpdated ?? item.frontmatter?.lastUpdated)),\n };\n}\n\nfunction itemLoc(input: FeedsRenderInput, item: FeedItemInput): string {\n const home = homePageUrl(input.siteUrl, input.base);\n const urlPath = (item.path ?? \"\").replace(/^\\/+|\\/+$/g, \"\");\n return urlPath ? `${home}${urlPath}/` : home;\n}\n\nfunction dateField(value: unknown): string | undefined {\n if (typeof value === \"string\" && value.trim()) {\n return value.trim();\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n if (value instanceof Date && !Number.isNaN(value.getTime())) {\n return value.toISOString();\n }\n return undefined;\n}\n","/**\n * Escaped taxonomy HTML and confined output paths.\n */\n\nimport * as path from \"node:path\";\n\n/** One built page considered for terms and related lists. */\nexport interface TaxonomySourcePage {\n title: string;\n frontmatter: Record<string, unknown>;\n transformedHtml: string;\n inputPath?: string;\n routePaths: { href: string };\n}\n\nexport interface TermBucket {\n label: string;\n slug: string;\n pages: TaxonomySourcePage[];\n}\n\nexport function relatedMarkup(pages: readonly TaxonomySourcePage[]): string {\n const items = pages.map((page) => listItem(page.routePaths.href, page.title)).join(\"\");\n return `<nav class=\"ox-related\" aria-label=\"Related pages\"><h2>Related pages</h2><ul>${items}</ul></nav>`;\n}\n\nexport function listPageContent(\n terms: readonly TermBucket[],\n base: string,\n urlName: string,\n): string {\n const items = terms\n .map((term) => listItem(siteHref(base, urlName, term.slug), term.label))\n .join(\"\");\n return `<h1>${escapeHtml(displayTaxonomyName(urlName))}</h1><ul class=\"ox-taxonomy\">${items}</ul>`;\n}\n\nexport function termPageContent(term: TermBucket): string {\n const pages = [...term.pages].sort((left, right) => {\n const titleCmp = left.title.localeCompare(right.title);\n return titleCmp !== 0 ? titleCmp : left.routePaths.href.localeCompare(right.routePaths.href);\n });\n const items = pages.map((page) => listItem(page.routePaths.href, page.title)).join(\"\");\n return `<h1>${escapeHtml(term.label)}</h1><ul class=\"ox-taxonomy-term\">${items}</ul>`;\n}\n\nexport function displayTaxonomyName(name: string): string {\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\nexport function siteHref(base: string, ...segments: string[]): string {\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n const rest = segments.filter(Boolean).join(\"/\");\n return rest ? `${prefix}${rest}/` : prefix;\n}\n\nexport function containedPath(outDir: string, ...segments: string[]): string | undefined {\n const root = path.resolve(outDir);\n const resolved = path.resolve(root, ...segments);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved === root || !resolved.startsWith(prefix)) {\n return undefined;\n }\n return resolved;\n}\n\nfunction listItem(href: string, label: string): string {\n return `<li><a href=\"${escapeHtml(href)}\">${escapeHtml(label)}</a></li>`;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n","/**\n * Opt-in taxonomy term pages and related-page lists.\n *\n * Resolution and HTML live here. The Vite plugin injects related markup into\n * page content, then writes themed list and per-term pages during SSG.\n */\n\nimport {\n containedPath,\n displayTaxonomyName,\n listPageContent,\n relatedMarkup,\n siteHref,\n termPageContent,\n type TaxonomySourcePage,\n type TermBucket,\n} from \"./taxonomies-html\";\nimport type { ResolvedTaxonomiesOptions, TaxonomiesOptions } from \"./types\";\n\nexport type { TaxonomySourcePage } from \"./taxonomies-html\";\n\nconst DEFAULT_TAXONOMIES = [\"tags\", \"categories\"];\nconst DEFAULT_RELATED_LIMIT = 5;\nconst HOSTILE_TERM = /^(?:javascript|data):/i;\n\n/** Synthetic page passed back to `generateHtmlPage`. */\nexport interface TaxonomyGeneratedPage {\n title: string;\n content: string;\n outputPath: string;\n urlPath: string;\n href: string;\n}\n\n/**\n * Resolves `taxonomies` with defaults.\n *\n * `false` / omitted stays off. `true` enables `tags` and `categories` with\n * relatedLimit 5. An object enables the feature and overrides only set fields.\n */\nexport function resolveTaxonomiesOptions(\n value: boolean | TaxonomiesOptions | undefined,\n): ResolvedTaxonomiesOptions {\n if (!value) {\n return {\n enabled: false,\n taxonomies: [...DEFAULT_TAXONOMIES],\n relatedLimit: DEFAULT_RELATED_LIMIT,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n taxonomies: [...DEFAULT_TAXONOMIES],\n relatedLimit: DEFAULT_RELATED_LIMIT,\n };\n }\n return {\n enabled: true,\n taxonomies: normalizeTaxonomyNames(value.taxonomies),\n relatedLimit: normalizeRelatedLimit(value.relatedLimit),\n };\n}\n\n/**\n * Stable URL slug for a frontmatter term.\n *\n * Returns `undefined` when the value cannot become a safe `[a-z0-9-]` href.\n */\nexport function termSlug(term: string): string | undefined {\n const trimmed = term.trim();\n if (!trimmed || HOSTILE_TERM.test(trimmed) || trimmed.includes(\"..\") || trimmed.includes(\"//\")) {\n return undefined;\n }\n const slug = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug || undefined;\n}\n\n/** Appends related-page HTML to source pages that share a listed term. */\nexport function injectRelatedPages(\n pages: TaxonomySourcePage[],\n listed: readonly TaxonomySourcePage[],\n options?: ResolvedTaxonomiesOptions,\n): void {\n if (!options?.enabled) {\n return;\n }\n const listedKeys = listed.map((page) => pageTermKeys(page, options.taxonomies));\n for (const page of pages) {\n const keys = pageTermKeys(page, options.taxonomies);\n if (keys.size === 0) {\n continue;\n }\n const related = listed\n .map((candidate, index) => ({\n page: candidate,\n score: samePage(page, candidate) ? 0 : sharedCount(keys, listedKeys[index] ?? new Set()),\n }))\n .filter((entry) => entry.score > 0)\n .sort((left, right) => {\n if (left.score !== right.score) {\n return right.score - left.score;\n }\n const titleCmp = left.page.title.localeCompare(right.page.title);\n return titleCmp !== 0\n ? titleCmp\n : left.page.routePaths.href.localeCompare(right.page.routePaths.href);\n })\n .slice(0, options.relatedLimit)\n .map((entry) => entry.page);\n if (related.length === 0) {\n continue;\n }\n page.transformedHtml += relatedMarkup(related);\n }\n}\n\n/** Maps a generated taxonomy page onto the SSG render shape. */\nexport function toTaxonomyProcessResult(page: TaxonomyGeneratedPage): {\n inputPath: string;\n routePaths: {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n };\n transformedHtml: string;\n title: string;\n frontmatter: Record<string, unknown>;\n toc: [];\n} {\n return {\n inputPath: page.outputPath,\n routePaths: {\n outputPath: page.outputPath,\n urlPath: page.urlPath,\n href: page.href,\n ogImagePath: \"\",\n ogImageUrl: \"\",\n },\n transformedHtml: page.content,\n title: page.title,\n frontmatter: {},\n toc: [],\n };\n}\n\n/** Renders themed list and per-term pages and appends them to the build. */\nexport async function appendTaxonomyPages(input: {\n generatedPages: Array<{ inputPath: string; outputPath: string; html: string }>;\n listedPages: readonly TaxonomySourcePage[];\n options?: ResolvedTaxonomiesOptions;\n outDir: string;\n base: string;\n render: (page: TaxonomyGeneratedPage) => Promise<string>;\n errors: string[];\n}): Promise<void> {\n if (!input.options?.enabled) {\n return;\n }\n for (const spec of taxonomyPageSpecs(\n input.listedPages,\n input.options,\n input.outDir,\n input.base,\n )) {\n try {\n input.generatedPages.push({\n inputPath: spec.outputPath,\n outputPath: spec.outputPath,\n html: await input.render(spec),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n input.errors.push(`Failed to generate taxonomy page ${spec.href}: ${message}`);\n }\n }\n}\n\nfunction taxonomyPageSpecs(\n listed: readonly TaxonomySourcePage[],\n options: ResolvedTaxonomiesOptions,\n outDir: string,\n base: string,\n): TaxonomyGeneratedPage[] {\n const pages: TaxonomyGeneratedPage[] = [];\n for (const taxonomy of options.taxonomies) {\n const urlName = taxonomy.toLowerCase();\n const terms = collectTerms(listed, taxonomy);\n const listHref = siteHref(base, urlName);\n const listOutput = containedPath(outDir, urlName, \"index.html\");\n if (listOutput) {\n pages.push({\n title: displayTaxonomyName(urlName),\n content: listPageContent(terms, base, urlName),\n outputPath: listOutput,\n urlPath: urlName,\n href: listHref,\n });\n }\n for (const term of terms) {\n const outputPath = containedPath(outDir, urlName, term.slug, \"index.html\");\n if (!outputPath) {\n continue;\n }\n pages.push({\n title: term.label,\n content: termPageContent(term),\n outputPath,\n urlPath: `${urlName}/${term.slug}`,\n href: siteHref(base, urlName, term.slug),\n });\n }\n }\n return pages;\n}\n\nfunction collectTerms(listed: readonly TaxonomySourcePage[], taxonomy: string): TermBucket[] {\n const buckets = new Map<string, TermBucket>();\n for (const page of listed) {\n for (const label of termsFromValue(page.frontmatter[taxonomy])) {\n const slug = termSlug(label);\n if (!slug) {\n continue;\n }\n const existing = buckets.get(slug);\n if (existing) {\n existing.pages.push(page);\n } else {\n buckets.set(slug, { label, slug, pages: [page] });\n }\n }\n }\n return [...buckets.values()].sort((left, right) => left.label.localeCompare(right.label));\n}\n\nfunction pageTermKeys(page: TaxonomySourcePage, taxonomies: readonly string[]): Set<string> {\n const keys = new Set<string>();\n for (const taxonomy of taxonomies) {\n for (const label of termsFromValue(page.frontmatter[taxonomy])) {\n const slug = termSlug(label);\n if (slug) {\n keys.add(`${taxonomy.toLowerCase()}\\0${slug}`);\n }\n }\n }\n return keys;\n}\n\nfunction termsFromValue(value: unknown): string[] {\n if (typeof value === \"string\") {\n return value.trim() ? [value.trim()] : [];\n }\n if (!Array.isArray(value)) {\n return [];\n }\n return value.flatMap((item) => (typeof item === \"string\" && item.trim() ? [item.trim()] : []));\n}\n\nfunction normalizeTaxonomyNames(names: string[] | undefined): string[] {\n if (!names) {\n return [...DEFAULT_TAXONOMIES];\n }\n const seen = new Set<string>();\n const resolved: string[] = [];\n for (const name of names) {\n if (typeof name !== \"string\") {\n continue;\n }\n const trimmed = name.trim();\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(trimmed)) {\n continue;\n }\n const url = trimmed.toLowerCase();\n if (seen.has(url)) {\n continue;\n }\n seen.add(url);\n resolved.push(trimmed);\n }\n return resolved;\n}\n\nfunction normalizeRelatedLimit(value: number | undefined): number {\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return Math.floor(value);\n }\n return DEFAULT_RELATED_LIMIT;\n}\n\nfunction samePage(left: TaxonomySourcePage, right: TaxonomySourcePage): boolean {\n if (left.inputPath && right.inputPath) {\n return left.inputPath === right.inputPath;\n }\n return left.routePaths.href === right.routePaths.href;\n}\n\nfunction sharedCount(left: Set<string>, right: Set<string>): number {\n let count = 0;\n for (const key of left) {\n if (right.has(key)) {\n count += 1;\n }\n }\n return count;\n}\n","/**\n * Opt-in team / members page helpers.\n *\n * Resolution lives here. Member cards are rendered in Rust\n * (`ox_content_ssg::render_team_page`) when a page has `layout: team`.\n */\n\nimport type { ResolvedTeamOptions, TeamMember, TeamOptions } from \"./types\";\n\n/**\n * Resolves `ssg.team` with defaults.\n *\n * `false` / omitted stays off. `true` enables an empty member list.\n * An object enables the feature and keeps the members the site set.\n */\nexport function resolveTeamOptions(value: boolean | TeamOptions | undefined): ResolvedTeamOptions {\n if (!value) {\n return { enabled: false, members: [] };\n }\n if (value === true) {\n return { enabled: true, members: [] };\n }\n return {\n enabled: true,\n members: normalizeMembers(value.members),\n };\n}\n\nfunction normalizeMembers(members: TeamMember[] | undefined): TeamMember[] {\n if (!Array.isArray(members)) {\n return [];\n }\n return members.flatMap((member) => {\n if (!member || typeof member.name !== \"string\") {\n return [];\n }\n const links = Array.isArray(member.links)\n ? member.links.flatMap((link) => {\n if (!link || typeof link.label !== \"string\" || typeof link.href !== \"string\") {\n return [];\n }\n return [{ label: link.label, href: link.href }];\n })\n : undefined;\n return [\n {\n name: member.name,\n role: typeof member.role === \"string\" ? member.role : undefined,\n avatar: typeof member.avatar === \"string\" ? member.avatar : undefined,\n links,\n },\n ];\n });\n}\n","/**\n * Opt-in hosted search provider for `virtual:ox-content/search`.\n *\n * Local BM25 stays the default. Hosted queries use a generic HTTP adapter and\n * a public search-only key. Write and admin keys are rejected.\n */\n\nimport type { ResolvedSearchOptions, SearchOptions } from \"./types\";\n\nconst FORBIDDEN_KEY_NAMES = new Set([\"adminkey\", \"writekey\", \"apikey\"]);\nconst DEFAULT_HOSTED_ENDPOINT = \"/search\";\n\nexport type HostedSearchConfig = {\n appId: string;\n indexName: string;\n searchKey: string;\n endpoint: string;\n};\n\nfunction normalizeOptionKey(name: string): string {\n return name.replace(/[_-]/g, \"\").toLowerCase();\n}\n\nfunction readNonEmpty(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Returns true when the options object names a write or admin credential.\n */\nexport function hasForbiddenSearchCredentialFields(options: object): boolean {\n return Object.keys(options).some((key) => FORBIDDEN_KEY_NAMES.has(normalizeOptionKey(key)));\n}\n\n/**\n * Resolves hosted credentials from config or env. Missing or forbidden keys\n * fail closed and return null without echoing secrets.\n */\nexport function resolveHostedSearchConfig(\n options: SearchOptions,\n env: NodeJS.ProcessEnv = process.env,\n): HostedSearchConfig | null {\n if (hasForbiddenSearchCredentialFields(options)) {\n return null;\n }\n\n const appId = readNonEmpty(options.appId) ?? readNonEmpty(env.OX_CONTENT_SEARCH_APP_ID);\n const indexName =\n readNonEmpty(options.indexName) ?? readNonEmpty(env.OX_CONTENT_SEARCH_INDEX_NAME);\n const searchKey =\n readNonEmpty(options.searchKey) ??\n readNonEmpty(options.publicKey) ??\n readNonEmpty(env.OX_CONTENT_SEARCH_KEY) ??\n readNonEmpty(env.OX_CONTENT_SEARCH_PUBLIC_KEY);\n const endpoint =\n readNonEmpty(options.endpoint) ??\n readNonEmpty(env.OX_CONTENT_SEARCH_ENDPOINT) ??\n DEFAULT_HOSTED_ENDPOINT;\n\n if (!appId || !indexName || !searchKey) {\n return null;\n }\n\n return { appId, indexName, searchKey, endpoint };\n}\n\n/**\n * JSON-embeds a value so it stays inert inside a script tag.\n */\nexport function embedSearchJson(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, \"\\\\u003c\")\n .replace(/>/g, \"\\\\u003e\")\n .replace(/&/g, \"\\\\u0026\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction hostedClientOptions(options: ResolvedSearchOptions) {\n return {\n enabled: options.enabled,\n limit: options.limit,\n prefix: options.prefix,\n placeholder: options.placeholder,\n hotkey: options.hotkey,\n provider: \"hosted\" as const,\n };\n}\n\nfunction failClosedSearchModule(options: ResolvedSearchOptions): string {\n return `// Search module generated by ox-content\nconst searchOptions = ${embedSearchJson(hostedClientOptions(options))};\nexport async function search() { return []; }\nexport { searchOptions };\nexport default { search, searchOptions };\n`;\n}\n\nconst HOSTED_SEARCH_RUNTIME = `export async function search(query, options = {}) {\n const hosted = searchOptions.hosted;\n if (!hosted || !query) return [];\n const limit = options.limit ?? searchOptions.limit;\n try {\n const response = await fetch(hosted.endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n \"x-app-id\": hosted.appId,\n \"x-index-name\": hosted.indexName,\n \"x-search-key\": hosted.searchKey,\n },\n body: JSON.stringify({\n query: String(query),\n limit,\n indexName: hosted.indexName,\n }),\n });\n if (!response.ok) return [];\n const data = await response.json();\n const hits = Array.isArray(data) ? data : (data && (data.hits || data.results)) || [];\n return hits.slice(0, limit).map(normalizeHostedHit);\n } catch {\n return [];\n }\n}\nfunction normalizeHostedHit(hit) {\n if (!hit || typeof hit !== \"object\") {\n return { id: \"\", title: \"\", url: \"\", score: 0, matches: [], snippet: \"\" };\n }\n return {\n id: String(hit.id ?? hit.objectID ?? \"\"),\n title: String(hit.title ?? \"\"),\n url: String(hit.url ?? \"\"),\n score: Number(hit.score ?? 0) || 0,\n matches: Array.isArray(hit.matches) ? hit.matches.map(String) : [],\n snippet: String(hit.snippet ?? hit.content ?? \"\"),\n };\n}\nexport { searchOptions };\nexport default { search, searchOptions };\n`;\n\n/**\n * Client runtime that queries the hosted HTTP adapter.\n *\n * Misconfigured hosted search emits a no-op client so the UI never calls a\n * broken endpoint.\n */\nexport function generateHostedSearchModule(options: ResolvedSearchOptions): string {\n if (!options.appId || !options.indexName || !options.searchKey) {\n return failClosedSearchModule(options);\n }\n\n const searchOptions = {\n ...hostedClientOptions(options),\n hosted: {\n appId: options.appId,\n indexName: options.indexName,\n searchKey: options.searchKey,\n endpoint: options.endpoint ?? DEFAULT_HOSTED_ENDPOINT,\n },\n };\n\n return `// Search module generated by ox-content\nconst searchOptions = ${embedSearchJson(searchOptions)};\n${HOSTED_SEARCH_RUNTIME}`;\n}\n\n/**\n * Runtime fields accepted by the native local BM25 module generator.\n */\nexport function toLocalSearchRuntimeOptions(options: ResolvedSearchOptions) {\n return {\n enabled: options.enabled,\n limit: options.limit,\n prefix: options.prefix,\n placeholder: options.placeholder,\n hotkey: options.hotkey,\n };\n}\n","/**\n * Full-text search functionality for Ox Content.\n *\n * Generates search index at build time and provides client-side search.\n */\n\nimport { importNapiModule, importNapiModuleSync } from \"./napi\";\nimport { DEFAULT_MARKDOWN_EXTENSIONS } from \"./markdown\";\nimport type {\n SearchOptions,\n ResolvedSearchOptions,\n ResolvedPublishStateOptions,\n SearchDocument,\n ScopedSearchQuery,\n} from \"./types\";\nimport { toNapiPublishState } from \"./publish-state\";\nimport {\n generateHostedSearchModule,\n resolveHostedSearchConfig,\n toLocalSearchRuntimeOptions,\n} from \"./search-provider\";\n\n// Import Rust bindings\nlet oxContent: typeof import(\"@ox-content/napi\") | null = null;\n\nasync function getOxContent() {\n if (!oxContent) {\n try {\n oxContent = await importNapiModule();\n } catch {\n console.warn(\"[ox-content] Native bindings not available, search disabled\");\n return null;\n }\n }\n return oxContent;\n}\n\n/**\n * Splits a raw query into free-text terms and `@scope` prefixes.\n */\nexport function parseScopedSearchQuery(query: string): ScopedSearchQuery {\n return importNapiModuleSync().parseScopedSearchQuery(query);\n}\n\n/**\n * Derives hierarchical search scopes from a document id or URL.\n *\n * For example, `api/math/index` yields `[\"api\", \"api/math\"]`.\n */\nexport function getSearchDocumentScopes(doc: Pick<SearchDocument, \"id\" | \"url\">): string[] {\n return importNapiModuleSync().getSearchDocumentScopes(doc.id ?? \"\", doc.url ?? \"\");\n}\n\n/**\n * Returns true when a search document belongs to at least one requested scope.\n */\nexport function matchesSearchScopes(\n doc: Pick<SearchDocument, \"id\" | \"url\">,\n scopes: string[],\n): boolean {\n return importNapiModuleSync().matchesSearchScopes(doc.id ?? \"\", doc.url ?? \"\", scopes);\n}\n\n/**\n * Resolves search options with defaults.\n */\nexport function resolveSearchOptions(\n options: SearchOptions | boolean | undefined,\n): ResolvedSearchOptions {\n if (options === false) {\n return {\n enabled: false,\n limit: 10,\n prefix: true,\n placeholder: \"Search documentation...\",\n hotkey: \"/\",\n provider: \"local\",\n };\n }\n\n const opts = typeof options === \"object\" ? options : {};\n const enabled = opts.enabled ?? true;\n const provider = opts.provider === \"hosted\" ? \"hosted\" : \"local\";\n const resolved: ResolvedSearchOptions = {\n enabled,\n limit: opts.limit ?? 10,\n prefix: opts.prefix ?? true,\n placeholder: opts.placeholder ?? \"Search documentation...\",\n hotkey: opts.hotkey ?? \"/\",\n provider,\n };\n\n if (!enabled || provider !== \"hosted\") {\n return resolved;\n }\n\n const hosted = resolveHostedSearchConfig(opts, process.env);\n if (!hosted) {\n console.warn(\"[ox-content] Hosted search is not configured\");\n return resolved;\n }\n\n return {\n ...resolved,\n appId: hosted.appId,\n indexName: hosted.indexName,\n searchKey: hosted.searchKey,\n endpoint: hosted.endpoint,\n };\n}\n\n/**\n * Builds the search index from Markdown files.\n *\n * `publishState` is forwarded to the native indexer. `excludeDocumentIds`\n * then drops matching documents and rebuilds the BM25 index so omitted\n * pages (such as the opt-in 404 source) are not searchable.\n */\nexport async function buildSearchIndex(\n srcDir: string,\n base: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n publishState?: ResolvedPublishStateOptions,\n excludeDocumentIds: readonly string[] = [],\n mdx?: boolean,\n): Promise<string> {\n const napi = await getOxContent();\n\n if (!napi) {\n return JSON.stringify({\n documents: [],\n index: {},\n df: {},\n avg_dl: 0,\n doc_count: 0,\n });\n }\n\n const indexJson = napi.buildSearchIndexFromDirectory(srcDir, base, [...extensions], {\n publishState: toNapiPublishState(publishState),\n mdx,\n });\n if (excludeDocumentIds.length === 0) {\n return indexJson;\n }\n return excludeSearchDocuments(napi, indexJson, excludeDocumentIds);\n}\n\nfunction excludeSearchDocuments(\n napi: NonNullable<Awaited<ReturnType<typeof getOxContent>>>,\n indexJson: string,\n excludeDocumentIds: readonly string[],\n): string {\n const excluded = new Set(excludeDocumentIds);\n let documents: Array<{\n id: string;\n title: string;\n url: string;\n body: string;\n headings: string[];\n code: string[];\n }>;\n try {\n const parsed = JSON.parse(indexJson) as { documents?: typeof documents };\n documents = parsed.documents ?? [];\n } catch {\n return indexJson;\n }\n\n const kept = documents.filter((doc) => !excluded.has(doc.id));\n if (kept.length === documents.length) {\n return indexJson;\n }\n return napi.buildSearchIndex(kept);\n}\n\n/**\n * Writes the search index to a file.\n */\nexport async function writeSearchIndex(indexJson: string, outDir: string): Promise<void> {\n const napi = await getOxContent();\n\n if (!napi) {\n return;\n }\n\n napi.writeSearchIndex(indexJson, outDir);\n}\n\n/**\n * Client-side search module code.\n * This is injected into the bundle as a virtual module.\n */\nexport function generateSearchModule(options: ResolvedSearchOptions, indexPath: string): string {\n if (options.provider === \"hosted\") {\n return generateHostedSearchModule(options);\n }\n return importNapiModuleSync().generateSearchModuleFromOptions(\n toLocalSearchRuntimeOptions(options),\n indexPath,\n );\n}\n","/**\n * Escaped version switcher, banner, and badge markup.\n */\n\nimport type { VersionBannerKind } from \"./types\";\n\nexport interface VersionLink {\n id: string;\n label: string;\n href: string;\n current: boolean;\n banner?: VersionBannerKind | false;\n}\n\nexport function versionSwitcherMarkup(links: readonly VersionLink[], badge: boolean): string {\n if (links.length === 0) {\n return \"\";\n }\n const current = links.find((link) => link.current) ?? links[0];\n const items = links\n .map((link) => {\n const label = `${escapeHtml(link.label)}${badgeMarkup(link, badge)}`;\n if (link.current || !isSafeHref(link.href)) {\n return `<li><span aria-current=\"page\">${label}</span></li>`;\n }\n return `<li><a href=\"${escapeHtml(link.href)}\">${label}</a></li>`;\n })\n .join(\"\");\n return `<nav class=\"ox-header-select ox-version-switcher\" aria-label=\"Version\"><button type=\"button\" aria-expanded=\"false\" aria-haspopup=\"true\">${escapeHtml(current.label)}${badgeMarkup(current, badge)}</button><ul class=\"ox-header-select-menu\">${items}</ul></nav><script>(function(){var n=document.currentScript&&document.currentScript.previousElementSibling;if(!n||!n.classList.contains(\"ox-version-switcher\"))return;var b=n.querySelector(\"button\");if(!b)return;function closeOthers(){document.querySelectorAll(\".header-nav-dropdown > button[aria-expanded='true'], .ox-locale-switcher > button[aria-expanded='true']\").forEach(function(btn){btn.setAttribute(\"aria-expanded\",\"false\");});}b.addEventListener(\"click\",function(e){e.stopPropagation();var o=b.getAttribute(\"aria-expanded\")===\"true\";closeOthers();b.setAttribute(\"aria-expanded\",o?\"false\":\"true\");});document.addEventListener(\"click\",function(e){if(!n.contains(e.target))b.setAttribute(\"aria-expanded\",\"false\");});document.addEventListener(\"keydown\",function(e){if(e.key===\"Escape\"){b.setAttribute(\"aria-expanded\",\"false\");b.focus();}});})()</script>`;\n}\n\nexport function versionBannerMarkup(kind: VersionBannerKind | false | undefined): string {\n if (kind === \"unreleased\") {\n return `<aside class=\"ox-version-banner ox-version-banner--unreleased\" role=\"status\">This documentation describes an unreleased version.</aside>`;\n }\n if (kind === \"unmaintained\") {\n return `<aside class=\"ox-version-banner ox-version-banner--unmaintained\" role=\"status\">This documentation is unmaintained.</aside>`;\n }\n return \"\";\n}\n\nexport function injectVersionChrome(\n html: string,\n switcher: string,\n banner: string,\n searchFrom?: string,\n searchTo?: string,\n): string {\n let next = html;\n if (banner) {\n next = next.replace(/<body([^>]*)>/, `<body$1>${banner}`);\n }\n if (switcher) {\n if (next.includes('<div class=\"header-actions\">')) {\n next = next.replace(\n '<div class=\"header-actions\">',\n `<div class=\"header-actions\">${switcher}`,\n );\n } else if (next.includes(\"</header>\")) {\n next = next.replace(\"</header>\", `${switcher}</header>`);\n }\n }\n if (searchTo && isSafeHref(searchTo)) {\n next = next.replace(/<html([^>]*)>/i, (match, attrs: string) => {\n if (/\\sdata-ox-search-index=/.test(attrs)) {\n return match;\n }\n return `<html${attrs} data-ox-search-index=\"${escapeHtml(searchTo)}\">`;\n });\n }\n if (searchFrom && searchTo && searchFrom !== searchTo && isSafeHref(searchTo)) {\n next = next.split(searchFrom).join(searchTo);\n const script = `<script>(function(){var f=${JSON.stringify(searchFrom)},t=${JSON.stringify(searchTo)};var o=window.fetch;window.fetch=function(i,n){if(typeof i===\"string\"&&i.indexOf(f)!==-1)i=i.split(f).join(t);return o.call(this,i,n);};})()</script>`;\n next = next.includes(\"</body>\")\n ? next.replace(\"</body>\", `${script}</body>`)\n : `${next}${script}`;\n }\n return next;\n}\n\nexport function searchIndexUrl(base: string, prefix: string): string {\n const root = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return prefix ? `${root}${prefix}/search-index.json` : `${root}search-index.json`;\n}\n\nexport function isSafeHref(href: string): boolean {\n const trimmed = href.trim();\n if (!trimmed || trimmed.startsWith(\"//\")) {\n return false;\n }\n const lower = trimmed.replace(/\\s+/g, \"\").toLowerCase();\n if (\n lower.startsWith(\"javascript:\") ||\n lower.startsWith(\"data:\") ||\n lower.startsWith(\"vbscript:\")\n ) {\n return false;\n }\n return trimmed.startsWith(\"/\") || trimmed.startsWith(\"./\") || !trimmed.includes(\":\");\n}\n\nexport function escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n\nfunction badgeMarkup(link: VersionLink, badge: boolean): string {\n if (!badge || !link.banner) {\n return \"\";\n }\n const text = link.banner === \"unreleased\" ? \"unreleased\" : \"unmaintained\";\n return `<span class=\"ox-version-badge\">${text}</span>`;\n}\n","/**\n * Opt-in documentation versioning: prefixes, snapshots, and header chrome.\n *\n * Historical snapshot directories are read-only during the build. Recreate\n * them with an explicit snapshot command.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { buildSearchIndex, writeSearchIndex } from \"./search\";\nimport type {\n ResolvedPublishStateOptions,\n ResolvedVersionEntry,\n ResolvedVersionsOptions,\n VersionBannerKind,\n VersionEntry,\n VersionsOptions,\n} from \"./types\";\nimport {\n injectVersionChrome,\n searchIndexUrl,\n versionBannerMarkup,\n versionSwitcherMarkup,\n type VersionLink,\n} from \"./versions-html\";\n\nexport {\n injectVersionChrome,\n searchIndexUrl,\n versionBannerMarkup,\n versionSwitcherMarkup,\n} from \"./versions-html\";\n\nconst DEFAULT_CURRENT_ID = \"current\";\nconst PREFIX_RE = /^[a-z0-9](?:[a-z0-9.-]{0,62})$/;\n\n/**\n * Resolves `versions`. Omitted / `false` stay off. `true` enables a single\n * current entry. An object enables the feature and overrides set fields.\n */\nexport function resolveVersionsOptions(\n value: boolean | VersionsOptions | undefined,\n): ResolvedVersionsOptions {\n if (!value) {\n return {\n enabled: false,\n current: DEFAULT_CURRENT_ID,\n switcher: true,\n badge: true,\n entries: [],\n };\n }\n if (value === true) {\n return {\n enabled: true,\n current: DEFAULT_CURRENT_ID,\n switcher: true,\n badge: true,\n entries: [defaultCurrentEntry()],\n };\n }\n const entries = normalizeEntries(value.entries);\n const current =\n typeof value.current === \"string\" && value.current.trim()\n ? value.current.trim()\n : (entries[0]?.id ?? DEFAULT_CURRENT_ID);\n return {\n enabled: true,\n current,\n switcher: value.switcher !== false,\n badge: value.badge !== false,\n entries: entries.length > 0 ? entries : [defaultCurrentEntry()],\n };\n}\n\n/** Prefix used for the active version (empty string = site root). */\nexport function currentVersionPrefix(options?: ResolvedVersionsOptions): string {\n if (!options?.enabled) {\n return \"\";\n }\n return options.entries.find((entry) => entry.id === options.current)?.prefix ?? \"\";\n}\n\nexport function snapshotEntries(options?: ResolvedVersionsOptions): ResolvedVersionEntry[] {\n if (!options?.enabled) {\n return [];\n }\n return options.entries.filter((entry) => entry.dir && entry.prefix);\n}\n\n/** Confines a snapshot dir to `root`. */\nexport function resolveSnapshotDir(root: string, dir: string): string | undefined {\n const trimmed = dir.trim();\n if (!trimmed || trimmed.includes(\"\\0\") || trimmed.includes(\"..\")) {\n return undefined;\n }\n const resolved = path.resolve(root, trimmed);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved === root || !resolved.startsWith(prefix)) {\n return undefined;\n }\n return resolved;\n}\n\nexport function prefixRoutePaths(\n routes: { outputPath: string; urlPath: string; href: string },\n prefix: string,\n outDir: string,\n base: string,\n): { outputPath: string; urlPath: string; href: string } {\n const safe = sanitizePrefix(prefix);\n if (!safe) {\n return routes;\n }\n const rel = path.relative(path.resolve(outDir), path.resolve(routes.outputPath));\n if (rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n return routes;\n }\n return {\n outputPath: path.join(outDir, safe, rel),\n urlPath: routes.urlPath ? `${safe}/${routes.urlPath}` : safe,\n href: siteHref(base, safe, routes.urlPath),\n };\n}\n\nexport function versionLinks(\n options: ResolvedVersionsOptions,\n activeId: string,\n siblingPath: string,\n base: string,\n existingHrefs?: ReadonlySet<string>,\n): VersionLink[] {\n return options.entries.map((entry) => {\n const siblingHref = siteHref(base, entry.prefix, siblingPath);\n const rootHref = siteHref(base, entry.prefix, \"\");\n const href =\n !existingHrefs || siblingPath === \"\" || existingHrefs.has(siblingHref)\n ? siblingHref\n : rootHref;\n return {\n id: entry.id,\n label: entry.label,\n href,\n current: entry.id === activeId,\n banner: entry.banner,\n };\n });\n}\n\n/** Version id and same-path remainder for a generated HTML file. */\nexport function versionLocation(\n outputPath: string,\n outDir: string,\n options: ResolvedVersionsOptions,\n): { id: string; sibling: string } {\n const normalized = relativeUrl(outputPath, outDir);\n for (const entry of options.entries) {\n if (!entry.prefix) {\n continue;\n }\n if (normalized === entry.prefix) {\n return { id: entry.id, sibling: \"\" };\n }\n if (normalized.startsWith(`${entry.prefix}/`)) {\n return { id: entry.id, sibling: normalized.slice(entry.prefix.length + 1) };\n }\n }\n return { id: options.current, sibling: normalized };\n}\n\nexport function outputToHref(outputPath: string, outDir: string, base: string): string {\n return siteHref(base, \"\", relativeUrl(outputPath, outDir));\n}\n\n/** Applies switcher / banner / search rewrite after every version tree is generated. */\nexport function decorateVersionedPages(\n pages: Array<{ outputPath: string; html: string }>,\n options: ResolvedVersionsOptions,\n outDir: string,\n base: string,\n): void {\n if (!options.enabled) {\n return;\n }\n const existingHrefs = new Set(pages.map((page) => outputToHref(page.outputPath, outDir, base)));\n for (const page of pages) {\n const { id, sibling } = versionLocation(page.outputPath, outDir, options);\n page.html = applyVersionChrome(page.html, options, id, sibling, base, existingHrefs);\n }\n}\n\nexport async function writeSnapshotSearchIndex(input: {\n srcDir: string;\n outDir: string;\n prefix: string;\n base: string;\n extensions: readonly string[];\n publishState?: ResolvedPublishStateOptions;\n mdx?: boolean;\n}): Promise<string | undefined> {\n const prefix = sanitizePrefix(input.prefix);\n if (!prefix) {\n return undefined;\n }\n const destDir = path.join(input.outDir, prefix);\n const prefixBase = searchIndexUrl(input.base, prefix).replace(/search-index\\.json$/, \"\");\n const json = await buildSearchIndex(\n input.srcDir,\n prefixBase,\n input.extensions,\n input.publishState,\n [],\n input.mdx,\n );\n await fs.mkdir(destDir, { recursive: true });\n await writeSearchIndex(json, destDir);\n const dest = path.join(destDir, \"search-index.json\");\n try {\n await fs.access(dest);\n } catch {\n await fs.writeFile(dest, json, \"utf8\");\n }\n return dest;\n}\n\nexport function applyVersionChrome(\n html: string,\n options: ResolvedVersionsOptions,\n activeId: string,\n siblingPath: string,\n base: string,\n existingHrefs?: ReadonlySet<string>,\n): string {\n if (!options.enabled) {\n return html;\n }\n const active = options.entries.find((entry) => entry.id === activeId);\n const switcher = options.switcher\n ? versionSwitcherMarkup(\n versionLinks(options, activeId, siblingPath, base, existingHrefs),\n options.badge,\n )\n : \"\";\n const banner = versionBannerMarkup(active?.banner);\n const from = searchIndexUrl(base, currentVersionPrefix(options));\n const to = searchIndexUrl(base, active?.prefix ?? \"\");\n return injectVersionChrome(html, switcher, banner, from, to);\n}\n\nexport function sanitizePrefix(prefix: string): string {\n const trimmed = prefix.trim().replace(/^\\/+|\\/+$/g, \"\");\n if (!trimmed) {\n return \"\";\n }\n return PREFIX_RE.test(trimmed) && !trimmed.includes(\"..\") ? trimmed : \"\";\n}\n\nfunction defaultCurrentEntry(): ResolvedVersionEntry {\n return {\n id: DEFAULT_CURRENT_ID,\n label: \"Latest\",\n prefix: \"\",\n banner: false,\n };\n}\n\nfunction normalizeEntries(entries: VersionEntry[] | undefined): ResolvedVersionEntry[] {\n if (!entries) {\n return [];\n }\n const seen = new Set<string>();\n const resolved: ResolvedVersionEntry[] = [];\n for (const entry of entries) {\n if (!entry || typeof entry.id !== \"string\" || typeof entry.label !== \"string\") {\n continue;\n }\n const id = entry.id.trim();\n const label = entry.label.trim();\n if (!id || !label || seen.has(id)) {\n continue;\n }\n const prefix = sanitizePrefix(typeof entry.prefix === \"string\" ? entry.prefix : \"\");\n if (entry.prefix && !prefix) {\n continue;\n }\n const dir = typeof entry.dir === \"string\" && entry.dir.trim() ? entry.dir.trim() : undefined;\n if (dir && (dir.includes(\"\\0\") || dir.includes(\"..\"))) {\n continue;\n }\n seen.add(id);\n resolved.push({\n id,\n label,\n prefix,\n dir,\n banner: normalizeBanner(entry.banner),\n });\n }\n return resolved;\n}\n\nfunction normalizeBanner(value: VersionEntry[\"banner\"]): VersionBannerKind | false {\n return value === \"unreleased\" || value === \"unmaintained\" ? value : false;\n}\n\nfunction siteHref(base: string, prefix: string, rest: string): string {\n const root = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n const parts = [prefix, rest].filter((part) => part && part !== \"/\");\n return parts.length === 0 ? root : `${root}${parts.join(\"/\")}/`;\n}\n\nfunction relativeUrl(outputPath: string, outDir: string): string {\n const rel = path.posix.normalize(\n path.relative(path.resolve(outDir), path.resolve(outputPath)).replaceAll(path.sep, \"/\"),\n );\n if (rel.startsWith(\"..\")) {\n return \"\";\n }\n const dir = rel.endsWith(\"/index.html\")\n ? rel.slice(0, -\"/index.html\".length)\n : rel.replace(/\\.html$/, \"\");\n return dir === \".\" ? \"\" : dir;\n}\n","/**\n * Keeps navigation inside a frozen documentation-version tree.\n *\n * Locale resolution runs before these helpers. The lookup therefore uses\n * unversioned route keys while every destination points at the versioned\n * output tree.\n */\n\nimport type { HeaderNavItem } from \"./header-chrome\";\nimport { sitePathFromHref } from \"./locale-nav\";\n\n/** @internal */\nexport interface VersionNavigationPage {\n /** Canonical route before the documentation-version prefix is added. */\n path: string;\n /** Canonical route after the documentation-version prefix is added. */\n versionedPath: string;\n /** Final versioned href. */\n href: string;\n /** File-tree route, used when a manual nav item predates a permalink. */\n sourcePath?: string;\n /** Frontmatter aliases that resolve to this page. */\n aliases?: readonly string[];\n}\n\n/** @internal */\nexport interface VersionNavigationContext {\n prefix: string;\n base: string;\n root: VersionNavigationTarget;\n pages: Array<{ path: string; href: string; aliases?: readonly string[] }>;\n lookup: ReadonlyMap<string, VersionNavigationTarget>;\n}\n\ninterface VersionNavigationTarget {\n path: string;\n href: string;\n}\n\ninterface VersionableNavItem {\n path: string;\n href: string;\n children?: VersionableNavItem[];\n}\n\ninterface VersionableNavGroup {\n items: VersionableNavItem[];\n}\n\n/** @internal */\nexport function createVersionNavigationContext(input: {\n prefix: string;\n base: string;\n pages: readonly VersionNavigationPage[];\n redirects?: Readonly<Record<string, string>>;\n}): VersionNavigationContext {\n const prefix = normalizeRouteKey(input.prefix, input.base);\n const root: VersionNavigationTarget = {\n path: prefix,\n href: siteHref(input.base, prefix),\n };\n const lookup = new Map<string, VersionNavigationTarget>();\n const targets = input.pages.map((page) => ({\n page,\n target: { path: normalizeRouteKey(page.versionedPath, input.base), href: page.href },\n }));\n\n // Canonical pages always win over a colliding source path or alias.\n for (const { page, target } of targets) {\n const key = routeLookupKey(page.path, input.base, prefix);\n if (key !== undefined) {\n lookup.set(key, target);\n }\n }\n for (const { page, target } of targets) {\n addLookup(lookup, page.sourcePath, target, input.base, prefix);\n for (const alias of page.aliases ?? []) {\n addLookup(lookup, alias, target, input.base, prefix);\n }\n }\n\n resolveRedirectAliases(lookup, input.redirects, input.base, prefix);\n return {\n prefix,\n base: input.base,\n root,\n pages: input.pages.map((page) => ({\n path: page.path,\n href: page.href,\n aliases: navigationAliases(page, lookup, input.redirects, input.base, prefix),\n })),\n lookup,\n };\n}\n\nfunction navigationAliases(\n page: VersionNavigationPage,\n lookup: ReadonlyMap<string, VersionNavigationTarget>,\n redirects: Readonly<Record<string, string>> | undefined,\n base: string,\n prefix: string,\n): string[] | undefined {\n const target = lookup.get(routeLookupKey(page.path, base, prefix) ?? \"\");\n const aliases = [page.sourcePath, ...(page.aliases ?? [])].filter(\n (value): value is string => typeof value === \"string\",\n );\n if (target && redirects) {\n for (const from of Object.keys(redirects)) {\n const key = routeLookupKey(from, base, prefix);\n if (key !== undefined && lookup.get(key) === target) {\n aliases.push(key);\n }\n }\n }\n const unique = [...new Set(aliases.map((value) => normalizeRouteKey(value, base)))];\n return unique.length > 0 ? unique : undefined;\n}\n\n/**\n * Rewrites safe internal sidebar destinations and all nested children.\n * @internal\n */\nexport function rewriteVersionedNavGroups<T extends VersionableNavGroup>(\n groups: T[],\n context: VersionNavigationContext,\n): T[] {\n return groups.map(\n (group) =>\n ({\n ...group,\n items: group.items.map((item) => rewriteNavItem(item, context)),\n }) as T,\n );\n}\n\n/**\n * Rewrites safe internal header destinations with the same sibling policy.\n * @internal\n */\nexport function rewriteVersionedHeaderNavItems(\n items: HeaderNavItem[] | undefined,\n context: VersionNavigationContext,\n): HeaderNavItem[] | undefined {\n return items?.map((item) => ({\n ...item,\n link: item.link ? rewriteHref(item.link, context).href : item.link,\n items: rewriteVersionedHeaderNavItems(item.items, context),\n }));\n}\n\n/**\n * Rewrites one safe internal destination, including pager overrides.\n * @internal\n */\nexport function rewriteVersionedHref(href: string, context: VersionNavigationContext): string {\n return rewriteHref(href, context).href;\n}\n\n/**\n * Removes only the active version prefix, leaving locale/path resolution intact.\n * @internal\n */\nexport function unversionedPath(path: string, context: VersionNavigationContext): string {\n const normalized = normalizeRouteKey(path, context.base);\n if (normalized === context.prefix) {\n return \"\";\n }\n return normalized.startsWith(`${context.prefix}/`)\n ? normalized.slice(context.prefix.length + 1)\n : normalized;\n}\n\n/** @internal Keeps missing locale siblings inside the active version tree. */\nexport function versionedLocaleRoots(\n context: VersionNavigationContext,\n locales: readonly { code: string }[],\n defaultLocale: string,\n hideDefaultLocale: boolean,\n): Record<string, string> {\n return Object.fromEntries(\n locales.map((locale) => {\n const route = hideDefaultLocale && locale.code === defaultLocale ? \"\" : locale.code;\n return [locale.code, context.lookup.get(route)?.href ?? context.root.href];\n }),\n );\n}\n\nfunction rewriteNavItem<T extends VersionableNavItem>(\n item: T,\n context: VersionNavigationContext,\n): T {\n const rewritten = rewriteHref(item.href, context, item.path);\n return {\n ...item,\n href: rewritten.href,\n path: rewritten.path,\n children: (item.children ?? []).map((child) => rewriteNavItem(child, context)),\n };\n}\n\nfunction rewriteHref(\n href: string,\n context: VersionNavigationContext,\n path?: string,\n): VersionNavigationTarget {\n const hrefKey = sitePathFromHref(href, context.base);\n if (hrefKey === undefined) {\n return { path: path ?? \"\", href };\n }\n const suffixIndex = href.search(/[?#]/u);\n const suffix = suffixIndex === -1 ? \"\" : href.slice(suffixIndex);\n const target = [path, hrefKey]\n .map((candidate) => routeLookupKey(candidate, context.base, context.prefix))\n .find((candidate) => candidate !== undefined && context.lookup.has(candidate));\n const resolved = target === undefined ? context.root : context.lookup.get(target)!;\n return { path: resolved.path, href: `${resolved.href}${suffix}` };\n}\n\nfunction addLookup(\n lookup: Map<string, VersionNavigationTarget>,\n value: string | undefined,\n target: VersionNavigationTarget,\n base: string,\n prefix: string,\n): void {\n const key = routeLookupKey(value, base, prefix);\n if (key !== undefined && !lookup.has(key)) {\n lookup.set(key, target);\n }\n}\n\nfunction resolveRedirectAliases(\n lookup: Map<string, VersionNavigationTarget>,\n redirects: Readonly<Record<string, string>> | undefined,\n base: string,\n prefix: string,\n): void {\n if (!redirects) {\n return;\n }\n const pending = Object.entries(redirects);\n for (let pass = 0; pass <= pending.length; pass++) {\n let changed = false;\n for (const [from, to] of pending) {\n const fromKey = routeLookupKey(from, base, prefix);\n const toKey = routeLookupKey(to, base, prefix);\n const target = toKey === undefined ? undefined : lookup.get(toKey);\n if (fromKey !== undefined && target && !lookup.has(fromKey)) {\n lookup.set(fromKey, target);\n changed = true;\n }\n }\n if (!changed) {\n break;\n }\n }\n}\n\nfunction routeLookupKey(\n value: string | undefined,\n base: string,\n prefix: string,\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n const fromHref = sitePathFromHref(value, base);\n const key = normalizeRouteKey(fromHref ?? value, base);\n if (key === prefix) {\n return \"\";\n }\n return key.startsWith(`${prefix}/`) ? key.slice(prefix.length + 1) : key;\n}\n\nfunction normalizeRouteKey(value: string, base: string): string {\n const fromHref = sitePathFromHref(value, base);\n return (fromHref ?? value)\n .trim()\n .split(/[?#]/u, 1)[0]!\n .replace(/^\\/+|\\/+$/gu, \"\")\n .replace(/\\/index\\.html$/iu, \"\")\n .replace(/\\.(?:mdx|markdown|md|html)$/iu, \"\");\n}\n\nfunction siteHref(base: string, path: string): string {\n const root = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return path ? `${root}${path}/` : root;\n}\n","/**\n * SSG (Static Site Generation) module for ox-content\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport { transformMarkdown } from \"./transform\";\nimport { generateOgImages } from \"./og-image\";\nimport type { OgImagePageEntry } from \"./og-image\";\nimport { transformAllPlugins } from \"./plugins\";\nimport type { TransformAllOptions } from \"./plugins\";\nimport { protectMermaidSvgs, restoreMermaidSvgs } from \"./plugins/mermaid-protect\";\nimport { transformIslands, hasIslands } from \"./island\";\nimport { importNapiModule, importNapiModuleSync } from \"./napi\";\nimport { DEFAULT_MARKDOWN_EXTENSIONS } from \"./markdown\";\nimport type {\n ResolvedOptions,\n ResolvedA11y,\n ResolvedReaderChrome,\n ResolvedSsgOptions,\n A11yOptions,\n ResolvedTeamOptions,\n ReaderChromeOptions,\n SsgOptions,\n SsgNavigationGroup,\n TocEntry,\n HeroConfig,\n FeatureConfig,\n LocaleConfig,\n} from \"./types\";\nimport { buildLocalePaths, resolveLocaleSwitcherOption } from \"./locale-switcher\";\nimport type { SsgLocalePath } from \"./locale-switcher\";\nimport {\n attachSidebarLabels,\n localizeHeaderNavItems,\n localizeNavGroups,\n resolveSidebarItems,\n} from \"./locale-nav\";\nimport {\n parsePageChromeFlags,\n resolvePageChromeOption,\n type PageChromeFlags,\n} from \"./header-chrome\";\nimport { resolveTheme, themeToNapi } from \"./theme\";\nimport type { ResolvedThemeConfig, SidebarItem } from \"./theme\";\nimport { normalizeVitePressFrontmatter } from \"./vitepress\";\nimport { renderPage } from \"./theme-renderer\";\nimport type { PageData as ThemePageData } from \"./theme-renderer\";\nimport { writeSiteMapFiles } from \"./site-maps\";\nimport { filterNavGroups, hiddenNavKeys, partitionPublishedPages } from \"./publish-state\";\nimport { applySsgPageRoutes, remapNavGroups } from \"./apply-permalinks\";\nimport { writeRedirectFiles } from \"./redirects\";\nimport {\n FALLBACK_NOT_FOUND_MARKDOWN,\n isNotFoundSourceFile,\n resolveNotFoundOptions,\n resolveNotFoundOutputPath,\n resolveNotFoundSourcePath,\n} from \"./not-found\";\nimport { buildCollectionManifest } from \"./collections\";\nimport { writeFeedFiles } from \"./feeds\";\nimport { appendTaxonomyPages, injectRelatedPages, toTaxonomyProcessResult } from \"./taxonomies\";\nimport { resolveTeamOptions } from \"./team\";\nimport {\n decorateVersionedPages,\n prefixRoutePaths,\n resolveSnapshotDir,\n snapshotEntries,\n writeSnapshotSearchIndex,\n} from \"./versions\";\nimport {\n createVersionNavigationContext,\n rewriteVersionedHeaderNavItems,\n rewriteVersionedHref,\n rewriteVersionedNavGroups,\n unversionedPath,\n versionedLocaleRoots,\n type VersionNavigationContext,\n} from \"./version-navigation\";\n\n/**\n * Navigation item for SSG.\n */\nexport interface SsgNavItem {\n title: string;\n path: string;\n href: string;\n children?: SsgNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/**\n * Entry page configuration for SSG (passed to Rust).\n */\nexport interface SsgEntryPageConfig {\n hero?: HeroConfig;\n features?: FeatureConfig[];\n}\n\n/**\n * Page data for SSG.\n */\nexport interface SsgPageData {\n title: string;\n description?: string;\n content: string;\n toc: TocEntry[];\n lastUpdated?: number;\n frontmatter: Record<string, unknown>;\n path: string;\n href: string;\n /** Entry page configuration (if layout: entry) */\n entryPage?: SsgEntryPageConfig;\n /** Frontmatter override for the previous-page link. */\n prev?: SsgPagerOverride;\n /** Frontmatter override for the next-page link. */\n next?: SsgPagerOverride;\n /** Frontmatter `breadcrumbs: false` hides the trail on this page. */\n breadcrumbs?: boolean;\n /** Per-page chrome flags. Honored only when `ssg.pageChrome` is on. */\n chrome?: PageChromeFlags;\n}\n\n/** Frontmatter override for one previous/next pager side. */\nexport interface SsgPagerOverride {\n hidden?: boolean;\n text?: string;\n href?: string;\n}\n\ninterface SsgRoutePaths {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n}\n\n/**\n * Deprecated compatibility export for consumers that imported the former\n * TypeScript SSG template. HTML generation is Rust-backed now.\n *\n * @deprecated Use `generateHtmlPage`/`buildSsg` instead.\n */\nexport const DEFAULT_HTML_TEMPLATE = \"<!-- ox-content default HTML template is Rust-backed -->\";\n\n/**\n * Resolves SSG options with defaults.\n */\nexport function resolveSsgOptions(ssg: SsgOptions | boolean | undefined): ResolvedSsgOptions {\n if (ssg === false) {\n return {\n enabled: false,\n extension: \".html\",\n clean: false,\n bare: false,\n generateOgImage: false,\n lastUpdated: false,\n pagination: false,\n breadcrumbs: false,\n readerChrome: false,\n localeSwitcher: false,\n a11y: false,\n pageChrome: false,\n notFound: resolveNotFoundOptions(undefined),\n team: resolveTeamOptions(undefined),\n };\n }\n\n if (ssg === true || ssg === undefined) {\n return {\n enabled: true,\n extension: \".html\",\n clean: false,\n bare: false,\n generateOgImage: false,\n lastUpdated: false,\n pagination: false,\n breadcrumbs: false,\n readerChrome: false,\n localeSwitcher: false,\n a11y: false,\n pageChrome: false,\n notFound: resolveNotFoundOptions(undefined),\n team: resolveTeamOptions(undefined),\n theme: resolveTheme(undefined),\n };\n }\n\n return {\n enabled: ssg.enabled ?? true,\n extension: ssg.extension ?? \".html\",\n clean: ssg.clean ?? false,\n bare: ssg.bare ?? false,\n render: ssg.render,\n lang: ssg.lang,\n head: ssg.head,\n bodyStart: ssg.bodyStart,\n bodyEnd: ssg.bodyEnd,\n siteName: ssg.siteName,\n ogImage: ssg.ogImage,\n generateOgImage: ssg.generateOgImage ?? false,\n lastUpdated: ssg.lastUpdated ?? false,\n pagination: resolvePaginationOption(ssg.pagination),\n breadcrumbs: resolvePaginationOption(ssg.breadcrumbs),\n readerChrome: resolveReaderChromeOption(ssg.readerChrome),\n localeSwitcher: resolveLocaleSwitcherOption(ssg.localeSwitcher),\n a11y: resolveA11yOption(ssg.a11y),\n pageChrome: resolvePageChromeOption(ssg.pageChrome),\n notFound: resolveNotFoundOptions(ssg.notFound),\n team: resolveTeamOptions(ssg.team),\n siteUrl: ssg.siteUrl,\n theme: resolveTheme(ssg.theme),\n navigation: ssg.navigation,\n };\n}\n\nfunction resolvePaginationOption(value: boolean | Record<string, unknown> | undefined): boolean {\n return value === true || (typeof value === \"object\" && value !== null);\n}\n\nfunction resolveReaderChromeOption(\n value: boolean | ReaderChromeOptions | undefined,\n): ResolvedReaderChrome {\n if (value === true) {\n return { copy: true, externalLinks: true, backToTop: true };\n }\n if (value && typeof value === \"object\") {\n return {\n copy: value.copy !== false,\n externalLinks: value.externalLinks !== false,\n backToTop: value.backToTop !== false,\n };\n }\n return false;\n}\n\nconst DEFAULT_SKIP_LINK_LABEL = \"Skip to content\";\n\nfunction resolveA11yOption(value: boolean | A11yOptions | undefined): ResolvedA11y {\n if (value === true) {\n return { skipLinkLabel: DEFAULT_SKIP_LINK_LABEL };\n }\n if (value && typeof value === \"object\") {\n const label = value.skipLinkLabel?.trim();\n return { skipLinkLabel: label || DEFAULT_SKIP_LINK_LABEL };\n }\n return false;\n}\n\n/** Parses `prev` / `next` frontmatter into a pager override. */\nexport function parseSsgPagerOverride(value: unknown): SsgPagerOverride | undefined {\n if (value === false) {\n return { hidden: true };\n }\n if (value == null || value === true) {\n return undefined;\n }\n if (typeof value !== \"object\") {\n return undefined;\n }\n const record = value as Record<string, unknown>;\n const text =\n typeof record.text === \"string\"\n ? record.text\n : typeof record.title === \"string\"\n ? record.title\n : undefined;\n const href =\n typeof record.link === \"string\"\n ? record.link\n : typeof record.href === \"string\"\n ? record.href\n : undefined;\n if (text === undefined && href === undefined) {\n return undefined;\n }\n return { text, href };\n}\n\n/**\n * Extracts title from content or frontmatter.\n */\nexport function extractTitle(content: string, frontmatter: Record<string, unknown>): string {\n return importNapiModuleSync().extractSsgTitle(\n content,\n typeof frontmatter.title === \"string\" ? frontmatter.title : undefined,\n );\n}\n\n/**\n * Generates bare HTML page (no navigation, no styles).\n */\nexport function generateBareHtmlPage(content: string, title: string): string {\n return importNapiModuleSync().generateSsgBareHtml(content, title);\n}\n\n/**\n * Generates a bare HTML page carrying head metadata and injected markup.\n *\n * Bare mode leaves the shell to the consumer, but the metadata here is\n * already computed for the themed page and cannot be recovered afterwards —\n * the generated OG image in particular was only discoverable by guessing at\n * the output directory. A page with none of it set renders exactly what bare\n * mode emitted before, which keeps the no-JS size baseline honest.\n */\nexport function generateBarePage(page: SsgBarePage): string {\n return importNapiModuleSync().generateSsgBarePage(page);\n}\n\n/** Head metadata and injected markup for a bare page. */\nexport interface SsgBarePage {\n title: string;\n content: string;\n lang?: string;\n dir?: string;\n description?: string;\n canonicalUrl?: string;\n siteName?: string;\n ogImage?: string;\n head?: string;\n bodyStart?: string;\n bodyEnd?: string;\n}\n\n/** NAPI-facing nav group shape produced from a [`NavGroup`]. */\ninterface RustNavGroup {\n title: string;\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n items: SsgNavItem[];\n}\n\n/**\n * Per-build cache for the Rust-facing nav conversion. `navGroups` is the same\n * `context.navItems` reference for every page in a build, so the deep recursive\n * copy below only needs to run once per build instead of once per page.\n */\nconst navGroupsForRustCache = new WeakMap<NavGroup[], RustNavGroup[]>();\n\nfunction toRustNavItem(item: SsgNavItem): SsgNavItem {\n return {\n title: item.title,\n path: item.path,\n href: item.href,\n children: item.children?.map(toRustNavItem),\n collapsed: item.collapsed,\n stickyCollapsed: item.stickyCollapsed,\n };\n}\n\nfunction convertNavGroupsForRust(navGroups: NavGroup[]): RustNavGroup[] {\n const cached = navGroupsForRustCache.get(navGroups);\n if (cached) {\n return cached;\n }\n const converted = navGroups.map((group) => ({\n title: group.title,\n collapsed: group.collapsed,\n stickyCollapsed: group.stickyCollapsed,\n items: group.items.map(toRustNavItem),\n }));\n navGroupsForRustCache.set(navGroups, converted);\n return converted;\n}\n\n/**\n * Converts a `TocEntry` tree into the plain shape the Rust binding expects.\n * Hoisted to module scope so it isn't reallocated for every page; the\n * per-page `.map` over `pageData.toc` still runs since the TOC is page-specific.\n */\nfunction toRustTocEntry(entry: TocEntry): TocEntry {\n return {\n depth: entry.depth,\n text: entry.text,\n slug: entry.slug,\n children: entry.children?.map(toRustTocEntry) ?? [],\n };\n}\n\n/** Rust-facing locale shape. */\ninterface RustLocale {\n code: string;\n name: string;\n dir: string;\n}\n\n/**\n * Per-build cache for the Rust-facing locale list. `i18n.locales` is the same\n * reference for every page in a build, so this mapping (and the `?? \"ltr\"`\n * default) only runs once per build instead of once per page.\n */\nconst rustLocalesCache = new WeakMap<LocaleConfig[], RustLocale[]>();\n\nfunction toRustLocales(locales: LocaleConfig[]): RustLocale[] {\n const cached = rustLocalesCache.get(locales);\n if (cached) {\n return cached;\n }\n const converted = locales.map((locale) => ({\n code: locale.code,\n name: locale.name,\n dir: locale.dir ?? \"ltr\",\n }));\n rustLocalesCache.set(locales, converted);\n return converted;\n}\n\n/**\n * Per-build cache for the locale-code list passed to `getSsgPageLocale`. The\n * `i18n.locales` reference is stable across a build, so the `.map` to codes\n * runs once instead of once per page.\n */\nconst localeCodesCache = new WeakMap<LocaleConfig[], string[]>();\n\nfunction localeCodesFor(locales: LocaleConfig[]): string[] {\n const cached = localeCodesCache.get(locales);\n if (cached) {\n return cached;\n }\n const codes = locales.map((locale) => locale.code);\n localeCodesCache.set(locales, codes);\n return codes;\n}\n\n/**\n * Generates HTML page with navigation using Rust NAPI bindings.\n */\nexport async function generateHtmlPage(\n pageData: SsgPageData,\n navGroups: NavGroup[],\n siteName: string,\n base: string,\n ogImage?: string,\n theme?: ResolvedThemeConfig,\n locale?: string,\n availableLocales?: LocaleConfig[],\n pagination = false,\n readerChrome: ResolvedReaderChrome = false,\n breadcrumbs = false,\n localeSwitcher = false,\n localePaths?: SsgLocalePath[],\n a11y: ResolvedA11y = false,\n team: ResolvedTeamOptions = { enabled: false, members: [] },\n pageChrome: boolean = false,\n breadcrumbRootHref?: string,\n): Promise<string> {\n const mod = await importNapiModule();\n\n // Convert TocEntry to the format expected by Rust (converter is module-scoped).\n const tocForRust = pageData.toc.map(toRustTocEntry);\n\n // Convert NavGroup to the format expected by Rust (cached per build).\n const navGroupsForRust = convertNavGroupsForRust(navGroups);\n\n // Convert theme to NAPI format if provided\n const themeForRust = theme ? themeToNapi(theme, locale) : undefined;\n\n // Convert entry page to NAPI format if provided\n const entryPageForRust = pageData.entryPage\n ? {\n hero: pageData.entryPage.hero\n ? {\n name: pageData.entryPage.hero.name,\n text: pageData.entryPage.hero.text,\n tagline: pageData.entryPage.hero.tagline,\n notice: pageData.entryPage.hero.notice\n ? {\n title: pageData.entryPage.hero.notice.title,\n body: pageData.entryPage.hero.notice.body,\n }\n : undefined,\n image: pageData.entryPage.hero.image\n ? {\n src: pageData.entryPage.hero.image.src,\n lightSrc: pageData.entryPage.hero.image.lightSrc,\n darkSrc: pageData.entryPage.hero.image.darkSrc,\n alt: pageData.entryPage.hero.image.alt,\n width: pageData.entryPage.hero.image.width,\n height: pageData.entryPage.hero.image.height,\n }\n : undefined,\n actions: pageData.entryPage.hero.actions?.map((a) => ({\n theme: a.theme,\n text: a.text,\n link: a.link,\n })),\n }\n : undefined,\n features: pageData.entryPage.features?.map((f) => ({\n icon: f.icon,\n title: f.title,\n details: f.details,\n link: f.link,\n linkText: f.linkText,\n })),\n }\n : undefined;\n\n return mod.generateSsgHtml(\n {\n title: pageData.title,\n description: pageData.description,\n content: pageData.content,\n toc: tocForRust,\n lastUpdated: pageData.lastUpdated,\n path: pageData.path,\n entryPage: entryPageForRust,\n prev: pageData.prev,\n next: pageData.next,\n breadcrumbs: pageData.breadcrumbs,\n layout:\n typeof pageData.frontmatter.layout === \"string\" ? pageData.frontmatter.layout : undefined,\n chrome: pageData.chrome,\n },\n navGroupsForRust,\n {\n siteName,\n base,\n breadcrumbRootHref,\n ogImage,\n theme: themeForRust,\n locale,\n availableLocales: availableLocales ? toRustLocales(availableLocales) : undefined,\n pagination,\n breadcrumbs,\n readerChrome: readerChrome\n ? {\n copy: readerChrome.copy,\n externalLinks: readerChrome.externalLinks,\n backToTop: readerChrome.backToTop,\n }\n : undefined,\n localeSwitcher: localeSwitcher || undefined,\n localePaths,\n a11y: a11y ? { skipLinkLabel: a11y.skipLinkLabel } : undefined,\n team,\n pageChrome,\n },\n );\n}\n\ninterface GeneratedHtmlPage {\n inputPath: string;\n outputPath: string;\n html: string;\n}\n\ninterface ExternalizedSharedAsset {\n outputPath: string;\n content: string;\n}\n\nasync function externalizeSharedPageAssets(\n pages: GeneratedHtmlPage[],\n outDir: string,\n base: string,\n): Promise<{ pages: GeneratedHtmlPage[]; assets: string[] }> {\n // Asset extraction is batched after all pages are rendered so the Rust side\n // can de-duplicate identical CSS/JS chunks across the whole build. Doing it\n // page-by-page would miss shared chunks and write duplicate assets.\n const mod = await importNapiModule();\n const optimized = mod.externalizeSsgAssets(pages, outDir, base) as {\n pages: GeneratedHtmlPage[];\n assets: ExternalizedSharedAsset[];\n };\n\n await Promise.all(\n optimized.assets.map(async (asset) => {\n await fs.mkdir(path.dirname(asset.outputPath), { recursive: true });\n await fs.writeFile(asset.outputPath, asset.content, \"utf-8\");\n }),\n );\n\n return {\n pages: optimized.pages,\n assets: optimized.assets.map((asset) => asset.outputPath),\n };\n}\n\n/**\n * Converts a markdown file path to its corresponding HTML output path.\n */\nexport function getOutputPath(\n inputPath: string,\n srcDir: string,\n outDir: string,\n extension: string,\n): string {\n return importNapiModuleSync().getSsgOutputPath(inputPath, srcDir, outDir, extension);\n}\n\n/**\n * Converts a markdown file path to a relative URL path.\n */\nexport function getUrlPath(inputPath: string, srcDir: string): string {\n return importNapiModuleSync().getSsgUrlPath(inputPath, srcDir);\n}\n\n/**\n * Converts a markdown file path to an href.\n */\nexport function getHref(\n inputPath: string,\n srcDir: string,\n base: string,\n extension: string,\n): string {\n return importNapiModuleSync().getSsgHref(inputPath, srcDir, base, extension);\n}\n\n/**\n * Resolves manual navigation config to the format used by the built-in SSG renderer.\n */\nexport function resolveNavigationGroups(\n navigation: SsgNavigationGroup[] | undefined,\n base: string,\n extension: string,\n): NavGroup[] | undefined {\n if (!navigation) {\n return undefined;\n }\n\n return importNapiModuleSync().resolveSsgNavigationGroups(navigation, base, extension);\n}\n\nexport function getPageLocale(urlPath: string, i18n: ResolvedOptions[\"i18n\"]): string | undefined {\n if (!i18n) return undefined;\n return (\n importNapiModuleSync().getSsgPageLocale(\n urlPath,\n i18n.defaultLocale,\n localeCodesFor(i18n.locales),\n ) ?? undefined\n );\n}\n\nfunction getRoutePaths(\n inputPath: string,\n srcDir: string,\n outDir: string,\n base: string,\n extension: string,\n siteUrl?: string,\n): SsgRoutePaths {\n return importNapiModuleSync().resolveSsgRoutePaths(\n inputPath,\n srcDir,\n outDir,\n base,\n extension,\n siteUrl,\n );\n}\n\n/**\n * Formats a file/dir name as a title.\n */\nexport function formatTitle(name: string): string {\n return importNapiModuleSync().formatSsgTitle(name);\n}\n\n/**\n * Collects all markdown files from the source directory.\n */\nexport async function collectMarkdownFiles(\n srcDir: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n): Promise<string[]> {\n return importNapiModuleSync().collectSsgMarkdownFiles(srcDir, [...extensions]);\n}\n\n/**\n * Navigation group for hierarchical navigation.\n */\nexport interface NavGroup {\n title: string;\n items: SsgNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/**\n * Builds navigation items from markdown files, grouped by directory.\n */\nexport function buildNavItems(\n markdownFiles: string[],\n srcDir: string,\n base: string,\n extension: string,\n): NavGroup[] {\n return importNapiModuleSync().buildSsgNavItems(markdownFiles, srcDir, base, extension);\n}\n\n/**\n * Builds navigation items from an explicit theme sidebar tree while retaining\n * locale-map labels for per-page resolution.\n */\nexport function buildThemeNavItems(\n sidebar: SidebarItem[],\n base: string,\n extension: string,\n): NavGroup[] {\n const groups = importNapiModuleSync().buildSsgThemeNavItems(\n resolveSidebarItems(sidebar),\n base,\n extension,\n );\n return attachSidebarLabels(groups, sidebar);\n}\n\ninterface BuildSsgContext {\n options: ResolvedOptions;\n ssgOptions: ResolvedSsgOptions;\n root: string;\n srcDir: string;\n outDir: string;\n base: string;\n siteName: string;\n navItems: NavGroup[];\n versionNavigation?: VersionNavigationContext;\n shouldGenerateOgImages: boolean;\n napi?: Awaited<ReturnType<typeof importNapiModule>>;\n}\n\ninterface PageProcessResult {\n inputPath: string;\n routePaths: SsgRoutePaths;\n transformedHtml: string;\n title: string;\n description?: string;\n lastUpdated?: number;\n frontmatter: Record<string, unknown>;\n toc: TocEntry[];\n}\n\ninterface CollectedPageResults {\n pageResults: PageProcessResult[];\n ogImageEntries: OgImagePageEntry[];\n ogImageInputPaths: string[];\n ogImageUrlMap: Map<string, string>;\n errors: string[];\n}\n\n/** Result of an SSG build. */\nexport interface SsgBuildResult {\n /** Every file written, HTML pages and generated OG images alike. */\n files: string[];\n /** Per-page failures that did not abort the build. */\n errors: string[];\n /**\n * Generated OG image URL per source file, keyed by absolute input path.\n *\n * Bare mode renders these into the page itself, but a consumer\n * post-processing the output had no way to find them short of probing the\n * output directory for `og-image.png`.\n */\n ogImages: Record<string, string>;\n}\n\n/**\n * Builds all markdown files to static HTML.\n */\nexport async function buildSsg(options: ResolvedOptions, root: string): Promise<SsgBuildResult> {\n const ssgOptions = options.ssg;\n if (!ssgOptions.enabled) {\n return { files: [], errors: [], ogImages: {} };\n }\n\n const srcDir = path.resolve(root, options.srcDir);\n const outDir = path.resolve(root, options.outDir);\n const generatedFiles: string[] = [];\n const errors: string[] = [];\n\n await cleanOutputDirectory(ssgOptions, outDir);\n\n const markdownFiles = await collectMarkdownFiles(srcDir, options.extensions);\n const pageFiles = markdownFiles.filter(\n (file) => !isNotFoundSourceFile(file, srcDir, ssgOptions.notFound),\n );\n const context = await createBuildSsgContext(options, root, srcDir, outDir, pageFiles);\n const collected = await collectPageResults(context, pageFiles);\n applyPermalinkRoutes(context, collected);\n errors.push(...collected.errors);\n const { outputPages, listedPages } = applyPublishState(context, collected);\n remapPermalinkNav(context, listedPages);\n\n await generateOgImageAssets(context, collected, generatedFiles, errors);\n\n injectRelatedPages(outputPages, listedPages, context.options.taxonomies);\n const generatedPages = await generateHtmlPages(context, outputPages, collected, errors);\n await appendNotFoundPage(generatedPages, context, collected, errors);\n await appendTaxonomyPages({\n generatedPages,\n listedPages,\n options: context.options.taxonomies,\n outDir: context.outDir,\n base: context.base,\n errors,\n render: (page) => renderSsgPage(context, toTaxonomyProcessResult(page), collected, listedPages),\n });\n await applyDocumentationVersions(generatedPages, context, errors);\n await writeGeneratedPages(\n generatedPages,\n context,\n generatedFiles,\n listedPages,\n outputPages,\n errors,\n );\n\n return {\n files: generatedFiles,\n errors,\n ogImages: Object.fromEntries(collected.ogImageUrlMap),\n };\n}\n\nasync function cleanOutputDirectory(ssgOptions: ResolvedSsgOptions, outDir: string): Promise<void> {\n if (!ssgOptions.clean) {\n return;\n }\n\n try {\n await fs.rm(outDir, { recursive: true, force: true });\n } catch {\n // Ignore if directory doesn't exist.\n }\n}\n\nasync function createBuildSsgContext(\n options: ResolvedOptions,\n root: string,\n srcDir: string,\n outDir: string,\n markdownFiles: string[],\n): Promise<BuildSsgContext> {\n const ssgOptions = options.ssg;\n const base = options.base.endsWith(\"/\") ? options.base : options.base + \"/\";\n const navItems =\n resolveNavigationGroups(ssgOptions.navigation, base, ssgOptions.extension) ??\n (ssgOptions.theme?.sidebar.length\n ? buildThemeNavItems(ssgOptions.theme.sidebar, base, ssgOptions.extension)\n : buildNavItems(markdownFiles, srcDir, base, ssgOptions.extension));\n\n return {\n options,\n ssgOptions,\n root,\n srcDir,\n outDir,\n base,\n navItems,\n siteName: await resolveSiteName(root, ssgOptions),\n shouldGenerateOgImages: shouldGenerateOgImages(options),\n napi: ssgOptions.lastUpdated ? await importNapiModule() : undefined,\n };\n}\n\n/**\n * Whether this build emits one Open Graph image per page.\n *\n * `ssg.bare` deliberately does not turn this off. Bare mode only drops the\n * generated page shell, and bringing your own shell is exactly the case where\n * per-page OG images are still wanted — the images are written to the output\n * tree and the consumer injects the `<meta>` tags itself. Nothing in the bare\n * HTML references them, because bare output has no `<head>` to put them in.\n */\nexport function shouldGenerateOgImages(options: ResolvedOptions): boolean {\n return options.ogImage || options.ssg.generateOgImage;\n}\n\nasync function resolveSiteName(root: string, ssgOptions: ResolvedSsgOptions): Promise<string> {\n if (ssgOptions.siteName) {\n return ssgOptions.siteName;\n }\n\n try {\n const pkgPath = path.join(root, \"package.json\");\n const pkg = JSON.parse(await fs.readFile(pkgPath, \"utf-8\"));\n return pkg.name ? formatTitle(pkg.name) : \"Documentation\";\n } catch {\n return \"Documentation\";\n }\n}\n\nfunction applyPermalinkRoutes(context: BuildSsgContext, collected: CollectedPageResults): void {\n if (!context.options.permalinks?.enabled && !context.options.cascade?.enabled) {\n return;\n }\n\n const routed = applySsgPageRoutes({\n pages: collected.pageResults,\n permalinks: context.options.permalinks,\n cascade: context.options.cascade,\n srcDir: context.srcDir,\n outDir: context.outDir,\n base: context.base,\n extension: context.ssgOptions.extension,\n siteUrl: context.ssgOptions.siteUrl,\n });\n collected.errors.push(...routed.errors);\n collected.pageResults = routed.pages as PageProcessResult[];\n\n collected.ogImageEntries = [];\n collected.ogImageInputPaths = [];\n collected.ogImageUrlMap.clear();\n for (const page of collected.pageResults) {\n collectOgImageEntry(context, page, collected);\n }\n}\n\nfunction remapPermalinkNav(context: BuildSsgContext, listedPages: PageProcessResult[]): void {\n if (!context.options.permalinks?.enabled) {\n return;\n }\n const usedManualNav =\n Boolean(context.ssgOptions.navigation) || Boolean(context.ssgOptions.theme?.sidebar.length);\n if (usedManualNav) {\n return;\n }\n\n context.navItems = remapNavGroups(\n buildNavItems(\n listedPages.map((page) => page.inputPath),\n context.srcDir,\n context.base,\n context.ssgOptions.extension,\n ),\n listedPages.map((page) => ({\n fileUrl: getUrlPath(page.inputPath, context.srcDir),\n urlPath: page.routePaths.urlPath,\n href: page.routePaths.href,\n })),\n [],\n );\n}\n\nasync function collectPageResults(\n context: BuildSsgContext,\n markdownFiles: string[],\n): Promise<CollectedPageResults> {\n const collected: CollectedPageResults = {\n pageResults: [],\n ogImageEntries: [],\n ogImageInputPaths: [],\n ogImageUrlMap: new Map(),\n errors: [],\n };\n\n for (const inputPath of markdownFiles) {\n try {\n const pageResult = await transformSsgPage(context, inputPath);\n collected.pageResults.push(pageResult);\n collectOgImageEntry(context, pageResult, collected);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n collected.errors.push(`Failed to process ${inputPath}: ${errorMessage}`);\n }\n }\n\n return collected;\n}\n\nfunction applyPublishState(\n context: BuildSsgContext,\n collected: CollectedPageResults,\n): { outputPages: PageProcessResult[]; listedPages: PageProcessResult[] } {\n const publishState = context.options.publishState;\n const { output, listed } = partitionPublishedPages(collected.pageResults, publishState);\n if (!publishState?.enabled) {\n return { outputPages: output, listedPages: listed };\n }\n\n const usedManualNav =\n Boolean(context.ssgOptions.navigation) || Boolean(context.ssgOptions.theme?.sidebar.length);\n if (usedManualNav) {\n context.navItems = filterNavGroups(\n context.navItems,\n hiddenNavKeys(collected.pageResults, listed),\n );\n } else {\n context.navItems = buildNavItems(\n listed.map((page) => page.inputPath),\n context.srcDir,\n context.base,\n context.ssgOptions.extension,\n );\n }\n\n const outputPaths = new Set(output.map((page) => page.inputPath));\n collected.ogImageEntries = collected.ogImageEntries.filter((_, index) =>\n outputPaths.has(collected.ogImageInputPaths[index] ?? \"\"),\n );\n collected.ogImageInputPaths = collected.ogImageInputPaths.filter((inputPath) =>\n outputPaths.has(inputPath),\n );\n for (const inputPath of collected.ogImageUrlMap.keys()) {\n if (!outputPaths.has(inputPath)) {\n collected.ogImageUrlMap.delete(inputPath);\n }\n }\n\n return { outputPages: output, listedPages: listed };\n}\n\nasync function transformSsgPage(\n context: BuildSsgContext,\n inputPath: string,\n): Promise<PageProcessResult> {\n const content = await fs.readFile(inputPath, \"utf-8\");\n const result = await transformMarkdown(content, inputPath, context.options, {\n convertMdLinks: true,\n baseUrl: context.base,\n sourcePath: inputPath,\n });\n const frontmatter = normalizeVitePressFrontmatter(result.frontmatter);\n const transformedHtml = await transformSsgHtml(result.html, context.options);\n const title = extractTitle(transformedHtml, frontmatter);\n\n return {\n inputPath,\n routePaths: getRoutePaths(\n inputPath,\n context.srcDir,\n context.outDir,\n context.base,\n context.ssgOptions.extension,\n context.ssgOptions.siteUrl,\n ),\n transformedHtml,\n title,\n description: frontmatter.description as string | undefined,\n lastUpdated: context.napi?.getGitLastUpdated(inputPath, context.root) ?? undefined,\n frontmatter,\n toc: result.toc,\n };\n}\n\nasync function transformSsgHtml(html: string, options: ResolvedOptions): Promise<string> {\n // Mermaid SVGs are protected before plugin transforms because some transforms\n // still use HTML parser/stringifier steps that can corrupt SVG foreignObject\n // markup. The protect/restore pair keeps the rest of the pipeline free to\n // operate on normal HTML strings.\n const { html: protectedHtml, svgs: mermaidSvgs } = protectMermaidSvgs(html);\n const pluginOptions: TransformAllOptions = {\n tabs: true,\n youtube: true,\n github: options.embeds.github,\n openGraph: options.embeds.openGraph,\n pm: options.embeds.pm,\n spotify: options.embeds.spotify,\n stackBlitz: options.embeds.stackBlitz,\n twitter: options.embeds.twitter,\n bluesky: options.embeds.bluesky,\n webContainer: options.embeds.webContainer,\n mermaid: true,\n githubToken: process.env.GITHUB_TOKEN,\n };\n\n let transformedHtml = await transformAllPlugins(protectedHtml, pluginOptions);\n if (hasIslands(transformedHtml)) {\n const islandResult = await transformIslands(transformedHtml);\n transformedHtml = islandResult.html;\n }\n\n return restoreMermaidSvgs(transformedHtml, mermaidSvgs);\n}\n\nfunction collectOgImageEntry(\n context: BuildSsgContext,\n pageResult: PageProcessResult,\n collected: CollectedPageResults,\n): void {\n if (!context.shouldGenerateOgImages) {\n return;\n }\n\n const { layout: _layout, ...frontmatterRest } = pageResult.frontmatter;\n collected.ogImageEntries.push({\n props: {\n ...frontmatterRest,\n title: pageResult.title,\n description: pageResult.description,\n siteName: context.siteName,\n },\n outputPath: pageResult.routePaths.ogImagePath,\n });\n collected.ogImageInputPaths.push(pageResult.inputPath);\n collected.ogImageUrlMap.set(pageResult.inputPath, pageResult.routePaths.ogImageUrl);\n}\n\nasync function generateOgImageAssets(\n context: BuildSsgContext,\n collected: CollectedPageResults,\n generatedFiles: string[],\n errors: string[],\n): Promise<void> {\n if (!context.shouldGenerateOgImages || collected.ogImageEntries.length === 0) {\n return;\n }\n\n try {\n const ogResults = await generateOgImages(\n collected.ogImageEntries,\n context.options.ogImageOptions,\n context.root,\n );\n if (clearMissingBrowserOgImages(ogResults, collected)) {\n return;\n }\n\n reportOgImageResults(ogResults, collected, generatedFiles, errors);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n console.warn(`[ox-content:og-image] Batch generation failed: ${errorMessage}`);\n collected.ogImageUrlMap.clear();\n }\n}\n\nfunction clearMissingBrowserOgImages(\n ogResults: Awaited<ReturnType<typeof generateOgImages>>,\n collected: CollectedPageResults,\n): boolean {\n const allMissingBrowser =\n ogResults.length > 0 && ogResults.every((result) => result.error === \"Chromium not available\");\n if (!allMissingBrowser) {\n return false;\n }\n\n for (const inputPath of collected.ogImageInputPaths) {\n collected.ogImageUrlMap.delete(inputPath);\n }\n return true;\n}\n\nfunction reportOgImageResults(\n ogResults: Awaited<ReturnType<typeof generateOgImages>>,\n collected: CollectedPageResults,\n generatedFiles: string[],\n errors: string[],\n): void {\n let ogSuccessCount = 0;\n\n for (let i = 0; i < ogResults.length; i++) {\n const result = ogResults[i];\n if (result.error) {\n errors.push(`OG image failed for ${result.outputPath}: ${result.error}`);\n collected.ogImageUrlMap.delete(collected.ogImageInputPaths[i]);\n } else {\n generatedFiles.push(result.outputPath);\n ogSuccessCount++;\n }\n }\n\n if (ogSuccessCount > 0) {\n const cachedCount = ogResults.filter((result) => result.cached && !result.error).length;\n console.log(\n `[ox-content:og-image] Generated ${ogSuccessCount} OG images` +\n (cachedCount > 0 ? ` (${cachedCount} from cache)` : \"\"),\n );\n }\n}\n\nasync function generateHtmlPages(\n context: BuildSsgContext,\n pageResults: PageProcessResult[],\n collected: CollectedPageResults,\n errors: string[],\n): Promise<GeneratedHtmlPage[]> {\n const generatedPages: GeneratedHtmlPage[] = [];\n\n for (const pageResult of pageResults) {\n try {\n generatedPages.push({\n inputPath: pageResult.inputPath,\n outputPath: pageResult.routePaths.outputPath,\n html: await renderSsgPage(context, pageResult, collected, pageResults),\n });\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n errors.push(`Failed to generate HTML for ${pageResult.inputPath}: ${errorMessage}`);\n }\n }\n\n return generatedPages;\n}\n\nasync function renderSsgPage(\n context: BuildSsgContext,\n pageResult: PageProcessResult,\n collected: CollectedPageResults,\n allPageResults: PageProcessResult[],\n): Promise<string> {\n const { ogImageUrlMap } = collected;\n const pageOgImage =\n context.shouldGenerateOgImages && ogImageUrlMap.has(pageResult.inputPath)\n ? ogImageUrlMap.get(pageResult.inputPath)\n : context.ssgOptions.ogImage;\n\n // A theme component owns the whole document, so it comes before both the\n // bare shell and the built-in renderer.\n if (context.ssgOptions.render) {\n const nav = context.versionNavigation\n ? rewriteVersionedNavGroups(context.navItems, context.versionNavigation)\n : context.navItems;\n return renderPage(toThemePageData(pageResult), {\n theme: context.ssgOptions.render,\n siteName: context.siteName,\n base: context.base,\n nav,\n pages: allPageResults.map(toThemePageData),\n });\n }\n\n if (context.ssgOptions.bare) {\n return generateBarePage({\n title: pageResult.title,\n content: pageResult.transformedHtml,\n lang:\n context.ssgOptions.lang ??\n getPageLocale(pageResult.routePaths.urlPath, context.options.i18n),\n description: pageResult.description,\n canonicalUrl: canonicalPageUrl(context, pageResult.routePaths.urlPath),\n siteName: context.ssgOptions.siteName,\n ogImage: pageOgImage,\n head: context.ssgOptions.head,\n bodyStart: context.ssgOptions.bodyStart,\n bodyEnd: context.ssgOptions.bodyEnd,\n });\n }\n\n const pageData = createSsgPageData(pageResult);\n const versionNavigation = context.versionNavigation;\n if (versionNavigation) {\n pageData.prev = rewritePagerOverride(pageData.prev, versionNavigation);\n pageData.next = rewritePagerOverride(pageData.next, versionNavigation);\n }\n\n const i18n = context.options.i18n;\n const pages = versionNavigation\n ? versionNavigation.pages\n : allPageResults.map((result) => ({\n path: result.routePaths.urlPath,\n href: result.routePaths.href,\n }));\n const localePath = versionNavigation\n ? unversionedPath(pageData.path, versionNavigation)\n : pageData.path;\n const locale = getPageLocale(localePath, i18n);\n const localeNav =\n i18n && locale\n ? {\n locale,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages,\n base: context.base,\n }\n : undefined;\n const localizedNav = localeNav\n ? localizeNavGroups(context.navItems, localeNav)\n : context.navItems;\n const navItems = versionNavigation\n ? rewriteVersionedNavGroups(localizedNav, versionNavigation)\n : localizedNav;\n const localizedTheme = context.ssgOptions.theme\n ? localeNav\n ? {\n ...context.ssgOptions.theme,\n nav: localizeHeaderNavItems(context.ssgOptions.theme.nav, localeNav),\n }\n : context.ssgOptions.theme\n : undefined;\n const theme =\n localizedTheme && versionNavigation\n ? {\n ...localizedTheme,\n nav: rewriteVersionedHeaderNavItems(localizedTheme.nav, versionNavigation),\n }\n : localizedTheme;\n const localePaths =\n context.ssgOptions.localeSwitcher && i18n\n ? buildLocalePaths({\n currentPath: localePath,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages,\n base: context.base,\n roots: versionNavigation\n ? versionedLocaleRoots(\n versionNavigation,\n i18n.locales,\n i18n.defaultLocale,\n i18n.hideDefaultLocale,\n )\n : undefined,\n })\n : undefined;\n\n return generateHtmlPage(\n pageData,\n navItems,\n context.siteName,\n context.base,\n pageOgImage,\n theme,\n locale,\n i18n ? i18n.locales : undefined,\n context.ssgOptions.pagination,\n context.ssgOptions.readerChrome,\n context.ssgOptions.breadcrumbs,\n context.ssgOptions.localeSwitcher,\n localePaths,\n context.ssgOptions.a11y,\n context.ssgOptions.team ?? { enabled: false, members: [] },\n context.ssgOptions.pageChrome,\n versionNavigation?.root.href,\n );\n}\n\nfunction rewritePagerOverride(\n pager: SsgPagerOverride | undefined,\n context: VersionNavigationContext,\n): SsgPagerOverride | undefined {\n return pager?.href ? { ...pager, href: rewriteVersionedHref(pager.href, context) } : pager;\n}\n\n/** Maps an internal page result onto the theme renderer's page shape. */\nfunction toThemePageData(pageResult: PageProcessResult): ThemePageData {\n return {\n title: pageResult.title,\n description: pageResult.description,\n html: pageResult.transformedHtml,\n toc: pageResult.toc,\n lastUpdated: pageResult.lastUpdated,\n path: pageResult.inputPath,\n url: pageResult.routePaths.href,\n frontmatter: pageResult.frontmatter,\n layout:\n typeof pageResult.frontmatter.layout === \"string\" ? pageResult.frontmatter.layout : undefined,\n };\n}\n\n/**\n * Absolute URL of a page, or `undefined` when `ssg.siteUrl` is not set.\n *\n * Built the same way `get_og_image_url` builds the image URL next to it, so\n * the canonical link and `og:image` always agree about where the page lives.\n */\nfunction canonicalPageUrl(context: BuildSsgContext, urlPath: string): string | undefined {\n const siteUrl = context.ssgOptions.siteUrl?.replace(/\\/+$/, \"\");\n if (!siteUrl) {\n return undefined;\n }\n if (urlPath === \"/\" || urlPath === \"\") {\n return `${siteUrl}${context.base}`;\n }\n return `${siteUrl}${context.base}${urlPath}/`;\n}\n\nfunction createSsgPageData(pageResult: PageProcessResult): SsgPageData {\n const { frontmatter } = pageResult;\n const entryPage =\n frontmatter.layout === \"entry\"\n ? {\n hero: frontmatter.hero as HeroConfig | undefined,\n features: frontmatter.features as FeatureConfig[] | undefined,\n }\n : undefined;\n\n return {\n title: pageResult.title,\n description: pageResult.description,\n content: pageResult.transformedHtml,\n toc: pageResult.toc,\n lastUpdated: pageResult.lastUpdated,\n frontmatter,\n path: pageResult.routePaths.urlPath,\n href: pageResult.routePaths.href,\n entryPage,\n prev: parseSsgPagerOverride(frontmatter.prev),\n next: parseSsgPagerOverride(frontmatter.next),\n breadcrumbs: frontmatter.breadcrumbs === false ? false : undefined,\n chrome: parsePageChromeFlags(frontmatter),\n };\n}\n\nasync function appendNotFoundPage(\n generatedPages: GeneratedHtmlPage[],\n context: BuildSsgContext,\n collected: CollectedPageResults,\n errors: string[],\n): Promise<void> {\n const notFound = context.ssgOptions.notFound;\n if (!notFound?.enabled) {\n return;\n }\n\n const sourcePath = resolveNotFoundSourcePath(context.srcDir, notFound.source);\n const outputPath = resolveNotFoundOutputPath(context.outDir, notFound.output);\n\n try {\n const markdown = (await fileExists(sourcePath))\n ? await fs.readFile(sourcePath, \"utf8\")\n : FALLBACK_NOT_FOUND_MARKDOWN;\n const pageResult = await transformNotFoundMarkdown(context, sourcePath, markdown);\n pageResult.routePaths = { ...pageResult.routePaths, outputPath, urlPath: \"\" };\n generatedPages.push({\n inputPath: sourcePath,\n outputPath,\n html: await renderSsgPage(context, pageResult, collected, collected.pageResults),\n });\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n errors.push(`Failed to generate 404 page: ${errorMessage}`);\n }\n}\n\nasync function fileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function transformNotFoundMarkdown(\n context: BuildSsgContext,\n inputPath: string,\n markdown: string,\n): Promise<PageProcessResult> {\n const result = await transformMarkdown(markdown, inputPath, context.options, {\n convertMdLinks: true,\n baseUrl: context.base,\n // The page is written at the output root (`404.html`), so relative links\n // must resolve as if authored by that root's index page.\n sourcePath: path.join(context.srcDir, \"index.md\"),\n });\n const frontmatter = normalizeVitePressFrontmatter(result.frontmatter);\n const transformedHtml = await transformSsgHtml(result.html, context.options);\n\n return {\n inputPath,\n routePaths: {\n outputPath: inputPath,\n urlPath: \"\",\n href: `${context.base}${context.ssgOptions.notFound?.output ?? \"404.html\"}`,\n ogImagePath: \"\",\n ogImageUrl: \"\",\n },\n transformedHtml,\n title: extractTitle(transformedHtml, frontmatter),\n description: typeof frontmatter.description === \"string\" ? frontmatter.description : undefined,\n frontmatter,\n toc: result.toc,\n };\n}\n\nasync function applyDocumentationVersions(\n generatedPages: GeneratedHtmlPage[],\n context: BuildSsgContext,\n errors: string[],\n): Promise<void> {\n const versions = context.options.versions;\n if (!versions?.enabled) {\n return;\n }\n for (const entry of snapshotEntries(versions)) {\n const snapSrc = resolveSnapshotDir(context.root, entry.dir ?? \"\");\n if (!snapSrc) {\n continue;\n }\n const files = await collectMarkdownFiles(snapSrc, context.options.extensions);\n if (files.length === 0) {\n continue;\n }\n const snapContext = await createBuildSsgContext(\n context.options,\n context.root,\n snapSrc,\n context.outDir,\n files,\n );\n const snapCollected = await collectPageResults(snapContext, files);\n applyPermalinkRoutes(snapContext, snapCollected);\n errors.push(...snapCollected.errors);\n const { outputPages, listedPages } = applyPublishState(snapContext, snapCollected);\n remapPermalinkNav(snapContext, listedPages);\n const unversionedRoutes = new Map(\n snapCollected.pageResults.map((page) => [page.inputPath, { ...page.routePaths }]),\n );\n for (const page of snapCollected.pageResults) {\n page.routePaths = {\n ...page.routePaths,\n ...prefixRoutePaths(page.routePaths, entry.prefix, context.outDir, context.base),\n };\n }\n snapContext.versionNavigation = createVersionNavigationContext({\n prefix: entry.prefix,\n base: context.base,\n pages: listedPages.flatMap((page) => {\n const route = unversionedRoutes.get(page.inputPath);\n return route\n ? [\n {\n path: route.urlPath,\n versionedPath: page.routePaths.urlPath,\n href: page.routePaths.href,\n sourcePath: getUrlPath(page.inputPath, snapContext.srcDir),\n aliases: pageAliases(page.frontmatter),\n },\n ]\n : [];\n }),\n redirects: snapContext.options.redirects?.map,\n });\n const snapPages = await generateHtmlPages(snapContext, outputPages, snapCollected, errors);\n generatedPages.push(...snapPages);\n if (context.options.search?.enabled) {\n try {\n await writeSnapshotSearchIndex({\n srcDir: snapSrc,\n outDir: context.outDir,\n prefix: entry.prefix,\n base: context.base,\n extensions: context.options.extensions,\n publishState: context.options.publishState,\n mdx: context.options.mdx,\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n errors.push(`Failed to write search index for ${entry.id}: ${message}`);\n }\n }\n }\n decorateVersionedPages(generatedPages, versions, context.outDir, context.base);\n}\n\nfunction pageAliases(frontmatter: Record<string, unknown>): string[] {\n const aliases = frontmatter.aliases;\n const values = typeof aliases === \"string\" ? [aliases] : Array.isArray(aliases) ? aliases : [];\n const resolved = values.filter((value): value is string => typeof value === \"string\");\n return typeof frontmatter.redirect === \"string\" ? [...resolved, frontmatter.redirect] : resolved;\n}\n\nasync function writeGeneratedPages(\n generatedPages: GeneratedHtmlPage[],\n context: BuildSsgContext,\n generatedFiles: string[],\n listedPages: PageProcessResult[],\n outputPages: PageProcessResult[],\n errors: string[],\n): Promise<void> {\n // Shared asset extraction needs the complete page set to maximize\n // de-duplication. Only after replacement do we write pages and record both\n // the generated assets and the rewritten HTML files.\n const optimizedOutput = await externalizeSharedPageAssets(\n generatedPages,\n context.outDir,\n context.base,\n );\n generatedFiles.push(...optimizedOutput.assets);\n\n for (const page of optimizedOutput.pages) {\n await fs.mkdir(path.dirname(page.outputPath), { recursive: true });\n await fs.writeFile(page.outputPath, page.html, \"utf-8\");\n generatedFiles.push(page.outputPath);\n }\n\n const siteMaps = await writeSiteMapFiles({\n outDir: context.outDir,\n siteUrl: context.ssgOptions.siteUrl,\n base: context.base,\n siteName: context.siteName,\n options: context.options.siteMaps,\n pages: sitemapPages(context, listedPages, outputPages),\n });\n generatedFiles.push(...siteMaps.files);\n if (siteMaps.warning) {\n errors.push(siteMaps.warning);\n console.warn(siteMaps.warning);\n }\n\n const redirects = await writeRedirectFiles({\n outDir: context.outDir,\n base: context.base,\n options: context.options.redirects,\n pages: outputPages.map((page) => ({\n dest: sitePathFromUrlPath(page.routePaths.urlPath),\n aliases: page.frontmatter.aliases,\n redirect: page.frontmatter.redirect,\n })),\n });\n generatedFiles.push(...redirects.files);\n\n const feeds = await writeFeedFiles({\n outDir: context.outDir,\n siteUrl: context.ssgOptions.siteUrl,\n base: context.base,\n siteName: context.siteName,\n options: context.options.feeds,\n publishState: context.options.publishState,\n collectionNames: Object.keys(context.options.collections?.collections ?? {}),\n collections: context.options.feeds?.enabled\n ? (await buildCollectionManifest(context.root, context.options)).collections\n : undefined,\n });\n generatedFiles.push(...feeds.files);\n if (feeds.warning) {\n errors.push(feeds.warning);\n console.warn(feeds.warning);\n }\n}\n\n/** Turns an SSG `urlPath` (`guide` or `/`) into a same-origin dest (`/guide`). */\nfunction sitePathFromUrlPath(urlPath: string): string {\n if (!urlPath || urlPath === \"/\") {\n return \"/\";\n }\n return urlPath.startsWith(\"/\") ? urlPath : `/${urlPath}`;\n}\n\nfunction sitemapPages(\n context: BuildSsgContext,\n listedPages: PageProcessResult[],\n outputPages: PageProcessResult[],\n): Array<{ loc: string; title: string; description?: string; draft: boolean; unlisted: boolean }> {\n const pages = context.options.publishState?.enabled ? listedPages : outputPages;\n const listedPaths = new Set(listedPages.map((page) => page.inputPath));\n return pages.map((page) => ({\n loc: canonicalPageUrl(context, page.routePaths.urlPath) ?? \"\",\n title: page.title,\n description: page.description,\n draft: page.frontmatter.draft === true,\n unlisted: Boolean(context.options.publishState?.enabled) && !listedPaths.has(page.inputPath),\n }));\n}\n","/**\n * Dev server middleware for ox-content SSG.\n *\n * Serves fully-rendered HTML pages (with navigation, theme, etc.)\n * during `vite dev`, matching the SSG build output.\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport type { Connect } from \"vite\";\nimport { transformMarkdown } from \"./transform\";\nimport { transformAllPlugins } from \"./plugins\";\nimport { resetTabGroupCounter } from \"./plugins\";\nimport { protectMermaidSvgs, restoreMermaidSvgs } from \"./plugins/mermaid-protect\";\nimport { transformIslands, hasIslands, resetIslandCounter } from \"./island\";\nimport {\n collectMarkdownFiles,\n buildNavItems,\n buildThemeNavItems,\n extractTitle,\n getUrlPath,\n getHref,\n generateHtmlPage,\n getPageLocale,\n formatTitle,\n parseSsgPagerOverride,\n resolveNavigationGroups,\n} from \"./ssg\";\nimport type { NavGroup, SsgPageData, SsgEntryPageConfig } from \"./ssg\";\nimport type { ResolvedOptions } from \"./types\";\nimport type { HeroConfig, FeatureConfig } from \"./types\";\nimport { normalizeVitePressFrontmatter } from \"./vitepress\";\nimport { parsePageChromeFlags } from \"./header-chrome\";\nimport { buildLocalePaths } from \"./locale-switcher\";\nimport { localizeHeaderNavItems, localizeNavGroups } from \"./locale-nav\";\nimport { isMarkdownFilePath } from \"./markdown\";\n\n/** File extensions to skip in the middleware. */\nconst SKIP_EXTENSIONS = new Set([\n \".js\",\n \".ts\",\n \".css\",\n \".scss\",\n \".less\",\n \".svg\",\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".gif\",\n \".webp\",\n \".ico\",\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".eot\",\n \".json\",\n \".map\",\n \".mp4\",\n \".webm\",\n \".mp3\",\n \".pdf\",\n]);\n\n/** Vite internal URL prefixes to skip. */\nconst VITE_INTERNAL_PREFIXES = [\"/@vite/\", \"/@fs/\", \"/@id/\", \"/__\"];\n\n/**\n * Check if a request URL should be skipped by the dev server middleware.\n */\nfunction shouldSkip(url: string): boolean {\n // Skip Vite internal URLs\n for (const prefix of VITE_INTERNAL_PREFIXES) {\n if (url.startsWith(prefix)) return true;\n }\n\n // Skip node_modules\n if (url.includes(\"/node_modules/\")) return true;\n\n // Skip requests with known static file extensions\n const extMatch = url.match(/\\.([a-zA-Z0-9]+)(?:\\?|$)/);\n if (extMatch) {\n const ext = \".\" + extMatch[1].toLowerCase();\n if (SKIP_EXTENSIONS.has(ext)) return true;\n }\n\n return false;\n}\n\n/**\n * Resolve a request URL to a markdown file path.\n * Returns null if no matching file exists.\n */\nasync function resolveMarkdownFile(\n url: string,\n srcDir: string,\n extensions: readonly string[],\n): Promise<string | null> {\n // Remove query string and hash\n let pathname = url.split(\"?\")[0].split(\"#\")[0];\n\n // Remove trailing /index.html\n if (pathname.endsWith(\"/index.html\")) {\n pathname = pathname.slice(0, -\"/index.html\".length) || \"/\";\n }\n\n // Remove trailing slash (except for root)\n if (pathname !== \"/\" && pathname.endsWith(\"/\")) {\n pathname = pathname.slice(0, -1);\n }\n\n const routePath = pathname === \"/\" ? \"\" : pathname.slice(1);\n const directCandidates =\n pathname === \"/\"\n ? extensions.map((extension) => `index${extension}`)\n : isMarkdownFilePath(routePath, extensions)\n ? [routePath]\n : extensions.map((extension) => `${routePath}${extension}`);\n\n for (const relativePath of directCandidates) {\n const filePath = path.join(srcDir, relativePath);\n try {\n await fs.access(filePath);\n return filePath;\n } catch {\n // Try the next extension.\n }\n }\n\n for (const extension of extensions) {\n const indexPath = path.join(srcDir, routePath, `index${extension}`);\n try {\n await fs.access(indexPath);\n return indexPath;\n } catch {\n // Try the next extension.\n }\n }\n\n return null;\n}\n\n/**\n * Inject Vite HMR client script into the HTML.\n */\nfunction injectViteHmrClient(html: string): string {\n const hmrScript = `<script type=\"module\" src=\"/@vite/client\"></script>\n<script type=\"module\">\nif (import.meta.hot) {\n const reexecuteBodyScripts = () => {\n const scripts = Array.from(document.body.querySelectorAll('script'));\n for (const script of scripts) {\n const nextScript = document.createElement('script');\n for (const attr of script.attributes) {\n nextScript.setAttribute(attr.name, attr.value);\n }\n nextScript.textContent = script.textContent;\n script.replaceWith(nextScript);\n }\n };\n\n const applyHotUpdate = async () => {\n const nextUrl = new URL(window.location.href);\n nextUrl.searchParams.set('__ox_hmr', String(Date.now()));\n\n const scrollX = window.scrollX;\n const scrollY = window.scrollY;\n const theme = document.documentElement.getAttribute('data-theme');\n\n const response = await fetch(nextUrl.toString(), {\n cache: 'no-store',\n headers: {\n 'x-ox-content-hmr': '1',\n },\n });\n\n if (!response.ok) {\n throw new Error('Failed to fetch updated page');\n }\n\n const nextHtml = await response.text();\n const nextDocument = new DOMParser().parseFromString(nextHtml, 'text/html');\n\n if (!nextDocument.body) {\n throw new Error('Updated page is missing a body');\n }\n\n document.title = nextDocument.title;\n document.body.innerHTML = nextDocument.body.innerHTML;\n reexecuteBodyScripts();\n\n if (theme) {\n document.documentElement.setAttribute('data-theme', theme);\n }\n\n window.scrollTo({ left: scrollX, top: scrollY });\n };\n\n let pendingUpdate = Promise.resolve();\n\n import.meta.hot.on('ox-content:update', () => {\n pendingUpdate = pendingUpdate\n .then(() => applyHotUpdate())\n .catch((error) => {\n console.warn('[ox-content] HMR patch failed, falling back to reload.', error);\n location.reload();\n });\n });\n}\n</script>`;\n\n return html.replace(\"</head>\", hmrScript + \"\\n</head>\");\n}\n\n/**\n * Dev server state for caching.\n */\ninterface DevServerCache {\n /** Cached navigation groups. Invalidated on file add/unlink. */\n navGroups: NavGroup[] | null;\n /** Cached urlPath → href pairs for locale sibling lookup. */\n localePages: Array<{ path: string; href: string }> | null;\n /** Cached rendered HTML keyed by absolute file path. */\n pages: Map<string, string>;\n /** Cached site name. Computed once. */\n siteName: string | null;\n}\n\n/**\n * Create a dev server cache instance.\n */\nexport function createDevServerCache(): DevServerCache {\n return {\n navGroups: null,\n localePages: null,\n pages: new Map(),\n siteName: null,\n };\n}\n\n/**\n * Invalidate navigation cache (called on file add/unlink).\n */\nexport function invalidateNavCache(cache: DevServerCache): void {\n cache.navGroups = null;\n cache.localePages = null;\n // Also clear all page caches since navigation HTML is embedded in pages\n cache.pages.clear();\n}\n\n/**\n * Invalidate page cache for a specific file (called on file change).\n */\nexport function invalidatePageCache(cache: DevServerCache, filePath: string): void {\n cache.pages.delete(filePath);\n}\n\n/**\n * Resolve site name from options or package.json.\n */\nasync function resolveSiteName(options: ResolvedOptions, root: string): Promise<string> {\n if (options.ssg.siteName) {\n return options.ssg.siteName;\n }\n\n try {\n const pkgPath = path.join(root, \"package.json\");\n const pkg = JSON.parse(await fs.readFile(pkgPath, \"utf-8\"));\n if (pkg.name) {\n return formatTitle(pkg.name);\n }\n } catch {\n // Use default\n }\n\n return \"Documentation\";\n}\n\n/**\n * Render a single markdown page to full HTML.\n */\nasync function renderPage(\n filePath: string,\n options: ResolvedOptions,\n navGroups: NavGroup[],\n siteName: string,\n base: string,\n root: string,\n localePages: Array<{ path: string; href: string }>,\n): Promise<string> {\n const srcDir = path.resolve(root, options.srcDir);\n\n // Reset counters for clean render\n resetTabGroupCounter();\n resetIslandCounter();\n\n // Read markdown content\n const content = await fs.readFile(filePath, \"utf-8\");\n\n // Transform markdown to HTML\n const result = await transformMarkdown(content, filePath, options, {\n convertMdLinks: true,\n baseUrl: base,\n sourcePath: filePath,\n });\n const frontmatter = normalizeVitePressFrontmatter(result.frontmatter);\n\n let transformedHtml = result.html;\n\n // Protect mermaid SVGs from rehype processing\n const { html: protectedHtml, svgs: mermaidSvgs } = protectMermaidSvgs(transformedHtml);\n transformedHtml = protectedHtml;\n\n // Transform all plugins\n transformedHtml = await transformAllPlugins(transformedHtml, {\n tabs: true,\n youtube: true,\n github: options.embeds.github,\n openGraph: options.embeds.openGraph,\n pm: options.embeds.pm,\n spotify: options.embeds.spotify,\n stackBlitz: options.embeds.stackBlitz,\n twitter: options.embeds.twitter,\n bluesky: options.embeds.bluesky,\n webContainer: options.embeds.webContainer,\n mermaid: true,\n githubToken: process.env.GITHUB_TOKEN,\n });\n\n // Transform Island components\n if (hasIslands(transformedHtml)) {\n const islandResult = await transformIslands(transformedHtml);\n transformedHtml = islandResult.html;\n }\n\n // Restore protected mermaid SVGs\n transformedHtml = restoreMermaidSvgs(transformedHtml, mermaidSvgs);\n\n // Extract title\n const title = extractTitle(transformedHtml, frontmatter);\n const description = frontmatter.description as string | undefined;\n\n // Check if this is an entry page\n let entryPage: SsgEntryPageConfig | undefined;\n if (frontmatter.layout === \"entry\") {\n entryPage = {\n hero: frontmatter.hero as HeroConfig | undefined,\n features: frontmatter.features as FeatureConfig[] | undefined,\n };\n }\n\n // Build page data\n const pageData: SsgPageData = {\n title,\n description,\n content: transformedHtml,\n toc: result.toc,\n frontmatter,\n path: getUrlPath(filePath, srcDir),\n href: getUrlPath(filePath, srcDir) || \"/\",\n entryPage,\n prev: parseSsgPagerOverride(frontmatter.prev),\n next: parseSsgPagerOverride(frontmatter.next),\n breadcrumbs: frontmatter.breadcrumbs === false ? false : undefined,\n chrome: parsePageChromeFlags(frontmatter),\n };\n\n const i18n = options.i18n;\n const locale = getPageLocale(pageData.path, i18n);\n const localeNav =\n i18n && locale\n ? {\n locale,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages: localePages,\n base,\n }\n : undefined;\n const localizedNav = localeNav ? localizeNavGroups(navGroups, localeNav) : navGroups;\n const theme = options.ssg.theme\n ? localeNav\n ? {\n ...options.ssg.theme,\n nav: localizeHeaderNavItems(options.ssg.theme.nav, localeNav),\n }\n : options.ssg.theme\n : undefined;\n const localePaths =\n options.ssg.localeSwitcher && i18n\n ? buildLocalePaths({\n currentPath: pageData.path,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages: localePages,\n base,\n })\n : undefined;\n\n // Generate full HTML page\n let html = await generateHtmlPage(\n pageData,\n localizedNav,\n siteName,\n base,\n options.ssg.ogImage,\n theme,\n locale,\n i18n ? i18n.locales : undefined,\n options.ssg.pagination,\n options.ssg.readerChrome,\n options.ssg.breadcrumbs,\n options.ssg.localeSwitcher,\n localePaths,\n options.ssg.a11y,\n options.ssg.team ?? { enabled: false, members: [] },\n options.ssg.pageChrome,\n );\n\n // Inject Vite HMR client for live reload\n html = injectViteHmrClient(html);\n\n return html;\n}\n\n/**\n * Create the dev server middleware for SSG page serving.\n */\nexport function createDevServerMiddleware(\n options: ResolvedOptions,\n root: string,\n cache: DevServerCache,\n): Connect.NextHandleFunction {\n const srcDir = path.resolve(root, options.srcDir);\n const base = options.base.endsWith(\"/\") ? options.base : options.base + \"/\";\n\n return async (req, res, next) => {\n const url = req.url;\n if (!url) return next();\n\n // Strip base from URL for routing\n let routeUrl = url;\n if (base !== \"/\" && routeUrl.startsWith(base)) {\n routeUrl = \"/\" + routeUrl.slice(base.length);\n }\n\n // Skip non-page requests\n if (shouldSkip(routeUrl)) return next();\n\n // Resolve markdown file\n const filePath = await resolveMarkdownFile(routeUrl, srcDir, options.extensions);\n if (!filePath) return next();\n\n try {\n // Check page cache\n const cached = cache.pages.get(filePath);\n if (cached) {\n res.setHeader(\"Content-Type\", \"text/html\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.end(cached);\n return;\n }\n\n // Resolve site name (cached after first call)\n if (!cache.siteName) {\n cache.siteName = await resolveSiteName(options, root);\n }\n\n // Build navigation if not cached\n if (!cache.navGroups || !cache.localePages) {\n const markdownFiles = await collectMarkdownFiles(srcDir, options.extensions);\n cache.localePages = markdownFiles.map((file) => ({\n path: getUrlPath(file, srcDir),\n href: getHref(file, srcDir, base, options.ssg.extension),\n }));\n cache.navGroups =\n resolveNavigationGroups(options.ssg.navigation, base, options.ssg.extension) ??\n (options.ssg.theme?.sidebar.length\n ? buildThemeNavItems(options.ssg.theme.sidebar, base, options.ssg.extension)\n : buildNavItems(markdownFiles, srcDir, base, options.ssg.extension));\n }\n\n const navGroups = cache.navGroups;\n const localePages = cache.localePages;\n if (!navGroups || !localePages) {\n return next();\n }\n\n // Render the page\n const html = await renderPage(\n filePath,\n options,\n navGroups,\n cache.siteName,\n base,\n root,\n localePages,\n );\n\n // Cache the result\n cache.pages.set(filePath, html);\n\n res.setHeader(\"Content-Type\", \"text/html\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.end(html);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.error(`[ox-content:dev] Failed to render ${filePath}:`, message);\n next();\n }\n };\n}\n","/**\n * OG Viewer - Dev tool for previewing Open Graph metadata\n *\n * Accessible at /__og-viewer during development.\n * Shows all pages with their OG metadata, validation warnings,\n * and social card previews.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { glob } from \"glob\";\nimport type { Plugin } from \"vite\";\nimport type { ResolvedOptions } from \"./types\";\nimport { normalizeVitePressFrontmatter } from \"./vitepress\";\nimport { markdownGlobPattern, stripMarkdownExtension } from \"./markdown\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\ninterface PageOgData {\n path: string;\n urlPath: string;\n title: string;\n description: string;\n author: string;\n tags: string[];\n ogImageUrl: string;\n warnings: { level: \"error\" | \"warning\"; message: string }[];\n}\n\n// =============================================================================\n// Data Collection\n// =============================================================================\n\nfunction parseFrontmatter(content: string): Record<string, unknown> {\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (!match) return {};\n\n const yaml = match[1];\n const result: Record<string, unknown> = {};\n\n for (const line of yaml.split(\"\\n\")) {\n const kv = line.match(/^(\\w[\\w-]*):\\s*(.*)$/);\n if (!kv) continue;\n const [, key, rawValue] = kv;\n let value: unknown = rawValue.trim();\n\n // Handle arrays (simple inline: [a, b])\n if (typeof value === \"string\" && value.startsWith(\"[\") && value.endsWith(\"]\")) {\n value = value\n .slice(1, -1)\n .split(\",\")\n .map((s) => s.trim().replace(/^['\"]|['\"]$/g, \"\"))\n .filter(Boolean);\n }\n // Strip quotes\n else if (typeof value === \"string\" && /^['\"].*['\"]$/.test(value)) {\n value = value.slice(1, -1);\n }\n // Booleans\n else if (value === \"true\") value = true;\n else if (value === \"false\") value = false;\n\n result[key] = value;\n }\n\n return result;\n}\n\nfunction extractTitle(content: string, frontmatter: Record<string, unknown>): string {\n if (typeof frontmatter.title === \"string\" && frontmatter.title) {\n return frontmatter.title;\n }\n // Fallback: first # heading\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1].trim() : \"\";\n}\n\nfunction getUrlPath(filePath: string, srcDir: string, extensions: readonly string[]): string {\n let rel = path.relative(srcDir, filePath).replace(/\\\\/g, \"/\");\n rel = stripMarkdownExtension(rel, extensions);\n if (rel === \"index\") return \"/\";\n if (rel.endsWith(\"/index\")) rel = rel.slice(0, -\"/index\".length);\n return \"/\" + rel;\n}\n\nfunction computeOgImageUrl(\n urlPath: string,\n base: string,\n siteUrl?: string,\n generateOgImage?: boolean,\n staticOgImage?: string,\n): string {\n if (!generateOgImage) return staticOgImage || \"\";\n\n const cleanBase = base.endsWith(\"/\") ? base : base + \"/\";\n let relativePath: string;\n if (urlPath === \"/\") {\n relativePath = `${cleanBase}og-image.png`;\n } else {\n relativePath = `${cleanBase}${urlPath.replace(/^\\//, \"\")}/og-image.png`;\n }\n\n if (siteUrl) {\n const cleanSiteUrl = siteUrl.replace(/\\/$/, \"\");\n return `${cleanSiteUrl}${relativePath}`;\n }\n return relativePath;\n}\n\nfunction validatePage(\n page: { title: string; description: string; ogImageUrl: string },\n options: ResolvedOptions,\n): { level: \"error\" | \"warning\"; message: string }[] {\n const warnings: { level: \"error\" | \"warning\"; message: string }[] = [];\n\n if (!page.title) {\n warnings.push({ level: \"error\", message: \"title is missing\" });\n } else if (page.title.length > 70) {\n warnings.push({ level: \"warning\", message: `title is too long (${page.title.length}/70)` });\n }\n\n if (!page.description) {\n warnings.push({ level: \"warning\", message: \"description is missing\" });\n } else if (page.description.length > 200) {\n warnings.push({\n level: \"warning\",\n message: `description is too long (${page.description.length}/200)`,\n });\n }\n\n const generateOgImage = options.ogImage || options.ssg.generateOgImage;\n if (generateOgImage && !options.ssg.siteUrl) {\n warnings.push({ level: \"warning\", message: \"ogImage enabled but siteUrl is not set\" });\n }\n\n return warnings;\n}\n\nasync function collectPages(options: ResolvedOptions, root: string): Promise<PageOgData[]> {\n const srcDir = path.resolve(root, options.srcDir);\n const files = await glob(markdownGlobPattern(srcDir, options.extensions), { absolute: true });\n\n const pages: PageOgData[] = [];\n const generateOgImage = options.ogImage || options.ssg.generateOgImage;\n\n for (const file of files.sort()) {\n const content = fs.readFileSync(file, \"utf-8\");\n const frontmatter = normalizeVitePressFrontmatter(parseFrontmatter(content));\n\n // Skip entry layout pages (they are landing pages, not content pages)\n if (frontmatter.layout === \"entry\") continue;\n\n const title = extractTitle(content, frontmatter);\n const description = typeof frontmatter.description === \"string\" ? frontmatter.description : \"\";\n const author = typeof frontmatter.author === \"string\" ? frontmatter.author : \"\";\n const tags = Array.isArray(frontmatter.tags)\n ? (frontmatter.tags as string[])\n : typeof frontmatter.tags === \"string\"\n ? [frontmatter.tags]\n : [];\n\n const urlPath = getUrlPath(file, srcDir, options.extensions);\n const ogImageUrl = computeOgImageUrl(\n urlPath,\n options.base,\n options.ssg.siteUrl,\n generateOgImage,\n options.ssg.ogImage,\n );\n\n const page = {\n path: path.relative(srcDir, file),\n urlPath,\n title,\n description,\n author,\n tags,\n ogImageUrl,\n warnings: [] as PageOgData[\"warnings\"],\n };\n page.warnings = validatePage(page, options);\n pages.push(page);\n }\n\n return pages;\n}\n\n// =============================================================================\n// HTML Rendering\n// =============================================================================\n\nfunction renderViewerHtml(pages: PageOgData[], options: ResolvedOptions): string {\n const generateOgImage = options.ogImage || options.ssg.generateOgImage;\n const totalWarnings = pages.reduce(\n (sum, p) => sum + p.warnings.filter((w) => w.level === \"warning\").length,\n 0,\n );\n const totalErrors = pages.reduce(\n (sum, p) => sum + p.warnings.filter((w) => w.level === \"error\").length,\n 0,\n );\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>OG Viewer - ox-content</title>\n <style>\n :root {\n --bg: #ffffff;\n --bg-card: #f5f7fb;\n --bg-preview: #ffffff;\n --text: #131a30;\n --text-muted: #4f607b;\n --border: #d2dbea;\n --accent: #4f6fae;\n --accent-light: #eef2fa;\n --error: #dc2626;\n --error-bg: #fef2f2;\n --warning: #d97706;\n --warning-bg: #fffbeb;\n --success: #16a34a;\n --tag-bg: #ecf3ff;\n --radius: 16px;\n }\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: #060816;\n --bg-card: #0d1528;\n --bg-preview: #10172d;\n --text: #ebf2ff;\n --text-muted: #8ea0bf;\n --border: #223252;\n --accent: #86a4da;\n --accent-light: #151730;\n --error: #f87171;\n --error-bg: #450a0a;\n --warning: #fbbf24;\n --warning-bg: #451a03;\n --success: #4ade80;\n --tag-bg: #131b33;\n }\n }\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { font-family: 'IBM Plex Sans', 'Avenir Next', 'Segoe UI', system-ui, sans-serif; background: radial-gradient(circle at top left, rgba(79,111,174,0.10), transparent 24%), radial-gradient(circle at 85% 14%, rgba(145,237,233,0.08), transparent 22%), var(--bg); color: var(--text); }\n .header { padding: 16px 24px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; }\n .header svg { width: 28px; height: 28px; color: var(--accent); }\n .header h1 { font-size: 18px; font-weight: 600; }\n .header h1 span { color: var(--text-muted); font-weight: 400; }\n .header-actions { margin-left: auto; }\n .btn { padding: 6px 14px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); color: var(--text); cursor: pointer; font-size: 13px; transition: all 0.15s; }\n .btn:hover { border-color: var(--accent); color: var(--accent); }\n .summary { padding: 12px 24px; display: flex; gap: 20px; border-bottom: 1px solid var(--border); font-size: 13px; color: var(--text-muted); flex-wrap: wrap; align-items: center; }\n .summary-item { display: flex; align-items: center; gap: 4px; }\n .summary-item strong { color: var(--text); }\n .summary-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }\n .dot-error { background: var(--error); }\n .dot-warning { background: var(--warning); }\n .dot-success { background: var(--success); }\n .toolbar { padding: 12px 24px; display: flex; gap: 8px; border-bottom: 1px solid var(--border); flex-wrap: wrap; align-items: center; }\n .filter-btn { padding: 4px 12px; border: 1px solid var(--border); border-radius: 16px; background: transparent; color: var(--text-muted); cursor: pointer; font-size: 12px; transition: all 0.15s; }\n .filter-btn.active { background: var(--accent); color: #fff; border-color: var(--accent); }\n .search-input { padding: 6px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font-size: 13px; flex: 1; min-width: 200px; }\n .search-input::placeholder { color: var(--text-muted); }\n .container { padding: 24px; display: flex; flex-direction: column; gap: 20px; max-width: 1200px; margin: 0 auto; }\n .card { border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg-card); overflow: hidden; }\n .card-header { padding: 16px; border-bottom: 1px solid var(--border); }\n .card-path { font-size: 12px; color: var(--text-muted); font-family: monospace; margin-bottom: 4px; }\n .card-title { font-size: 16px; font-weight: 600; }\n .card-desc { font-size: 13px; color: var(--text-muted); margin-top: 4px; }\n .card-meta { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; align-items: center; }\n .tag { padding: 2px 8px; background: var(--tag-bg); border-radius: 4px; font-size: 11px; color: var(--text-muted); }\n .card-warnings { padding: 8px 16px; display: flex; flex-direction: column; gap: 4px; }\n .warning-item { font-size: 12px; padding: 4px 8px; border-radius: 4px; }\n .warning-item.error { background: var(--error-bg); color: var(--error); }\n .warning-item.warning { background: var(--warning-bg); color: var(--warning); }\n .card-previews { padding: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }\n @media (max-width: 768px) { .card-previews { grid-template-columns: 1fr; } }\n .preview { border: 1px solid var(--border); border-radius: 6px; overflow: hidden; }\n .preview-label { padding: 6px 10px; font-size: 11px; font-weight: 600; color: var(--text-muted); background: var(--bg); border-bottom: 1px solid var(--border); text-transform: uppercase; letter-spacing: 0.5px; }\n .preview-card { background: var(--bg-preview); }\n .preview-img { width: 100%; aspect-ratio: 1200/630; background: linear-gradient(135deg, var(--accent-light), var(--bg-card)); display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 12px; overflow: hidden; }\n .preview-img img { width: 100%; height: 100%; object-fit: cover; }\n .preview-body { padding: 10px 12px; }\n .preview-url { font-size: 11px; color: var(--text-muted); margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .preview-title { font-size: 14px; font-weight: 600; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }\n .preview-desc { font-size: 12px; color: var(--text-muted); margin-top: 2px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }\n .empty { text-align: center; padding: 60px; color: var(--text-muted); }\n .spin { animation: spin 0.6s linear infinite; }\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n</head>\n<body>\n <div class=\"header\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"/></svg>\n <h1>OG Viewer <span>/ ox-content</span></h1>\n <div class=\"header-actions\">\n <button class=\"btn\" id=\"refresh-btn\" onclick=\"refresh()\">Refresh</button>\n </div>\n </div>\n <div class=\"summary\" id=\"summary\">\n <div class=\"summary-item\"><strong id=\"s-pages\">${pages.length}</strong>&nbsp;pages</div>\n <div class=\"summary-item\"><span class=\"summary-dot dot-error\"></span>&nbsp;<strong id=\"s-errors\">${totalErrors}</strong>&nbsp;errors</div>\n <div class=\"summary-item\"><span class=\"summary-dot dot-warning\"></span>&nbsp;<strong id=\"s-warnings\">${totalWarnings}</strong>&nbsp;warnings</div>\n <div class=\"summary-item\"><span class=\"summary-dot ${generateOgImage ? \"dot-success\" : \"dot-warning\"}\"></span>&nbsp;ogImage: <strong>${generateOgImage ? \"enabled\" : \"disabled\"}</strong></div>\n </div>\n <div class=\"toolbar\">\n <button class=\"filter-btn active\" data-filter=\"all\" onclick=\"setFilter('all')\">All</button>\n <button class=\"filter-btn\" data-filter=\"warnings\" onclick=\"setFilter('warnings')\">Warnings</button>\n <button class=\"filter-btn\" data-filter=\"errors\" onclick=\"setFilter('errors')\">Errors</button>\n <input class=\"search-input\" type=\"text\" placeholder=\"Search pages...\" oninput=\"applyFilters()\" id=\"search-input\">\n </div>\n <div class=\"container\" id=\"container\"></div>\n\n <script>\n let pages = ${JSON.stringify(pages)};\n let currentFilter = 'all';\n\n function setFilter(f) {\n currentFilter = f;\n document.querySelectorAll('.filter-btn').forEach(b => b.classList.toggle('active', b.dataset.filter === f));\n applyFilters();\n }\n\n function applyFilters() {\n const q = document.getElementById('search-input').value.toLowerCase();\n const filtered = pages.filter(p => {\n if (currentFilter === 'errors' && !p.warnings.some(w => w.level === 'error')) return false;\n if (currentFilter === 'warnings' && !p.warnings.length) return false;\n if (q && !p.path.toLowerCase().includes(q) && !p.title.toLowerCase().includes(q) && !p.description.toLowerCase().includes(q)) return false;\n return true;\n });\n renderCards(filtered);\n }\n\n function esc(s) {\n const d = document.createElement('div');\n d.textContent = s;\n return d.innerHTML;\n }\n\n function renderCards(list) {\n const c = document.getElementById('container');\n if (!list.length) {\n c.innerHTML = '<div class=\"empty\">No pages match the current filter.</div>';\n return;\n }\n c.innerHTML = list.map(p => {\n const warnings = p.warnings.map(w =>\n '<div class=\"warning-item ' + w.level + '\">' + (w.level === 'error' ? '\\\\u2716' : '\\\\u26A0') + ' ' + esc(w.message) + '</div>'\n ).join('');\n const tags = p.tags.map(t => '<span class=\"tag\">' + esc(t) + '</span>').join('');\n const author = p.author ? '<span class=\"tag\">by ' + esc(p.author) + '</span>' : '';\n const imgHtml = p.ogImageUrl\n ? '<img src=\"' + esc(p.ogImageUrl) + '\" onerror=\"this.parentNode.innerHTML=\\\\'No OG image\\\\'\">'\n : 'No OG image';\n const siteHost = ${JSON.stringify(options.ssg.siteUrl || \"example.com\")};\n return '<div class=\"card\">'\n + '<div class=\"card-header\">'\n + '<div class=\"card-path\">' + esc(p.path) + ' &rarr; ' + esc(p.urlPath) + '</div>'\n + '<div class=\"card-title\">' + (esc(p.title) || '<em style=\"color:var(--error)\">No title</em>') + '</div>'\n + (p.description ? '<div class=\"card-desc\">' + esc(p.description) + '</div>' : '')\n + (tags || author ? '<div class=\"card-meta\">' + author + tags + '</div>' : '')\n + '</div>'\n + (warnings ? '<div class=\"card-warnings\">' + warnings + '</div>' : '')\n + '<div class=\"card-previews\">'\n + '<div class=\"preview\"><div class=\"preview-label\">Twitter (summary_large_image)</div><div class=\"preview-card\"><div class=\"preview-img\">' + imgHtml + '</div><div class=\"preview-body\"><div class=\"preview-url\">' + esc(siteHost) + '</div><div class=\"preview-title\">' + esc(p.title) + '</div><div class=\"preview-desc\">' + esc(p.description) + '</div></div></div></div>'\n + '<div class=\"preview\"><div class=\"preview-label\">Facebook (Open Graph)</div><div class=\"preview-card\"><div class=\"preview-img\">' + imgHtml + '</div><div class=\"preview-body\"><div class=\"preview-url\">' + esc(siteHost) + '</div><div class=\"preview-title\">' + esc(p.title) + '</div><div class=\"preview-desc\">' + esc(p.description) + '</div></div></div></div>'\n + '</div>'\n + '</div>';\n }).join('');\n }\n\n async function refresh() {\n const btn = document.getElementById('refresh-btn');\n btn.textContent = 'Refreshing...';\n btn.disabled = true;\n try {\n const res = await fetch('/__og-viewer/api/pages');\n pages = await res.json();\n updateSummary();\n applyFilters();\n } catch(e) {\n console.error('Refresh failed:', e);\n } finally {\n btn.textContent = 'Refresh';\n btn.disabled = false;\n }\n }\n\n function updateSummary() {\n document.getElementById('s-pages').textContent = pages.length;\n document.getElementById('s-errors').textContent = pages.reduce((s,p) => s + p.warnings.filter(w => w.level === 'error').length, 0);\n document.getElementById('s-warnings').textContent = pages.reduce((s,p) => s + p.warnings.filter(w => w.level === 'warning').length, 0);\n }\n\n renderCards(pages);\n </script>\n</body>\n</html>`;\n}\n\n// =============================================================================\n// Plugin\n// =============================================================================\n\nexport function createOgViewerPlugin(options: ResolvedOptions): Plugin {\n return {\n name: \"ox-content:og-viewer\",\n apply: \"serve\",\n\n configureServer(server) {\n server.middlewares.use(async (req, res, next) => {\n if (req.url === \"/__og-viewer\" || req.url === \"/__og-viewer/\") {\n const root = server.config.root || process.cwd();\n try {\n const pages = await collectPages(options, root);\n const html = renderViewerHtml(pages, options);\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(html);\n } catch (err) {\n res.statusCode = 500;\n res.end(`OG Viewer error: ${err instanceof Error ? err.message : String(err)}`);\n }\n return;\n }\n\n if (req.url === \"/__og-viewer/api/pages\") {\n const root = server.config.root || process.cwd();\n try {\n const pages = await collectPages(options, root);\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(pages));\n } catch (err) {\n res.statusCode = 500;\n res.end(JSON.stringify({ error: String(err) }));\n }\n return;\n }\n\n next();\n });\n },\n };\n}\n","/**\n * i18n plugin for Ox Content.\n *\n * Provides:\n * - Dictionary loading and validation at build time\n * - Virtual module for i18n config\n * - Build-time i18n checking\n * - Locale-aware routing middleware for dev server\n */\n\nimport * as path from \"path\";\nimport * as fs from \"fs\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { importNapiModule } from \"./napi\";\nimport type { I18nOptions, ResolvedI18nOptions, LocaleConfig, ResolvedOptions } from \"./types\";\n\n/**\n * Resolves i18n options with defaults.\n */\nexport function resolveI18nOptions(\n options: I18nOptions | false | undefined,\n): ResolvedI18nOptions | false {\n if (options === false) return false;\n if (!options || !options.enabled) {\n return false;\n }\n\n const defaultLocale = options.defaultLocale ?? \"en\";\n const locales: LocaleConfig[] = options.locales ?? [{ code: defaultLocale, name: defaultLocale }];\n\n // Ensure default locale is in the locales list\n if (!locales.some((l) => l.code === defaultLocale)) {\n locales.unshift({ code: defaultLocale, name: defaultLocale });\n }\n\n return {\n enabled: true,\n dir: options.dir ?? \"content/i18n\",\n defaultLocale,\n locales,\n hideDefaultLocale: options.hideDefaultLocale ?? true,\n check: options.check ?? true,\n functionNames: options.functionNames ?? [\"t\", \"$t\"],\n };\n}\n\n/**\n * Creates the i18n sub-plugin for the Vite plugin array.\n */\nexport function createI18nPlugin(resolvedOptions: ResolvedOptions): Plugin {\n const i18nOptions = resolvedOptions.i18n;\n let root = process.cwd();\n\n return {\n name: \"ox-content:i18n\",\n\n configResolved(config) {\n root = config.root;\n },\n\n resolveId(id) {\n if (id === \"virtual:ox-content/i18n\") {\n return \"\\0virtual:ox-content/i18n\";\n }\n return null;\n },\n\n load(id) {\n if (id === \"\\0virtual:ox-content/i18n\") {\n if (!i18nOptions) {\n return `export const i18n = { enabled: false }; export default i18n;`;\n }\n\n return generateI18nModule(i18nOptions, root);\n }\n return null;\n },\n\n async buildStart() {\n if (!i18nOptions || !i18nOptions.check) return;\n\n const dictDir = path.resolve(root, i18nOptions.dir);\n if (!fs.existsSync(dictDir)) {\n console.warn(`[ox-content:i18n] Dictionary directory not found: ${dictDir}`);\n return;\n }\n\n try {\n const { checkI18nProject } = await importNapiModule();\n const checkResult = checkI18nProject(\n dictDir,\n [path.resolve(root, \"src\"), path.resolve(root, \"content\")],\n i18nOptions.functionNames,\n i18nOptions.defaultLocale,\n );\n if (checkResult.errorCount > 0 || checkResult.warningCount > 0) {\n for (const diag of checkResult.diagnostics) {\n if (diag.severity === \"error\") {\n console.error(`[ox-content:i18n] ${diag.message}`);\n } else if (diag.severity === \"warning\") {\n console.warn(`[ox-content:i18n] ${diag.message}`);\n }\n }\n }\n } catch {\n // NAPI binding not available; skip checks\n }\n },\n\n configureServer(server: ViteDevServer) {\n if (!i18nOptions) return;\n\n // Watch dictionary directory for changes\n const dictDir = path.resolve(root, i18nOptions.dir);\n if (fs.existsSync(dictDir)) {\n server.watcher.add(dictDir);\n\n server.watcher.on(\"change\", (filePath: string) => {\n if (!filePath.startsWith(dictDir)) return;\n if (!/\\.(json|yaml|yml)$/.test(filePath)) return;\n\n // Invalidate the virtual module\n const mod = server.moduleGraph.getModuleById(\"\\0virtual:ox-content/i18n\");\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n // Trigger full reload\n server.ws.send({ type: \"full-reload\" });\n });\n }\n\n // Add locale routing middleware\n server.middlewares.use((req, _res, next) => {\n if (!req.url) return next();\n\n // Parse locale from URL\n const url = req.url;\n const localeMatch = url.match(/^\\/([A-Za-z]{2,3}(?:-[A-Za-z0-9]+)*)(\\/|$)/);\n\n if (localeMatch) {\n const localeCode = localeMatch[1];\n const isKnown = i18nOptions.locales.some((l) => l.code === localeCode);\n if (isKnown) {\n // Set locale header for downstream middleware\n (req as any).__oxLocale = localeCode;\n }\n } else if (i18nOptions.hideDefaultLocale) {\n // No locale prefix: use default locale\n (req as any).__oxLocale = i18nOptions.defaultLocale;\n }\n\n next();\n });\n },\n };\n}\n\n/**\n * Generates the virtual module for i18n configuration.\n */\nexport function generateI18nModule(options: ResolvedI18nOptions, root: string): string {\n const dictDir = path.resolve(root, options.dir);\n const config = {\n defaultLocale: options.defaultLocale,\n locales: options.locales,\n hideDefaultLocale: options.hideDefaultLocale,\n };\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const napi = require(\"@ox-content/napi\") as {\n generateI18nModule?: (dictDir: string, runtimeConfig: typeof config) => string;\n };\n\n if (typeof napi.generateI18nModule === \"function\") {\n return napi.generateI18nModule(dictDir, config);\n }\n } catch (error) {\n throw new Error(\n `[ox-content:i18n] Failed to load @ox-content/napi for i18n module generation: ${String(error)}`,\n );\n }\n\n throw new Error(\n \"[ox-content:i18n] @ox-content/napi does not expose generateI18nModule. Please rebuild the NAPI package.\",\n );\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveImageOptions(\n options: OxContentOptions[\"images\"],\n): ResolvedOptions[\"images\"] {\n if (!options) return { enabled: false, lazy: true };\n if (options === true) return { enabled: true, lazy: true };\n return { enabled: true, lazy: options.lazy ?? true };\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveCardOptions(options: OxContentOptions[\"cards\"]): ResolvedOptions[\"cards\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveFileTreeOptions(\n options: OxContentOptions[\"fileTree\"],\n): ResolvedOptions[\"fileTree\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveIncludeOptions(\n options: OxContentOptions[\"includes\"],\n): ResolvedOptions[\"includes\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: true, rootDir: options.rootDir };\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveStepsOptions(options: OxContentOptions[\"steps\"]): ResolvedOptions[\"steps\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n","import { importNapiModuleSync } from \"./napi\";\n\ntype NapiModule = typeof import(\"@ox-content/napi\");\ntype NativeIncrementalMarkdownParser = InstanceType<NapiModule[\"IncrementalMarkdownParser\"]>;\ntype NativeIncrementalMarkdownRenderer = InstanceType<NapiModule[\"IncrementalMarkdownRenderer\"]>;\ntype NativeParseResult = import(\"@ox-content/napi\").IncrementalMarkdownParseResult;\n\nexport interface IncrementalMarkdownParserOptions {\n /**\n * Enable GitHub Flavored Markdown extensions.\n * @default true\n */\n gfm?: boolean;\n\n /**\n * Enable MDX JSX, ESM, and expression nodes.\n * @default false\n */\n mdx?: boolean;\n\n /**\n * Enable footnotes.\n * @default true\n */\n footnotes?: boolean;\n\n /**\n * Enable task list items.\n * @default true\n */\n taskLists?: boolean;\n\n /**\n * Enable GFM tables.\n * @default true\n */\n tables?: boolean;\n\n /**\n * Enable strikethrough.\n * @default true\n */\n strikethrough?: boolean;\n\n /**\n * Enable Markdown autolinks.\n * @default true\n */\n autolinks?: boolean;\n}\n\nexport interface IncrementalMarkdownParseAppendOptions {\n /**\n * Commit the current chunk as the final stream input.\n * @default false\n */\n final?: boolean;\n\n /**\n * Include a provisional AST for the current replaceable tail.\n * The constructor-level value is reused when omitted on `append`.\n * @default false\n */\n includePendingAst?: boolean;\n\n /**\n * Temporarily close unmatched inline delimiters in the provisional AST.\n * @default true\n */\n completeInline?: boolean;\n}\n\nexport interface IncrementalMarkdownRendererOptions extends IncrementalMarkdownParserOptions {\n /**\n * Render the unstable tail as replaceable provisional HTML.\n * @default true\n */\n renderPending?: boolean;\n\n /**\n * Temporarily close unmatched inline delimiters in provisional HTML.\n * @default true\n */\n completeInline?: boolean;\n}\n\nexport interface IncrementalMarkdownRenderAppendOptions {\n /**\n * Commit the current chunk as the final stream input.\n * @default false\n */\n final?: boolean;\n\n /**\n * Render the unstable tail as replaceable provisional HTML.\n * The constructor-level value is reused when omitted on `append`.\n * @default true\n */\n renderPending?: boolean;\n\n /**\n * Temporarily close unmatched inline delimiters in provisional HTML.\n * @default true\n */\n completeInline?: boolean;\n}\n\nexport type IncrementalMarkdownRenderResult =\n import(\"@ox-content/napi\").IncrementalMarkdownRenderResult;\n\nexport interface IncrementalMarkdownParseResult<TAst = unknown> extends Omit<\n NativeParseResult,\n \"ast\" | \"pendingAst\"\n> {\n /** Parsed mdast for the newly committed Markdown prefix, or null when nothing committed. */\n ast: TAst | null;\n\n /** Raw mdast JSON for the newly committed Markdown prefix. */\n astJson: string;\n\n /** Provisional parsed mdast for the current replaceable tail, or null when not requested. */\n pendingAst: TAst | null;\n\n /** Raw provisional mdast JSON for the current replaceable tail. */\n pendingAstJson: string;\n}\n\nexport type MarkdownChunkSource = Iterable<string> | AsyncIterable<string>;\n\nfunction toNativeParserOptions(options: IncrementalMarkdownParserOptions = {}) {\n return {\n gfm: options.gfm ?? true,\n mdx: options.mdx,\n footnotes: options.footnotes,\n taskLists: options.taskLists,\n tables: options.tables,\n strikethrough: options.strikethrough,\n autolinks: options.autolinks,\n };\n}\n\nfunction parseAstJson<TAst>(json: string): TAst | null {\n return json ? (JSON.parse(json) as TAst) : null;\n}\n\nfunction normalizeParseResult<TAst>(\n result: NativeParseResult,\n): IncrementalMarkdownParseResult<TAst> {\n const { ast, pendingAst, ...rest } = result;\n return {\n ...rest,\n ast: parseAstJson<TAst>(ast),\n astJson: ast,\n pendingAst: parseAstJson<TAst>(pendingAst),\n pendingAstJson: pendingAst,\n };\n}\n\nexport class IncrementalMarkdownParser<TAst = unknown> {\n readonly #native: NativeIncrementalMarkdownParser;\n readonly #includePendingAst: boolean;\n readonly #completeInline: boolean;\n\n constructor(\n options: IncrementalMarkdownParserOptions & IncrementalMarkdownParseAppendOptions = {},\n ) {\n const napi = importNapiModuleSync();\n this.#native = new napi.IncrementalMarkdownParser(toNativeParserOptions(options));\n this.#includePendingAst = options.includePendingAst ?? false;\n this.#completeInline = options.completeInline ?? true;\n }\n\n append(\n chunk: string,\n options: IncrementalMarkdownParseAppendOptions = {},\n ): IncrementalMarkdownParseResult<TAst> {\n return normalizeParseResult<TAst>(\n this.#native.append(chunk, {\n isFinal: options.final ?? false,\n includePendingAst: options.includePendingAst ?? this.#includePendingAst,\n completeInline: options.completeInline ?? this.#completeInline,\n }),\n );\n }\n\n finish(\n options: IncrementalMarkdownParseAppendOptions = {},\n ): IncrementalMarkdownParseResult<TAst> {\n return normalizeParseResult<TAst>(\n this.#native.finish({\n includePendingAst: options.includePendingAst ?? this.#includePendingAst,\n completeInline: options.completeInline ?? this.#completeInline,\n }),\n );\n }\n\n reset(): void {\n this.#native.reset();\n }\n\n get pendingMarkdown(): string {\n return this.#native.pendingMarkdown;\n }\n\n get committedBytes(): number {\n return this.#native.committedBytes;\n }\n\n get totalBytes(): number {\n return this.#native.totalBytes;\n }\n}\n\nexport class IncrementalMarkdownRenderer {\n readonly #native: NativeIncrementalMarkdownRenderer;\n readonly #renderPending: boolean;\n readonly #completeInline: boolean;\n\n constructor(options: IncrementalMarkdownRendererOptions = {}) {\n const napi = importNapiModuleSync();\n this.#native = new napi.IncrementalMarkdownRenderer(toNativeParserOptions(options));\n this.#renderPending = options.renderPending ?? true;\n this.#completeInline = options.completeInline ?? true;\n }\n\n append(\n chunk: string,\n options: IncrementalMarkdownRenderAppendOptions = {},\n ): IncrementalMarkdownRenderResult {\n return this.#native.append(chunk, {\n isFinal: options.final ?? false,\n renderPending: options.renderPending ?? this.#renderPending,\n completeInline: options.completeInline ?? this.#completeInline,\n });\n }\n\n finish(): IncrementalMarkdownRenderResult {\n return this.#native.finish();\n }\n\n reset(): void {\n this.#native.reset();\n }\n\n get committedHtml(): string {\n return this.#native.committedHtml;\n }\n\n get pendingMarkdown(): string {\n return this.#native.pendingMarkdown;\n }\n}\n\nexport function createIncrementalMarkdownParser<TAst = unknown>(\n options?: IncrementalMarkdownParserOptions & IncrementalMarkdownParseAppendOptions,\n): IncrementalMarkdownParser<TAst> {\n return new IncrementalMarkdownParser<TAst>(options);\n}\n\nexport function createIncrementalMarkdownRenderer(\n options?: IncrementalMarkdownRendererOptions,\n): IncrementalMarkdownRenderer {\n return new IncrementalMarkdownRenderer(options);\n}\n\nexport async function* renderMarkdownStream(\n chunks: MarkdownChunkSource,\n options: IncrementalMarkdownRendererOptions = {},\n): AsyncGenerator<IncrementalMarkdownRenderResult> {\n const renderer = createIncrementalMarkdownRenderer(options);\n\n for await (const chunk of chunks) {\n yield renderer.append(chunk);\n }\n\n yield renderer.finish();\n}\n","import { importNapiModuleSync } from \"./napi\";\nimport type { ResolvedOptions, TocEntry } from \"./types\";\n\nexport type FrameworkRenderTarget = \"html\" | \"native\";\nexport type FrameworkCodegenTarget = \"react\" | \"vue\" | \"svelte\";\nexport type FrameworkCodegenMode = \"innerHtml\" | \"expression\" | \"renderFunction\" | \"component\";\n\nexport interface FrameworkMarkdownOptions {\n srcDir: string;\n outDir: string;\n base: string;\n extensions: string[];\n gfm: boolean;\n frontmatter?: boolean;\n toc: boolean;\n tocMaxDepth: number;\n codeAnnotations?: {\n enabled?: boolean;\n metaKey?: string;\n };\n embeds?: {\n github?: ResolvedOptions[\"embeds\"][\"github\"];\n openGraph?: ResolvedOptions[\"embeds\"][\"openGraph\"];\n };\n math?: boolean | { enabled?: boolean };\n}\n\nexport interface FrameworkComponentIsland {\n name: string;\n props: Record<string, unknown>;\n id: string;\n content?: string;\n}\n\nexport interface FrameworkTransformData {\n html: string;\n frontmatter: Record<string, unknown>;\n toc: TocEntry[];\n}\n\nexport function createFrameworkMarkdownOptions(options: FrameworkMarkdownOptions): ResolvedOptions {\n return {\n srcDir: options.srcDir,\n outDir: options.outDir,\n base: options.base,\n extensions: options.extensions,\n ssg: {\n enabled: false,\n extension: \".html\",\n clean: false,\n bare: false,\n generateOgImage: false,\n lastUpdated: false,\n pagination: false,\n breadcrumbs: false,\n readerChrome: false,\n localeSwitcher: false,\n a11y: false,\n pageChrome: false,\n },\n siteMaps: { enabled: false, robots: true, llms: true },\n publishState: { enabled: false, includeDrafts: false },\n permalinks: { enabled: false },\n cascade: { enabled: false },\n redirects: {\n enabled: false,\n map: {},\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n },\n gfm: options.gfm,\n frontmatter: options.frontmatter ?? false,\n toc: options.toc,\n tocMaxDepth: options.tocMaxDepth,\n codeAnnotations: {\n enabled: options.codeAnnotations?.enabled ?? false,\n notation: \"attribute\",\n metaKey: options.codeAnnotations?.metaKey ?? \"annotate\",\n defaultLineNumbers: false,\n },\n footnotes: true,\n tables: true,\n taskLists: true,\n strikethrough: true,\n autolinks: options.gfm,\n highlight: false,\n mermaid: false,\n math: {\n enabled:\n options.math === true ||\n (typeof options.math === \"object\" && options.math.enabled !== false),\n },\n ogImage: false,\n ogImageOptions: {\n vuePlugin: \"vitejs\",\n width: 1200,\n height: 630,\n cache: true,\n concurrency: 1,\n },\n transformers: [],\n docs: false,\n ogViewer: false,\n search: {\n enabled: false,\n limit: 10,\n prefix: true,\n placeholder: \"Search...\",\n hotkey: \"k\",\n },\n collections: { enabled: false, collections: {} },\n embeds: {\n github: options.embeds?.github ?? {},\n openGraph: options.embeds?.openGraph ?? {},\n pm: false,\n spotify: false,\n stackBlitz: false,\n twitter: false,\n bluesky: false,\n webContainer: false,\n },\n i18n: false,\n wikiLinks: { enabled: false, baseUrl: options.base },\n emojiShortcodes: { enabled: false, custom: {} },\n attrs: { enabled: false },\n badges: { enabled: false },\n containers: { enabled: false, types: {} },\n images: { enabled: false, lazy: true },\n codeImports: { enabled: false },\n includes: { enabled: false },\n cards: { enabled: false },\n steps: { enabled: false },\n fileTree: { enabled: false },\n sanitize: { enabled: false },\n editThisPage: { enabled: false, branch: \"main\", label: \"Edit this page\" },\n cjkEmphasis: false,\n codeBlockLint: { enabled: false, requireLanguage: false, trailingSpaces: true, mode: \"warn\" },\n codeBlockTypecheck: {\n enabled: false,\n languages: [\"ts\", \"tsx\"],\n requireMeta: true,\n tsgoCommand: \"tsgo\",\n mode: \"warn\",\n },\n docsTests: {\n enabled: false,\n languages: [\"js\", \"jsx\", \"ts\", \"tsx\"],\n requireMeta: true,\n },\n } as ResolvedOptions;\n}\n\nexport function renderHtmlToReactCreateElement(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"react\", \"expression\", islands);\n}\n\nexport function renderHtmlToVueH(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"vue\", \"expression\", islands);\n}\n\nexport function renderHtmlToFrameworkCode(\n html: string,\n target: FrameworkCodegenTarget,\n mode: FrameworkCodegenMode,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return importNapiModuleSync().renderFrameworkComponentCode(\n html,\n target,\n toNapiIslands(islands),\n mode,\n );\n}\n\nexport function renderHtmlToReactComponent(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"react\", \"component\", islands);\n}\n\nexport function renderHtmlToVueComponent(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"vue\", \"component\", islands);\n}\n\nexport function renderHtmlToSvelteComponent(html: string): string {\n return renderHtmlToFrameworkCode(html, \"svelte\", \"component\");\n}\n\nexport function escapeSvelteMarkup(html: string): string {\n return importNapiModuleSync().escapeSvelteMarkup(html);\n}\n\nfunction toNapiIslands(islands: readonly FrameworkComponentIsland[]) {\n return islands.map((island) => ({\n name: island.name,\n props: island.props,\n id: island.id,\n content: island.content,\n }));\n}\n","import { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { glob } from \"glob\";\nimport { extractDocsTests, type DocsTestOptions, type ExtractedCodeBlock } from \"./code-blocks\";\nimport { extractDocs, resolveDocsOptions } from \"./docs\";\nimport type { DocEntry, DocsOptions, ExtractedDocs, ResolvedDocsOptions } from \"./types\";\n\nexport interface CollectedDocsTest extends ExtractedCodeBlock {\n sourcePath: string;\n relativePath: string;\n index: number;\n}\n\nexport type DocsTestSource = \"markdown\" | \"jsdoc\";\n\nexport interface DocsTestHarnessOptions extends DocsTestOptions {\n /**\n * Source kind to scan for runnable examples.\n * - `markdown` scans Markdown files for fenced code blocks.\n * - `jsdoc` scans JSDoc/TSDoc `@example` blocks through ox-content's docs extractor.\n * @default \"markdown\"\n */\n source?: DocsTestSource;\n\n /**\n * Markdown glob patterns, or source-file include globs when `source` is `jsdoc`.\n */\n include?: string | string[];\n\n /**\n * Glob patterns to skip. For `jsdoc`, this is passed to docs extraction as `exclude`.\n */\n ignore?: string | string[];\n\n /**\n * Working directory used for globs and generated test files.\n * @default process.cwd()\n */\n cwd?: string;\n\n /**\n * Source directories to scan when `source` is `jsdoc`.\n * @default [\"./src\"]\n */\n src?: string | string[];\n\n /**\n * Additional docs extraction options for `jsdoc` source mode.\n */\n docs?: DocsOptions;\n}\n\nexport interface DocsTestFileOptions extends DocsTestHarnessOptions {\n /**\n * Directory for generated Vitest files.\n * @default \".cache/ox-content-docs-tests\"\n */\n generatedDir?: string;\n\n /**\n * Remove the generated directory before writing files.\n * @default true\n */\n clean?: boolean;\n\n /**\n * Optional code prepended to every generated test file.\n */\n setupCode?: string;\n\n /**\n * How each generated file should execute the docs block.\n * - `test` wraps the block in a generated Vitest test, similar to Cargo doctests.\n * - `module` writes the block as-is for snippets that declare their own tests.\n * @default \"test\"\n */\n executionMode?: \"test\" | \"module\";\n\n /**\n * Module used for the generated `test` import.\n * @default \"vitest\"\n */\n testImport?: string;\n\n /**\n * Optional static import specifier rewrites for generated test files.\n */\n importRewrites?: Record<string, string>;\n}\n\nexport interface WrittenDocsTestFile {\n filePath: string;\n sourcePath: string;\n relativePath: string;\n startLine: number;\n endLine: number;\n language: string;\n}\n\nexport interface DocsTestWriteResult {\n cwd: string;\n generatedDir: string;\n blocks: CollectedDocsTest[];\n files: WrittenDocsTestFile[];\n}\n\nexport interface RunDocsTestsOptions extends DocsTestFileOptions {\n /**\n * Vitest-compatible command to run.\n * @default \"vitest\"\n */\n vitestCommand?: string;\n\n /**\n * Arguments passed before generated test file paths.\n * @default [\"run\"]\n */\n vitestArgs?: string[];\n\n /**\n * Environment overrides for the Vitest child process.\n */\n env?: NodeJS.ProcessEnv;\n\n /**\n * Allow a scan that finds no runnable docs tests.\n * @default false\n */\n allowEmpty?: boolean;\n}\n\nexport interface DocsTestRunResult extends DocsTestWriteResult {\n command: string;\n args: string[];\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport class DocsTestRunError extends Error {\n readonly result: DocsTestRunResult;\n\n constructor(result: DocsTestRunResult) {\n const command = [result.command, ...result.args].join(\" \");\n super(`[ox-content] Docs tests failed with exit code ${result.exitCode}: ${command}`);\n this.name = \"DocsTestRunError\";\n this.result = result;\n }\n}\n\nexport async function collectDocsTests(\n options: DocsTestHarnessOptions,\n): Promise<CollectedDocsTest[]> {\n const cwd = path.resolve(options.cwd ?? process.cwd());\n if ((options.source ?? \"markdown\") === \"jsdoc\") {\n return collectJsdocDocsTests(options, cwd);\n }\n\n return collectMarkdownDocsTests(options, cwd);\n}\n\nasync function collectMarkdownDocsTests(\n options: DocsTestHarnessOptions,\n cwd: string,\n): Promise<CollectedDocsTest[]> {\n const include = toArray(options.include);\n const ignore = toArray(options.ignore);\n const files = new Map<string, string>();\n\n if (include.length === 0) {\n throw new Error(\"[ox-content] Docs test include patterns are required for markdown sources.\");\n }\n\n for (const pattern of include) {\n const matches = await glob(pattern, {\n absolute: true,\n cwd,\n ignore,\n nodir: true,\n });\n\n for (const filePath of matches) {\n const absolutePath = path.resolve(filePath);\n files.set(absolutePath, normalizePath(path.relative(cwd, absolutePath)));\n }\n }\n\n const blocks: CollectedDocsTest[] = [];\n let index = 0;\n for (const [sourcePath, relativePath] of [...files.entries()].sort((left, right) =>\n left[0].localeCompare(right[0]),\n )) {\n const source = await fs.readFile(sourcePath, \"utf-8\");\n const extracted = await extractDocsTests(source, {\n languages: options.languages,\n requireMeta: options.requireMeta,\n });\n\n for (const block of extracted) {\n blocks.push({\n ...block,\n sourcePath,\n relativePath,\n index,\n });\n index += 1;\n }\n }\n\n return blocks;\n}\n\nasync function collectJsdocDocsTests(\n options: DocsTestHarnessOptions,\n cwd: string,\n): Promise<CollectedDocsTest[]> {\n const docsOptions = resolveJsdocDocsOptions(options, cwd);\n const docs = await extractDocs(docsOptions.src, docsOptions);\n const blocks: CollectedDocsTest[] = [];\n let index = 0;\n\n for (const doc of sortDocs(docs)) {\n for (const entry of sortEntries(doc.entries)) {\n for (const example of entry.examples ?? []) {\n const extracted = await extractDocsTests(example, {\n languages: options.languages,\n requireMeta: options.requireMeta,\n });\n const sourcePath = resolveEntrySourcePath(entry, doc, cwd);\n const relativePath = relativeSourcePath(cwd, sourcePath);\n\n for (const block of extracted) {\n blocks.push({\n ...block,\n sourcePath,\n relativePath,\n startLine: entry.line,\n endLine: entry.endLine,\n index,\n });\n index += 1;\n }\n }\n }\n }\n\n return blocks;\n}\n\nfunction resolveJsdocDocsOptions(\n options: DocsTestHarnessOptions,\n cwd: string,\n): ResolvedDocsOptions {\n const docsOptions: DocsOptions = {\n ...options.docs,\n };\n\n if (options.src !== undefined) {\n docsOptions.src = toArray(options.src);\n }\n if (options.include !== undefined) {\n docsOptions.include = toArray(options.include);\n }\n if (options.ignore !== undefined) {\n docsOptions.exclude = toArray(options.ignore);\n }\n\n const resolved = resolveDocsOptions(docsOptions);\n return {\n ...resolved,\n src: resolved.src.map((sourceDir) => path.resolve(cwd, sourceDir)),\n entryPoints: resolved.entryPoints?.map((entryPoint) => ({\n ...entryPoint,\n path: path.resolve(cwd, entryPoint.path),\n })),\n };\n}\n\nfunction sortDocs(docs: ExtractedDocs[]): ExtractedDocs[] {\n return [...docs].sort((left, right) => left.file.localeCompare(right.file));\n}\n\nfunction sortEntries(entries: DocEntry[]): DocEntry[] {\n return [...entries].sort((left, right) => {\n const byFile = left.file.localeCompare(right.file);\n if (byFile !== 0) return byFile;\n const byLine = left.line - right.line;\n if (byLine !== 0) return byLine;\n return left.name.localeCompare(right.name);\n });\n}\n\nfunction resolveEntrySourcePath(entry: DocEntry, doc: ExtractedDocs, cwd: string): string {\n const sourcePath = entry.file || doc.file;\n return path.isAbsolute(sourcePath) ? path.resolve(sourcePath) : path.resolve(cwd, sourcePath);\n}\n\nfunction relativeSourcePath(cwd: string, sourcePath: string): string {\n const relativePath = path.relative(cwd, sourcePath);\n if (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n return normalizePath(relativePath);\n }\n return normalizePath(sourcePath);\n}\n\nexport async function writeDocsTestFiles(\n options: DocsTestFileOptions,\n): Promise<DocsTestWriteResult> {\n const cwd = path.resolve(options.cwd ?? process.cwd());\n const generatedDir = path.resolve(cwd, options.generatedDir ?? \".cache/ox-content-docs-tests\");\n const clean = options.clean ?? true;\n const blocks = await collectDocsTests({ ...options, cwd });\n\n if (clean) {\n await fs.rm(generatedDir, { recursive: true, force: true });\n }\n await fs.mkdir(generatedDir, { recursive: true });\n\n const files = await Promise.all(\n blocks.map(async (block) => {\n const filePath = path.join(generatedDir, docsTestFileName(block));\n await fs.writeFile(filePath, renderDocsTestFile(block, options), \"utf-8\");\n return {\n filePath,\n sourcePath: block.sourcePath,\n relativePath: block.relativePath,\n startLine: block.startLine,\n endLine: block.endLine,\n language: block.language,\n };\n }),\n );\n\n return {\n cwd,\n generatedDir,\n blocks,\n files,\n };\n}\n\nexport async function runDocsTests(options: RunDocsTestsOptions): Promise<DocsTestRunResult> {\n const writeResult = await writeDocsTestFiles(options);\n const command = options.vitestCommand ?? \"vitest\";\n const leadingArgs = options.vitestArgs ?? [\"run\"];\n const fileArgs = writeResult.files.map((file) => file.filePath);\n const args = [...leadingArgs, ...fileArgs];\n\n if (fileArgs.length === 0) {\n if (options.allowEmpty) {\n return {\n ...writeResult,\n command,\n args,\n exitCode: 0,\n stdout: \"\",\n stderr: \"\",\n };\n }\n throw new Error(\"[ox-content] No runnable docs test blocks were found.\");\n }\n\n const result = await runCommand(command, args, {\n cwd: writeResult.cwd,\n env: mergeEnv(options.env),\n });\n const runResult = {\n ...writeResult,\n command,\n args,\n ...result,\n };\n\n if (runResult.exitCode !== 0) {\n throw new DocsTestRunError(runResult);\n }\n\n return runResult;\n}\n\nfunction renderDocsTestFile(block: CollectedDocsTest, options: DocsTestFileOptions): string {\n const parts = [\n \"// Generated by @ox-content/vite-plugin docs test harness.\",\n `// Source: ${block.relativePath}:${block.startLine}-${block.endLine}`,\n \"\",\n ];\n const setupCode = options.setupCode?.trimEnd();\n const code = rewriteImports(block.code.trimEnd(), options.importRewrites);\n if (setupCode) {\n parts.push(setupCode, \"\");\n }\n if ((options.executionMode ?? \"test\") === \"module\") {\n parts.push(code, \"\");\n return parts.join(\"\\n\");\n }\n\n const { imports, body } = partitionImports(code);\n parts.push(\n `import { test } from ${JSON.stringify(\n rewriteSpecifier(options.testImport ?? \"vitest\", options.importRewrites),\n )};`,\n );\n if (imports.length > 0) {\n parts.push(...imports);\n }\n parts.push(\n \"\",\n `test(${JSON.stringify(`${block.relativePath}:${block.startLine}`)}, async () => {`,\n );\n if (body.trim().length > 0) {\n parts.push(indentCode(body.trimEnd()));\n }\n parts.push(\"});\", \"\");\n return parts.join(\"\\n\");\n}\n\nfunction partitionImports(source: string): { imports: string[]; body: string } {\n const imports: string[] = [];\n const body: string[] = [];\n const lines = source.split(/\\r?\\n/);\n let currentImport: string[] | undefined;\n\n for (const line of lines) {\n if (currentImport) {\n currentImport.push(line);\n if (endsImportDeclaration(line)) {\n imports.push(currentImport.join(\"\\n\"));\n currentImport = undefined;\n }\n continue;\n }\n\n if (startsStaticImport(line)) {\n if (endsImportDeclaration(line)) {\n imports.push(line);\n } else {\n currentImport = [line];\n }\n continue;\n }\n\n body.push(line);\n }\n\n if (currentImport) {\n body.push(...currentImport);\n }\n\n return { imports, body: body.join(\"\\n\") };\n}\n\nfunction startsStaticImport(line: string): boolean {\n const trimmed = line.trimStart();\n return trimmed.startsWith(\"import \") && !trimmed.startsWith(\"import(\");\n}\n\nfunction endsImportDeclaration(line: string): boolean {\n const trimmed = line.trim();\n return (\n trimmed.endsWith(\";\") ||\n /^import\\s+[\"'][^\"']+[\"']$/.test(trimmed) ||\n /\\sfrom\\s+[\"'][^\"']+[\"']$/.test(trimmed)\n );\n}\n\nfunction indentCode(source: string): string {\n return source\n .split(\"\\n\")\n .map((line) => (line.length > 0 ? ` ${line}` : line))\n .join(\"\\n\");\n}\n\nfunction rewriteImports(source: string, rewrites: Record<string, string> | undefined): string {\n if (!rewrites) {\n return source;\n }\n\n let result = source;\n for (const [from, to] of Object.entries(rewrites)) {\n const escaped = escapeRegExp(from);\n result = result\n .replace(new RegExp(`(from\\\\s+[\"'])${escaped}([\"'])`, \"g\"), `$1${to}$2`)\n .replace(new RegExp(`(import\\\\s+[\"'])${escaped}([\"'])`, \"g\"), `$1${to}$2`)\n .replace(new RegExp(`(import\\\\(\\\\s*[\"'])${escaped}([\"']\\\\s*\\\\))`, \"g\"), `$1${to}$2`);\n }\n return result;\n}\n\n/**\n * Applies the same import rewrite table to harness-owned imports.\n *\n * @internal\n * @example\n * ```ts docs-test\n * import { expect } from \"vitest\";\n * import { extractDocsTests } from \"../../src/code-blocks\";\n *\n * const markdown = [\n * \"```ts docs-test\",\n * \"expect(1 + 1).toBe(2);\",\n * \"```\",\n * ].join(\"\\n\");\n *\n * const blocks = await extractDocsTests(markdown);\n *\n * expect(blocks).toHaveLength(1);\n * expect(blocks[0]?.code).toMatchInlineSnapshot('\"expect(1 + 1).toBe(2);\"');\n * ```\n */\nfunction rewriteSpecifier(specifier: string, rewrites: Record<string, string> | undefined): string {\n return rewrites?.[specifier] ?? specifier;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction docsTestFileName(block: CollectedDocsTest): string {\n const baseName =\n block.relativePath\n .replace(/^\\.\\//, \"\")\n .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"docs-test\";\n return `${baseName}-L${block.startLine}-${block.index + 1}.test.${extensionForLanguage(\n block.language,\n )}`;\n}\n\nfunction extensionForLanguage(language: string): string {\n switch (language.toLowerCase()) {\n case \"jsx\":\n return \"jsx\";\n case \"tsx\":\n return \"tsx\";\n case \"mjs\":\n return \"mjs\";\n case \"mts\":\n return \"mts\";\n case \"js\":\n return \"js\";\n default:\n return \"ts\";\n }\n}\n\nfunction toArray(value: string | string[] | undefined): string[] {\n if (!value) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction normalizePath(value: string): string {\n return value.split(path.sep).join(\"/\");\n}\n\nfunction mergeEnv(overrides: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...process.env };\n for (const [key, value] of Object.entries(overrides ?? {})) {\n if (value === undefined) {\n delete env[key];\n } else {\n env[key] = value;\n }\n }\n return env;\n}\n\nfunction runCommand(\n command: string,\n args: string[],\n options: { cwd: string; env: NodeJS.ProcessEnv },\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: options.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n\n if (child.stdout) {\n child.stdout.setEncoding(\"utf-8\");\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n }\n if (child.stderr) {\n child.stderr.setEncoding(\"utf-8\");\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n }\n child.on(\"error\", reject);\n child.on(\"close\", (exitCode) => {\n resolve({ exitCode: exitCode ?? 1, stdout, stderr });\n });\n });\n}\n","import { createRequire } from \"node:module\";\nimport type { CSpellUserSettings, SpellCheckFileOptions, ValidationIssue } from \"cspell-lib\";\n\nconst require = createRequire(import.meta.url);\n\nconst SUPPORTED_MARKDOWN_LINT_LANGUAGES = [\"en\", \"ja\", \"zh\", \"fr\", \"de\", \"pl\"] as const;\nconst DEFAULT_LANGUAGES = [\"en\"] as const;\nconst DEFAULT_RULES = {\n duplicateHeadings: true,\n headingIncrement: true,\n maxConsecutiveBlankLines: 1,\n repeatedPunctuation: true,\n repeatedWords: true,\n spellcheck: true,\n trailingSpaces: true,\n} as const;\nconst DEFAULT_CSPELL_IMPORTS: Partial<Record<MarkdownLintLanguage, string>> = {\n de: \"@cspell/dict-de-de/cspell-ext.json\",\n en: \"@cspell/dict-en_us/cspell-ext.json\",\n fr: \"@cspell/dict-fr-fr/cspell-ext.json\",\n pl: \"@cspell/dict-pl_pl/cspell-ext.json\",\n};\n\nexport type MarkdownLintLanguage = (typeof SUPPORTED_MARKDOWN_LINT_LANGUAGES)[number];\nexport type MarkdownLintSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * Opt-in standard dictionary sources.\n *\n * The default provider uses CSpell dictionary packages because those packages\n * are actively maintained and expose locale-specific dictionaries in a stable\n * config format. Languages without a bundled preset can still be added through\n * custom `imports`.\n */\nexport interface MarkdownLintStandardDictionaryOptions {\n /**\n * Standard dictionary provider.\n * @default \"cspell\"\n */\n provider?: \"cspell\";\n\n /**\n * Languages whose default standard dictionaries should be enabled.\n *\n * Built-in preset package mappings currently exist for `en`, `fr`, `de`,\n * and `pl`. For other languages, use `imports`.\n *\n * @default []\n */\n languages?: MarkdownLintLanguage[];\n\n /**\n * Additional CSpell-compatible imports.\n *\n * This can point at installed packages like\n * `@cspell/dict-fr-fr/cspell-ext.json` or local CSpell config files.\n * @default []\n */\n imports?: string[];\n\n /**\n * Base URL or path used when resolving `imports`.\n *\n * @default new URL(\".\", import.meta.url)\n */\n resolveImportsRelativeTo?: string | URL;\n}\n\n/**\n * Additional dictionary configuration for the Markdown linter.\n */\nexport interface MarkdownLintDictionaryOptions {\n /**\n * Words ignored across all configured languages.\n * @default []\n */\n words?: string[];\n\n /**\n * Extra words to allow per language.\n * @default {}\n */\n byLanguage?: Partial<Record<MarkdownLintLanguage, string[]>>;\n\n /**\n * Words that should never produce diagnostics.\n * @default []\n */\n ignoredWords?: string[];\n\n /**\n * Opt-in standard dictionary datasets.\n *\n * By default the linter stays on a minimal built-in dictionary. Enable this\n * to load larger locale dictionaries from a standard external source.\n * @default false\n */\n standard?: MarkdownLintStandardDictionaryOptions | false;\n}\n\n/**\n * Rule switches for Markdown linting.\n */\nexport interface MarkdownLintRuleOptions {\n /**\n * Report headings that repeat the same visible text.\n * @default true\n */\n duplicateHeadings?: boolean;\n\n /**\n * Report heading depth jumps such as `#` -> `###`.\n * @default true\n */\n headingIncrement?: boolean;\n\n /**\n * Maximum number of blank lines allowed in a row.\n * @default 1\n */\n maxConsecutiveBlankLines?: number;\n\n /**\n * Report duplicated terminal punctuation such as `!!` or `??`.\n * @default true\n */\n repeatedPunctuation?: boolean;\n\n /**\n * Report adjacent repeated words in visible prose.\n * @default true\n */\n repeatedWords?: boolean;\n\n /**\n * Enable built-in multilingual spellchecking.\n * @default true\n */\n spellcheck?: boolean;\n\n /**\n * Report trailing spaces.\n * @default true\n */\n trailingSpaces?: boolean;\n}\n\n/**\n * Options for linting Markdown documents.\n */\nexport interface MarkdownLintOptions {\n /**\n * Languages enabled for spellchecking.\n *\n * When `dictionary.standard.languages` is provided and this option is\n * omitted, those languages are used instead.\n *\n * @default ['en']\n */\n languages?: MarkdownLintLanguage[];\n\n /**\n * Rule configuration.\n * Omitted fields use `MarkdownLintRuleOptions` defaults.\n * @default {}\n */\n rules?: MarkdownLintRuleOptions;\n\n /**\n * Built-in and opt-in standard dictionary overrides.\n * @default {}\n */\n dictionary?: MarkdownLintDictionaryOptions;\n\n /**\n * Enable MDX-aware syntax masking while linting visible prose.\n * File-oriented APIs infer this from `.mdx` when omitted.\n * @default false for content APIs; inferred for file APIs\n */\n mdx?: boolean;\n}\n\n/**\n * A single Markdown lint diagnostic.\n */\nexport interface MarkdownLintDiagnostic {\n /**\n * Stable rule identifier.\n */\n ruleId: string;\n\n /**\n * Diagnostic severity.\n */\n severity: MarkdownLintSeverity;\n\n /**\n * Human-readable explanation.\n */\n message: string;\n\n /**\n * 1-indexed line number.\n */\n line: number;\n\n /**\n * 1-indexed start column.\n */\n column: number;\n\n /**\n * 1-indexed end line.\n */\n endLine: number;\n\n /**\n * 1-indexed end column.\n */\n endColumn: number;\n\n /**\n * Language used for spellchecking, when relevant.\n */\n language?: MarkdownLintLanguage;\n\n /**\n * Suggested replacements, when available.\n */\n suggestions?: string[];\n}\n\n/**\n * Markdown lint report.\n */\nexport interface MarkdownLintResult {\n /**\n * All collected diagnostics.\n */\n diagnostics: MarkdownLintDiagnostic[];\n\n /**\n * Number of error diagnostics.\n */\n errorCount: number;\n\n /**\n * Number of warning diagnostics.\n */\n warningCount: number;\n\n /**\n * Number of info diagnostics.\n */\n infoCount: number;\n}\n\ninterface NormalizedStandardDictionaryOptions {\n imports: string[];\n languages: MarkdownLintLanguage[];\n provider: \"cspell\";\n resolveImportsRelativeTo: string | URL;\n}\n\ninterface InternalNormalizedMarkdownLintOptions {\n dictionary: Omit<MarkdownLintDictionaryOptions, \"standard\"> & {\n standard: NormalizedStandardDictionaryOptions | false;\n };\n languages: MarkdownLintLanguage[];\n mdx: boolean;\n rules: Required<MarkdownLintRuleOptions>;\n}\n\ninterface NapiMarkdownLintLanguageWords {\n language: MarkdownLintLanguage;\n words: string[];\n}\n\ninterface NapiMarkdownLintOptions {\n dictionary?: {\n byLanguage?: NapiMarkdownLintLanguageWords[];\n ignoredWords?: string[];\n words?: string[];\n };\n languages?: MarkdownLintLanguage[];\n mdx?: boolean;\n rules?: Required<MarkdownLintRuleOptions>;\n}\n\ninterface NapiMarkdownLintResult extends MarkdownLintResult {\n maskedDocument: string;\n}\n\ninterface NapiMarkdownLintModule {\n lintMarkdownDocuments?: (\n sources: string[],\n options?: NapiMarkdownLintOptions,\n ) => NapiMarkdownLintResult[];\n lintMarkdown: (source: string, options?: NapiMarkdownLintOptions) => NapiMarkdownLintResult;\n}\n\nlet napiBinding: NapiMarkdownLintModule | null | undefined;\nlet cspellLibPromise: Promise<typeof import(\"cspell-lib\")> | undefined;\n\n/**\n * Lints Markdown prose with the Rust-backed built-in rule engine.\n */\nexport function lintMarkdown(\n source: string,\n options: MarkdownLintOptions = {},\n): MarkdownLintResult {\n const normalizedOptions = normalizeLintOptions(options);\n return lintMarkdownWithNormalizedOptions(source, normalizedOptions);\n}\n\n/**\n * Async Markdown linter that supports opt-in standard dictionaries.\n */\nexport async function lintMarkdownAsync(\n source: string,\n options: MarkdownLintOptions = {},\n): Promise<MarkdownLintResult> {\n const normalizedOptions = normalizeLintOptions(options);\n const [result] = await lintMarkdownDocumentsWithNormalizedOptions([source], normalizedOptions);\n return result ?? createEmptyLintResult();\n}\n\n/**\n * Internal batched Markdown linting entry point used by file-based workflows.\n */\nexport async function lintMarkdownDocumentsAsync(\n sources: string[],\n options: MarkdownLintOptions = {},\n): Promise<MarkdownLintResult[]> {\n const normalizedOptions = normalizeLintOptions(options);\n return lintMarkdownDocumentsWithNormalizedOptions(sources, normalizedOptions);\n}\n\nfunction lintMarkdownWithNormalizedOptions(\n source: string,\n normalizedOptions: InternalNormalizedMarkdownLintOptions,\n): MarkdownLintResult {\n if (normalizedOptions.dictionary.standard) {\n throw new Error(\n \"[ox-content] lintMarkdownAsync is required when dictionary.standard is enabled.\",\n );\n }\n\n const napi = loadNapiBindingSync();\n return stripMaskedDocument(\n napi.lintMarkdown(source, toNapiMarkdownLintOptions(normalizedOptions)),\n );\n}\n\nasync function lintMarkdownDocumentsWithNormalizedOptions(\n sources: string[],\n normalizedOptions: InternalNormalizedMarkdownLintOptions,\n): Promise<MarkdownLintResult[]> {\n if (sources.length === 0) {\n return [];\n }\n\n const napi = loadNapiBindingSync();\n const napiOptions = toNapiMarkdownLintOptions(\n normalizedOptions,\n Boolean(normalizedOptions.dictionary.standard),\n );\n const builtInResults =\n typeof napi.lintMarkdownDocuments === \"function\"\n ? napi.lintMarkdownDocuments(sources, napiOptions)\n : sources.map((source) => napi.lintMarkdown(source, napiOptions));\n\n if (!normalizedOptions.rules.spellcheck || !normalizedOptions.dictionary.standard) {\n return builtInResults.map(stripMaskedDocument);\n }\n\n const standardDiagnostics = await runStandardSpellcheckDocuments(\n builtInResults.map((result) => result.maskedDocument),\n normalizedOptions,\n );\n\n return builtInResults.map((result, index) =>\n summarizeDiagnostics(\n sortDiagnostics(result.diagnostics.concat(standardDiagnostics[index] ?? [])),\n ),\n );\n}\n\nfunction loadNapiBindingSync(): NapiMarkdownLintModule {\n if (napiBinding) {\n return napiBinding;\n }\n\n if (napiBinding === null) {\n throw new Error(\n \"[ox-content] @ox-content/napi is required for Markdown linting. Please ensure the NAPI module is built.\",\n );\n }\n\n try {\n const loaded = require(\"@ox-content/napi\") as NapiMarkdownLintModule & {\n default?: Partial<NapiMarkdownLintModule>;\n };\n napiBinding =\n loaded.default && typeof loaded.default === \"object\"\n ? { ...loaded.default, ...loaded }\n : loaded;\n\n return napiBinding;\n } catch {\n napiBinding = null;\n throw new Error(\n \"[ox-content] @ox-content/napi is required for Markdown linting. Please ensure the NAPI module is built.\",\n );\n }\n}\n\nfunction toNapiMarkdownLintOptions(\n options: InternalNormalizedMarkdownLintOptions,\n disableBuiltinSpellcheck = false,\n): NapiMarkdownLintOptions {\n const byLanguage = Object.entries(options.dictionary.byLanguage ?? {}).map(\n ([language, words]): NapiMarkdownLintLanguageWords => ({\n language: language as MarkdownLintLanguage,\n words,\n }),\n );\n\n return {\n dictionary: {\n byLanguage,\n ignoredWords: options.dictionary.ignoredWords,\n words: options.dictionary.words,\n },\n languages: options.languages,\n mdx: options.mdx,\n rules: {\n ...options.rules,\n spellcheck: disableBuiltinSpellcheck ? false : options.rules.spellcheck,\n },\n };\n}\n\nfunction stripMaskedDocument(result: NapiMarkdownLintResult): MarkdownLintResult {\n return {\n diagnostics: result.diagnostics,\n errorCount: result.errorCount,\n infoCount: result.infoCount,\n warningCount: result.warningCount,\n };\n}\n\nfunction normalizeLintOptions(options: MarkdownLintOptions): InternalNormalizedMarkdownLintOptions {\n const standardDictionary =\n options.dictionary?.standard && typeof options.dictionary.standard === \"object\"\n ? options.dictionary.standard\n : undefined;\n const optionLanguages = options.languages?.filter((language): language is MarkdownLintLanguage =>\n SUPPORTED_MARKDOWN_LINT_LANGUAGES.includes(language),\n );\n const standardLanguages = standardDictionary?.languages?.filter(\n (language): language is MarkdownLintLanguage =>\n SUPPORTED_MARKDOWN_LINT_LANGUAGES.includes(language),\n );\n const languages: MarkdownLintLanguage[] = optionLanguages ??\n standardLanguages ?? [...DEFAULT_LANGUAGES];\n\n const standard = normalizeStandardDictionaryOptions(options.dictionary?.standard, languages);\n\n return {\n dictionary: {\n ...options.dictionary,\n standard,\n },\n languages: [...new Set(languages)],\n mdx: options.mdx ?? false,\n rules: {\n duplicateHeadings: options.rules?.duplicateHeadings ?? DEFAULT_RULES.duplicateHeadings,\n headingIncrement: options.rules?.headingIncrement ?? DEFAULT_RULES.headingIncrement,\n maxConsecutiveBlankLines:\n options.rules?.maxConsecutiveBlankLines ?? DEFAULT_RULES.maxConsecutiveBlankLines,\n repeatedPunctuation: options.rules?.repeatedPunctuation ?? DEFAULT_RULES.repeatedPunctuation,\n repeatedWords: options.rules?.repeatedWords ?? DEFAULT_RULES.repeatedWords,\n spellcheck: options.rules?.spellcheck ?? DEFAULT_RULES.spellcheck,\n trailingSpaces: options.rules?.trailingSpaces ?? DEFAULT_RULES.trailingSpaces,\n },\n };\n}\n\nfunction normalizeStandardDictionaryOptions(\n standard: MarkdownLintDictionaryOptions[\"standard\"],\n fallbackLanguages: MarkdownLintLanguage[],\n): NormalizedStandardDictionaryOptions | false {\n if (!standard) {\n return false;\n }\n\n const languages =\n standard.languages?.filter((language): language is MarkdownLintLanguage =>\n SUPPORTED_MARKDOWN_LINT_LANGUAGES.includes(language),\n ) ?? fallbackLanguages;\n const customImports = standard.imports ?? [];\n const missingPresetLanguages = languages.filter((language) => !DEFAULT_CSPELL_IMPORTS[language]);\n\n if (missingPresetLanguages.length > 0 && customImports.length === 0) {\n throw new Error(\n `[ox-content] No bundled standard dictionary preset exists for ${missingPresetLanguages.join(\n \", \",\n )}. Provide dictionary.standard.imports to enable those languages.`,\n );\n }\n\n const imports = [\n ...languages\n .map((language) => DEFAULT_CSPELL_IMPORTS[language])\n .filter((value): value is string => Boolean(value)),\n ...customImports,\n ];\n\n if (imports.length === 0) {\n throw new Error(\n \"[ox-content] dictionary.standard requires at least one bundled preset language or custom import.\",\n );\n }\n\n return {\n imports: [...new Set(imports)],\n languages: [...new Set(languages)],\n provider: standard.provider ?? \"cspell\",\n resolveImportsRelativeTo: standard.resolveImportsRelativeTo ?? new URL(\".\", import.meta.url),\n };\n}\n\nasync function runStandardSpellcheckDocuments(\n maskedDocuments: string[],\n options: InternalNormalizedMarkdownLintOptions,\n): Promise<MarkdownLintDiagnostic[][]> {\n const standard = options.dictionary.standard;\n\n if (!standard || maskedDocuments.length === 0) {\n return maskedDocuments.map(() => []);\n }\n\n try {\n const { spellCheckDocument } = await loadCspellLib();\n const locale = standard.languages.join(\",\");\n const settings = createStandardSpellcheckSettings(options, locale);\n const spellCheckOptions = {\n generateSuggestions: true,\n noConfigSearch: true,\n numSuggestions: 3,\n resolveImportsRelativeTo: standard.resolveImportsRelativeTo,\n } satisfies SpellCheckFileOptions & { resolveImportsRelativeTo: string | URL };\n\n return Promise.all(\n maskedDocuments.map(async (maskedDocument, index) => {\n if (maskedDocument.trim().length === 0) {\n return [];\n }\n\n const result = await spellCheckDocument(\n {\n languageId: \"plaintext\",\n locale,\n text: maskedDocument,\n uri: `file:///ox-content-lint-${index}.md`,\n },\n spellCheckOptions,\n settings,\n );\n\n // Precompute the document's newline offsets once so each issue's line\n // can be resolved with a binary search instead of a fresh O(N) scan\n // from offset 0 (which made line resolution O(issues * length)).\n const newlineOffsets: number[] = [];\n for (let i = 0; i < maskedDocument.length; i++) {\n if (maskedDocument.charCodeAt(i) === 10) {\n newlineOffsets.push(i);\n }\n }\n\n return result.issues.map((issue) =>\n mapStandardIssueToDiagnostic(issue, standard.languages, newlineOffsets),\n );\n }),\n );\n } catch (error) {\n const imports = standard.imports.join(\", \");\n const message =\n imports.length > 0\n ? `[ox-content] Failed to load standard dictionaries from ${imports}. Verify the imports and install the referenced CSpell packages.`\n : \"[ox-content] Failed to load the configured standard dictionaries.\";\n\n throw new Error(message, {\n cause: error,\n });\n }\n}\n\nfunction createStandardSpellcheckSettings(\n options: InternalNormalizedMarkdownLintOptions,\n locale: string,\n): CSpellUserSettings {\n return {\n import: options.dictionary.standard ? options.dictionary.standard.imports : [],\n ignoreWords: options.dictionary.ignoredWords,\n language: locale,\n version: \"0.2\",\n words: [\n ...(options.dictionary.words ?? []),\n ...Object.values(options.dictionary.byLanguage ?? {}).flat(),\n ],\n };\n}\n\nasync function loadCspellLib(): Promise<typeof import(\"cspell-lib\")> {\n // CSpell is optional and relatively heavy; lazy-load it only when standard\n // dictionaries are enabled, then reuse the same module promise for all files\n // in the lint run.\n cspellLibPromise ??= import(\"cspell-lib\");\n return cspellLibPromise;\n}\n\nfunction mapStandardIssueToDiagnostic(\n issue: ValidationIssue,\n languages: MarkdownLintLanguage[],\n newlineOffsets: number[],\n): MarkdownLintDiagnostic {\n const line = getLineNumberAtOffset(newlineOffsets, issue.line.offset);\n const column = issue.offset - issue.line.offset + 1;\n const length = issue.length ?? issue.text.length;\n\n return {\n column,\n endColumn: column + length,\n endLine: line,\n language: inferStandardIssueLanguage(issue.text, languages),\n line,\n message: `Unknown word \"${issue.text}\".`,\n ruleId: \"spellcheck\",\n severity: \"warning\",\n suggestions: issue.suggestions?.slice(0, 3),\n };\n}\n\nfunction getLineNumberAtOffset(newlineOffsets: number[], offset: number): number {\n // Line number = 1 + (count of newline offsets strictly less than `offset`).\n // This matches the old linear scan exactly: a newline can only exist at an\n // index < text.length, so counting positions `< offset` over the whole\n // document gives the same count for every `offset` (including past EOF).\n let lo = 0;\n let hi = newlineOffsets.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (newlineOffsets[mid] < offset) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n\n return lo + 1;\n}\n\nfunction inferStandardIssueLanguage(\n word: string,\n languages: MarkdownLintLanguage[],\n): MarkdownLintLanguage | undefined {\n if (/[\\p{Script=Hiragana}\\p{Script=Katakana}]/u.test(word) && languages.includes(\"ja\")) {\n return \"ja\";\n }\n\n if (/[\\p{Script=Han}]/u.test(word)) {\n if (languages.includes(\"zh\") && !languages.includes(\"ja\")) {\n return \"zh\";\n }\n if (languages.includes(\"ja\") && !languages.includes(\"zh\")) {\n return \"ja\";\n }\n }\n\n if (/[\\p{Script=Latin}]/u.test(word)) {\n const latinLanguages = languages.filter(\n (language): language is Exclude<MarkdownLintLanguage, \"ja\" | \"zh\"> =>\n language !== \"ja\" && language !== \"zh\",\n );\n\n if (latinLanguages.length === 1) {\n return latinLanguages[0];\n }\n\n return inferLatinLanguageFromCharacters(word, latinLanguages);\n }\n\n return undefined;\n}\n\nfunction inferLatinLanguageFromCharacters(\n word: string,\n languages: Exclude<MarkdownLintLanguage, \"ja\" | \"zh\">[],\n): Exclude<MarkdownLintLanguage, \"ja\" | \"zh\"> | undefined {\n if (languages.includes(\"pl\") && /[ąćęłńóśźż]/iu.test(word)) {\n return \"pl\";\n }\n\n if (languages.includes(\"de\") && /[äöüß]/iu.test(word)) {\n return \"de\";\n }\n\n if (languages.includes(\"fr\") && /[àâæçéèêëîïôœùûüÿ]/iu.test(word)) {\n return \"fr\";\n }\n\n return undefined;\n}\n\nfunction summarizeDiagnostics(diagnostics: MarkdownLintDiagnostic[]): MarkdownLintResult {\n let errorCount = 0;\n let warningCount = 0;\n let infoCount = 0;\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.severity === \"error\") {\n errorCount += 1;\n } else if (diagnostic.severity === \"warning\") {\n warningCount += 1;\n } else {\n infoCount += 1;\n }\n }\n\n return { diagnostics, errorCount, infoCount, warningCount };\n}\n\nfunction createEmptyLintResult(): MarkdownLintResult {\n return summarizeDiagnostics([]);\n}\n\nfunction sortDiagnostics(diagnostics: MarkdownLintDiagnostic[]): MarkdownLintDiagnostic[] {\n return [...diagnostics].sort((left, right) => {\n if (left.line !== right.line) {\n return left.line - right.line;\n }\n\n if (left.column !== right.column) {\n return left.column - right.column;\n }\n\n return left.ruleId.localeCompare(right.ruleId);\n });\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { glob } from \"glob\";\nimport {\n lintMarkdownDocumentsAsync,\n lintMarkdownAsync,\n type MarkdownLintDiagnostic,\n type MarkdownLintOptions,\n type MarkdownLintResult,\n} from \"./lint\";\nimport { resolveMdxForFilePath } from \"./markdown\";\n\nconst DEFAULT_LINT_FILE_INCLUDE = [\"**/*.md\", \"**/*.markdown\", \"**/*.mdx\"] as const;\nconst DEFAULT_LINT_FILE_EXCLUDE = [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\"] as const;\n\n/**\n * File-oriented Markdown lint options for end-user configuration.\n *\n * This extends the content-level lint options with project-level targeting,\n * so consumers can decide which files should be checked and which paths should\n * be ignored.\n */\nexport interface MarkdownLintFileOptions extends MarkdownLintOptions {\n /**\n * Base directory used to resolve `include` and `exclude` patterns.\n * @default process.cwd()\n */\n cwd?: string;\n\n /**\n * Glob patterns for files to lint.\n * @default ['**\\/*.md', '**\\/*.markdown', '**\\/*.mdx']\n */\n include?: string[];\n\n /**\n * Glob patterns for files to exclude from linting.\n * @default ['**\\/node_modules/**', '**\\/.git/**', '**\\/dist/**']\n */\n exclude?: string[];\n\n /**\n * Alias of `exclude`.\n * When omitted, only `exclude` is used.\n * @default undefined\n */\n ignore?: string[];\n}\n\n/**\n * A lint diagnostic annotated with file metadata.\n */\nexport interface MarkdownLintFileDiagnostic extends MarkdownLintDiagnostic {\n filePath: string;\n relativePath: string;\n}\n\n/**\n * Lint result for a single file.\n */\nexport interface MarkdownLintFileResult extends MarkdownLintResult {\n filePath: string;\n relativePath: string;\n skipped: boolean;\n}\n\n/**\n * Aggregated lint result for multiple files.\n */\nexport interface MarkdownLintFilesResult {\n checkedFileCount: number;\n diagnostics: MarkdownLintFileDiagnostic[];\n errorCount: number;\n files: MarkdownLintFileResult[];\n infoCount: number;\n warningCount: number;\n}\n\ninterface ResolvedMarkdownLintFileOptions {\n cwd: string;\n exclude: string[];\n include: string[];\n lintOptions: MarkdownLintOptions;\n}\n\ninterface MarkdownLintFileEntry {\n filePath: string;\n relativePath: string;\n}\n\n/**\n * Returns true if the file path is included by the configured glob filters.\n */\nexport function shouldLintMarkdownFile(\n filePath: string,\n options: MarkdownLintFileOptions = {},\n): boolean {\n const resolvedOptions = resolveMarkdownLintFileOptions(options);\n return shouldLintAbsoluteFile(path.resolve(resolvedOptions.cwd, filePath), resolvedOptions);\n}\n\n/**\n * Lints a single Markdown file using project-style include/exclude settings.\n *\n * If the file is filtered out by `include` / `exclude`, the returned result is\n * marked as `skipped` and contains no diagnostics.\n */\nexport async function lintMarkdownFile(\n filePath: string,\n options: MarkdownLintFileOptions = {},\n): Promise<MarkdownLintFileResult> {\n const resolvedOptions = resolveMarkdownLintFileOptions(options);\n return lintMarkdownFileWithResolvedOptions(\n path.resolve(resolvedOptions.cwd, filePath),\n resolvedOptions,\n );\n}\n\n/**\n * Lints all Markdown files matched by the configured include/exclude patterns.\n */\nexport async function lintMarkdownFiles(\n options: MarkdownLintFileOptions = {},\n): Promise<MarkdownLintFilesResult> {\n const resolvedOptions = resolveMarkdownLintFileOptions(options);\n const matchedFiles = await collectMarkdownLintFileEntries(resolvedOptions);\n const sources = await Promise.all(\n matchedFiles.map((file) => fs.readFile(file.filePath, \"utf-8\")),\n );\n const results = await lintMatchedMarkdownFiles(\n matchedFiles,\n sources,\n resolvedOptions.lintOptions,\n );\n\n const files = matchedFiles.map((file, index): MarkdownLintFileResult => ({\n ...(results[index] ?? createEmptyLintResult()),\n filePath: file.filePath,\n relativePath: file.relativePath,\n skipped: false,\n }));\n\n const diagnostics = files.flatMap((fileResult) =>\n fileResult.diagnostics.map((diagnostic): MarkdownLintFileDiagnostic => ({\n ...diagnostic,\n filePath: fileResult.filePath,\n relativePath: fileResult.relativePath,\n })),\n );\n\n return {\n checkedFileCount: files.length,\n diagnostics,\n errorCount: files.reduce((count, fileResult) => count + fileResult.errorCount, 0),\n files,\n infoCount: files.reduce((count, fileResult) => count + fileResult.infoCount, 0),\n warningCount: files.reduce((count, fileResult) => count + fileResult.warningCount, 0),\n };\n}\n\nfunction resolveMarkdownLintFileOptions(\n options: MarkdownLintFileOptions,\n): ResolvedMarkdownLintFileOptions {\n return {\n cwd: path.resolve(options.cwd ?? process.cwd()),\n exclude: [\n ...new Set([...(options.exclude ?? DEFAULT_LINT_FILE_EXCLUDE), ...(options.ignore ?? [])]),\n ],\n include: [...new Set(options.include ?? DEFAULT_LINT_FILE_INCLUDE)],\n lintOptions: {\n dictionary: options.dictionary,\n languages: options.languages,\n mdx: options.mdx,\n rules: options.rules,\n },\n };\n}\n\nasync function lintMarkdownFileWithResolvedOptions(\n filePath: string,\n options: ResolvedMarkdownLintFileOptions,\n): Promise<MarkdownLintFileResult> {\n const absoluteFilePath = path.resolve(filePath);\n const relativePath = normalizePath(path.relative(options.cwd, absoluteFilePath));\n\n if (!shouldLintAbsoluteFile(absoluteFilePath, options)) {\n return {\n ...createEmptyLintResult(),\n filePath: absoluteFilePath,\n relativePath,\n skipped: true,\n };\n }\n\n const source = await fs.readFile(absoluteFilePath, \"utf-8\");\n const result = await lintMarkdownAsync(source, {\n ...options.lintOptions,\n mdx: resolveMdxForFilePath(absoluteFilePath, options.lintOptions.mdx),\n });\n\n return {\n ...result,\n filePath: absoluteFilePath,\n relativePath,\n skipped: false,\n };\n}\n\nasync function collectMarkdownLintFileEntries(\n options: ResolvedMarkdownLintFileOptions,\n): Promise<MarkdownLintFileEntry[]> {\n const files = new Map<string, MarkdownLintFileEntry>();\n\n for (const pattern of options.include) {\n const matches = await glob(pattern, {\n absolute: true,\n cwd: options.cwd,\n ignore: options.exclude,\n nocase: true,\n nodir: true,\n });\n\n for (const filePath of matches) {\n const absoluteFilePath = path.resolve(filePath);\n if (shouldLintAbsoluteFile(absoluteFilePath, options)) {\n files.set(absoluteFilePath, {\n filePath: absoluteFilePath,\n relativePath: normalizePath(path.relative(options.cwd, absoluteFilePath)),\n });\n }\n }\n }\n\n return [...files.values()].sort((left, right) => left.filePath.localeCompare(right.filePath));\n}\n\nfunction shouldLintAbsoluteFile(\n filePath: string,\n options: ResolvedMarkdownLintFileOptions,\n): boolean {\n const absolutePath = normalizePath(path.resolve(filePath));\n const relativePath = normalizePath(path.relative(options.cwd, absolutePath));\n\n const matches = (patterns: string[]) =>\n patterns.some((pattern) => {\n const normalizedPattern = normalizePath(pattern);\n return [relativePath, absolutePath].some(\n (candidate) =>\n path.matchesGlob(candidate, normalizedPattern) ||\n path.matchesGlob(candidate.toLowerCase(), normalizedPattern.toLowerCase()),\n );\n });\n\n return matches(options.include) && !matches(options.exclude);\n}\n\nasync function lintMatchedMarkdownFiles(\n files: MarkdownLintFileEntry[],\n sources: string[],\n options: MarkdownLintOptions,\n): Promise<MarkdownLintResult[]> {\n const results = Array.from({ length: sources.length }, () => createEmptyLintResult());\n\n await Promise.all(\n [false, true].map(async (mdx) => {\n const indexes = files\n .map((file, index) => ({\n index,\n mdx: resolveMdxForFilePath(file.filePath, options.mdx),\n }))\n .filter((entry) => entry.mdx === mdx)\n .map((entry) => entry.index);\n if (indexes.length === 0) {\n return;\n }\n\n const groupResults = await lintMarkdownDocumentsAsync(\n indexes.map((index) => sources[index] ?? \"\"),\n { ...options, mdx },\n );\n for (const [groupIndex, result] of groupResults.entries()) {\n const sourceIndex = indexes[groupIndex];\n if (sourceIndex !== undefined) {\n results[sourceIndex] = result;\n }\n }\n }),\n );\n\n return results;\n}\n\nfunction normalizePath(value: string): string {\n return value.split(path.sep).join(\"/\");\n}\n\nfunction createEmptyLintResult(): MarkdownLintResult {\n return {\n diagnostics: [],\n errorCount: 0,\n infoCount: 0,\n warningCount: 0,\n };\n}\n","/**\n * Vite Plugin for Ox Content\n *\n * Uses Vite's Environment API for SSG-focused Markdown processing.\n * Provides separate environments for client and server rendering.\n */\n\nimport * as path from \"path\";\nimport type { Plugin, ViteDevServer, ResolvedConfig } from \"vite\";\nimport \"./virtual\";\nimport { createMarkdownEnvironment } from \"./environment\";\nimport { transformMarkdown } from \"./transform\";\nimport { extractDocs, generateMarkdown, writeDocs, resolveDocsOptions } from \"./docs\";\nimport { buildSsg, resolveSsgOptions } from \"./ssg\";\nimport { resolveSiteMapsOptions } from \"./site-maps\";\nimport { resolvePublishStateOptions } from \"./publish-state\";\nimport { resolveCascadeOptions, resolvePermalinksOptions } from \"./permalinks\";\nimport { resolveRedirectsOptions } from \"./redirects\";\nimport { notFoundSearchExcludeIds } from \"./not-found\";\nimport { resolveFeedsOptions } from \"./feeds\";\nimport { resolveTaxonomiesOptions } from \"./taxonomies\";\nimport { resolveVersionsOptions } from \"./versions\";\nimport {\n resolveSearchOptions,\n buildSearchIndex,\n writeSearchIndex,\n generateSearchModule,\n} from \"./search\";\nimport { resolveOgImageOptions } from \"./og-image\";\nimport {\n createDevServerMiddleware,\n createDevServerCache,\n invalidateNavCache,\n invalidatePageCache,\n} from \"./dev-server\";\nimport { createOgViewerPlugin } from \"./og-viewer\";\nimport { resolveI18nOptions, createI18nPlugin } from \"./i18n\";\nimport { isMarkdownFilePath, normalizeMarkdownExtensions } from \"./markdown\";\nimport { resolveImageOptions } from \"./resolve-image-options\";\nimport { generateCollectionsVirtualModule, resolveCollectionsOptions } from \"./collections\";\nimport type { BuiltinPmOptions, OxContentOptions, ResolvedOptions } from \"./types\";\nimport { resolveCardOptions } from \"./card-options\";\nimport { resolveFileTreeOptions } from \"./file-tree-options\";\nimport { resolveIncludeOptions } from \"./include-options\";\nimport { resolveStepsOptions } from \"./step-options\";\nimport type { TwitterEmbedOptions } from \"./plugins\";\n\nexport type { OxContentOptions } from \"./types\";\nexport type { TwitterEmbedOptions } from \"./plugins\";\nexport type {\n CodeAnnotationSyntax,\n CodeAnnotationsOptions,\n ResolvedCodeAnnotationsOptions,\n WikiLinkOptions,\n ResolvedWikiLinkOptions,\n EmojiShortcodeOptions,\n ResolvedEmojiShortcodeOptions,\n MathOptions,\n ResolvedMathOptions,\n AttrsOptions,\n ResolvedAttrsOptions,\n BadgeOptions,\n ResolvedBadgeOptions,\n ContainerOptions,\n ContainerTypeOptions,\n ResolvedContainerOptions,\n ImageOptions,\n ResolvedImageOptions,\n CodeImportOptions,\n ResolvedCodeImportOptions,\n IncludeOptions,\n ResolvedIncludeOptions,\n CardOptions,\n ResolvedCardOptions,\n StepsOptions,\n ResolvedStepsOptions,\n FileTreeOptions,\n ResolvedFileTreeOptions,\n SanitizeOptions,\n ResolvedSanitizeOptions,\n EditThisPageOptions,\n ResolvedEditThisPageOptions,\n CodeBlockLintOptions,\n ResolvedCodeBlockLintOptions,\n CodeBlockTypecheckOptions,\n ResolvedCodeBlockTypecheckOptions,\n DocsTestOptions,\n ResolvedDocsTestOptions,\n MarkdownDisplayFormat,\n DocsOptions,\n ResolvedDocsOptions,\n DocEntry,\n ParamDoc,\n ReturnDoc,\n ExtractedDocs,\n SsgOptions,\n ResolvedSsgOptions,\n A11yOptions,\n ResolvedA11y,\n ReaderChromeOptions,\n ResolvedReaderChrome,\n NotFoundOptions,\n ResolvedNotFoundOptions,\n TeamLink,\n TeamMember,\n TeamOptions,\n ResolvedTeamOptions,\n SiteMapsOptions,\n ResolvedSiteMapsOptions,\n PublishStateOptions,\n ResolvedPublishStateOptions,\n PermalinksOptions,\n ResolvedPermalinksOptions,\n CascadeOptions,\n ResolvedCascadeOptions,\n RedirectsOptions,\n ResolvedRedirectsOptions,\n FeedFormat,\n FeedsOptions,\n ResolvedFeedsOptions,\n TaxonomiesOptions,\n ResolvedTaxonomiesOptions,\n SearchOptions,\n ResolvedSearchOptions,\n SearchDocument,\n SearchResult,\n CollectionEntry,\n CollectionOptions,\n CollectionsOptions,\n ResolvedCollectionOptions,\n ResolvedCollectionsOptions,\n CollectionIncludeField,\n CollectionManifest,\n CollectionQueryBuilder,\n CollectionQueryOperator,\n // Entry page types\n HeroAction,\n HeroImage,\n HeroConfig,\n FeatureConfig,\n EntryPageConfig,\n SsgNavigationItem,\n SsgNavigationGroup,\n // i18n types\n I18nOptions,\n ResolvedI18nOptions,\n LocaleConfig,\n BuiltinEmbedOptions,\n ResolvedBuiltinEmbedOptions,\n BuiltinPmOptions,\n} from \"./types\";\n\n/**\n * Creates the Ox Content Vite plugin.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { oxContent } from '@ox-content/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [\n * oxContent({\n * srcDir: 'content',\n * gfm: true,\n * }),\n * ],\n * });\n * ```\n */\nexport function oxContent(options: OxContentOptions = {}): Plugin[] {\n const resolvedOptions = resolveOptions(options);\n let config: ResolvedConfig | undefined;\n const getRoot = () => config?.root || process.cwd();\n\n const ssgDevCache = createDevServerCache();\n const plugins: Plugin[] = [\n createMainPlugin(resolvedOptions, (resolvedConfig) => {\n config = resolvedConfig;\n }),\n createEnvironmentPlugin(resolvedOptions),\n createDocsPlugin(resolvedOptions, getRoot),\n createSsgPlugin(resolvedOptions, getRoot, ssgDevCache),\n createCollectionsPlugin(resolvedOptions, getRoot),\n createSearchPlugin(resolvedOptions, getRoot),\n ];\n\n if (resolvedOptions.i18n) {\n plugins.push(createI18nPlugin(resolvedOptions));\n }\n\n if (resolvedOptions.ogViewer) {\n plugins.push(createOgViewerPlugin(resolvedOptions));\n }\n\n return plugins;\n}\n\nasync function regenerateDocs(resolvedOptions: ResolvedOptions, root: string): Promise<number> {\n const docsOptions = resolvedOptions.docs;\n if (!docsOptions || !docsOptions.enabled) {\n return 0;\n }\n\n const srcDirs = docsOptions.src.map((src) => path.resolve(root, src));\n const outDir = path.resolve(root, docsOptions.out);\n const extracted = await extractDocs(srcDirs, docsOptions);\n const generated = generateMarkdown(extracted, docsOptions);\n\n await writeDocs(generated, outDir, extracted, docsOptions);\n\n return Object.keys(generated).length;\n}\n\nfunction createMainPlugin(\n resolvedOptions: ResolvedOptions,\n setConfig: (config: ResolvedConfig) => void,\n): Plugin {\n return {\n name: \"ox-content\",\n\n configResolved: setConfig,\n\n configureServer(devServer) {\n devServer.middlewares.use(async (req, res, next) => {\n const url = req.url;\n if (!url || !isMarkdownFilePath(url, resolvedOptions.extensions)) {\n return next();\n }\n\n next();\n });\n },\n\n resolveId(id) {\n if (id === \"virtual:ox-content/config\" || id === \"virtual:ox-content/runtime\") {\n return \"\\0\" + id;\n }\n\n if (isMarkdownFilePath(id, resolvedOptions.extensions)) {\n return id;\n }\n\n return null;\n },\n\n async load(id) {\n if (id === \"\\0virtual:ox-content/config\" || id === \"\\0virtual:ox-content/runtime\") {\n const virtualPath = id.slice(\"\\0virtual:ox-content/\".length);\n return generateVirtualModule(virtualPath, resolvedOptions);\n }\n\n return null;\n },\n\n async transform(code, id) {\n if (!isMarkdownFilePath(id, resolvedOptions.extensions)) {\n return null;\n }\n\n const result = await transformMarkdown(code, id, resolvedOptions);\n return {\n code: result.code,\n map: null,\n };\n },\n\n async handleHotUpdate({ file, server }) {\n if (!isMarkdownFilePath(file, resolvedOptions.extensions)) {\n return;\n }\n\n server.ws.send({\n type: \"custom\",\n event: \"ox-content:update\",\n data: { file },\n });\n\n const modules = server.moduleGraph.getModulesByFile(file);\n return modules ? Array.from(modules) : [];\n },\n };\n}\n\nfunction createCollectionsPlugin(resolvedOptions: ResolvedOptions, getRoot: () => string): Plugin {\n const moduleId = \"\\0virtual:ox-content/collections\";\n let moduleCode: Promise<string> | undefined;\n\n const invalidate = (devServer: ViteDevServer) => {\n moduleCode = undefined;\n const mod = devServer.moduleGraph.getModuleById(moduleId);\n if (mod) {\n devServer.moduleGraph.invalidateModule(mod);\n devServer.ws.send({ type: \"full-reload\" });\n }\n };\n\n return {\n name: \"ox-content:collections\",\n\n resolveId(id) {\n return id === \"virtual:ox-content/collections\" ? moduleId : null;\n },\n\n async load(id) {\n if (id !== moduleId) {\n return null;\n }\n moduleCode ??= generateCollectionsVirtualModule(getRoot(), resolvedOptions);\n return moduleCode;\n },\n\n configureServer(devServer) {\n if (!resolvedOptions.collections.enabled) {\n return;\n }\n\n const srcDir = path.resolve(getRoot(), resolvedOptions.srcDir);\n devServer.watcher.add(srcDir);\n devServer.watcher.on(\"all\", (_event, file) => {\n if (file.startsWith(srcDir) && isMarkdownFilePath(file, resolvedOptions.extensions)) {\n invalidate(devServer);\n }\n });\n },\n };\n}\n\nfunction createEnvironmentPlugin(resolvedOptions: ResolvedOptions): Plugin {\n return {\n name: \"ox-content:environment\",\n\n config() {\n return {\n environments: {\n markdown: createMarkdownEnvironment(resolvedOptions),\n },\n };\n },\n };\n}\n\nfunction createDocsPlugin(resolvedOptions: ResolvedOptions, getRoot: () => string): Plugin {\n return {\n name: \"ox-content:docs\",\n\n async buildStart() {\n const docsOptions = resolvedOptions.docs;\n if (!docsOptions || !docsOptions.enabled) {\n return;\n }\n\n try {\n const count = await regenerateDocs(resolvedOptions, getRoot());\n console.log(`[ox-content] Generated ${count} documentation files to ${docsOptions.out}`);\n } catch (err) {\n console.warn(\"[ox-content] Failed to generate documentation:\", err);\n }\n },\n\n configureServer(devServer) {\n const docsOptions = resolvedOptions.docs;\n if (!docsOptions || !docsOptions.enabled) {\n return;\n }\n\n const root = getRoot();\n const srcDirs = docsOptions.src.map((src) => path.resolve(root, src));\n for (const srcDir of srcDirs) {\n devServer.watcher.add(srcDir);\n }\n\n devServer.watcher.on(\"all\", async (event, file) => {\n if (event !== \"add\" && event !== \"change\" && event !== \"unlink\") {\n return;\n }\n\n const isSourceFile = srcDirs.some(\n (srcDir) => file.startsWith(srcDir) && (file.endsWith(\".ts\") || file.endsWith(\".tsx\")),\n );\n if (!isSourceFile) {\n return;\n }\n\n try {\n await regenerateDocs(resolvedOptions, root);\n } catch {\n // Ignore errors during dev.\n }\n });\n },\n };\n}\n\nfunction createSsgPlugin(\n resolvedOptions: ResolvedOptions,\n getRoot: () => string,\n ssgDevCache: ReturnType<typeof createDevServerCache>,\n): Plugin {\n return {\n name: \"ox-content:ssg\",\n\n configureServer(devServer) {\n const ssgOptions = resolvedOptions.ssg;\n if (!ssgOptions.enabled) return;\n\n const root = getRoot();\n const srcDir = path.resolve(root, resolvedOptions.srcDir);\n devServer.middlewares.use(createDevServerMiddleware(resolvedOptions, root, ssgDevCache));\n\n devServer.watcher.on(\"add\", (file: string) => {\n notifySsgFileAddedOrRemoved(devServer, resolvedOptions, ssgDevCache, srcDir, file, \"add\");\n });\n devServer.watcher.on(\"unlink\", (file: string) => {\n notifySsgFileAddedOrRemoved(\n devServer,\n resolvedOptions,\n ssgDevCache,\n srcDir,\n file,\n \"unlink\",\n );\n });\n devServer.watcher.on(\"change\", (file: string) => {\n if (file.startsWith(srcDir) && isMarkdownFilePath(file, resolvedOptions.extensions)) {\n invalidatePageCache(ssgDevCache, file);\n }\n });\n },\n\n async closeBundle() {\n const ssgOptions = resolvedOptions.ssg;\n if (!ssgOptions.enabled) {\n return;\n }\n\n try {\n const result = await buildSsg(resolvedOptions, getRoot());\n if (result.files.length > 0) {\n console.log(`[ox-content] Generated ${result.files.length} output files`);\n }\n\n for (const error of result.errors) {\n console.warn(`[ox-content] ${error}`);\n }\n } catch (err) {\n console.error(\"[ox-content] SSG build failed:\", err);\n }\n },\n };\n}\n\nfunction notifySsgFileAddedOrRemoved(\n devServer: ViteDevServer,\n resolvedOptions: ResolvedOptions,\n ssgDevCache: ReturnType<typeof createDevServerCache>,\n srcDir: string,\n file: string,\n type: \"add\" | \"unlink\",\n): void {\n if (!file.startsWith(srcDir) || !isMarkdownFilePath(file, resolvedOptions.extensions)) {\n return;\n }\n\n invalidateNavCache(ssgDevCache);\n devServer.ws.send({\n type: \"custom\",\n event: \"ox-content:update\",\n data: { file, type },\n });\n}\n\nfunction searchPublishState(\n resolvedOptions: ResolvedOptions,\n command: \"build\" | \"serve\",\n): ResolvedOptions[\"publishState\"] {\n const publishState = resolvedOptions.publishState ?? {\n enabled: false,\n includeDrafts: false,\n };\n return {\n ...publishState,\n includeDrafts: publishState.includeDrafts || command === \"serve\",\n };\n}\n\nfunction createSearchPlugin(resolvedOptions: ResolvedOptions, getRoot: () => string): Plugin {\n let searchIndexJson = \"\";\n let command: \"build\" | \"serve\" = \"build\";\n\n return {\n name: \"ox-content:search\",\n\n config(_config, env) {\n command = env.command;\n },\n\n resolveId(id) {\n if (id === \"virtual:ox-content/search\") {\n return \"\\0virtual:ox-content/search\";\n }\n return null;\n },\n\n async load(id) {\n if (id !== \"\\0virtual:ox-content/search\") {\n return null;\n }\n\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled) {\n return \"export const search = () => []; export const searchOptions = { enabled: false }; export default { search, searchOptions };\";\n }\n\n const indexPath = resolvedOptions.base + \"search-index.json\";\n return generateSearchModule(searchOptions, indexPath);\n },\n\n async buildStart() {\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled) {\n return;\n }\n\n const srcDir = path.resolve(getRoot(), resolvedOptions.srcDir);\n try {\n searchIndexJson = await buildSearchIndex(\n srcDir,\n resolvedOptions.base,\n resolvedOptions.extensions,\n searchPublishState(resolvedOptions, command),\n notFoundSearchExcludeIds(resolvedOptions.ssg.notFound),\n resolvedOptions.mdx,\n );\n console.log(\"[ox-content] Search index built\");\n } catch (err) {\n console.warn(\"[ox-content] Failed to build search index:\", err);\n }\n },\n\n configureServer(devServer) {\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled) {\n return;\n }\n\n // The index is only written to disk by the static build (closeBundle);\n // without a dev handler the client's fetch falls through to the html\n // fallback and search reports the index unavailable. Serve it from\n // memory, rebuilt lazily after a Markdown change.\n const srcDir = path.resolve(getRoot(), resolvedOptions.srcDir);\n let stale = false;\n devServer.watcher.on(\"all\", (event, file) => {\n if (event !== \"add\" && event !== \"change\" && event !== \"unlink\") {\n return;\n }\n const relative = path.relative(srcDir, file);\n const isInsideSrcDir =\n relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n if (isInsideSrcDir && isMarkdownFilePath(file, resolvedOptions.extensions)) {\n stale = true;\n }\n });\n\n const indexPath = resolvedOptions.base + \"search-index.json\";\n devServer.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== indexPath) {\n return next();\n }\n try {\n if (stale || !searchIndexJson) {\n searchIndexJson = await buildSearchIndex(\n srcDir,\n resolvedOptions.base,\n resolvedOptions.extensions,\n searchPublishState(resolvedOptions, command),\n notFoundSearchExcludeIds(resolvedOptions.ssg.notFound),\n resolvedOptions.mdx,\n );\n stale = false;\n }\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(searchIndexJson);\n } catch (err) {\n next(err);\n }\n });\n },\n\n async closeBundle() {\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled || !searchIndexJson) {\n return;\n }\n\n const outDir = path.resolve(getRoot(), resolvedOptions.outDir);\n try {\n await writeSearchIndex(searchIndexJson, outDir);\n console.log(\"[ox-content] Search index written to\", path.join(outDir, \"search-index.json\"));\n } catch (err) {\n console.warn(\"[ox-content] Failed to write search index:\", err);\n }\n },\n };\n}\n\n/**\n * Resolves plugin options with defaults.\n */\nfunction resolveOptions(options: OxContentOptions): ResolvedOptions {\n return {\n srcDir: options.srcDir ?? \"content\",\n outDir: options.outDir ?? \"dist\",\n base: options.base ?? \"/\",\n extensions: normalizeMarkdownExtensions(options.extensions),\n ssg: resolveSsgOptions(options.ssg),\n siteMaps: resolveSiteMapsOptions(options.siteMaps),\n publishState: resolvePublishStateOptions(options.publishState),\n permalinks: resolvePermalinksOptions(options.permalinks),\n cascade: resolveCascadeOptions(options.cascade),\n redirects: resolveRedirectsOptions(options.redirects),\n feeds: resolveFeedsOptions(options.feeds),\n taxonomies: resolveTaxonomiesOptions(options.taxonomies),\n versions: resolveVersionsOptions(options.versions),\n gfm: options.gfm ?? true,\n mdx: options.mdx,\n footnotes: options.footnotes ?? true,\n tables: options.tables ?? true,\n taskLists: options.taskLists ?? true,\n strikethrough: options.strikethrough ?? true,\n autolinks: options.autolinks ?? options.gfm ?? true,\n highlight: options.highlight ?? false,\n codeAnnotations: resolveCodeAnnotationsOptions(options.codeAnnotations),\n wikiLinks: resolveWikiLinkOptions(options.wikiLinks, options.base ?? \"/\"),\n emojiShortcodes: resolveEmojiShortcodeOptions(options.emojiShortcodes),\n attrs: resolveAttrsOptions(options.attrs),\n badges: resolveBadgeOptions(options.badges),\n containers: resolveContainerOptions(options.containers),\n images: resolveImageOptions(options.images),\n codeImports: resolveCodeImportOptions(options.codeImports),\n includes: resolveIncludeOptions(options.includes),\n cards: resolveCardOptions(options.cards),\n steps: resolveStepsOptions(options.steps),\n fileTree: resolveFileTreeOptions(options.fileTree),\n sanitize: resolveSanitizeOptions(options.sanitize),\n editThisPage: resolveEditThisPageOptions(options.editThisPage),\n cjkEmphasis: options.cjkEmphasis ?? false,\n codeBlockLint: resolveCodeBlockLintOptions(options.codeBlockLint),\n codeBlockTypecheck: resolveCodeBlockTypecheckOptions(options.codeBlockTypecheck),\n docsTests: resolveDocsTestOptions(options.docsTests),\n mermaid: options.mermaid ?? false,\n math: resolveMathOptions(options.math),\n frontmatter: options.frontmatter ?? true,\n toc: options.toc ?? true,\n tocMaxDepth: options.tocMaxDepth ?? 3,\n ogImage: options.ogImage ?? false,\n ogImageOptions: resolveOgImageOptions(options.ogImageOptions),\n transformers: options.transformers ?? [],\n docs: resolveDocsOptions(options.docs),\n search: resolveSearchOptions(options.search),\n collections: resolveCollectionsOptions(options.collections),\n ogViewer: options.ogViewer ?? true,\n embeds: resolveBuiltinEmbedOptions(options.embeds),\n i18n: resolveI18nOptions(options.i18n),\n };\n}\n\nexport function resolveBuiltinEmbedOptions(\n options: OxContentOptions[\"embeds\"],\n): ResolvedOptions[\"embeds\"] {\n if (options === false) {\n return {\n github: false,\n openGraph: false,\n pm: false,\n spotify: false,\n stackBlitz: false,\n twitter: false,\n bluesky: false,\n webContainer: false,\n };\n }\n\n return {\n github: resolveSingleEmbedOptions(options?.github),\n openGraph: resolveSingleEmbedOptions(options?.openGraph),\n pm: resolvePmOptions(options?.pm),\n spotify: options?.spotify === true,\n stackBlitz: options?.stackBlitz === true,\n twitter: resolveTwitterEmbedOptions(options?.twitter),\n bluesky: options?.bluesky === true,\n webContainer: options?.webContainer === true,\n };\n}\n\nfunction resolveSingleEmbedOptions<T extends object>(options: boolean | T | undefined): T | false {\n if (options === false) return false;\n if (options === true || options === undefined) return {} as T;\n return options;\n}\n\nfunction resolveTwitterEmbedOptions(\n options: boolean | TwitterEmbedOptions | undefined,\n): TwitterEmbedOptions | false {\n if (options === false || options === undefined) return false;\n if (options === true) return {};\n return options;\n}\n\nfunction resolvePmOptions(\n options: boolean | BuiltinPmOptions | undefined,\n): BuiltinPmOptions | false {\n if (options === false || options === undefined) return false;\n if (options === true) return {};\n return options;\n}\n\nfunction resolveWikiLinkOptions(\n options: OxContentOptions[\"wikiLinks\"],\n baseUrl: string,\n): ResolvedOptions[\"wikiLinks\"] {\n if (!options) return { enabled: false, baseUrl };\n if (options === true) return { enabled: true, baseUrl };\n return { enabled: true, baseUrl: options.baseUrl ?? baseUrl };\n}\n\nfunction resolveEmojiShortcodeOptions(\n options: OxContentOptions[\"emojiShortcodes\"],\n): ResolvedOptions[\"emojiShortcodes\"] {\n if (!options) return { enabled: false, custom: {} };\n if (options === true) return { enabled: true, custom: {} };\n return { enabled: true, custom: options.custom ?? {} };\n}\n\nexport function resolveMathOptions(options: OxContentOptions[\"math\"]): ResolvedOptions[\"math\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n\nfunction resolveAttrsOptions(options: OxContentOptions[\"attrs\"]): ResolvedOptions[\"attrs\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n\nexport function resolveBadgeOptions(\n options: OxContentOptions[\"badges\"],\n): ResolvedOptions[\"badges\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n\nfunction resolveContainerOptions(\n options: OxContentOptions[\"containers\"],\n): ResolvedOptions[\"containers\"] {\n if (!options) return { enabled: false, types: {} };\n if (options === true) return { enabled: true, types: {} };\n return { enabled: options.enabled ?? true, types: options.types ?? {} };\n}\n\nfunction resolveCodeImportOptions(\n options: OxContentOptions[\"codeImports\"],\n): ResolvedOptions[\"codeImports\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: true, rootDir: options.rootDir };\n}\n\nexport { resolveCardOptions } from \"./card-options\";\nexport { resolveIncludeOptions } from \"./include-options\";\nexport { resolveStepsOptions } from \"./step-options\";\nexport { resolveFileTreeOptions } from \"./file-tree-options\";\n\nfunction resolveSanitizeOptions(\n options: OxContentOptions[\"sanitize\"],\n): ResolvedOptions[\"sanitize\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return {\n enabled: true,\n allowedTags: options.allowedTags,\n allowedAttributes: options.allowedAttributes,\n allowedUrlSchemes: options.allowedUrlSchemes,\n };\n}\n\nfunction resolveEditThisPageOptions(\n options: OxContentOptions[\"editThisPage\"],\n): ResolvedOptions[\"editThisPage\"] {\n if (!options) return { enabled: false, branch: \"main\", label: \"Edit this page\" };\n if (options === true) return { enabled: false, branch: \"main\", label: \"Edit this page\" };\n return {\n enabled: Boolean(options.repoUrl),\n repoUrl: options.repoUrl,\n branch: options.branch ?? \"main\",\n rootDir: options.rootDir,\n label: options.label ?? \"Edit this page\",\n };\n}\n\nfunction resolveCodeBlockLintOptions(\n options: OxContentOptions[\"codeBlockLint\"],\n): ResolvedOptions[\"codeBlockLint\"] {\n if (!options) {\n return { enabled: false, requireLanguage: false, trailingSpaces: true, mode: \"warn\" };\n }\n if (options === true) {\n return { enabled: true, requireLanguage: false, trailingSpaces: true, mode: \"warn\" };\n }\n return {\n enabled: true,\n languages: options.languages,\n requireLanguage: options.requireLanguage ?? false,\n trailingSpaces: options.trailingSpaces ?? true,\n mode: options.mode ?? \"warn\",\n };\n}\n\nfunction resolveCodeBlockTypecheckOptions(\n options: OxContentOptions[\"codeBlockTypecheck\"],\n): ResolvedOptions[\"codeBlockTypecheck\"] {\n if (!options) {\n return {\n enabled: false,\n languages: [\"ts\", \"tsx\"],\n requireMeta: true,\n tsgoCommand: \"tsgo\",\n mode: \"warn\",\n };\n }\n if (options === true) {\n return {\n enabled: true,\n languages: [\"ts\", \"tsx\"],\n requireMeta: true,\n tsgoCommand: \"tsgo\",\n mode: \"warn\",\n };\n }\n return {\n enabled: true,\n languages: options.languages ?? [\"ts\", \"tsx\"],\n requireMeta: options.requireMeta ?? true,\n tsgoCommand: options.tsgoCommand ?? \"tsgo\",\n mode: options.mode ?? \"warn\",\n };\n}\n\nfunction resolveDocsTestOptions(\n options: OxContentOptions[\"docsTests\"],\n): ResolvedOptions[\"docsTests\"] {\n if (!options) return { enabled: false, languages: [\"js\", \"jsx\", \"ts\", \"tsx\"], requireMeta: true };\n if (options === true) {\n return { enabled: true, languages: [\"js\", \"jsx\", \"ts\", \"tsx\"], requireMeta: true };\n }\n return {\n enabled: true,\n languages: options.languages ?? [\"js\", \"jsx\", \"ts\", \"tsx\"],\n requireMeta: options.requireMeta ?? true,\n };\n}\n\nfunction resolveCodeAnnotationsOptions(\n options: OxContentOptions[\"codeAnnotations\"],\n): ResolvedOptions[\"codeAnnotations\"] {\n if (!options) {\n return {\n enabled: false,\n notation: \"attribute\",\n metaKey: \"annotate\",\n defaultLineNumbers: false,\n };\n }\n\n if (options === true) {\n return {\n enabled: true,\n notation: \"attribute\",\n metaKey: \"annotate\",\n defaultLineNumbers: false,\n };\n }\n\n return {\n enabled: true,\n notation: options.notation ?? \"attribute\",\n metaKey: options.metaKey ?? \"annotate\",\n defaultLineNumbers: options.defaultLineNumbers ?? false,\n };\n}\n\n/**\n * Generates virtual module content.\n */\nexport function generateVirtualModule(path: string, options: ResolvedOptions): string {\n if (path === \"config\") {\n return `export default ${JSON.stringify(options)};`;\n }\n\n if (path === \"runtime\") {\n const base = normalizeRuntimeBase(options.base);\n return `\n export const base = ${JSON.stringify(base)};\n export const runtimeConfig = { base };\n\n export function isExternalUrl(value) {\n return /^(?:https?:)?\\\\/\\\\//i.test(value) || /^(?:mailto|tel):/i.test(value);\n }\n\n export function withBase(pathname = \"\") {\n const value = String(pathname);\n if (!value || value === \"/\") return base;\n if (value.startsWith(\"#\") || isExternalUrl(value)) return value;\n return base + (value.startsWith(\"/\") ? value.slice(1) : value);\n }\n\n export function withoutBase(pathname = \"\") {\n const value = String(pathname);\n if (base === \"/\" || value.startsWith(\"#\") || isExternalUrl(value)) return value;\n const bareBase = base.slice(0, -1);\n if (value === bareBase) return \"/\";\n if (value.startsWith(base)) return \"/\" + value.slice(base.length);\n return value;\n }\n\n export function useMarkdown() {\n return {\n base,\n withBase,\n withoutBase,\n render: (content) => {\n return content;\n },\n };\n }\n `;\n }\n\n return \"export default {};\";\n}\n\nfunction normalizeRuntimeBase(base: string): string {\n const trimmed = base.trim();\n if (!trimmed || trimmed === \"/\") return \"/\";\n const withLeading = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n return withLeading.endsWith(\"/\") ? withLeading : `${withLeading}/`;\n}\n\n// Re-export types and utilities\nexport { createMarkdownEnvironment } from \"./environment\";\nexport {\n IncrementalMarkdownParser,\n IncrementalMarkdownRenderer,\n createIncrementalMarkdownParser,\n createIncrementalMarkdownRenderer,\n renderMarkdownStream,\n type IncrementalMarkdownParseAppendOptions,\n type IncrementalMarkdownParseResult,\n type IncrementalMarkdownParserOptions,\n type IncrementalMarkdownRenderAppendOptions,\n type IncrementalMarkdownRenderResult,\n type IncrementalMarkdownRendererOptions,\n type MarkdownChunkSource,\n} from \"./incremental\";\nexport { transformMarkdown } from \"./transform\";\nexport { resolveImageOptions } from \"./resolve-image-options\";\nexport {\n createFrameworkMarkdownOptions,\n escapeSvelteMarkup,\n renderHtmlToFrameworkCode,\n renderHtmlToReactCreateElement,\n renderHtmlToReactComponent,\n renderHtmlToSvelteComponent,\n renderHtmlToVueComponent,\n renderHtmlToVueH,\n type FrameworkCodegenMode,\n type FrameworkCodegenTarget,\n type FrameworkComponentIsland,\n type FrameworkMarkdownOptions,\n type FrameworkRenderTarget,\n type FrameworkTransformData,\n} from \"./framework\";\nexport {\n extractCodeBlocks,\n extractDocsTests,\n lintCodeBlocks,\n typecheckCodeBlocks,\n type CodeBlockDiagnostic,\n type ExtractedCodeBlock,\n type TypecheckCodeBlockOptions,\n} from \"./code-blocks\";\nexport {\n collectDocsTests,\n DocsTestRunError,\n runDocsTests,\n writeDocsTestFiles,\n type CollectedDocsTest,\n type DocsTestFileOptions,\n type DocsTestHarnessOptions,\n type DocsTestRunResult,\n type DocsTestSource,\n type DocsTestWriteResult,\n type RunDocsTestsOptions,\n type WrittenDocsTestFile,\n} from \"./docs-tests\";\nexport { extractDocs, generateMarkdown, writeDocs, resolveDocsOptions } from \"./docs\";\nexport { lintMarkdown, lintMarkdownAsync } from \"./lint\";\nexport { lintMarkdownFile, lintMarkdownFiles, shouldLintMarkdownFile } from \"./lint-files\";\nexport type {\n MarkdownLintDiagnostic,\n MarkdownLintDictionaryOptions,\n MarkdownLintLanguage,\n MarkdownLintOptions,\n MarkdownLintResult,\n MarkdownLintRuleOptions,\n MarkdownLintSeverity,\n MarkdownLintStandardDictionaryOptions,\n} from \"./lint\";\nexport type {\n MarkdownLintFileDiagnostic as MarkdownLintBatchDiagnostic,\n MarkdownLintFileDiagnostic,\n MarkdownLintFileOptions,\n MarkdownLintFileResult,\n MarkdownLintFilesResult,\n MarkdownLintFileOptions as MarkdownLintProjectOptions,\n} from \"./lint-files\";\nexport { buildSsg, resolveSsgOptions, DEFAULT_HTML_TEMPLATE } from \"./ssg\";\nexport { resolveNotFoundOptions } from \"./not-found\";\nexport { resolveSiteMapsOptions } from \"./site-maps\";\nexport {\n classifyPublishState,\n resolvePublishStateOptions,\n partitionPublishedPages,\n} from \"./publish-state\";\nexport { resolvePermalinksOptions, resolveCascadeOptions } from \"./permalinks\";\nexport { resolveRedirectsOptions } from \"./redirects\";\nexport { resolveFeedsOptions } from \"./feeds\";\nexport { resolveTaxonomiesOptions } from \"./taxonomies\";\nexport { resolveVersionsOptions } from \"./versions\";\nexport { resolveTeamOptions } from \"./team\";\nexport { resolveSearchOptions, buildSearchIndex, writeSearchIndex } from \"./search\";\nexport {\n buildCollectionManifest,\n defineCollection,\n defineCollections,\n generateCollectionsVirtualModule,\n resolveCollectionsOptions,\n} from \"./collections\";\nexport {\n DEFAULT_MARKDOWN_EXTENSIONS,\n normalizeMarkdownExtensions,\n isMarkdownFilePath,\n stripMarkdownExtension,\n} from \"./markdown\";\nexport { defineTheme, defaultTheme, mergeThemes, resolveTheme } from \"./theme\";\nexport {\n fromVitePressConfig,\n generateVitePressMigrationConfig,\n convertVitePressSidebar,\n convertVitePressNav,\n normalizeVitePressFrontmatter,\n} from \"./vitepress\";\nexport type {\n GenerateVitePressMigrationConfigOptions,\n VitePressConfig,\n VitePressThemeConfig,\n VitePressSidebar,\n VitePressSidebarItem,\n VitePressNavItem,\n VitePressSocialLink,\n VitePressFooter,\n VitePressLogo,\n} from \"./vitepress\";\nexport type {\n ThemeConfig,\n ThemeColors,\n ThemeLayout,\n ThemeFonts,\n ThemeEntryPage,\n ThemeHeader,\n ThemeFooter,\n ThemeTokens,\n SocialLinks,\n ThemeEmbed,\n ResolvedThemeConfig,\n HeaderNavItem,\n LocaleLabel,\n SidebarItem,\n ThemeAnnouncement,\n} from \"./theme\";\nexport type { PageChromeFlags } from \"./header-chrome\";\nexport {\n parsePageChromeFlags,\n resolveHeaderNavItems,\n resolveLocaleLabel,\n resolvePageChromeOption,\n} from \"./header-chrome\";\nexport * from \"./types\";\n\n// JSX Runtime\nexport { jsx, jsxs, Fragment, renderToString, raw, when, each } from \"./jsx-html\";\nexport type { JSXNode, JSXChild, JSXProps, JSXElementType } from \"./jsx-html\";\n\n// Page Context\nexport {\n usePageProps,\n useSiteConfig,\n useRenderContext,\n useNav,\n useIsActive,\n setRenderContext,\n clearRenderContext,\n generateFrontmatterTypes,\n inferType,\n} from \"./page-context\";\nexport type {\n BasePageProps,\n PageProps,\n SiteConfig,\n NavGroup,\n NavItem,\n RenderContext,\n FrontmatterSchema,\n} from \"./page-context\";\n\n// Theme Renderer\nexport {\n renderPage,\n renderAllPages,\n generateTypes,\n DefaultTheme,\n createTheme,\n} from \"./theme-renderer\";\nexport type { ThemeComponent, ThemeProps, PageData, ThemeRenderOptions } from \"./theme-renderer\";\n\n// Built-in Plugins (No-JS First)\nexport {\n transformTabs,\n generateTabsCSS,\n transformYouTube,\n extractVideoId,\n transformGitHub,\n fetchRepoData,\n fetchGitHubSource,\n collectGitHubRepos,\n collectGitHubSources,\n prefetchGitHubRepos,\n prefetchGitHubSources,\n parseGitHubPermalink,\n parseGitHubLineRange,\n transformOgp,\n fetchOgpData,\n collectOgpUrls,\n prefetchOgpData,\n transformMermaidStatic,\n mermaidClientScript,\n transformAllPlugins,\n} from \"./plugins\";\nexport type {\n YouTubeOptions,\n GitHubRepoData,\n GitHubSourceData,\n GitHubSourceRef,\n GitHubLineRange,\n GitHubOptions,\n OgpData,\n OgpOptions,\n MermaidOptions,\n TransformAllOptions,\n} from \"./plugins\";\n\n// Island Architecture\nexport { transformIslands, hasIslands, extractIslandInfo, generateHydrationScript } from \"./island\";\nexport type { LoadStrategy, IslandInfo, ParseIslandsResult } from \"./island\";\n\n// OG Image\nexport { resolveOgImageOptions, generateOgImages } from \"./og-image\";\nexport { resolveI18nOptions, createI18nPlugin } from \"./i18n\";\nexport type {\n OgImageOptions as OgImagePluginOptions,\n ResolvedOgImageOptions,\n OgImageTemplateProps,\n OgImageTemplateFn,\n OgImagePageEntry,\n OgImageResult,\n OgBrowserSession,\n} from \"./og-image\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAa,8BAA8B;CAAC;CAAO;CAAa;AAAM;AAEtE,SAAgB,4BAA4B,YAA0C;CACpF,MAAM,SAAS,YAAY,SAAS,aAAa;CACjD,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,aAAuB,CAAC;CAE9B,KAAK,MAAM,aAAa,QAAQ;EAC9B,MAAM,QAAQ,UAAU,WAAW,GAAG,IAAI,YAAY,IAAI;EAC1D,MAAM,MAAM,MAAM,YAAY;EAC9B,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,WAAW,KAAK,KAAK;EACvB;CACF;CAEA,OAAO;AACT;AAEA,SAAgB,mBACd,UACA,aAAgC,6BACvB;CACT,MAAM,WAAW,SAAS,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,YAAY;CAClE,OAAO,WAAW,MAAM,cAAc,SAAS,SAAS,UAAU,YAAY,CAAC,CAAC;AAClF;;AAGA,SAAgB,cAAc,UAA2B;CAEvD,OADiB,SAAS,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,EACpC,CAAC,YAAY,CAAC,CAAC,SAAS,MAAM;AAC/C;;AAGA,SAAgB,sBAAsB,UAAkB,YAA+B;CACrF,OAAO,cAAc,cAAc,QAAQ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AoB;CACtB;CAGF,IAAI,YAAY,MACd,OAAO;EACL,SAAS;EACT,UAAU;EACV,SAAS;EACT,oBAAoB;CACtB;CAGF,OAAO;EACL,SAAS;EACT,UAAU,QAAQ,YAAY;EAC9B,SAAS,QAAQ,WAAW;EAC5B,oBAAoB,QAAQ,sBAAsB;CACpD;AACF;;;;AAKA,SAAgB,sBAAsB,QAAc,SAAkC;CACpF,IAAIE,WAAS,UACX,OAAO,kBAAkB,KAAK,UAAU,OAAO,EAAE;CAGnD,IAAIA,WAAS,WAAW;EACtB,MAAM,OAAO,qBAAqB,QAAQ,IAAI;EAC9C,OAAO;4BACiB,KAAK,UAAU,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkC/C;CAEA,OAAO;AACT;AAEA,SAAS,qBAAqB,MAAsB;CAClD,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,WAAW,YAAY,KAAK,OAAO;CACxC,MAAM,cAAc,QAAQ,WAAW,GAAG,IAAI,UAAU,IAAI;CAC5D,OAAO,YAAY,SAAS,GAAG,IAAI,cAAc,GAAG,YAAY;AAClE"}
1
+ {"version":3,"file":"index.cjs","names":["importNapiModuleSync","rehypeParse","interopDefault","rehypeParsePlugin","rehypeStringify","rehypeStringifyPlugin","importNapiModule","join","dirname","existsSync","createRequire","decodeHtmlAttr","join","dirname","createRequire","importNapiModule","getTabGroupCounter","importNapiModule","path","access","mkdir","writeFile","readFile","escapeHtml","escapeAttribute","resolveTwitterEmbedOptions","path","importNapiModule","defaultOptions","Buffer","defaultOptions","getAttribute","createFallbackCard","rehypeParse","interopDefault","rehypeParsePlugin","rehypeStringify","rehypeStringifyPlugin","createFallbackCard","defaultOptions","rehypeParse","interopDefault","rehypeParsePlugin","rehypeStringify","rehypeStringifyPlugin","getAttribute","promisify","execFile","importNapiModule","mkdtemp","join","tmpdir","writeFile","rm","mkdtemp","join","tmpdir","writeFile","rm","DEFAULT_LANGUAGES","importNapiModule","importNapiModule","importNapiModuleSync","readFileSync","path","escapeHtml","fs","join","mkdir","copyFile","cp","resolve","sep","relative","extname","interopDefault","rehypeParsePlugin","rehypeStringifyPlugin","resolveLocaleLabel","raw","renderToString","join","mkdir","dirname","writeFile","escapeHtml","MISSING_SITE_URL","hasSiteUrl","fs","path","escapeXml","importNapiModuleSync","normalizeUrlPath","normalizeUrlPath","importNapiModuleSync","path","normalizePath","fs","path","escapeHtml","path","importNapiModule","path","MISSING_SITE_URL","DEFAULT_FORMATS","normalizeFormats","hasSiteUrl","fs","path","dateField","fs","path","escapeAttribute","listItem","siteHref","escapeHtml","containedPath","path","HOSTILE_TERM","siteHref","containedPath","termsFromValue","createHash","escapeHtml","siteHref","containedPath","path","path","siteHref","containedPath","siteHref","fs","importNapiModuleSync","path","importNapiModuleSync","path","oxContent","importNapiModule","importNapiModuleSync","path","siteHref","fs","inflateSync","deflateSync","path","fs","isInsideRoot","createHash","isInsideRoot","path","resolveTheme","resolvePageChromeOption","extractTitle","importNapiModuleSync","importNapiModule","themeToNapi","fs","getUrlPath","resolveSiteName","normalizeVitePressFrontmatter","parsePageChromeFlags","fs","renderPage","normalizeVitePressFrontmatter","extractTitle","getUrlPath","parsePageChromeFlags","normalizeVitePressFrontmatter","importNapiModule","#native","#includePendingAst","#completeInline","importNapiModuleSync","#renderPending","decodeHtmlAttr","isMapRegistry","importNapiModule","path","fs","path","importNapiModuleSync","path","normalizePath","fs","spawn","require","createRequire","createEmptyLintResult","path","fs","path"],"sources":["../src/markdown.ts","../src/environment.ts","../src/highlight-native.ts","../src/highlight.ts","../src/plugins/mermaid.ts","../src/plugins/math.ts","../src/plugins/pm.ts","../src/plugins/youtube.ts","../src/plugins/twitter/url.ts","../src/plugins/twitter/fetch.ts","../src/plugins/twitter/render.ts","../src/plugins/twitter/transform.ts","../src/plugins/media.ts","../src/plugins/github/validation.ts","../src/plugins/github/source.ts","../src/plugins/github/types.ts","../src/plugins/github/api.ts","../src/plugins/github/attributes.ts","../src/plugins/github/fallback-card.ts","../src/plugins/github/repo-card.ts","../src/plugins/github/source-card.ts","../src/plugins/github/transform.ts","../src/plugins/github.ts","../src/plugins/ogp.ts","../src/plugins/index.ts","../src/plugins/mermaid-protect.ts","../src/code-blocks.ts","../src/typed-hover-generate.ts","../src/typed-hover.ts","../src/file-tree-options.ts","../src/transform.ts","../src/docs.ts","../src/og-image/renderer.ts","../src/og-image/browser.ts","../src/og-image/template.ts","../src/og-image/cache.ts","../src/og-image/index.ts","../src/plugins/math-assets.ts","../src/island/parse.ts","../src/locale-switcher.ts","../src/locale-nav.ts","../src/page-context.ts","../src/theme-renderer.ts","../src/site-maps.ts","../src/publish-state.ts","../src/permalinks.ts","../src/apply-permalinks.ts","../src/redirects.ts","../src/not-found.ts","../src/collections-runtime.ts","../src/collections.ts","../src/feed-format.ts","../src/feeds.ts","../src/pwa.ts","../src/taxonomies-html.ts","../src/taxonomies.ts","../src/team.ts","../src/contributors.ts","../src/blog-options.ts","../src/blog-reading.ts","../src/blog-html.ts","../src/blog-posts.ts","../src/blog-pages.ts","../src/section-index-html.ts","../src/section-index-paths.ts","../src/section-index.ts","../src/search-provider.ts","../src/search.ts","../src/versions-html.ts","../src/versions.ts","../src/resources-jpeg.ts","../src/resources-image.ts","../src/resources-process.ts","../src/resources.ts","../src/version-navigation.ts","../src/ssg.ts","../src/dev-server.ts","../src/og-viewer.ts","../src/i18n.ts","../src/resolve-image-options.ts","../src/card-options.ts","../src/include-options.ts","../src/step-options.ts","../src/incremental.ts","../src/mdx-islands.ts","../src/document-imports.ts","../src/document-islands.ts","../src/island-codegen.ts","../src/island-ssr.ts","../src/framework.ts","../src/docs-tests.ts","../src/lint.ts","../src/lint-files.ts","../src/index.ts"],"sourcesContent":["import * as path from \"path\";\n\nexport const DEFAULT_MARKDOWN_EXTENSIONS = [\".md\", \".markdown\", \".mdx\"] as const;\n\nexport function normalizeMarkdownExtensions(extensions?: readonly string[]): string[] {\n const values = extensions?.length ? extensions : DEFAULT_MARKDOWN_EXTENSIONS;\n const seen = new Set<string>();\n const normalized: string[] = [];\n\n for (const extension of values) {\n const value = extension.startsWith(\".\") ? extension : `.${extension}`;\n const key = value.toLowerCase();\n if (!seen.has(key)) {\n seen.add(key);\n normalized.push(value);\n }\n }\n\n return normalized;\n}\n\nexport function isMarkdownFilePath(\n filePath: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n): boolean {\n const pathname = filePath.split(\"?\")[0].split(\"#\")[0].toLowerCase();\n return extensions.some((extension) => pathname.endsWith(extension.toLowerCase()));\n}\n\n/** Returns true when a resource id points at an MDX source file. */\nexport function isMdxFilePath(filePath: string): boolean {\n const pathname = filePath.split(\"?\")[0].split(\"#\")[0];\n return pathname.toLowerCase().endsWith(\".mdx\");\n}\n\n/** Explicit configuration wins; otherwise MDX follows the source extension. */\nexport function resolveMdxForFilePath(filePath: string, configured?: boolean): boolean {\n return configured ?? isMdxFilePath(filePath);\n}\n\nexport function stripMarkdownExtension(\n filePath: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n): string {\n const match = [...extensions]\n .sort((left, right) => right.length - left.length)\n .find((extension) => filePath.toLowerCase().endsWith(extension.toLowerCase()));\n\n return match ? filePath.slice(0, -match.length) : filePath;\n}\n\nexport function markdownGlobPattern(srcDir: string, extensions: readonly string[]): string {\n const suffixes = extensions.map((extension) => extension.replace(/^\\./, \"\"));\n if (suffixes.length === 1) {\n return path.join(srcDir, `**/*.${suffixes[0]}`);\n }\n return path.join(srcDir, `**/*.{${suffixes.join(\",\")}}`);\n}\n","/**\n * Vite Environment API integration for Ox Content.\n *\n * Creates a dedicated environment for Markdown processing,\n * enabling SSG-style rendering with separate client/server contexts.\n */\n\nimport type { EnvironmentOptions } from \"vite\";\nimport type { ResolvedOptions } from \"./types\";\nimport { isMarkdownFilePath } from \"./markdown\";\n\n/**\n * Creates the Markdown processing environment configuration.\n *\n * This environment is used for:\n * - Server-side rendering of Markdown files\n * - Static site generation\n * - Pre-rendering at build time\n *\n * @example\n * ```ts\n * // In your vite.config.ts\n * export default defineConfig({\n * environments: {\n * markdown: createMarkdownEnvironment({\n * srcDir: 'content',\n * gfm: true,\n * }),\n * },\n * });\n * ```\n */\nexport function createMarkdownEnvironment(options: ResolvedOptions): EnvironmentOptions {\n return {\n // Consumer type for this environment\n consumer: \"server\",\n\n // Build configuration\n build: {\n // Output to a separate directory\n outDir: `${options.outDir}/.markdown`,\n\n // Emit assets for SSG\n emitAssets: true,\n\n // Create manifest for asset tracking\n manifest: true,\n\n // SSR-like externalization\n rollupOptions: {\n external: [\n // Externalize Node.js built-ins\n /^node:/,\n // Externalize native modules\n /\\.node$/,\n ],\n },\n },\n\n // Resolve configuration\n resolve: {\n // Handle Markdown-like files\n extensions: options.extensions,\n\n // Conditions for module resolution\n conditions: [\"markdown\", \"node\", \"import\"],\n\n // Don't dedupe - each environment gets its own modules\n dedupe: [],\n },\n\n // Optimize dependencies\n optimizeDeps: {\n // Include ox-content dependencies\n include: [],\n // Exclude native modules\n exclude: [\"@ox-content/napi\"],\n },\n };\n}\n\n/**\n * Environment-specific module transformer.\n *\n * This is called during the transform phase to process\n * Markdown files within the environment context.\n */\nexport interface EnvironmentTransformContext {\n /**\n * Current environment name.\n */\n environment: string;\n\n /**\n * Whether we're in development mode.\n */\n isDev: boolean;\n\n /**\n * Whether this is a server-side render.\n */\n isSSR: boolean;\n\n /**\n * The resolved Vite config.\n */\n config: unknown;\n}\n\n/**\n * Creates environment-aware transform options.\n */\nexport function createTransformOptions(\n ctx: EnvironmentTransformContext,\n options: ResolvedOptions,\n): ResolvedOptions {\n return {\n ...options,\n // Adjust options based on environment\n highlight: ctx.isSSR ? options.highlight : false,\n ogImage: ctx.isSSR ? options.ogImage : false,\n };\n}\n\n/**\n * Runs pre-render for SSG.\n *\n * This function is called during build to pre-render all Markdown files.\n */\nexport async function prerender(\n files: string[],\n _options: ResolvedOptions,\n): Promise<Map<string, string>> {\n const results = new Map<string, string>();\n\n for (const file of files) {\n // In production, this would use the Ox Content parser\n // For now, we just mark the file as needing processing\n results.set(file, `/* Pre-rendered: ${file} */`);\n }\n\n return results;\n}\n\n/**\n * Environment plugin factory.\n *\n * Creates plugins specific to the Markdown environment.\n */\nexport function createEnvironmentPlugins(options: ResolvedOptions) {\n return [\n {\n name: \"ox-content:markdown-env\",\n\n // Only apply to markdown environment\n applyToEnvironment(name: string) {\n return name === \"markdown\";\n },\n\n // Transform within the environment\n transform(code: string, id: string) {\n if (!isMarkdownFilePath(id, options.extensions)) {\n return null;\n }\n\n // Environment-specific transformation\n return {\n code: `\n // Transformed in markdown environment\n ${code}\n `,\n };\n },\n },\n ];\n}\n","/**\n * The native tree-sitter highlighting path, plus the small hast helpers the\n * per-block walk uses when the document pass cannot read the markup.\n */\n\nimport type { Root, Element } from \"hast\";\n\nimport { importNapiModuleSync } from \"./napi\";\n\n/**\n * Extract text content from a hast node.\n */\nexport function getTextContent(node: Element | Root): string {\n let text = \"\";\n\n if (\"children\" in node) {\n for (const child of node.children) {\n if (child.type === \"text\") {\n text += child.value;\n } else if (child.type === \"element\") {\n text += getTextContent(child);\n }\n }\n }\n\n return text;\n}\n\nexport function normalizeClassName(className: unknown): string[] {\n if (Array.isArray(className)) {\n return className.filter((value): value is string => typeof value === \"string\");\n }\n\n if (typeof className === \"string\" && className) {\n return className.split(/\\s+/).filter(Boolean);\n }\n\n return [];\n}\n\n/**\n * Highlights with the native tree-sitter engine, or `null` when it has no\n * grammar for `lang`.\n *\n * It emits `--octc-shiki-*` markup (the `shiki` prefix is historical) so\n * theme-color packages keep working.\n */\nexport function highlightNatively(code: string, lang: string): string | null {\n try {\n return importNapiModuleSync().highlightCodeBlock(code, lang);\n } catch {\n return null;\n }\n}\n\n/**\n * Highlights every code block in a rendered document in one native call.\n *\n * Returns the rewritten HTML and the languages it declined. Pending languages\n * stay unhighlighted. Returns `null` when the native module is unavailable.\n */\nexport async function highlightDocumentNatively(html: string): Promise<NativeDocument | null> {\n try {\n return await importNapiModuleSync().highlightHtmlCodeBlocksAsync(html);\n } catch {\n return null;\n }\n}\n\n/** A block the native pass left unhighlighted (no grammar). */\nexport interface PendingBlock {\n language: string;\n source: string;\n}\n\n/** What {@link highlightDocumentNatively} produced for a page. */\nexport interface NativeDocument {\n html: string;\n /**\n * Languages of elements the native pass could not read. Non-empty means the\n * page has to be produced by the per-block walk instead.\n */\n skipped: string[];\n /** Well-formed blocks whose language has no native grammar, in order. */\n pending: PendingBlock[];\n}\n","/**\n * Syntax highlighting with the native tree-sitter engine.\n *\n * Markup keeps the historical `<pre class=\"shiki css-variables\">` wrapper and\n * `--octc-shiki-*` custom properties so theme-color packages keep working.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\nimport { interopDefault } from \"./interop\";\nimport {\n getTextContent,\n highlightDocumentNatively,\n highlightNatively,\n normalizeClassName,\n} from \"./highlight-native\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\n/**\n * Per-block walk used when the native document pass cannot read the markup.\n * Unknown languages stay as the original `<pre><code>`.\n */\nfunction rehypeNativeHighlight() {\n return (tree: Root) => {\n const highlightBlockCode = (codeElement: Element): Element | null => {\n let lang = \"text\";\n const originalCodeClasses = normalizeClassName(codeElement.properties?.className);\n\n const langClass = originalCodeClasses.find((value) => value.startsWith(\"language-\"));\n if (langClass) {\n lang = langClass.replace(\"language-\", \"\");\n }\n\n const highlighted = highlightNatively(getTextContent(codeElement), lang);\n if (!highlighted) {\n return null;\n }\n\n try {\n const parsed = unified().use(rehypeParse, { fragment: true }).parse(highlighted);\n\n if (parsed.children[0]?.type === \"element\") {\n const highlightedPre = parsed.children[0];\n highlightedPre.properties ??= {};\n highlightedPre.properties[\"data-language\"] = lang;\n return highlightedPre;\n }\n } catch {\n // If highlighting fails, keep the original\n }\n\n return null;\n };\n\n const highlightInlineCode = (codeElement: Element): Element | null => {\n const originalCodeClasses = normalizeClassName(codeElement.properties?.className);\n\n const langClass = originalCodeClasses.find((value) => value.startsWith(\"language-\"));\n if (!langClass) {\n return null;\n }\n\n const lang = langClass.replace(\"language-\", \"\");\n const highlighted = highlightNatively(getTextContent(codeElement), lang);\n if (!highlighted) {\n return null;\n }\n\n try {\n const parsed = unified().use(rehypeParse, { fragment: true }).parse(highlighted);\n\n if (parsed.children[0]?.type === \"element\") {\n const highlightedPre = parsed.children[0];\n const highlightedCode = highlightedPre.children.find(\n (child): child is Element => child.type === \"element\" && child.tagName === \"code\",\n );\n\n if (highlightedCode) {\n highlightedCode.properties ??= {};\n const highlightedClasses = normalizeClassName(highlightedCode.properties.className);\n highlightedCode.properties.className = [\n ...new Set([...originalCodeClasses, ...highlightedClasses, \"shiki-inline\"]),\n ];\n highlightedCode.properties[\"data-language\"] = lang;\n return highlightedCode;\n }\n }\n } catch {\n // If highlighting fails, keep the original\n }\n\n return null;\n };\n\n const visit = (node: Root | Element) => {\n if (!(\"children\" in node)) {\n return;\n }\n\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\" && child.tagName === \"pre\") {\n const codeElement = child.children.find(\n (c): c is Element => c.type === \"element\" && c.tagName === \"code\",\n );\n\n const alreadyHighlighted = normalizeClassName(child.properties?.className).includes(\n \"shiki\",\n );\n\n if (codeElement && !alreadyHighlighted) {\n const highlightedPre = highlightBlockCode(codeElement);\n if (highlightedPre) {\n node.children[i] = highlightedPre;\n }\n }\n } else if (child.type === \"element\" && child.tagName === \"code\") {\n const highlightedCode = highlightInlineCode(child);\n if (highlightedCode) {\n node.children[i] = highlightedCode;\n }\n } else if (child.type === \"element\") {\n visit(child);\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Apply native tree-sitter highlighting to HTML.\n *\n * Tries the document pass first. If that pass skips unreadable markup, falls\n * back to a native-only per-block walk. Languages with no native grammar stay\n * as the original `<pre><code>`.\n */\nexport async function highlightCode(html: string): Promise<string> {\n const native = await highlightDocumentNatively(html);\n if (native && native.skipped.length === 0) {\n return native.html;\n }\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeNativeHighlight)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n\n/**\n * Highlight every code block in a rendered page, preserving original classes\n * and per-line metadata when the native document pass cannot read the markup.\n */\nexport async function highlightPageHtml(\n html: string,\n mergeHighlightedCodeBlocks: (originalHtml: string, highlightedHtml: string) => string,\n): Promise<string> {\n const native = await highlightDocumentNatively(html);\n if (native && native.skipped.length === 0) {\n return native.html;\n }\n\n return mergeHighlightedCodeBlocks(html, await highlightCode(html));\n}\n","/**\n * Mermaid Plugin - Native Rust renderer via NAPI\n *\n * Renders mermaid code blocks to SVG using the native Rust renderer\n * via NAPI. Delegates to the NAPI `transformMermaid` function which\n * extracts mermaid code blocks from HTML and renders them using mmdc.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { importNapiModule } from \"../napi\";\n\nexport interface MermaidOptions {\n /**\n * Mermaid theme used by the CLI renderer.\n * @default 'neutral'\n */\n theme?: \"default\" | \"dark\" | \"forest\" | \"neutral\" | \"base\";\n}\n\n/** Cached NAPI bindings */\nlet napiBindings: {\n transformMermaid: (html: string, mmdcPath: string) => { html: string; errors: string[] };\n} | null = null;\n\nlet napiLoadAttempted = false;\n\nasync function loadNapi() {\n if (napiLoadAttempted) return napiBindings;\n napiLoadAttempted = true;\n try {\n const binding = (await importNapiModule()) as unknown as NonNullable<typeof napiBindings>;\n if (typeof binding.transformMermaid !== \"function\") {\n napiBindings = null;\n return null;\n }\n napiBindings = binding;\n return binding;\n } catch {\n napiBindings = null;\n return null;\n }\n}\n\nlet cachedMmdcPath: string | null | undefined;\nlet missingMmdcWarned = false;\n\nfunction resolveMmdcPath(): string | null {\n if (cachedMmdcPath !== undefined) return cachedMmdcPath;\n\n for (const resolver of createMmdcResolvers()) {\n try {\n const entry = resolver.resolve(\"@mermaid-js/mermaid-cli\");\n const cliPath = join(dirname(entry), \"cli.js\");\n if (existsSync(cliPath)) {\n cachedMmdcPath = cliPath;\n return cachedMmdcPath;\n }\n } catch {\n // Try the next resolver.\n }\n }\n\n // Fallback: node_modules/.bin/mmdc relative to cwd\n const binPath = join(process.cwd(), \"node_modules\", \".bin\", \"mmdc\");\n if (existsSync(binPath)) {\n cachedMmdcPath = binPath;\n return cachedMmdcPath;\n }\n\n cachedMmdcPath = null;\n return null;\n}\n\nfunction createMmdcResolvers(): NodeJS.Require[] {\n // Resolve from the consumer first, then from this package. The second lookup\n // matters under pnpm strict linking: docs apps can depend on the plugin\n // without directly depending on mermaid-cli.\n const consumerRequire = createRequire(join(process.cwd(), \"noop.js\"));\n const resolvers = [consumerRequire];\n\n try {\n resolvers.push(createRequire(consumerRequire.resolve(\"@ox-content/vite-plugin\")));\n } catch {\n // If the package is used from source without its package name resolvable,\n // the consumer resolver and bin fallback still cover direct installs.\n }\n\n return resolvers;\n}\n\n/**\n * Transforms mermaid code blocks in HTML to rendered SVG diagrams.\n * Uses the native Rust NAPI transformMermaid function.\n */\nexport async function transformMermaidStatic(\n html: string,\n _options?: MermaidOptions,\n): Promise<string> {\n const napi = await loadNapi();\n if (!napi) {\n return html;\n }\n\n const mmdcPath = resolveMmdcPath();\n if (!mmdcPath) {\n warnMissingMmdcOnce();\n return html;\n }\n\n try {\n const result = napi.transformMermaid(html, mmdcPath);\n for (const error of result.errors) {\n console.warn(\"[ox-content] Mermaid render error:\", error);\n }\n return result.html;\n } catch (err) {\n console.warn(\"[ox-content] Mermaid transform error:\", err);\n return html;\n }\n}\n\nfunction warnMissingMmdcOnce(): void {\n if (missingMmdcWarned) {\n return;\n }\n\n missingMmdcWarned = true;\n console.warn(\"[ox-content] mmdc not found; skipping Mermaid rendering.\");\n}\n\n/**\n * @deprecated No longer used. Mermaid rendering is now done at build time via NAPI.\n */\nexport const mermaidClientScript = \"\";\n","/**\n * Build-time KaTeX rendering for opt-in `$…$` / `$$…$$` math.\n *\n * KaTeX is an optional peer. Sites that never enable `math` do not install it,\n * and the published plugin does not bundle or depend on it.\n */\n\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\n\nexport const KATEX_ASSET_DIR = \"__ox_katex__\";\n\ntype KatexModule = {\n renderToString(\n tex: string,\n options?: {\n displayMode?: boolean;\n throwOnError?: boolean;\n trust?: boolean;\n output?: \"html\" | \"mathml\" | \"htmlAndMathml\";\n },\n ): string;\n};\n\nconst MATH_TAG =\n /<(span|div) class=\"ox-math ox-math-(inline|block)\" data-ox-tex=\"([^\"]*)\">[\\s\\S]*?<\\/\\1>/g;\n\nlet missingWarned = false;\n\n/**\n * Replaces rust `ox-math` placeholders with static KaTeX HTML.\n * Leaves the escaped TeX fallback when `katex` is not installed.\n */\nexport async function renderKatexMath(html: string): Promise<string> {\n if (!html.includes(\"data-ox-tex\")) {\n return html;\n }\n\n const katex = loadKatex();\n if (!katex) {\n warnMissingKatexOnce();\n return html;\n }\n\n return html.replace(MATH_TAG, (_match, tag: string, kind: string, encoded: string) => {\n const rendered = katex.renderToString(decodeHtmlAttr(encoded), {\n displayMode: kind === \"block\",\n throwOnError: false,\n trust: false,\n output: \"htmlAndMathml\",\n });\n return `<${tag} class=\"ox-math ox-math-${kind}\">${rendered}</${tag}>`;\n });\n}\n\n/** Directory that contains `katex.min.css` and `fonts/`, or `null`. */\nexport function resolveKatexDist(): string | null {\n for (const resolver of createKatexResolvers()) {\n try {\n return join(dirname(resolver.resolve(\"katex/package.json\")), \"dist\");\n } catch {\n // Try the next resolver.\n }\n }\n return null;\n}\n\nexport function resetKatexWarningForTests(): void {\n missingWarned = false;\n}\n\nfunction loadKatex(): KatexModule | null {\n for (const resolver of createKatexResolvers()) {\n try {\n const loaded = resolver(resolver.resolve(\"katex\")) as {\n default?: KatexModule;\n } & KatexModule;\n if (typeof loaded.renderToString === \"function\") {\n return loaded;\n }\n if (loaded.default && typeof loaded.default.renderToString === \"function\") {\n return loaded.default;\n }\n } catch {\n // Try the next resolver.\n }\n }\n return null;\n}\n\nfunction createKatexResolvers(): NodeJS.Require[] {\n const consumerRequire = createRequire(join(process.cwd(), \"noop.js\"));\n const resolvers = [consumerRequire];\n try {\n resolvers.push(createRequire(consumerRequire.resolve(\"@ox-content/vite-plugin\")));\n } catch {\n // Source checkouts still resolve from this file and from cwd.\n }\n resolvers.push(createRequire(import.meta.url));\n return resolvers;\n}\n\nfunction decodeHtmlAttr(value: string): string {\n return value\n .replaceAll(\"&quot;\", '\"')\n .replaceAll(\"&#39;\", \"'\")\n .replaceAll(\"&lt;\", \"<\")\n .replaceAll(\"&gt;\", \">\")\n .replaceAll(\"&amp;\", \"&\");\n}\n\nfunction warnMissingKatexOnce(): void {\n if (missingWarned) {\n return;\n }\n missingWarned = true;\n console.warn(\n \"[ox-content] math is enabled but `katex` was not found. \" +\n \"Install it with `npm i -D katex` to render LaTeX; \" +\n \"escaped TeX placeholders are left as-is.\",\n );\n}\n","/**\n * Package Manager Tabs Plugin\n *\n * Transforms <pm>npm install …</pm> blocks into a tab group with one tab per\n * package manager (npm/pnpm/yarn/bun). The single npm-style command is converted\n * to each package manager's equivalent natively in Rust (`transformPmEmbeds` in\n * @ox-content/napi), and the result reuses the same `ox-tabs` widget markup as\n * the generic `<tabs>` plugin so styling and keyboard navigation are consistent.\n *\n * Syncing is opt-in (off by default): when enabled, the rendered group carries a\n * `data-ox-tab-group=\"pkg-manager\"` attribute so the client runtime can keep\n * every package-manager group on the page in sync via localStorage.\n *\n * Package-manager groups share the tab-group counter with the `<tabs>` plugin so\n * `data-group` ids (and the CSS produced by `generateTabsCSS`) stay unique.\n */\n\nimport { importNapiModule } from \"../napi\";\nimport { getTabGroupCounter, setTabGroupCounter } from \"./tabs\";\n\n/** Options for {@link transformPm}. */\nexport interface PmOptions {\n /**\n * Enable opt-in synced package-manager tab groups. When `true`, a\n * `data-ox-tab-group=\"pkg-manager\"` attribute is emitted so the client runtime\n * syncs the active package manager across every pm group on the page and\n * persists the choice in localStorage.\n * @default false\n */\n sync?: boolean;\n}\n\n/**\n * Transform `<pm>` package-manager blocks in HTML into install tabs.\n *\n * @param html - Rendered HTML potentially containing `<pm>` blocks.\n * @param options - Package-manager tab options (syncing is opt-in).\n * @returns The rewritten HTML.\n */\nexport async function transformPm(html: string, options?: PmOptions): Promise<string> {\n // Cheap marker check: skip the NAPI call entirely when there's no `<pm>`\n // element. The Rust side guards the same way, but short-circuiting here avoids\n // marshalling the whole document across the boundary.\n if (!/<pm[\\s/>]/i.test(html)) {\n return html;\n }\n\n const mod = await importNapiModule();\n const startGroup = getTabGroupCounter();\n const result = mod.transformPmEmbeds(html, startGroup, {\n sync: options?.sync ?? false,\n });\n setTabGroupCounter(startGroup + result.groupCount);\n return result.html;\n}\n","/**\n * YouTube Plugin - Privacy-enhanced iframe embedding\n *\n * Transforms <YouTube> components into responsive iframe embeds using\n * youtube-nocookie.com for enhanced privacy.\n *\n * The HTML rewrite is performed in Rust (`transformYoutubeEmbeds` in\n * @ox-content/napi), replacing the previous rehype parse/stringify\n * round-trip. This module keeps the public TS surface and a cheap marker\n * check so pages without a `<youtube>` element never cross the NAPI boundary.\n */\n\nimport { importNapiModule } from \"../napi\";\n\nexport interface YouTubeOptions {\n /**\n * Use privacy-enhanced mode (`youtube-nocookie.com`).\n * @default true\n */\n privacyEnhanced?: boolean;\n\n /**\n * Default iframe aspect ratio.\n * @default '16/9'\n */\n aspectRatio?: string;\n\n /**\n * Allow fullscreen playback.\n * @default true\n */\n allowFullscreen?: boolean;\n\n /**\n * Lazy load the iframe.\n * @default true\n */\n lazyLoad?: boolean;\n}\n\n/**\n * Extract YouTube video ID from various URL formats.\n */\nexport function extractVideoId(input: string): string | null {\n // Already a video ID (11 characters, alphanumeric + _ -)\n if (/^[a-zA-Z0-9_-]{11}$/.test(input)) {\n return input;\n }\n\n // Full URL patterns\n const patterns = [\n /(?:youtube\\.com\\/watch\\?v=|youtu\\.be\\/|youtube\\.com\\/embed\\/|youtube\\.com\\/v\\/)([a-zA-Z0-9_-]{11})/,\n /youtube\\.com\\/shorts\\/([a-zA-Z0-9_-]{11})/,\n ];\n\n for (const pattern of patterns) {\n const match = input.match(pattern);\n if (match) return match[1];\n }\n\n return null;\n}\n\n/**\n * Transform YouTube components in HTML.\n */\nexport async function transformYouTube(html: string, options?: YouTubeOptions): Promise<string> {\n // Cheap marker check: skip the NAPI call entirely when there's no\n // `<youtube>` element (the common case). The Rust side guards the same way,\n // but short-circuiting here avoids marshalling the whole document across\n // the boundary.\n if (!/<youtube/i.test(html)) {\n return html;\n }\n\n const mod = await importNapiModule();\n return mod.transformYoutubeEmbeds(html, options);\n}\n","import type { TweetReference } from \"./types\";\n\nconst STATUS_PATH = /^\\/(?:[^/]+|i\\/web)\\/status\\/(\\d+)(?:\\/.*)?$/;\n\nexport function createSyndicationToken(id: string): string {\n return ((Number(id) / 1e15) * Math.PI).toString(36).replaceAll(/(0+|\\.)/g, \"\");\n}\n\nexport function parseTweetReference(value: string): TweetReference | null {\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) {\n return { id: trimmed, url: `https://x.com/i/web/status/${trimmed}` };\n }\n\n try {\n const url = new URL(trimmed);\n const hostname = url.hostname.toLowerCase().replace(/^(?:www\\.|mobile\\.)/, \"\");\n if (url.protocol !== \"https:\" || (hostname !== \"x.com\" && hostname !== \"twitter.com\")) {\n return null;\n }\n\n const match = url.pathname.match(STATUS_PATH);\n if (!match) return null;\n const screenName = url.pathname.startsWith(\"/i/web/status/\")\n ? \"i/web\"\n : url.pathname.split(\"/\")[1];\n return {\n id: match[1],\n url: `https://x.com/${screenName}/status/${match[1]}`,\n };\n } catch {\n return null;\n }\n}\n\nexport function referenceFromAttributes(attributes: string): TweetReference | null {\n const values = new Map<string, string>();\n const pattern = /\\b(url|href|id)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi;\n for (const match of attributes.matchAll(pattern)) {\n values.set(match[1].toLowerCase(), match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n return parseTweetReference(values.get(\"url\") ?? values.get(\"href\") ?? values.get(\"id\") ?? \"\");\n}\n","import { access, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createSyndicationToken } from \"./url\";\nimport type { ResolvedTwitterEmbedOptions, TweetAssets, TweetData, TweetMedia } from \"./types\";\n\nconst tweetCache = new Map<string, TweetData>();\n\nexport function clearTweetCache(): void {\n tweetCache.clear();\n}\n\nexport async function fetchTweetData(\n id: string,\n options: ResolvedTwitterEmbedOptions,\n): Promise<TweetData | null> {\n const key = `${id}-${sanitizeSegment(options.lang)}`;\n if (options.cache) {\n const memory = tweetCache.get(key);\n if (memory) return memory;\n const disk = await readCachedTweet(key, options.cacheDir);\n if (disk) {\n tweetCache.set(key, disk);\n return disk;\n }\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), options.timeout);\n const endpoint = new URL(\"https://cdn.syndication.twimg.com/tweet-result\");\n endpoint.searchParams.set(\"id\", id);\n endpoint.searchParams.set(\"lang\", options.lang);\n endpoint.searchParams.set(\"token\", createSyndicationToken(id));\n\n try {\n const response = await fetch(endpoint, {\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n });\n if (!response.ok) return null;\n const data: unknown = await response.json();\n if (!isTweetData(data)) return null;\n if (options.cache) {\n tweetCache.set(key, data);\n await writeCachedTweet(key, data, options.cacheDir);\n }\n return data;\n } catch {\n return null;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport async function materializeTweetAssets(\n id: string,\n data: TweetData,\n options: ResolvedTwitterEmbedOptions,\n): Promise<TweetAssets> {\n const assets: TweetAssets = { media: [] };\n const avatarUrl = data.user.profile_image_url_https?.replace(/_normal(?=\\.[^.]+$)/, \"_bigger\");\n if (avatarUrl) {\n assets.avatar = await downloadAsset(avatarUrl, `${id}-avatar`, options);\n }\n\n const media = data.mediaDetails ?? data.entities?.media ?? [];\n for (const [index, item] of media.entries()) {\n if (item.type && item.type !== \"photo\") continue;\n if (!item.media_url_https) continue;\n const src = await downloadAsset(item.media_url_https, `${id}-media-${index + 1}`, options);\n if (src) assets.media.push(assetRecord(src, item));\n }\n return assets;\n}\n\nasync function downloadAsset(\n source: string,\n basename: string,\n options: ResolvedTwitterEmbedOptions,\n): Promise<string | undefined> {\n let url: URL;\n try {\n url = new URL(source);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" || url.hostname.toLowerCase() !== \"pbs.twimg.com\") {\n return undefined;\n }\n\n const extension = extensionFromUrl(url);\n const filename = `${basename}${extension}`;\n const output = path.join(options.mediaOutputDir, filename);\n try {\n await access(output);\n return joinPublicPath(options.mediaPublicPath, filename);\n } catch {\n // Download the missing asset below.\n }\n\n try {\n const response = await fetch(url, { headers: { Accept: \"image/*\" } });\n if (!response.ok) return undefined;\n await mkdir(options.mediaOutputDir, { recursive: true });\n await writeFile(output, new Uint8Array(await response.arrayBuffer()));\n return joinPublicPath(options.mediaPublicPath, filename);\n } catch {\n return undefined;\n }\n}\n\nasync function readCachedTweet(key: string, directory: string): Promise<TweetData | null> {\n try {\n const data: unknown = JSON.parse(await readFile(path.join(directory, `${key}.json`), \"utf8\"));\n return isTweetData(data) ? data : null;\n } catch {\n return null;\n }\n}\n\nasync function writeCachedTweet(key: string, data: TweetData, directory: string): Promise<void> {\n try {\n await mkdir(directory, { recursive: true });\n await writeFile(path.join(directory, `${key}.json`), `${JSON.stringify(data)}\\n`);\n } catch {\n // A read-only cache directory must not fail the build.\n }\n}\n\nfunction isTweetData(data: unknown): data is TweetData {\n if (!data || typeof data !== \"object\") return false;\n const value = data as Partial<TweetData>;\n return (\n typeof value.text === \"string\" &&\n Boolean(value.user) &&\n typeof value.user?.name === \"string\" &&\n typeof value.user.screen_name === \"string\"\n );\n}\n\nfunction extensionFromUrl(url: URL): string {\n const match = url.pathname.match(/\\.(jpe?g|png|webp|gif)$/i);\n return match ? `.${match[1].toLowerCase().replace(\"jpeg\", \"jpg\")}` : \".jpg\";\n}\n\nfunction joinPublicPath(prefix: string, filename: string): string {\n return `${prefix.replace(/\\/$/, \"\")}/${filename}`;\n}\n\nfunction sanitizeSegment(value: string): string {\n return value.replaceAll(/[^a-zA-Z0-9_-]/g, \"-\");\n}\n\nfunction assetRecord(src: string, media: TweetMedia): TweetAssets[\"media\"][number] {\n return {\n src,\n alt: media.ext_alt_text,\n width: media.original_info?.width,\n height: media.original_info?.height,\n };\n}\n","import type { ResolvedTwitterEmbedOptions, TweetAssets, TweetData, TweetEntity } from \"./types\";\n\nexport function renderFetchedTweet(\n permalink: string,\n data: TweetData,\n assets: TweetAssets,\n options: ResolvedTwitterEmbedOptions,\n): string {\n const profile = `https://x.com/${encodeURIComponent(data.user.screen_name)}`;\n const author = escapeHtml(data.user.name);\n const handle = escapeHtml(data.user.screen_name);\n const avatar = assets.avatar\n ? `<img class=\"ox-tweet__avatar\" src=\"${escapeAttribute(assets.avatar)}\" alt=\"\" width=\"48\" height=\"48\" loading=\"lazy\" decoding=\"async\">`\n : \"\";\n const media = renderMedia(assets);\n const footer = renderFooter(permalink, data.created_at, options.lang);\n\n return [\n '<figure class=\"ox-tweet ox-tweet--fetched\">',\n '<header class=\"ox-tweet__header\">',\n `<a class=\"ox-tweet__profile\" href=\"${escapeAttribute(profile)}\" target=\"_blank\" rel=\"noopener noreferrer\">`,\n avatar,\n `<span class=\"ox-tweet__author-name\">${author}</span>`,\n `<span class=\"ox-tweet__author-handle\">@${handle}</span>`,\n \"</a></header>\",\n `<div class=\"ox-tweet__body\">${renderTweetText(data)}</div>`,\n media,\n footer,\n \"</figure>\",\n ].join(\"\");\n}\n\nexport function renderTweetText(data: TweetData): string {\n const [start, end] = data.display_text_range ?? [0, data.text.length];\n const entities = collectEntities(data)\n .filter((entity) => validRange(entity.indices, start, end))\n .sort((left, right) => left.indices![0] - right.indices![0]);\n\n let cursor = start;\n let output = \"\";\n for (const entity of entities) {\n const [entityStart, entityEnd] = entity.indices!;\n if (entityStart < cursor) continue;\n output += escapeText(data.text.slice(cursor, entityStart));\n if (entity.kind === \"url\") {\n const href = entity.expanded_url ?? entity.url;\n const label = entity.display_url ?? href;\n output += `<a href=\"${escapeAttribute(href)}\" target=\"_blank\" rel=\"noopener noreferrer\">${escapeHtml(label)}</a>`;\n }\n cursor = entityEnd;\n }\n output += escapeText(data.text.slice(cursor, end));\n return output.trim();\n}\n\nfunction collectEntities(data: TweetData): Array<TweetEntity & { kind: \"url\" | \"media\" }> {\n return [\n ...(data.entities?.urls ?? []).map((entity) => ({ ...entity, kind: \"url\" as const })),\n ...(data.entities?.media ?? []).map((entity) => ({ ...entity, kind: \"media\" as const })),\n ];\n}\n\nfunction validRange(\n indices: [number, number] | undefined,\n start: number,\n end: number,\n): indices is [number, number] {\n return Boolean(indices && indices[0] >= start && indices[1] <= end && indices[0] < indices[1]);\n}\n\nfunction renderMedia(assets: TweetAssets): string {\n if (assets.media.length === 0) return \"\";\n const images = assets.media\n .map((item) => {\n const size = [\n item.width ? ` width=\"${item.width}\"` : \"\",\n item.height ? ` height=\"${item.height}\"` : \"\",\n ].join(\"\");\n return `<img class=\"ox-tweet__media-item\" src=\"${escapeAttribute(item.src)}\" alt=\"${escapeAttribute(item.alt ?? \"\")}\"${size} loading=\"lazy\" decoding=\"async\">`;\n })\n .join(\"\");\n return `<div class=\"ox-tweet__media\" data-count=\"${assets.media.length}\">${images}</div>`;\n}\n\nfunction renderFooter(permalink: string, createdAt: string | undefined, lang: string): string {\n if (!createdAt) {\n return `<footer class=\"ox-tweet__footer\"><a class=\"ox-tweet__permalink\" href=\"${escapeAttribute(permalink)}\" target=\"_blank\" rel=\"noopener noreferrer\">View on X</a></footer>`;\n }\n const date = new Date(createdAt);\n if (Number.isNaN(date.valueOf())) return renderFooter(permalink, undefined, lang);\n const iso = date.toISOString();\n let label: string;\n try {\n label = new Intl.DateTimeFormat(lang, { dateStyle: \"medium\", timeZone: \"UTC\" }).format(date);\n } catch {\n label = new Intl.DateTimeFormat(\"en\", { dateStyle: \"medium\", timeZone: \"UTC\" }).format(date);\n }\n return `<footer class=\"ox-tweet__footer\"><a class=\"ox-tweet__permalink\" href=\"${escapeAttribute(permalink)}\" target=\"_blank\" rel=\"noopener noreferrer\"><time datetime=\"${iso}\">${escapeHtml(label)}</time></a></footer>`;\n}\n\nfunction escapeText(value: string): string {\n return escapeHtml(value).replaceAll(\"\\n\", \"<br>\");\n}\n\nfunction escapeAttribute(value: string): string {\n return escapeHtml(value).replaceAll(\"`\", \"&#96;\");\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n","import path from \"node:path\";\nimport { fetchTweetData, materializeTweetAssets } from \"./fetch\";\nimport { renderFetchedTweet } from \"./render\";\nimport type { ResolvedTwitterEmbedOptions, TwitterEmbedOptions } from \"./types\";\nimport { referenceFromAttributes } from \"./url\";\n\nconst TWEET_ELEMENT = /<(tweet|xpost)\\b([^>]*?)(?:\\/\\s*>|>[\\s\\S]*?<\\/\\1\\s*>)/gi;\n\nexport function resolveTwitterEmbedOptions(\n options: TwitterEmbedOptions,\n): ResolvedTwitterEmbedOptions {\n return {\n fetch: options.fetch ?? false,\n lang: options.lang ?? \"en\",\n timeout: options.timeout ?? 10000,\n cache: options.cache ?? true,\n cacheDir: path.resolve(options.cacheDir ?? \".cache/ox-content/twitter\"),\n mediaOutputDir: path.resolve(options.mediaOutputDir ?? \"public/ox-content/twitter\"),\n mediaPublicPath: options.mediaPublicPath ?? \"/ox-content/twitter\",\n };\n}\n\nexport async function transformFetchedTweets(\n html: string,\n options: TwitterEmbedOptions,\n): Promise<string> {\n const resolved = resolveTwitterEmbedOptions(options);\n if (!resolved.fetch) return html;\n\n let output = \"\";\n let cursor = 0;\n for (const match of html.matchAll(TWEET_ELEMENT)) {\n const index = match.index ?? 0;\n output += html.slice(cursor, index);\n const reference = referenceFromAttributes(match[2]);\n if (!reference) {\n output += match[0];\n cursor = index + match[0].length;\n continue;\n }\n\n const data = await fetchTweetData(reference.id, resolved);\n if (!data) {\n output += match[0];\n cursor = index + match[0].length;\n continue;\n }\n\n const assets = await materializeTweetAssets(reference.id, data, resolved);\n output += renderFetchedTweet(reference.url, data, assets, resolved);\n cursor = index + match[0].length;\n }\n return output + html.slice(cursor);\n}\n","import { importNapiModule } from \"../napi\";\nimport { transformFetchedTweets } from \"./twitter\";\nimport type { TwitterEmbedOptions } from \"./twitter\";\n\nexport interface MediaEmbedOptions {\n /**\n * Render `<Spotify>` embeds.\n * @default false\n */\n spotify?: boolean;\n\n /**\n * Render `<StackBlitz>` embeds.\n * @default false\n */\n stackBlitz?: boolean;\n\n /**\n * Render `<Tweet>` / `<XPost>` static cards. Pass `{ fetch: true }` to\n * resolve the post content and self-host its media at build time.\n * @default false\n */\n twitter?: boolean | TwitterEmbedOptions;\n\n /**\n * Render `<Bluesky>` static cards.\n * @default false\n */\n bluesky?: boolean;\n\n /**\n * Render `<WebContainer>` lazy placeholder blocks.\n * @default false\n */\n webContainer?: boolean;\n}\n\nexport async function transformMediaEmbeds(\n html: string,\n options: MediaEmbedOptions,\n): Promise<string> {\n if (!hasEnabledMediaEmbed(options) || !hasMediaMarker(html)) {\n return html;\n }\n\n let result = html;\n if (typeof options.twitter === \"object\") {\n result = await transformFetchedTweets(result, options.twitter);\n }\n if (!hasMediaMarker(result)) return result;\n\n const mod = await importNapiModule();\n return mod.transformMediaEmbeds(result, {\n spotify: options.spotify,\n stackBlitz: options.stackBlitz,\n twitter: Boolean(options.twitter),\n bluesky: options.bluesky,\n webContainer: options.webContainer,\n });\n}\n\nfunction hasEnabledMediaEmbed(options: MediaEmbedOptions): boolean {\n return Boolean(\n options.spotify ||\n options.stackBlitz ||\n options.twitter ||\n options.bluesky ||\n options.webContainer,\n );\n}\n\nfunction hasMediaMarker(html: string): boolean {\n return /<(spotify|stackblitz|tweet|xpost|bluesky|webcontainer)[\\s/>]/i.test(html);\n}\n","const GITHUB_REPO_RE = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/;\n\nfunction hasControlChar(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || code === 0x7f) {\n return true;\n }\n }\n return false;\n}\n\nexport function isSafeGitHubRepo(repo: string): boolean {\n return (\n GITHUB_REPO_RE.test(repo) && !repo.split(\"/\").some((part) => part === \".\" || part === \"..\")\n );\n}\n\nexport function isSafeGitHubRef(ref: string): boolean {\n return Boolean(ref) && !hasControlChar(ref) && !hasUnsafePathSegment(ref);\n}\n\nexport function isSafeGitHubPath(path: string): boolean {\n return Boolean(path) && !hasControlChar(path) && !hasUnsafePathSegment(path);\n}\n\nfunction hasUnsafePathSegment(value: string): boolean {\n return value\n .split(\"/\")\n .some((part) => !part || part === \".\" || part === \"..\" || part.includes(\"\\\\\"));\n}\n\nexport function encodePath(path: string): string {\n return path.split(\"/\").map(encodeURIComponent).join(\"/\");\n}\n","import type { GitHubLineRange, GitHubSourceRef } from \"./types\";\nimport { encodePath, isSafeGitHubPath, isSafeGitHubRef, isSafeGitHubRepo } from \"./validation\";\n\nconst EXTENSION_LANGUAGE_MAP = new Map<string, string>([\n [\"cjs\", \"javascript\"],\n [\"css\", \"css\"],\n [\"go\", \"go\"],\n [\"html\", \"html\"],\n [\"js\", \"javascript\"],\n [\"json\", \"json\"],\n [\"jsx\", \"jsx\"],\n [\"md\", \"markdown\"],\n [\"mdx\", \"mdx\"],\n [\"mjs\", \"javascript\"],\n [\"py\", \"python\"],\n [\"rb\", \"ruby\"],\n [\"rs\", \"rust\"],\n [\"sh\", \"shell\"],\n [\"svelte\", \"svelte\"],\n [\"toml\", \"toml\"],\n [\"ts\", \"typescript\"],\n [\"tsx\", \"tsx\"],\n [\"vue\", \"vue\"],\n [\"yaml\", \"yaml\"],\n [\"yml\", \"yaml\"],\n]);\n\nexport function sourceKey(source: GitHubSourceRef): string {\n return `${source.repo}@${source.ref}:${source.path}`;\n}\n\nexport function formatLineRange(lines: GitHubLineRange): string {\n return lines.start === lines.end ? `L${lines.start}` : `L${lines.start}-L${lines.end}`;\n}\n\nexport function summarizeCommitMessage(message: string): string {\n const firstLine = message.split(/\\r?\\n/, 1)[0]?.replace(/\\s+/g, \" \").trim() ?? \"\";\n if (firstLine.length <= 120) {\n return firstLine;\n }\n return `${firstLine.slice(0, 119)}…`;\n}\n\nexport function parseGitHubLineRange(value: string | undefined): GitHubLineRange | undefined {\n if (!value) return undefined;\n const match = value.trim().match(/^#?L?(\\d+)(?:-L?(\\d+))?$/i);\n if (!match) return undefined;\n\n const start = Number.parseInt(match[1], 10);\n const end = match[2] ? Number.parseInt(match[2], 10) : start;\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end < start) {\n return undefined;\n }\n\n return { start, end };\n}\n\nexport function createGitHubPermalink(source: Omit<GitHubSourceRef, \"permalink\">): string {\n const fragment = source.lines ? `#${formatLineRange(source.lines)}` : \"\";\n return `https://github.com/${source.repo}/blob/${encodeURIComponent(source.ref)}/${encodePath(\n source.path,\n )}${fragment}`;\n}\n\nexport function parseGitHubPermalink(value: string): GitHubSourceRef | null {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n\n if (url.protocol !== \"https:\" || url.hostname !== \"github.com\") {\n return null;\n }\n\n let parts: string[];\n try {\n parts = url.pathname\n .split(\"/\")\n .filter(Boolean)\n .map((part) => decodeURIComponent(part));\n } catch {\n return null;\n }\n\n if (parts.length < 5 || parts[2] !== \"blob\") {\n return null;\n }\n\n const repo = `${parts[0]}/${parts[1]}`;\n const ref = parts[3];\n const path = parts.slice(4).join(\"/\");\n if (!isSafeGitHubRepo(repo) || !isSafeGitHubRef(ref) || !isSafeGitHubPath(path)) {\n return null;\n }\n\n const lines = parseGitHubLineRange(url.hash);\n const source = { repo, ref, path, lines };\n return {\n ...source,\n permalink: createGitHubPermalink(source),\n };\n}\n\nexport function inferLanguage(path: string): string | null {\n const fileName = path.split(\"/\").at(-1)?.toLowerCase() ?? \"\";\n if (fileName === \"dockerfile\") return \"dockerfile\";\n if (fileName === \"makefile\") return \"makefile\";\n\n const extension = fileName.includes(\".\") ? fileName.split(\".\").at(-1) : undefined;\n return extension ? (EXTENSION_LANGUAGE_MAP.get(extension) ?? extension) : null;\n}\n","export interface GitHubRepoData {\n name: string;\n full_name: string;\n description: string | null;\n html_url: string;\n stargazers_count: number;\n forks_count: number;\n language: string | null;\n owner: {\n login: string;\n avatar_url: string;\n };\n}\n\nexport interface GitHubLineRange {\n start: number;\n end: number;\n}\n\nexport interface GitHubSourceRef {\n repo: string;\n ref: string;\n path: string;\n permalink: string;\n lines?: GitHubLineRange;\n}\n\nexport interface GitHubSourceCommit {\n sha: string;\n message: string;\n html_url: string;\n}\n\nexport interface GitHubSourceData {\n repo: string;\n ref: string;\n path: string;\n permalink: string;\n content: string;\n size: number;\n html_url: string;\n language: string | null;\n commit?: GitHubSourceCommit;\n}\n\nexport interface GitHubOptions {\n /**\n * GitHub API token used for higher rate limits and private repository access.\n * @default ''\n */\n token?: string;\n\n /**\n * Cache fetched repository and source data in memory for the current process.\n * @default true\n */\n cache?: boolean;\n\n /**\n * Cache TTL in milliseconds.\n * @default 3600000\n */\n cacheTTL?: number;\n\n /**\n * Maximum source file size to inline in bytes.\n * @default 200000\n */\n maxSourceBytes?: number;\n\n /**\n * Maximum source lines to inline when no line range is specified.\n * @default 120\n */\n maxSourceLines?: number;\n}\n\nexport const defaultOptions: Required<GitHubOptions> = {\n token: \"\",\n cache: true,\n cacheTTL: 3600000,\n maxSourceBytes: 200000,\n maxSourceLines: 120,\n};\n","import { Buffer } from \"node:buffer\";\nimport { inferLanguage, sourceKey, summarizeCommitMessage } from \"./source\";\nimport {\n defaultOptions,\n type GitHubOptions,\n type GitHubRepoData,\n type GitHubSourceCommit,\n type GitHubSourceData,\n type GitHubSourceRef,\n} from \"./types\";\nimport { encodePath, isSafeGitHubPath, isSafeGitHubRef, isSafeGitHubRepo } from \"./validation\";\n\nconst repoCache = new Map<string, { data: GitHubRepoData; timestamp: number }>();\nconst sourceCache = new Map<string, { data: GitHubSourceData; timestamp: number }>();\n\ninterface GitHubContentApiFile {\n type: string;\n encoding?: string;\n content?: string;\n size?: number;\n html_url?: string;\n}\n\ninterface GitHubCommitApiItem {\n sha?: string;\n html_url?: string;\n commit?: { message?: string };\n}\n\nfunction githubHeaders(options: Required<GitHubOptions>): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: \"application/vnd.github.v3+json\",\n \"User-Agent\": \"ox-content-github-plugin\",\n };\n\n if (options.token) {\n headers.Authorization = `Bearer ${options.token}`;\n }\n\n return headers;\n}\n\nasync function fetchSourceCommit(\n source: GitHubSourceRef,\n options: Required<GitHubOptions>,\n): Promise<GitHubSourceCommit | undefined> {\n try {\n const apiUrl = `https://api.github.com/repos/${source.repo}/commits?path=${encodeURIComponent(\n source.path,\n )}&sha=${encodeURIComponent(source.ref)}&per_page=1`;\n const response = await fetch(apiUrl, { headers: githubHeaders(options) });\n if (!response.ok) {\n return undefined;\n }\n\n const items = (await response.json()) as GitHubCommitApiItem[];\n const item = items[0];\n const sha = item?.sha;\n const message = item?.commit?.message ? summarizeCommitMessage(item.commit.message) : \"\";\n if (!sha || !message) {\n return undefined;\n }\n\n return {\n sha,\n message,\n html_url: item.html_url ?? `https://github.com/${source.repo}/commit/${sha}`,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Fetch repository data from GitHub API.\n */\nexport async function fetchRepoData(\n repo: string,\n options: Required<GitHubOptions>,\n): Promise<GitHubRepoData | null> {\n if (!isSafeGitHubRepo(repo)) {\n return null;\n }\n\n if (options.cache) {\n const cached = repoCache.get(repo);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const response = await fetch(`https://api.github.com/repos/${repo}`, {\n headers: githubHeaders(options),\n });\n\n if (!response.ok) {\n console.warn(`Failed to fetch GitHub repo ${repo}: ${response.status}`);\n return null;\n }\n\n const data = (await response.json()) as GitHubRepoData;\n if (options.cache) {\n repoCache.set(repo, { data, timestamp: Date.now() });\n }\n\n return data;\n } catch (error) {\n console.warn(`Error fetching GitHub repo ${repo}:`, error);\n return null;\n }\n}\n\n/**\n * Fetch source file data from GitHub API.\n */\nexport async function fetchGitHubSource(\n source: GitHubSourceRef,\n options: Required<GitHubOptions>,\n): Promise<GitHubSourceData | null> {\n if (\n !isSafeGitHubRepo(source.repo) ||\n !isSafeGitHubRef(source.ref) ||\n !isSafeGitHubPath(source.path)\n ) {\n return null;\n }\n\n const key = sourceKey(source);\n if (options.cache) {\n const cached = sourceCache.get(key);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const apiUrl = `https://api.github.com/repos/${source.repo}/contents/${encodePath(\n source.path,\n )}?ref=${encodeURIComponent(source.ref)}`;\n const [response, commit] = await Promise.all([\n fetch(apiUrl, { headers: githubHeaders(options) }),\n fetchSourceCommit(source, options),\n ]);\n\n if (!response.ok) {\n console.warn(`Failed to fetch GitHub source ${source.permalink}: ${response.status}`);\n return null;\n }\n\n const data = (await response.json()) as GitHubContentApiFile;\n if (\n data.type !== \"file\" ||\n data.encoding !== \"base64\" ||\n !data.content ||\n (data.size ?? 0) > options.maxSourceBytes\n ) {\n return null;\n }\n\n const content = Buffer.from(data.content.replace(/\\s/g, \"\"), \"base64\").toString(\"utf8\");\n if (Buffer.byteLength(content) > options.maxSourceBytes) {\n return null;\n }\n\n const sourceData: GitHubSourceData = {\n repo: source.repo,\n ref: source.ref,\n path: source.path,\n permalink: source.permalink,\n content,\n size: data.size ?? Buffer.byteLength(content),\n html_url: data.html_url ?? source.permalink,\n language: inferLanguage(source.path),\n ...(commit ? { commit } : {}),\n };\n\n if (options.cache) {\n sourceCache.set(key, { data: sourceData, timestamp: Date.now() });\n }\n\n return sourceData;\n } catch (error) {\n console.warn(`Error fetching GitHub source ${source.permalink}:`, error);\n return null;\n }\n}\n\n/**\n * Pre-fetch all GitHub repos data.\n */\nexport async function prefetchGitHubRepos(\n repos: string[],\n options?: GitHubOptions,\n): Promise<Map<string, GitHubRepoData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, GitHubRepoData | null>();\n\n await Promise.all(\n Array.from(new Set(repos)).map(async (repo) => {\n const data = await fetchRepoData(repo, mergedOptions);\n results.set(repo, data);\n }),\n );\n\n return results;\n}\n\n/**\n * Pre-fetch all GitHub source files.\n */\nexport async function prefetchGitHubSources(\n sources: GitHubSourceRef[],\n options?: GitHubOptions,\n): Promise<Map<string, GitHubSourceData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, GitHubSourceData | null>();\n const uniqueSources = Array.from(\n new Map(sources.map((source) => [sourceKey(source), source])).values(),\n );\n\n await Promise.all(\n uniqueSources.map(async (source) => {\n const data = await fetchGitHubSource(source, mergedOptions);\n results.set(sourceKey(source), data);\n }),\n );\n\n return results;\n}\n","import type { Element } from \"hast\";\nimport { createGitHubPermalink, parseGitHubLineRange, parseGitHubPermalink } from \"./source\";\nimport type { GitHubSourceRef } from \"./types\";\nimport { isSafeGitHubPath, isSafeGitHubRef, isSafeGitHubRepo } from \"./validation\";\n\nconst GITHUB_COMPONENT_RE = /<github\\b([^>]*)>/gi;\nconst ATTRIBUTE_RE = /([:\\w-]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'>/]+)))?/g;\n\n/**\n * Collect all GitHub repos from HTML for pre-fetching.\n */\nexport async function collectGitHubRepos(html: string): Promise<string[]> {\n const repos: string[] = [];\n\n GITHUB_COMPONENT_RE.lastIndex = 0;\n let match;\n while ((match = GITHUB_COMPONENT_RE.exec(html)) !== null) {\n const attrs = parseAttributes(match[1]);\n if (attrs.path || attrs.file || attrs.permalink || attrs.url || attrs.href) {\n continue;\n }\n\n const repo = attrs.repo;\n if (repo && isSafeGitHubRepo(repo)) {\n repos.push(repo);\n }\n }\n\n return repos;\n}\n\n/**\n * Collect all GitHub source references from HTML for pre-fetching.\n */\nexport async function collectGitHubSources(html: string): Promise<GitHubSourceRef[]> {\n const sources: GitHubSourceRef[] = [];\n\n GITHUB_COMPONENT_RE.lastIndex = 0;\n let match;\n while ((match = GITHUB_COMPONENT_RE.exec(html)) !== null) {\n const source = sourceRefFromAttributes(parseAttributes(match[1]));\n if (source) {\n sources.push(source);\n }\n }\n\n return sources;\n}\n\nfunction parseAttributes(raw: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n ATTRIBUTE_RE.lastIndex = 0;\n let match;\n\n while ((match = ATTRIBUTE_RE.exec(raw)) !== null) {\n attrs[match[1].toLowerCase()] = match[2] ?? match[3] ?? match[4] ?? \"\";\n }\n\n return attrs;\n}\n\nexport function attributesFromElement(el: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const name of [\n \"permalink\",\n \"url\",\n \"href\",\n \"repo\",\n \"path\",\n \"file\",\n \"ref\",\n \"sha\",\n \"branch\",\n \"loc\",\n \"lines\",\n \"line\",\n ]) {\n const value = getAttribute(el, name);\n if (value !== undefined) {\n attrs[name] = value;\n }\n }\n return attrs;\n}\n\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\nexport function sourceRefFromAttributes(attrs: Record<string, string>): GitHubSourceRef | null {\n const permalink = attrs.permalink ?? attrs.url ?? attrs.href;\n if (permalink) {\n return parseGitHubPermalink(permalink);\n }\n\n const repo = attrs.repo;\n const path = attrs.path ?? attrs.file;\n if (!repo || !path || !isSafeGitHubRepo(repo) || !isSafeGitHubPath(path)) {\n return null;\n }\n\n const ref = attrs.ref ?? attrs.sha ?? attrs.branch ?? \"main\";\n if (!isSafeGitHubRef(ref)) {\n return null;\n }\n\n const lines = parseGitHubLineRange(attrs.loc ?? attrs.lines ?? attrs.line);\n const source = { repo, ref, path, lines };\n return {\n ...source,\n permalink: createGitHubPermalink(source),\n };\n}\n","import type { Element } from \"hast\";\nimport { isSafeGitHubRepo } from \"./validation\";\n\n/**\n * Create fallback element when repo data is unavailable.\n */\nexport function createFallbackCard(repo: string): Element {\n const href = isSafeGitHubRepo(repo) ? `https://github.com/${repo}` : \"#\";\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-github-card\", \"error\"],\n href,\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-github-header\"] },\n children: [\n {\n type: \"element\",\n tagName: \"svg\",\n properties: {\n className: [\"ox-github-icon\"],\n viewBox: \"0 0 16 16\",\n fill: \"currentColor\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"path\",\n properties: {\n d: \"M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z\",\n },\n children: [],\n },\n ],\n },\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-repo\"] },\n children: [{ type: \"text\", value: repo }],\n },\n ],\n },\n ],\n };\n}\n","import type { Element } from \"hast\";\nimport type { GitHubRepoData } from \"./types\";\n\nfunction formatNumber(num: number): string {\n if (num >= 1000000) {\n return `${(num / 1000000).toFixed(1)}M`;\n }\n if (num >= 1000) {\n return `${(num / 1000).toFixed(1)}k`;\n }\n return String(num);\n}\n\nfunction iconPath(d: string): Element {\n return {\n type: \"element\",\n tagName: \"svg\",\n properties: { viewBox: \"0 0 16 16\", fill: \"currentColor\" },\n children: [{ type: \"element\", tagName: \"path\", properties: { d }, children: [] }],\n };\n}\n\nfunction createStatsChildren(repoData: GitHubRepoData): Element[\"children\"] {\n const statsChildren: Element[\"children\"] = [];\n\n if (repoData.language) {\n statsChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-language\"] },\n children: [\n {\n type: \"element\",\n tagName: \"span\",\n properties: {\n className: [\"ox-github-language-color\"],\n \"data-lang\": repoData.language.toLowerCase(),\n },\n children: [],\n },\n { type: \"text\", value: repoData.language },\n ],\n });\n }\n\n statsChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-stat\"] },\n children: [\n iconPath(\n \"M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Z\",\n ),\n { type: \"text\", value: formatNumber(repoData.stargazers_count) },\n ],\n });\n\n statsChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-stat\"] },\n children: [\n iconPath(\n \"M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z\",\n ),\n { type: \"text\", value: formatNumber(repoData.forks_count) },\n ],\n });\n\n return statsChildren;\n}\n\n/**\n * Create GitHub card element from repo data.\n */\nexport function createGitHubCard(repoData: GitHubRepoData): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-github-card\"],\n href: repoData.html_url,\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-github-header\"] },\n children: [\n {\n ...iconPath(\n \"M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z\",\n ),\n properties: {\n className: [\"ox-github-icon\"],\n viewBox: \"0 0 16 16\",\n fill: \"currentColor\",\n },\n },\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-repo\"] },\n children: [{ type: \"text\", value: repoData.full_name }],\n },\n ],\n },\n ...(repoData.description\n ? [\n {\n type: \"element\" as const,\n tagName: \"p\",\n properties: { className: [\"ox-github-description\"] },\n children: [{ type: \"text\" as const, value: repoData.description }],\n },\n ]\n : []),\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-github-stats\"] },\n children: createStatsChildren(repoData),\n },\n ],\n };\n}\n","import type { Element, Text } from \"hast\";\nimport { formatLineRange } from \"./source\";\nimport type { GitHubLineRange, GitHubOptions, GitHubSourceCommit, GitHubSourceData } from \"./types\";\n\nfunction normalizeSourceLines(content: string): string[] {\n const lines = content.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n if (lines.length > 1 && lines.at(-1) === \"\") {\n lines.pop();\n }\n return lines.length > 0 ? lines : [\"\"];\n}\n\nfunction text(value: string): Text {\n return { type: \"text\", value };\n}\n\nfunction createSourceLines(lines: string[], start: number): Array<Element | Text> {\n return lines.flatMap((line, index) => {\n const lineNumber = start + index;\n const span: Element = {\n type: \"element\",\n tagName: \"span\",\n properties: {\n className: [\"line\"],\n \"data-line\": String(lineNumber),\n \"data-line-number\": String(lineNumber),\n },\n children: [text(line)],\n };\n return index === 0 ? [span] : [text(\"\\n\"), span];\n });\n}\n\nfunction createCommitMeta(commit: GitHubSourceCommit): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-github-code-commit\"],\n href: commit.html_url,\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n title: commit.message,\n },\n children: [\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-code-sha\"] },\n children: [text(commit.sha.slice(0, 7))],\n },\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-code-commit-message\"] },\n children: [text(commit.message)],\n },\n ],\n };\n}\n\nexport function createGitHubSourceCard(\n source: GitHubSourceData,\n lines: GitHubLineRange | undefined,\n options: Required<GitHubOptions>,\n): Element {\n const allLines = normalizeSourceLines(source.content);\n const start = Math.min(lines?.start ?? 1, allLines.length);\n const end = lines\n ? Math.min(lines.end, allLines.length)\n : Math.min(allLines.length, options.maxSourceLines);\n const selectedLines = allLines.slice(start - 1, end);\n const loc = selectedLines.length;\n const rangeLabel = formatLineRange({ start, end });\n const locLabel =\n !lines && end < allLines.length\n ? `${rangeLabel} of ${allLines.length} LOC`\n : `${rangeLabel} · ${loc} LOC`;\n const languageClass = source.language ? [`language-${source.language}`] : [];\n const heading: Element[] = [\n {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-github-code-title\"],\n href: source.permalink,\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [text(`${source.repo}/${source.path}`)],\n },\n ];\n if (source.commit) {\n heading.push(createCommitMeta(source.commit));\n }\n\n return {\n type: \"element\",\n tagName: \"figure\",\n properties: {\n className: [\"ox-github-code\"],\n \"data-loc\": String(loc),\n \"data-source\": source.permalink,\n },\n children: [\n {\n type: \"element\",\n tagName: \"figcaption\",\n properties: { className: [\"ox-github-code-header\"] },\n children: [\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-github-code-heading\"] },\n children: heading,\n },\n {\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-github-code-loc\"] },\n children: [text(locLabel)],\n },\n ],\n },\n {\n type: \"element\",\n tagName: \"pre\",\n properties: {\n className: [\n \"ox-github-code-block\",\n \"ox-code-block\",\n \"line-numbers-mode\",\n ...languageClass,\n ],\n \"data-line-numbers\": \"true\",\n \"data-line-number-start\": String(start),\n ...(source.language ? { \"data-language\": source.language } : {}),\n },\n children: [\n {\n type: \"element\",\n tagName: \"code\",\n properties: { className: languageClass },\n children: createSourceLines(selectedLines, start),\n },\n ],\n },\n ],\n };\n}\n","import type { Element, Root } from \"hast\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport { unified } from \"unified\";\nimport { interopDefault } from \"../../interop\";\nimport { prefetchGitHubRepos, prefetchGitHubSources } from \"./api\";\nimport {\n attributesFromElement,\n collectGitHubRepos,\n collectGitHubSources,\n sourceRefFromAttributes,\n} from \"./attributes\";\nimport { createFallbackCard } from \"./fallback-card\";\nimport { createGitHubCard } from \"./repo-card\";\nimport { sourceKey } from \"./source\";\nimport { createGitHubSourceCard } from \"./source-card\";\nimport {\n defaultOptions,\n type GitHubOptions,\n type GitHubRepoData,\n type GitHubSourceData,\n} from \"./types\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\n/**\n * Rehype plugin to transform GitHub components.\n */\nfunction rehypeGitHub(\n repoDataMap: Map<string, GitHubRepoData | null>,\n sourceDataMap: Map<string, GitHubSourceData | null>,\n options: Required<GitHubOptions>,\n) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type !== \"element\") {\n continue;\n }\n\n if (child.tagName.toLowerCase() !== \"github\") {\n visit(child);\n continue;\n }\n\n const attrs = attributesFromElement(child);\n const source = sourceRefFromAttributes(attrs);\n\n if (source) {\n const sourceData = sourceDataMap.get(sourceKey(source));\n node.children[i] = sourceData\n ? createGitHubSourceCard(sourceData, source.lines, options)\n : createFallbackCard(source.permalink);\n continue;\n }\n\n const repo = attrs.repo;\n if (repo) {\n const repoData = repoDataMap.get(repo);\n node.children[i] = repoData ? createGitHubCard(repoData) : createFallbackCard(repo);\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform GitHub components in HTML.\n */\nexport async function transformGitHub(\n html: string,\n repoDataMap?: Map<string, GitHubRepoData | null>,\n options?: GitHubOptions,\n): Promise<string> {\n const mergedOptions = { ...defaultOptions, ...options };\n let dataMap = repoDataMap;\n if (!dataMap) {\n const repos = await collectGitHubRepos(html);\n dataMap = await prefetchGitHubRepos(repos, mergedOptions);\n }\n const sources = await collectGitHubSources(html);\n const sourceDataMap = await prefetchGitHubSources(sources, mergedOptions);\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeGitHub, dataMap, sourceDataMap, mergedOptions)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n","export {\n fetchGitHubSource,\n fetchRepoData,\n prefetchGitHubRepos,\n prefetchGitHubSources,\n} from \"./github/api\";\nexport { collectGitHubRepos, collectGitHubSources } from \"./github/attributes\";\nexport { createGitHubPermalink, parseGitHubLineRange, parseGitHubPermalink } from \"./github/source\";\nexport { transformGitHub } from \"./github/transform\";\nexport type {\n GitHubLineRange,\n GitHubOptions,\n GitHubRepoData,\n GitHubSourceCommit,\n GitHubSourceData,\n GitHubSourceRef,\n} from \"./github/types\";\nexport { isSafeGitHubRepo } from \"./github/validation\";\n","/**\n * OGP Card Plugin - Link card embedding\n *\n * Transforms <OgCard> components into static link preview cards\n * by fetching OGP metadata at build time.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\nimport { interopDefault } from \"../interop\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\nexport interface OgpData {\n url: string;\n title: string;\n description?: string;\n image?: string;\n siteName?: string;\n favicon?: string;\n}\n\nexport interface OgpOptions {\n /**\n * Request timeout in milliseconds.\n * @default 10000\n */\n timeout?: number;\n\n /**\n * Cache fetched Open Graph metadata in memory for the current process.\n * @default true\n */\n cache?: boolean;\n\n /**\n * Cache TTL in milliseconds.\n * @default 3600000\n */\n cacheTTL?: number;\n\n /**\n * User agent sent with metadata fetch requests.\n * @default 'ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei-prod/ox-content)'\n */\n userAgent?: string;\n}\n\nconst defaultOptions: Required<OgpOptions> = {\n timeout: 10000,\n cache: true,\n cacheTTL: 3600000,\n userAgent: \"ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei-prod/ox-content)\",\n};\n\n// Simple in-memory cache\nconst ogpCache = new Map<string, { data: OgpData; timestamp: number }>();\n\nfunction isPrivateIPv4(hostname: string): boolean {\n const parts = hostname.split(\".\").map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n const [a, b] = parts;\n return (\n a === 10 ||\n a === 127 ||\n a === 0 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 169 && b === 254)\n );\n}\n\nexport function isSafeOgpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n const host = url.hostname.toLowerCase();\n const ipv6 = host.replace(/^\\[|\\]$/g, \"\");\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n if (host === \"localhost\" || host.endsWith(\".localhost\")) return false;\n if (\n ipv6.includes(\":\") &&\n (ipv6 === \"::1\" || ipv6.startsWith(\"fc\") || ipv6.startsWith(\"fd\") || ipv6.startsWith(\"fe80\"))\n )\n return false;\n return !isPrivateIPv4(host);\n } catch {\n return false;\n }\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Extract domain from URL.\n */\nfunction extractDomain(url: string): string {\n try {\n const urlObj = new URL(url);\n return urlObj.hostname;\n } catch {\n return url;\n }\n}\n\n/**\n * Get favicon URL for a domain.\n */\nfunction getFaviconUrl(url: string): string {\n try {\n const urlObj = new URL(url);\n // Use Google's favicon service as fallback\n return `https://www.google.com/s2/favicons?domain=${urlObj.hostname}&sz=32`;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Parse OGP metadata from HTML.\n */\nfunction parseOgpFromHtml(html: string, url: string): OgpData {\n const result: OgpData = {\n url,\n title: \"\",\n };\n\n // Extract title\n const titleMatch = html.match(/<title[^>]*>([^<]+)<\\/title>/i);\n const ogTitleMatch =\n html.match(/<meta[^>]*property=[\"']og:title[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:title[\"']/i);\n\n result.title = ogTitleMatch?.[1] || titleMatch?.[1] || extractDomain(url);\n\n // Extract description\n const descMatch =\n html.match(/<meta[^>]*property=[\"']og:description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:description[\"']/i) ||\n html.match(/<meta[^>]*name=[\"']description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*name=[\"']description[\"']/i);\n\n if (descMatch) {\n result.description = descMatch[1];\n }\n\n // Extract image\n const imageMatch =\n html.match(/<meta[^>]*property=[\"']og:image[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:image[\"']/i);\n\n if (imageMatch) {\n let imageUrl = imageMatch[1];\n // Handle relative URLs\n if (imageUrl.startsWith(\"/\")) {\n try {\n const urlObj = new URL(url);\n imageUrl = `${urlObj.protocol}//${urlObj.host}${imageUrl}`;\n } catch {\n // Keep as is\n }\n }\n result.image = imageUrl;\n }\n\n // Extract site name\n const siteNameMatch =\n html.match(/<meta[^>]*property=[\"']og:site_name[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:site_name[\"']/i);\n\n if (siteNameMatch) {\n result.siteName = siteNameMatch[1];\n }\n\n // Get favicon\n result.favicon = getFaviconUrl(url);\n\n return result;\n}\n\n/**\n * Fetch OGP data for a URL.\n */\nexport async function fetchOgpData(\n url: string,\n options: Required<OgpOptions>,\n): Promise<OgpData | null> {\n if (!isSafeOgpUrl(url)) {\n return null;\n }\n\n // Check cache\n if (options.cache) {\n const cached = ogpCache.get(url);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n\n const response = await fetch(url, {\n headers: {\n \"User-Agent\": options.userAgent,\n Accept: \"text/html,application/xhtml+xml\",\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`Failed to fetch OGP for ${url}: ${response.status}`);\n return null;\n }\n\n const html = await response.text();\n const data = parseOgpFromHtml(html, url);\n\n // Cache the result\n if (options.cache) {\n ogpCache.set(url, { data, timestamp: Date.now() });\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n console.warn(`Timeout fetching OGP for ${url}`);\n } else {\n console.warn(`Error fetching OGP for ${url}:`, error);\n }\n return null;\n }\n}\n\n/**\n * Create OGP card element.\n */\nfunction createOgpCard(data: OgpData): Element {\n const children: Element[\"children\"] = [];\n\n // Content section\n const contentChildren: Element[\"children\"] = [];\n\n // Title\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-title\"] },\n children: [{ type: \"text\", value: data.title }],\n });\n\n // Description\n if (data.description) {\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-description\"] },\n children: [{ type: \"text\", value: data.description }],\n });\n }\n\n // Meta (favicon + domain)\n const metaChildren: Element[\"children\"] = [];\n\n if (data.favicon) {\n metaChildren.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-favicon\"],\n src: data.favicon,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n metaChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-ogp-domain\"] },\n children: [{ type: \"text\", value: data.siteName || extractDomain(data.url) }],\n });\n\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-meta\"] },\n children: metaChildren,\n });\n\n children.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-content\"] },\n children: contentChildren,\n });\n\n // Image\n if (data.image) {\n children.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-image\"],\n src: data.image,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-card\"],\n href: isSafeOgpUrl(data.url) ? data.url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children,\n };\n}\n\n/**\n * Create fallback element when OGP data is unavailable.\n */\nfunction createFallbackCard(url: string): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-simple\"],\n href: isSafeOgpUrl(url) ? url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"svg\",\n properties: {\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n \"stroke-width\": \"2\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"path\",\n properties: {\n d: \"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3\",\n },\n children: [],\n },\n ],\n },\n { type: \"text\", value: extractDomain(url) },\n ],\n };\n}\n\n/**\n * Collect all OGP URLs from HTML for pre-fetching.\n */\nexport async function collectOgpUrls(html: string): Promise<string[]> {\n const urls: string[] = [];\n const urlPattern = /<ogcard[^>]*\\s+url=[\"']([^\"']+)[\"']/gi;\n\n let match;\n while ((match = urlPattern.exec(html)) !== null) {\n if (isSafeOgpUrl(match[1])) {\n urls.push(match[1]);\n }\n }\n\n return urls;\n}\n\n/**\n * Pre-fetch all OGP data.\n */\nexport async function prefetchOgpData(\n urls: string[],\n options?: OgpOptions,\n): Promise<Map<string, OgpData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, OgpData | null>();\n\n await Promise.all(\n urls.map(async (url) => {\n const data = await fetchOgpData(url, mergedOptions);\n results.set(url, data);\n }),\n );\n\n return results;\n}\n\n/**\n * Rehype plugin to transform OgCard components.\n */\nfunction rehypeOgp(ogpDataMap: Map<string, OgpData | null>) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <OgCard> component\n if (child.tagName.toLowerCase() === \"ogcard\") {\n const url = getAttribute(child, \"url\");\n\n if (url) {\n const ogpData = ogpDataMap.get(url);\n const cardElement = ogpData ? createOgpCard(ogpData) : createFallbackCard(url);\n node.children[i] = cardElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform OgCard components in HTML.\n */\nexport async function transformOgp(\n html: string,\n ogpDataMap?: Map<string, OgpData | null>,\n options?: OgpOptions,\n): Promise<string> {\n // If no pre-fetched data, collect and fetch\n let dataMap = ogpDataMap;\n if (!dataMap) {\n const urls = await collectOgpUrls(html);\n dataMap = await prefetchOgpData(urls, options);\n }\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeOgp, dataMap)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n","/**\n * ox-content Built-in Plugins\n *\n * All plugins are designed with No-JavaScript-First principle.\n * They generate static HTML at build time and require no client-side JS.\n */\n\nimport type { GitHubOptions } from \"./github\";\nimport type { MediaEmbedOptions } from \"./media\";\nimport type { TwitterEmbedOptions } from \"./twitter\";\nimport type { OgpOptions } from \"./ogp\";\nimport type { PmOptions } from \"./pm\";\n\nexport {\n transformTabs,\n generateTabsCSS,\n resetTabGroupCounter,\n getTabGroupCounter,\n setTabGroupCounter,\n} from \"./tabs\";\n\nexport { transformPm, type PmOptions } from \"./pm\";\n\nexport { transformYouTube, extractVideoId, type YouTubeOptions } from \"./youtube\";\nexport { transformMediaEmbeds, type MediaEmbedOptions } from \"./media\";\nexport {\n createSyndicationToken,\n parseTweetReference,\n type TweetData,\n type TwitterEmbedOptions,\n} from \"./twitter\";\n\nexport {\n transformGitHub,\n fetchRepoData,\n fetchGitHubSource,\n collectGitHubRepos,\n collectGitHubSources,\n prefetchGitHubRepos,\n prefetchGitHubSources,\n parseGitHubPermalink,\n parseGitHubLineRange,\n type GitHubRepoData,\n type GitHubSourceCommit,\n type GitHubSourceData,\n type GitHubSourceRef,\n type GitHubLineRange,\n type GitHubOptions,\n} from \"./github\";\n\nexport {\n transformOgp,\n fetchOgpData,\n collectOgpUrls,\n prefetchOgpData,\n type OgpData,\n type OgpOptions,\n} from \"./ogp\";\n\nexport { transformMermaidStatic, mermaidClientScript, type MermaidOptions } from \"./mermaid\";\n\nconst SELF_CLOSING_EMBED_TAG =\n /<(GitHub|OgCard|Tweet|XPost|Bluesky|Spotify|StackBlitz|WebContainer|YouTube)((?:[^>\"']|\"[^\"]*\"|'[^']*')*?)\\s*\\/>/gi;\n\n/**\n * Custom embed tags are not HTML void elements, so a self-closing authoring\n * form like `<GitHub ... />` reaches the HTML re-parsers (Shiki highlighting,\n * embed transforms) as an unclosed element that swallows the rest of the\n * document. Normalize to an explicit open/close pair before any rehype pass\n * runs.\n */\nexport function normalizeSelfClosingEmbeds(html: string): string {\n return html.replace(SELF_CLOSING_EMBED_TAG, (_match, tag: string, attrs: string) => {\n return `<${tag}${attrs}></${tag}>`;\n });\n}\n\n/**\n * Transform all plugin components in HTML.\n * Call this during SSG build to process all plugins at once.\n */\nexport interface TransformAllOptions {\n tabs?: boolean;\n /**\n * Expand `<pm>` package-manager blocks into install tabs. Pass an object to\n * opt in to synced groups (`{ sync: true }`); syncing is off by default.\n * @default false\n */\n pm?: boolean | PmOptions;\n youtube?: boolean;\n github?: boolean | GitHubOptions;\n ogp?: boolean | OgpOptions;\n openGraph?: boolean | OgpOptions;\n mermaid?: boolean;\n githubToken?: string;\n spotify?: boolean;\n stackBlitz?: boolean;\n twitter?: boolean | TwitterEmbedOptions;\n bluesky?: boolean;\n webContainer?: boolean;\n}\n\n/**\n * Transform all enabled plugins in HTML content.\n */\nexport async function transformAllPlugins(\n html: string,\n options: TransformAllOptions = {},\n): Promise<string> {\n const {\n tabs = true,\n pm = false,\n youtube = true,\n github = true,\n ogp,\n openGraph,\n mermaid = true,\n githubToken,\n spotify = false,\n stackBlitz = false,\n twitter = false,\n bluesky = false,\n webContainer = false,\n } = options;\n\n let result = normalizeSelfClosingEmbeds(html);\n const ogpOptions = openGraph ?? ogp ?? true;\n\n // Order matters: process in dependency order\n\n // 1. Tabs (no external dependencies)\n if (tabs) {\n const { transformTabs } = await import(\"./tabs\");\n result = await transformTabs(result);\n }\n\n // 1b. Package-manager tabs (no external dependencies). Shares the tab-group\n // counter with the tabs transform, so it runs right after it. Syncing is\n // opt-in via `{ pm: { sync: true } }` and off by default.\n if (pm) {\n const { transformPm } = await import(\"./pm\");\n result = await transformPm(result, typeof pm === \"object\" ? pm : {});\n }\n\n // 2. YouTube (no external dependencies)\n if (youtube) {\n const { transformYouTube } = await import(\"./youtube\");\n result = await transformYouTube(result);\n }\n\n // 3. GitHub (requires API calls)\n if (github !== false) {\n const { transformGitHub } = await import(\"./github\");\n const options = typeof github === \"object\" ? github : {};\n result = await transformGitHub(result, undefined, { token: githubToken, ...options });\n }\n\n // 4. OGP (requires fetch calls)\n if (ogpOptions !== false) {\n const { transformOgp } = await import(\"./ogp\");\n result = await transformOgp(\n result,\n undefined,\n typeof ogpOptions === \"object\" ? ogpOptions : {},\n );\n }\n\n const mediaOptions = { spotify, stackBlitz, twitter, bluesky, webContainer };\n if (Object.values(mediaOptions).some(Boolean)) {\n const { transformMediaEmbeds } = await import(\"./media\");\n result = await transformMediaEmbeds(result, mediaOptions);\n }\n\n // 5. Mermaid (requires mermaid library)\n if (mermaid) {\n const { transformMermaidStatic } = await import(\"./mermaid\");\n result = await transformMermaidStatic(result);\n }\n\n return result;\n}\n\n/**\n * Transform built-in embed components in HTML content.\n */\nexport async function transformBuiltinEmbeds(\n html: string,\n options: {\n github: GitHubOptions | false;\n openGraph: OgpOptions | false;\n pm?: PmOptions | false;\n spotify?: boolean;\n stackBlitz?: boolean;\n twitter?: boolean | TwitterEmbedOptions;\n bluesky?: boolean;\n webContainer?: boolean;\n },\n): Promise<string> {\n let result = normalizeSelfClosingEmbeds(html);\n\n if (options.github) {\n const { transformGitHub } = await import(\"./github\");\n result = await transformGitHub(result, undefined, {\n token: process.env.GITHUB_TOKEN,\n ...options.github,\n });\n }\n\n if (options.openGraph) {\n const { transformOgp } = await import(\"./ogp\");\n result = await transformOgp(result, undefined, options.openGraph);\n }\n\n if (options.pm) {\n const { transformPm } = await import(\"./pm\");\n result = await transformPm(result, typeof options.pm === \"object\" ? options.pm : {});\n }\n\n const mediaOptions: MediaEmbedOptions = {\n spotify: options.spotify,\n stackBlitz: options.stackBlitz,\n twitter: options.twitter,\n bluesky: options.bluesky,\n webContainer: options.webContainer,\n };\n if (Object.values(mediaOptions).some(Boolean)) {\n const { transformMediaEmbeds } = await import(\"./media\");\n result = await transformMediaEmbeds(result, mediaOptions);\n }\n\n return result;\n}\n","/**\n * Protects mermaid SVG content from rehype HTML5 parser corruption.\n *\n * rehypeParse + rehypeStringify converts `<br />` in SVG foreignObject\n * to `<br></br>`, which HTML5 interprets as 2 <br> elements.\n * Each rehype pass doubles them: 1 → 2 → 4 → 8 → 16.\n *\n * This module extracts ox-mermaid SVG blocks into placeholders before\n * rehype processing and restores them after.\n */\n\nexport interface MermaidSvgProtection {\n html: string;\n svgs: Map<string, string>;\n}\n\n/**\n * Extract `<div class=\"ox-mermaid\">...</div>` blocks and replace\n * with HTML comment placeholders that rehype will preserve.\n */\nexport function protectMermaidSvgs(html: string): MermaidSvgProtection {\n const svgs = new Map<string, string>();\n let result = html;\n let idx = 0;\n\n while (true) {\n const marker = `<div class=\"ox-mermaid\">`;\n const start = result.indexOf(marker, idx);\n if (start === -1) break;\n\n // Find the matching </div> by counting nested divs\n let depth = 0;\n let pos = start;\n let endPos = -1;\n\n while (pos < result.length) {\n const openIdx = result.indexOf(\"<div\", pos);\n const closeIdx = result.indexOf(\"</div>\", pos);\n if (closeIdx === -1) break;\n\n if (openIdx !== -1 && openIdx < closeIdx) {\n depth++;\n pos = openIdx + 4;\n } else {\n depth--;\n if (depth === 0) {\n endPos = closeIdx + 6;\n break;\n }\n pos = closeIdx + 6;\n }\n }\n\n if (endPos === -1) break;\n\n const svgContent = result.substring(start, endPos);\n const placeholder = `<!--ox-mermaid-${svgs.size}-->`;\n svgs.set(placeholder, svgContent);\n result = result.substring(0, start) + placeholder + result.substring(endPos);\n idx = start + placeholder.length;\n }\n\n return { html: result, svgs };\n}\n\n/**\n * Restore protected mermaid SVG blocks from placeholders.\n */\nexport function restoreMermaidSvgs(html: string, svgs: Map<string, string>): string {\n if (svgs.size === 0) {\n return html;\n }\n // Single pass over the HTML instead of one full `String.replace` scan per\n // placeholder (O(svgs × html) → O(html)). The function replacer also avoids\n // the `$`-pattern interpretation that the string form of `replace` applies\n // to the SVG replacement content.\n return html.replace(/<!--ox-mermaid-\\d+-->/g, (placeholder) => {\n const content = svgs.get(placeholder);\n return content !== undefined ? content : placeholder;\n });\n}\n","import { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { execFile } from \"node:child_process\";\nimport { importNapiModule } from \"./napi\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface ExtractedCodeBlock {\n language: string;\n meta: string;\n code: string;\n startLine: number;\n endLine: number;\n}\n\nexport interface CodeBlockDiagnostic {\n ruleId: string;\n severity: \"error\" | \"warning\" | \"info\";\n message: string;\n line: number;\n column: number;\n endLine: number;\n endColumn: number;\n language?: string;\n}\n\nexport interface CodeBlockLintOptions {\n /**\n * Languages to lint. Omit to lint every fenced block language.\n * @default undefined\n */\n languages?: string[];\n\n /**\n * Report fences without a language identifier.\n * @default false\n */\n requireLanguage?: boolean;\n\n /**\n * Report trailing whitespace in code block lines.\n * @default true\n */\n trailingSpaces?: boolean;\n}\n\nexport interface DocsTestOptions {\n /**\n * Fence languages to collect as runnable examples.\n * @default ['js', 'jsx', 'ts', 'tsx', 'mjs', 'mts']\n */\n languages?: string[];\n\n /**\n * Require fence meta such as `test`, `runnable`, `vitest`, or `docs-test`.\n * @default true\n */\n requireMeta?: boolean;\n}\n\nexport interface TypecheckCodeBlockOptions {\n /**\n * Fence languages to type-check.\n * @default ['ts', 'tsx']\n */\n languages?: string[];\n\n /**\n * Require fence meta such as `typecheck`, `twoslash`, or `typecheck=...`.\n * @default true\n */\n requireMeta?: boolean;\n\n /**\n * Command used to run the TypeScript checker.\n * @default 'tsgo'\n */\n tsgoCommand?: string;\n}\n\nexport async function extractCodeBlocks(source: string): Promise<ExtractedCodeBlock[]> {\n const mod = await importNapiModule();\n return mod.extractCodeBlocks(source).map(normalizeBlock);\n}\n\nexport async function lintCodeBlocks(\n source: string,\n options: CodeBlockLintOptions = {},\n): Promise<CodeBlockDiagnostic[]> {\n const mod = await importNapiModule();\n return mod\n .lintCodeBlocks(source, {\n enabled: true,\n languages: options.languages,\n requireLanguage: options.requireLanguage,\n trailingSpaces: options.trailingSpaces,\n })\n .map(normalizeDiagnostic);\n}\n\nexport async function extractDocsTests(\n source: string,\n options: DocsTestOptions = {},\n): Promise<ExtractedCodeBlock[]> {\n const mod = await importNapiModule();\n return mod\n .extractDocsTests(source, {\n enabled: true,\n languages: options.languages,\n requireMeta: options.requireMeta,\n })\n .map(normalizeBlock);\n}\n\nexport async function typecheckCodeBlocks(\n source: string,\n options: TypecheckCodeBlockOptions = {},\n): Promise<CodeBlockDiagnostic[]> {\n if (!source.includes(\"```\")) {\n return [];\n }\n\n const languages = new Set(\n (options.languages ?? [\"ts\", \"tsx\"]).map((language) => language.toLowerCase()),\n );\n const blocks = (await extractCodeBlocks(source)).filter((block) => {\n if (!languages.has(block.language.toLowerCase())) {\n return false;\n }\n return options.requireMeta === false || hasTypecheckMeta(block.meta);\n });\n if (blocks.length === 0) {\n return [];\n }\n\n const temp = await mkdtemp(join(tmpdir(), \"ox-content-code-blocks-\"));\n try {\n const files: string[] = [];\n await Promise.all(\n blocks.map(async (block, index) => {\n const extension = block.language.toLowerCase() === \"tsx\" ? \"tsx\" : \"ts\";\n const file = join(temp, `snippet-${index}.${extension}`);\n files.push(file);\n await writeFile(file, block.code);\n }),\n );\n\n try {\n await execFileAsync(\n options.tsgoCommand ?? \"tsgo\",\n [\"--noEmit\", \"--pretty\", \"false\", ...files],\n {\n cwd: process.cwd(),\n maxBuffer: 1024 * 1024 * 4,\n },\n );\n return [];\n } catch (error) {\n const output = commandOutput(error);\n return [\n {\n ruleId: \"code-block-typecheck\",\n severity: \"error\",\n message: output || \"TypeScript code block type-checking failed.\",\n line: blocks[0]?.startLine ?? 1,\n column: 1,\n endLine: blocks[0]?.startLine ?? 1,\n endColumn: 1,\n language: \"ts\",\n },\n ];\n }\n } finally {\n await rm(temp, { recursive: true, force: true });\n }\n}\n\nfunction hasTypecheckMeta(meta: string): boolean {\n return meta\n .split(/\\s+/)\n .some(\n (token) => token === \"typecheck\" || token === \"twoslash\" || token.startsWith(\"typecheck=\"),\n );\n}\n\nfunction commandOutput(error: unknown): string {\n if (!error || typeof error !== \"object\") {\n return \"\";\n }\n const value = error as { stdout?: unknown; stderr?: unknown; message?: unknown };\n return [value.stdout, value.stderr, value.message]\n .filter((part): part is string => typeof part === \"string\" && part.trim().length > 0)\n .join(\"\\n\")\n .trim();\n}\n\nfunction normalizeBlock(block: {\n language: string;\n meta: string;\n code: string;\n startLine: number;\n endLine: number;\n}): ExtractedCodeBlock {\n return block;\n}\n\nfunction normalizeDiagnostic(diagnostic: {\n ruleId: string;\n severity: string;\n message: string;\n line: number;\n column: number;\n endLine: number;\n endColumn: number;\n language?: string;\n}): CodeBlockDiagnostic {\n return {\n ...diagnostic,\n severity:\n diagnostic.severity === \"error\" || diagnostic.severity === \"info\"\n ? diagnostic.severity\n : \"warning\",\n };\n}\n","import { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nexport interface TypedHoverRange {\n start: number;\n end: number;\n type: string;\n}\n\nexport interface TypedHoverAttachment {\n code: string;\n hovers: TypedHoverRange[];\n}\n\ntype TsgoApi = {\n API: new (options?: { cwd?: string; tsserverPath?: string }) => {\n updateSnapshot: (params: { openFiles?: string[] }) => {\n getDefaultProjectForFile: (file: string) => TsgoProject | undefined;\n };\n close: () => void;\n };\n};\n\ntype TsgoProject = {\n checker: {\n getTypeAtPosition: (file: string, position: number) => TsgoType | undefined;\n getBaseTypeOfLiteralType: (type: TsgoType) => TsgoType | undefined;\n typeToString: (type: TsgoType) => string;\n };\n};\n\ntype TsgoType = {\n isErrorType?: () => boolean;\n};\n\nasync function loadTsgoApi(): Promise<TsgoApi | undefined> {\n try {\n const specifier = \"@typescript/native-preview/unstable/sync\";\n return (await import(specifier)) as TsgoApi;\n } catch {\n return undefined;\n }\n}\n\nexport async function generateTypedHoverAttachments(\n fences: readonly { language: string; code: string }[],\n tsgoCommand?: string,\n): Promise<TypedHoverAttachment[]> {\n if (fences.length === 0) {\n return [];\n }\n\n const apiMod = await loadTsgoApi();\n if (!apiMod) {\n return fences.map((fence) => ({ code: fence.code, hovers: [] }));\n }\n\n const temp = await mkdtemp(join(tmpdir(), \"ox-content-typed-hover-\"));\n const api = new apiMod.API({\n cwd: temp,\n ...(tsgoCommand ? { tsserverPath: tsgoCommand } : {}),\n });\n try {\n const files = await Promise.all(\n fences.map(async (fence, index) => {\n const extension = fence.language.toLowerCase() === \"tsx\" ? \"tsx\" : \"ts\";\n const file = join(temp, `snippet-${index}.${extension}`);\n await writeFile(file, fence.code);\n return { fence, file };\n }),\n );\n const snapshot = api.updateSnapshot({ openFiles: files.map((item) => item.file) });\n return files.map(({ fence, file }) => {\n const project = snapshot.getDefaultProjectForFile(file);\n if (!project) {\n return { code: fence.code, hovers: [] };\n }\n const hovers: TypedHoverRange[] = [];\n for (const ident of collectIdentifierRanges(fence.code)) {\n const type = project.checker.getTypeAtPosition(file, ident.start);\n if (!type || type.isErrorType?.()) {\n continue;\n }\n const widened = project.checker.getBaseTypeOfLiteralType(type) ?? type;\n const text = project.checker.typeToString(widened);\n if (text) {\n hovers.push({ start: ident.start, end: ident.end, type: text });\n }\n }\n return { code: fence.code, hovers };\n });\n } finally {\n api.close();\n await rm(temp, { recursive: true, force: true });\n }\n}\n\nconst IDENTIFIER_KEYWORDS = new Set([\n \"abstract\",\n \"any\",\n \"as\",\n \"asserts\",\n \"async\",\n \"await\",\n \"bigint\",\n \"boolean\",\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"declare\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"from\",\n \"function\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"infer\",\n \"instanceof\",\n \"interface\",\n \"is\",\n \"keyof\",\n \"let\",\n \"never\",\n \"new\",\n \"null\",\n \"number\",\n \"object\",\n \"of\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"readonly\",\n \"return\",\n \"satisfies\",\n \"static\",\n \"string\",\n \"super\",\n \"switch\",\n \"symbol\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"type\",\n \"typeof\",\n \"undefined\",\n \"unique\",\n \"unknown\",\n \"using\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n]);\n\nexport function collectIdentifierRanges(code: string): Array<{ start: number; end: number }> {\n const ranges: Array<{ start: number; end: number }> = [];\n let index = 0;\n while (index < code.length) {\n const char = code[index]!;\n if (char === \"/\" && code[index + 1] === \"/\") {\n index = code.indexOf(\"\\n\", index);\n if (index === -1) {\n break;\n }\n continue;\n }\n if (char === \"/\" && code[index + 1] === \"*\") {\n const close = code.indexOf(\"*/\", index + 2);\n index = close === -1 ? code.length : close + 2;\n continue;\n }\n if (char === '\"' || char === \"'\" || char === \"`\") {\n index = skipQuoted(code, index, char);\n continue;\n }\n if (/[A-Za-z_$]/.test(char)) {\n const start = index;\n index += 1;\n while (index < code.length && /[\\w$]/.test(code[index]!)) {\n index += 1;\n }\n const name = code.slice(start, index);\n if (!IDENTIFIER_KEYWORDS.has(name)) {\n ranges.push({ start, end: index });\n }\n continue;\n }\n index += 1;\n }\n return ranges;\n}\n\nfunction skipQuoted(code: string, start: number, quote: string): number {\n let index = start + 1;\n while (index < code.length) {\n if (code[index] === \"\\\\\") {\n index += 2;\n continue;\n }\n if (code[index] === quote) {\n return index + 1;\n }\n index += 1;\n }\n return code.length;\n}\n","import { extractCodeBlocks } from \"./code-blocks\";\nimport {\n generateTypedHoverAttachments,\n type TypedHoverAttachment,\n type TypedHoverRange,\n} from \"./typed-hover-generate\";\nimport type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport type { TypedHoverAttachment, TypedHoverRange };\n\nexport interface TypedHoverPayload {\n hovers: TypedHoverRange[];\n}\n\nconst DEFAULT_LANGUAGES = [\"ts\", \"tsx\"] as const;\n\nexport function resolveTypedHoverOptions(\n options: OxContentOptions[\"typedHover\"],\n): ResolvedOptions[\"typedHover\"] {\n if (!options) {\n return { enabled: false, languages: [...DEFAULT_LANGUAGES] };\n }\n if (options === true) {\n return { enabled: true, languages: [...DEFAULT_LANGUAGES] };\n }\n return {\n enabled: options.enabled ?? true,\n languages: options.languages ?? [...DEFAULT_LANGUAGES],\n tsgoCommand: options.tsgoCommand,\n };\n}\n\nexport function hasTypedHoverMeta(meta: string): boolean {\n return meta.split(/\\s+/).some((token) => token === \"twoslash\");\n}\n\nexport function serializeTypedHoverPayload(payload: TypedHoverPayload): string {\n return JSON.stringify(payload).replace(/</g, \"\\\\u003c\").replace(/>/g, \"\\\\u003e\");\n}\n\nexport async function applyTypedHover(\n source: string,\n html: string,\n options: ResolvedOptions[\"typedHover\"],\n): Promise<string> {\n if (!options?.enabled || !source.includes(\"```\")) {\n return html;\n }\n\n const languages = new Set(options.languages.map((language) => language.toLowerCase()));\n const fences = (await extractCodeBlocks(source)).filter((block) => {\n return languages.has(block.language.toLowerCase()) && hasTypedHoverMeta(block.meta);\n });\n if (fences.length === 0) {\n return html;\n }\n\n try {\n const attachments = await generateTypedHoverAttachments(fences, options.tsgoCommand);\n return attachTypedHoverPayloads(html, attachments);\n } catch {\n return html;\n }\n}\n\nexport function attachTypedHoverPayloads(\n html: string,\n attachments: TypedHoverAttachment[],\n): string {\n const unused = attachments.filter((item) => item.hovers.length > 0);\n if (unused.length === 0) {\n return html;\n }\n\n let attached = 0;\n const next = html.replace(\n /<pre(\\b[^>]*)><code(\\b[^>]*)>([\\s\\S]*?)<\\/code><\\/pre>/g,\n (full, preAttrs: string, codeAttrs: string, inner: string) => {\n if (unused.length === 0) {\n return full;\n }\n if (!isTypeScriptFence(codeAttrs)) {\n return full;\n }\n const text = decodeHtmlEntities(inner.replace(/<[^>]+>/g, \"\"));\n const index = unused.findIndex(\n (item) => normalizeFenceText(item.code) === normalizeFenceText(text),\n );\n if (index === -1) {\n return full;\n }\n const item = unused.splice(index, 1)[0];\n if (!item) {\n return full;\n }\n attached += 1;\n const wrapped = wrapHoverRanges(inner, item.hovers);\n return `${withTypedHoverClass(`<pre${preAttrs}`)}><code${codeAttrs}>${wrapped}</code></pre>\\n<script type=\"application/json\" class=\"ox-typed-hover-data\">${serializeTypedHoverPayload({ hovers: item.hovers })}</script>`;\n },\n );\n\n if (attached === 0) {\n return html;\n }\n return `${next}${TYPED_HOVER_STYLE}${TYPED_HOVER_CLIENT}`;\n}\n\nfunction isTypeScriptFence(codeAttrs: string): boolean {\n const match = codeAttrs.match(/class=\"([^\"]*)\"/);\n if (!match?.[1]) {\n return false;\n }\n return match[1].split(/\\s+/).some((token) => {\n const language = token.replace(/^language-/, \"\").toLowerCase();\n return (\n language === \"ts\" ||\n language === \"tsx\" ||\n language === \"typescript\" ||\n language === \"typescriptreact\"\n );\n });\n}\n\nfunction withTypedHoverClass(openPre: string): string {\n if (/\\bclass=\"/.test(openPre)) {\n return openPre.replace(/\\bclass=\"([^\"]*)\"/, (_, classes: string) => {\n return `class=\"${classes} ox-typed-hover\"`;\n });\n }\n return `${openPre} class=\"ox-typed-hover\"`;\n}\n\nfunction wrapHoverRanges(inner: string, hovers: TypedHoverRange[]): string {\n const ranges = [...hovers].sort((a, b) => a.start - b.start || b.end - a.end);\n let output = \"\";\n let htmlIndex = 0;\n let sourceOffset = 0;\n let rangeIndex = 0;\n let openUntil = -1;\n let openHoverIndex = -1;\n\n const startRange = (): void => {\n while (rangeIndex < ranges.length && ranges[rangeIndex]!.start < sourceOffset) {\n rangeIndex += 1;\n }\n const range = ranges[rangeIndex];\n if (!range || range.start !== sourceOffset || openUntil !== -1) {\n return;\n }\n output += `<span class=\"ox-typed-hover-token\" tabindex=\"0\" data-ox-typed-hover=\"${rangeIndex}\">`;\n openUntil = range.end;\n openHoverIndex = rangeIndex;\n rangeIndex += 1;\n };\n\n const endRange = (): void => {\n if (openUntil === sourceOffset && openHoverIndex !== -1) {\n output += \"</span>\";\n openUntil = -1;\n openHoverIndex = -1;\n }\n };\n\n while (htmlIndex < inner.length) {\n const char = inner[htmlIndex]!;\n if (char === \"<\") {\n const close = inner.indexOf(\">\", htmlIndex);\n const tag = close === -1 ? inner.slice(htmlIndex) : inner.slice(htmlIndex, close + 1);\n output += tag;\n htmlIndex += tag.length;\n continue;\n }\n\n startRange();\n if (char === \"&\") {\n const semi = inner.indexOf(\";\", htmlIndex);\n const entity = semi === -1 ? inner.slice(htmlIndex) : inner.slice(htmlIndex, semi + 1);\n output += entity;\n htmlIndex += entity.length;\n sourceOffset += 1;\n endRange();\n continue;\n }\n\n output += char;\n htmlIndex += 1;\n sourceOffset += 1;\n endRange();\n }\n\n if (openHoverIndex !== -1) {\n output += \"</span>\";\n }\n return output;\n}\n\nfunction normalizeFenceText(value: string): string {\n return decodeHtmlEntities(value).replace(/\\r\\n/g, \"\\n\").trim();\n}\n\nfunction decodeHtmlEntities(value: string): string {\n return value\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&amp;/g, \"&\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\");\n}\n\nconst TYPED_HOVER_STYLE = `<style data-ox-typed-hover-style>.ox-typed-hover-token{cursor:help;text-decoration:underline dotted}.ox-typed-hover-overlay{position:fixed;z-index:50;max-width:36rem;padding:.35rem .55rem;border:1px solid #444;border-radius:4px;background:#1e1e1e;color:#d4d4d4;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;pointer-events:none}</style>`;\n\nconst TYPED_HOVER_CLIENT = `<script data-ox-typed-hover-runtime>(function(){if(window.__oxTypedHover)return;window.__oxTypedHover=1;var tip=document.createElement(\"div\");tip.className=\"ox-typed-hover-overlay\";tip.setAttribute(\"role\",\"tooltip\");tip.hidden=true;document.body.appendChild(tip);function payload(token){var pre=token.closest(\".ox-typed-hover\");var data=pre&&pre.nextElementSibling;if(!data||!data.classList.contains(\"ox-typed-hover-data\"))return null;try{return JSON.parse(data.textContent||\"\")}catch(e){return null}}function show(token){var data=payload(token);var item=data&&data.hovers[Number(token.getAttribute(\"data-ox-typed-hover\"))];if(!item)return;tip.textContent=item.type;tip.hidden=false;var box=token.getBoundingClientRect();tip.style.left=Math.max(8,box.left)+\"px\";tip.style.top=Math.max(8,box.top-tip.offsetHeight-8)+\"px\"}function hide(){tip.hidden=true}document.addEventListener(\"mouseover\",function(e){var t=e.target.closest(\".ox-typed-hover-token\");if(t)show(t)});document.addEventListener(\"mouseout\",function(e){var t=e.target.closest(\".ox-typed-hover-token\");if(t&&!t.contains(e.relatedTarget))hide()});document.addEventListener(\"focusin\",function(e){var t=e.target.closest(\".ox-typed-hover-token\");if(t)show(t)});document.addEventListener(\"focusout\",function(e){if(!e.relatedTarget||!e.relatedTarget.closest(\".ox-typed-hover-token\"))hide()});document.addEventListener(\"keydown\",function(e){if(e.key===\"Escape\")hide()})})();</script>`;\n","import type { FileTreeIconOptions, OxContentOptions, ResolvedOptions } from \"./types\";\n\ntype JsFileTreeOptions = {\n enabled: true;\n defaultOpen: boolean;\n icons: boolean;\n iconFolder?: string;\n iconFolderOpen?: string;\n iconFile?: string;\n iconFiles?: Record<string, string>;\n};\n\nconst disabled: ResolvedOptions[\"fileTree\"] = {\n enabled: false,\n defaultOpen: true,\n icons: true,\n};\n\nexport function resolveFileTreeOptions(\n options: OxContentOptions[\"fileTree\"],\n): ResolvedOptions[\"fileTree\"] {\n if (!options) return { ...disabled };\n if (options === true) return enabledDefaults();\n if (options.enabled === false) {\n return { ...enabledDefaults(), enabled: false, ...resolveIcons(options.icons) };\n }\n return {\n enabled: options.enabled ?? true,\n defaultOpen: options.defaultOpen ?? true,\n ...resolveIcons(options.icons),\n };\n}\n\nexport function toJsFileTreeOptions(\n options: ResolvedOptions[\"fileTree\"] | undefined,\n): JsFileTreeOptions | undefined {\n if (!options?.enabled) return undefined;\n return {\n enabled: true,\n defaultOpen: options.defaultOpen,\n icons: options.icons,\n iconFolder: options.iconFolder,\n iconFolderOpen: options.iconFolderOpen,\n iconFile: options.iconFile,\n iconFiles: options.iconFiles,\n };\n}\n\nfunction enabledDefaults(): ResolvedOptions[\"fileTree\"] {\n return { enabled: true, defaultOpen: true, icons: true };\n}\n\nfunction resolveIcons(\n icons: boolean | FileTreeIconOptions | undefined,\n): Pick<\n ResolvedOptions[\"fileTree\"],\n \"icons\" | \"iconFolder\" | \"iconFolderOpen\" | \"iconFile\" | \"iconFiles\"\n> {\n if (icons === false) return { icons: false };\n if (icons === true || icons == null) return { icons: true };\n return {\n icons: true,\n iconFolder: icons.folder,\n iconFolderOpen: icons.folderOpen,\n iconFile: icons.file,\n iconFiles: icons.files,\n };\n}\n","/**\n * Markdown Transformation Engine\n *\n * This module handles the complete transformation pipeline for Markdown files,\n * converting raw Markdown content into JavaScript modules that can be imported\n * by web applications. The transformation process includes:\n *\n * 1. **Parsing**: Uses Rust-based parser via NAPI bindings for high performance\n * 2. **Rendering**: Converts parsed AST to semantic HTML\n * 3. **Enhancement**: Applies syntax highlighting, Mermaid diagram rendering, etc.\n * 4. **Code Generation**: Generates JavaScript/TypeScript module code\n *\n * The generated modules export:\n * - `html`: Rendered HTML content\n * - `frontmatter`: Parsed YAML metadata\n * - `toc`: Hierarchical table of contents\n * - `imports`: MDX import statements from the AST\n * - `exports`: MDX export names from the AST\n * - `components`: Unique JSX component names from the AST\n * - `render`: Client-side render function for dynamic updates\n *\n * @example\n * ```typescript\n * import { transformMarkdown } from './transform';\n *\n * const content = await transformMarkdown(\n * '# Hello\\n\\nWorld',\n * 'path/to/file.md',\n * resolvedOptions\n * );\n *\n * console.log(content.html); // '<h1>Hello</h1><p>World</p>'\n * console.log(content.toc); // [{ depth: 1, text: 'Hello', slug: 'hello', children: [] }]\n * ```\n */\n\nimport type { MdxImport, ResolvedOptions, TocEntry, TransformResult } from \"./types\";\nimport { highlightPageHtml } from \"./highlight\";\nimport { importNapiModule } from \"./napi\";\nimport { transformMermaidStatic } from \"./plugins/mermaid\";\nimport { renderKatexMath } from \"./plugins/math\";\nimport { normalizeSelfClosingEmbeds, transformBuiltinEmbeds } from \"./plugins\";\nimport { protectMermaidSvgs, restoreMermaidSvgs } from \"./plugins/mermaid-protect\";\nimport { typecheckCodeBlocks } from \"./code-blocks\";\nimport { applyTypedHover } from \"./typed-hover\";\nimport { resolveMdxForFilePath } from \"./markdown\";\nimport { toJsFileTreeOptions } from \"./file-tree-options\";\n\n/**\n * NAPI bindings for Rust-based Markdown processing.\n *\n * Provides access to compiled Rust functions for high-performance\n * Markdown parsing and rendering operations.\n */\ninterface NapiBindings {\n /**\n * Simple Markdown parser and renderer in one step.\n * Faster for simple use cases but lacks advanced features.\n *\n * @param source - Raw Markdown content\n * @param options - Parser configuration (GFM flag)\n * @returns Rendered HTML and parsing errors\n */\n parseAndRender: (\n source: string,\n options?: { gfm?: boolean },\n ) => { html: string; errors: string[] };\n\n /**\n * Full-featured Markdown transformation pipeline.\n * Handles frontmatter extraction, TOC generation, and advanced parsing.\n *\n * @param source - Raw Markdown content (may include frontmatter)\n * @param options - Comprehensive transformation options\n * @returns Transformed result with HTML, metadata, and TOC\n */\n transform: (\n source: string,\n options?: JsTransformOptions,\n ) => {\n html: string;\n frontmatter: string;\n toc: Array<{ depth: number; text: string; slug: string; children?: TocEntry[] }>;\n errors: string[];\n imports: MdxImport[];\n exports: string[];\n components: string[];\n };\n\n /**\n * Generates an OG image as SVG.\n *\n * @param data - OG image data (title, description, etc.)\n * @param config - Optional OG image configuration\n * @returns SVG string\n */\n generateOgImageSvg: (data: OgImageData, config?: OgImageConfig) => string;\n\n /**\n * Restores code block metadata after JavaScript-side syntax highlighting.\n *\n * @param originalHtml - HTML before syntax highlighting\n * @param highlightedHtml - HTML after native highlighting\n * @returns Highlighted HTML with original code block metadata reapplied\n */\n mergeHighlightedCodeBlocks: (originalHtml: string, highlightedHtml: string) => string;\n\n sanitizeHtml: (html: string, options?: JsSanitizeOptions) => string;\n\n lintCodeBlocks: (source: string, options?: JsCodeBlockLintOptions) => JsCodeBlockDiagnostic[];\n}\n\n/**\n * OG image data for generating social media preview images.\n */\nexport interface OgImageData {\n /** Page title */\n title: string;\n /** Page description */\n description?: string;\n /** Site name */\n siteName?: string;\n /** Author name */\n author?: string;\n}\n\n/**\n * OG image configuration.\n */\nexport interface OgImageConfig {\n /** Image width in pixels */\n width?: number;\n /** Image height in pixels */\n height?: number;\n /** Background color (hex) */\n backgroundColor?: string;\n /** Text color (hex) */\n textColor?: string;\n /** Title font size */\n titleFontSize?: number;\n /** Description font size */\n descriptionFontSize?: number;\n}\n\n/**\n * Options for Rust-based Markdown transformation.\n *\n * Controls which Markdown extensions and features are enabled\n * during parsing and rendering.\n */\ninterface JsTransformOptions {\n /**\n * Enable GitHub Flavored Markdown extensions.\n * Includes tables, task lists, strikethrough, and autolinks.\n * @default false\n */\n gfm?: boolean;\n\n /**\n * Enable MDX JSX, ESM, and expression nodes.\n * @default false\n */\n mdx?: boolean;\n\n /**\n * Enable footnotes syntax ([^1]: definition).\n * @default false\n */\n footnotes?: boolean;\n\n /**\n * Enable task list syntax (- [ ] unchecked, - [x] checked).\n * @default false\n */\n taskLists?: boolean;\n\n /**\n * Enable table rendering (GFM extension).\n * Requires GFM to be enabled for full functionality.\n * @default false\n */\n tables?: boolean;\n\n /**\n * Enable strikethrough syntax (~~text~~).\n * Requires GFM to be enabled.\n * @default false\n */\n strikethrough?: boolean;\n\n /**\n * Enable automatic link conversion (URLs become clickable).\n * @default false\n */\n autolinks?: boolean;\n\n /**\n * Linkify bare URLs while rendering.\n * @default true\n */\n autolinkUrls?: boolean;\n\n /**\n * Parse YAML frontmatter before transforming.\n * @default true\n */\n frontmatter?: boolean;\n\n /**\n * Maximum heading depth for table of contents.\n * Headings deeper than this level are excluded from TOC.\n * @default 3\n * @min 1\n * @max 6\n */\n tocMaxDepth?: number;\n\n /**\n * Convert `.md` links to `.html` links for SSG output.\n * @default false\n */\n convertMdLinks?: boolean;\n\n /**\n * Base URL for absolute link conversion (e.g., \"/\" or \"/docs/\").\n * @default \"/\"\n */\n baseUrl?: string;\n\n /**\n * Source file path for relative link resolution.\n * Used to determine if the current file is an index file.\n */\n sourcePath?: string;\n\n /**\n * Enable line annotations for code blocks using fence meta.\n * @default false\n */\n codeAnnotations?: boolean;\n\n /**\n * Fence meta key used to read code annotations.\n * @default \"annotate\"\n */\n codeAnnotationMetaKey?: string;\n\n /**\n * Code annotation syntax mode.\n * @default \"attribute\"\n */\n codeAnnotationSyntax?: \"attribute\" | \"vitepress\" | \"both\";\n\n /**\n * Enable line numbers for all code blocks by default.\n * @default false\n */\n codeAnnotationDefaultLineNumbers?: boolean;\n\n wikiLinks?: {\n enabled?: boolean;\n baseUrl?: string;\n };\n\n emojiShortcodes?: {\n enabled?: boolean;\n custom?: Record<string, string>;\n };\n\n attributes?: {\n enabled?: boolean;\n };\n\n badges?: {\n enabled?: boolean;\n };\n\n containers?: {\n enabled?: boolean;\n types?: Record<string, { title?: string; tag?: string }>;\n };\n\n images?: {\n enabled?: boolean;\n lazy?: boolean;\n };\n\n cjkEmphasis?: boolean;\n\n codeImports?: {\n enabled?: boolean;\n rootDir?: string;\n };\n\n includes?: {\n enabled?: boolean;\n rootDir?: string;\n };\n\n cards?: {\n enabled?: boolean;\n };\n\n steps?: {\n enabled?: boolean;\n };\n\n fileTree?: {\n enabled?: boolean;\n defaultOpen?: boolean;\n icons?: boolean;\n iconFolder?: string;\n iconFolderOpen?: string;\n iconFile?: string;\n iconFiles?: Record<string, string>;\n };\n\n sanitize?: JsSanitizeOptions;\n\n editThisPage?: {\n enabled?: boolean;\n repoUrl?: string;\n branch?: string;\n rootDir?: string;\n label?: string;\n };\n\n /**\n * Opt-in `$…$` inline and `$$…$$` block math.\n *\n * Omitted or `false` leaves `$` literal. `true` or `{}` enables defaults;\n * `{ enabled: false }` disables math.\n *\n * @default false\n */\n math?:\n | boolean\n | {\n enabled?: boolean;\n };\n}\n\ninterface JsSanitizeOptions {\n enabled?: boolean;\n allowedTags?: string[];\n allowedAttributes?: string[];\n allowedUrlSchemes?: string[];\n}\n\ninterface JsCodeBlockLintOptions {\n enabled?: boolean;\n languages?: string[];\n requireLanguage?: boolean;\n trailingSpaces?: boolean;\n}\n\ninterface JsCodeBlockDiagnostic {\n ruleId: string;\n severity: string;\n message: string;\n line: number;\n column: number;\n endLine: number;\n endColumn: number;\n language?: string;\n}\n\n/**\n * The NAPI load, cached as the promise rather than as its result.\n *\n * The load yields, and a caller arriving during that yield has to wait for it\n * rather than read a result that is not there yet. Holding the promise is what\n * makes every caller wait for the same load; holding an \"already attempted\"\n * flag beside an unset result meant the first page to arrive loaded the module\n * and every page behind it concluded there were no bindings at all.\n *\n * @internal\n */\nlet napiLoad: Promise<NapiBindings | null> | undefined;\n\n/**\n * Lazily loads and caches NAPI bindings.\n *\n * This function uses lazy loading to defer the import of NAPI bindings\n * until they're actually needed. The bindings are loaded only once and\n * cached for subsequent uses, including by callers that ask for them while\n * that first load is still in flight. If loading fails (e.g., bindings not\n * built), the failure is cached to avoid repeated load attempts.\n *\n * ## Performance Considerations\n *\n * The first call to this function may have a slight performance penalty\n * due to module loading. Subsequent calls use the cached result and are\n * essentially zero-cost.\n *\n * ## Error Handling\n *\n * If NAPI bindings are not available (not built, wrong architecture, etc.),\n * this function returns `null`. The caller should handle this gracefully\n * or provide fallback behavior.\n *\n * @returns Promise resolving to NAPI bindings or null if unavailable\n *\n * @example\n * ```typescript\n * // Simple check with fallback\n * const napi = await loadNapiBindings();\n * if (!napi) {\n * console.warn('NAPI bindings not available, using fallback');\n * return fallbackRender(content);\n * }\n *\n * // Use Rust implementation\n * const result = napi.transform(content, { gfm: true });\n * ```\n *\n * @internal\n */\nfunction loadNapiBindings(): Promise<NapiBindings | null> {\n // Started once; everyone after that awaits the same load, including the\n // callers that arrive while it is still in flight.\n napiLoad ??= importNapiModule().catch((error: unknown) => {\n // NAPI not available (not built, missing dependencies, etc.)\n // Log for debugging but don't throw - allow graceful degradation.\n // The rejection is settled here, so the failure is cached too.\n if (process.env.DEBUG) {\n console.debug(\"[ox-content] NAPI bindings load failed:\", error);\n }\n return null;\n });\n\n return napiLoad;\n}\n\n/**\n * Transforms Markdown content into a JavaScript module.\n *\n * This is the primary entry point for transforming Markdown files. It handles\n * the complete transformation pipeline including parsing, rendering, syntax\n * highlighting, and code generation.\n *\n * ## Pipeline Steps\n *\n * 1. **Parse & Render**: Uses Rust-based parser via NAPI for high performance\n * 2. **Extract Metadata**: Parses YAML frontmatter and generates table of contents\n * 3. **Enhance HTML**: Applies syntax highlighting and Mermaid diagram rendering\n * 4. **Generate Code**: Creates importable JavaScript module\n *\n * ## Generated Module Exports\n *\n * - `html` (string): Rendered HTML content with all enhancements applied\n * - `frontmatter` (object): Parsed YAML frontmatter as JavaScript object\n * - `toc` (array): Hierarchical table of contents entries\n * - `imports` (array): MDX import statements (`source` + specifiers)\n * - `exports` (array): MDX export names\n * - `components` (array): Unique JSX component names\n * - `render` (function): Client-side render function for dynamic updates\n *\n * ## Markdown Features Supported\n *\n * The supported features depend on parser options:\n * - **Commonmark**: Headings, paragraphs, lists, code blocks, links, images\n * - **GFM Extensions**: Tables, task lists, strikethrough, autolinks\n * - **Enhancements**: Syntax highlighting, Mermaid diagrams, TOC generation\n * - **Metadata**: YAML frontmatter parsing\n *\n * ## Performance\n *\n * Uses Rust-based parsing via NAPI bindings for optimal performance. Falls back\n * gracefully if Rust bindings are unavailable.\n *\n * @param source - Raw Markdown source code (may include YAML frontmatter)\n * @param filePath - File path for source attribution and relative link resolution\n * @param options - Resolved plugin options controlling transformation behavior\n *\n * @returns Promise resolving to transformation result with HTML and metadata\n *\n * @throws Error if NAPI bindings are unavailable (can be handled gracefully)\n *\n * @example\n * ```typescript\n * import { transformMarkdown } from './transform';\n * import { resolveOptions } from './index';\n *\n * // Transform a Markdown file with YAML frontmatter\n * const markdown = `---\n * title: Getting Started\n * author: john\n * ---\n *\n * # Getting Started\n *\n * Welcome! This guide explains [transformMarkdown] function.\n *\n * ## Installation\n *\n * \\`\\`\\`bash\n * npm install @ox-content/vite-plugin\n * \\`\\`\\`\n * `;\n *\n * const options = resolveOptions({\n * highlight: true,\n * toc: true,\n * gfm: true,\n * mermaid: true,\n * });\n *\n * const result = await transformMarkdown(markdown, 'docs/getting-started.md', options);\n *\n * // Generated module exports\n * console.log(result.html); // Rendered HTML with syntax highlighting\n * console.log(result.frontmatter); // { title: 'Getting Started', author: 'john' }\n * console.log(result.toc); // [{ depth: 1, text: 'Getting Started', ... }]\n * console.log(result.code); // ES module export statement\n * ```\n */\n/**\n * SSG-specific transform options.\n */\nexport interface SsgTransformOptions {\n /** Convert `.md` links to `.html` links */\n convertMdLinks?: boolean;\n /** Base URL for absolute link conversion */\n baseUrl?: string;\n /** Source file path for relative link resolution */\n sourcePath?: string;\n}\n\nexport async function transformMarkdown(\n source: string,\n filePath: string,\n options: ResolvedOptions,\n ssgOptions?: SsgTransformOptions,\n): Promise<TransformResult> {\n const napi = await loadNapiBindings();\n\n if (!napi) {\n throw new Error(\n \"[ox-content] NAPI bindings not available. Please ensure @ox-content/napi is built.\",\n );\n }\n\n // Use Rust-based transformation, including frontmatter preparation.\n runCodeBlockLint(source, napi, options);\n await runCodeBlockTypecheck(source, options);\n\n const result = napi.transform(source, {\n gfm: options.gfm,\n mdx: resolveMdxForFilePath(filePath, options.mdx),\n footnotes: options.footnotes,\n taskLists: options.taskLists,\n tables: options.tables,\n strikethrough: options.strikethrough,\n autolinks: options.autolinks,\n autolinkUrls: options.autolinks,\n frontmatter: options.frontmatter,\n tocMaxDepth: options.tocMaxDepth,\n convertMdLinks: ssgOptions?.convertMdLinks,\n baseUrl: ssgOptions?.baseUrl,\n sourcePath: ssgOptions?.sourcePath ?? filePath,\n codeAnnotations: options.codeAnnotations?.enabled ?? false,\n codeAnnotationMetaKey: options.codeAnnotations?.metaKey ?? \"annotate\",\n codeAnnotationSyntax: options.codeAnnotations?.notation ?? \"attribute\",\n codeAnnotationDefaultLineNumbers: options.codeAnnotations?.defaultLineNumbers ?? false,\n wikiLinks: options.wikiLinks?.enabled\n ? {\n enabled: true,\n baseUrl: options.wikiLinks.baseUrl,\n }\n : undefined,\n emojiShortcodes: options.emojiShortcodes?.enabled\n ? {\n enabled: true,\n custom: options.emojiShortcodes.custom,\n }\n : undefined,\n attributes: options.attrs?.enabled ? { enabled: true } : undefined,\n badges: options.badges?.enabled ? { enabled: true } : undefined,\n containers: options.containers?.enabled\n ? {\n enabled: true,\n types: options.containers.types,\n }\n : undefined,\n images: options.images?.enabled\n ? {\n enabled: true,\n lazy: options.images.lazy,\n }\n : undefined,\n cjkEmphasis: options.cjkEmphasis ?? false,\n codeImports: options.codeImports?.enabled\n ? {\n enabled: true,\n rootDir: options.codeImports.rootDir,\n }\n : undefined,\n includes: options.includes?.enabled\n ? {\n enabled: true,\n rootDir: options.includes.rootDir,\n }\n : undefined,\n cards: options.cards?.enabled ? { enabled: true } : undefined,\n steps: options.steps?.enabled ? { enabled: true } : undefined,\n fileTree: toJsFileTreeOptions(options.fileTree),\n // Sanitize once at the end of the JS pipeline so opt-in embeds can be\n // expanded before the allow-list is applied.\n sanitize: undefined,\n editThisPage: options.editThisPage?.enabled\n ? {\n enabled: true,\n repoUrl: options.editThisPage.repoUrl,\n branch: options.editThisPage.branch,\n rootDir: options.editThisPage.rootDir,\n label: options.editThisPage.label,\n }\n : undefined,\n math: isMathEnabled(options.math),\n });\n\n if (result.errors.length > 0) {\n console.warn(\"[ox-content] Transform warnings:\", result.errors);\n }\n\n // Normalize before the first rehype pass (highlighting), which would\n // otherwise reparse a self-closing embed tag as an unclosed element.\n let html = normalizeSelfClosingEmbeds(result.html);\n const frontmatter = parseFrontmatterJson(result.frontmatter);\n\n const toc = options.toc ? result.toc.map(normalizeTocEntry) : [];\n\n // Transform mermaid diagrams before highlighting to avoid entity re-encoding\n if (options.mermaid) {\n html = await transformMermaidStatic(html);\n }\n\n // Protect mermaid SVGs from rehype processing (which corrupts <br /> in foreignObjects)\n const { html: protectedHtml, svgs } = protectMermaidSvgs(html);\n html = protectedHtml;\n\n // Apply syntax highlighting if enabled\n if (options.highlight) {\n // The native document pass handles the whole page without an HTML parser\n // in the loop. Languages with no native grammar stay as the original\n // `<pre><code>`. Only markup the pass cannot read — where a text scan and\n // a real HTML parser would disagree — falls back to a native-only\n // per-block walk.\n html = await highlightPageHtml(html, napi.mergeHighlightedCodeBlocks);\n }\n\n // Render static built-in embeds while Mermaid SVG placeholders are protected.\n html = await transformBuiltinEmbeds(\n html,\n options.embeds ?? {\n github: {},\n openGraph: {},\n },\n );\n\n // GitHub source cards are created after the first highlight pass, so run\n // highlighting again when those blocks are present.\n if (options.highlight && html.includes(\"ox-github-code-block\")) {\n html = await highlightPageHtml(html, napi.mergeHighlightedCodeBlocks);\n }\n\n // Restore protected SVGs\n html = restoreMermaidSvgs(html, svgs);\n\n if (options.sanitize?.enabled) {\n html = napi.sanitizeHtml(html, toJsSanitizeOptions(options.sanitize));\n }\n\n if (isMathEnabled(options.math)) {\n html = await renderKatexMath(html);\n }\n\n const imports = result.imports ?? [];\n const exports = result.exports ?? [];\n const components = result.components ?? [];\n html = await applyTypedHover(source, html, options.typedHover);\n\n // Generate JavaScript module code\n const code = generateModuleCode(html, frontmatter, toc, imports, exports, components, filePath);\n\n return {\n code,\n html,\n frontmatter,\n toc,\n imports,\n exports,\n components,\n };\n}\n\nasync function runCodeBlockTypecheck(source: string, options: ResolvedOptions): Promise<void> {\n const typecheck = options.codeBlockTypecheck;\n if (!typecheck?.enabled || !source.includes(\"```\")) {\n return;\n }\n\n const diagnostics = await typecheckCodeBlocks(source, {\n languages: typecheck.languages,\n requireMeta: typecheck.requireMeta,\n tsgoCommand: typecheck.tsgoCommand,\n });\n if (diagnostics.length === 0) {\n return;\n }\n\n const message = diagnostics\n .slice(0, 3)\n .map((diagnostic) => `${diagnostic.ruleId} at ${diagnostic.line}: ${diagnostic.message}`)\n .join(\"\\n\");\n if (typecheck.mode === \"error\") {\n throw new Error(`[ox-content] Code block type-checking failed:\\n${message}`);\n }\n console.warn(`[ox-content] Code block type-checking warnings:\\n${message}`);\n}\n\nfunction runCodeBlockLint(source: string, napi: NapiBindings, options: ResolvedOptions): void {\n const lint = options.codeBlockLint;\n if (!lint?.enabled || !source.includes(\"```\")) {\n return;\n }\n\n const diagnostics = napi.lintCodeBlocks(source, {\n enabled: true,\n languages: lint.languages,\n requireLanguage: lint.requireLanguage,\n trailingSpaces: lint.trailingSpaces,\n });\n if (diagnostics.length === 0) {\n return;\n }\n\n const message = diagnostics\n .slice(0, 5)\n .map((diagnostic) => {\n return `${diagnostic.ruleId} at ${diagnostic.line}:${diagnostic.column} ${diagnostic.message}`;\n })\n .join(\"\\n\");\n if (lint.mode === \"error\") {\n throw new Error(`[ox-content] Code block lint failed:\\n${message}`);\n }\n console.warn(`[ox-content] Code block lint warnings:\\n${message}`);\n}\n\nfunction toJsSanitizeOptions(options: ResolvedOptions[\"sanitize\"]): JsSanitizeOptions {\n return {\n enabled: true,\n allowedTags: options.allowedTags,\n allowedAttributes: options.allowedAttributes,\n allowedUrlSchemes: options.allowedUrlSchemes,\n };\n}\n\nfunction parseFrontmatterJson(json: string): Record<string, unknown> {\n if (!json) {\n return {};\n }\n\n try {\n const value = JSON.parse(json);\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction normalizeTocEntry(entry: {\n depth: number;\n text: string;\n slug: string;\n children?: TocEntry[];\n}): TocEntry {\n return {\n depth: entry.depth,\n text: entry.text,\n slug: entry.slug,\n children: (entry.children ?? []).map(normalizeTocEntry),\n };\n}\n\n/**\n * Generates the JavaScript module code.\n *\n * MDX metadata is serialized as JSON. User `import` / `export` source is never\n * emitted as live JavaScript, so transform does not execute module side effects.\n */\nfunction generateModuleCode(\n html: string,\n frontmatter: Record<string, unknown>,\n toc: TocEntry[],\n imports: MdxImport[],\n exports: string[],\n components: string[],\n filePath: string,\n): string {\n const htmlJson = JSON.stringify(html);\n const frontmatterJson = JSON.stringify(frontmatter);\n const tocJson = JSON.stringify(toc);\n const importsJson = JSON.stringify(imports);\n const exportsJson = JSON.stringify(exports);\n const componentsJson = JSON.stringify(components);\n\n return `\n// Generated by @ox-content/vite-plugin\n// Source: ${filePath}\n\n/**\n * Rendered HTML content.\n */\nexport const html = ${htmlJson};\n\n/**\n * Parsed frontmatter.\n */\nexport const frontmatter = ${frontmatterJson};\n\n/**\n * Table of contents.\n */\nexport const toc = ${tocJson};\n\n/**\n * MDX import statements collected from the AST.\n */\nexport const imports = ${importsJson};\n\n/**\n * MDX export names collected from the AST.\n */\nexport const exports = ${exportsJson};\n\n/**\n * Unique JSX component names collected from the AST.\n */\nexport const components = ${componentsJson};\n\n/**\n * Default export with all data.\n */\nexport default {\n html,\n frontmatter,\n toc,\n imports,\n exports,\n components,\n};\n\n// HMR support\nif (import.meta.hot) {\n import.meta.hot.accept((newModule) => {\n if (newModule) {\n // Trigger re-render with new content\n import.meta.hot.invalidate();\n }\n });\n}\n`;\n}\n\n/**\n * Extracts imports from Markdown content.\n *\n * Supports importing components for interactive islands.\n */\nexport function extractImports(content: string): string[] {\n const importRegex = /^import\\s+.+\\s+from\\s+['\"](.+)['\"]/gm;\n const imports: string[] = [];\n let match;\n\n while ((match = importRegex.exec(content)) !== null) {\n imports.push(match[1]);\n }\n\n return imports;\n}\n\n/**\n * Generates an OG image SVG using the Rust-based generator.\n *\n * This function uses the Rust NAPI bindings to generate SVG-based\n * OG images for social media previews. The SVG can be served directly\n * or converted to PNG/JPEG for broader compatibility.\n *\n * In the future, custom JS templates can be provided to override\n * the default Rust-based template.\n *\n * @param data - OG image data (title, description, etc.)\n * @param config - Optional OG image configuration\n * @returns SVG string or null if NAPI bindings are unavailable\n */\nexport async function generateOgImageSvg(\n data: OgImageData,\n config?: OgImageConfig,\n): Promise<string | null> {\n const napi = await loadNapiBindings();\n if (!napi) {\n return null;\n }\n\n // Convert config to NAPI format (camelCase to snake_case)\n const napiConfig = config\n ? {\n width: config.width,\n height: config.height,\n backgroundColor: config.backgroundColor,\n textColor: config.textColor,\n titleFontSize: config.titleFontSize,\n descriptionFontSize: config.descriptionFontSize,\n }\n : undefined;\n\n return napi.generateOgImageSvg(data, napiConfig);\n}\n\nfunction isMathEnabled(math: boolean | { enabled?: boolean } | undefined): boolean {\n if (math === true) return true;\n if (math === false || math == null) return false;\n return math.enabled !== false;\n}\n","/**\n * Source Documentation Extraction and Generation\n *\n * This module provides comprehensive tools for extracting JSDoc/TSDoc comments\n * from TypeScript/JavaScript source files and automatically generating Markdown\n * documentation.\n *\n * ## Features\n *\n * - **Automatic Extraction**: Parses JSDoc comments from functions, classes, interfaces, and types\n * - **Flexible Filtering**: Include/exclude patterns for selective documentation\n * - **Markdown Generation**: Converts extracted docs to organized Markdown files\n * - **Navigation Generation**: Auto-generates sidebar navigation metadata\n * - **GitHub Links**: Includes clickable links to source code on GitHub\n *\n * ## Supported JSDoc Tags\n *\n * - `@param {type} name - description` - Function parameter documentation\n * - `@returns {type} description` - Return value documentation\n * - `@example` - Code examples (multi-line blocks)\n * - `@private` - Mark item as private (excluded from docs if private=false)\n * - `@default value` - Default parameter value\n * - Custom tags are preserved in the `tags` field\n *\n * ## Usage Flow\n *\n * 1. Call `extractDocs()` to parse source files\n * 2. Call `generateMarkdown()` to create Markdown content\n * 3. Call `writeDocs()` to write files to output directory\n * 4. Generated nav.ts can be imported for sidebar navigation\n *\n * @example\n * ```typescript\n * import { extractDocs, generateMarkdown, writeDocs } from './docs';\n *\n * const docsOptions = {\n * enabled: true,\n * src: ['./src'],\n * out: './docs/api',\n * include: ['**\\/*.ts'],\n * exclude: ['**\\/*.test.ts'],\n * groupBy: 'file',\n * githubUrl: 'https://github.com/user/project',\n * };\n *\n * const extracted = await extractDocs(['./src'], docsOptions);\n * const markdown = generateMarkdown(extracted, docsOptions);\n * await writeDocs(markdown, './docs/api', extracted, docsOptions);\n * ```\n */\n\nimport { readFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport type {\n ResolvedDocsOptions,\n ExtractedDocs,\n DocEntry,\n ResolvedDocsEntryPoint,\n DocsOptions,\n} from \"./types\";\nimport { importNapiModule, importNapiModuleSync } from \"./napi\";\n\ntype NapiMarkdownTag = { tag: string; value: string };\n\nconst DEFAULT_DOCS_INCLUDE = [\n \"**/*.ts\",\n \"**/*.tsx\",\n \"**/*.js\",\n \"**/*.jsx\",\n \"**/*.mts\",\n \"**/*.mjs\",\n \"**/*.cts\",\n \"**/*.cjs\",\n];\n\n/**\n * Extracts JSDoc documentation from source files in specified directories.\n *\n * This function recursively searches directories for source files matching\n * the include/exclude patterns, then extracts all documented items (functions,\n * classes, interfaces, types) from those files.\n *\n * ## Process\n *\n * 1. **File Discovery**: Recursively walks directories, applying filters\n * 2. **File Reading**: Loads each matching file's content\n * 3. **JSDoc Extraction**: Parses JSDoc comments using the native parser\n * 4. **Declaration Matching**: Pairs JSDoc comments with source declarations\n * 5. **Result Collection**: Aggregates extracted documentation by file\n *\n * ## Include/Exclude Patterns\n *\n * Patterns support:\n * - `**` - Match any directory structure\n * - `*` - Match any filename\n * - Standard glob patterns (e.g., `**\\/*.test.ts`)\n *\n * ## Performance Considerations\n *\n * - Uses filesystem I/O which can be slow for large codebases\n * - Consider using more specific include patterns to reduce file scanning\n * - Results are not cached; call once per build/dev session\n *\n * @param srcDirs - Array of source directory paths to scan\n * @param options - Documentation extraction options (filters, grouping, etc.)\n *\n * @returns Promise resolving to array of extracted documentation by file.\n * Each ExtractedDocs object contains file path and array of DocEntry items.\n *\n * @example\n * ```typescript\n * const docs = await extractDocs(\n * ['./packages/vite-plugin/src'],\n * {\n * enabled: true,\n * src: [],\n * out: 'docs',\n * include: ['**\\/*.ts'],\n * exclude: ['**\\/*.test.ts', '**\\/*.spec.ts'],\n * format: 'markdown',\n * private: false,\n * toc: true,\n * groupBy: 'file',\n * generateNav: true,\n * }\n * );\n *\n * // Returns:\n * // [\n * // {\n * // file: '/path/to/transform.ts',\n * // entries: [\n * // { name: 'transformMarkdown', kind: 'function', ... },\n * // { name: 'loadNapiBindings', kind: 'function', ... },\n * // ]\n * // },\n * // ...\n * // ]\n * ```\n */\nexport async function extractDocs(\n srcDirs: string[],\n options: ResolvedDocsOptions,\n): Promise<ExtractedDocs[]> {\n const napi = await importNapiModule();\n\n if (options.entryPoints?.length) {\n const extractDocsFromEntryPoints = (\n napi as {\n extractDocsFromEntryPoints?: (\n entryPoints: ResolvedDocsEntryPoint[],\n options?: {\n root?: string;\n private?: boolean;\n internal?: boolean;\n typeParameters?: boolean;\n },\n ) => Array<{\n file: string;\n description?: string;\n sourcePath?: string;\n examples?: string[];\n tags?: NapiMarkdownTag[];\n entries: DocEntry[];\n }>;\n }\n ).extractDocsFromEntryPoints;\n\n if (!extractDocsFromEntryPoints) {\n throw new Error(\n \"[ox-content] extractDocsFromEntryPoints is not available from @ox-content/napi.\",\n );\n }\n\n return extractDocsFromEntryPoints(options.entryPoints, {\n root: process.cwd(),\n private: options.private,\n internal: options.internal,\n typeParameters: options.typeParameters,\n }).map((doc) => ({\n file: doc.file,\n description: doc.description,\n sourcePath: doc.sourcePath,\n examples: doc.examples,\n tags: toTagRecord(doc.tags),\n entries: doc.entries,\n }));\n }\n\n const extractDocsFromDirectories = (\n napi as {\n extractDocsFromDirectories?: (\n srcDirs: string[],\n include: string[],\n exclude: string[],\n includePrivate?: boolean,\n includeInternal?: boolean,\n typeParameters?: boolean,\n ) => Array<{ file: string; entries: DocEntry[] }>;\n }\n ).extractDocsFromDirectories;\n\n if (!extractDocsFromDirectories) {\n throw new Error(\n \"[ox-content] extractDocsFromDirectories is not available from @ox-content/napi.\",\n );\n }\n\n return extractDocsFromDirectories(\n srcDirs,\n options.include,\n options.exclude,\n options.private,\n options.internal,\n options.typeParameters,\n ).map((doc) => ({ file: doc.file, entries: doc.entries }));\n}\n\n/**\n * Generates Markdown documentation from extracted docs.\n */\nexport function generateMarkdown(\n docs: ExtractedDocs[],\n options: ResolvedDocsOptions,\n): Record<string, string> {\n const napi = importNapiModuleSync();\n\n if (typeof napi.generateDocsMarkdown !== \"function\") {\n throw new Error(\n \"[ox-content] generateDocsMarkdown is not available from @ox-content/napi. Please rebuild the NAPI package.\",\n );\n }\n\n return napi.generateDocsMarkdown(toRustDocsModules(docs), {\n groupBy: options.groupBy,\n githubUrl: options.githubUrl,\n linkStyle: options.linkStyle,\n basePath: options.basePath,\n pathStrategy: options.pathStrategy,\n renderStyle: options.renderStyle,\n indexFormat: options.indexFormat,\n parametersFormat: options.parametersFormat,\n interfacePropertiesFormat: options.interfacePropertiesFormat,\n classPropertiesFormat: options.classPropertiesFormat,\n typeAliasPropertiesFormat: options.typeAliasPropertiesFormat,\n enumMembersFormat: options.enumMembersFormat,\n propertyMembersFormat: options.propertyMembersFormat,\n typeDeclarationFormat: options.typeDeclarationFormat,\n renderStats: options.renderStats,\n renderGeneratedBy: options.renderGeneratedBy,\n groupOrder: options.groupOrder,\n sort: options.sort,\n sortEntryPoints: options.sortEntryPoints,\n kindSortOrder: options.kindSortOrder,\n singleEntryRoot: options.singleEntryRoot,\n });\n}\n\n/**\n * Writes generated documentation to the output directory.\n */\nexport async function writeDocs(\n docs: Record<string, string>,\n outDir: string,\n extractedDocs?: ExtractedDocs[],\n options?: ResolvedDocsOptions,\n): Promise<void> {\n const napi = importNapiModuleSync();\n\n if (typeof napi.writeGeneratedDocs !== \"function\") {\n throw new Error(\n \"[ox-content] writeGeneratedDocs is not available from @ox-content/napi. Please rebuild the NAPI package.\",\n );\n }\n\n napi.writeGeneratedDocs(\n docs,\n outDir,\n extractedDocs ? toRustDocsModules(extractedDocs) : undefined,\n {\n generateNav: options?.generateNav ?? false,\n groupBy: options?.groupBy ?? \"file\",\n generatedAt: existingGeneratedAt(outDir) ?? new Date().toISOString(),\n basePath: options?.basePath,\n pathStrategy: options?.pathStrategy,\n groupOrder: options?.groupOrder,\n sort: options?.sort,\n sortEntryPoints: options?.sortEntryPoints,\n kindSortOrder: options?.kindSortOrder,\n singleEntryRoot: options?.singleEntryRoot,\n },\n );\n}\n\n/** Keep `docs.json`'s timestamp stable across regenerations of the same tree. */\nfunction existingGeneratedAt(outDir: string): string | undefined {\n try {\n const parsed = JSON.parse(readFileSync(path.join(outDir, \"docs.json\"), \"utf8\")) as {\n generatedAt?: unknown;\n };\n return typeof parsed.generatedAt === \"string\" && parsed.generatedAt.length > 0\n ? parsed.generatedAt\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function toRustDocsModules(docs: ExtractedDocs[]) {\n return docs.map((doc) => ({\n file: doc.file,\n description: doc.description,\n sourcePath: doc.sourcePath,\n examples: doc.examples,\n tags: doc.tags ? Object.entries(doc.tags).map(([tag, value]) => ({ tag, value })) : undefined,\n entries: doc.entries.map((entry) => ({\n name: entry.name,\n kind: entry.kind,\n description: entry.description,\n params: entry.params,\n returns: entry.returns,\n examples: entry.examples,\n tags: entry.tags\n ? Object.entries(entry.tags).map(([tag, value]) => ({ tag, value }))\n : undefined,\n private: entry.private ?? false,\n file: entry.file,\n line: entry.line,\n endLine: entry.endLine,\n signature: entry.signature,\n members: entry.members,\n })),\n }));\n}\n\nfunction toTagRecord(tags: NapiMarkdownTag[] | undefined) {\n if (!tags?.length) {\n return undefined;\n }\n return Object.fromEntries(tags.map(({ tag, value }) => [tag, value]));\n}\n\n/**\n * Resolves docs options with defaults.\n */\nexport function resolveDocsOptions(options: false): false;\nexport function resolveDocsOptions(options?: DocsOptions): ResolvedDocsOptions;\nexport function resolveDocsOptions(\n options: DocsOptions | false | undefined,\n): ResolvedDocsOptions | false;\nexport function resolveDocsOptions(\n options: DocsOptions | false | undefined,\n): ResolvedDocsOptions | false {\n if (options === false) {\n return false;\n }\n\n const opts = options || {};\n\n return {\n enabled: opts.enabled ?? true,\n src: opts.src ?? [\"./src\"],\n out: opts.out ?? \"docs/api\",\n include: opts.include ?? DEFAULT_DOCS_INCLUDE,\n exclude: opts.exclude ?? [\"**/*.test.*\", \"**/*.spec.*\", \"node_modules\"],\n entryPoints: opts.entryPoints?.map((entryPoint) =>\n typeof entryPoint === \"string\" ? { path: entryPoint } : entryPoint,\n ),\n format: opts.format ?? \"markdown\",\n private: opts.private ?? false,\n internal: opts.internal ?? false,\n toc: false,\n groupBy: opts.groupBy ?? \"file\",\n githubUrl: opts.githubUrl,\n linkStyle: opts.linkStyle ?? \"markdown\",\n basePath: opts.basePath,\n pathStrategy: opts.pathStrategy ?? \"flat\",\n renderStyle: opts.renderStyle ?? \"html\",\n indexFormat: opts.indexFormat ?? \"none\",\n parametersFormat: opts.parametersFormat ?? \"none\",\n interfacePropertiesFormat: opts.interfacePropertiesFormat ?? \"none\",\n classPropertiesFormat: opts.classPropertiesFormat ?? \"none\",\n typeAliasPropertiesFormat: opts.typeAliasPropertiesFormat ?? \"none\",\n enumMembersFormat: opts.enumMembersFormat ?? \"none\",\n propertyMembersFormat: opts.propertyMembersFormat ?? \"none\",\n typeDeclarationFormat: opts.typeDeclarationFormat ?? \"none\",\n typeParameters: opts.typeParameters ?? false,\n renderStats: opts.renderStats ?? true,\n renderGeneratedBy: opts.renderGeneratedBy ?? true,\n groupOrder: opts.groupOrder,\n sort: opts.sort,\n sortEntryPoints: opts.sortEntryPoints ?? true,\n kindSortOrder: opts.kindSortOrder,\n singleEntryRoot: opts.singleEntryRoot ?? \"preserve\",\n generateNav: opts.generateNav ?? true,\n };\n}\n","/**\n * HTML → PNG renderer using Chromium screenshots via Playwright.\n */\n\nimport * as path from \"path\";\nimport type { Page } from \"playwright\";\n\n/**\n * Wraps template HTML in a minimal document with viewport locked to given dimensions.\n */\nfunction wrapHtml(bodyHtml: string, width: number, height: number, useBaseUrl: boolean): string {\n const baseTag = useBaseUrl ? `\\n<base href=\"http://localhost/\">` : \"\";\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">${baseTag}\n<style>\n* { margin: 0; padding: 0; box-sizing: border-box; }\nhtml, body { width: ${width}px; height: ${height}px; overflow: hidden; }\n</style>\n</head>\n<body>${bodyHtml}</body>\n</html>`;\n}\n\n/**\n * Renders an HTML string to a PNG buffer using Chromium.\n *\n * @param page - Playwright page instance\n * @param html - HTML string from template function\n * @param width - Image width\n * @param height - Image height\n * @param publicDir - Optional public directory for serving local assets (images, fonts, etc.)\n * @returns PNG buffer\n */\nexport async function renderHtmlToPng(\n page: Page,\n html: string,\n width: number,\n height: number,\n publicDir?: string,\n): Promise<Buffer> {\n await page.setViewportSize({ width, height });\n\n // Serve local assets from the public directory\n if (publicDir) {\n const fs = await import(\"fs/promises\");\n await page.route(\"**/*\", async (route) => {\n const url = new URL(route.request().url());\n // Only intercept paths that look like local assets (not data: or blob:)\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n await route.continue();\n return;\n }\n const filePath = path.join(publicDir, url.pathname);\n try {\n const body = await fs.readFile(filePath);\n const ext = path.extname(filePath).toLowerCase();\n const mimeTypes: Record<string, string> = {\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".css\": \"text/css\",\n \".js\": \"application/javascript\",\n };\n await route.fulfill({\n body,\n contentType: mimeTypes[ext] || \"application/octet-stream\",\n });\n } catch {\n await route.continue();\n }\n });\n }\n\n const fullHtml = wrapHtml(html, width, height, !!publicDir);\n await page.setContent(fullHtml, { waitUntil: \"networkidle\" });\n\n const screenshot = await page.screenshot({\n type: \"png\",\n clip: { x: 0, y: 0, width, height },\n });\n\n return Buffer.from(screenshot);\n}\n","/**\n * Chromium browser session with automatic cleanup via Explicit Resource Management.\n *\n * Usage:\n * await using session = await openBrowser();\n * const png = await session.renderPage(html, 1200, 630);\n * // browser.close() is called automatically when session goes out of scope\n */\n\nimport type { Page } from \"playwright\";\nimport { renderHtmlToPng } from \"./renderer\";\n\nconst PLAYWRIGHT_BROWSER_INSTALL_HINT =\n \"Install Playwright browsers with `npx playwright install chromium` to enable OG image generation.\";\n\nlet chromiumUnavailableWarned = false;\n\n/**\n * A browser session that can render HTML pages to PNG.\n * Implements AsyncDisposable for automatic cleanup via `await using`.\n */\nexport interface OgBrowserSession extends AsyncDisposable {\n renderPage(html: string, width: number, height: number, publicDir?: string): Promise<Buffer>;\n}\n\n/**\n * Opens a Chromium browser and returns a session for rendering OG images.\n * Returns null if Playwright/Chromium is not available.\n *\n * The session implements AsyncDisposable — use `await using` for automatic cleanup:\n * ```ts\n * await using session = await openBrowser();\n * if (!session) return;\n * const png = await session.renderPage(html, 1200, 630);\n * ```\n */\nexport async function openBrowser(): Promise<OgBrowserSession | null> {\n try {\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch({\n headless: true,\n args: [\n \"--no-sandbox\",\n \"--disable-setuid-sandbox\",\n \"--disable-dev-shm-usage\",\n \"--disable-gpu\",\n ],\n });\n\n return {\n async renderPage(\n html: string,\n width: number,\n height: number,\n publicDir?: string,\n ): Promise<Buffer> {\n const page: Page = await browser.newPage();\n try {\n return await renderHtmlToPng(page, html, width, height, publicDir);\n } finally {\n await page.close();\n }\n },\n\n async [Symbol.asyncDispose]() {\n try {\n await browser.close();\n } catch {\n // Ignore close errors\n }\n },\n };\n } catch (err) {\n warnChromiumUnavailableOnce(err);\n return null;\n }\n}\n\nfunction warnChromiumUnavailableOnce(err: unknown): void {\n if (chromiumUnavailableWarned) {\n return;\n }\n\n chromiumUnavailableWarned = true;\n console.warn(\n `[ox-content:og-image] Chromium not available, skipping OG image generation. ${formatChromiumUnavailableDetail(\n err,\n )}`,\n );\n}\n\nfunction formatChromiumUnavailableDetail(err: unknown): string {\n const message = err instanceof Error ? err.message : String(err);\n\n if (\n message.includes(\"Executable doesn't exist\") ||\n message.includes(\"Please run the following command to download new browsers\")\n ) {\n return PLAYWRIGHT_BROWSER_INSTALL_HINT;\n }\n\n return (\n message\n .split(/\\r?\\n/)\n .find((line) => line.trim())\n ?.trim() ?? \"Unknown launch error.\"\n );\n}\n","/**\n * Default OG image template.\n *\n * Uses inline HTML/CSS for a flat, low-color brand card with title,\n * description, siteName, and tags. No external dependencies required.\n */\n\nimport type { OgImageTemplateFn, OgImageTemplateProps } from \"./types\";\n\n/**\n * Escapes HTML special characters.\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nfunction normalizeBrandValue(str: string): string {\n return str.replace(/\\s+/g, \"\").toLowerCase();\n}\n\nfunction renderWordmarkSvg(): string {\n return `<svg width=\"430\" height=\"102\" viewBox=\"0 0 270 64\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <linearGradient id=\"ogWordmarkGradient\" x1=\"286\" y1=\"10\" x2=\"320\" y2=\"54\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0%\" stop-color=\"#355cff\"/>\n <stop offset=\"100%\" stop-color=\"#74c7ff\"/>\n </linearGradient>\n </defs>\n <text\n x=\"2\"\n y=\"43\"\n fill=\"#eff6ff\"\n font-family=\"IBM Plex Sans, IBM Plex Mono, Avenir Next, Segoe UI, sans-serif\"\n font-size=\"34\"\n font-weight=\"700\"\n letter-spacing=\"-1.4\"\n >\n OXCONTENT\n </text>\n <text\n x=\"213\"\n y=\"43.5\"\n fill=\"#eff6ff\"\n font-family=\"IBM Plex Sans, IBM Plex Mono, Avenir Next, Segoe UI, sans-serif\"\n font-size=\"40\"\n font-weight=\"400\"\n >\n (\n </text>\n <g transform=\"translate(216 9) scale(0.089) rotate(-7 256 256)\">\n <path\n d=\"M161 96H286C298 96 309 101 318 110L352 144C361 153 366 164 366 176V386C366 399 355 410 342 410H161C148 410 138 399 138 386V120C138 107 148 96 161 96Z\"\n fill=\"url(#ogWordmarkGradient)\"\n />\n </g>\n <text\n x=\"252\"\n y=\"43.5\"\n fill=\"#eff6ff\"\n font-family=\"IBM Plex Sans, IBM Plex Mono, Avenir Next, Segoe UI, sans-serif\"\n font-size=\"40\"\n font-weight=\"400\"\n >\n )\n </text>\n</svg>`;\n}\n\n/**\n * Returns the built-in default template function.\n */\nexport function getDefaultTemplate(): OgImageTemplateFn {\n return function defaultTemplate(props: OgImageTemplateProps): string {\n const { title, description, siteName } = props;\n const rawBrand = siteName?.trim() ? siteName : \"Ox Content\";\n const isBrandCard = normalizeBrandValue(title) === normalizeBrandValue(rawBrand);\n\n const heroTitle = isBrandCard ? \"High-performance Markdown toolkit\" : title;\n const heroDescription = isBrandCard\n ? \"Rust-powered docs and high-performance Markdown tooling.\"\n : description && description.trim().length > 0\n ? description\n : \"Rust-powered docs and Markdown tooling.\";\n const descriptionHtml =\n heroDescription.trim().length > 0\n ? `<p style=\"max-width:760px;font-size:28px;color:#93a4c3;line-height:1.45;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;\">${escapeHtml(heroDescription)}</p>`\n : \"\";\n\n return `<div style=\"width:100%;height:100%;position:relative;overflow:hidden;box-sizing:border-box;padding:56px 64px 52px;background:#0b1220;font-family:'IBM Plex Sans','Avenir Next','Segoe UI',system-ui,sans-serif;color:#eff6ff;border:1px solid #223252;border-top:4px solid #4f6fae;\">\n <div style=\"position:relative;z-index:1;display:flex;flex-direction:column;height:100%;\">\n <div style=\"display:flex;align-items:flex-start;\">${renderWordmarkSvg()}</div>\n <div style=\"display:flex;flex-direction:column;justify-content:center;gap:24px;max-width:860px;flex:1;padding:22px 0 0;\">\n <h1 style=\"font-size:78px;font-weight:700;color:#eff6ff;line-height:1.02;letter-spacing:-0.055em;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;\">${escapeHtml(heroTitle)}</h1>\n ${descriptionHtml}\n </div>\n </div>\n</div>`;\n };\n}\n","/**\n * Content-hash based caching for OG images.\n *\n * Uses SHA256 of (template source + props + options) to determine\n * if a re-render is needed. Cache dir: .cache/og-images\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport * as crypto from \"crypto\";\n\n/**\n * Computes a cache key from template + props + options.\n */\nexport function computeCacheKey(\n templateSource: string,\n props: Record<string, unknown>,\n width: number,\n height: number,\n): string {\n const data = JSON.stringify({ templateSource, props, width, height });\n return crypto.createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\n/**\n * Checks if a cached PNG exists for the given key.\n * Returns the cached file path if found, null otherwise.\n */\nexport async function getCached(cacheDir: string, key: string): Promise<Buffer | null> {\n const filePath = path.join(cacheDir, `${key}.png`);\n try {\n return await fs.readFile(filePath);\n } catch {\n return null;\n }\n}\n\n/**\n * Writes a PNG buffer to the cache.\n */\nexport async function writeCache(cacheDir: string, key: string, png: Buffer): Promise<void> {\n await fs.mkdir(cacheDir, { recursive: true });\n const filePath = path.join(cacheDir, `${key}.png`);\n await fs.writeFile(filePath, png);\n}\n","/**\n * Public API for Chromium-based OG image generation.\n *\n * Orchestrates browser lifecycle, template resolution, caching,\n * and batch rendering with concurrency control.\n */\nimport * as path from \"path\";\nimport * as crypto from \"crypto\";\nimport { openBrowser } from \"./browser\";\nimport type { OgBrowserSession } from \"./browser\";\nimport { getDefaultTemplate } from \"./template\";\nimport { computeCacheKey, getCached, writeCache } from \"./cache\";\nimport type {\n OgImageOptions,\n ResolvedOgImageOptions,\n OgImageTemplateProps,\n OgImageTemplateFn,\n} from \"./types\";\n\nexport type {\n OgImageOptions,\n ResolvedOgImageOptions,\n OgImageTemplateProps,\n OgImageTemplateFn,\n} from \"./types\";\n\nexport type { OgBrowserSession } from \"./browser\";\n\n/**\n * Resolves user-provided OG image options with defaults.\n */\nexport function resolveOgImageOptions(options: OgImageOptions | undefined): ResolvedOgImageOptions {\n return {\n template: options?.template,\n vuePlugin: options?.vuePlugin ?? \"vitejs\",\n width: options?.width ?? 1200,\n height: options?.height ?? 630,\n cache: options?.cache ?? true,\n concurrency: options?.concurrency ?? 1,\n };\n}\n\n/**\n * A single page entry for batch OG image generation.\n */\nexport interface OgImagePageEntry {\n /** Props to pass to the template */\n props: OgImageTemplateProps;\n /** Absolute path to write the output PNG */\n outputPath: string;\n}\n\n/**\n * Result of OG image generation for a single page.\n */\nexport interface OgImageResult {\n outputPath: string;\n cached: boolean;\n error?: string;\n}\n\n/**\n * Resolves the template function from options.\n *\n * Dispatches by file extension:\n * - `.vue` → Vue SFC (SSR via vue/server-renderer)\n * - `.svelte` → Svelte SFC (SSR via svelte/server)\n * - `.tsx`/`.jsx` → React Server Component (SSR via react-dom/server)\n * - others → TypeScript template (direct function export)\n */\nasync function resolveTemplate(\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageTemplateFn> {\n if (!options.template) {\n return getDefaultTemplate();\n }\n\n const templatePath = path.resolve(root, options.template);\n\n // Verify file exists\n const fs = await import(\"fs/promises\");\n try {\n await fs.access(templatePath);\n } catch {\n throw new Error(`[ox-content:og-image] Template file not found: ${templatePath}`);\n }\n\n const ext = path.extname(templatePath).toLowerCase();\n\n switch (ext) {\n case \".vue\":\n return resolveVueTemplate(templatePath, options, root);\n case \".svelte\":\n return resolveSvelteTemplate(templatePath, root);\n case \".tsx\":\n case \".jsx\":\n return resolveReactTemplate(templatePath, root);\n default:\n return resolveTsTemplate(templatePath, options, root);\n }\n}\n\n/**\n * Matches this package and every subpath it exports.\n *\n * A template's natural runtime is whatever renders it, and for the\n * framework-less kinds that is this package: `renderToString`, `raw`, `when`\n * and `each` live at its root, and the JSX runtime under `./jsx-runtime`.\n * Inlining them instead drags the entire plugin — chokidar, fsevents and all\n * — into the template bundle, which is what made importing it fail outright.\n */\nconst OX_CONTENT_PACKAGE = /^@ox-content\\/vite-plugin(\\/.*)?$/;\n\n/**\n * Whether `id` is a bare specifier, and so resolvable at runtime rather than\n * something the template bundle has to inline.\n *\n * Template bundles are written to `<root>/.cache/og-images/` and imported\n * from there, so Node resolves anything left external against the project's\n * own `node_modules`. Relative and absolute imports still bundle, which is\n * what a template actually needs — its own components travel with it.\n */\nexport function isBareSpecifier(id: string): boolean {\n if (id.startsWith(\".\") || id.startsWith(\"/\") || id.startsWith(\"\\0\")) {\n return false;\n }\n // Windows drive letters and rolldown's virtual-module prefixes.\n return !/^[a-zA-Z]:[\\\\/]/.test(id);\n}\n\n/**\n * Rolldown input options for a `.ts` template bundle.\n *\n * A `.ts` template is the framework-less kind, so it has no single runtime to\n * externalize the way the `.vue`, `.svelte` and `.tsx` paths do — anything\n * from `node_modules` is better resolved at import time than inlined. Nothing\n * on this path has a compiler plugin, so nothing here needed bundling to be\n * loadable in the first place.\n */\nexport function tsTemplateBundleOptions(templatePath: string) {\n return {\n input: templatePath,\n platform: \"node\" as const,\n external: (id: string) => isBareSpecifier(id),\n };\n}\n\n/**\n * Resolves a plain TypeScript template (existing behavior).\n */\nasync function resolveTsTemplate(\n templatePath: string,\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template.mjs\");\n\n const bundle = await rolldown(tsTemplateBundleOptions(templatePath));\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const templateFn = mod.default;\n\n if (typeof templateFn !== \"function\") {\n throw new Error(\n `[ox-content:og-image] Template must default-export a function: ${options.template}`,\n );\n }\n\n return templateFn as OgImageTemplateFn;\n}\n\n/**\n * Resolves a Vue SFC template via SSR.\n *\n * Compiles the SFC with @vue/compiler-sfc (or @vizejs/vite-plugin),\n * bundles with rolldown, then wraps with createSSRApp + renderToString.\n */\nasync function resolveVueTemplate(\n templatePath: string,\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template_vue.mjs\");\n\n const plugins =\n options.vuePlugin === \"vizejs\" ? await getVizejsPlugin() : [createVueCompilerPlugin()];\n\n const bundle = await rolldown({\n input: templatePath,\n platform: \"node\",\n external: [\"vue\", \"vue/server-renderer\", OX_CONTENT_PACKAGE],\n plugins,\n });\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const Component = mod.default;\n\n if (!Component) {\n throw new Error(\n `[ox-content:og-image] Vue template must have a default export: ${templatePath}`,\n );\n }\n\n // Extract CSS from SFC <style> blocks (Vue SSR does not include styles).\n // OG image templates render in complete isolation, so scoping is unnecessary.\n // We use raw CSS content to avoid scope ID mismatches between compilers\n // (e.g., vizejs and @vue/compiler-sfc may produce different scope hashes).\n let extractedCss = ((mod as Record<string, unknown>).__vize_css__ as string) || \"\";\n if (!extractedCss) {\n try {\n let compilerSfc: typeof import(\"@vue/compiler-sfc\");\n try {\n compilerSfc = await import(\"@vue/compiler-sfc\");\n } catch {\n compilerSfc = null as never;\n }\n if (compilerSfc) {\n const sfcSource = await fs.readFile(templatePath, \"utf-8\");\n const { descriptor } = compilerSfc.parse(sfcSource, { filename: templatePath });\n for (const style of descriptor.styles) {\n extractedCss += style.content;\n }\n }\n } catch {\n // CSS extraction is best-effort\n }\n }\n\n // Import Vue SSR utilities\n const { createSSRApp } = await import(\"vue\");\n const { renderToString } = await import(\"vue/server-renderer\");\n\n return async (props) => {\n const app = createSSRApp(Component, props);\n const html = await renderToString(app);\n if (extractedCss) {\n return `<style>${extractedCss}</style>${html}`;\n }\n return html;\n };\n}\n\n/**\n * Creates a rolldown plugin that compiles Vue SFCs using @vue/compiler-sfc.\n */\nfunction createVueCompilerPlugin(): import(\"rolldown\").Plugin {\n return {\n name: \"ox-content-vue-sfc\",\n async transform(code, id) {\n if (!id.endsWith(\".vue\")) return null;\n\n let compilerSfc: typeof import(\"@vue/compiler-sfc\");\n try {\n compilerSfc = await import(\"@vue/compiler-sfc\");\n } catch {\n throw new Error(\n \"[ox-content:og-image] @vue/compiler-sfc is required for .vue templates. \" +\n \"Install it with: pnpm add -D @vue/compiler-sfc\",\n );\n }\n\n const { descriptor } = compilerSfc.parse(code, { filename: id });\n\n // Compile <script setup> or <script>\n let scriptCode: string;\n if (descriptor.scriptSetup || descriptor.script) {\n const compiled = compilerSfc.compileScript(descriptor, {\n id,\n inlineTemplate: true,\n });\n scriptCode = compiled.content;\n } else {\n // Template-only SFC: compile template separately\n if (!descriptor.template) {\n throw new Error(\n `[ox-content:og-image] Vue SFC must have a <template> or <script>: ${id}`,\n );\n }\n const templateResult = compilerSfc.compileTemplate({\n source: descriptor.template.content,\n filename: id,\n id,\n });\n if (templateResult.errors.length > 0) {\n throw new Error(\n `[ox-content:og-image] Vue template compilation errors in ${id}: ${templateResult.errors.map(String).join(\", \")}`,\n );\n }\n scriptCode = `${templateResult.code}\\nexport default { render }`;\n }\n\n // Determine if the compiled output contains TypeScript\n const isTs = !!(descriptor.scriptSetup?.lang === \"ts\" || descriptor.script?.lang === \"ts\");\n\n return { code: scriptCode, moduleType: isTs ? \"ts\" : \"js\" };\n },\n };\n}\n\n/**\n * Loads @vizejs/vite-plugin as a rolldown plugin for Vue SFC compilation.\n */\nasync function getVizejsPlugin(): Promise<import(\"rolldown\").Plugin[]> {\n try {\n const vizejs = await import(\"@vizejs/vite-plugin\");\n const plugin = vizejs.default?.() ?? vizejs;\n return Array.isArray(plugin) ? plugin : [plugin];\n } catch {\n throw new Error(\n \"[ox-content:og-image] @vizejs/vite-plugin is required when vuePlugin is 'vizejs'. \" +\n \"Install it with: pnpm add -D @vizejs/vite-plugin\",\n );\n }\n}\n\n/**\n * Resolves a Svelte SFC template via SSR.\n *\n * Compiles the SFC with svelte/compiler (server mode + runes),\n * bundles with rolldown, then wraps with svelte/server render().\n */\nasync function resolveSvelteTemplate(\n templatePath: string,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template_svelte.mjs\");\n\n const bundle = await rolldown({\n input: templatePath,\n platform: \"node\",\n external: [\n \"svelte\",\n \"svelte/server\",\n \"svelte/internal\",\n \"svelte/internal/server\",\n OX_CONTENT_PACKAGE,\n ],\n plugins: [createSvelteCompilerPlugin()],\n });\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const Component = mod.default;\n\n if (!Component) {\n throw new Error(\n `[ox-content:og-image] Svelte template must have a default export: ${templatePath}`,\n );\n }\n\n // Import Svelte SSR utility\n const { render } = (await import(\"svelte/server\")) as {\n render: (component: unknown, options: { props: Record<string, unknown> }) => { body: string };\n };\n\n return async (props) => {\n const { body } = render(Component, { props });\n return body;\n };\n}\n\n/**\n * Creates a rolldown plugin that compiles Svelte SFCs using svelte/compiler.\n */\nfunction createSvelteCompilerPlugin(): import(\"rolldown\").Plugin {\n return {\n name: \"ox-content-svelte-sfc\",\n async transform(code, id) {\n if (!id.endsWith(\".svelte\")) return null;\n\n let svelteCompiler: typeof import(\"svelte/compiler\");\n try {\n svelteCompiler = await import(\"svelte/compiler\");\n } catch {\n throw new Error(\n \"[ox-content:og-image] svelte is required for .svelte templates. \" +\n \"Install it with: pnpm add -D svelte\",\n );\n }\n\n const result = svelteCompiler.compile(code, {\n generate: \"server\",\n runes: true,\n filename: id,\n });\n\n return { code: result.js.code };\n },\n };\n}\n\n/**\n * Resolves a React (.tsx/.jsx) template via SSR.\n *\n * Bundles with rolldown (JSX transform), then wraps with\n * react-dom/server renderToReadableStream for async Server Component support.\n */\nasync function resolveReactTemplate(\n templatePath: string,\n root: string,\n): Promise<OgImageTemplateFn> {\n const fs = await import(\"fs/promises\");\n const { rolldown } = await import(\"rolldown\");\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n await fs.mkdir(cacheDir, { recursive: true });\n\n const outfile = path.join(cacheDir, \"_template_react.mjs\");\n\n const bundle = await rolldown({\n input: templatePath,\n platform: \"node\",\n external: [\n \"react\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n \"react-dom\",\n \"react-dom/server\",\n OX_CONTENT_PACKAGE,\n ],\n transform: {\n jsx: \"react-jsx\",\n },\n });\n await bundle.write({\n file: outfile,\n format: \"esm\",\n });\n await bundle.close();\n\n const mod = await import(`${outfile}?t=${Date.now()}`);\n const Component = mod.default;\n\n if (!Component) {\n throw new Error(\n `[ox-content:og-image] React template must have a default export: ${templatePath}`,\n );\n }\n\n // Import React SSR utilities\n let React: typeof import(\"react\");\n let ReactDOMServer: typeof import(\"react-dom/server\");\n try {\n React = await import(\"react\");\n ReactDOMServer = await import(\"react-dom/server\");\n } catch {\n throw new Error(\n \"[ox-content:og-image] react and react-dom are required for .tsx/.jsx templates. \" +\n \"Install them with: pnpm add -D react react-dom\",\n );\n }\n\n return async (props) => {\n const element = React.createElement(Component, props);\n // Use renderToReadableStream for async Server Component support\n const stream = await ReactDOMServer.renderToReadableStream(element);\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n const decoder = new TextDecoder();\n return (\n chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join(\"\") + decoder.decode()\n );\n };\n}\n\n/**\n * Computes a stable template source identifier for cache keys.\n *\n * For custom templates, hashes the file content so cache invalidates\n * when the template changes. For the default template, returns a fixed string.\n */\nasync function computeTemplateSource(\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<string> {\n if (!options.template) {\n return \"__default__\";\n }\n\n const fs = await import(\"fs/promises\");\n const templatePath = path.resolve(root, options.template);\n const content = await fs.readFile(templatePath, \"utf-8\");\n return crypto.createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/**\n * Generates OG images for a batch of pages.\n *\n * Manages the full lifecycle: resolve template → launch browser (with `using`) →\n * render each page (with caching and concurrency).\n *\n * All errors are non-fatal: failures are reported in results but never throw.\n */\nexport async function generateOgImages(\n pages: OgImagePageEntry[],\n options: ResolvedOgImageOptions,\n root: string,\n): Promise<OgImageResult[]> {\n if (pages.length === 0) return [];\n\n // Resolve template\n const templateFn = await resolveTemplate(options, root);\n\n // Compute template source for cache key\n const templateSource = await computeTemplateSource(options, root);\n\n // Cache directory\n const cacheDir = path.join(root, \".cache\", \"og-images\");\n\n // Try to serve all from cache first if caching is enabled\n if (options.cache) {\n const allCached = await tryServeAllFromCache(pages, templateSource, options, cacheDir);\n if (allCached) return allCached;\n }\n\n // Launch browser\n await using session = await openBrowser();\n if (!session) {\n return pages.map((p) => ({\n outputPath: p.outputPath,\n cached: false,\n error: \"Chromium not available\",\n }));\n }\n\n const results: OgImageResult[] = [];\n\n // Resolve public directory for serving local assets in templates\n const publicDir = path.join(root, \"public\");\n\n // Process pages with concurrency control\n const concurrency = Math.max(1, options.concurrency);\n\n for (let i = 0; i < pages.length; i += concurrency) {\n const batch = pages.slice(i, i + concurrency);\n const batchResults = await Promise.all(\n batch.map((entry) =>\n renderSinglePage(entry, templateFn, templateSource, options, cacheDir, session, publicDir),\n ),\n );\n results.push(...batchResults);\n }\n\n return results;\n}\n\n/**\n * Tries to serve all pages from cache.\n * Returns results if ALL pages are cached, null otherwise.\n */\nasync function tryServeAllFromCache(\n pages: OgImagePageEntry[],\n templateSource: string,\n options: ResolvedOgImageOptions,\n cacheDir: string,\n): Promise<OgImageResult[] | null> {\n const fs = await import(\"fs/promises\");\n const results: OgImageResult[] = [];\n\n for (const entry of pages) {\n const key = computeCacheKey(\n templateSource,\n entry.props as unknown as Record<string, unknown>,\n options.width,\n options.height,\n );\n const cached = await getCached(cacheDir, key);\n if (!cached) return null; // At least one miss, need browser\n\n // Write cached file to output\n await fs.mkdir(path.dirname(entry.outputPath), { recursive: true });\n await fs.writeFile(entry.outputPath, cached);\n results.push({ outputPath: entry.outputPath, cached: true });\n }\n\n return results;\n}\n\n/**\n * Renders a single page to PNG, with cache support.\n */\nasync function renderSinglePage(\n entry: OgImagePageEntry,\n templateFn: OgImageTemplateFn,\n templateSource: string,\n options: ResolvedOgImageOptions,\n cacheDir: string,\n session: OgBrowserSession,\n publicDir?: string,\n): Promise<OgImageResult> {\n const fs = await import(\"fs/promises\");\n\n try {\n // Check cache\n if (options.cache) {\n const key = computeCacheKey(\n templateSource,\n entry.props as unknown as Record<string, unknown>,\n options.width,\n options.height,\n );\n const cached = await getCached(cacheDir, key);\n if (cached) {\n await fs.mkdir(path.dirname(entry.outputPath), { recursive: true });\n await fs.writeFile(entry.outputPath, cached);\n return { outputPath: entry.outputPath, cached: true };\n }\n }\n\n // Render template to HTML (may be async for SFC templates)\n const html = await templateFn(entry.props);\n\n // Render HTML to PNG via session (page create/close handled internally)\n const png = await session.renderPage(html, options.width, options.height, publicDir);\n\n // Write output\n await fs.mkdir(path.dirname(entry.outputPath), { recursive: true });\n await fs.writeFile(entry.outputPath, png);\n\n // Write cache\n if (options.cache) {\n const key = computeCacheKey(\n templateSource,\n entry.props as unknown as Record<string, unknown>,\n options.width,\n options.height,\n );\n await writeCache(cacheDir, key, png);\n }\n\n return { outputPath: entry.outputPath, cached: false };\n } catch (err) {\n return {\n outputPath: entry.outputPath,\n cached: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n","/**\n * Serve and copy KaTeX CSS/fonts only when the optional `katex` package exists.\n */\n\nimport { createReadStream } from \"node:fs\";\nimport { copyFile, cp, mkdir, stat } from \"node:fs/promises\";\nimport { extname, join, relative, resolve, sep } from \"node:path\";\nimport type { Plugin } from \"vite\";\nimport { KATEX_ASSET_DIR, resolveKatexDist } from \"./math\";\n\n/**\n * Copies `katex.min.css` and `fonts/` into the SSG output.\n * Returns an empty list when KaTeX is not installed.\n */\nexport async function copyKatexAssets(outDir: string): Promise<string[]> {\n const dist = resolveKatexDist();\n if (!dist) {\n return [];\n }\n\n const dest = join(outDir, KATEX_ASSET_DIR);\n await mkdir(join(dest, \"fonts\"), { recursive: true });\n const cssDest = join(dest, \"katex.min.css\");\n await copyFile(join(dist, \"katex.min.css\"), cssDest);\n await cp(join(dist, \"fonts\"), join(dest, \"fonts\"), { recursive: true });\n return [cssDest];\n}\n\n/** Dev-server middleware that serves `/__ox_katex__/*` from `katex/dist`. */\nexport function createKatexAssetsPlugin(): Plugin {\n return {\n name: \"ox-content:katex-assets\",\n configureServer(server) {\n const dist = resolveKatexDist();\n if (!dist) {\n return;\n }\n\n server.middlewares.use((req, res, next) => {\n const url = req.url ?? \"\";\n const marker = `/${KATEX_ASSET_DIR}/`;\n const index = url.indexOf(marker);\n if (index === -1) {\n next();\n return;\n }\n\n const rel = decodeURIComponent(url.slice(index + marker.length).split(\"?\")[0] ?? \"\");\n const file = safeKatexFile(dist, rel);\n if (!file) {\n res.statusCode = 404;\n res.end();\n return;\n }\n\n stat(file)\n .then((info) => {\n if (!info.isFile()) {\n res.statusCode = 404;\n res.end();\n return;\n }\n res.setHeader(\"Content-Type\", katexContentType(file));\n createReadStream(file).pipe(res);\n })\n .catch(() => {\n res.statusCode = 404;\n res.end();\n });\n });\n },\n };\n}\n\nfunction safeKatexFile(dist: string, rel: string): string | null {\n if (!rel || rel.includes(\"\\0\") || rel.split(/[\\\\/]/).includes(\"..\")) {\n return null;\n }\n const full = resolve(dist, rel);\n const root = resolve(dist) + sep;\n if (full !== resolve(dist) && !full.startsWith(root)) {\n return null;\n }\n const inside = relative(dist, full);\n if (inside.startsWith(\"..\") || inside.includes(`..${sep}`)) {\n return null;\n }\n return full;\n}\n\nfunction katexContentType(file: string): string {\n const ext = extname(file);\n if (ext === \".css\") {\n return \"text/css; charset=utf-8\";\n }\n if (ext === \".woff2\") {\n return \"font/woff2\";\n }\n if (ext === \".woff\") {\n return \"font/woff\";\n }\n if (ext === \".ttf\") {\n return \"font/ttf\";\n }\n return \"application/octet-stream\";\n}\n","/**\n * Island Parser\n *\n * Detects <Island> components in HTML and transforms them\n * into hydration-ready elements with data attributes.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParsePlugin from \"rehype-parse\";\nimport rehypeStringifyPlugin from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\nimport { interopDefault } from \"../interop\";\n\n// ESM-only plugins are double-wrapped by the CommonJS interop; unwrap. See #452.\nconst rehypeParse = interopDefault(rehypeParsePlugin);\nconst rehypeStringify = interopDefault(rehypeStringifyPlugin);\n\nexport type LoadStrategy = \"eager\" | \"idle\" | \"visible\" | \"media\";\n\nexport interface IslandInfo {\n component: string;\n load: LoadStrategy;\n mediaQuery?: string;\n props: Record<string, unknown>;\n}\n\nexport interface ParseIslandsResult {\n html: string;\n islands: IslandInfo[];\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Parse JSX-style props from attributes.\n */\nfunction parseProps(el: Element): Record<string, unknown> {\n const props: Record<string, unknown> = {};\n\n if (!el.properties) return props;\n\n for (const [key, value] of Object.entries(el.properties)) {\n // Skip special attributes\n if ([\"load\", \"media\", \"className\", \"class\"].includes(key)) continue;\n\n // Handle JSX-style props like {0} or {true}\n if (typeof value === \"string\") {\n // Try to parse as JSON/JS value if it looks like one\n const trimmed = value.trim();\n if (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n const inner = trimmed.slice(1, -1);\n try {\n // Try JSON parse first\n props[key] = JSON.parse(inner);\n } catch {\n // Try evaluating simple expressions\n if (inner === \"true\") props[key] = true;\n else if (inner === \"false\") props[key] = false;\n else if (inner === \"null\") props[key] = null;\n else if (!Number.isNaN(Number(inner))) props[key] = Number(inner);\n else props[key] = value;\n }\n } else {\n props[key] = value;\n }\n } else if (typeof value === \"number\" || typeof value === \"boolean\") {\n props[key] = value;\n } else if (Array.isArray(value)) {\n props[key] = value;\n }\n }\n\n return props;\n}\n\n/**\n * Find the component element inside <Island>.\n */\nfunction findComponentElement(children: Element[\"children\"]): Element | null {\n for (const child of children) {\n if (child.type === \"element\") {\n // Skip text/whitespace, look for actual component\n if (child.tagName !== \"br\" && child.tagName !== \"span\") {\n return child;\n }\n }\n }\n return null;\n}\n\n/**\n * Get component name from child element.\n */\nfunction getComponentName(el: Element): string {\n // PascalCase tag names are components\n const tagName = el.tagName;\n if (tagName && /^[A-Z]/.test(tagName)) {\n return tagName;\n }\n // Check for data-component attribute\n return getAttribute(el, \"data-component\") || tagName;\n}\n\nlet islandCounter = 0;\n\n/**\n * Reset island counter (for testing).\n */\nexport function resetIslandCounter(): void {\n islandCounter = 0;\n}\n\n/**\n * Rehype plugin to transform Island components.\n */\nfunction rehypeIslands(collectedIslands: IslandInfo[]) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <Island> component\n if (child.tagName.toLowerCase() === \"island\") {\n const load = (getAttribute(child, \"load\") as LoadStrategy) || \"eager\";\n const mediaQuery = getAttribute(child, \"media\");\n\n // Find the component inside\n const componentEl = findComponentElement(child.children);\n\n if (componentEl) {\n const componentName = getComponentName(componentEl);\n const componentProps = parseProps(componentEl);\n\n // Collect island info\n const islandInfo: IslandInfo = {\n component: componentName,\n load,\n mediaQuery,\n props: componentProps,\n };\n collectedIslands.push(islandInfo);\n\n // Create island wrapper with data attributes\n const islandId = `ox-island-${islandCounter++}`;\n\n const islandElement: Element = {\n type: \"element\",\n tagName: \"div\",\n properties: {\n id: islandId,\n \"data-ox-island\": componentName,\n \"data-ox-load\": load,\n ...(mediaQuery && { \"data-ox-media\": mediaQuery }),\n \"data-ox-props\": JSON.stringify(componentProps),\n className: [\"ox-island\"],\n },\n children: [\n // Keep original content as fallback/placeholder\n ...componentEl.children,\n ],\n };\n\n node.children[i] = islandElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform Island components in HTML.\n *\n * Converts:\n * ```html\n * <Island load=\"visible\">\n * <Counter initial={0} />\n * </Island>\n * ```\n *\n * To:\n * ```html\n * <div id=\"ox-island-0\"\n * data-ox-island=\"Counter\"\n * data-ox-load=\"visible\"\n * data-ox-props='{\"initial\":0}'\n * class=\"ox-island\">\n * <!-- fallback content -->\n * </div>\n * ```\n */\nexport async function transformIslands(html: string): Promise<ParseIslandsResult> {\n const islands: IslandInfo[] = [];\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeIslands, islands)\n .use(rehypeStringify)\n .process(html);\n\n return {\n html: String(result),\n islands,\n };\n}\n\n/**\n * Check if HTML contains any Island components.\n */\nexport function hasIslands(html: string): boolean {\n return /<island[\\s>]/i.test(html);\n}\n\n/**\n * Extract island info without transforming HTML.\n * Useful for analysis/bundling purposes.\n */\nexport async function extractIslandInfo(html: string): Promise<IslandInfo[]> {\n const { islands } = await transformIslands(html);\n return islands;\n}\n\n/**\n * Generate client-side hydration script.\n * This is a minimal script that imports and initializes islands.\n */\nexport function generateHydrationScript(components: string[]): string {\n if (components.length === 0) return \"\";\n\n const imports = components.map((name) => `import ${name} from './${name}';`).join(\"\\n\");\n\n return `\nimport { initIslands } from '@ox-content/islands';\n${imports}\n\nconst components = {\n ${components.join(\",\\n \")}\n};\n\n// Initialize with your framework's hydration\n// This example uses Vue, adapt for React/Svelte/etc.\nimport { createApp, h } from 'vue';\n\ninitIslands((el, props) => {\n const name = el.dataset.oxIsland;\n const Component = components[name];\n if (!Component) {\n console.warn(\\`[ox-islands] Unknown component: \\${name}\\`);\n return;\n }\n\n const app = createApp({ render: () => h(Component, props) });\n app.mount(el);\n\n return () => app.unmount();\n});\n`;\n}\n","import type { LocaleConfig } from \"./types\";\n\n/**\n * Sibling page or locale-root href for one locale in the default-theme switcher.\n */\nexport interface SsgLocalePath {\n code: string;\n href?: string;\n root?: string;\n}\n\n/**\n * Resolves `ssg.localeSwitcher`. Omitted / `false` stay off. `true` or an\n * object enables the control.\n */\nexport function resolveLocaleSwitcherOption(\n value: boolean | Record<string, unknown> | undefined,\n): boolean {\n return value === true || (typeof value === \"object\" && value !== null);\n}\n\nexport function normalizeLocalePath(path: string): string {\n return path.replaceAll(\"\\\\\", \"/\").replace(/^\\/+|\\/+$/g, \"\");\n}\n\nexport function remainderPath(urlPath: string, locale: string): string {\n const normalized = normalizeLocalePath(urlPath);\n if (normalized === locale) {\n return \"\";\n }\n const prefix = `${locale}/`;\n if (normalized.startsWith(prefix)) {\n return normalized.slice(prefix.length);\n }\n return normalized;\n}\n\nexport function pathForLocale(\n remainder: string,\n locale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean,\n): string {\n if (hideDefaultLocale && locale === defaultLocale) {\n return remainder;\n }\n return remainder ? `${locale}/${remainder}` : locale;\n}\n\nexport function defaultLocaleRoot(base: string, locale: string): string {\n const prefix = base.endsWith(\"/\") ? base : `${base}/`;\n return `${prefix}${locale}/`;\n}\n\nexport function buildLocalePaths(options: {\n currentPath: string;\n locales: LocaleConfig[];\n defaultLocale: string;\n hideDefaultLocale: boolean;\n pages: Array<{ path: string; href: string }>;\n base: string;\n roots?: Record<string, string>;\n}): SsgLocalePath[] {\n const currentLocale =\n options.locales.find((locale) => {\n const normalized = normalizeLocalePath(options.currentPath);\n return normalized === locale.code || normalized.startsWith(`${locale.code}/`);\n })?.code ?? options.defaultLocale;\n const remainder = remainderPath(options.currentPath, currentLocale);\n const existing = new Map(\n options.pages.map((page) => [normalizeLocalePath(page.path), page.href]),\n );\n\n return options.locales.map((locale) => {\n const sibling = pathForLocale(\n remainder,\n locale.code,\n options.defaultLocale,\n options.hideDefaultLocale,\n );\n const href = existing.get(normalizeLocalePath(sibling));\n const configuredRoot = options.roots?.[locale.code];\n const root =\n configuredRoot ??\n (options.hideDefaultLocale && locale.code === options.defaultLocale\n ? options.base.endsWith(\"/\")\n ? options.base\n : `${options.base}/`\n : defaultLocaleRoot(options.base, locale.code));\n return { code: locale.code, href, root };\n });\n}\n","/**\n * Rewrites default-theme nav hrefs to the current locale sibling when it exists.\n */\n\nimport { resolveLocaleLabel, type HeaderNavItem, type LocaleLabel } from \"./header-chrome\";\nimport { normalizeLocalePath, pathForLocale, remainderPath } from \"./locale-switcher\";\nimport type { SidebarItem } from \"./theme\";\nimport type { LocaleConfig } from \"./types\";\n\n/** @internal Label metadata kept off the serializable navigation shape. */\nconst localizedNavTitle: unique symbol = Symbol(\"ox-content.localized-nav-title\");\n\nexport interface LocalePageRef {\n path: string;\n href: string;\n /** Alternate source/permalink paths that resolve to this canonical page. */\n aliases?: readonly string[];\n}\n\nexport interface LocalizeNavOptions {\n locale: string;\n locales: readonly Pick<LocaleConfig, \"code\">[];\n defaultLocale: string;\n hideDefaultLocale: boolean;\n pages: readonly LocalePageRef[];\n base: string;\n}\n\nexport interface LocalizableNavItem {\n title: string;\n path: string;\n href: string;\n children?: LocalizableNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\nexport interface LocalizableNavGroup {\n title: string;\n items: LocalizableNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\ntype LocalizedNavItem = LocalizableNavItem & {\n [localizedNavTitle]?: LocaleLabel;\n children?: LocalizedNavItem[];\n};\n\ntype LocalizedNavGroup = LocalizableNavGroup & {\n [localizedNavTitle]?: LocaleLabel;\n items: LocalizedNavItem[];\n};\n\ninterface ResolvedSidebarItem {\n text?: string;\n link?: string;\n items?: ResolvedSidebarItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/** @internal Flattens sidebar locale maps before crossing the string-only NAPI boundary. */\nexport function resolveSidebarItems(\n sidebar: readonly SidebarItem[],\n locale?: string,\n defaultLocale?: string,\n): ResolvedSidebarItem[] {\n return sidebar.map((item) => ({\n text:\n item.text === undefined ? undefined : resolveLocaleLabel(item.text, locale, defaultLocale),\n link: item.link,\n items: item.items ? resolveSidebarItems(item.items, locale, defaultLocale) : undefined,\n collapsed: item.collapsed,\n stickyCollapsed: item.stickyCollapsed,\n }));\n}\n\n/** @internal Associates rendered nav nodes with authored locale maps by tree position. */\nexport function attachSidebarLabels<T extends LocalizableNavGroup>(\n groups: T[],\n sidebar: readonly SidebarItem[],\n): T[] {\n const sources = sidebarGroupSources(sidebar);\n return groups.map((group, index) => {\n const source = sources[index];\n return {\n ...group,\n ...(source?.title === undefined ? {} : { [localizedNavTitle]: source.title }),\n items: attachItemLabels(group.items, source?.items ?? []),\n } as T;\n });\n}\n\nfunction sidebarGroupSources(sidebar: readonly SidebarItem[]): Array<{\n title?: LocaleLabel;\n items: readonly SidebarItem[];\n}> {\n const groups: Array<{ title?: LocaleLabel; items: readonly SidebarItem[] }> = [];\n let loose: SidebarItem[] = [];\n const flushLoose = () => {\n if (loose.length > 0) {\n groups.push({ items: loose });\n loose = [];\n }\n };\n for (const item of sidebar) {\n if ((item.items?.length ?? 0) > 0 && item.link === undefined) {\n flushLoose();\n groups.push({ title: item.text, items: item.items ?? [] });\n } else {\n loose.push(item);\n }\n }\n flushLoose();\n return groups;\n}\n\nfunction attachItemLabels<T extends LocalizableNavItem>(\n items: T[],\n sources: readonly SidebarItem[],\n): T[] {\n return items.map((item, index) => {\n const source = sources[index];\n return {\n ...item,\n ...(source?.text === undefined ? {} : { [localizedNavTitle]: source.text }),\n children: attachItemLabels(item.children ?? [], source?.items ?? []),\n };\n });\n}\n\n/**\n * Resolves authored sidebar label maps and prefixes hrefs/paths with the\n * current locale when that page exists. Missing siblings stay as authored.\n */\nexport function localizeNavGroups<T extends LocalizableNavGroup>(\n groups: T[],\n options: LocalizeNavOptions,\n): T[] {\n const lookup = pageLookup(options);\n if (!lookup && !hasLocalizedTitles(groups)) {\n return groups;\n }\n return groups.map((group) => ({\n ...group,\n title: resolveNavTitle(group, options),\n items: group.items.map((item) => localizeNavItem(item, options, lookup)),\n }));\n}\n\n/**\n * Resolves header labels and rewrites `link` values the same way as the sidebar.\n */\nexport function localizeHeaderNavItems(\n items: HeaderNavItem[] | undefined,\n options: LocalizeNavOptions,\n): HeaderNavItem[] | undefined {\n if (!items?.length) {\n return items;\n }\n const lookup = pageLookup(options);\n return items.map((item) => ({\n ...item,\n text: resolveLocaleLabel(item.text, options.locale, options.defaultLocale),\n link: item.link && lookup ? localizeHref(item.link, options, lookup) : item.link,\n items: localizeHeaderNavItems(item.items, options),\n }));\n}\n\nexport function localizeHref(\n href: string,\n options: LocalizeNavOptions,\n lookup = pageLookup(options),\n): string {\n if (!lookup) {\n return href;\n }\n const hash = href.includes(\"#\") ? href.slice(href.indexOf(\"#\")) : \"\";\n const sitePath = sitePathFromHref(href, options.base);\n if (sitePath === undefined) {\n return href;\n }\n const remainder = stripLocalePrefix(sitePath, options.locales);\n const siblingPath = pathForLocale(\n remainder,\n options.locale,\n options.defaultLocale,\n options.hideDefaultLocale,\n );\n const sibling = lookup.get(normalizeLocalePath(siblingPath));\n return sibling ? `${sibling.href}${hash}` : href;\n}\n\nexport function sitePathFromHref(href: string, base: string): string | undefined {\n const trimmed = href.trim();\n if (!trimmed || trimmed.startsWith(\"#\") || trimmed.startsWith(\"//\")) {\n return undefined;\n }\n const noHash = trimmed.split(\"#\")[0]?.split(\"?\")[0] ?? \"\";\n const compact = noHash.replace(/\\s+/g, \"\").toLowerCase();\n if (\n compact.startsWith(\"javascript:\") ||\n compact.startsWith(\"data:\") ||\n compact.startsWith(\"vbscript:\")\n ) {\n return undefined;\n }\n if (/^[a-z][a-z0-9+.-]*:/i.test(noHash)) {\n return undefined;\n }\n const normalizedBase = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n let path = noHash;\n if (normalizedBase !== \"/\" && path.startsWith(normalizedBase)) {\n path = path.slice(normalizedBase.length);\n } else if (path.startsWith(\"/\")) {\n path = path.slice(1);\n } else {\n return undefined;\n }\n path = path\n .replace(/\\/index\\.html$/i, \"\")\n .replace(/\\.html$/i, \"\")\n .replace(/\\.(mdx|markdown|md)$/i, \"\")\n .replace(/\\/+$/g, \"\");\n if (path === \"index\") {\n return \"\";\n }\n return path;\n}\n\nfunction localizeNavItem<T extends LocalizableNavItem>(\n item: T,\n options: LocalizeNavOptions,\n lookup: Map<string, LocalePageRef> | undefined,\n): T {\n if (!lookup) {\n return {\n ...item,\n title: resolveNavTitle(item, options),\n children: (item.children ?? []).map((child) => localizeNavItem(child, options, lookup)),\n };\n }\n const hash = item.href.includes(\"#\") ? item.href.slice(item.href.indexOf(\"#\")) : \"\";\n const sitePath = sitePathFromHref(item.href, options.base) ?? normalizeLocalePath(item.path);\n const remainder = stripLocalePrefix(sitePath, options.locales);\n const siblingPath = pathForLocale(\n remainder,\n options.locale,\n options.defaultLocale,\n options.hideDefaultLocale,\n );\n const sibling = lookup.get(normalizeLocalePath(siblingPath));\n return {\n ...item,\n title: resolveNavTitle(item, options),\n href: sibling ? `${sibling.href}${hash}` : item.href,\n path: sibling ? sibling.path : item.path,\n children: (item.children ?? []).map((child) => localizeNavItem(child, options, lookup)),\n };\n}\n\nfunction resolveNavTitle(\n item: LocalizableNavItem | LocalizableNavGroup,\n options: LocalizeNavOptions,\n): string {\n const label = (item as LocalizedNavItem | LocalizedNavGroup)[localizedNavTitle];\n return label === undefined\n ? item.title\n : resolveLocaleLabel(label, options.locale, options.defaultLocale);\n}\n\nfunction hasLocalizedTitles(groups: readonly LocalizableNavGroup[]): boolean {\n return groups.some(\n (group) =>\n (group as LocalizedNavGroup)[localizedNavTitle] !== undefined ||\n hasLocalizedItemTitles(group.items),\n );\n}\n\nfunction hasLocalizedItemTitles(items: readonly LocalizableNavItem[]): boolean {\n return items.some(\n (item) =>\n (item as LocalizedNavItem)[localizedNavTitle] !== undefined ||\n hasLocalizedItemTitles(item.children ?? []),\n );\n}\n\nfunction pageLookup(options: LocalizeNavOptions): Map<string, LocalePageRef> | undefined {\n if (!options.locale || options.pages.length === 0) {\n return undefined;\n }\n if (options.hideDefaultLocale && options.locale === options.defaultLocale) {\n return undefined;\n }\n const lookup = new Map<string, LocalePageRef>();\n for (const page of options.pages) {\n lookup.set(normalizeLocalePath(page.path), page);\n for (const alias of page.aliases ?? []) {\n const key = normalizeLocalePath(alias);\n if (!lookup.has(key)) {\n lookup.set(key, page);\n }\n }\n }\n return lookup;\n}\n\nfunction stripLocalePrefix(\n sitePath: string,\n locales: readonly Pick<LocaleConfig, \"code\">[],\n): string {\n const normalized = normalizeLocalePath(sitePath);\n const codes = locales.map((locale) => locale.code).sort((a, b) => b.length - a.length);\n for (const code of codes) {\n if (normalized === code || normalized.startsWith(`${code}/`)) {\n return remainderPath(normalized, code);\n }\n }\n return normalized;\n}\n","/**\n * Page Context for Static HTML Generation\n *\n * Provides a way to access page props (frontmatter, content, etc.)\n * from theme components during static rendering.\n *\n * @example\n * ```tsx\n * // theme/Layout.tsx\n * import { usePageProps, PageProps } from '@ox-content/vite-plugin';\n *\n * export function Layout({ children }: { children: JSX.Element }) {\n * const page = usePageProps<MyPageProps>();\n * return (\n * <html>\n * <head>\n * <title>{page.title}</title>\n * </head>\n * <body>\n * <header>{page.title}</header>\n * <main>{children}</main>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\n\nimport type { TocEntry } from \"./types\";\n\n/**\n * Base page props available for all pages.\n */\nexport interface BasePageProps {\n /** Page title from frontmatter or first heading */\n title: string;\n /** Page description from frontmatter */\n description?: string;\n /** Rendered HTML content */\n html: string;\n /** Table of contents entries */\n toc: TocEntry[];\n /** Last git commit timestamp in milliseconds */\n lastUpdated?: number;\n /** Unique git authors for this page */\n contributors?: Array<{ name: string; avatar?: string }>;\n /** Source file path (relative to docs root) */\n path: string;\n /** Output URL path */\n url: string;\n /** Raw frontmatter object */\n frontmatter: Record<string, unknown>;\n /** Layout name from frontmatter */\n layout?: string;\n}\n\n/**\n * Extended page props with custom frontmatter.\n */\nexport type PageProps<T extends Record<string, unknown> = Record<string, unknown>> =\n BasePageProps & {\n /** Custom frontmatter fields */\n frontmatter: T & Record<string, unknown>;\n };\n\n/**\n * Site-wide configuration available in context.\n */\nexport interface SiteConfig {\n /** Site name */\n name: string;\n /** Base URL path */\n base: string;\n /** All pages in the site */\n pages: BasePageProps[];\n /** Navigation groups */\n nav: NavGroup[];\n}\n\n/**\n * Navigation group.\n */\nexport interface NavGroup {\n title: string;\n items: NavItem[];\n}\n\n/**\n * Navigation item.\n */\nexport interface NavItem {\n title: string;\n path: string;\n href: string;\n}\n\n/**\n * Complete render context.\n */\nexport interface RenderContext<T extends Record<string, unknown> = Record<string, unknown>> {\n /** Current page props */\n page: PageProps<T>;\n /** Site configuration */\n site: SiteConfig;\n}\n\n// Internal context storage (set during render)\nlet currentContext: RenderContext | null = null;\n\n/**\n * Sets the current render context.\n * Called internally during page rendering.\n * @internal\n */\nexport function setRenderContext(ctx: RenderContext): void {\n currentContext = ctx;\n}\n\n/**\n * Clears the current render context.\n * Called internally after page rendering.\n * @internal\n */\nexport function clearRenderContext(): void {\n currentContext = null;\n}\n\n/**\n * Gets the current page props.\n *\n * @returns The current page props\n * @throws Error if called outside of a render context\n *\n * @example\n * ```tsx\n * function PageTitle() {\n * const page = usePageProps();\n * return <h1>{page.title}</h1>;\n * }\n * ```\n */\nexport function usePageProps<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(): PageProps<T> {\n if (!currentContext) {\n throw new Error(\n \"[ox-content] usePageProps() must be called during page rendering. \" +\n \"Make sure you are using it inside a theme component.\",\n );\n }\n return currentContext.page as PageProps<T>;\n}\n\n/**\n * Gets the site configuration.\n *\n * @returns The site configuration\n * @throws Error if called outside of a render context\n *\n * @example\n * ```tsx\n * function SiteHeader() {\n * const site = useSiteConfig();\n * return <header>{site.name}</header>;\n * }\n * ```\n */\nexport function useSiteConfig(): SiteConfig {\n if (!currentContext) {\n throw new Error(\n \"[ox-content] useSiteConfig() must be called during page rendering. \" +\n \"Make sure you are using it inside a theme component.\",\n );\n }\n return currentContext.site;\n}\n\n/**\n * Gets the full render context.\n *\n * @returns The complete render context\n * @throws Error if called outside of a render context\n *\n * @example\n * ```tsx\n * function Layout({ children }) {\n * const ctx = useRenderContext();\n * return (\n * <html>\n * <head><title>{ctx.page.title} - {ctx.site.name}</title></head>\n * <body>{children}</body>\n * </html>\n * );\n * }\n * ```\n */\nexport function useRenderContext<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(): RenderContext<T> {\n if (!currentContext) {\n throw new Error(\n \"[ox-content] useRenderContext() must be called during page rendering. \" +\n \"Make sure you are using it inside a theme component.\",\n );\n }\n return currentContext as RenderContext<T>;\n}\n\n/**\n * Gets the navigation groups.\n *\n * @example\n * ```tsx\n * function Sidebar() {\n * const nav = useNav();\n * return (\n * <nav>\n * {each(nav, (group) => (\n * <div>\n * <h3>{group.title}</h3>\n * <ul>\n * {each(group.items, (item) => (\n * <li><a href={item.href}>{item.title}</a></li>\n * ))}\n * </ul>\n * </div>\n * ))}\n * </nav>\n * );\n * }\n * ```\n */\nexport function useNav(): NavGroup[] {\n return useSiteConfig().nav;\n}\n\n/**\n * Checks if the given path is the current page.\n *\n * @example\n * ```tsx\n * function NavLink({ href, children }) {\n * const isActive = useIsActive(href);\n * return <a href={href} class={isActive ? 'active' : ''}>{children}</a>;\n * }\n * ```\n */\nexport function useIsActive(path: string): boolean {\n const page = usePageProps();\n return page.path === path || page.url === path;\n}\n\n// Type generation helpers\n\n/**\n * Schema for frontmatter type generation.\n */\nexport interface FrontmatterSchema {\n /** Field name */\n name: string;\n /** TypeScript type */\n type: string;\n /** Whether the field is optional */\n optional: boolean;\n /** JSDoc description */\n description?: string;\n}\n\n/**\n * Infers TypeScript types from frontmatter values.\n */\nexport function inferType(value: unknown): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (typeof value === \"string\") return \"string\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"boolean\") return \"boolean\";\n if (Array.isArray(value)) {\n if (value.length === 0) return \"unknown[]\";\n const itemTypes = [...new Set(value.map(inferType))];\n if (itemTypes.length === 1) return `${itemTypes[0]}[]`;\n return `(${itemTypes.join(\" | \")})[]`;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) return \"Record<string, unknown>\";\n const props = entries.map(([k, v]) => `${k}: ${inferType(v)}`).join(\"; \");\n return `{ ${props} }`;\n }\n return \"unknown\";\n}\n\n/**\n * Generates TypeScript interface from frontmatter samples.\n */\nexport function generateFrontmatterTypes(\n samples: Record<string, unknown>[],\n interfaceName = \"PageFrontmatter\",\n): string {\n // Collect all fields and their types across all samples\n const fields = new Map<string, { types: Set<string>; count: number }>();\n\n for (const sample of samples) {\n for (const [key, value] of Object.entries(sample)) {\n const existing = fields.get(key) ?? { types: new Set(), count: 0 };\n existing.types.add(inferType(value));\n existing.count++;\n fields.set(key, existing);\n }\n }\n\n // Generate interface\n const lines: string[] = [\n \"/**\",\n \" * Auto-generated frontmatter type based on your pages.\",\n \" * DO NOT EDIT - this file is generated by ox-content.\",\n \" */\",\n \"\",\n `export interface ${interfaceName} {`,\n ];\n\n for (const [name, { types, count }] of fields) {\n const isOptional = count < samples.length;\n const typeStr = [...types].join(\" | \");\n const optionalMark = isOptional ? \"?\" : \"\";\n lines.push(` ${name}${optionalMark}: ${typeStr};`);\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n lines.push(\n `export type PageProps = import('@ox-content/vite-plugin').PageProps<${interfaceName}>;`,\n );\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Theme Renderer for Static HTML Generation\n *\n * Renders JSX theme components to static HTML strings.\n * No client-side JavaScript is included by default.\n */\n\nimport { renderToString, raw, type JSXNode } from \"./jsx-html\";\nimport {\n setRenderContext,\n clearRenderContext,\n generateFrontmatterTypes,\n usePageProps,\n type RenderContext,\n type PageProps,\n type SiteConfig,\n type NavGroup,\n} from \"./page-context\";\nimport type { TocEntry } from \"./types\";\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * Theme component type.\n */\nexport type ThemeComponent = (props: ThemeProps) => JSXNode;\n\n/**\n * Props passed to the theme component.\n */\nexport interface ThemeProps {\n /** Rendered page content as JSX */\n children: JSXNode;\n}\n\n/**\n * Page data for rendering.\n */\nexport interface PageData {\n /** Page title */\n title: string;\n /** Page description */\n description?: string;\n /** Rendered HTML content */\n html: string;\n /** Table of contents */\n toc: TocEntry[];\n /** Last git commit timestamp in milliseconds */\n lastUpdated?: number;\n /** Unique git authors for this page */\n contributors?: Array<{ name: string; avatar?: string }>;\n /** Source file path */\n path: string;\n /** Output URL path */\n url: string;\n /** Frontmatter */\n frontmatter: Record<string, unknown>;\n /** Layout name */\n layout?: string;\n}\n\n/**\n * Theme render options.\n */\nexport interface ThemeRenderOptions {\n /** Theme component to use */\n theme: ThemeComponent;\n /** Site name */\n siteName: string;\n /** Base URL path */\n base: string;\n /** Navigation groups */\n nav: NavGroup[];\n /** All pages (for site context) */\n pages: PageData[];\n /** Output directory for type definitions */\n typesOutDir?: string;\n}\n\n/**\n * Renders a page using the theme component.\n *\n * @param page - Page data to render\n * @param options - Theme render options\n * @returns Rendered HTML string\n */\nexport function renderPage(page: PageData, options: ThemeRenderOptions): string {\n const { theme, siteName, base, nav, pages } = options;\n\n // Build page props\n const pageProps: PageProps = {\n title: page.title,\n description: page.description,\n html: page.html,\n toc: page.toc,\n lastUpdated: page.lastUpdated,\n contributors: page.contributors,\n path: page.path,\n url: page.url,\n frontmatter: page.frontmatter,\n layout: page.layout,\n };\n\n // Build site config\n const siteConfig: SiteConfig = {\n name: siteName,\n base,\n nav,\n pages: pages.map((p) => ({\n title: p.title,\n description: p.description,\n html: p.html,\n toc: p.toc,\n lastUpdated: p.lastUpdated,\n contributors: p.contributors,\n path: p.path,\n url: p.url,\n frontmatter: p.frontmatter,\n layout: p.layout,\n })),\n };\n\n // Set render context\n const context: RenderContext = {\n page: pageProps,\n site: siteConfig,\n };\n\n setRenderContext(context);\n\n try {\n // Render theme with page content\n const contentNode = raw(page.html);\n const result = theme({ children: contentNode });\n\n // Get HTML string\n const html = renderToString(result);\n\n // Add doctype if not present\n if (!html.trimStart().toLowerCase().startsWith(\"<!doctype\")) {\n return `<!DOCTYPE html>\\n${html}`;\n }\n\n return html;\n } finally {\n clearRenderContext();\n }\n}\n\n/**\n * Renders all pages and generates type definitions.\n *\n * @param pages - All pages to render\n * @param options - Theme render options\n * @returns Map of output paths to rendered HTML\n */\nexport async function renderAllPages(\n pages: PageData[],\n options: ThemeRenderOptions,\n): Promise<Map<string, string>> {\n const results = new Map<string, string>();\n\n // Render each page\n for (const page of pages) {\n const html = renderPage(page, { ...options, pages });\n results.set(page.url, html);\n }\n\n // Generate type definitions if output directory is specified\n if (options.typesOutDir) {\n await generateTypes(pages, options.typesOutDir);\n }\n\n return results;\n}\n\n/**\n * Generates TypeScript type definitions from page frontmatter.\n *\n * @param pages - All pages\n * @param outDir - Output directory for types\n */\nexport async function generateTypes(pages: PageData[], outDir: string): Promise<void> {\n // Collect all frontmatter samples\n const samples = pages.map((p) => p.frontmatter);\n\n // Generate types\n const types = generateFrontmatterTypes(samples);\n\n // Write to file\n const typesPath = join(outDir, \"page-props.d.ts\");\n await mkdir(dirname(typesPath), { recursive: true });\n await writeFile(typesPath, types, \"utf-8\");\n}\n\n/**\n * Default theme component.\n * A minimal theme that renders page content with basic styling.\n */\nexport function DefaultTheme({ children }: ThemeProps): JSXNode {\n // Use hooks inside the component\n const { usePageProps, useSiteConfig } = require(\"./page-context\");\n const page = usePageProps();\n const site = useSiteConfig();\n\n return {\n __html: `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(page.title)} - ${escapeHtml(site.name)}</title>\n ${page.description ? `<meta name=\"description\" content=\"${escapeHtml(page.description)}\">` : \"\"}\n <style>\n :root {\n --octc-color-primary: #4f6fae;\n --octc-color-text: #131a30;\n --octc-color-bg: #ffffff;\n --octc-color-bg-alt: #f5f7fb;\n --octc-color-text-muted: #4f607b;\n --octc-color-border: #d2dbea;\n }\n body {\n font-family: \"IBM Plex Sans\", \"Avenir Next\", \"Segoe UI Variable\", \"Segoe UI\", sans-serif;\n line-height: 1.7;\n color: var(--octc-color-text);\n background: var(--octc-color-bg);\n max-width: 800px;\n margin: 0 auto;\n padding: 2rem;\n }\n a { color: var(--octc-color-primary); }\n </style>\n</head>\n<body>\n <header>\n <h1>${escapeHtml(site.name)}</h1>\n </header>\n <main>\n ${children.__html}\n </main>\n</body>\n</html>`,\n };\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\n/**\n * Creates a theme with layout switching support.\n *\n * @example\n * ```tsx\n * import { createTheme } from '@ox-content/vite-plugin';\n * import { DefaultLayout } from './layouts/Default';\n * import { EntryLayout } from './layouts/Entry';\n *\n * export default createTheme({\n * layouts: {\n * default: DefaultLayout,\n * entry: EntryLayout,\n * },\n * });\n * ```\n */\nexport function createTheme(config: {\n layouts: Record<string, ThemeComponent>;\n defaultLayout?: string;\n}): ThemeComponent {\n const { layouts, defaultLayout = \"default\" } = config;\n\n return function ThemeWithLayouts({ children }: ThemeProps): JSXNode {\n // `page-context` is already imported statically above, so there is no\n // cycle to dodge here. The lazy `require` this replaces threw\n // \"Cannot find module\" outright once the package shipped as ESM, which\n // is what made `createTheme` unusable.\n const page = usePageProps();\n\n // Get layout from frontmatter or use default\n const layoutName = page.layout ?? defaultLayout;\n const Layout = layouts[layoutName] ?? layouts[defaultLayout];\n\n if (!Layout) {\n throw new Error(\n `[ox-content] Layout \"${layoutName}\" not found. ` +\n `Available layouts: ${Object.keys(layouts).join(\", \")}`,\n );\n }\n\n return Layout({ children });\n };\n}\n","/**\n * Opt-in sitemap.xml / robots.txt / llms.txt helpers.\n *\n * String bodies follow `ox_content_ssg::generate_site_maps`. The Vite plugin\n * writes those files during SSG without adding a NAPI surface.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { ResolvedSiteMapsOptions, SiteMapsOptions } from \"./types\";\n\nconst MISSING_SITE_URL =\n \"[ox-content] siteMaps is enabled but ssg.siteUrl is not set; sitemap.xml, robots.txt, and llms.txt were not written\";\n\n/** One page considered for crawl manifests. */\nexport interface SiteMapPageInput {\n loc: string;\n title: string;\n description?: string;\n draft?: boolean;\n unlisted?: boolean;\n}\n\n/** Inputs for rendering crawl-manifest bodies. */\nexport interface SiteMapsRenderInput {\n options?: ResolvedSiteMapsOptions | null;\n siteUrl?: string;\n sitemapLoc?: string;\n siteName?: string;\n siteDescription?: string;\n pages: readonly SiteMapPageInput[];\n}\n\n/** Rendered crawl-manifest bodies, or a skip warning. */\nexport interface SiteMapsRenderResult {\n sitemapXml?: string;\n robotsTxt?: string;\n llmsTxt?: string;\n warning?: string;\n}\n\n/** Inputs for writing crawl manifests next to generated HTML. */\nexport interface WriteSiteMapFilesInput {\n outDir: string;\n siteUrl?: string;\n base: string;\n siteName?: string;\n siteDescription?: string;\n options?: ResolvedSiteMapsOptions;\n pages: readonly SiteMapPageInput[];\n}\n\n/**\n * Resolves `siteMaps` with defaults.\n *\n * `false` / omitted stays off. `true` enables all three files. An object\n * enables the feature and overrides only the fields the site set.\n */\nexport function resolveSiteMapsOptions(\n value: boolean | SiteMapsOptions | undefined,\n): ResolvedSiteMapsOptions {\n if (!value) {\n return { enabled: false, robots: true, llms: true };\n }\n if (value === true) {\n return { enabled: true, robots: true, llms: true };\n }\n return {\n enabled: true,\n robots: value.robots ?? true,\n llms: value.llms ?? true,\n };\n}\n\n/** Builds sitemap / robots / llms bodies without writing files. */\nexport function generateSiteMaps(input: SiteMapsRenderInput): SiteMapsRenderResult {\n if (!input.options?.enabled) {\n return {};\n }\n if (!hasSiteUrl(input.siteUrl)) {\n return { warning: MISSING_SITE_URL };\n }\n\n const published = input.pages\n .filter((page) => !page.draft && !page.unlisted && page.loc.length > 0)\n .slice()\n .sort((left, right) => (left.loc < right.loc ? -1 : left.loc > right.loc ? 1 : 0));\n\n const result: SiteMapsRenderResult = {\n sitemapXml: generateSitemapXml(published),\n };\n if (input.options.robots) {\n result.robotsTxt = generateRobotsTxt(input.sitemapLoc ?? \"\");\n }\n if (input.options.llms) {\n result.llmsTxt = generateLlmsTxt(input, published);\n }\n return result;\n}\n\n/** Writes enabled crawl manifests into `outDir`. */\nexport async function writeSiteMapFiles(\n input: WriteSiteMapFilesInput,\n): Promise<{ files: string[]; warning?: string }> {\n const generated = generateSiteMaps({\n options: input.options,\n siteUrl: input.siteUrl,\n sitemapLoc: absoluteSitemapUrl(input.siteUrl, input.base),\n siteName: input.siteName,\n siteDescription: input.siteDescription,\n pages: input.pages,\n });\n if (generated.warning) {\n return { files: [], warning: generated.warning };\n }\n\n const outputs: Array<[string, string]> = [\n [generated.sitemapXml, \"sitemap.xml\"],\n [generated.robotsTxt, \"robots.txt\"],\n [generated.llmsTxt, \"llms.txt\"],\n ].filter((entry): entry is [string, string] => entry[0] != null);\n if (outputs.length === 0) {\n return { files: [] };\n }\n\n await fs.mkdir(input.outDir, { recursive: true });\n const files: string[] = [];\n for (const [body, name] of outputs) {\n const outputPath = path.join(input.outDir, name);\n await fs.writeFile(outputPath, body, \"utf8\");\n files.push(outputPath);\n }\n return { files };\n}\n\nfunction hasSiteUrl(siteUrl: string | undefined): boolean {\n return Boolean(siteUrl && siteUrl.trim());\n}\n\nfunction absoluteSitemapUrl(siteUrl: string | undefined, base: string): string {\n if (!hasSiteUrl(siteUrl)) {\n return \"\";\n }\n const origin = (siteUrl ?? \"\").trim().replace(/\\/+$/, \"\");\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return `${origin}${prefix}sitemap.xml`;\n}\n\nfunction generateSitemapXml(pages: readonly SiteMapPageInput[]): string {\n let xml =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\\n';\n for (const page of pages) {\n xml += \" <url>\\n <loc>\";\n xml += escapeXml(page.loc);\n xml += \"</loc>\\n </url>\\n\";\n }\n xml += \"</urlset>\\n\";\n return xml;\n}\n\nfunction generateRobotsTxt(sitemapLoc: string): string {\n let loc = \"\";\n for (const ch of sitemapLoc) {\n if (ch !== \"\\n\" && ch !== \"\\r\") {\n loc += ch;\n }\n }\n return `User-agent: *\\nAllow: /\\n\\nSitemap: ${loc}\\n`;\n}\n\nfunction generateLlmsTxt(input: SiteMapsRenderInput, pages: readonly SiteMapPageInput[]): string {\n let text = `# ${escapeLlmsText(input.siteName ?? \"\")}\\n\\n`;\n const siteDescription = input.siteDescription?.trim();\n if (siteDescription) {\n text += `> ${escapeLlmsText(siteDescription)}\\n\\n`;\n }\n text += \"## Pages\\n\\n\";\n for (const page of pages) {\n text += `- [${escapeLlmsText(page.title)}](${escapeLlmsUrl(page.loc)})`;\n const description = page.description?.trim();\n if (description) {\n text += `: ${escapeLlmsText(description)}`;\n }\n text += \"\\n\";\n }\n return text;\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n\nfunction flattenText(value: string): string {\n return value.split(/\\s+/u).filter(Boolean).join(\" \");\n}\n\nfunction escapeLlmsText(value: string): string {\n return flattenText(value).replace(/[\\\\[\\]()<>&\"]/g, (ch) => {\n switch (ch) {\n case \"\\\\\":\n return \"\\\\\\\\\";\n case \"[\":\n return \"\\\\[\";\n case \"]\":\n return \"\\\\]\";\n case \"(\":\n return \"\\\\(\";\n case \")\":\n return \"\\\\)\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case \"&\":\n return \"&amp;\";\n default:\n return \"&quot;\";\n }\n });\n}\n\nfunction escapeLlmsUrl(value: string): string {\n let escaped = \"\";\n for (const ch of value) {\n if (ch === \" \") {\n escaped += \"%20\";\n } else if (ch === \"(\") {\n escaped += \"%28\";\n } else if (ch === \")\") {\n escaped += \"%29\";\n } else if (ch !== \"\\n\" && ch !== \"\\r\" && ch !== \"\\t\") {\n escaped += ch;\n }\n }\n return escaped;\n}\n","/**\n * Opt-in draft / unlisted / scheduled page classification.\n */\n\nimport { importNapiModuleSync } from \"./napi\";\nimport type { PublishStateOptions, ResolvedPublishStateOptions } from \"./types\";\n\ninterface NavItemLike {\n title: string;\n path: string;\n href: string;\n children?: NavItemLike[];\n}\n\ninterface NavGroupLike {\n title: string;\n items: NavItemLike[];\n}\n\n/** One page considered for publish-state filtering. */\nexport interface PublishStatePage {\n inputPath: string;\n title: string;\n frontmatter: Record<string, unknown>;\n routePaths: {\n href: string;\n urlPath: string;\n };\n}\n\n/** Split pages into production output vs listing surfaces. */\nexport interface PartitionedPages<T> {\n output: T[];\n listed: T[];\n}\n\n/**\n * Resolves `publishState` with defaults.\n *\n * `false` / omitted stays off. `true` enables production filtering. An object\n * enables the feature and overrides only the fields the site set.\n */\nexport function resolvePublishStateOptions(\n value: boolean | PublishStateOptions | undefined,\n): ResolvedPublishStateOptions {\n if (!value) {\n return { enabled: false, includeDrafts: false };\n }\n if (value === true) {\n return { enabled: true, includeDrafts: false };\n }\n return {\n enabled: value.enabled ?? true,\n now: value.now,\n includeDrafts: value.includeDrafts ?? false,\n };\n}\n\n/** Classifies one frontmatter object. Never throws. */\nexport function classifyPublishState(\n frontmatter: Record<string, unknown>,\n options: ResolvedPublishStateOptions | undefined,\n): { output: boolean; listed: boolean } {\n try {\n return importNapiModuleSync().classifyPublishState(\n JSON.stringify(frontmatter ?? {}),\n toNapiPublishState(options),\n );\n } catch {\n return { output: true, listed: true };\n }\n}\n\n/** Splits pages into those that write HTML and those that appear in listings. */\nexport function partitionPublishedPages<T extends { frontmatter: Record<string, unknown> }>(\n pages: readonly T[],\n options: ResolvedPublishStateOptions | undefined,\n): PartitionedPages<T> {\n if (!options?.enabled) {\n return { output: [...pages], listed: [...pages] };\n }\n const output: T[] = [];\n const listed: T[] = [];\n for (const page of pages) {\n const decision = classifyPublishState(page.frontmatter, options);\n if (decision.output) {\n output.push(page);\n }\n if (decision.listed) {\n listed.push(page);\n }\n }\n return { output, listed };\n}\n\n/** Drops nav items that resolve to hidden (unpublished or unlisted) pages. */\nexport function filterNavGroups<T extends NavGroupLike>(\n groups: T[],\n hidden: ReadonlySet<string>,\n): T[] {\n return groups\n .map((group) => ({\n ...group,\n items: filterNavItems(group.items, hidden),\n }))\n .filter((group) => group.items.length > 0);\n}\n\nfunction filterNavItems<T extends NavItemLike>(items: T[], hidden: ReadonlySet<string>): T[] {\n const kept: SsgNavItem[] = [];\n for (const item of items) {\n if (isHiddenNavTarget(item, hidden)) {\n continue;\n }\n const children = item.children?.length ? filterNavItems(item.children, hidden) : item.children;\n kept.push(children === item.children ? item : { ...item, children });\n }\n return kept;\n}\n\nfunction isHiddenNavTarget(item: NavItemLike, hidden: ReadonlySet<string>): boolean {\n return hidden.has(item.path) || hidden.has(item.href);\n}\n\n/** Keys used to match a page against generated nav items. */\nexport function hiddenNavKeys(\n pages: readonly PublishStatePage[],\n listed: readonly PublishStatePage[],\n): Set<string> {\n const listedPaths = new Set(listed.map((page) => page.inputPath));\n const hidden = new Set<string>();\n for (const page of pages) {\n if (listedPaths.has(page.inputPath)) {\n continue;\n }\n hidden.add(page.routePaths.urlPath);\n hidden.add(page.routePaths.href);\n }\n return hidden;\n}\n\nexport function toNapiPublishState(\n options: ResolvedPublishStateOptions | undefined,\n): { enabled?: boolean; now?: string; includeDrafts?: boolean } | undefined {\n if (!options) {\n return undefined;\n }\n return {\n enabled: options.enabled,\n now: options.now,\n includeDrafts: options.includeDrafts,\n };\n}\n","/**\n * Opt-in permalink / slug routing and `_index` frontmatter cascade.\n *\n * Resolution follows `ox_content_ssg::resolve_page_routes`. The Vite plugin\n * applies those URLs during SSG and collection manifest builds.\n */\n\nimport type {\n CascadeOptions,\n PermalinksOptions,\n ResolvedCascadeOptions,\n ResolvedPermalinksOptions,\n} from \"./types\";\n\nconst RESERVED_CASCADE_KEYS = new Set([\"permalink\", \"slug\"]);\n\n/** One page considered for cascade and permalink resolution. */\nexport interface RoutePageInput {\n source: string;\n fileUrl: string;\n frontmatter: Record<string, unknown>;\n}\n\n/** A page after cascade and optional permalink / slug rewriting. */\nexport interface ResolvedRoutePage {\n source: string;\n urlPath: string;\n frontmatter: Record<string, unknown>;\n}\n\n/** Resolved pages plus collision / rejection errors. */\nexport interface RouteResolveOutput {\n pages: ResolvedRoutePage[];\n errors: string[];\n}\n\n/** Resolves `permalinks`. `false` / omitted stays off. `true` / `{}` enables. */\nexport function resolvePermalinksOptions(\n value: boolean | PermalinksOptions | undefined,\n): ResolvedPermalinksOptions {\n return resolveFlag(value);\n}\n\n/** Resolves `cascade`. `false` / omitted stays off. `true` / `{}` enables. */\nexport function resolveCascadeOptions(\n value: boolean | CascadeOptions | undefined,\n): ResolvedCascadeOptions {\n return resolveFlag(value);\n}\n\n/**\n * Applies cascade (when on) then permalink / slug rewriting (when on).\n *\n * Collisions skip the later page and keep the first. Rejected permalinks stay\n * on the file-tree URL. Hostile non-string values are ignored.\n */\nexport function resolvePageRoutes(input: {\n pages: readonly RoutePageInput[];\n permalinks?: ResolvedPermalinksOptions | null;\n cascade?: ResolvedCascadeOptions | null;\n}): RouteResolveOutput {\n const cascaded = applyCascade(input.pages, input.cascade);\n if (!input.permalinks?.enabled) {\n return {\n pages: cascaded.map((page) => ({\n source: page.source,\n urlPath: normalizeUrlPath(page.fileUrl),\n frontmatter: page.frontmatter,\n })),\n errors: [],\n };\n }\n\n const pages: ResolvedRoutePage[] = [];\n const errors: string[] = [];\n const claimed = new Map<string, string>();\n for (const page of cascaded) {\n const { urlPath, error } = resolveOne(page);\n if (error) {\n errors.push(error);\n }\n const owner = claimed.get(urlPath);\n if (owner) {\n errors.push(\n `[ox-content] URL collision at \"${urlPath}\": ${owner} kept, ${page.source} skipped`,\n );\n continue;\n }\n claimed.set(urlPath, page.source);\n pages.push({ source: page.source, urlPath, frontmatter: page.frontmatter });\n }\n return { pages, errors };\n}\n\n/** Escapes a value for use in an HTML attribute. */\nexport function escapeAttribute(value: string): string {\n return value.replace(/[&<>\"']/gu, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n\nexport function normalizeUrlPath(value: string): string {\n const segments = pathSegments(value);\n return segments.length === 0 ? \"/\" : segments.join(\"/\");\n}\n\nfunction resolveFlag(value: boolean | { enabled?: boolean } | undefined): { enabled: boolean } {\n if (!value) {\n return { enabled: false };\n }\n if (value === true) {\n return { enabled: true };\n }\n return { enabled: value.enabled !== false };\n}\n\nfunction applyCascade(\n pages: readonly RoutePageInput[],\n options?: ResolvedCascadeOptions | null,\n): RoutePageInput[] {\n if (!options?.enabled) {\n return pages.map((page) => ({ ...page, frontmatter: { ...page.frontmatter } }));\n }\n const indexes = new Map<string, Record<string, unknown>>();\n for (const page of pages) {\n const source = normalizeSeparators(page.source);\n if (isIndexFile(source)) {\n indexes.set(directoryOf(source), { ...page.frontmatter });\n }\n }\n return pages.map((page) => {\n const source = normalizeSeparators(page.source);\n const frontmatter = { ...page.frontmatter };\n for (const dir of ancestorDirs(source)) {\n const defaults = indexes.get(dir);\n if (!defaults || (isIndexFile(source) && directoryOf(source) === dir)) {\n continue;\n }\n for (const [key, value] of Object.entries(defaults)) {\n if (!RESERVED_CASCADE_KEYS.has(key) && !(key in frontmatter)) {\n frontmatter[key] = value;\n }\n }\n }\n return { ...page, frontmatter };\n });\n}\n\nfunction resolveOne(page: RoutePageInput): { urlPath: string; error?: string } {\n const fileUrl = normalizeUrlPath(page.fileUrl);\n const permalink = readString(page.frontmatter.permalink);\n if (permalink !== undefined) {\n const url = isSafePermalink(permalink) ? normalizeUrlPath(permalink) : undefined;\n return url\n ? { urlPath: url }\n : {\n urlPath: fileUrl,\n error: `[ox-content] rejected permalink ${JSON.stringify(permalink)} on ${page.source} (path escape); using the file-tree URL`,\n };\n }\n const slug = readString(page.frontmatter.slug);\n if (slug !== undefined) {\n const url = rewriteSlug(fileUrl, slug);\n return url\n ? { urlPath: url }\n : {\n urlPath: fileUrl,\n error: `[ox-content] rejected slug ${JSON.stringify(slug)} on ${page.source} (path escape); using the file-tree URL`,\n };\n }\n return { urlPath: fileUrl };\n}\n\nfunction rewriteSlug(fileUrl: string, slug: string): string | undefined {\n const trimmed = slug.trim();\n if (trimmed.includes(\"/\") || !isSafePermalink(trimmed)) {\n return undefined;\n }\n const normalized = normalizeUrlPath(trimmed);\n if (normalized === \"/\") {\n return undefined;\n }\n if (fileUrl === \"/\") {\n return normalized;\n }\n const segments = fileUrl.split(\"/\").filter(Boolean);\n segments.pop();\n segments.push(normalized);\n return segments.join(\"/\");\n}\n\nfunction isSafePermalink(value: string): boolean {\n const trimmed = value.trim();\n if (!trimmed || /[\\n\\r\\0]/u.test(trimmed) || trimmed.includes(\"\\\\\") || trimmed.startsWith(\"//\")) {\n return false;\n }\n if (/^[A-Za-z]:/u.test(trimmed)) {\n return false;\n }\n const lower = trimmed.toLowerCase();\n if (\n lower.includes(\"javascript:\") ||\n lower.includes(\"data:\") ||\n lower.includes(\"vbscript:\") ||\n lower.includes(\"file:\") ||\n lower.includes(\"://\")\n ) {\n return false;\n }\n return pathSegments(trimmed).every((segment) => segment !== \"..\" && segment !== \".\");\n}\n\nfunction pathSegments(value: string): string[] {\n return value\n .trim()\n .replace(/^\\/+|\\/+$/gu, \"\")\n .split(\"/\")\n .filter(Boolean);\n}\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction normalizeSeparators(value: string): string {\n return value.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction isIndexFile(source: string): boolean {\n const name = source.split(\"/\").pop() ?? source;\n const stem = name.includes(\".\") ? name.slice(0, name.lastIndexOf(\".\")) : name;\n return stem.toLowerCase() === \"_index\";\n}\n\nfunction directoryOf(source: string): string {\n const index = source.lastIndexOf(\"/\");\n return index === -1 ? \"\" : source.slice(0, index);\n}\n\nfunction ancestorDirs(source: string): string[] {\n const dir = directoryOf(source);\n const dirs = [\"\"];\n if (!dir) {\n return dirs;\n }\n let acc = \"\";\n for (const segment of dir.split(\"/\")) {\n acc = acc ? `${acc}/${segment}` : segment;\n dirs.push(acc);\n }\n return dirs;\n}\n","/**\n * Applies resolved permalinks / cascade to SSG pages and collection entries.\n */\n\nimport * as path from \"node:path\";\nimport { importNapiModuleSync } from \"./napi\";\nimport { normalizeUrlPath, resolvePageRoutes } from \"./permalinks\";\nimport type {\n CollectionManifest,\n ResolvedCascadeOptions,\n ResolvedPermalinksOptions,\n} from \"./types\";\n\n/** SSG page shape that can have its `routePaths` rewritten. */\nexport interface SsgRoutablePage {\n inputPath: string;\n routePaths: {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n };\n frontmatter: Record<string, unknown>;\n}\n\ninterface NavItem {\n title: string;\n path: string;\n href: string;\n children?: NavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\ninterface NavGroup {\n title: string;\n items: NavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/** Rewrites SSG `routePaths` from resolved permalinks / slugs. */\nexport function applySsgPageRoutes(input: {\n pages: readonly SsgRoutablePage[];\n permalinks?: ResolvedPermalinksOptions | null;\n cascade?: ResolvedCascadeOptions | null;\n srcDir: string;\n outDir: string;\n base: string;\n extension: string;\n siteUrl?: string;\n}): { pages: SsgRoutablePage[]; errors: string[] } {\n const resolved = resolvePageRoutes({\n pages: input.pages.map((page) => ({\n source: page.inputPath,\n fileUrl: page.routePaths.urlPath,\n frontmatter: page.frontmatter,\n })),\n permalinks: input.permalinks,\n cascade: input.cascade,\n });\n const bySource = new Map(resolved.pages.map((page) => [page.source, page]));\n const pages: SsgRoutablePage[] = [];\n for (const page of input.pages) {\n const hit = bySource.get(page.inputPath);\n if (!hit) {\n continue;\n }\n pages.push({\n ...page,\n frontmatter: hit.frontmatter,\n routePaths: routePathsFromUrl(\n hit.urlPath,\n input.srcDir,\n input.outDir,\n input.base,\n input.extension,\n input.siteUrl,\n ),\n });\n }\n return { pages, errors: resolved.errors };\n}\n\n/** Rewrites collection `path` / `stem` / inherited frontmatter. */\nexport function applyCollectionRoutes(\n manifest: CollectionManifest,\n permalinks?: ResolvedPermalinksOptions | null,\n cascade?: ResolvedCascadeOptions | null,\n): { manifest: CollectionManifest; errors: string[] } {\n if (!permalinks?.enabled && !cascade?.enabled) {\n return { manifest, errors: [] };\n }\n const errors: string[] = [];\n const collections: CollectionManifest[\"collections\"] = {};\n for (const [name, entries] of Object.entries(manifest.collections)) {\n const resolved = resolvePageRoutes({\n pages: entries.map((entry) => ({\n source: entry.source,\n fileUrl: entry.path,\n frontmatter: { ...entry.frontmatter },\n })),\n permalinks,\n cascade,\n });\n errors.push(...resolved.errors);\n const bySource = new Map(resolved.pages.map((page) => [page.source, page]));\n collections[name] = entries.flatMap((entry) => {\n const hit = bySource.get(entry.source);\n if (!hit) {\n return [];\n }\n const urlPath = hit.urlPath;\n const pathValue = urlPath === \"/\" ? \"/\" : `/${urlPath.replace(/^\\/+/u, \"\")}`;\n return [\n {\n ...entry,\n ...pickInherited(hit.frontmatter),\n path: pathValue,\n stem: pathValue === \"/\" ? \"\" : pathValue.slice(1),\n frontmatter: hit.frontmatter,\n },\n ];\n });\n }\n return { manifest: { collections }, errors };\n}\n\n/** Updates auto-nav hrefs after permalinks change a page URL. */\nexport function remapNavGroups<T extends NavGroup>(\n nav: T[],\n kept: readonly { fileUrl: string; urlPath: string; href: string }[],\n skippedFileUrls: readonly string[],\n): T[] {\n const skipped = new Set(skippedFileUrls.map(normalizeUrlPath));\n const byFile = new Map(kept.map((page) => [normalizeUrlPath(page.fileUrl), page]));\n return nav\n .map((group) => ({ ...group, items: remapNavItems(group.items, byFile, skipped) }))\n .filter((group) => group.items.length > 0);\n}\n\nfunction routePathsFromUrl(\n urlPath: string,\n srcDir: string,\n outDir: string,\n base: string,\n extension: string,\n siteUrl?: string,\n) {\n const relative =\n urlPath === \"/\" || !urlPath ? \"index.md\" : `${urlPath.replace(/^\\/+|\\/+$/gu, \"\")}.md`;\n return importNapiModuleSync().resolveSsgRoutePaths(\n path.join(srcDir, relative),\n srcDir,\n outDir,\n base,\n extension,\n siteUrl,\n );\n}\n\nfunction remapNavItems<T extends NavItem>(\n items: T[],\n byFile: Map<string, { urlPath: string; href: string }>,\n skipped: Set<string>,\n): T[] {\n return items.flatMap((item) => {\n const key = normalizeUrlPath(item.path);\n if (skipped.has(key)) {\n return [];\n }\n const hit = byFile.get(key);\n const children = item.children ? remapNavItems(item.children, byFile, skipped) : undefined;\n return [{ ...item, path: hit?.urlPath ?? item.path, href: hit?.href ?? item.href, children }];\n });\n}\n\nfunction pickInherited(frontmatter: Record<string, unknown>): Record<string, unknown> {\n const skip = new Set([\"id\", \"collection\", \"path\", \"stem\", \"source\", \"extension\", \"frontmatter\"]);\n const picked: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(frontmatter)) {\n if (!skip.has(key)) {\n picked[key] = value;\n }\n }\n return picked;\n}\n","/**\n * Opt-in static redirects / aliases.\n *\n * HTML bodies follow `ox_content_ssg::generate_redirects`. The Vite plugin\n * writes those files during SSG without adding a NAPI surface.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { RedirectsOptions, ResolvedRedirectsOptions } from \"./types\";\n\nconst OPTION_KEYS = new Set([\"map\", \"netlify\", \"headers\", \"json\", \"allowExternal\"]);\n\n/** One page that may declare aliases or a single `redirect` source. */\nexport interface RedirectPageInput {\n dest: string;\n aliases?: unknown;\n redirect?: unknown;\n}\n\n/** Inputs for planning redirect files. */\nexport interface RedirectPlanInput {\n options?: ResolvedRedirectsOptions | null;\n base?: string;\n pages: readonly RedirectPageInput[];\n}\n\n/** One planned static HTML redirect. */\nexport interface RedirectFilePlan {\n from: string;\n to: string;\n relativePath: string;\n html: string;\n}\n\n/** Planned redirect files and optional host / JSON bodies. */\nexport interface RedirectPlan {\n files: RedirectFilePlan[];\n netlify?: string;\n headers?: string;\n json?: string;\n}\n\n/** Inputs for writing redirect files next to generated HTML. */\nexport interface WriteRedirectFilesInput {\n outDir: string;\n base?: string;\n options?: ResolvedRedirectsOptions;\n pages: readonly RedirectPageInput[];\n}\n\n/**\n * Resolves `redirects` with defaults.\n *\n * `false` / omitted stays off. `true` or `{}` enables empty defaults.\n * A path map (`{ \"/old\": \"/new\" }`) enables the feature with that map.\n * `{ map, netlify, headers, json, allowExternal }` overrides only set fields.\n */\nexport function resolveRedirectsOptions(\n value: boolean | RedirectsOptions | Record<string, string> | undefined,\n): ResolvedRedirectsOptions {\n if (!value) {\n return {\n enabled: false,\n map: {},\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n map: {},\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n };\n }\n if (isOptionsObject(value)) {\n return {\n enabled: true,\n map: { ...value.map },\n netlify: value.netlify ?? false,\n headers: value.headers ?? false,\n json: value.json ?? false,\n allowExternal: value.allowExternal ?? false,\n };\n }\n return {\n enabled: true,\n map: { ...value },\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n };\n}\n\n/** Plans redirect HTML files without writing them. */\nexport function planRedirectFiles(input: RedirectPlanInput): RedirectPlan {\n if (!input.options?.enabled) {\n return { files: [] };\n }\n\n const occupied = new Set<string>();\n for (const page of input.pages) {\n const dest = normalizePath(page.dest);\n if (dest) {\n occupied.add(dest);\n }\n }\n\n const files: RedirectFilePlan[] = [];\n const index = new Map<string, number>();\n\n for (const page of input.pages) {\n const to = normalizeDest(page.dest, input.options.allowExternal);\n if (!to) {\n continue;\n }\n for (const alias of readStringList(page.aliases)) {\n upsert(files, index, occupied, alias, to, input.base);\n }\n if (typeof page.redirect === \"string\") {\n upsert(files, index, occupied, page.redirect, to, input.base);\n }\n }\n for (const [from, to] of Object.entries(input.options.map)) {\n const dest = normalizeDest(to, input.options.allowExternal);\n if (!dest) {\n continue;\n }\n upsert(files, index, occupied, from, dest, input.base);\n }\n\n if (files.length === 0) {\n return { files: [] };\n }\n\n const plan: RedirectPlan = { files };\n if (input.options.netlify) {\n plan.netlify = files.map((file) => `${file.from} ${file.to} 301`).join(\"\\n\") + \"\\n\";\n }\n if (input.options.headers) {\n plan.headers = files.map((file) => `${file.from}\\n Location: ${file.to}`).join(\"\\n\") + \"\\n\";\n }\n if (input.options.json) {\n plan.json = JSON.stringify(files.map((file) => ({ from: file.from, to: file.to })));\n }\n return plan;\n}\n\n/** Writes planned redirect HTML (and optional host files) into `outDir`. */\nexport async function writeRedirectFiles(\n input: WriteRedirectFilesInput,\n): Promise<{ files: string[] }> {\n const plan = planRedirectFiles(input);\n if (plan.files.length === 0 && !plan.netlify && !plan.headers && !plan.json) {\n return { files: [] };\n }\n\n await fs.mkdir(input.outDir, { recursive: true });\n const files: string[] = [];\n for (const entry of plan.files) {\n const outputPath = path.join(input.outDir, entry.relativePath);\n try {\n await fs.access(outputPath);\n continue;\n } catch {\n await fs.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.writeFile(outputPath, entry.html, \"utf8\");\n files.push(outputPath);\n }\n }\n for (const [body, name] of [\n [plan.netlify, \"_redirects\"],\n [plan.headers, \"_headers\"],\n [plan.json, \"redirects.json\"],\n ] as const) {\n if (!body) {\n continue;\n }\n const outputPath = path.join(input.outDir, name);\n await fs.writeFile(outputPath, body, \"utf8\");\n files.push(outputPath);\n }\n return { files };\n}\n\n/** Static HTML redirect body. `dest` is escaped. */\nexport function generateRedirectHtml(dest: string): string {\n const escaped = escapeHtml(dest);\n return `\\\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta http-equiv=\"refresh\" content=\"0;url=${escaped}\">\n<link rel=\"canonical\" href=\"${escaped}\">\n<title>Redirecting</title>\n</head>\n<body>\n<p>Redirecting to <a href=\"${escaped}\">${escaped}</a>.</p>\n</body>\n</html>\n`;\n}\n\n/** Same-origin path: leading `/`, not `//`, and no scheme. */\nexport function isSafeDest(value: string): boolean {\n return isAllowedDest(value, false);\n}\n\n/** Strips a trailing slash except for `/`. Unsafe values become `null`. */\nexport function normalizePath(value: string): string | null {\n return normalizeDest(value, false);\n}\n\nfunction normalizeDest(value: string, allowExternal: boolean): string | null {\n if (!isAllowedDest(value, allowExternal)) {\n return null;\n }\n const trimmed = value.trim();\n if (isHttpUrl(trimmed)) {\n return trimmed;\n }\n if (trimmed === \"/\") {\n return \"/\";\n }\n return trimmed.replace(/\\/+$/u, \"\");\n}\n\nfunction isAllowedDest(value: string, allowExternal: boolean): boolean {\n const trimmed = value.trim();\n if (!trimmed || hasDisallowedDestChars(trimmed)) {\n return false;\n }\n if (isHttpUrl(trimmed)) {\n return allowExternal;\n }\n if (!trimmed.startsWith(\"/\") || trimmed.startsWith(\"//\") || hasUnsafePathSegments(trimmed)) {\n return false;\n }\n const lower = trimmed.toLowerCase();\n return !lower.includes(\"javascript:\") && !lower.includes(\"data:\") && !lower.includes(\"://\");\n}\n\nfunction hasDisallowedDestChars(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || code === 0x7f || code === 0x3b) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasUnsafePathSegments(value: string): boolean {\n return (\n value.includes(\"\\\\\") || value.split(\"/\").some((segment) => segment === \".\" || segment === \"..\")\n );\n}\n\nfunction isHttpUrl(value: string): boolean {\n const lower = value.toLowerCase();\n return lower.startsWith(\"https://\") || lower.startsWith(\"http://\");\n}\n\nfunction isOptionsObject(\n value: RedirectsOptions | Record<string, string>,\n): value is RedirectsOptions {\n return Object.keys(value).some((key) => OPTION_KEYS.has(key));\n}\n\nfunction readStringList(value: unknown): string[] {\n if (typeof value === \"string\") {\n return [value];\n }\n if (!Array.isArray(value)) {\n return [];\n }\n return value.filter((entry): entry is string => typeof entry === \"string\");\n}\n\nfunction applyBase(dest: string, base: string | undefined): string {\n if (isHttpUrl(dest) || !base || base === \"/\") {\n return dest;\n }\n const prefix = base.replace(/\\/+$/u, \"\");\n return dest === \"/\" ? `${prefix}/` : `${prefix}${dest}`;\n}\n\nfunction upsert(\n files: RedirectFilePlan[],\n index: Map<string, number>,\n occupied: Set<string>,\n from: string,\n to: string,\n base: string | undefined,\n): void {\n const source = normalizePath(from);\n if (!source || source === to || occupied.has(source)) {\n return;\n }\n const href = applyBase(to, base);\n const html = generateRedirectHtml(href);\n const relativePath = source === \"/\" ? \"index.html\" : `${source.slice(1)}/index.html`;\n const slot = index.get(source);\n if (slot !== undefined) {\n files[slot] = { from: source, to, relativePath, html };\n return;\n }\n index.set(source, files.length);\n files.push({ from: source, to, relativePath, html });\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n","/**\n * Opt-in custom 404 page helpers.\n *\n * Resolution and path rules live here. The Vite plugin writes the themed HTML\n * during SSG and omits the page from the search index and sitemap.\n */\n\nimport * as path from \"node:path\";\nimport type { NotFoundOptions, ResolvedNotFoundOptions } from \"./types\";\nimport { stripMarkdownExtension } from \"./markdown\";\n\nexport const DEFAULT_NOT_FOUND_SOURCE = \"404.md\";\nexport const DEFAULT_NOT_FOUND_OUTPUT = \"404.html\";\nexport const FALLBACK_NOT_FOUND_TITLE = \"Page not found\";\n\n/** Built-in Markdown used when the configured source file is missing. */\nexport const FALLBACK_NOT_FOUND_MARKDOWN = `---\ntitle: ${FALLBACK_NOT_FOUND_TITLE}\n---\n\n# ${FALLBACK_NOT_FOUND_TITLE}\n\nThe page you requested does not exist. Use search or the navigation to find what you need.\n`;\n\n/**\n * Resolves `ssg.notFound` with defaults.\n *\n * `false` / omitted stays off. `true` enables `404.md` → `404.html`. An object\n * enables the feature and overrides only the fields the site set.\n */\nexport function resolveNotFoundOptions(\n value: boolean | NotFoundOptions | undefined,\n): ResolvedNotFoundOptions {\n if (!value) {\n return {\n enabled: false,\n source: DEFAULT_NOT_FOUND_SOURCE,\n output: DEFAULT_NOT_FOUND_OUTPUT,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n source: DEFAULT_NOT_FOUND_SOURCE,\n output: DEFAULT_NOT_FOUND_OUTPUT,\n };\n }\n return {\n enabled: true,\n source: value.source ?? DEFAULT_NOT_FOUND_SOURCE,\n output: value.output ?? DEFAULT_NOT_FOUND_OUTPUT,\n };\n}\n\n/** Absolute source path, confined to `srcDir`. */\nexport function resolveNotFoundSourcePath(srcDir: string, source: string): string {\n return resolveContainedPath(srcDir, source, DEFAULT_NOT_FOUND_SOURCE);\n}\n\n/** Absolute output path, confined to `outDir`. */\nexport function resolveNotFoundOutputPath(outDir: string, output: string): string {\n return resolveContainedPath(outDir, output, DEFAULT_NOT_FOUND_OUTPUT);\n}\n\n/** True when `filePath` is the enabled not-found source. */\nexport function isNotFoundSourceFile(\n filePath: string,\n srcDir: string,\n options?: ResolvedNotFoundOptions,\n): boolean {\n if (!options?.enabled) {\n return false;\n }\n return path.resolve(filePath) === resolveNotFoundSourcePath(srcDir, options.source);\n}\n\n/** Search document id for a not-found source path. */\nexport function notFoundSearchDocumentId(source: string): string {\n const normalized = source.replaceAll(\"\\\\\", \"/\").replace(/^\\.?\\//, \"\");\n return stripMarkdownExtension(normalized);\n}\n\n/** Search document ids that must not be indexed when the feature is on. */\nexport function notFoundSearchExcludeIds(options?: ResolvedNotFoundOptions): string[] {\n if (!options?.enabled) {\n return [];\n }\n return [notFoundSearchDocumentId(options.source)];\n}\n\nfunction resolveContainedPath(rootDir: string, relativePath: string, fallback: string): string {\n const root = path.resolve(rootDir);\n const resolved = path.resolve(root, relativePath);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved === root || resolved.startsWith(prefix)) {\n return resolved;\n }\n return path.join(root, fallback);\n}\n","import type { CollectionManifest } from \"./types\";\n\nconst runtime = String.raw`\nfunction getValue(row, field) {\n if (field in row) return row[field];\n return String(field)\n .split(\".\")\n .reduce((value, key) => (value == null ? undefined : value[key]), row);\n}\n\nfunction normalizePath(value) {\n const path = String(value || \"/\");\n if (path === \"/\") return path;\n return path.startsWith(\"/\") ? path.replace(/\\/+$/, \"\") : \"/\" + path.replace(/\\/+$/, \"\");\n}\n\nfunction likePattern(value) {\n const escaped = String(value).replace(/[\\\\^$.*+?()[\\]{}|]/g, \"\\\\$&\");\n return new RegExp(\"^\" + escaped.replace(/%/g, \".*\").replace(/_/g, \".\") + \"$\", \"i\");\n}\n\nfunction compare(left, right) {\n if (left == null && right == null) return 0;\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === \"number\" && typeof right === \"number\") return left - right;\n if (left instanceof Date || right instanceof Date) {\n return new Date(left).getTime() - new Date(right).getTime();\n }\n return String(left).localeCompare(String(right), undefined, {\n numeric: true,\n sensitivity: \"base\",\n });\n}\n\nfunction createPredicate(field, operator, value) {\n let op = String(operator ?? \"=\").toUpperCase();\n let expected = value;\n if (arguments.length === 2) {\n op = \"=\";\n expected = operator;\n }\n\n return (row) => {\n const actual = getValue(row, field);\n switch (op) {\n case \"=\":\n case \"==\":\n return actual === expected;\n case \"!=\":\n case \"<>\":\n return actual !== expected;\n case \">\":\n return compare(actual, expected) > 0;\n case \">=\":\n return compare(actual, expected) >= 0;\n case \"<\":\n return compare(actual, expected) < 0;\n case \"<=\":\n return compare(actual, expected) <= 0;\n case \"IN\":\n return Array.isArray(expected) && expected.includes(actual);\n case \"NOT IN\":\n return Array.isArray(expected) && !expected.includes(actual);\n case \"BETWEEN\":\n return Array.isArray(expected) && expected.length >= 2\n ? compare(actual, expected[0]) >= 0 && compare(actual, expected[1]) <= 0\n : false;\n case \"NOT BETWEEN\":\n return Array.isArray(expected) && expected.length >= 2\n ? compare(actual, expected[0]) < 0 || compare(actual, expected[1]) > 0\n : false;\n case \"IS NULL\":\n return actual == null;\n case \"IS NOT NULL\":\n return actual != null;\n case \"LIKE\":\n return likePattern(expected).test(String(actual ?? \"\"));\n case \"NOT LIKE\":\n return !likePattern(expected).test(String(actual ?? \"\"));\n default:\n throw new Error(\"Unsupported collection query operator: \" + op);\n }\n };\n}\n\nclass QueryGroup {\n constructor(rows) {\n this.rows = rows;\n this.conditions = [];\n }\n\n where(field, operator, value) {\n const test =\n arguments.length === 2\n ? createPredicate(field, operator)\n : createPredicate(field, operator, value);\n this.conditions.push({ join: \"and\", test });\n return this;\n }\n\n andWhere(factory) {\n const group = new QueryGroup(this.rows);\n factory(group);\n this.conditions.push({ join: \"and\", test: (row) => group.test(row) });\n return this;\n }\n\n orWhere(factory) {\n const group = new QueryGroup(this.rows);\n factory(group);\n this.conditions.push({ join: \"or\", test: (row) => group.test(row) });\n return this;\n }\n\n test(row) {\n let matched = true;\n for (const condition of this.conditions) {\n matched =\n condition.join === \"or\" ? matched || condition.test(row) : matched && condition.test(row);\n }\n return matched;\n }\n}\n\nclass CollectionQueryBuilder extends QueryGroup {\n constructor(rows) {\n super(rows);\n this.orders = [];\n this.selected = undefined;\n this.offset = 0;\n this.max = undefined;\n }\n\n path(path) {\n return this.where(\"path\", \"=\", normalizePath(path));\n }\n\n select(...fields) {\n this.selected = fields;\n return this;\n }\n\n order(field, direction = \"ASC\") {\n this.orders.push({ field, direction: String(direction).toUpperCase() });\n return this;\n }\n\n limit(limit) {\n this.max = Math.max(0, Number(limit) || 0);\n return this;\n }\n\n skip(skip) {\n this.offset = Math.max(0, Number(skip) || 0);\n return this;\n }\n\n materialize() {\n let rows = this.conditions.length ? this.rows.filter((row) => this.test(row)) : this.rows;\n if (this.orders.length) {\n rows = [...rows].sort((left, right) => {\n for (const order of this.orders) {\n const result = compare(getValue(left, order.field), getValue(right, order.field));\n if (result !== 0) return order.direction === \"DESC\" ? -result : result;\n }\n return 0;\n });\n }\n if (this.offset || this.max !== undefined) {\n rows = rows.slice(this.offset, this.max === undefined ? undefined : this.offset + this.max);\n }\n if (!this.selected) return rows;\n return rows.map((row) => {\n const selected = {};\n for (const field of this.selected) selected[field] = getValue(row, field);\n return selected;\n });\n }\n\n async all() {\n return this.materialize();\n }\n\n async first() {\n return this.materialize()[0] ?? null;\n }\n\n async count() {\n return this.conditions.length\n ? this.rows.filter((row) => this.test(row)).length\n : this.rows.length;\n }\n}\n\nexport function getCollection(name) {\n return collections[name] ? [...collections[name]] : [];\n}\n\nexport function queryCollection(name) {\n return new CollectionQueryBuilder(collections[name] || []);\n}\n\nexport const collectionNames = Object.keys(collections);\nexport { CollectionQueryBuilder };\nexport default { collections, collectionNames, getCollection, queryCollection };\n`;\n\nexport function generateCollectionsModule(manifest: CollectionManifest): string {\n return `const collections = ${JSON.stringify(manifest.collections)};\\n${runtime}`;\n}\n","import * as path from \"node:path\";\nimport { applyCollectionRoutes } from \"./apply-permalinks\";\nimport { toJsFileTreeOptions } from \"./file-tree-options\";\nimport { generateCollectionsModule } from \"./collections-runtime\";\nimport { importNapiModule } from \"./napi\";\nimport type {\n CollectionManifest,\n CollectionOptions,\n CollectionsOptions,\n ResolvedCollectionsOptions,\n ResolvedOptions,\n} from \"./types\";\n\nconst DEFAULT_COLLECTION_NAME = \"content\";\nconst DEFAULT_COLLECTION_SOURCE = \"**/*\";\n\ntype NativeCollectionDefinition = {\n name: string;\n source: string[];\n include: string[];\n};\n\ntype NativeTransformOptions = {\n gfm?: boolean;\n footnotes?: boolean;\n taskLists?: boolean;\n tables?: boolean;\n strikethrough?: boolean;\n autolinks?: boolean;\n autolinkUrls?: boolean;\n frontmatter?: boolean;\n tocMaxDepth?: number;\n codeAnnotations?: boolean;\n codeAnnotationMetaKey?: string;\n codeAnnotationSyntax?: string;\n codeAnnotationDefaultLineNumbers?: boolean;\n wikiLinks?: { enabled?: boolean; baseUrl?: string };\n emojiShortcodes?: { enabled?: boolean; custom?: Record<string, string> };\n attributes?: { enabled?: boolean };\n badges?: { enabled?: boolean };\n containers?: {\n enabled?: boolean;\n types?: Record<string, { title?: string; tag?: string }>;\n };\n images?: { enabled?: boolean; lazy?: boolean };\n cjkEmphasis?: boolean;\n codeImports?: { enabled?: boolean; rootDir?: string };\n includes?: { enabled?: boolean; rootDir?: string };\n steps?: { enabled?: boolean };\n fileTree?: {\n enabled?: boolean;\n defaultOpen?: boolean;\n icons?: boolean;\n iconFolder?: string;\n iconFolderOpen?: string;\n iconFile?: string;\n iconFiles?: Record<string, string>;\n };\n editThisPage?: {\n enabled?: boolean;\n repoUrl?: string;\n branch?: string;\n rootDir?: string;\n label?: string;\n };\n math?: boolean | { enabled?: boolean };\n};\n\ntype BuildCollectionManifestNapi = {\n buildCollectionManifest: (options: {\n srcDir: string;\n extensions: string[];\n frontmatter?: boolean;\n collections: NativeCollectionDefinition[];\n transformOptions?: NativeTransformOptions;\n }) => string;\n};\n\nexport function defineCollection<T extends CollectionOptions>(collection: T): T {\n return collection;\n}\n\nexport function defineCollections<T extends CollectionsOptions>(collections: T): T {\n return collections;\n}\n\nexport function resolveCollectionsOptions(\n options: CollectionsOptions | boolean | undefined,\n): ResolvedCollectionsOptions {\n if (options === false) {\n return { enabled: false, collections: {} };\n }\n\n const source = options === true || options === undefined ? defaultCollections() : options;\n const collections: ResolvedCollectionsOptions[\"collections\"] = {};\n\n for (const [name, value] of Object.entries(source)) {\n const collection = normalizeCollectionOptions(value);\n collections[name] = {\n name,\n source: normalizeSourcePatterns(collection.source),\n include: [...new Set(collection.include ?? [])],\n };\n }\n\n return { enabled: true, collections };\n}\n\nexport async function buildCollectionManifest(\n root: string,\n options: ResolvedOptions,\n): Promise<CollectionManifest> {\n if (!options.collections.enabled) {\n return { collections: {} };\n }\n\n const napi = (await importNapiModule()) as unknown as BuildCollectionManifestNapi;\n const manifestJson = napi.buildCollectionManifest({\n srcDir: path.resolve(root, options.srcDir),\n extensions: [...options.extensions],\n frontmatter: options.frontmatter,\n collections: Object.values(options.collections.collections).map((collection) => ({\n name: collection.name,\n source: collection.source,\n include: collection.include,\n })),\n transformOptions: createNativeTransformOptions(options),\n });\n\n const { manifest, errors } = applyCollectionRoutes(\n parseCollectionManifest(manifestJson),\n options.permalinks,\n options.cascade,\n );\n for (const error of errors) {\n console.warn(error);\n }\n return manifest;\n}\n\nexport async function generateCollectionsVirtualModule(\n root: string,\n options: ResolvedOptions,\n): Promise<string> {\n return generateCollectionsModule(await buildCollectionManifest(root, options));\n}\n\nfunction normalizeCollectionOptions(\n options: CollectionOptions | string | readonly string[],\n): CollectionOptions {\n if (typeof options === \"string\" || Array.isArray(options)) {\n return { source: options };\n }\n return options as CollectionOptions;\n}\n\nfunction normalizeSourcePatterns(source: CollectionOptions[\"source\"]): string[] {\n const values = Array.isArray(source) ? source : [source ?? DEFAULT_COLLECTION_SOURCE];\n return values.map((value) => value || DEFAULT_COLLECTION_SOURCE);\n}\n\nfunction parseCollectionManifest(json: string): CollectionManifest {\n const value = JSON.parse(json) as unknown;\n if (!value || typeof value !== \"object\" || !(\"collections\" in value)) {\n throw new Error(\"[ox-content] Native collection manifest returned an invalid payload.\");\n }\n return value as CollectionManifest;\n}\n\nfunction createNativeTransformOptions(options: ResolvedOptions): NativeTransformOptions {\n return {\n gfm: options.gfm,\n footnotes: options.footnotes,\n taskLists: options.taskLists,\n tables: options.tables,\n strikethrough: options.strikethrough,\n autolinks: options.autolinks,\n autolinkUrls: options.autolinks,\n frontmatter: options.frontmatter,\n tocMaxDepth: options.tocMaxDepth,\n codeAnnotations: options.codeAnnotations?.enabled ?? false,\n codeAnnotationMetaKey: options.codeAnnotations?.metaKey ?? \"annotate\",\n codeAnnotationSyntax: options.codeAnnotations?.notation ?? \"attribute\",\n codeAnnotationDefaultLineNumbers: options.codeAnnotations?.defaultLineNumbers ?? false,\n wikiLinks: options.wikiLinks?.enabled\n ? {\n enabled: true,\n baseUrl: options.wikiLinks.baseUrl,\n }\n : undefined,\n emojiShortcodes: options.emojiShortcodes?.enabled\n ? {\n enabled: true,\n custom: options.emojiShortcodes.custom,\n }\n : undefined,\n attributes: options.attrs?.enabled ? { enabled: true } : undefined,\n badges: options.badges?.enabled ? { enabled: true } : undefined,\n containers: options.containers?.enabled\n ? {\n enabled: true,\n types: options.containers.types,\n }\n : undefined,\n images: options.images?.enabled\n ? {\n enabled: true,\n lazy: options.images.lazy,\n }\n : undefined,\n cjkEmphasis: options.cjkEmphasis ?? false,\n codeImports: options.codeImports?.enabled\n ? {\n enabled: true,\n rootDir: options.codeImports.rootDir,\n }\n : undefined,\n includes: options.includes?.enabled\n ? {\n enabled: true,\n rootDir: options.includes.rootDir,\n }\n : undefined,\n cards: options.cards?.enabled ? { enabled: true } : undefined,\n steps: options.steps?.enabled ? { enabled: true } : undefined,\n fileTree: toJsFileTreeOptions(options.fileTree),\n editThisPage: options.editThisPage?.enabled\n ? {\n enabled: true,\n repoUrl: options.editThisPage.repoUrl,\n branch: options.editThisPage.branch,\n rootDir: options.editThisPage.rootDir,\n label: options.editThisPage.label,\n }\n : undefined,\n math: options.math?.enabled ?? false,\n };\n}\n\nfunction defaultCollections(): CollectionsOptions {\n return {\n [DEFAULT_COLLECTION_NAME]: {\n source: DEFAULT_COLLECTION_SOURCE,\n },\n };\n}\n","/** RSS / Atom / JSON Feed string bodies used by `feeds.ts`. */\n\nexport interface ParsedDate {\n unix: number;\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n}\n\nexport interface FeedDocument {\n siteName: string;\n siteDescription?: string;\n home: string;\n atomUrl: string;\n jsonUrl: string;\n}\n\nexport interface FeedEntry {\n title: string;\n description?: string;\n loc: string;\n date?: ParsedDate;\n}\n\nexport function generateRss(doc: FeedDocument, items: readonly FeedEntry[]): string {\n let xml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<rss version=\"2.0\">\\n <channel>\\n <title>';\n xml += escapeXml(doc.siteName);\n xml += \"</title>\\n <link>\";\n xml += escapeXml(doc.home);\n xml += \"</link>\\n <description>\";\n xml += escapeXml(channelDescription(doc));\n xml += \"</description>\\n\";\n for (const item of items) {\n xml += \" <item>\\n <title>\";\n xml += escapeXml(item.title);\n xml += \"</title>\\n <link>\";\n xml += escapeXml(item.loc);\n xml += \"</link>\\n <guid>\";\n xml += escapeXml(item.loc);\n xml += \"</guid>\\n\";\n if (item.description) {\n xml += \" <description>\";\n xml += escapeXml(item.description);\n xml += \"</description>\\n\";\n }\n if (item.date) {\n xml += ` <pubDate>${formatRfc822(item.date)}</pubDate>\\n`;\n }\n xml += \" </item>\\n\";\n }\n xml += \" </channel>\\n</rss>\\n\";\n return xml;\n}\n\nexport function generateAtom(doc: FeedDocument, items: readonly FeedEntry[]): string {\n const updated = items[0]?.date ? formatRfc3339(items[0].date) : \"1970-01-01T00:00:00Z\";\n let xml =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\\n <title>';\n xml += escapeXml(doc.siteName);\n xml += '</title>\\n <link href=\"';\n xml += escapeXml(doc.atomUrl);\n xml += '\" rel=\"self\"/>\\n <link href=\"';\n xml += escapeXml(doc.home);\n xml += '\" rel=\"alternate\"/>\\n <id>';\n xml += escapeXml(doc.home);\n xml += `</id>\\n <updated>${updated}</updated>\\n`;\n if (doc.siteDescription?.trim()) {\n xml += \" <subtitle>\";\n xml += escapeXml(doc.siteDescription);\n xml += \"</subtitle>\\n\";\n }\n for (const item of items) {\n xml += \" <entry>\\n <title>\";\n xml += escapeXml(item.title);\n xml += '</title>\\n <link href=\"';\n xml += escapeXml(item.loc);\n xml += '\"/>\\n <id>';\n xml += escapeXml(item.loc);\n xml += `</id>\\n <updated>${item.date ? formatRfc3339(item.date) : updated}</updated>\\n`;\n if (item.description) {\n xml += \" <summary>\";\n xml += escapeXml(item.description);\n xml += \"</summary>\\n\";\n }\n xml += \" </entry>\\n\";\n }\n xml += \"</feed>\\n\";\n return xml;\n}\n\nexport function generateJson(doc: FeedDocument, items: readonly FeedEntry[]): string {\n let json = '{\\n \"version\": \"https://jsonfeed.org/version/1.1\",\\n \"title\": ';\n json += jsonString(doc.siteName);\n json += ',\\n \"home_page_url\": ';\n json += jsonString(doc.home);\n json += ',\\n \"feed_url\": ';\n json += jsonString(doc.jsonUrl);\n if (doc.siteDescription?.trim()) {\n json += ',\\n \"description\": ';\n json += jsonString(doc.siteDescription);\n }\n json += ',\\n \"items\": [';\n items.forEach((item, index) => {\n if (index > 0) {\n json += \",\";\n }\n json += '\\n {\\n \"id\": ';\n json += jsonString(item.loc);\n json += ',\\n \"url\": ';\n json += jsonString(item.loc);\n json += ',\\n \"title\": ';\n json += jsonString(item.title);\n if (item.description) {\n json += ',\\n \"content_text\": ';\n json += jsonString(item.description);\n }\n if (item.date) {\n json += ',\\n \"date_published\": ';\n json += jsonString(formatRfc3339(item.date));\n }\n json += \"\\n }\";\n });\n json += \"\\n ]\\n}\\n\";\n return json;\n}\n\nexport function parseDate(value: string | undefined): ParsedDate | undefined {\n if (!value) {\n return undefined;\n }\n if (/^\\d+$/.test(value)) {\n const n = Number(value);\n return unixToDate(value.length >= 13 ? Math.trunc(n / 1000) : n);\n }\n return parseCivilDate(value);\n}\n\nfunction channelDescription(doc: FeedDocument): string {\n const description = doc.siteDescription?.trim();\n return description ? description : doc.siteName;\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n\nfunction jsonString(value: string): string {\n let escaped = '\"';\n for (const ch of value) {\n const code = ch.codePointAt(0) ?? 0;\n if (ch === '\"') {\n escaped += '\\\\\"';\n } else if (ch === \"\\\\\") {\n escaped += \"\\\\\\\\\";\n } else if (ch === \"\\n\") {\n escaped += \"\\\\n\";\n } else if (ch === \"\\r\") {\n escaped += \"\\\\r\";\n } else if (ch === \"\\t\") {\n escaped += \"\\\\t\";\n } else if (ch === \"<\") {\n escaped += \"\\\\u003c\";\n } else if (ch === \">\") {\n escaped += \"\\\\u003e\";\n } else if (ch === \"&\") {\n escaped += \"\\\\u0026\";\n } else if (code < 0x20) {\n escaped += `\\\\u${code.toString(16).padStart(4, \"0\")}`;\n } else {\n escaped += ch;\n }\n }\n escaped += '\"';\n return escaped;\n}\n\nfunction formatRfc3339(date: ParsedDate): string {\n return `${pad(date.year, 4)}-${pad(date.month, 2)}-${pad(date.day, 2)}T${pad(date.hour, 2)}:${pad(date.minute, 2)}:${pad(date.second, 2)}Z`;\n}\n\nfunction formatRfc822(date: ParsedDate): string {\n const weekdays = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const months = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n ];\n return `${weekdays[weekdayUtc(date.year, date.month, date.day)]}, ${pad(date.day, 2)} ${months[date.month - 1]} ${pad(date.year, 4)} ${pad(date.hour, 2)}:${pad(date.minute, 2)}:${pad(date.second, 2)} +0000`;\n}\n\nfunction pad(value: number, width: number): string {\n return String(value).padStart(width, \"0\");\n}\n\nfunction parseCivilDate(value: string): ParsedDate | undefined {\n if (value.length < 10 || value[4] !== \"-\" || value[7] !== \"-\") {\n return undefined;\n }\n const year = Number(value.slice(0, 4));\n const month = Number(value.slice(5, 7));\n const day = Number(value.slice(8, 10));\n let hour = 0;\n let minute = 0;\n let second = 0;\n let offset = 0;\n if (value.length > 10) {\n const rest = value.slice(10);\n const time = rest.startsWith(\"T\") || rest.startsWith(\" \") ? rest.slice(1) : \"\";\n if (time.length < 8 || time[2] !== \":\" || time[5] !== \":\") {\n return undefined;\n }\n hour = Number(time.slice(0, 2));\n minute = Number(time.slice(3, 5));\n second = Number(time.slice(6, 8));\n const parsedOffset = parseOffset(timezoneSuffix(time));\n if (parsedOffset == null) {\n return undefined;\n }\n offset = parsedOffset;\n }\n const unix = civilToUnix(year, month, day, hour, minute, second);\n return unix == null ? undefined : unixToDate(unix - offset);\n}\n\nfunction timezoneSuffix(rest: string): string {\n const afterTime = rest.slice(8);\n if (afterTime.startsWith(\".\")) {\n const index = afterTime.search(/[Z+-]/);\n return index === -1 ? \"\" : afterTime.slice(index);\n }\n return afterTime;\n}\n\nfunction parseOffset(tz: string): number | undefined {\n if (!tz || tz === \"Z\") {\n return 0;\n }\n if (tz.length < 6) {\n return undefined;\n }\n const sign = tz[0] === \"+\" ? 1 : tz[0] === \"-\" ? -1 : 0;\n if (!sign) {\n return undefined;\n }\n return sign * (Number(tz.slice(1, 3)) * 3600 + Number(tz.slice(4, 6)) * 60);\n}\n\nfunction civilToUnix(\n year: number,\n month: number,\n day: number,\n hour: number,\n minute: number,\n second: number,\n): number | undefined {\n if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 60) {\n return undefined;\n }\n let y = year;\n if (month <= 2) {\n y -= 1;\n }\n const era = Math.trunc((y >= 0 ? y : y - 399) / 400);\n const yoe = y - era * 400;\n const shifted = month + (month > 2 ? -3 : 9);\n const doy = Math.trunc((153 * shifted + 2) / 5) + day - 1;\n const doe = yoe * 365 + Math.trunc(yoe / 4) - Math.trunc(yoe / 100) + doy;\n const days = era * 146097 + doe - 719468;\n return days * 86400 + hour * 3600 + minute * 60 + second;\n}\n\nfunction unixToDate(unix: number): ParsedDate | undefined {\n const days = Math.floor(unix / 86400);\n const tod = ((unix % 86400) + 86400) % 86400;\n const z = days + 719468;\n const era = Math.trunc((z >= 0 ? z : z - 146096) / 146097);\n const doe = z - era * 146097;\n const yoe = Math.trunc(\n (doe - Math.trunc(doe / 1460) + Math.trunc(doe / 36524) - Math.trunc(doe / 146096)) / 365,\n );\n const year = yoe + era * 400;\n const doy = doe - (365 * yoe + Math.trunc(yoe / 4) - Math.trunc(yoe / 100));\n const mp = Math.trunc((5 * doy + 2) / 153);\n const day = doy - Math.trunc((153 * mp + 2) / 5) + 1;\n const month = mp < 10 ? mp + 3 : mp - 9;\n return {\n unix,\n year: year + (month <= 2 ? 1 : 0),\n month,\n day,\n hour: Math.trunc(tod / 3600),\n minute: Math.trunc((tod % 3600) / 60),\n second: tod % 60,\n };\n}\n\nfunction weekdayUtc(year: number, month: number, day: number): number {\n const table = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];\n const y = month < 3 ? year - 1 : year;\n return (\n (((y + Math.trunc(y / 4) - Math.trunc(y / 100) + Math.trunc(y / 400) + table[month - 1] + day) %\n 7) +\n 7) %\n 7\n );\n}\n","/**\n * Opt-in RSS / Atom / JSON Feed helpers.\n *\n * String bodies follow `ox_content_ssg::generate_feeds`. The Vite plugin\n * writes those files during SSG without adding a NAPI surface.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { generateAtom, generateJson, generateRss, parseDate } from \"./feed-format\";\nimport type { FeedDocument, FeedEntry } from \"./feed-format\";\nimport { classifyPublishState } from \"./publish-state\";\nimport type {\n FeedFormat,\n FeedsOptions,\n ResolvedFeedsOptions,\n ResolvedPublishStateOptions,\n} from \"./types\";\n\nconst MISSING_SITE_URL =\n \"[ox-content] feeds is enabled but ssg.siteUrl is not set; RSS, Atom, and JSON feeds were not written\";\n\nconst DEFAULT_FORMATS: FeedFormat[] = [\"rss\", \"atom\", \"json\"];\nconst DEFAULT_LIMIT = 20;\nconst DEFAULT_PATH = \"/\";\n\n/** One collection entry considered for a feed. */\nexport interface FeedItemInput {\n title?: string;\n description?: string;\n path?: string;\n loc?: string;\n date?: unknown;\n lastUpdated?: unknown;\n draft?: unknown;\n unlisted?: unknown;\n frontmatter?: Record<string, unknown>;\n}\n\n/** Inputs for rendering feed bodies. */\nexport interface FeedsRenderInput {\n options?: ResolvedFeedsOptions | null;\n siteUrl?: string;\n siteName?: string;\n siteDescription?: string;\n base?: string;\n collections?: Record<string, readonly FeedItemInput[]>;\n collectionNames?: readonly string[];\n items?: readonly FeedItemInput[];\n publishState?: ResolvedPublishStateOptions;\n}\n\n/** Rendered feed bodies, or a skip warning. */\nexport interface FeedsRenderResult {\n rssXml?: string;\n atomXml?: string;\n jsonFeed?: string;\n warning?: string;\n}\n\n/** Inputs for writing feeds next to generated HTML. */\nexport interface WriteFeedFilesInput extends FeedsRenderInput {\n outDir: string;\n base: string;\n}\n\n/**\n * Resolves `feeds` with defaults.\n *\n * `false` / omitted stays off. `true` enables all three formats with\n * collection `content` (or the first configured collection) and limit 20.\n * An object enables the feature and overrides only the fields the site set.\n */\nexport function resolveFeedsOptions(\n value: boolean | FeedsOptions | undefined,\n): ResolvedFeedsOptions {\n if (!value) {\n return {\n enabled: false,\n formats: [...DEFAULT_FORMATS],\n limit: DEFAULT_LIMIT,\n path: DEFAULT_PATH,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n formats: [...DEFAULT_FORMATS],\n limit: DEFAULT_LIMIT,\n path: DEFAULT_PATH,\n };\n }\n return {\n enabled: true,\n formats: normalizeFormats(value.formats),\n collection: value.collection,\n limit: value.limit ?? DEFAULT_LIMIT,\n path: value.path ?? DEFAULT_PATH,\n };\n}\n\n/** Picks `content`, else the first configured collection name. */\nexport function resolveFeedCollectionName(\n requested: string | undefined,\n collectionNames: readonly string[],\n): string | undefined {\n if (requested) {\n return requested;\n }\n if (collectionNames.includes(\"content\")) {\n return \"content\";\n }\n return collectionNames[0];\n}\n\n/** Builds RSS / Atom / JSON Feed bodies without writing files. */\nexport function generateFeeds(input: FeedsRenderInput): FeedsRenderResult {\n if (!input.options?.enabled) {\n return {};\n }\n if (!hasSiteUrl(input.siteUrl)) {\n return { warning: MISSING_SITE_URL };\n }\n\n const published = publishedItems(input);\n const doc = feedDocument(input);\n const result: FeedsRenderResult = {};\n if (input.options.formats.includes(\"rss\")) {\n result.rssXml = generateRss(doc, published);\n }\n if (input.options.formats.includes(\"atom\")) {\n result.atomXml = generateAtom(doc, published);\n }\n if (input.options.formats.includes(\"json\")) {\n result.jsonFeed = generateJson(doc, published);\n }\n return result;\n}\n\n/** Writes enabled feed files into `outDir`. */\nexport async function writeFeedFiles(\n input: WriteFeedFilesInput,\n): Promise<{ files: string[]; warning?: string }> {\n const generated = generateFeeds(input);\n if (generated.warning) {\n return { files: [], warning: generated.warning };\n }\n\n const outputs: Array<[string, string]> = [\n [generated.rssXml, \"feed.xml\"],\n [generated.atomXml, \"atom.xml\"],\n [generated.jsonFeed, \"feed.json\"],\n ].filter((entry): entry is [string, string] => entry[0] != null);\n if (outputs.length === 0) {\n return { files: [] };\n }\n\n const dest = outputDir(input.outDir, input.options?.path ?? DEFAULT_PATH);\n await fs.mkdir(dest, { recursive: true });\n const files: string[] = [];\n for (const [body, name] of outputs) {\n const outputPath = path.join(dest, name);\n await fs.writeFile(outputPath, body, \"utf8\");\n files.push(outputPath);\n }\n return { files };\n}\n\nfunction normalizeFormats(formats: FeedFormat[] | undefined): FeedFormat[] {\n if (!formats) {\n return [...DEFAULT_FORMATS];\n }\n const seen = new Set<FeedFormat>();\n const resolved: FeedFormat[] = [];\n for (const format of formats) {\n if ((format === \"rss\" || format === \"atom\" || format === \"json\") && !seen.has(format)) {\n seen.add(format);\n resolved.push(format);\n }\n }\n return resolved;\n}\n\nfunction hasSiteUrl(siteUrl: string | undefined): boolean {\n return Boolean(siteUrl && siteUrl.trim());\n}\n\nfunction homePageUrl(siteUrl: string | undefined, base = \"/\"): string {\n const origin = (siteUrl ?? \"\").trim().replace(/\\/+$/, \"\");\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return `${origin}${prefix}`;\n}\n\nfunction feedDocument(input: FeedsRenderInput): FeedDocument {\n const home = homePageUrl(input.siteUrl, input.base);\n const dir = (input.options?.path ?? DEFAULT_PATH).replace(/^\\/+|\\/+$/g, \"\");\n const prefix = dir ? `${home}${dir}/` : home;\n return {\n siteName: input.siteName ?? \"\",\n siteDescription: input.siteDescription,\n home,\n atomUrl: `${prefix}atom.xml`,\n jsonUrl: `${prefix}feed.json`,\n };\n}\n\nfunction outputDir(outDir: string, feedPath: string): string {\n const relative = feedPath.replace(/^\\/+|\\/+$/g, \"\");\n return relative ? path.join(outDir, relative) : outDir;\n}\n\nfunction rawItems(input: FeedsRenderInput): readonly FeedItemInput[] {\n if (input.items) {\n return input.items;\n }\n const names = input.collectionNames ?? Object.keys(input.collections ?? {});\n const name = resolveFeedCollectionName(input.options?.collection, names);\n return name ? (input.collections?.[name] ?? []) : [];\n}\n\nfunction publishedItems(input: FeedsRenderInput): FeedEntry[] {\n const published = rawItems(input)\n .filter((item) => !isExcludedFromFeed(item, input.publishState))\n .map((item) => normalizeItem(item, input))\n .filter((item) => item.loc.length > 0);\n published.sort((left, right) => {\n const dateCmp =\n (right.date?.unix ?? Number.NEGATIVE_INFINITY) -\n (left.date?.unix ?? Number.NEGATIVE_INFINITY);\n return dateCmp !== 0 ? dateCmp : left.loc < right.loc ? -1 : left.loc > right.loc ? 1 : 0;\n });\n return published.slice(0, input.options?.limit ?? DEFAULT_LIMIT);\n}\n\nfunction isExcludedFromFeed(\n item: FeedItemInput,\n publishState: ResolvedPublishStateOptions | undefined,\n): boolean {\n const frontmatter = item.frontmatter ?? {};\n if (item.draft === true || frontmatter.draft === true) {\n return true;\n }\n if (item.unlisted === true || frontmatter.unlisted === true) {\n return true;\n }\n if (!publishState?.enabled) {\n return false;\n }\n return !classifyPublishState(\n {\n ...frontmatter,\n ...(item.draft === true ? { draft: true } : {}),\n ...(item.unlisted === true ? { unlisted: true } : {}),\n },\n publishState,\n ).listed;\n}\n\nfunction normalizeItem(item: FeedItemInput, input: FeedsRenderInput): FeedEntry {\n return {\n title: item.title ?? \"\",\n description: typeof item.description === \"string\" ? item.description : undefined,\n loc: item.loc || itemLoc(input, item),\n date:\n parseDate(dateField(item.date ?? item.frontmatter?.date)) ??\n parseDate(dateField(item.lastUpdated ?? item.frontmatter?.lastUpdated)),\n };\n}\n\nfunction itemLoc(input: FeedsRenderInput, item: FeedItemInput): string {\n const home = homePageUrl(input.siteUrl, input.base);\n const urlPath = (item.path ?? \"\").replace(/^\\/+|\\/+$/g, \"\");\n return urlPath ? `${home}${urlPath}/` : home;\n}\n\nfunction dateField(value: unknown): string | undefined {\n if (typeof value === \"string\" && value.trim()) {\n return value.trim();\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n if (value instanceof Date && !Number.isNaN(value.getTime())) {\n return value.toISOString();\n }\n return undefined;\n}\n","/**\n * Opt-in web app manifest and conservative service worker.\n *\n * The Vite plugin writes those files during SSG without adding a NAPI surface.\n * Enabling `offline` injects a tiny client script that registers `sw.js`.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { PwaOptions, ResolvedPwaOptions } from \"./types\";\n\nconst MISSING_SITE_URL =\n \"[ox-content] pwa is enabled but ssg.siteUrl is not set; manifest.webmanifest and sw.js were not written\";\n\nconst DEFAULT_THEME_COLOR = \"#000000\";\nconst DEFAULT_BACKGROUND_COLOR = \"#ffffff\";\nconst MANIFEST_NAME = \"manifest.webmanifest\";\nconst SERVICE_WORKER_NAME = \"sw.js\";\n\n/** Inputs for rendering PWA file bodies. */\nexport interface PwaRenderInput {\n options?: ResolvedPwaOptions | null;\n siteUrl?: string;\n siteName?: string;\n base?: string;\n}\n\n/** Rendered PWA bodies, or a skip warning. */\nexport interface PwaRenderResult {\n manifest?: string;\n serviceWorker?: string;\n warning?: string;\n}\n\n/** Inputs for writing PWA files next to generated HTML. */\nexport interface WritePwaFilesInput extends PwaRenderInput {\n outDir: string;\n base: string;\n}\n\n/**\n * Resolves `pwa` with defaults.\n *\n * `false` / omitted stays off. `true` enables the manifest and offline\n * service worker. An object enables the feature and overrides only the\n * fields the site set.\n */\nexport function resolvePwaOptions(value: boolean | PwaOptions | undefined): ResolvedPwaOptions {\n if (!value) {\n return { enabled: false, offline: true };\n }\n if (value === true) {\n return { enabled: true, offline: true };\n }\n return {\n enabled: true,\n offline: value.offline ?? true,\n name: value.name,\n shortName: value.shortName,\n themeColor: value.themeColor,\n backgroundColor: value.backgroundColor,\n startUrl: value.startUrl,\n };\n}\n\n/** Builds manifest / service-worker bodies without writing files. */\nexport function generatePwa(input: PwaRenderInput): PwaRenderResult {\n if (!input.options?.enabled) {\n return {};\n }\n if (!hasSiteUrl(input.siteUrl)) {\n return { warning: MISSING_SITE_URL };\n }\n\n const base = normalizeBase(input.base);\n const name = sanitizeManifestText(input.options.name ?? input.siteName ?? \"\");\n const shortName = sanitizeManifestText(input.options.shortName ?? name);\n const startUrl = sanitizeStartUrl(input.options.startUrl, base);\n const themeColor = sanitizeColor(input.options.themeColor, DEFAULT_THEME_COLOR);\n const backgroundColor = sanitizeColor(input.options.backgroundColor, DEFAULT_BACKGROUND_COLOR);\n\n const result: PwaRenderResult = {\n manifest: `${escapeJsonScript(\n JSON.stringify(\n {\n name,\n short_name: shortName,\n start_url: startUrl,\n scope: base,\n display: \"standalone\",\n background_color: backgroundColor,\n theme_color: themeColor,\n },\n null,\n 2,\n ),\n )}\\n`,\n };\n if (input.options.offline) {\n result.serviceWorker = generateServiceWorker(base);\n }\n return result;\n}\n\n/** Writes enabled PWA files into `outDir`. */\nexport async function writePwaFiles(\n input: WritePwaFilesInput,\n): Promise<{ files: string[]; warning?: string }> {\n const generated = generatePwa(input);\n if (generated.warning) {\n return { files: [], warning: generated.warning };\n }\n\n const outputs: Array<[string, string]> = [\n [generated.manifest, MANIFEST_NAME],\n [generated.serviceWorker, SERVICE_WORKER_NAME],\n ].filter((entry): entry is [string, string] => entry[0] != null);\n if (outputs.length === 0) {\n return { files: [] };\n }\n\n await fs.mkdir(input.outDir, { recursive: true });\n const files: string[] = [];\n for (const [body, name] of outputs) {\n const outputPath = path.join(input.outDir, name);\n await fs.writeFile(outputPath, body, \"utf8\");\n files.push(outputPath);\n }\n return { files };\n}\n\n/**\n * Injects `rel=manifest` (and the service-worker register script when offline)\n * into a themed HTML document. Bare / fragment HTML is left unchanged.\n */\nexport function injectPwaPageTags(\n html: string,\n input: { options?: ResolvedPwaOptions | null; base?: string },\n): string {\n if (!input.options?.enabled || !isThemedDocument(html)) {\n return html;\n }\n\n const base = normalizeBase(input.base);\n const manifestHref = escapeAttribute(`${base}${MANIFEST_NAME}`);\n const themeColor = sanitizeColor(input.options.themeColor, DEFAULT_THEME_COLOR);\n const headTags = [\n `<link rel=\"manifest\" href=\"${manifestHref}\">`,\n `<meta name=\"theme-color\" content=\"${escapeAttribute(themeColor)}\">`,\n ].join(\"\\n \");\n\n let next = insertBeforeTag(html, \"</head>\", ` ${headTags}\\n`);\n if (input.options.offline) {\n const swHref = JSON.stringify(`${base}${SERVICE_WORKER_NAME}`);\n const script = `<script>if(\"serviceWorker\"in navigator)navigator.serviceWorker.register(${swHref})</script>`;\n next = insertBeforeTag(next, \"</body>\", ` ${script}\\n`);\n }\n return next;\n}\n\nfunction generateServiceWorker(base: string): string {\n const assetPrefix = JSON.stringify(`${base}assets/`);\n return `/* ox-content PWA service worker */\nconst CACHE = \"ox-content-pwa-v1\";\nconst ASSET_PREFIX = ${assetPrefix};\n\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(self.skipWaiting());\n});\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil(self.clients.claim());\n});\n\nself.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n const url = new URL(request.url);\n if (url.origin !== self.location.origin) return;\n\n if (isHashedAsset(url.pathname)) {\n event.respondWith(cacheFirst(request));\n return;\n }\n\n if (isHtmlPage(request)) {\n event.respondWith(networkFirst(request));\n }\n});\n\nfunction isHashedAsset(pathname) {\n if (!pathname.startsWith(ASSET_PREFIX)) return false;\n return /-[0-9a-f]{8,}\\\\.[a-z0-9]+$/i.test(pathname);\n}\n\nfunction isHtmlPage(request) {\n if (request.mode === \"navigate\") return true;\n const accept = request.headers.get(\"accept\") || \"\";\n return accept.includes(\"text/html\");\n}\n\nasync function cacheFirst(request) {\n const cache = await caches.open(CACHE);\n const cached = await cache.match(request);\n if (cached) return cached;\n const response = await fetch(request);\n if (response.ok) cache.put(request, response.clone());\n return response;\n}\n\nasync function networkFirst(request) {\n const cache = await caches.open(CACHE);\n try {\n const response = await fetch(request);\n if (response.ok) cache.put(request, response.clone());\n return response;\n } catch (error) {\n const cached = await cache.match(request);\n if (cached) return cached;\n throw error;\n }\n}\n`;\n}\n\nfunction hasSiteUrl(siteUrl: string | undefined): boolean {\n return Boolean(siteUrl && siteUrl.trim());\n}\n\nfunction normalizeBase(base: string | undefined): string {\n if (!base || base === \"/\") {\n return \"/\";\n }\n return base.endsWith(\"/\") ? base : `${base}/`;\n}\n\nfunction sanitizeManifestText(value: string): string {\n return value.split(/\\s+/u).filter(Boolean).join(\" \");\n}\n\nfunction sanitizeColor(value: string | undefined, fallback: string): string {\n if (!value) {\n return fallback;\n }\n const trimmed = value.trim();\n if (/^#[0-9A-Fa-f]{3,8}$/.test(trimmed)) {\n return trimmed;\n }\n if (/^[a-zA-Z][a-zA-Z0-9-]{0,31}$/.test(trimmed)) {\n return trimmed;\n }\n return fallback;\n}\n\nfunction sanitizeStartUrl(value: string | undefined, base: string): string {\n if (!value) {\n return base;\n }\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"/\") || trimmed.startsWith(\"//\")) {\n return base;\n }\n if (/[\\n\\r\\t<>\"'`]/.test(trimmed)) {\n return base;\n }\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {\n return base;\n }\n return trimmed;\n}\n\nfunction isThemedDocument(html: string): boolean {\n return /<\\/head>/i.test(html) && /<\\/body>/i.test(html);\n}\n\nfunction insertBeforeTag(html: string, tag: string, snippet: string): string {\n const index = html.toLowerCase().lastIndexOf(tag.toLowerCase());\n if (index === -1) {\n return html;\n }\n return `${html.slice(0, index)}${snippet}${html.slice(index)}`;\n}\n\nfunction escapeJsonScript(value: string): string {\n return value.replace(/[<>]/g, (ch) => (ch === \"<\" ? \"\\\\u003c\" : \"\\\\u003e\"));\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/[&<>\"']/g, (ch) => {\n switch (ch) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n","/**\n * Escaped taxonomy HTML and confined output paths.\n */\n\nimport * as path from \"node:path\";\n\n/** One built page considered for terms and related lists. */\nexport interface TaxonomySourcePage {\n title: string;\n frontmatter: Record<string, unknown>;\n transformedHtml: string;\n inputPath?: string;\n routePaths: { href: string };\n}\n\nexport interface TermBucket {\n label: string;\n slug: string;\n pages: TaxonomySourcePage[];\n}\n\nexport function relatedMarkup(pages: readonly TaxonomySourcePage[]): string {\n const items = pages.map((page) => listItem(page.routePaths.href, page.title)).join(\"\");\n return `<nav class=\"ox-related\" aria-label=\"Related pages\"><h2>Related pages</h2><ul>${items}</ul></nav>`;\n}\n\nexport function listPageContent(\n terms: readonly TermBucket[],\n base: string,\n urlName: string,\n): string {\n const items = terms\n .map((term) => listItem(siteHref(base, urlName, term.slug), term.label))\n .join(\"\");\n return `<h1>${escapeHtml(displayTaxonomyName(urlName))}</h1><ul class=\"ox-taxonomy\">${items}</ul>`;\n}\n\nexport function termPageContent(term: TermBucket): string {\n const pages = [...term.pages].sort((left, right) => {\n const titleCmp = left.title.localeCompare(right.title);\n return titleCmp !== 0 ? titleCmp : left.routePaths.href.localeCompare(right.routePaths.href);\n });\n const items = pages.map((page) => listItem(page.routePaths.href, page.title)).join(\"\");\n return `<h1>${escapeHtml(term.label)}</h1><ul class=\"ox-taxonomy-term\">${items}</ul>`;\n}\n\nexport function displayTaxonomyName(name: string): string {\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\nexport function siteHref(base: string, ...segments: string[]): string {\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n const rest = segments.filter(Boolean).join(\"/\");\n return rest ? `${prefix}${rest}/` : prefix;\n}\n\nexport function containedPath(outDir: string, ...segments: string[]): string | undefined {\n const root = path.resolve(outDir);\n const resolved = path.resolve(root, ...segments);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved === root || !resolved.startsWith(prefix)) {\n return undefined;\n }\n return resolved;\n}\n\nfunction listItem(href: string, label: string): string {\n return `<li><a href=\"${escapeHtml(href)}\">${escapeHtml(label)}</a></li>`;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n","/**\n * Opt-in taxonomy term pages and related-page lists.\n *\n * Resolution and HTML live here. The Vite plugin injects related markup into\n * page content, then writes themed list and per-term pages during SSG.\n */\n\nimport {\n containedPath,\n displayTaxonomyName,\n listPageContent,\n relatedMarkup,\n siteHref,\n termPageContent,\n type TaxonomySourcePage,\n type TermBucket,\n} from \"./taxonomies-html\";\nimport type { ResolvedTaxonomiesOptions, TaxonomiesOptions } from \"./types\";\n\nexport type { TaxonomySourcePage } from \"./taxonomies-html\";\n\nconst DEFAULT_TAXONOMIES = [\"tags\", \"categories\"];\nconst DEFAULT_RELATED_LIMIT = 5;\nconst HOSTILE_TERM = /^(?:javascript|data):/i;\n\n/** Synthetic page passed back to `generateHtmlPage`. */\nexport interface TaxonomyGeneratedPage {\n title: string;\n content: string;\n outputPath: string;\n urlPath: string;\n href: string;\n}\n\n/**\n * Resolves `taxonomies` with defaults.\n *\n * `false` / omitted stays off. `true` enables `tags` and `categories` with\n * relatedLimit 5. An object enables the feature and overrides only set fields.\n */\nexport function resolveTaxonomiesOptions(\n value: boolean | TaxonomiesOptions | undefined,\n): ResolvedTaxonomiesOptions {\n if (!value) {\n return {\n enabled: false,\n taxonomies: [...DEFAULT_TAXONOMIES],\n relatedLimit: DEFAULT_RELATED_LIMIT,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n taxonomies: [...DEFAULT_TAXONOMIES],\n relatedLimit: DEFAULT_RELATED_LIMIT,\n };\n }\n return {\n enabled: true,\n taxonomies: normalizeTaxonomyNames(value.taxonomies),\n relatedLimit: normalizeRelatedLimit(value.relatedLimit),\n };\n}\n\n/**\n * Stable URL slug for a frontmatter term.\n *\n * Returns `undefined` when the value cannot become a safe `[a-z0-9-]` href.\n */\nexport function termSlug(term: string): string | undefined {\n const trimmed = term.trim();\n if (!trimmed || HOSTILE_TERM.test(trimmed) || trimmed.includes(\"..\") || trimmed.includes(\"//\")) {\n return undefined;\n }\n const slug = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug || undefined;\n}\n\n/** Appends related-page HTML to source pages that share a listed term. */\nexport function injectRelatedPages(\n pages: TaxonomySourcePage[],\n listed: readonly TaxonomySourcePage[],\n options?: ResolvedTaxonomiesOptions,\n): void {\n if (!options?.enabled) {\n return;\n }\n const listedKeys = listed.map((page) => pageTermKeys(page, options.taxonomies));\n for (const page of pages) {\n const keys = pageTermKeys(page, options.taxonomies);\n if (keys.size === 0) {\n continue;\n }\n const related = listed\n .map((candidate, index) => ({\n page: candidate,\n score: samePage(page, candidate) ? 0 : sharedCount(keys, listedKeys[index] ?? new Set()),\n }))\n .filter((entry) => entry.score > 0)\n .sort((left, right) => {\n if (left.score !== right.score) {\n return right.score - left.score;\n }\n const titleCmp = left.page.title.localeCompare(right.page.title);\n return titleCmp !== 0\n ? titleCmp\n : left.page.routePaths.href.localeCompare(right.page.routePaths.href);\n })\n .slice(0, options.relatedLimit)\n .map((entry) => entry.page);\n if (related.length === 0) {\n continue;\n }\n page.transformedHtml += relatedMarkup(related);\n }\n}\n\n/** Maps a generated taxonomy page onto the SSG render shape. */\nexport function toTaxonomyProcessResult(page: TaxonomyGeneratedPage): {\n inputPath: string;\n routePaths: {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n };\n transformedHtml: string;\n title: string;\n frontmatter: Record<string, unknown>;\n toc: [];\n} {\n return {\n inputPath: page.outputPath,\n routePaths: {\n outputPath: page.outputPath,\n urlPath: page.urlPath,\n href: page.href,\n ogImagePath: \"\",\n ogImageUrl: \"\",\n },\n transformedHtml: page.content,\n title: page.title,\n frontmatter: {},\n toc: [],\n };\n}\n\n/** Renders themed list and per-term pages and appends them to the build. */\nexport async function appendTaxonomyPages(input: {\n generatedPages: Array<{ inputPath: string; outputPath: string; html: string }>;\n listedPages: readonly TaxonomySourcePage[];\n options?: ResolvedTaxonomiesOptions;\n outDir: string;\n base: string;\n render: (page: TaxonomyGeneratedPage) => Promise<string>;\n errors: string[];\n}): Promise<void> {\n if (!input.options?.enabled) {\n return;\n }\n for (const spec of taxonomyPageSpecs(\n input.listedPages,\n input.options,\n input.outDir,\n input.base,\n )) {\n try {\n input.generatedPages.push({\n inputPath: spec.outputPath,\n outputPath: spec.outputPath,\n html: await input.render(spec),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n input.errors.push(`Failed to generate taxonomy page ${spec.href}: ${message}`);\n }\n }\n}\n\nfunction taxonomyPageSpecs(\n listed: readonly TaxonomySourcePage[],\n options: ResolvedTaxonomiesOptions,\n outDir: string,\n base: string,\n): TaxonomyGeneratedPage[] {\n const pages: TaxonomyGeneratedPage[] = [];\n for (const taxonomy of options.taxonomies) {\n const urlName = taxonomy.toLowerCase();\n const terms = collectTerms(listed, taxonomy);\n const listHref = siteHref(base, urlName);\n const listOutput = containedPath(outDir, urlName, \"index.html\");\n if (listOutput) {\n pages.push({\n title: displayTaxonomyName(urlName),\n content: listPageContent(terms, base, urlName),\n outputPath: listOutput,\n urlPath: urlName,\n href: listHref,\n });\n }\n for (const term of terms) {\n const outputPath = containedPath(outDir, urlName, term.slug, \"index.html\");\n if (!outputPath) {\n continue;\n }\n pages.push({\n title: term.label,\n content: termPageContent(term),\n outputPath,\n urlPath: `${urlName}/${term.slug}`,\n href: siteHref(base, urlName, term.slug),\n });\n }\n }\n return pages;\n}\n\nfunction collectTerms(listed: readonly TaxonomySourcePage[], taxonomy: string): TermBucket[] {\n const buckets = new Map<string, TermBucket>();\n for (const page of listed) {\n for (const label of termsFromValue(page.frontmatter[taxonomy])) {\n const slug = termSlug(label);\n if (!slug) {\n continue;\n }\n const existing = buckets.get(slug);\n if (existing) {\n existing.pages.push(page);\n } else {\n buckets.set(slug, { label, slug, pages: [page] });\n }\n }\n }\n return [...buckets.values()].sort((left, right) => left.label.localeCompare(right.label));\n}\n\nfunction pageTermKeys(page: TaxonomySourcePage, taxonomies: readonly string[]): Set<string> {\n const keys = new Set<string>();\n for (const taxonomy of taxonomies) {\n for (const label of termsFromValue(page.frontmatter[taxonomy])) {\n const slug = termSlug(label);\n if (slug) {\n keys.add(`${taxonomy.toLowerCase()}\\0${slug}`);\n }\n }\n }\n return keys;\n}\n\nfunction termsFromValue(value: unknown): string[] {\n if (typeof value === \"string\") {\n return value.trim() ? [value.trim()] : [];\n }\n if (!Array.isArray(value)) {\n return [];\n }\n return value.flatMap((item) => (typeof item === \"string\" && item.trim() ? [item.trim()] : []));\n}\n\nfunction normalizeTaxonomyNames(names: string[] | undefined): string[] {\n if (!names) {\n return [...DEFAULT_TAXONOMIES];\n }\n const seen = new Set<string>();\n const resolved: string[] = [];\n for (const name of names) {\n if (typeof name !== \"string\") {\n continue;\n }\n const trimmed = name.trim();\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(trimmed)) {\n continue;\n }\n const url = trimmed.toLowerCase();\n if (seen.has(url)) {\n continue;\n }\n seen.add(url);\n resolved.push(trimmed);\n }\n return resolved;\n}\n\nfunction normalizeRelatedLimit(value: number | undefined): number {\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return Math.floor(value);\n }\n return DEFAULT_RELATED_LIMIT;\n}\n\nfunction samePage(left: TaxonomySourcePage, right: TaxonomySourcePage): boolean {\n if (left.inputPath && right.inputPath) {\n return left.inputPath === right.inputPath;\n }\n return left.routePaths.href === right.routePaths.href;\n}\n\nfunction sharedCount(left: Set<string>, right: Set<string>): number {\n let count = 0;\n for (const key of left) {\n if (right.has(key)) {\n count += 1;\n }\n }\n return count;\n}\n","/**\n * Opt-in team / members page helpers.\n *\n * Resolution lives here. Member cards are rendered in Rust\n * (`ox_content_ssg::render_team_page`) when a page has `layout: team`.\n */\n\nimport type { ResolvedTeamOptions, TeamMember, TeamOptions } from \"./types\";\n\n/**\n * Resolves `ssg.team` with defaults.\n *\n * `false` / omitted stays off. `true` enables an empty member list.\n * An object enables the feature and keeps the members the site set.\n */\nexport function resolveTeamOptions(value: boolean | TeamOptions | undefined): ResolvedTeamOptions {\n if (!value) {\n return { enabled: false, members: [] };\n }\n if (value === true) {\n return { enabled: true, members: [] };\n }\n return {\n enabled: true,\n members: normalizeMembers(value.members),\n };\n}\n\nfunction normalizeMembers(members: TeamMember[] | undefined): TeamMember[] {\n if (!Array.isArray(members)) {\n return [];\n }\n return members.flatMap((member) => {\n if (!member || typeof member.name !== \"string\") {\n return [];\n }\n const links = Array.isArray(member.links)\n ? member.links.flatMap((link) => {\n if (!link || typeof link.label !== \"string\" || typeof link.href !== \"string\") {\n return [];\n }\n return [{ label: link.label, href: link.href }];\n })\n : undefined;\n return [\n {\n name: member.name,\n role: typeof member.role === \"string\" ? member.role : undefined,\n avatar: typeof member.avatar === \"string\" ? member.avatar : undefined,\n links,\n },\n ];\n });\n}\n","/**\n * Opt-in git contributor list helpers.\n *\n * Resolution and ignore filtering live here. `git log` is read in Rust\n * (`getGitContributors`) and names are rendered from `PageData.contributors`.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { ContributorsOptions, ResolvedContributors } from \"./types\";\n\nexport interface GitContributor {\n name: string;\n email?: string | null;\n commits?: number | null;\n}\n\nexport interface SsgContributor {\n name: string;\n avatar?: string;\n}\n\n/**\n * Resolves `ssg.contributors` with defaults.\n *\n * `false` / omitted stays off. `true` enables names only.\n * An object enables the feature and keeps `ignore` / `avatars`.\n */\nexport function resolveContributorsOption(\n value: boolean | ContributorsOptions | undefined,\n): ResolvedContributors {\n if (!value) {\n return false;\n }\n if (value === true) {\n return { ignore: [], avatars: false };\n }\n return {\n ignore: Array.isArray(value.ignore)\n ? value.ignore.filter((entry): entry is string => typeof entry === \"string\")\n : [],\n avatars: value.avatars === true,\n };\n}\n\nexport function filterGitContributors(\n contributors: GitContributor[],\n ignore: string[],\n): GitContributor[] {\n if (ignore.length === 0) {\n return contributors.filter((contributor) => contributor.name.trim());\n }\n const needles = new Set(ignore.map((entry) => entry.toLowerCase()));\n return contributors.filter((contributor) => {\n const name = contributor.name.trim();\n if (!name) {\n return false;\n }\n if (needles.has(name.toLowerCase())) {\n return false;\n }\n const email = contributor.email?.trim().toLowerCase();\n return !email || !needles.has(email);\n });\n}\n\nexport function gravatarAvatar(email: string): string {\n const hash = createHash(\"md5\").update(email.trim().toLowerCase()).digest(\"hex\");\n return `https://www.gravatar.com/avatar/${hash}?d=mp&s=40`;\n}\n\nexport function applyContributorOptions(\n raw: GitContributor[],\n option: Exclude<ResolvedContributors, false>,\n): SsgContributor[] {\n return filterGitContributors(raw, option.ignore).map((contributor) => ({\n name: contributor.name.trim(),\n avatar:\n option.avatars && contributor.email?.trim() ? gravatarAvatar(contributor.email) : undefined,\n }));\n}\n","/**\n * Blog option resolution.\n */\n\nimport type { BlogAuthor, BlogOptions, ResolvedBlogOptions } from \"./types\";\n\nconst DEFAULT_PAGE_SIZE = 10;\n\nexport function resolveBlogOptions(value: boolean | BlogOptions | undefined): ResolvedBlogOptions {\n if (!value) {\n return {\n enabled: false,\n authors: {},\n pageSize: DEFAULT_PAGE_SIZE,\n };\n }\n if (value === true) {\n return {\n enabled: true,\n authors: {},\n pageSize: DEFAULT_PAGE_SIZE,\n };\n }\n return {\n enabled: true,\n collection: value.collection,\n authors: normalizeAuthors(value.authors),\n pageSize: normalizePageSize(value.pageSize),\n };\n}\n\n/**\n * Picks a collection named `blog`, else the only configured collection.\n *\n * An explicit name always wins. Several collections and no `blog` name\n * require `blog.collection`.\n */\nexport function resolveBlogCollectionName(\n requested: string | undefined,\n collectionNames: readonly string[],\n): string | undefined {\n if (requested) {\n return requested;\n }\n if (collectionNames.includes(\"blog\")) {\n return \"blog\";\n }\n if (collectionNames.length === 1) {\n return collectionNames[0];\n }\n return undefined;\n}\n\nfunction normalizeAuthors(authors: BlogOptions[\"authors\"]): Record<string, BlogAuthor> {\n if (!authors || typeof authors !== \"object\") {\n return {};\n }\n const resolved: Record<string, BlogAuthor> = {};\n for (const [key, value] of Object.entries(authors)) {\n if (!value || typeof value.name !== \"string\") {\n continue;\n }\n resolved[key] = {\n name: value.name,\n bio: typeof value.bio === \"string\" ? value.bio : undefined,\n url: typeof value.url === \"string\" ? value.url : undefined,\n };\n }\n return resolved;\n}\n\nfunction normalizePageSize(value: number | undefined): number {\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 1) {\n return Math.floor(value);\n }\n return DEFAULT_PAGE_SIZE;\n}\n","/**\n * Deterministic blog reading-time estimates.\n */\n\nconst LATIN_WORDS_PER_MINUTE = 200;\nconst CJK_CHARS_PER_MINUTE = 500;\n\nexport function readingTimeMinutes(markdown: string): number {\n const body = stripInlineCode(stripFences(stripFrontmatter(markdown)));\n let latin = 0;\n let cjk = 0;\n let latinRun = false;\n for (const char of body) {\n const code = char.codePointAt(0) ?? 0;\n if (isCjkCodePoint(code)) {\n cjk += 1;\n latinRun = false;\n continue;\n }\n if (isLatinWordChar(code)) {\n if (!latinRun) {\n latin += 1;\n latinRun = true;\n }\n continue;\n }\n if (char === \"'\" || char === \"\\u2019\") {\n continue;\n }\n latinRun = false;\n }\n if (latin === 0 && cjk === 0) {\n return 0;\n }\n return Math.max(1, Math.ceil(latin / LATIN_WORDS_PER_MINUTE + cjk / CJK_CHARS_PER_MINUTE));\n}\n\nfunction stripFrontmatter(markdown: string): string {\n if (!markdown.startsWith(\"---\")) {\n return markdown;\n }\n const match = markdown.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/);\n return match ? markdown.slice(match[0].length) : markdown;\n}\n\nfunction stripFences(text: string): string {\n return text.replace(/```[\\s\\S]*?(?:```|$)/g, \" \");\n}\n\nfunction stripInlineCode(text: string): string {\n return text.replace(/`[^`\\n]*`/g, \" \");\n}\n\nfunction isCjkCodePoint(code: number): boolean {\n return (\n (code >= 0x3040 && code <= 0x30ff) ||\n (code >= 0x31f0 && code <= 0x31ff) ||\n (code >= 0x3400 && code <= 0x4dbf) ||\n (code >= 0x4e00 && code <= 0x9fff) ||\n (code >= 0xf900 && code <= 0xfaff) ||\n (code >= 0xac00 && code <= 0xd7af) ||\n (code >= 0x1100 && code <= 0x11ff)\n );\n}\n\nfunction isLatinWordChar(code: number): boolean {\n return (\n (code >= 0x30 && code <= 0x39) ||\n (code >= 0x41 && code <= 0x5a) ||\n (code >= 0x61 && code <= 0x7a)\n );\n}\n","/**\n * Escaped blog index, tag, archive, and post-meta HTML.\n */\n\nimport * as path from \"node:path\";\nimport type { BlogAuthor } from \"./types\";\n\n/** One listed post considered for blog surfaces. */\nexport interface BlogSourcePage {\n title: string;\n frontmatter: Record<string, unknown>;\n transformedHtml: string;\n inputPath: string;\n routePaths: { href: string };\n}\n\nexport interface BlogPostMeta {\n authors: readonly BlogAuthor[];\n minutes: number;\n tags: readonly { label: string; href: string }[];\n}\n\nexport interface BlogListItem {\n title: string;\n href: string;\n dateLabel?: string;\n}\n\n/** `https:` or a same-origin path starting with `/` but not `//`. */\nexport function isSafeBlogUrl(value: string): boolean {\n const trimmed = value.trim();\n if (\n trimmed.length === 0 ||\n trimmed.split(\"\").some((ch) => ch === \"\\n\" || ch === \"\\r\" || ch === \"\\0\" || ch === \"\\t\")\n ) {\n return false;\n }\n if (trimmed.startsWith(\"//\")) {\n return false;\n }\n if (trimmed.startsWith(\"/\")) {\n return true;\n }\n return trimmed.toLowerCase().startsWith(\"https:\");\n}\n\nexport function postMetaMarkup(meta: BlogPostMeta): string {\n const parts = [\n `<p class=\"ox-blog-meta__reading-time\">${escapeHtml(String(meta.minutes))} min read</p>`,\n ];\n if (meta.authors.length > 0) {\n const items = meta.authors.map((author) => authorMarkup(author)).join(\"\");\n parts.push(`<ul class=\"ox-blog-meta__authors\">${items}</ul>`);\n }\n if (meta.tags.length > 0) {\n const items = meta.tags\n .map((tag) => `<li><a href=\"${escapeHtml(tag.href)}\">${escapeHtml(tag.label)}</a></li>`)\n .join(\"\");\n parts.push(`<ul class=\"ox-blog-meta__tags\">${items}</ul>`);\n }\n return `<aside class=\"ox-blog-meta\">${parts.join(\"\")}</aside>\\n`;\n}\n\nexport function indexPageContent(\n items: readonly BlogListItem[],\n pager: { newerHref?: string; olderHref?: string },\n): string {\n const list = items.map((item) => listItem(item)).join(\"\");\n const links: string[] = [];\n if (pager.newerHref) {\n links.push(`<a href=\"${escapeHtml(pager.newerHref)}\" rel=\"prev\">Newer</a>`);\n }\n if (pager.olderHref) {\n links.push(`<a href=\"${escapeHtml(pager.olderHref)}\" rel=\"next\">Older</a>`);\n }\n const nav = links.length > 0 ? `<nav class=\"ox-blog-pager\">${links.join(\"\")}</nav>` : \"\";\n return `<h1>Blog</h1><ul class=\"ox-blog\">${list}</ul>${nav}`;\n}\n\nexport function tagPageContent(label: string, items: readonly BlogListItem[]): string {\n const list = items.map((item) => listItem(item)).join(\"\");\n return `<h1>${escapeHtml(label)}</h1><ul class=\"ox-blog-tag\">${list}</ul>`;\n}\n\nexport function archiveIndexContent(years: readonly { year: string; href: string }[]): string {\n const items = years\n .map((entry) => `<li><a href=\"${escapeHtml(entry.href)}\">${escapeHtml(entry.year)}</a></li>`)\n .join(\"\");\n return `<h1>Archive</h1><ul class=\"ox-blog-archive\">${items}</ul>`;\n}\n\nexport function archiveYearContent(\n year: string,\n months: readonly { month: string; href: string }[],\n items: readonly BlogListItem[],\n): string {\n const monthList = months\n .map((entry) => `<li><a href=\"${escapeHtml(entry.href)}\">${escapeHtml(entry.month)}</a></li>`)\n .join(\"\");\n const posts = items.map((item) => listItem(item)).join(\"\");\n return `<h1>${escapeHtml(year)}</h1><ul class=\"ox-blog-archive-months\">${monthList}</ul><ul class=\"ox-blog\">${posts}</ul>`;\n}\n\nexport function archiveMonthContent(label: string, items: readonly BlogListItem[]): string {\n const list = items.map((item) => listItem(item)).join(\"\");\n return `<h1>${escapeHtml(label)}</h1><ul class=\"ox-blog\">${list}</ul>`;\n}\n\nexport function siteHref(base: string, ...segments: string[]): string {\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n const rest = segments.filter(Boolean).join(\"/\");\n return rest ? `${prefix}${rest}/` : prefix;\n}\n\nexport function containedPath(outDir: string, ...segments: string[]): string | undefined {\n const root = path.resolve(outDir);\n const resolved = path.resolve(root, ...segments);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved === root || !resolved.startsWith(prefix)) {\n return undefined;\n }\n return resolved;\n}\n\nexport function escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n\nfunction authorMarkup(author: BlogAuthor): string {\n const name = escapeHtml(author.name);\n const url = author.url?.trim();\n const heading =\n url && isSafeBlogUrl(url)\n ? `<a class=\"ox-blog-meta__name\" href=\"${escapeHtml(url)}\">${name}</a>`\n : `<span class=\"ox-blog-meta__name\">${name}</span>`;\n const bio =\n author.bio && author.bio.length > 0\n ? `<p class=\"ox-blog-meta__bio\">${escapeHtml(author.bio)}</p>`\n : \"\";\n return `<li>${heading}${bio}</li>`;\n}\n\nfunction listItem(item: BlogListItem): string {\n const time = item.dateLabel\n ? ` <time datetime=\"${escapeHtml(item.dateLabel)}\">${escapeHtml(item.dateLabel)}</time>`\n : \"\";\n return `<li><a href=\"${escapeHtml(item.href)}\">${escapeHtml(item.title)}</a>${time}</li>`;\n}\n","/**\n * Blog post selection, tags, authors, and dates.\n */\n\nimport * as path from \"node:path\";\nimport { parseDate } from \"./feed-format\";\nimport { resolveBlogCollectionName } from \"./blog-options\";\nimport { siteHref, type BlogSourcePage } from \"./blog-html\";\nimport type { BlogAuthor, ResolvedBlogOptions, ResolvedCollectionsOptions } from \"./types\";\n\nconst HOSTILE_TERM = /^(?:javascript|data):/i;\n\nexport function selectBlogPosts(\n listed: readonly BlogSourcePage[],\n options: ResolvedBlogOptions,\n srcDir: string,\n collections: ResolvedCollectionsOptions | undefined,\n): BlogSourcePage[] | undefined {\n if (isAmbiguousCollection(options, collections)) {\n return undefined;\n }\n const names = collectionNames(collections);\n const name = resolveBlogCollectionName(options.collection, names);\n const sources = name && collections?.enabled ? collections.collections[name]?.source : undefined;\n return listed.filter((page) => {\n if (isExcludedPost(page.frontmatter)) {\n return false;\n }\n if (!sources) {\n return true;\n }\n return pageMatchesSources(page.inputPath, srcDir, sources);\n });\n}\n\nexport function isAmbiguousCollection(\n options: ResolvedBlogOptions,\n collections: ResolvedCollectionsOptions | undefined,\n): boolean {\n if (options.collection) {\n return false;\n }\n const names = collectionNames(collections);\n return names.length > 1 && !names.includes(\"blog\");\n}\n\nfunction collectionNames(collections: ResolvedCollectionsOptions | undefined): string[] {\n if (!collections?.enabled) {\n return [];\n }\n return Object.keys(collections.collections);\n}\n\nfunction pageMatchesSources(\n inputPath: string,\n srcDir: string,\n sources: readonly string[],\n): boolean {\n const relative = path.relative(srcDir, inputPath).split(path.sep).join(\"/\");\n return sources.some((source) => matchGlob(relative, source));\n}\n\nfunction matchGlob(relative: string, pattern: string): boolean {\n const normalized = pattern.replace(/^\\/+/, \"\");\n let out = \"^\";\n for (let i = 0; i < normalized.length; i += 1) {\n if (normalized.startsWith(\"**/\", i)) {\n out += \"(?:.*/)?\";\n i += 2;\n continue;\n }\n const ch = normalized[i] ?? \"\";\n if (ch === \"*\") {\n out += \"[^/]*\";\n continue;\n }\n if (ch === \"?\") {\n out += \"[^/]\";\n continue;\n }\n if (/[.+^${}()|[\\]\\\\]/.test(ch)) {\n out += `\\\\${ch}`;\n continue;\n }\n out += ch;\n }\n out += \"$\";\n return new RegExp(out).test(relative);\n}\n\nexport function sortPosts(posts: readonly BlogSourcePage[]): BlogSourcePage[] {\n return [...posts].sort((left, right) => {\n const dateCmp =\n (pageUnix(right.frontmatter) ?? Number.NEGATIVE_INFINITY) -\n (pageUnix(left.frontmatter) ?? Number.NEGATIVE_INFINITY);\n if (dateCmp !== 0) {\n return dateCmp;\n }\n return left.routePaths.href < right.routePaths.href\n ? -1\n : left.routePaths.href > right.routePaths.href\n ? 1\n : 0;\n });\n}\n\nexport function collectTags(\n posts: readonly BlogSourcePage[],\n): Array<{ label: string; slug: string; pages: BlogSourcePage[] }> {\n const buckets = new Map<string, { label: string; slug: string; pages: BlogSourcePage[] }>();\n for (const page of posts) {\n for (const label of termsFromValue(page.frontmatter.tags)) {\n const slug = tagSlug(label);\n if (!slug) {\n continue;\n }\n const existing = buckets.get(slug);\n if (existing) {\n existing.pages.push(page);\n } else {\n buckets.set(slug, { label, slug, pages: [page] });\n }\n }\n }\n return [...buckets.values()].sort((left, right) => left.label.localeCompare(right.label));\n}\n\nexport function datedPosts(\n posts: readonly BlogSourcePage[],\n): Array<{ page: BlogSourcePage; year: string; month: string; label: string }> {\n const dated: Array<{ page: BlogSourcePage; year: string; month: string; label: string }> = [];\n for (const page of posts) {\n const parsed = pageDate(page.frontmatter);\n if (!parsed) {\n continue;\n }\n dated.push({\n page,\n year: String(parsed.year).padStart(4, \"0\"),\n month: String(parsed.month).padStart(2, \"0\"),\n label: `${String(parsed.year).padStart(4, \"0\")}-${String(parsed.month).padStart(2, \"0\")}-${String(parsed.day).padStart(2, \"0\")}`,\n });\n }\n return dated;\n}\n\nexport function uniqueYears(dated: readonly { year: string }[]): string[] {\n return [...new Set(dated.map((entry) => entry.year))].sort((left, right) =>\n right.localeCompare(left),\n );\n}\n\nexport function uniqueMonths(dated: readonly { month: string }[]): string[] {\n return [...new Set(dated.map((entry) => entry.month))].sort((left, right) =>\n left.localeCompare(right),\n );\n}\n\nexport function toListItem(page: BlogSourcePage): {\n title: string;\n href: string;\n dateLabel?: string;\n} {\n const parsed = pageDate(page.frontmatter);\n return {\n title: page.title,\n href: page.routePaths.href,\n dateLabel: parsed\n ? `${String(parsed.year).padStart(4, \"0\")}-${String(parsed.month).padStart(2, \"0\")}-${String(parsed.day).padStart(2, \"0\")}`\n : undefined,\n };\n}\n\nexport function resolvePostAuthors(\n frontmatter: Record<string, unknown>,\n map: Record<string, BlogAuthor>,\n): BlogAuthor[] {\n const seen = new Set<string>();\n const authors: BlogAuthor[] = [];\n for (const key of authorKeys(frontmatter)) {\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n authors.push(map[key] ?? { name: key });\n }\n return authors;\n}\n\nfunction authorKeys(frontmatter: Record<string, unknown>): string[] {\n return [...keysFromValue(frontmatter.author), ...keysFromValue(frontmatter.authors)];\n}\n\nfunction keysFromValue(value: unknown): string[] {\n if (typeof value === \"string\") {\n return value.trim() ? [value.trim()] : [];\n }\n if (!Array.isArray(value)) {\n return [];\n }\n return value.flatMap((item) => (typeof item === \"string\" && item.trim() ? [item.trim()] : []));\n}\n\nexport function postTagLinks(\n frontmatter: Record<string, unknown>,\n base: string,\n): Array<{ label: string; href: string }> {\n const links: Array<{ label: string; href: string }> = [];\n const seen = new Set<string>();\n for (const label of termsFromValue(frontmatter.tags)) {\n const slug = tagSlug(label);\n if (!slug || seen.has(slug)) {\n continue;\n }\n seen.add(slug);\n links.push({ label, href: siteHref(base, \"blog\", \"tags\", slug) });\n }\n return links;\n}\n\nfunction tagSlug(term: string): string | undefined {\n const trimmed = term.trim();\n if (!trimmed || HOSTILE_TERM.test(trimmed) || trimmed.includes(\"..\") || trimmed.includes(\"//\")) {\n return undefined;\n }\n const slug = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug || undefined;\n}\n\nfunction termsFromValue(value: unknown): string[] {\n if (typeof value === \"string\") {\n return value.trim() ? [value.trim()] : [];\n }\n if (!Array.isArray(value)) {\n return [];\n }\n return value.flatMap((item) => (typeof item === \"string\" && item.trim() ? [item.trim()] : []));\n}\n\nfunction isExcludedPost(frontmatter: Record<string, unknown>): boolean {\n return frontmatter.draft === true || frontmatter.unlisted === true;\n}\n\nfunction pageDate(frontmatter: Record<string, unknown>): ReturnType<typeof parseDate> {\n return parseDate(dateField(frontmatter.date));\n}\n\nfunction pageUnix(frontmatter: Record<string, unknown>): number | undefined {\n return pageDate(frontmatter)?.unix;\n}\n\nfunction dateField(value: unknown): string | undefined {\n if (typeof value === \"string\" && value.trim()) {\n return value.trim();\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n if (value instanceof Date && !Number.isNaN(value.getTime())) {\n return value.toISOString();\n }\n return undefined;\n}\n","/**\n * Generated blog index, tag, and archive pages.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport {\n archiveIndexContent,\n archiveMonthContent,\n archiveYearContent,\n containedPath,\n indexPageContent,\n postMetaMarkup,\n siteHref,\n tagPageContent,\n type BlogSourcePage,\n} from \"./blog-html\";\nimport { readingTimeMinutes } from \"./blog-reading\";\nimport {\n collectTags,\n datedPosts,\n isAmbiguousCollection,\n postTagLinks,\n resolvePostAuthors,\n selectBlogPosts,\n sortPosts,\n toListItem,\n uniqueMonths,\n uniqueYears,\n} from \"./blog-posts\";\nimport type { ResolvedBlogOptions, ResolvedCollectionsOptions } from \"./types\";\n\nconst AMBIGUOUS_COLLECTION =\n \"[ox-content] blog is enabled but multiple collections are configured; set blog.collection\";\n\n/** Synthetic page passed back to `generateHtmlPage`. */\nexport interface BlogGeneratedPage {\n title: string;\n content: string;\n outputPath: string;\n urlPath: string;\n href: string;\n}\n\nexport async function injectBlogPostMeta(input: {\n pages: BlogSourcePage[];\n listed: readonly BlogSourcePage[];\n options?: ResolvedBlogOptions;\n srcDir: string;\n collections?: ResolvedCollectionsOptions;\n base: string;\n}): Promise<void> {\n if (!input.options?.enabled) {\n return;\n }\n const posts = selectBlogPosts(input.listed, input.options, input.srcDir, input.collections);\n if (posts === undefined) {\n return;\n }\n const listedPaths = new Set(posts.map((page) => page.inputPath));\n for (const page of input.pages) {\n if (!listedPaths.has(page.inputPath)) {\n continue;\n }\n const markdown = await readMarkdown(page.inputPath);\n page.transformedHtml =\n postMetaMarkup({\n authors: resolvePostAuthors(page.frontmatter, input.options.authors),\n minutes: readingTimeMinutes(markdown),\n tags: postTagLinks(page.frontmatter, input.base),\n }) + page.transformedHtml;\n }\n}\n\n/** Maps a generated blog page onto the SSG render shape. */\nexport function toBlogProcessResult(page: BlogGeneratedPage): {\n inputPath: string;\n routePaths: {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n };\n transformedHtml: string;\n title: string;\n frontmatter: Record<string, unknown>;\n toc: [];\n} {\n return {\n inputPath: page.outputPath,\n routePaths: {\n outputPath: page.outputPath,\n urlPath: page.urlPath,\n href: page.href,\n ogImagePath: \"\",\n ogImageUrl: \"\",\n },\n transformedHtml: page.content,\n title: page.title,\n frontmatter: {},\n toc: [],\n };\n}\n\n/** Renders index, tag, and archive pages and appends them to the build. */\nexport async function appendBlogPages(input: {\n generatedPages: Array<{ inputPath: string; outputPath: string; html: string }>;\n listedPages: readonly BlogSourcePage[];\n options?: ResolvedBlogOptions;\n collections?: ResolvedCollectionsOptions;\n srcDir: string;\n outDir: string;\n base: string;\n render: (page: BlogGeneratedPage) => Promise<string>;\n errors: string[];\n}): Promise<void> {\n if (!input.options?.enabled) {\n return;\n }\n if (isAmbiguousCollection(input.options, input.collections)) {\n input.errors.push(AMBIGUOUS_COLLECTION);\n return;\n }\n const posts = selectBlogPosts(input.listedPages, input.options, input.srcDir, input.collections);\n if (posts === undefined) {\n return;\n }\n for (const spec of blogPageSpecs(posts, input.options, input.outDir, input.base)) {\n try {\n input.generatedPages.push({\n inputPath: spec.outputPath,\n outputPath: spec.outputPath,\n html: await input.render(spec),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n input.errors.push(`Failed to generate blog page ${spec.href}: ${message}`);\n }\n }\n}\n\nfunction blogPageSpecs(\n posts: readonly BlogSourcePage[],\n options: ResolvedBlogOptions,\n outDir: string,\n base: string,\n): BlogGeneratedPage[] {\n const sorted = sortPosts(posts);\n const pages: BlogGeneratedPage[] = [];\n const pageSize = options.pageSize;\n const pageCount = Math.max(1, Math.ceil(sorted.length / pageSize) || 1);\n const totalPages = sorted.length === 0 ? 1 : pageCount;\n\n for (let pageNumber = 1; pageNumber <= totalPages; pageNumber += 1) {\n const slice = sorted.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);\n const isFirst = pageNumber === 1;\n const urlPath = isFirst ? \"blog\" : `blog/page/${pageNumber}`;\n const outputPath = isFirst\n ? containedPath(outDir, \"blog\", \"index.html\")\n : containedPath(outDir, \"blog\", \"page\", String(pageNumber), \"index.html\");\n if (!outputPath) {\n continue;\n }\n pages.push({\n title: isFirst ? \"Blog\" : `Blog · page ${pageNumber}`,\n content: indexPageContent(slice.map(toListItem), {\n newerHref: isFirst\n ? undefined\n : siteHref(\n base,\n ...(pageNumber === 2 ? [\"blog\"] : [\"blog\", \"page\", String(pageNumber - 1)]),\n ),\n olderHref:\n pageNumber < totalPages\n ? siteHref(base, \"blog\", \"page\", String(pageNumber + 1))\n : undefined,\n }),\n outputPath,\n urlPath,\n href: siteHref(base, ...urlPath.split(\"/\")),\n });\n }\n\n const tags = collectTags(sorted);\n for (const tag of tags) {\n const outputPath = containedPath(outDir, \"blog\", \"tags\", tag.slug, \"index.html\");\n if (!outputPath) {\n continue;\n }\n pages.push({\n title: tag.label,\n content: tagPageContent(tag.label, tag.pages.map(toListItem)),\n outputPath,\n urlPath: `blog/tags/${tag.slug}`,\n href: siteHref(base, \"blog\", \"tags\", tag.slug),\n });\n }\n\n const dated = datedPosts(sorted);\n if (dated.length > 0) {\n const years = uniqueYears(dated);\n const archiveIndex = containedPath(outDir, \"blog\", \"archive\", \"index.html\");\n if (archiveIndex) {\n pages.push({\n title: \"Archive\",\n content: archiveIndexContent(\n years.map((year) => ({ year, href: siteHref(base, \"blog\", \"archive\", year) })),\n ),\n outputPath: archiveIndex,\n urlPath: \"blog/archive\",\n href: siteHref(base, \"blog\", \"archive\"),\n });\n }\n for (const year of years) {\n const yearPosts = dated.filter((entry) => entry.year === year);\n const months = uniqueMonths(yearPosts);\n const yearPath = containedPath(outDir, \"blog\", \"archive\", year, \"index.html\");\n if (yearPath) {\n pages.push({\n title: year,\n content: archiveYearContent(\n year,\n months.map((month) => ({\n month: `${year}-${month}`,\n href: siteHref(base, \"blog\", \"archive\", year, month),\n })),\n yearPosts.map((entry) => toListItem(entry.page)),\n ),\n outputPath: yearPath,\n urlPath: `blog/archive/${year}`,\n href: siteHref(base, \"blog\", \"archive\", year),\n });\n }\n for (const month of months) {\n const monthPosts = yearPosts.filter((entry) => entry.month === month);\n const monthPath = containedPath(outDir, \"blog\", \"archive\", year, month, \"index.html\");\n if (!monthPath) {\n continue;\n }\n pages.push({\n title: `${year}-${month}`,\n content: archiveMonthContent(\n `${year}-${month}`,\n monthPosts.map((entry) => toListItem(entry.page)),\n ),\n outputPath: monthPath,\n urlPath: `blog/archive/${year}/${month}`,\n href: siteHref(base, \"blog\", \"archive\", year, month),\n });\n }\n }\n }\n\n return pages;\n}\n\nasync function readMarkdown(inputPath: string): Promise<string> {\n try {\n return await fs.readFile(inputPath, \"utf8\");\n } catch {\n return \"\";\n }\n}\n","/**\n * Section-index listing HTML and href safety.\n *\n * Titles are escaped. `javascript:` / `data:` / `vbscript:` / `file:` hrefs\n * are dropped. The NAPI helper is preferred when present.\n */\n\nimport { importNapiModuleSync } from \"./napi\";\nimport type { SectionIndexStyle } from \"./types\";\n\nconst HOSTILE_SCHEME = /^(?:javascript|data|vbscript|file):/i;\n\n/** One child link on a generated section index. */\nexport interface SectionIndexItem {\n title: string;\n href: string;\n description?: string;\n}\n\n/** `https:`-free, same-origin or relative href. `javascript:` is rejected. */\nexport function isSafeSectionHref(value: string): boolean {\n const trimmed = value.trim();\n if (!trimmed || /[\\n\\r\\0\\t]/.test(trimmed) || trimmed.startsWith(\"//\")) {\n return false;\n }\n if (trimmed.startsWith(\"/\")) {\n return true;\n }\n const scheme = trimmed.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);\n if (scheme) {\n return false;\n }\n return !HOSTILE_SCHEME.test(trimmed);\n}\n\n/** Escapes text and attribute values in generated listing markup. */\nexport function escapeSectionIndexHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n\n/** Renders the listing body. Titles are escaped; hostile hrefs are dropped. */\nexport function renderSectionIndexHtml(\n title: string,\n items: readonly SectionIndexItem[],\n style: SectionIndexStyle,\n): string {\n try {\n const napi = importNapiModuleSync() as typeof import(\"@ox-content/napi\") & {\n renderSsgSectionIndex?: (\n title: string,\n items: Array<{ title: string; href: string; description?: string }>,\n style: string,\n ) => string;\n };\n if (typeof napi.renderSsgSectionIndex === \"function\") {\n return napi.renderSsgSectionIndex(\n title,\n items.map((item) => ({\n title: item.title,\n href: item.href,\n description: item.description,\n })),\n style,\n );\n }\n } catch {\n // Fall through to the local renderer when the native helper is absent.\n }\n return renderSectionIndexHtmlLocal(title, items, style);\n}\n\nfunction renderSectionIndexHtmlLocal(\n title: string,\n items: readonly SectionIndexItem[],\n style: SectionIndexStyle,\n): string {\n const safe = items.filter((item) => isSafeSectionHref(item.href));\n const modifier = style === \"list\" ? \"list\" : \"cards\";\n const listClass = style === \"list\" ? \"ox-section-index__list\" : \"ox-section-index__cards\";\n const body = safe.map((item) => renderItem(item, style)).join(\"\");\n return (\n `<nav class=\"ox-section-index ox-section-index--${modifier}\" aria-label=\"Section pages\">` +\n `<h1>${escapeSectionIndexHtml(title)}</h1>` +\n `<ul class=\"${listClass}\">${body}</ul>` +\n `</nav>`\n );\n}\n\nfunction renderItem(item: SectionIndexItem, style: SectionIndexStyle): string {\n const href = escapeSectionIndexHtml(item.href.trim());\n const label = escapeSectionIndexHtml(item.title);\n if (style === \"list\") {\n return `<li><a href=\"${href}\">${label}</a></li>`;\n }\n const description =\n typeof item.description === \"string\" && item.description.trim()\n ? `<span class=\"ox-section-index__desc\">${escapeSectionIndexHtml(item.description)}</span>`\n : \"\";\n return (\n `<li class=\"ox-section-index__card\">` +\n `<a href=\"${href}\"><span class=\"ox-section-index__title\">${label}</span>${description}</a>` +\n `</li>`\n );\n}\n","/**\n * Section-index URL, title, and output-path helpers.\n */\n\nimport * as path from \"node:path\";\nimport { importNapiModuleSync } from \"./napi\";\n\nexport function pageTitle(page: {\n title: string;\n inputPath?: string;\n routePaths: { urlPath: string };\n}): string {\n if (page.title.trim()) {\n return page.title;\n }\n const stem = path.basename(page.inputPath ?? page.routePaths.urlPath).replace(/\\.[^.]+$/, \"\");\n return formatSectionTitle(stem || page.routePaths.urlPath);\n}\n\nexport function sectionTitle(dir: string): string {\n if (!dir) {\n return \"Home\";\n }\n const segment = dir.slice(dir.lastIndexOf(\"/\") + 1);\n return formatSectionTitle(segment);\n}\n\nexport function formatSectionTitle(name: string): string {\n try {\n return importNapiModuleSync().formatSsgTitle(name);\n } catch {\n if (!name) {\n return \"Untitled\";\n }\n return name.charAt(0).toUpperCase() + name.slice(1).replace(/[-_]+/g, \" \");\n }\n}\n\nexport function normalizeUrlPath(urlPath: string): string {\n if (!urlPath || urlPath === \"/\") {\n return \"\";\n }\n return urlPath.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nexport function parentDir(urlPath: string): string | null {\n const normalized = normalizeUrlPath(urlPath);\n if (!normalized) {\n return null;\n }\n const index = normalized.lastIndexOf(\"/\");\n return index === -1 ? \"\" : normalized.slice(0, index);\n}\n\nexport function firstChildDir(urlPath: string, parent: string): string | undefined {\n const normalized = normalizeUrlPath(urlPath);\n if (!normalized) {\n return undefined;\n }\n if (!parent) {\n const slash = normalized.indexOf(\"/\");\n return slash === -1 ? undefined : normalized.slice(0, slash);\n }\n const prefix = `${parent}/`;\n if (!normalized.startsWith(prefix) || normalized === parent) {\n return undefined;\n }\n const rest = normalized.slice(prefix.length);\n const slash = rest.indexOf(\"/\");\n return slash === -1 ? undefined : `${parent}/${rest.slice(0, slash)}`;\n}\n\nexport function sectionHref(base: string, dir: string, extension: string): string {\n const prefix = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n const ext = extension.startsWith(\".\") ? extension : `.${extension}`;\n return dir ? `${prefix}${dir}/index${ext}` : `${prefix}index${ext}`;\n}\n\nexport function sectionOutputPath(\n outDir: string,\n dir: string,\n extension: string,\n): string | undefined {\n const ext = extension.startsWith(\".\") ? extension : `.${extension}`;\n const segments = dir ? [...dir.split(\"/\").filter(Boolean), `index${ext}`] : [`index${ext}`];\n return containedPath(outDir, ...segments);\n}\n\nexport function dirFromOutputPath(outputPath: string, outDir: string): string {\n const relative = path\n .relative(path.resolve(outDir), path.resolve(outputPath))\n .replaceAll(path.sep, \"/\");\n return relative\n .replace(/\\/index\\.[^/]+$/u, \"\")\n .replace(/^index\\.[^/]+$/u, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction containedPath(outDir: string, ...segments: string[]): string | undefined {\n const root = path.resolve(outDir);\n const resolved = path.resolve(root, ...segments);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved !== root && !resolved.startsWith(prefix)) {\n return undefined;\n }\n if (segments.some((segment) => segment === \"..\" || segment.includes(\"\\0\"))) {\n return undefined;\n }\n return resolved;\n}\n","/**\n * Opt-in generated section index pages.\n *\n * Resolution and directory walking live here. Listing HTML is rendered in\n * Rust (`ox_content_ssg::render_section_index`) when the NAPI helper is\n * available; a matching TypeScript renderer covers the same escape / href\n * rules so the SSG path stays safe either way. The Vite plugin appends\n * themed HTML during SSG and never overwrites an existing index page.\n */\n\nimport * as path from \"node:path\";\nimport {\n isSafeSectionHref,\n renderSectionIndexHtml,\n type SectionIndexItem,\n} from \"./section-index-html\";\nimport {\n dirFromOutputPath,\n firstChildDir,\n normalizeUrlPath,\n pageTitle,\n parentDir,\n sectionHref,\n sectionOutputPath,\n sectionTitle,\n} from \"./section-index-paths\";\nimport type { ResolvedSectionIndexOptions, SectionIndexOptions } from \"./types\";\n\nexport {\n escapeSectionIndexHtml,\n isSafeSectionHref,\n renderSectionIndexHtml,\n type SectionIndexItem,\n} from \"./section-index-html\";\n\n/** One built page considered when deciding indexes and children. */\nexport interface SectionIndexSourcePage {\n title: string;\n description?: string;\n frontmatter: Record<string, unknown>;\n inputPath?: string;\n routePaths: {\n href: string;\n urlPath: string;\n outputPath?: string;\n };\n}\n\n/** Synthetic page passed back to `generateHtmlPage`. */\nexport interface SectionIndexGeneratedPage {\n title: string;\n content: string;\n outputPath: string;\n urlPath: string;\n href: string;\n}\n\n/**\n * Resolves `ssg.sectionIndex` with defaults.\n *\n * `false` / omitted stays off. `true` enables card listings. An object\n * enables the feature and overrides only the fields the site set.\n */\nexport function resolveSectionIndexOptions(\n value: boolean | SectionIndexOptions | undefined,\n): ResolvedSectionIndexOptions {\n if (!value) {\n return { enabled: false, style: \"cards\" };\n }\n if (value === true) {\n return { enabled: true, style: \"cards\" };\n }\n return {\n enabled: true,\n style: value.style === \"list\" ? \"list\" : \"cards\",\n };\n}\n\n/** Maps a generated section index onto the SSG render shape. */\nexport function toSectionIndexProcessResult(page: SectionIndexGeneratedPage): {\n inputPath: string;\n routePaths: {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n };\n transformedHtml: string;\n title: string;\n frontmatter: Record<string, unknown>;\n toc: [];\n} {\n return {\n inputPath: page.outputPath,\n routePaths: {\n outputPath: page.outputPath,\n urlPath: page.urlPath,\n href: page.href,\n ogImagePath: \"\",\n ogImageUrl: \"\",\n },\n transformedHtml: page.content,\n title: page.title,\n frontmatter: {},\n toc: [],\n };\n}\n\n/** Appends generated section indexes for directories that have no real index. */\nexport async function appendSectionIndexPages(input: {\n generatedPages: Array<{ inputPath: string; outputPath: string; html: string }>;\n collectedPages: readonly SectionIndexSourcePage[];\n listedPages: readonly SectionIndexSourcePage[];\n options?: ResolvedSectionIndexOptions;\n outDir: string;\n base: string;\n extension: string;\n errors: string[];\n render: (page: SectionIndexGeneratedPage) => Promise<string>;\n}): Promise<void> {\n if (!input.options?.enabled) {\n return;\n }\n\n const existingOutputs = new Set(\n input.generatedPages.map((page) => path.normalize(page.outputPath)),\n );\n for (const spec of sectionIndexSpecs(\n input.collectedPages,\n input.listedPages,\n input.options,\n input.outDir,\n input.base,\n input.extension,\n )) {\n if (existingOutputs.has(path.normalize(spec.outputPath))) {\n continue;\n }\n try {\n const html = await input.render(spec);\n input.generatedPages.push({\n inputPath: spec.outputPath,\n outputPath: spec.outputPath,\n html,\n });\n existingOutputs.add(path.normalize(spec.outputPath));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n input.errors.push(`Failed to generate section index ${spec.href}: ${message}`);\n }\n }\n}\n\nfunction sectionIndexSpecs(\n collected: readonly SectionIndexSourcePage[],\n listed: readonly SectionIndexSourcePage[],\n options: ResolvedSectionIndexOptions,\n outDir: string,\n base: string,\n extension: string,\n): SectionIndexGeneratedPage[] {\n const occupied = new Set<string>();\n for (const page of collected) {\n occupied.add(normalizeUrlPath(page.routePaths.urlPath));\n }\n for (const page of collected) {\n const output = page.routePaths.outputPath;\n if (output) {\n occupied.add(dirFromOutputPath(output, outDir));\n }\n }\n\n const visible = listed.filter((page) => !isHiddenByFlags(page.frontmatter));\n const childrenByDir = new Map<string, SectionIndexItem[]>();\n\n for (const page of visible) {\n const urlPath = normalizeUrlPath(page.routePaths.urlPath);\n const parent = parentDir(urlPath);\n if (parent === null) {\n continue;\n }\n pushChild(childrenByDir, parent, {\n title: pageTitle(page),\n href: page.routePaths.href,\n description: page.description,\n });\n\n let ancestor = parent;\n while (ancestor !== \"\") {\n const grand = parentDir(ancestor);\n if (grand === null) {\n break;\n }\n const nested = firstChildDir(urlPath, grand);\n if (nested) {\n pushUniqueDir(childrenByDir, grand, nested, visible, base, extension);\n }\n ancestor = grand;\n }\n }\n\n const pages: SectionIndexGeneratedPage[] = [];\n const dirs = [...childrenByDir.keys()].sort();\n for (const dir of dirs) {\n if (occupied.has(dir)) {\n continue;\n }\n const children = uniqueItems(childrenByDir.get(dir) ?? []).filter((item) =>\n isSafeSectionHref(item.href),\n );\n if (children.length === 0) {\n continue;\n }\n children.sort((left, right) => {\n const titleCmp = left.title.localeCompare(right.title);\n return titleCmp !== 0 ? titleCmp : left.href.localeCompare(right.href);\n });\n const outputPath = sectionOutputPath(outDir, dir, extension);\n if (!outputPath) {\n continue;\n }\n const title = sectionTitle(dir);\n pages.push({\n title,\n content: renderSectionIndexHtml(title, children, options.style),\n outputPath,\n urlPath: dir || \"/\",\n href: sectionHref(base, dir, extension),\n });\n }\n return pages;\n}\n\nfunction pushChild(\n map: Map<string, SectionIndexItem[]>,\n dir: string,\n item: SectionIndexItem,\n): void {\n const list = map.get(dir);\n if (list) {\n list.push(item);\n return;\n }\n map.set(dir, [item]);\n}\n\nfunction pushUniqueDir(\n map: Map<string, SectionIndexItem[]>,\n parent: string,\n childDir: string,\n visible: readonly SectionIndexSourcePage[],\n base: string,\n extension: string,\n): void {\n const href = sectionHref(base, childDir, extension);\n const existing = map.get(parent);\n if (existing?.some((item) => item.href === href)) {\n return;\n }\n const indexPage = visible.find((page) => normalizeUrlPath(page.routePaths.urlPath) === childDir);\n pushChild(map, parent, {\n title: indexPage ? pageTitle(indexPage) : sectionTitle(childDir),\n href: indexPage?.routePaths.href ?? href,\n description: indexPage?.description,\n });\n}\n\nfunction uniqueItems(items: SectionIndexItem[]): SectionIndexItem[] {\n const seen = new Set<string>();\n const unique: SectionIndexItem[] = [];\n for (const item of items) {\n if (seen.has(item.href)) {\n continue;\n }\n seen.add(item.href);\n unique.push(item);\n }\n return unique;\n}\n\nfunction isHiddenByFlags(frontmatter: Record<string, unknown>): boolean {\n return frontmatter.draft === true || frontmatter.unlisted === true;\n}\n","/**\n * Opt-in hosted search provider for `virtual:ox-content/search`.\n *\n * Local BM25 stays the default. Hosted queries use a generic HTTP adapter and\n * a public search-only key. Write and admin keys are rejected.\n */\n\nimport type { ResolvedSearchOptions, SearchOptions } from \"./types\";\n\nconst FORBIDDEN_KEY_NAMES = new Set([\"adminkey\", \"writekey\", \"apikey\"]);\nconst DEFAULT_HOSTED_ENDPOINT = \"/search\";\n\nexport type HostedSearchConfig = {\n appId: string;\n indexName: string;\n searchKey: string;\n endpoint: string;\n};\n\nfunction normalizeOptionKey(name: string): string {\n return name.replace(/[_-]/g, \"\").toLowerCase();\n}\n\nfunction readNonEmpty(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Returns true when the options object names a write or admin credential.\n */\nexport function hasForbiddenSearchCredentialFields(options: object): boolean {\n return Object.keys(options).some((key) => FORBIDDEN_KEY_NAMES.has(normalizeOptionKey(key)));\n}\n\n/**\n * Resolves hosted credentials from config or env. Missing or forbidden keys\n * fail closed and return null without echoing secrets.\n */\nexport function resolveHostedSearchConfig(\n options: SearchOptions,\n env: NodeJS.ProcessEnv = process.env,\n): HostedSearchConfig | null {\n if (hasForbiddenSearchCredentialFields(options)) {\n return null;\n }\n\n const appId = readNonEmpty(options.appId) ?? readNonEmpty(env.OX_CONTENT_SEARCH_APP_ID);\n const indexName =\n readNonEmpty(options.indexName) ?? readNonEmpty(env.OX_CONTENT_SEARCH_INDEX_NAME);\n const searchKey =\n readNonEmpty(options.searchKey) ??\n readNonEmpty(options.publicKey) ??\n readNonEmpty(env.OX_CONTENT_SEARCH_KEY) ??\n readNonEmpty(env.OX_CONTENT_SEARCH_PUBLIC_KEY);\n const endpoint =\n readNonEmpty(options.endpoint) ??\n readNonEmpty(env.OX_CONTENT_SEARCH_ENDPOINT) ??\n DEFAULT_HOSTED_ENDPOINT;\n\n if (!appId || !indexName || !searchKey) {\n return null;\n }\n\n return { appId, indexName, searchKey, endpoint };\n}\n\n/**\n * JSON-embeds a value so it stays inert inside a script tag.\n */\nexport function embedSearchJson(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, \"\\\\u003c\")\n .replace(/>/g, \"\\\\u003e\")\n .replace(/&/g, \"\\\\u0026\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction hostedClientOptions(options: ResolvedSearchOptions) {\n return {\n enabled: options.enabled,\n limit: options.limit,\n prefix: options.prefix,\n placeholder: options.placeholder,\n hotkey: options.hotkey,\n provider: \"hosted\" as const,\n };\n}\n\nfunction failClosedSearchModule(options: ResolvedSearchOptions): string {\n return `// Search module generated by ox-content\nconst searchOptions = ${embedSearchJson(hostedClientOptions(options))};\nexport async function search() { return []; }\nexport { searchOptions };\nexport default { search, searchOptions };\n`;\n}\n\nconst HOSTED_SEARCH_RUNTIME = `export async function search(query, options = {}) {\n const hosted = searchOptions.hosted;\n if (!hosted || !query) return [];\n const limit = options.limit ?? searchOptions.limit;\n try {\n const response = await fetch(hosted.endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n \"x-app-id\": hosted.appId,\n \"x-index-name\": hosted.indexName,\n \"x-search-key\": hosted.searchKey,\n },\n body: JSON.stringify({\n query: String(query),\n limit,\n indexName: hosted.indexName,\n }),\n });\n if (!response.ok) return [];\n const data = await response.json();\n const hits = Array.isArray(data) ? data : (data && (data.hits || data.results)) || [];\n return hits.slice(0, limit).map(normalizeHostedHit);\n } catch {\n return [];\n }\n}\nfunction normalizeHostedHit(hit) {\n if (!hit || typeof hit !== \"object\") {\n return { id: \"\", title: \"\", url: \"\", score: 0, matches: [], snippet: \"\" };\n }\n return {\n id: String(hit.id ?? hit.objectID ?? \"\"),\n title: String(hit.title ?? \"\"),\n url: String(hit.url ?? \"\"),\n score: Number(hit.score ?? 0) || 0,\n matches: Array.isArray(hit.matches) ? hit.matches.map(String) : [],\n snippet: String(hit.snippet ?? hit.content ?? \"\"),\n };\n}\nexport { searchOptions };\nexport default { search, searchOptions };\n`;\n\n/**\n * Client runtime that queries the hosted HTTP adapter.\n *\n * Misconfigured hosted search emits a no-op client so the UI never calls a\n * broken endpoint.\n */\nexport function generateHostedSearchModule(options: ResolvedSearchOptions): string {\n if (!options.appId || !options.indexName || !options.searchKey) {\n return failClosedSearchModule(options);\n }\n\n const searchOptions = {\n ...hostedClientOptions(options),\n hosted: {\n appId: options.appId,\n indexName: options.indexName,\n searchKey: options.searchKey,\n endpoint: options.endpoint ?? DEFAULT_HOSTED_ENDPOINT,\n },\n };\n\n return `// Search module generated by ox-content\nconst searchOptions = ${embedSearchJson(searchOptions)};\n${HOSTED_SEARCH_RUNTIME}`;\n}\n\n/**\n * Runtime fields accepted by the native local BM25 module generator.\n */\nexport function toLocalSearchRuntimeOptions(options: ResolvedSearchOptions) {\n return {\n enabled: options.enabled,\n limit: options.limit,\n prefix: options.prefix,\n placeholder: options.placeholder,\n hotkey: options.hotkey,\n };\n}\n","/**\n * Full-text search functionality for Ox Content.\n *\n * Generates search index at build time and provides client-side search.\n */\n\nimport { importNapiModule, importNapiModuleSync } from \"./napi\";\nimport { DEFAULT_MARKDOWN_EXTENSIONS } from \"./markdown\";\nimport type {\n SearchOptions,\n ResolvedSearchOptions,\n ResolvedPublishStateOptions,\n SearchDocument,\n ScopedSearchQuery,\n} from \"./types\";\nimport { toNapiPublishState } from \"./publish-state\";\nimport {\n generateHostedSearchModule,\n resolveHostedSearchConfig,\n toLocalSearchRuntimeOptions,\n} from \"./search-provider\";\n\n// Import Rust bindings\nlet oxContent: typeof import(\"@ox-content/napi\") | null = null;\n\nasync function getOxContent() {\n if (!oxContent) {\n try {\n oxContent = await importNapiModule();\n } catch {\n console.warn(\"[ox-content] Native bindings not available, search disabled\");\n return null;\n }\n }\n return oxContent;\n}\n\n/**\n * Splits a raw query into free-text terms and `@scope` prefixes.\n */\nexport function parseScopedSearchQuery(query: string): ScopedSearchQuery {\n return importNapiModuleSync().parseScopedSearchQuery(query);\n}\n\n/**\n * Derives hierarchical search scopes from a document id or URL.\n *\n * For example, `api/math/index` yields `[\"api\", \"api/math\"]`.\n */\nexport function getSearchDocumentScopes(doc: Pick<SearchDocument, \"id\" | \"url\">): string[] {\n return importNapiModuleSync().getSearchDocumentScopes(doc.id ?? \"\", doc.url ?? \"\");\n}\n\n/**\n * Returns true when a search document belongs to at least one requested scope.\n */\nexport function matchesSearchScopes(\n doc: Pick<SearchDocument, \"id\" | \"url\">,\n scopes: string[],\n): boolean {\n return importNapiModuleSync().matchesSearchScopes(doc.id ?? \"\", doc.url ?? \"\", scopes);\n}\n\n/**\n * Resolves search options with defaults.\n */\nexport function resolveSearchOptions(\n options: SearchOptions | boolean | undefined,\n): ResolvedSearchOptions {\n if (options === false) {\n return {\n enabled: false,\n limit: 10,\n prefix: true,\n placeholder: \"Search documentation...\",\n hotkey: \"/\",\n provider: \"local\",\n };\n }\n\n const opts = typeof options === \"object\" ? options : {};\n const enabled = opts.enabled ?? true;\n const provider = opts.provider === \"hosted\" ? \"hosted\" : \"local\";\n const resolved: ResolvedSearchOptions = {\n enabled,\n limit: opts.limit ?? 10,\n prefix: opts.prefix ?? true,\n placeholder: opts.placeholder ?? \"Search documentation...\",\n hotkey: opts.hotkey ?? \"/\",\n provider,\n };\n\n if (!enabled || provider !== \"hosted\") {\n return resolved;\n }\n\n const hosted = resolveHostedSearchConfig(opts, process.env);\n if (!hosted) {\n console.warn(\"[ox-content] Hosted search is not configured\");\n return resolved;\n }\n\n return {\n ...resolved,\n appId: hosted.appId,\n indexName: hosted.indexName,\n searchKey: hosted.searchKey,\n endpoint: hosted.endpoint,\n };\n}\n\n/**\n * Builds the search index from Markdown files.\n *\n * `publishState` is forwarded to the native indexer. `excludeDocumentIds`\n * then drops matching documents and rebuilds the BM25 index so omitted\n * pages (such as the opt-in 404 source) are not searchable.\n */\nexport async function buildSearchIndex(\n srcDir: string,\n base: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n publishState?: ResolvedPublishStateOptions,\n excludeDocumentIds: readonly string[] = [],\n mdx?: boolean,\n): Promise<string> {\n const napi = await getOxContent();\n\n if (!napi) {\n return JSON.stringify({\n documents: [],\n index: {},\n df: {},\n avg_dl: 0,\n doc_count: 0,\n });\n }\n\n const indexJson = napi.buildSearchIndexFromDirectory(srcDir, base, [...extensions], {\n publishState: toNapiPublishState(publishState),\n mdx,\n });\n if (excludeDocumentIds.length === 0) {\n return indexJson;\n }\n return excludeSearchDocuments(napi, indexJson, excludeDocumentIds);\n}\n\nfunction excludeSearchDocuments(\n napi: NonNullable<Awaited<ReturnType<typeof getOxContent>>>,\n indexJson: string,\n excludeDocumentIds: readonly string[],\n): string {\n const excluded = new Set(excludeDocumentIds);\n let documents: Array<{\n id: string;\n title: string;\n url: string;\n body: string;\n headings: string[];\n code: string[];\n }>;\n try {\n const parsed = JSON.parse(indexJson) as { documents?: typeof documents };\n documents = parsed.documents ?? [];\n } catch {\n return indexJson;\n }\n\n const kept = documents.filter((doc) => !excluded.has(doc.id));\n if (kept.length === documents.length) {\n return indexJson;\n }\n return napi.buildSearchIndex(kept);\n}\n\n/**\n * Writes the search index to a file.\n */\nexport async function writeSearchIndex(indexJson: string, outDir: string): Promise<void> {\n const napi = await getOxContent();\n\n if (!napi) {\n return;\n }\n\n napi.writeSearchIndex(indexJson, outDir);\n}\n\n/**\n * Client-side search module code.\n * This is injected into the bundle as a virtual module.\n */\nexport function generateSearchModule(options: ResolvedSearchOptions, indexPath: string): string {\n if (options.provider === \"hosted\") {\n return generateHostedSearchModule(options);\n }\n return importNapiModuleSync().generateSearchModuleFromOptions(\n toLocalSearchRuntimeOptions(options),\n indexPath,\n );\n}\n","/**\n * Escaped version switcher, banner, and badge markup.\n */\n\nimport type { VersionBannerKind } from \"./types\";\n\nexport interface VersionLink {\n id: string;\n label: string;\n href: string;\n current: boolean;\n banner?: VersionBannerKind | false;\n}\n\nexport function versionSwitcherMarkup(links: readonly VersionLink[], badge: boolean): string {\n if (links.length === 0) {\n return \"\";\n }\n const current = links.find((link) => link.current) ?? links[0];\n const items = links\n .map((link) => {\n const label = `${escapeHtml(link.label)}${badgeMarkup(link, badge)}`;\n if (link.current || !isSafeHref(link.href)) {\n return `<li><span aria-current=\"page\">${label}</span></li>`;\n }\n return `<li><a href=\"${escapeHtml(link.href)}\">${label}</a></li>`;\n })\n .join(\"\");\n return `<nav class=\"ox-header-select ox-version-switcher\" aria-label=\"Version\"><button type=\"button\" aria-expanded=\"false\" aria-haspopup=\"true\">${escapeHtml(current.label)}${badgeMarkup(current, badge)}</button><ul class=\"ox-header-select-menu\">${items}</ul></nav><script>(function(){var n=document.currentScript&&document.currentScript.previousElementSibling;if(!n||!n.classList.contains(\"ox-version-switcher\"))return;var b=n.querySelector(\"button\");if(!b)return;function closeOthers(){document.querySelectorAll(\".header-nav-dropdown > button[aria-expanded='true'], .ox-locale-switcher > button[aria-expanded='true']\").forEach(function(btn){btn.setAttribute(\"aria-expanded\",\"false\");});}b.addEventListener(\"click\",function(e){e.stopPropagation();var o=b.getAttribute(\"aria-expanded\")===\"true\";closeOthers();b.setAttribute(\"aria-expanded\",o?\"false\":\"true\");});document.addEventListener(\"click\",function(e){if(!n.contains(e.target))b.setAttribute(\"aria-expanded\",\"false\");});document.addEventListener(\"keydown\",function(e){if(e.key===\"Escape\"){b.setAttribute(\"aria-expanded\",\"false\");b.focus();}});})()</script>`;\n}\n\nexport function versionBannerMarkup(kind: VersionBannerKind | false | undefined): string {\n if (kind === \"unreleased\") {\n return `<aside class=\"ox-version-banner ox-version-banner--unreleased\" role=\"status\">This documentation describes an unreleased version.</aside>`;\n }\n if (kind === \"unmaintained\") {\n return `<aside class=\"ox-version-banner ox-version-banner--unmaintained\" role=\"status\">This documentation is unmaintained.</aside>`;\n }\n return \"\";\n}\n\nexport function injectVersionChrome(\n html: string,\n switcher: string,\n banner: string,\n searchFrom?: string,\n searchTo?: string,\n): string {\n let next = html;\n if (banner) {\n next = next.replace(/<body([^>]*)>/, `<body$1>${banner}`);\n }\n if (switcher) {\n if (next.includes('<div class=\"header-actions\">')) {\n next = next.replace(\n '<div class=\"header-actions\">',\n `<div class=\"header-actions\">${switcher}`,\n );\n } else if (next.includes(\"</header>\")) {\n next = next.replace(\"</header>\", `${switcher}</header>`);\n }\n }\n if (searchTo && isSafeHref(searchTo)) {\n next = next.replace(/<html([^>]*)>/i, (match, attrs: string) => {\n if (/\\sdata-ox-search-index=/.test(attrs)) {\n return match;\n }\n return `<html${attrs} data-ox-search-index=\"${escapeHtml(searchTo)}\">`;\n });\n }\n if (searchFrom && searchTo && searchFrom !== searchTo && isSafeHref(searchTo)) {\n next = next.split(searchFrom).join(searchTo);\n const script = `<script>(function(){var f=${JSON.stringify(searchFrom)},t=${JSON.stringify(searchTo)};var o=window.fetch;window.fetch=function(i,n){if(typeof i===\"string\"&&i.indexOf(f)!==-1)i=i.split(f).join(t);return o.call(this,i,n);};})()</script>`;\n next = next.includes(\"</body>\")\n ? next.replace(\"</body>\", `${script}</body>`)\n : `${next}${script}`;\n }\n return next;\n}\n\nexport function searchIndexUrl(base: string, prefix: string): string {\n const root = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return prefix ? `${root}${prefix}/search-index.json` : `${root}search-index.json`;\n}\n\nexport function isSafeHref(href: string): boolean {\n const trimmed = href.trim();\n if (!trimmed || trimmed.startsWith(\"//\")) {\n return false;\n }\n const lower = trimmed.replace(/\\s+/g, \"\").toLowerCase();\n if (\n lower.startsWith(\"javascript:\") ||\n lower.startsWith(\"data:\") ||\n lower.startsWith(\"vbscript:\")\n ) {\n return false;\n }\n return trimmed.startsWith(\"/\") || trimmed.startsWith(\"./\") || !trimmed.includes(\":\");\n}\n\nexport function escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n\nfunction badgeMarkup(link: VersionLink, badge: boolean): string {\n if (!badge || !link.banner) {\n return \"\";\n }\n const text = link.banner === \"unreleased\" ? \"unreleased\" : \"unmaintained\";\n return `<span class=\"ox-version-badge\">${text}</span>`;\n}\n","/**\n * Opt-in documentation versioning: prefixes, snapshots, and header chrome.\n *\n * Historical snapshot directories are read-only during the build. Recreate\n * them with an explicit snapshot command.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { buildSearchIndex, writeSearchIndex } from \"./search\";\nimport type {\n ResolvedPublishStateOptions,\n ResolvedVersionEntry,\n ResolvedVersionsOptions,\n VersionBannerKind,\n VersionEntry,\n VersionsOptions,\n} from \"./types\";\nimport {\n injectVersionChrome,\n searchIndexUrl,\n versionBannerMarkup,\n versionSwitcherMarkup,\n type VersionLink,\n} from \"./versions-html\";\n\nexport {\n injectVersionChrome,\n searchIndexUrl,\n versionBannerMarkup,\n versionSwitcherMarkup,\n} from \"./versions-html\";\n\nconst DEFAULT_CURRENT_ID = \"current\";\nconst PREFIX_RE = /^[a-z0-9](?:[a-z0-9.-]{0,62})$/;\n\n/**\n * Resolves `versions`. Omitted / `false` stay off. `true` enables a single\n * current entry. An object enables the feature and overrides set fields.\n */\nexport function resolveVersionsOptions(\n value: boolean | VersionsOptions | undefined,\n): ResolvedVersionsOptions {\n if (!value) {\n return {\n enabled: false,\n current: DEFAULT_CURRENT_ID,\n switcher: true,\n badge: true,\n entries: [],\n };\n }\n if (value === true) {\n return {\n enabled: true,\n current: DEFAULT_CURRENT_ID,\n switcher: true,\n badge: true,\n entries: [defaultCurrentEntry()],\n };\n }\n const entries = normalizeEntries(value.entries);\n const current =\n typeof value.current === \"string\" && value.current.trim()\n ? value.current.trim()\n : (entries[0]?.id ?? DEFAULT_CURRENT_ID);\n return {\n enabled: true,\n current,\n switcher: value.switcher !== false,\n badge: value.badge !== false,\n entries: entries.length > 0 ? entries : [defaultCurrentEntry()],\n };\n}\n\n/** Prefix used for the active version (empty string = site root). */\nexport function currentVersionPrefix(options?: ResolvedVersionsOptions): string {\n if (!options?.enabled) {\n return \"\";\n }\n return options.entries.find((entry) => entry.id === options.current)?.prefix ?? \"\";\n}\n\nexport function snapshotEntries(options?: ResolvedVersionsOptions): ResolvedVersionEntry[] {\n if (!options?.enabled) {\n return [];\n }\n return options.entries.filter((entry) => entry.dir && entry.prefix);\n}\n\n/** Confines a snapshot dir to `root`. */\nexport function resolveSnapshotDir(root: string, dir: string): string | undefined {\n const trimmed = dir.trim();\n if (!trimmed || trimmed.includes(\"\\0\") || trimmed.includes(\"..\")) {\n return undefined;\n }\n const resolved = path.resolve(root, trimmed);\n const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n if (resolved === root || !resolved.startsWith(prefix)) {\n return undefined;\n }\n return resolved;\n}\n\nexport function prefixRoutePaths(\n routes: { outputPath: string; urlPath: string; href: string },\n prefix: string,\n outDir: string,\n base: string,\n): { outputPath: string; urlPath: string; href: string } {\n const safe = sanitizePrefix(prefix);\n if (!safe) {\n return routes;\n }\n const rel = path.relative(path.resolve(outDir), path.resolve(routes.outputPath));\n if (rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n return routes;\n }\n return {\n outputPath: path.join(outDir, safe, rel),\n urlPath: routes.urlPath ? `${safe}/${routes.urlPath}` : safe,\n href: siteHref(base, safe, routes.urlPath),\n };\n}\n\nexport function versionLinks(\n options: ResolvedVersionsOptions,\n activeId: string,\n siblingPath: string,\n base: string,\n existingHrefs?: ReadonlySet<string>,\n): VersionLink[] {\n return options.entries.map((entry) => {\n const siblingHref = siteHref(base, entry.prefix, siblingPath);\n const rootHref = siteHref(base, entry.prefix, \"\");\n const href =\n !existingHrefs || siblingPath === \"\" || existingHrefs.has(siblingHref)\n ? siblingHref\n : rootHref;\n return {\n id: entry.id,\n label: entry.label,\n href,\n current: entry.id === activeId,\n banner: entry.banner,\n };\n });\n}\n\n/** Version id and same-path remainder for a generated HTML file. */\nexport function versionLocation(\n outputPath: string,\n outDir: string,\n options: ResolvedVersionsOptions,\n): { id: string; sibling: string } {\n const normalized = relativeUrl(outputPath, outDir);\n for (const entry of options.entries) {\n if (!entry.prefix) {\n continue;\n }\n if (normalized === entry.prefix) {\n return { id: entry.id, sibling: \"\" };\n }\n if (normalized.startsWith(`${entry.prefix}/`)) {\n return { id: entry.id, sibling: normalized.slice(entry.prefix.length + 1) };\n }\n }\n return { id: options.current, sibling: normalized };\n}\n\nexport function outputToHref(outputPath: string, outDir: string, base: string): string {\n return siteHref(base, \"\", relativeUrl(outputPath, outDir));\n}\n\n/** Applies switcher / banner / search rewrite after every version tree is generated. */\nexport function decorateVersionedPages(\n pages: Array<{ outputPath: string; html: string }>,\n options: ResolvedVersionsOptions,\n outDir: string,\n base: string,\n): void {\n if (!options.enabled) {\n return;\n }\n const existingHrefs = new Set(pages.map((page) => outputToHref(page.outputPath, outDir, base)));\n for (const page of pages) {\n const { id, sibling } = versionLocation(page.outputPath, outDir, options);\n page.html = applyVersionChrome(page.html, options, id, sibling, base, existingHrefs);\n }\n}\n\nexport async function writeSnapshotSearchIndex(input: {\n srcDir: string;\n outDir: string;\n prefix: string;\n base: string;\n extensions: readonly string[];\n publishState?: ResolvedPublishStateOptions;\n mdx?: boolean;\n}): Promise<string | undefined> {\n const prefix = sanitizePrefix(input.prefix);\n if (!prefix) {\n return undefined;\n }\n const destDir = path.join(input.outDir, prefix);\n const prefixBase = searchIndexUrl(input.base, prefix).replace(/search-index\\.json$/, \"\");\n const json = await buildSearchIndex(\n input.srcDir,\n prefixBase,\n input.extensions,\n input.publishState,\n [],\n input.mdx,\n );\n await fs.mkdir(destDir, { recursive: true });\n await writeSearchIndex(json, destDir);\n const dest = path.join(destDir, \"search-index.json\");\n try {\n await fs.access(dest);\n } catch {\n await fs.writeFile(dest, json, \"utf8\");\n }\n return dest;\n}\n\nexport function applyVersionChrome(\n html: string,\n options: ResolvedVersionsOptions,\n activeId: string,\n siblingPath: string,\n base: string,\n existingHrefs?: ReadonlySet<string>,\n): string {\n if (!options.enabled) {\n return html;\n }\n const active = options.entries.find((entry) => entry.id === activeId);\n const switcher = options.switcher\n ? versionSwitcherMarkup(\n versionLinks(options, activeId, siblingPath, base, existingHrefs),\n options.badge,\n )\n : \"\";\n const banner = versionBannerMarkup(active?.banner);\n const from = searchIndexUrl(base, currentVersionPrefix(options));\n const to = searchIndexUrl(base, active?.prefix ?? \"\");\n return injectVersionChrome(html, switcher, banner, from, to);\n}\n\nexport function sanitizePrefix(prefix: string): string {\n const trimmed = prefix.trim().replace(/^\\/+|\\/+$/g, \"\");\n if (!trimmed) {\n return \"\";\n }\n return PREFIX_RE.test(trimmed) && !trimmed.includes(\"..\") ? trimmed : \"\";\n}\n\nfunction defaultCurrentEntry(): ResolvedVersionEntry {\n return {\n id: DEFAULT_CURRENT_ID,\n label: \"Latest\",\n prefix: \"\",\n banner: false,\n };\n}\n\nfunction normalizeEntries(entries: VersionEntry[] | undefined): ResolvedVersionEntry[] {\n if (!entries) {\n return [];\n }\n const seen = new Set<string>();\n const resolved: ResolvedVersionEntry[] = [];\n for (const entry of entries) {\n if (!entry || typeof entry.id !== \"string\" || typeof entry.label !== \"string\") {\n continue;\n }\n const id = entry.id.trim();\n const label = entry.label.trim();\n if (!id || !label || seen.has(id)) {\n continue;\n }\n const prefix = sanitizePrefix(typeof entry.prefix === \"string\" ? entry.prefix : \"\");\n if (entry.prefix && !prefix) {\n continue;\n }\n const dir = typeof entry.dir === \"string\" && entry.dir.trim() ? entry.dir.trim() : undefined;\n if (dir && (dir.includes(\"\\0\") || dir.includes(\"..\"))) {\n continue;\n }\n seen.add(id);\n resolved.push({\n id,\n label,\n prefix,\n dir,\n banner: normalizeBanner(entry.banner),\n });\n }\n return resolved;\n}\n\nfunction normalizeBanner(value: VersionEntry[\"banner\"]): VersionBannerKind | false {\n return value === \"unreleased\" || value === \"unmaintained\" ? value : false;\n}\n\nfunction siteHref(base: string, prefix: string, rest: string): string {\n const root = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n const parts = [prefix, rest].filter((part) => part && part !== \"/\");\n return parts.length === 0 ? root : `${root}${parts.join(\"/\")}/`;\n}\n\nfunction relativeUrl(outputPath: string, outDir: string): string {\n const rel = path.posix.normalize(\n path.relative(path.resolve(outDir), path.resolve(outputPath)).replaceAll(path.sep, \"/\"),\n );\n if (rel.startsWith(\"..\")) {\n return \"\";\n }\n const dir = rel.endsWith(\"/index.html\")\n ? rel.slice(0, -\"/index.html\".length)\n : rel.replace(/\\.html$/, \"\");\n return dir === \".\" ? \"\" : dir;\n}\n","/**\n * JPEG encode-only helpers for page resource transforms.\n */\n\nimport type { RgbaImage } from \"./resources-image\";\n\nexport function encodeJpeg(image: RgbaImage, quality = 80): Buffer {\n const yQuant = scaleQuant(LUM_QUANT, quality);\n const cQuant = scaleQuant(CHR_QUANT, quality);\n const width = image.width;\n const height = image.height;\n const duY = new Int32Array(64);\n const duCb = new Int32Array(64);\n const duCr = new Int32Array(64);\n const bits = new BitWriter();\n let dcY = 0;\n let dcCb = 0;\n let dcCr = 0;\n for (let y = 0; y < height; y += 8) {\n for (let x = 0; x < width; x += 8) {\n sampleBlock(image, x, y, duY, duCb, duCr);\n dcY = encodeBlock(bits, duY, yQuant, dcY, YDC, YAC);\n dcCb = encodeBlock(bits, duCb, cQuant, dcCb, CDC, CAC);\n dcCr = encodeBlock(bits, duCr, cQuant, dcCr, CDC, CAC);\n }\n }\n bits.flush();\n return Buffer.concat([\n jpegHeader(width, height, yQuant, cQuant),\n bits.toBuffer(),\n Buffer.from([0xff, 0xd9]),\n ]);\n}\n\nfunction sampleBlock(\n image: RgbaImage,\n left: number,\n top: number,\n yOut: Int32Array,\n cbOut: Int32Array,\n crOut: Int32Array,\n): void {\n for (let j = 0; j < 8; j++) {\n const y = Math.min(image.height - 1, top + j);\n for (let i = 0; i < 8; i++) {\n const x = Math.min(image.width - 1, left + i);\n const p = (y * image.width + x) * 4;\n const r = image.data[p] ?? 0;\n const g = image.data[p + 1] ?? 0;\n const b = image.data[p + 2] ?? 0;\n const idx = j * 8 + i;\n yOut[idx] = ((66 * r + 129 * g + 25 * b + 128) >> 8) - 128;\n cbOut[idx] = (-38 * r - 74 * g + 112 * b + 128) >> 8;\n crOut[idx] = (112 * r - 94 * g - 18 * b + 128) >> 8;\n }\n }\n}\n\nfunction encodeBlock(\n bits: BitWriter,\n block: Int32Array,\n quant: number[],\n lastDc: number,\n dcTable: HuffmanTable,\n acTable: HuffmanTable,\n): number {\n const dct = forwardDct(block);\n const zz = new Int32Array(64);\n for (let i = 0; i < 64; i++) {\n zz[i] = Math.round(dct[ZIGZAG[i]!]! / quant[i]!);\n }\n const dc = zz[0] ?? 0;\n writeCoeff(bits, dc - lastDc, dcTable);\n let zeroRun = 0;\n for (let i = 1; i < 64; i++) {\n const value = zz[i] ?? 0;\n if (value === 0) {\n zeroRun++;\n continue;\n }\n while (zeroRun > 15) {\n writeCode(bits, acTable, 0xf0);\n zeroRun -= 16;\n }\n writeCoeff(bits, value, acTable, zeroRun);\n zeroRun = 0;\n }\n if (zeroRun > 0) {\n writeCode(bits, acTable, 0);\n }\n return dc;\n}\n\nfunction writeCoeff(bits: BitWriter, value: number, table: HuffmanTable, run = 0): void {\n const category = bitCategory(value);\n writeCode(bits, table, (run << 4) | category);\n if (category > 0) {\n bits.writeBits(value < 0 ? value + ((1 << category) - 1) : value, category);\n }\n}\n\nfunction writeCode(bits: BitWriter, table: HuffmanTable, symbol: number): void {\n const entry = table.get(symbol);\n if (!entry) {\n throw new Error(\"missing Huffman code\");\n }\n bits.writeBits(entry.code, entry.len);\n}\n\nfunction bitCategory(value: number): number {\n const abs = Math.abs(value);\n if (!Number.isFinite(abs) || abs === 0) {\n return 0;\n }\n return Math.min(11, Math.ceil(Math.log2(abs + 1)));\n}\n\nfunction forwardDct(block: Int32Array): Float64Array {\n const out = new Float64Array(64);\n for (let v = 0; v < 8; v++) {\n for (let u = 0; u < 8; u++) {\n let sum = 0;\n for (let y = 0; y < 8; y++) {\n for (let x = 0; x < 8; x++) {\n sum +=\n (block[y * 8 + x] ?? 0) *\n Math.cos(((2 * x + 1) * u * Math.PI) / 16) *\n Math.cos(((2 * y + 1) * v * Math.PI) / 16);\n }\n }\n const cu = u === 0 ? Math.SQRT1_2 : 1;\n const cv = v === 0 ? Math.SQRT1_2 : 1;\n out[v * 8 + u] = 0.25 * cu * cv * sum;\n }\n }\n return out;\n}\n\nfunction scaleQuant(base: number[], quality: number): number[] {\n const q = Math.max(1, Math.min(100, quality));\n const scale = q < 50 ? Math.floor(5000 / q) : Math.floor(200 - q * 2);\n return base.map((value) => Math.max(1, Math.min(255, Math.floor((value * scale + 50) / 100))));\n}\n\nfunction jpegHeader(width: number, height: number, yQuant: number[], cQuant: number[]): Buffer {\n const chunks = [\n Buffer.from([0xff, 0xd8]),\n jfifApp0(),\n dqt(0, yQuant),\n dqt(1, cQuant),\n sof(width, height),\n dht(0, 0, STD_DC_LUM_NCODES, STD_DC_LUM_VALUES),\n dht(0, 1, STD_DC_CHR_NCODES, STD_DC_CHR_VALUES),\n dht(1, 0, STD_AC_LUM_NCODES, STD_AC_LUM_VALUES),\n dht(1, 1, STD_AC_CHR_NCODES, STD_AC_CHR_VALUES),\n sos(),\n ];\n return Buffer.concat(chunks);\n}\n\nfunction jfifApp0(): Buffer {\n return Buffer.from([\n 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01,\n 0x00, 0x00,\n ]);\n}\n\nfunction dqt(id: number, table: number[]): Buffer {\n const out = Buffer.alloc(5 + 64);\n out[0] = 0xff;\n out[1] = 0xdb;\n out.writeUInt16BE(67, 2);\n out[4] = id;\n for (let i = 0; i < 64; i++) {\n out[5 + i] = table[i] ?? 1;\n }\n return out;\n}\n\nfunction sof(width: number, height: number): Buffer {\n const out = Buffer.from([\n 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01,\n 0x03, 0x11, 0x01,\n ]);\n out.writeUInt16BE(height, 5);\n out.writeUInt16BE(width, 7);\n return out;\n}\n\nfunction dht(cls: number, id: number, ncodes: number[], values: number[]): Buffer {\n const out = Buffer.alloc(5 + 16 + values.length);\n out[0] = 0xff;\n out[1] = 0xc4;\n out.writeUInt16BE(3 + 16 + values.length, 2);\n out[4] = (cls << 4) | id;\n Buffer.from(ncodes).copy(out, 5);\n Buffer.from(values).copy(out, 21);\n return out;\n}\n\nfunction sos(): Buffer {\n return Buffer.from([\n 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00,\n ]);\n}\n\nclass BitWriter {\n private bytes: number[] = [];\n private bits = 0;\n private length = 0;\n\n writeBits(value: number, count: number): void {\n for (let i = count - 1; i >= 0; i--) {\n this.bits = (this.bits << 1) | ((value >> i) & 1);\n this.length++;\n if (this.length === 8) {\n this.pushByte();\n }\n }\n }\n\n flush(): void {\n if (this.length > 0) {\n this.bits <<= 8 - this.length;\n this.pushByte();\n }\n }\n\n toBuffer(): Buffer {\n return Buffer.from(this.bytes);\n }\n\n private pushByte(): void {\n this.bytes.push(this.bits & 0xff);\n if ((this.bits & 0xff) === 0xff) {\n this.bytes.push(0);\n }\n this.bits = 0;\n this.length = 0;\n }\n}\n\ntype HuffmanTable = Map<number, { code: number; len: number }>;\n\nfunction buildHuffman(ncodes: number[], values: number[]): HuffmanTable {\n const table: HuffmanTable = new Map();\n let code = 0;\n let index = 0;\n for (let len = 1; len <= 16; len++) {\n const count = ncodes[len - 1] ?? 0;\n for (let i = 0; i < count; i++) {\n table.set(values[index++] ?? 0, { code, len });\n code++;\n }\n code <<= 1;\n }\n return table;\n}\n\nconst ZIGZAG = [\n 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20,\n 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52,\n 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,\n];\n\nconst LUM_QUANT = [\n 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56,\n 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113,\n 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99,\n];\n\nconst CHR_QUANT = [\n 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99,\n 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,\n 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,\n];\n\nconst STD_DC_LUM_NCODES = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];\nconst STD_DC_LUM_VALUES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];\nconst STD_DC_CHR_NCODES = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];\nconst STD_DC_CHR_VALUES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];\nconst STD_AC_LUM_NCODES = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125];\nconst STD_AC_LUM_VALUES = [\n 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,\n 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,\n 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,\n 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,\n 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,\n 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,\n 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,\n 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,\n 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,\n 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,\n 0xf9, 0xfa,\n];\nconst STD_AC_CHR_NCODES = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119];\nconst STD_AC_CHR_VALUES = [\n 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,\n 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,\n 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,\n 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,\n 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,\n 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,\n 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,\n 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,\n 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,\n 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,\n 0xf9, 0xfa,\n];\n\nconst YDC = buildHuffman(STD_DC_LUM_NCODES, STD_DC_LUM_VALUES);\nconst CDC = buildHuffman(STD_DC_CHR_NCODES, STD_DC_CHR_VALUES);\nconst YAC = buildHuffman(STD_AC_LUM_NCODES, STD_AC_LUM_VALUES);\nconst CAC = buildHuffman(STD_AC_CHR_NCODES, STD_AC_CHR_VALUES);\n","/**\n * Build-time PNG/JPEG pixel helpers for page resources.\n *\n * PNG is decoded and re-encoded for resize/crop. JPEG is encode-only so a\n * `format=jpeg` transform can change the container after the pixel pass.\n */\n\nimport { deflateSync, inflateSync } from \"node:zlib\";\n\nexport interface RgbaImage {\n width: number;\n height: number;\n data: Uint8Array;\n}\n\nconst PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);\n\nexport function isPng(buffer: Buffer): boolean {\n return buffer.length >= 8 && PNG_SIGNATURE.equals(buffer.subarray(0, 8));\n}\n\nexport function pngSize(buffer: Buffer): { width: number; height: number } {\n return {\n width: buffer.readUInt32BE(16),\n height: buffer.readUInt32BE(20),\n };\n}\n\nexport function decodePng(buffer: Buffer): RgbaImage {\n if (!isPng(buffer)) {\n throw new Error(\"not a PNG\");\n }\n let width = 0;\n let height = 0;\n let bitDepth = 0;\n let colorType = 0;\n const idat: Buffer[] = [];\n let offset = 8;\n while (offset + 12 <= buffer.length) {\n const length = buffer.readUInt32BE(offset);\n const type = buffer.toString(\"ascii\", offset + 4, offset + 8);\n const start = offset + 8;\n const end = start + length;\n if (end + 4 > buffer.length) {\n break;\n }\n const chunk = buffer.subarray(start, end);\n if (type === \"IHDR\") {\n width = chunk.readUInt32BE(0);\n height = chunk.readUInt32BE(4);\n bitDepth = chunk[8] ?? 0;\n colorType = chunk[9] ?? 0;\n } else if (type === \"IDAT\") {\n idat.push(Buffer.from(chunk));\n } else if (type === \"IEND\") {\n break;\n }\n offset = end + 4;\n }\n if (bitDepth !== 8 || (colorType !== 2 && colorType !== 6)) {\n throw new Error(\"unsupported PNG\");\n }\n const channels = colorType === 6 ? 4 : 3;\n const raw = inflateSync(Buffer.concat(idat));\n const stride = width * channels;\n const data = new Uint8Array(width * height * 4);\n let src = 0;\n const prior = new Uint8Array(stride);\n const recon = new Uint8Array(stride);\n for (let y = 0; y < height; y++) {\n const filter = raw[src++] ?? 0;\n for (let x = 0; x < stride; x++) {\n const sample = raw[src++] ?? 0;\n const a = x >= channels ? recon[x - channels]! : 0;\n const b = prior[x] ?? 0;\n const c = x >= channels ? prior[x - channels]! : 0;\n recon[x] = (sample + paethPredict(filter, a, b, c)) & 0xff;\n }\n for (let x = 0; x < width; x++) {\n const i = x * channels;\n const o = (y * width + x) * 4;\n data[o] = recon[i] ?? 0;\n data[o + 1] = recon[i + 1] ?? 0;\n data[o + 2] = recon[i + 2] ?? 0;\n data[o + 3] = channels === 4 ? (recon[i + 3] ?? 255) : 255;\n }\n prior.set(recon);\n }\n return { width, height, data };\n}\n\nfunction paethPredict(filter: number, a: number, b: number, c: number): number {\n switch (filter) {\n case 0:\n return 0;\n case 1:\n return a;\n case 2:\n return b;\n case 3:\n return (a + b) >> 1;\n case 4: {\n const p = a + b - c;\n const pa = Math.abs(p - a);\n const pb = Math.abs(p - b);\n const pc = Math.abs(p - c);\n if (pa <= pb && pa <= pc) return a;\n if (pb <= pc) return b;\n return c;\n }\n default:\n throw new Error(\"unsupported PNG filter\");\n }\n}\n\nexport function encodePng(image: RgbaImage): Buffer {\n const { width, height, data } = image;\n const raw = Buffer.alloc((width * 4 + 1) * height);\n let offset = 0;\n for (let y = 0; y < height; y++) {\n raw[offset++] = 0;\n raw.set(data.subarray(y * width * 4, (y + 1) * width * 4), offset);\n offset += width * 4;\n }\n const ihdr = Buffer.alloc(13);\n ihdr.writeUInt32BE(width, 0);\n ihdr.writeUInt32BE(height, 4);\n ihdr[8] = 8;\n ihdr[9] = 6;\n return Buffer.concat([\n PNG_SIGNATURE,\n pngChunk(\"IHDR\", ihdr),\n pngChunk(\"IDAT\", deflateSync(raw)),\n pngChunk(\"IEND\", Buffer.alloc(0)),\n ]);\n}\n\nfunction pngChunk(type: string, data: Buffer): Buffer {\n const body = Buffer.concat([Buffer.from(type, \"ascii\"), data]);\n const chunk = Buffer.alloc(12 + data.length);\n chunk.writeUInt32BE(data.length, 0);\n body.copy(chunk, 4);\n chunk.writeUInt32BE(crc32(body), 8 + data.length);\n return chunk;\n}\n\nfunction crc32(data: Buffer): number {\n let crc = 0xffffffff;\n for (const byte of data) {\n crc ^= byte;\n for (let i = 0; i < 8; i++) {\n crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;\n }\n }\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nexport function createRgba(\n width: number,\n height: number,\n pixel: (x: number, y: number) => [number, number, number, number?],\n): RgbaImage {\n const data = new Uint8Array(width * height * 4);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const [r, g, b, a = 255] = pixel(x, y);\n const i = (y * width + x) * 4;\n data[i] = r;\n data[i + 1] = g;\n data[i + 2] = b;\n data[i + 3] = a;\n }\n }\n return { width, height, data };\n}\n\nexport function resizeNearest(image: RgbaImage, width: number, height: number): RgbaImage {\n const data = new Uint8Array(width * height * 4);\n for (let y = 0; y < height; y++) {\n const sy = Math.min(image.height - 1, Math.floor((y * image.height) / height));\n for (let x = 0; x < width; x++) {\n const sx = Math.min(image.width - 1, Math.floor((x * image.width) / width));\n data.set(\n image.data.subarray((sy * image.width + sx) * 4, (sy * image.width + sx) * 4 + 4),\n (y * width + x) * 4,\n );\n }\n }\n return { width, height, data };\n}\n\nexport function cropImage(\n image: RgbaImage,\n x: number,\n y: number,\n width: number,\n height: number,\n): RgbaImage {\n const left = Math.max(0, Math.min(image.width, Math.floor(x)));\n const top = Math.max(0, Math.min(image.height, Math.floor(y)));\n const cropW = Math.max(1, Math.min(image.width - left, Math.floor(width)));\n const cropH = Math.max(1, Math.min(image.height - top, Math.floor(height)));\n const data = new Uint8Array(cropW * cropH * 4);\n for (let row = 0; row < cropH; row++) {\n const src = ((top + row) * image.width + left) * 4;\n data.set(image.data.subarray(src, src + cropW * 4), row * cropW * 4);\n }\n return { width: cropW, height: cropH, data };\n}\n\nexport function coverCrop(image: RgbaImage, width: number, height: number): RgbaImage {\n const scale = Math.max(width / image.width, height / image.height);\n const scaled = resizeNearest(\n image,\n Math.max(width, Math.round(image.width * scale)),\n Math.max(height, Math.round(image.height * scale)),\n );\n const x = Math.max(0, Math.floor((scaled.width - width) / 2));\n const y = Math.max(0, Math.floor((scaled.height - height) / 2));\n return cropImage(scaled, x, y, width, height);\n}\n\nexport { encodeJpeg } from \"./resources-jpeg\";\n","/**\n * Page-resource HTML rewriting and transform writes.\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport {\n coverCrop,\n cropImage,\n decodePng,\n encodeJpeg,\n encodePng,\n isPng,\n resizeNearest,\n type RgbaImage,\n} from \"./resources-image\";\nimport {\n isInsideRoot,\n parseResourceSrc,\n resourceCacheKey,\n type ProcessPageResourcesInput,\n type ProcessPageResourcesResult,\n type ResourceTransform,\n} from \"./resources\";\nimport type { ResolvedResourcesOptions } from \"./types\";\n\nconst IMG_TAG = /<img\\b[^>]*>/gi;\nconst SRC_ATTR = /\\bsrc\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/i;\n\nexport async function processPageResources(\n input: ProcessPageResourcesInput,\n): Promise<ProcessPageResourcesResult> {\n if (!input.options.enabled) {\n return { html: input.html, files: [], errors: [], fatal: [] };\n }\n\n const bundleRoot = path.dirname(input.inputPath);\n const outputDir = path.dirname(input.outputPath);\n const files: string[] = [];\n const errors: string[] = [];\n const fatal: string[] = [];\n let html = input.html;\n\n const tags = input.html.match(IMG_TAG) ?? [];\n for (const tag of tags) {\n const srcMatch = tag.match(SRC_ATTR);\n const rawSrc = srcMatch?.[1] ?? srcMatch?.[2];\n if (!rawSrc) {\n continue;\n }\n const src = unescapeHtml(rawSrc);\n const parsed = parseResourceSrc(src);\n if (!parsed) {\n continue;\n }\n\n const resolved = resolveBundlePath(parsed.pathname, bundleRoot, input.srcDir);\n if (!resolved.ok) {\n const message = `[ox-content] page resource ${JSON.stringify(src)} on ${input.inputPath} is outside the page bundle`;\n errors.push(message);\n fatal.push(message);\n continue;\n }\n\n let stat: Awaited<ReturnType<typeof fs.stat>>;\n try {\n stat = await fs.stat(resolved.absolute);\n } catch {\n const message = `[ox-content] missing page resource ${JSON.stringify(parsed.pathname)} on ${input.inputPath}`;\n errors.push(message);\n if (input.options.missing === \"error\") {\n fatal.push(message);\n }\n continue;\n }\n\n const transformError = validateTransform(parsed.transform, input.options);\n if (transformError) {\n const message = `[ox-content] ${transformError} for ${JSON.stringify(src)} on ${input.inputPath}`;\n errors.push(message);\n fatal.push(message);\n continue;\n }\n\n const hasTransform = hasPixelOrFormatTransform(parsed.transform);\n const outputName = hasTransform\n ? transformedFileName(\n parsed.pathname,\n parsed.transform,\n resourceCacheKey(resolved.absolute, stat.mtimeMs, parsed.transform),\n )\n : path.basename(resolved.absolute);\n const outputFile = path.join(outputDir, outputName);\n\n try {\n if (hasTransform) {\n await writeTransformedResource({\n sourcePath: resolved.absolute,\n outputFile,\n cacheDir: input.cacheDir,\n mtimeMs: stat.mtimeMs,\n transform: parsed.transform,\n });\n } else {\n await fs.mkdir(outputDir, { recursive: true });\n await fs.copyFile(resolved.absolute, outputFile);\n }\n files.push(outputFile);\n const rewritten = tag.replace(rawSrc, escapeAttribute(outputName));\n html = html.replace(tag, rewritten);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n const message = `[ox-content] failed to process page resource ${JSON.stringify(src)} on ${input.inputPath}: ${detail}`;\n errors.push(message);\n fatal.push(message);\n }\n }\n\n return { html, files, errors, fatal };\n}\n\nfunction resolveBundlePath(\n pathname: string,\n bundleRoot: string,\n contentRoot: string,\n): { ok: true; absolute: string } | { ok: false } {\n if (path.isAbsolute(pathname) || pathname.includes(\"\\0\")) {\n return { ok: false };\n }\n const absolute = path.resolve(bundleRoot, pathname);\n if (!isInsideRoot(bundleRoot, absolute) || !isInsideRoot(contentRoot, absolute)) {\n return { ok: false };\n }\n return { ok: true, absolute };\n}\n\nfunction validateTransform(\n transform: ResourceTransform,\n options: ResolvedResourcesOptions,\n): string | undefined {\n if (transform.width && options.widths.length > 0 && !options.widths.includes(transform.width)) {\n return `width ${transform.width} is not in resources.widths`;\n }\n if (transform.format && !options.formats.includes(transform.format)) {\n return `format ${transform.format} is not in resources.formats`;\n }\n return undefined;\n}\n\nfunction hasPixelOrFormatTransform(transform: ResourceTransform): boolean {\n return Boolean(transform.width || transform.height || transform.crop || transform.format);\n}\n\nfunction transformedFileName(\n pathname: string,\n transform: ResourceTransform,\n cacheKey: string,\n): string {\n const base = path.basename(pathname);\n const stem = base.replace(/\\.[^.]+$/, \"\") || \"resource\";\n const ext = outputExtension(pathname, transform.format);\n return `${stem}.${cacheKey.slice(0, 12)}.${ext}`;\n}\n\nfunction outputExtension(pathname: string, format: string | undefined): string {\n if (format === \"jpeg\") {\n return \"jpg\";\n }\n if (format) {\n return format;\n }\n const ext = path.extname(pathname).slice(1).toLowerCase();\n return ext === \"jpeg\" ? \"jpg\" : ext || \"png\";\n}\n\nasync function writeTransformedResource(input: {\n sourcePath: string;\n outputFile: string;\n cacheDir: string;\n mtimeMs: number;\n transform: ResourceTransform;\n}): Promise<void> {\n const key = resourceCacheKey(input.sourcePath, input.mtimeMs, input.transform);\n const ext = path.extname(input.outputFile);\n const cacheFile = path.join(input.cacheDir, `${key}${ext}`);\n try {\n await fs.copyFile(cacheFile, input.outputFile);\n return;\n } catch {\n // Cache miss — process below.\n }\n\n const source = await fs.readFile(input.sourcePath);\n const output = transformResourceBuffer(source, input.sourcePath, input.transform);\n if (output.length > 8 * 1024 * 1024) {\n throw new Error(\"transform produced an oversized file\");\n }\n await fs.mkdir(path.dirname(input.outputFile), { recursive: true });\n await fs.mkdir(input.cacheDir, { recursive: true });\n await fs.writeFile(cacheFile, output);\n await fs.writeFile(input.outputFile, output);\n}\n\nfunction transformResourceBuffer(\n source: Buffer,\n sourcePath: string,\n transform: ResourceTransform,\n): Buffer {\n const needsPixels = Boolean(transform.width || transform.height || transform.crop);\n if (!needsPixels && !transform.format) {\n return source;\n }\n if (!needsPixels && transform.format) {\n if (!isPng(source)) {\n if (transform.format === formatFromPath(sourcePath)) {\n return source;\n }\n throw new Error(\n `cannot convert ${path.extname(sourcePath) || \"source\"} to ${transform.format}`,\n );\n }\n const image = decodePng(source);\n return encodeFormat(image, transform.format);\n }\n\n if (!isPng(source)) {\n throw new Error(\"resize/crop requires a PNG source\");\n }\n const encoded = encodeFormat(\n applyPixelTransform(decodePng(source), transform),\n transform.format ?? \"png\",\n );\n return encoded;\n}\n\nfunction applyPixelTransform(image: RgbaImage, transform: ResourceTransform): RgbaImage {\n const crop = transform.crop;\n if (crop && crop !== \"center\") {\n const parts = crop.split(\",\").map((part) => Number(part.trim()));\n if (parts.length === 4 && parts.every((part) => Number.isFinite(part))) {\n return cropImage(image, parts[0]!, parts[1]!, parts[2]!, parts[3]!);\n }\n throw new Error(`invalid crop ${crop}`);\n }\n\n const width = transform.width;\n const height = transform.height;\n if (crop === \"center\") {\n if (!width || !height) {\n throw new Error(\"crop=center requires width and height\");\n }\n return coverCrop(image, width, height);\n }\n if (width && height) {\n return resizeNearest(image, width, height);\n }\n if (width) {\n return resizeNearest(\n image,\n width,\n Math.max(1, Math.round((image.height * width) / image.width)),\n );\n }\n if (height) {\n return resizeNearest(\n image,\n Math.max(1, Math.round((image.width * height) / image.height)),\n height,\n );\n }\n return image;\n}\n\nfunction encodeFormat(image: RgbaImage, format: string): Buffer {\n if (format === \"jpeg\") {\n return encodeJpeg(image);\n }\n if (format === \"png\") {\n return encodePng(image);\n }\n if (format === \"webp\") {\n throw new Error(\"webp encoding requires a webp source without pixel transforms\");\n }\n throw new Error(`unsupported format ${format}`);\n}\n\nfunction formatFromPath(filePath: string): string {\n const ext = path.extname(filePath).slice(1).toLowerCase();\n return ext === \"jpg\" ? \"jpeg\" : ext;\n}\n\nfunction unescapeHtml(value: string): string {\n return value\n .replaceAll(\"&amp;\", \"&\")\n .replaceAll(\"&quot;\", '\"')\n .replaceAll(\"&#39;\", \"'\")\n .replaceAll(\"&lt;\", \"<\")\n .replaceAll(\"&gt;\", \">\");\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\");\n}\n","/**\n * Opt-in page-bundle resources and build-time image processing.\n *\n * A page directory is the bundle root. Sibling images are addressable with\n * relative URLs. Resize/crop/format query transforms run at build time and\n * are cached by source mtime plus transform params. Paths that leave the\n * bundle or `srcDir` are never processed.\n */\n\nimport { createHash } from \"node:crypto\";\nimport * as path from \"node:path\";\nimport type { ResourcesOptions, ResolvedResourcesOptions } from \"./types\";\n\nconst DEFAULT_FORMATS = [\"png\", \"jpeg\", \"webp\"];\nconst HOSTILE_SRC = /^(?:javascript|data|vbscript):/i;\n\nexport class PageResourceError extends Error {\n readonly issues: string[];\n\n constructor(issues: string[]) {\n super(issues.join(\"\\n\"));\n this.name = \"PageResourceError\";\n this.issues = issues;\n }\n}\n\nexport interface ResourceTransform {\n width?: number;\n height?: number;\n crop?: string;\n format?: string;\n}\n\nexport interface ProcessPageResourcesInput {\n html: string;\n inputPath: string;\n outputPath: string;\n srcDir: string;\n options: ResolvedResourcesOptions;\n cacheDir: string;\n}\n\nexport interface ProcessPageResourcesResult {\n html: string;\n files: string[];\n errors: string[];\n fatal: string[];\n}\n\n/**\n * Resolves `resources`. Omitted / `false` stay off. `true` or `{}` enables\n * defaults. An object enables the feature and overrides only set fields.\n */\nexport function resolveResourcesOptions(\n value: boolean | ResourcesOptions | undefined,\n): ResolvedResourcesOptions {\n if (!value) {\n return {\n enabled: false,\n formats: [...DEFAULT_FORMATS],\n widths: [],\n missing: \"error\",\n };\n }\n if (value === true) {\n return {\n enabled: true,\n formats: [...DEFAULT_FORMATS],\n widths: [],\n missing: \"error\",\n };\n }\n return {\n enabled: true,\n formats: normalizeFormats(value.formats),\n widths: normalizeWidths(value.widths),\n missing: value.missing === \"warn\" ? \"warn\" : \"error\",\n };\n}\n\n/**\n * Cache key for a source file plus transform. Changing mtime or params\n * produces a different key so stale derivatives are not reused.\n */\nexport function resourceCacheKey(\n sourcePath: string,\n mtimeMs: number,\n transform: ResourceTransform,\n): string {\n return createHash(\"sha256\")\n .update(sourcePath)\n .update(\"\\0\")\n .update(String(mtimeMs))\n .update(\"\\0\")\n .update(JSON.stringify(normalizeTransform(transform)))\n .digest(\"hex\");\n}\n\n/** True when `candidate` stays inside `root` after resolve. */\nexport function isInsideRoot(root: string, candidate: string): boolean {\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(candidate);\n const relative = path.relative(resolvedRoot, resolved);\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nexport function parseResourceSrc(\n src: string,\n): { pathname: string; transform: ResourceTransform } | undefined {\n const trimmed = src.trim();\n if (!trimmed || isRemoteOrAbsolute(trimmed) || HOSTILE_SRC.test(trimmed.replace(/\\s+/g, \"\"))) {\n return undefined;\n }\n const withoutHash = trimmed.split(\"#\")[0] ?? trimmed;\n const queryIndex = withoutHash.indexOf(\"?\");\n const pathname = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex);\n const query = queryIndex === -1 ? \"\" : withoutHash.slice(queryIndex + 1);\n if (!pathname || pathname.includes(\"\\0\")) {\n return undefined;\n }\n const params = new URLSearchParams(query);\n return {\n pathname,\n transform: {\n width: parsePositiveInt(params.get(\"width\") ?? params.get(\"w\")),\n height: parsePositiveInt(params.get(\"height\") ?? params.get(\"h\")),\n crop: params.get(\"crop\")?.trim() || undefined,\n format: normalizeFormat(params.get(\"format\") ?? undefined),\n },\n };\n}\n\nfunction isRemoteOrAbsolute(src: string): boolean {\n const compact = src.replace(/\\s+/g, \"\");\n return (\n /^[a-z][a-z0-9+.-]*:/i.test(compact) || compact.startsWith(\"//\") || compact.startsWith(\"/\")\n );\n}\n\nfunction parsePositiveInt(raw: string | null): number | undefined {\n if (!raw) {\n return undefined;\n }\n if (!/^[0-9]+$/.test(raw)) {\n return undefined;\n }\n const value = Number(raw);\n return value > 0 ? value : undefined;\n}\n\nfunction normalizeFormats(formats: string[] | undefined): string[] {\n if (!formats?.length) {\n return [...DEFAULT_FORMATS];\n }\n const normalized = formats\n .map((format) => normalizeFormat(format))\n .filter((format): format is string => Boolean(format));\n return normalized.length > 0 ? [...new Set(normalized)] : [...DEFAULT_FORMATS];\n}\n\nfunction normalizeWidths(widths: number[] | undefined): number[] {\n if (!widths?.length) {\n return [];\n }\n return [...new Set(widths.filter((width) => Number.isInteger(width) && width > 0))];\n}\n\nfunction normalizeFormat(format: string | undefined): string | undefined {\n if (!format) {\n return undefined;\n }\n const value = format.trim().toLowerCase();\n if (value === \"jpg\") {\n return \"jpeg\";\n }\n return value || undefined;\n}\n\nfunction normalizeTransform(transform: ResourceTransform): ResourceTransform {\n return {\n width: transform.width,\n height: transform.height,\n crop: transform.crop,\n format: transform.format,\n };\n}\n\nexport { processPageResources } from \"./resources-process\";\n","/**\n * Keeps navigation inside a frozen documentation-version tree.\n *\n * Locale resolution runs before these helpers. The lookup therefore uses\n * unversioned route keys while every destination points at the versioned\n * output tree.\n */\n\nimport type { HeaderNavItem } from \"./header-chrome\";\nimport { sitePathFromHref } from \"./locale-nav\";\n\n/** @internal */\nexport interface VersionNavigationPage {\n /** Canonical route before the documentation-version prefix is added. */\n path: string;\n /** Canonical route after the documentation-version prefix is added. */\n versionedPath: string;\n /** Final versioned href. */\n href: string;\n /** File-tree route, used when a manual nav item predates a permalink. */\n sourcePath?: string;\n /** Frontmatter aliases that resolve to this page. */\n aliases?: readonly string[];\n}\n\n/** @internal */\nexport interface VersionNavigationContext {\n prefix: string;\n base: string;\n root: VersionNavigationTarget;\n pages: Array<{ path: string; href: string; aliases?: readonly string[] }>;\n lookup: ReadonlyMap<string, VersionNavigationTarget>;\n}\n\ninterface VersionNavigationTarget {\n path: string;\n href: string;\n}\n\ninterface VersionableNavItem {\n path: string;\n href: string;\n children?: VersionableNavItem[];\n}\n\ninterface VersionableNavGroup {\n items: VersionableNavItem[];\n}\n\n/** @internal */\nexport function createVersionNavigationContext(input: {\n prefix: string;\n base: string;\n pages: readonly VersionNavigationPage[];\n redirects?: Readonly<Record<string, string>>;\n}): VersionNavigationContext {\n const prefix = normalizeRouteKey(input.prefix, input.base);\n const root: VersionNavigationTarget = {\n path: prefix,\n href: siteHref(input.base, prefix),\n };\n const lookup = new Map<string, VersionNavigationTarget>();\n const targets = input.pages.map((page) => ({\n page,\n target: { path: normalizeRouteKey(page.versionedPath, input.base), href: page.href },\n }));\n\n // Canonical pages always win over a colliding source path or alias.\n for (const { page, target } of targets) {\n const key = routeLookupKey(page.path, input.base, prefix);\n if (key !== undefined) {\n lookup.set(key, target);\n }\n }\n for (const { page, target } of targets) {\n addLookup(lookup, page.sourcePath, target, input.base, prefix);\n for (const alias of page.aliases ?? []) {\n addLookup(lookup, alias, target, input.base, prefix);\n }\n }\n\n resolveRedirectAliases(lookup, input.redirects, input.base, prefix);\n return {\n prefix,\n base: input.base,\n root,\n pages: input.pages.map((page) => ({\n path: page.path,\n href: page.href,\n aliases: navigationAliases(page, lookup, input.redirects, input.base, prefix),\n })),\n lookup,\n };\n}\n\nfunction navigationAliases(\n page: VersionNavigationPage,\n lookup: ReadonlyMap<string, VersionNavigationTarget>,\n redirects: Readonly<Record<string, string>> | undefined,\n base: string,\n prefix: string,\n): string[] | undefined {\n const target = lookup.get(routeLookupKey(page.path, base, prefix) ?? \"\");\n const aliases = [page.sourcePath, ...(page.aliases ?? [])].filter(\n (value): value is string => typeof value === \"string\",\n );\n if (target && redirects) {\n for (const from of Object.keys(redirects)) {\n const key = routeLookupKey(from, base, prefix);\n if (key !== undefined && lookup.get(key) === target) {\n aliases.push(key);\n }\n }\n }\n const unique = [...new Set(aliases.map((value) => normalizeRouteKey(value, base)))];\n return unique.length > 0 ? unique : undefined;\n}\n\n/**\n * Rewrites safe internal sidebar destinations and all nested children.\n * @internal\n */\nexport function rewriteVersionedNavGroups<T extends VersionableNavGroup>(\n groups: T[],\n context: VersionNavigationContext,\n): T[] {\n return groups.map(\n (group) =>\n ({\n ...group,\n items: group.items.map((item) => rewriteNavItem(item, context)),\n }) as T,\n );\n}\n\n/**\n * Rewrites safe internal header destinations with the same sibling policy.\n * @internal\n */\nexport function rewriteVersionedHeaderNavItems(\n items: HeaderNavItem[] | undefined,\n context: VersionNavigationContext,\n): HeaderNavItem[] | undefined {\n return items?.map((item) => ({\n ...item,\n link: item.link ? rewriteHref(item.link, context).href : item.link,\n items: rewriteVersionedHeaderNavItems(item.items, context),\n }));\n}\n\n/**\n * Rewrites one safe internal destination, including pager overrides.\n * @internal\n */\nexport function rewriteVersionedHref(href: string, context: VersionNavigationContext): string {\n return rewriteHref(href, context).href;\n}\n\n/**\n * Removes only the active version prefix, leaving locale/path resolution intact.\n * @internal\n */\nexport function unversionedPath(path: string, context: VersionNavigationContext): string {\n const normalized = normalizeRouteKey(path, context.base);\n if (normalized === context.prefix) {\n return \"\";\n }\n return normalized.startsWith(`${context.prefix}/`)\n ? normalized.slice(context.prefix.length + 1)\n : normalized;\n}\n\n/** @internal Keeps missing locale siblings inside the active version tree. */\nexport function versionedLocaleRoots(\n context: VersionNavigationContext,\n locales: readonly { code: string }[],\n defaultLocale: string,\n hideDefaultLocale: boolean,\n): Record<string, string> {\n return Object.fromEntries(\n locales.map((locale) => {\n const route = hideDefaultLocale && locale.code === defaultLocale ? \"\" : locale.code;\n return [locale.code, context.lookup.get(route)?.href ?? context.root.href];\n }),\n );\n}\n\nfunction rewriteNavItem<T extends VersionableNavItem>(\n item: T,\n context: VersionNavigationContext,\n): T {\n const rewritten = rewriteHref(item.href, context, item.path);\n return {\n ...item,\n href: rewritten.href,\n path: rewritten.path,\n children: (item.children ?? []).map((child) => rewriteNavItem(child, context)),\n };\n}\n\nfunction rewriteHref(\n href: string,\n context: VersionNavigationContext,\n path?: string,\n): VersionNavigationTarget {\n const hrefKey = sitePathFromHref(href, context.base);\n if (hrefKey === undefined) {\n return { path: path ?? \"\", href };\n }\n const suffixIndex = href.search(/[?#]/u);\n const suffix = suffixIndex === -1 ? \"\" : href.slice(suffixIndex);\n const target = [path, hrefKey]\n .map((candidate) => routeLookupKey(candidate, context.base, context.prefix))\n .find((candidate) => candidate !== undefined && context.lookup.has(candidate));\n const resolved = target === undefined ? context.root : context.lookup.get(target)!;\n return { path: resolved.path, href: `${resolved.href}${suffix}` };\n}\n\nfunction addLookup(\n lookup: Map<string, VersionNavigationTarget>,\n value: string | undefined,\n target: VersionNavigationTarget,\n base: string,\n prefix: string,\n): void {\n const key = routeLookupKey(value, base, prefix);\n if (key !== undefined && !lookup.has(key)) {\n lookup.set(key, target);\n }\n}\n\nfunction resolveRedirectAliases(\n lookup: Map<string, VersionNavigationTarget>,\n redirects: Readonly<Record<string, string>> | undefined,\n base: string,\n prefix: string,\n): void {\n if (!redirects) {\n return;\n }\n const pending = Object.entries(redirects);\n for (let pass = 0; pass <= pending.length; pass++) {\n let changed = false;\n for (const [from, to] of pending) {\n const fromKey = routeLookupKey(from, base, prefix);\n const toKey = routeLookupKey(to, base, prefix);\n const target = toKey === undefined ? undefined : lookup.get(toKey);\n if (fromKey !== undefined && target && !lookup.has(fromKey)) {\n lookup.set(fromKey, target);\n changed = true;\n }\n }\n if (!changed) {\n break;\n }\n }\n}\n\nfunction routeLookupKey(\n value: string | undefined,\n base: string,\n prefix: string,\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n const fromHref = sitePathFromHref(value, base);\n const key = normalizeRouteKey(fromHref ?? value, base);\n if (key === prefix) {\n return \"\";\n }\n return key.startsWith(`${prefix}/`) ? key.slice(prefix.length + 1) : key;\n}\n\nfunction normalizeRouteKey(value: string, base: string): string {\n const fromHref = sitePathFromHref(value, base);\n return (fromHref ?? value)\n .trim()\n .split(/[?#]/u, 1)[0]!\n .replace(/^\\/+|\\/+$/gu, \"\")\n .replace(/\\/index\\.html$/iu, \"\")\n .replace(/\\.(?:mdx|markdown|md|html)$/iu, \"\");\n}\n\nfunction siteHref(base: string, path: string): string {\n const root = !base || base === \"/\" ? \"/\" : base.endsWith(\"/\") ? base : `${base}/`;\n return path ? `${root}${path}/` : root;\n}\n","/**\n * SSG (Static Site Generation) module for ox-content\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport { transformMarkdown } from \"./transform\";\nimport { generateOgImages } from \"./og-image\";\nimport type { OgImagePageEntry } from \"./og-image\";\nimport { transformAllPlugins } from \"./plugins\";\nimport { copyKatexAssets } from \"./plugins/math-assets\";\nimport type { TransformAllOptions } from \"./plugins\";\nimport { protectMermaidSvgs, restoreMermaidSvgs } from \"./plugins/mermaid-protect\";\nimport { transformIslands, hasIslands } from \"./island\";\nimport { importNapiModule, importNapiModuleSync } from \"./napi\";\nimport { DEFAULT_MARKDOWN_EXTENSIONS } from \"./markdown\";\nimport type {\n ResolvedOptions,\n ResolvedA11y,\n ResolvedReaderChrome,\n ResolvedSsgOptions,\n A11yOptions,\n JsonLdOptions,\n JsonLdPublisherOptions,\n ResolvedJsonLd,\n ResolvedTeamOptions,\n ReaderChromeOptions,\n SsgOptions,\n SsgNavigationGroup,\n TocEntry,\n HeroConfig,\n FeatureConfig,\n LocaleConfig,\n} from \"./types\";\nimport { buildLocalePaths, resolveLocaleSwitcherOption } from \"./locale-switcher\";\nimport type { SsgLocalePath } from \"./locale-switcher\";\nimport {\n attachSidebarLabels,\n localizeHeaderNavItems,\n localizeNavGroups,\n resolveSidebarItems,\n} from \"./locale-nav\";\nimport {\n parsePageChromeFlags,\n resolvePageChromeOption,\n type PageChromeFlags,\n} from \"./header-chrome\";\nimport { resolveTheme, themeToNapi } from \"./theme\";\nimport type { ResolvedThemeConfig, SidebarItem } from \"./theme\";\nimport { normalizeVitePressFrontmatter } from \"./vitepress\";\nimport { renderPage } from \"./theme-renderer\";\nimport type { PageData as ThemePageData } from \"./theme-renderer\";\nimport { writeSiteMapFiles } from \"./site-maps\";\nimport { filterNavGroups, hiddenNavKeys, partitionPublishedPages } from \"./publish-state\";\nimport { applySsgPageRoutes, remapNavGroups } from \"./apply-permalinks\";\nimport { writeRedirectFiles } from \"./redirects\";\nimport {\n FALLBACK_NOT_FOUND_MARKDOWN,\n isNotFoundSourceFile,\n resolveNotFoundOptions,\n resolveNotFoundOutputPath,\n resolveNotFoundSourcePath,\n} from \"./not-found\";\nimport { buildCollectionManifest } from \"./collections\";\nimport { writeFeedFiles } from \"./feeds\";\nimport { injectPwaPageTags, writePwaFiles } from \"./pwa\";\nimport { appendTaxonomyPages, injectRelatedPages, toTaxonomyProcessResult } from \"./taxonomies\";\nimport { resolveTeamOptions } from \"./team\";\nimport { applyContributorOptions, resolveContributorsOption } from \"./contributors\";\nimport type { SsgContributor } from \"./contributors\";\nimport {\n appendBlogPages,\n injectBlogPostMeta,\n resolveBlogOptions,\n toBlogProcessResult,\n} from \"./blog\";\nimport {\n appendSectionIndexPages,\n resolveSectionIndexOptions,\n toSectionIndexProcessResult,\n} from \"./section-index\";\nimport {\n decorateVersionedPages,\n prefixRoutePaths,\n resolveSnapshotDir,\n snapshotEntries,\n writeSnapshotSearchIndex,\n} from \"./versions\";\nimport { PageResourceError, processPageResources } from \"./resources\";\nimport {\n createVersionNavigationContext,\n rewriteVersionedHeaderNavItems,\n rewriteVersionedHref,\n rewriteVersionedNavGroups,\n unversionedPath,\n versionedLocaleRoots,\n type VersionNavigationContext,\n} from \"./version-navigation\";\n\n/**\n * Navigation item for SSG.\n */\nexport interface SsgNavItem {\n title: string;\n path: string;\n href: string;\n children?: SsgNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/**\n * Entry page configuration for SSG (passed to Rust).\n */\nexport interface SsgEntryPageConfig {\n hero?: HeroConfig;\n features?: FeatureConfig[];\n}\n\n/**\n * Page data for SSG.\n */\nexport interface SsgPageData {\n title: string;\n description?: string;\n content: string;\n toc: TocEntry[];\n lastUpdated?: number;\n contributors?: SsgContributor[];\n frontmatter: Record<string, unknown>;\n path: string;\n href: string;\n /** Entry page configuration (if layout: entry) */\n entryPage?: SsgEntryPageConfig;\n /** Frontmatter override for the previous-page link. */\n prev?: SsgPagerOverride;\n /** Frontmatter override for the next-page link. */\n next?: SsgPagerOverride;\n /** Frontmatter `breadcrumbs: false` hides the trail on this page. */\n breadcrumbs?: boolean;\n /** Per-page chrome flags. Honored only when `ssg.pageChrome` is on. */\n chrome?: PageChromeFlags;\n}\n\n/** Frontmatter override for one previous/next pager side. */\nexport interface SsgPagerOverride {\n hidden?: boolean;\n text?: string;\n href?: string;\n}\n\ninterface SsgRoutePaths {\n outputPath: string;\n urlPath: string;\n href: string;\n ogImagePath: string;\n ogImageUrl: string;\n}\n\n/**\n * Deprecated compatibility export for consumers that imported the former\n * TypeScript SSG template. HTML generation is Rust-backed now.\n *\n * @deprecated Use `generateHtmlPage`/`buildSsg` instead.\n */\nexport const DEFAULT_HTML_TEMPLATE = \"<!-- ox-content default HTML template is Rust-backed -->\";\n\n/**\n * Resolves SSG options with defaults.\n */\nexport function resolveSsgOptions(ssg: SsgOptions | boolean | undefined): ResolvedSsgOptions {\n if (ssg === false) {\n return {\n enabled: false,\n extension: \".html\",\n clean: false,\n bare: false,\n generateOgImage: false,\n lastUpdated: false,\n contributors: resolveContributorsOption(undefined),\n pagination: false,\n breadcrumbs: false,\n jsonLd: false,\n readerChrome: false,\n localeSwitcher: false,\n a11y: false,\n pageChrome: false,\n notFound: resolveNotFoundOptions(undefined),\n team: resolveTeamOptions(undefined),\n blog: resolveBlogOptions(undefined),\n sectionIndex: resolveSectionIndexOptions(undefined),\n };\n }\n\n if (ssg === true || ssg === undefined) {\n return {\n enabled: true,\n extension: \".html\",\n clean: false,\n bare: false,\n generateOgImage: false,\n lastUpdated: false,\n contributors: resolveContributorsOption(undefined),\n pagination: false,\n breadcrumbs: false,\n jsonLd: false,\n readerChrome: false,\n localeSwitcher: false,\n a11y: false,\n pageChrome: false,\n notFound: resolveNotFoundOptions(undefined),\n team: resolveTeamOptions(undefined),\n blog: resolveBlogOptions(undefined),\n sectionIndex: resolveSectionIndexOptions(undefined),\n theme: resolveTheme(undefined),\n };\n }\n\n return {\n enabled: ssg.enabled ?? true,\n extension: ssg.extension ?? \".html\",\n clean: ssg.clean ?? false,\n bare: ssg.bare ?? false,\n render: ssg.render,\n lang: ssg.lang,\n head: ssg.head,\n bodyStart: ssg.bodyStart,\n bodyEnd: ssg.bodyEnd,\n siteName: ssg.siteName,\n ogImage: ssg.ogImage,\n generateOgImage: ssg.generateOgImage ?? false,\n lastUpdated: ssg.lastUpdated ?? false,\n contributors: resolveContributorsOption(ssg.contributors),\n pagination: resolvePaginationOption(ssg.pagination),\n breadcrumbs: resolvePaginationOption(ssg.breadcrumbs),\n jsonLd: resolveJsonLdOption(ssg.jsonLd),\n readerChrome: resolveReaderChromeOption(ssg.readerChrome),\n localeSwitcher: resolveLocaleSwitcherOption(ssg.localeSwitcher),\n a11y: resolveA11yOption(ssg.a11y),\n pageChrome: resolvePageChromeOption(ssg.pageChrome),\n notFound: resolveNotFoundOptions(ssg.notFound),\n team: resolveTeamOptions(ssg.team),\n blog: resolveBlogOptions(ssg.blog),\n sectionIndex: resolveSectionIndexOptions(ssg.sectionIndex),\n siteUrl: ssg.siteUrl,\n theme: resolveTheme(ssg.theme),\n navigation: ssg.navigation,\n };\n}\n\nfunction contributorsForPage(\n context: BuildSsgContext,\n inputPath: string,\n): SsgContributor[] | undefined {\n const option = context.ssgOptions.contributors;\n if (!option) {\n return undefined;\n }\n try {\n const raw = context.napi?.getGitContributors(inputPath, context.root) ?? [];\n return applyContributorOptions(raw, option);\n } catch {\n return [];\n }\n}\n\nfunction resolvePaginationOption(value: boolean | Record<string, unknown> | undefined): boolean {\n return value === true || (typeof value === \"object\" && value !== null);\n}\n\nfunction resolveJsonLdOption(value: boolean | JsonLdOptions | undefined): ResolvedJsonLd {\n if (value === true) {\n return { breadcrumbs: true };\n }\n if (value && typeof value === \"object\") {\n const publisher = resolveJsonLdPublisher(value.publisher);\n return {\n breadcrumbs: value.breadcrumbs !== false,\n ...(publisher ? { publisher } : {}),\n };\n }\n return false;\n}\n\nfunction resolveJsonLdPublisher(\n publisher: JsonLdPublisherOptions | undefined,\n): { name?: string; url?: string } | undefined {\n if (!publisher || typeof publisher !== \"object\") {\n return undefined;\n }\n const name = publisher.name?.trim();\n const url = publisher.url?.trim();\n if (!name && !url) {\n return undefined;\n }\n return {\n ...(name ? { name } : {}),\n ...(url ? { url } : {}),\n };\n}\n\nfunction resolveReaderChromeOption(\n value: boolean | ReaderChromeOptions | undefined,\n): ResolvedReaderChrome {\n if (value === true) {\n return { copy: true, externalLinks: true, backToTop: true };\n }\n if (value && typeof value === \"object\") {\n return {\n copy: value.copy !== false,\n externalLinks: value.externalLinks !== false,\n backToTop: value.backToTop !== false,\n };\n }\n return false;\n}\n\nconst DEFAULT_SKIP_LINK_LABEL = \"Skip to content\";\n\nfunction resolveA11yOption(value: boolean | A11yOptions | undefined): ResolvedA11y {\n if (value === true) {\n return { skipLinkLabel: DEFAULT_SKIP_LINK_LABEL };\n }\n if (value && typeof value === \"object\") {\n const label = value.skipLinkLabel?.trim();\n return { skipLinkLabel: label || DEFAULT_SKIP_LINK_LABEL };\n }\n return false;\n}\n\n/** Parses `prev` / `next` frontmatter into a pager override. */\nexport function parseSsgPagerOverride(value: unknown): SsgPagerOverride | undefined {\n if (value === false) {\n return { hidden: true };\n }\n if (value == null || value === true) {\n return undefined;\n }\n if (typeof value !== \"object\") {\n return undefined;\n }\n const record = value as Record<string, unknown>;\n const text =\n typeof record.text === \"string\"\n ? record.text\n : typeof record.title === \"string\"\n ? record.title\n : undefined;\n const href =\n typeof record.link === \"string\"\n ? record.link\n : typeof record.href === \"string\"\n ? record.href\n : undefined;\n if (text === undefined && href === undefined) {\n return undefined;\n }\n return { text, href };\n}\n\n/**\n * Extracts title from content or frontmatter.\n */\nexport function extractTitle(content: string, frontmatter: Record<string, unknown>): string {\n return importNapiModuleSync().extractSsgTitle(\n content,\n typeof frontmatter.title === \"string\" ? frontmatter.title : undefined,\n );\n}\n\n/**\n * Generates bare HTML page (no navigation, no styles).\n */\nexport function generateBareHtmlPage(content: string, title: string): string {\n return importNapiModuleSync().generateSsgBareHtml(content, title);\n}\n\n/**\n * Generates a bare HTML page carrying head metadata and injected markup.\n *\n * Bare mode leaves the shell to the consumer, but the metadata here is\n * already computed for the themed page and cannot be recovered afterwards —\n * the generated OG image in particular was only discoverable by guessing at\n * the output directory. A page with none of it set renders exactly what bare\n * mode emitted before, which keeps the no-JS size baseline honest.\n */\nexport function generateBarePage(page: SsgBarePage): string {\n return importNapiModuleSync().generateSsgBarePage(page);\n}\n\n/** Head metadata and injected markup for a bare page. */\nexport interface SsgBarePage {\n title: string;\n content: string;\n lang?: string;\n dir?: string;\n description?: string;\n canonicalUrl?: string;\n siteName?: string;\n ogImage?: string;\n head?: string;\n bodyStart?: string;\n bodyEnd?: string;\n}\n\n/** NAPI-facing nav group shape produced from a [`NavGroup`]. */\ninterface RustNavGroup {\n title: string;\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n items: SsgNavItem[];\n}\n\n/**\n * Per-build cache for the Rust-facing nav conversion. `navGroups` is the same\n * `context.navItems` reference for every page in a build, so the deep recursive\n * copy below only needs to run once per build instead of once per page.\n */\nconst navGroupsForRustCache = new WeakMap<NavGroup[], RustNavGroup[]>();\n\nfunction toRustNavItem(item: SsgNavItem): SsgNavItem {\n return {\n title: item.title,\n path: item.path,\n href: item.href,\n children: item.children?.map(toRustNavItem),\n collapsed: item.collapsed,\n stickyCollapsed: item.stickyCollapsed,\n };\n}\n\nfunction convertNavGroupsForRust(navGroups: NavGroup[]): RustNavGroup[] {\n const cached = navGroupsForRustCache.get(navGroups);\n if (cached) {\n return cached;\n }\n const converted = navGroups.map((group) => ({\n title: group.title,\n collapsed: group.collapsed,\n stickyCollapsed: group.stickyCollapsed,\n items: group.items.map(toRustNavItem),\n }));\n navGroupsForRustCache.set(navGroups, converted);\n return converted;\n}\n\n/**\n * Converts a `TocEntry` tree into the plain shape the Rust binding expects.\n * Hoisted to module scope so it isn't reallocated for every page; the\n * per-page `.map` over `pageData.toc` still runs since the TOC is page-specific.\n */\nfunction toRustTocEntry(entry: TocEntry): TocEntry {\n return {\n depth: entry.depth,\n text: entry.text,\n slug: entry.slug,\n children: entry.children?.map(toRustTocEntry) ?? [],\n };\n}\n\n/** Rust-facing locale shape. */\ninterface RustLocale {\n code: string;\n name: string;\n dir: string;\n}\n\n/**\n * Per-build cache for the Rust-facing locale list. `i18n.locales` is the same\n * reference for every page in a build, so this mapping (and the `?? \"ltr\"`\n * default) only runs once per build instead of once per page.\n */\nconst rustLocalesCache = new WeakMap<LocaleConfig[], RustLocale[]>();\n\nfunction toRustLocales(locales: LocaleConfig[]): RustLocale[] {\n const cached = rustLocalesCache.get(locales);\n if (cached) {\n return cached;\n }\n const converted = locales.map((locale) => ({\n code: locale.code,\n name: locale.name,\n dir: locale.dir ?? \"ltr\",\n }));\n rustLocalesCache.set(locales, converted);\n return converted;\n}\n\n/**\n * Per-build cache for the locale-code list passed to `getSsgPageLocale`. The\n * `i18n.locales` reference is stable across a build, so the `.map` to codes\n * runs once instead of once per page.\n */\nconst localeCodesCache = new WeakMap<LocaleConfig[], string[]>();\n\nfunction localeCodesFor(locales: LocaleConfig[]): string[] {\n const cached = localeCodesCache.get(locales);\n if (cached) {\n return cached;\n }\n const codes = locales.map((locale) => locale.code);\n localeCodesCache.set(locales, codes);\n return codes;\n}\n\n/**\n * Generates HTML page with navigation using Rust NAPI bindings.\n */\nexport async function generateHtmlPage(\n pageData: SsgPageData,\n navGroups: NavGroup[],\n siteName: string,\n base: string,\n ogImage?: string,\n theme?: ResolvedThemeConfig,\n locale?: string,\n availableLocales?: LocaleConfig[],\n pagination = false,\n readerChrome: ResolvedReaderChrome = false,\n breadcrumbs = false,\n localeSwitcher = false,\n localePaths?: SsgLocalePath[],\n a11y: ResolvedA11y = false,\n team: ResolvedTeamOptions = { enabled: false, members: [] },\n pageChrome: boolean = false,\n breadcrumbRootHref?: string,\n jsonLd: ResolvedJsonLd = false,\n siteUrl?: string,\n): Promise<string> {\n const mod = await importNapiModule();\n\n // Convert TocEntry to the format expected by Rust (converter is module-scoped).\n const tocForRust = pageData.toc.map(toRustTocEntry);\n\n // Convert NavGroup to the format expected by Rust (cached per build).\n const navGroupsForRust = convertNavGroupsForRust(navGroups);\n\n // Convert theme to NAPI format if provided\n const themeForRust = theme ? themeToNapi(theme, locale) : undefined;\n\n // Convert entry page to NAPI format if provided\n const entryPageForRust = pageData.entryPage\n ? {\n hero: pageData.entryPage.hero\n ? {\n name: pageData.entryPage.hero.name,\n text: pageData.entryPage.hero.text,\n tagline: pageData.entryPage.hero.tagline,\n notice: pageData.entryPage.hero.notice\n ? {\n title: pageData.entryPage.hero.notice.title,\n body: pageData.entryPage.hero.notice.body,\n }\n : undefined,\n image: pageData.entryPage.hero.image\n ? {\n src: pageData.entryPage.hero.image.src,\n lightSrc: pageData.entryPage.hero.image.lightSrc,\n darkSrc: pageData.entryPage.hero.image.darkSrc,\n alt: pageData.entryPage.hero.image.alt,\n width: pageData.entryPage.hero.image.width,\n height: pageData.entryPage.hero.image.height,\n }\n : undefined,\n actions: pageData.entryPage.hero.actions?.map((a) => ({\n theme: a.theme,\n text: a.text,\n link: a.link,\n })),\n }\n : undefined,\n features: pageData.entryPage.features?.map((f) => ({\n icon: f.icon,\n title: f.title,\n details: f.details,\n link: f.link,\n linkText: f.linkText,\n })),\n }\n : undefined;\n\n return mod.generateSsgHtml(\n {\n title: pageData.title,\n description: pageData.description,\n content: pageData.content,\n toc: tocForRust,\n lastUpdated: pageData.lastUpdated,\n contributors: pageData.contributors,\n path: pageData.path,\n entryPage: entryPageForRust,\n prev: pageData.prev,\n next: pageData.next,\n breadcrumbs: pageData.breadcrumbs,\n layout:\n typeof pageData.frontmatter.layout === \"string\" ? pageData.frontmatter.layout : undefined,\n chrome: pageData.chrome,\n },\n navGroupsForRust,\n {\n siteName,\n base,\n breadcrumbRootHref,\n ogImage,\n theme: themeForRust,\n locale,\n availableLocales: availableLocales ? toRustLocales(availableLocales) : undefined,\n pagination,\n breadcrumbs,\n readerChrome: readerChrome\n ? {\n copy: readerChrome.copy,\n externalLinks: readerChrome.externalLinks,\n backToTop: readerChrome.backToTop,\n }\n : undefined,\n localeSwitcher: localeSwitcher || undefined,\n localePaths,\n a11y: a11y ? { skipLinkLabel: a11y.skipLinkLabel } : undefined,\n team,\n pageChrome,\n jsonLd: jsonLd\n ? {\n breadcrumbs: jsonLd.breadcrumbs,\n publisher: jsonLd.publisher,\n siteUrl,\n }\n : undefined,\n },\n );\n}\n\ninterface GeneratedHtmlPage {\n inputPath: string;\n outputPath: string;\n html: string;\n}\n\ninterface ExternalizedSharedAsset {\n outputPath: string;\n content: string;\n}\n\nasync function externalizeSharedPageAssets(\n pages: GeneratedHtmlPage[],\n outDir: string,\n base: string,\n): Promise<{ pages: GeneratedHtmlPage[]; assets: string[] }> {\n // Asset extraction is batched after all pages are rendered so the Rust side\n // can de-duplicate identical CSS/JS chunks across the whole build. Doing it\n // page-by-page would miss shared chunks and write duplicate assets.\n const mod = await importNapiModule();\n const optimized = mod.externalizeSsgAssets(pages, outDir, base) as {\n pages: GeneratedHtmlPage[];\n assets: ExternalizedSharedAsset[];\n };\n\n await Promise.all(\n optimized.assets.map(async (asset) => {\n await fs.mkdir(path.dirname(asset.outputPath), { recursive: true });\n await fs.writeFile(asset.outputPath, asset.content, \"utf-8\");\n }),\n );\n\n return {\n pages: optimized.pages,\n assets: optimized.assets.map((asset) => asset.outputPath),\n };\n}\n\n/**\n * Converts a markdown file path to its corresponding HTML output path.\n */\nexport function getOutputPath(\n inputPath: string,\n srcDir: string,\n outDir: string,\n extension: string,\n): string {\n return importNapiModuleSync().getSsgOutputPath(inputPath, srcDir, outDir, extension);\n}\n\n/**\n * Converts a markdown file path to a relative URL path.\n */\nexport function getUrlPath(inputPath: string, srcDir: string): string {\n return importNapiModuleSync().getSsgUrlPath(inputPath, srcDir);\n}\n\n/**\n * Converts a markdown file path to an href.\n */\nexport function getHref(\n inputPath: string,\n srcDir: string,\n base: string,\n extension: string,\n): string {\n return importNapiModuleSync().getSsgHref(inputPath, srcDir, base, extension);\n}\n\n/**\n * Resolves manual navigation config to the format used by the built-in SSG renderer.\n */\nexport function resolveNavigationGroups(\n navigation: SsgNavigationGroup[] | undefined,\n base: string,\n extension: string,\n): NavGroup[] | undefined {\n if (!navigation) {\n return undefined;\n }\n\n return importNapiModuleSync().resolveSsgNavigationGroups(navigation, base, extension);\n}\n\nexport function getPageLocale(urlPath: string, i18n: ResolvedOptions[\"i18n\"]): string | undefined {\n if (!i18n) return undefined;\n return (\n importNapiModuleSync().getSsgPageLocale(\n urlPath,\n i18n.defaultLocale,\n localeCodesFor(i18n.locales),\n ) ?? undefined\n );\n}\n\nfunction getRoutePaths(\n inputPath: string,\n srcDir: string,\n outDir: string,\n base: string,\n extension: string,\n siteUrl?: string,\n): SsgRoutePaths {\n return importNapiModuleSync().resolveSsgRoutePaths(\n inputPath,\n srcDir,\n outDir,\n base,\n extension,\n siteUrl,\n );\n}\n\n/**\n * Formats a file/dir name as a title.\n */\nexport function formatTitle(name: string): string {\n return importNapiModuleSync().formatSsgTitle(name);\n}\n\n/**\n * Collects all markdown files from the source directory.\n */\nexport async function collectMarkdownFiles(\n srcDir: string,\n extensions: readonly string[] = DEFAULT_MARKDOWN_EXTENSIONS,\n): Promise<string[]> {\n return importNapiModuleSync().collectSsgMarkdownFiles(srcDir, [...extensions]);\n}\n\n/**\n * Navigation group for hierarchical navigation.\n */\nexport interface NavGroup {\n title: string;\n items: SsgNavItem[];\n collapsed?: boolean;\n stickyCollapsed?: boolean;\n}\n\n/**\n * Builds navigation items from markdown files, grouped by directory.\n */\nexport function buildNavItems(\n markdownFiles: string[],\n srcDir: string,\n base: string,\n extension: string,\n): NavGroup[] {\n return importNapiModuleSync().buildSsgNavItems(markdownFiles, srcDir, base, extension);\n}\n\n/**\n * Builds navigation items from an explicit theme sidebar tree while retaining\n * locale-map labels for per-page resolution.\n */\nexport function buildThemeNavItems(\n sidebar: SidebarItem[],\n base: string,\n extension: string,\n): NavGroup[] {\n const groups = importNapiModuleSync().buildSsgThemeNavItems(\n resolveSidebarItems(sidebar),\n base,\n extension,\n );\n return attachSidebarLabels(groups, sidebar);\n}\n\ninterface BuildSsgContext {\n options: ResolvedOptions;\n ssgOptions: ResolvedSsgOptions;\n root: string;\n srcDir: string;\n outDir: string;\n base: string;\n siteName: string;\n navItems: NavGroup[];\n versionNavigation?: VersionNavigationContext;\n shouldGenerateOgImages: boolean;\n napi?: Awaited<ReturnType<typeof importNapiModule>>;\n}\n\ninterface PageProcessResult {\n inputPath: string;\n routePaths: SsgRoutePaths;\n transformedHtml: string;\n title: string;\n description?: string;\n lastUpdated?: number;\n contributors?: SsgContributor[];\n frontmatter: Record<string, unknown>;\n toc: TocEntry[];\n}\n\ninterface CollectedPageResults {\n pageResults: PageProcessResult[];\n ogImageEntries: OgImagePageEntry[];\n ogImageInputPaths: string[];\n ogImageUrlMap: Map<string, string>;\n errors: string[];\n}\n\n/** Result of an SSG build. */\nexport interface SsgBuildResult {\n /** Every file written, HTML pages and generated OG images alike. */\n files: string[];\n /** Per-page failures that did not abort the build. */\n errors: string[];\n /**\n * Generated OG image URL per source file, keyed by absolute input path.\n *\n * Bare mode renders these into the page itself, but a consumer\n * post-processing the output had no way to find them short of probing the\n * output directory for `og-image.png`.\n */\n ogImages: Record<string, string>;\n}\n\n/**\n * Builds all markdown files to static HTML.\n */\nexport async function buildSsg(options: ResolvedOptions, root: string): Promise<SsgBuildResult> {\n const ssgOptions = options.ssg;\n if (!ssgOptions.enabled) {\n return { files: [], errors: [], ogImages: {} };\n }\n\n const srcDir = path.resolve(root, options.srcDir);\n const outDir = path.resolve(root, options.outDir);\n const generatedFiles: string[] = [];\n const errors: string[] = [];\n\n await cleanOutputDirectory(ssgOptions, outDir);\n\n const markdownFiles = await collectMarkdownFiles(srcDir, options.extensions);\n const pageFiles = markdownFiles.filter(\n (file) => !isNotFoundSourceFile(file, srcDir, ssgOptions.notFound),\n );\n const context = await createBuildSsgContext(options, root, srcDir, outDir, pageFiles);\n const collected = await collectPageResults(context, pageFiles);\n applyPermalinkRoutes(context, collected);\n errors.push(...collected.errors);\n const { outputPages, listedPages } = applyPublishState(context, collected);\n remapPermalinkNav(context, listedPages);\n\n await applyPageResources(context, outputPages, generatedFiles, errors);\n\n await generateOgImageAssets(context, collected, generatedFiles, errors);\n\n injectRelatedPages(outputPages, listedPages, context.options.taxonomies);\n const blog = context.options.blog ?? context.ssgOptions.blog;\n await injectBlogPostMeta({\n pages: outputPages,\n listed: listedPages,\n options: blog,\n srcDir: context.srcDir,\n collections: context.options.collections,\n base: context.base,\n });\n const generatedPages = await generateHtmlPages(context, outputPages, collected, errors);\n await appendNotFoundPage(generatedPages, context, collected, errors);\n await appendSectionIndexPages({\n generatedPages,\n collectedPages: collected.pageResults,\n listedPages,\n options: context.ssgOptions.sectionIndex,\n outDir: context.outDir,\n base: context.base,\n extension: context.ssgOptions.extension,\n errors,\n render: (page) =>\n renderSsgPage(context, toSectionIndexProcessResult(page), collected, listedPages),\n });\n await appendTaxonomyPages({\n generatedPages,\n listedPages,\n options: context.options.taxonomies,\n outDir: context.outDir,\n base: context.base,\n errors,\n render: (page) => renderSsgPage(context, toTaxonomyProcessResult(page), collected, listedPages),\n });\n await appendBlogPages({\n generatedPages,\n listedPages,\n options: blog,\n collections: context.options.collections,\n srcDir: context.srcDir,\n outDir: context.outDir,\n base: context.base,\n errors,\n render: (page) => renderSsgPage(context, toBlogProcessResult(page), collected, listedPages),\n });\n await applyDocumentationVersions(generatedPages, context, errors);\n await writeGeneratedPages(\n generatedPages,\n context,\n generatedFiles,\n listedPages,\n outputPages,\n errors,\n );\n\n if (options.math?.enabled) {\n generatedFiles.push(...(await copyKatexAssets(outDir)));\n }\n\n return {\n files: generatedFiles,\n errors,\n ogImages: Object.fromEntries(collected.ogImageUrlMap),\n };\n}\n\nasync function cleanOutputDirectory(ssgOptions: ResolvedSsgOptions, outDir: string): Promise<void> {\n if (!ssgOptions.clean) {\n return;\n }\n\n try {\n await fs.rm(outDir, { recursive: true, force: true });\n } catch {\n // Ignore if directory doesn't exist.\n }\n}\n\nasync function createBuildSsgContext(\n options: ResolvedOptions,\n root: string,\n srcDir: string,\n outDir: string,\n markdownFiles: string[],\n): Promise<BuildSsgContext> {\n const ssgOptions = options.ssg;\n const base = options.base.endsWith(\"/\") ? options.base : options.base + \"/\";\n const navItems =\n resolveNavigationGroups(ssgOptions.navigation, base, ssgOptions.extension) ??\n (ssgOptions.theme?.sidebar.length\n ? buildThemeNavItems(ssgOptions.theme.sidebar, base, ssgOptions.extension)\n : buildNavItems(markdownFiles, srcDir, base, ssgOptions.extension));\n\n return {\n options,\n ssgOptions,\n root,\n srcDir,\n outDir,\n base,\n navItems,\n siteName: await resolveSiteName(root, ssgOptions),\n shouldGenerateOgImages: shouldGenerateOgImages(options),\n napi: ssgOptions.lastUpdated || ssgOptions.contributors ? await importNapiModule() : undefined,\n };\n}\n\n/**\n * Whether this build emits one Open Graph image per page.\n *\n * `ssg.bare` deliberately does not turn this off. Bare mode only drops the\n * generated page shell, and bringing your own shell is exactly the case where\n * per-page OG images are still wanted — the images are written to the output\n * tree and the consumer injects the `<meta>` tags itself. Nothing in the bare\n * HTML references them, because bare output has no `<head>` to put them in.\n */\nexport function shouldGenerateOgImages(options: ResolvedOptions): boolean {\n return options.ogImage || options.ssg.generateOgImage;\n}\n\nasync function resolveSiteName(root: string, ssgOptions: ResolvedSsgOptions): Promise<string> {\n if (ssgOptions.siteName) {\n return ssgOptions.siteName;\n }\n\n try {\n const pkgPath = path.join(root, \"package.json\");\n const pkg = JSON.parse(await fs.readFile(pkgPath, \"utf-8\"));\n return pkg.name ? formatTitle(pkg.name) : \"Documentation\";\n } catch {\n return \"Documentation\";\n }\n}\n\nasync function applyPageResources(\n context: BuildSsgContext,\n pages: PageProcessResult[],\n generatedFiles: string[],\n errors: string[],\n): Promise<void> {\n const options = context.options.resources;\n if (!options?.enabled) {\n return;\n }\n\n const cacheDir = path.join(context.root, \".cache\", \"ox-content-resources\");\n const fatal: string[] = [];\n for (const page of pages) {\n const processed = await processPageResources({\n html: page.transformedHtml,\n inputPath: page.inputPath,\n outputPath: page.routePaths.outputPath,\n srcDir: context.srcDir,\n options,\n cacheDir,\n });\n page.transformedHtml = processed.html;\n generatedFiles.push(...processed.files);\n errors.push(...processed.errors);\n fatal.push(...processed.fatal);\n }\n if (fatal.length > 0) {\n throw new PageResourceError(fatal);\n }\n}\n\nfunction applyPermalinkRoutes(context: BuildSsgContext, collected: CollectedPageResults): void {\n if (!context.options.permalinks?.enabled && !context.options.cascade?.enabled) {\n return;\n }\n\n const routed = applySsgPageRoutes({\n pages: collected.pageResults,\n permalinks: context.options.permalinks,\n cascade: context.options.cascade,\n srcDir: context.srcDir,\n outDir: context.outDir,\n base: context.base,\n extension: context.ssgOptions.extension,\n siteUrl: context.ssgOptions.siteUrl,\n });\n collected.errors.push(...routed.errors);\n collected.pageResults = routed.pages as PageProcessResult[];\n\n collected.ogImageEntries = [];\n collected.ogImageInputPaths = [];\n collected.ogImageUrlMap.clear();\n for (const page of collected.pageResults) {\n collectOgImageEntry(context, page, collected);\n }\n}\n\nfunction remapPermalinkNav(context: BuildSsgContext, listedPages: PageProcessResult[]): void {\n if (!context.options.permalinks?.enabled) {\n return;\n }\n const usedManualNav =\n Boolean(context.ssgOptions.navigation) || Boolean(context.ssgOptions.theme?.sidebar.length);\n if (usedManualNav) {\n return;\n }\n\n context.navItems = remapNavGroups(\n buildNavItems(\n listedPages.map((page) => page.inputPath),\n context.srcDir,\n context.base,\n context.ssgOptions.extension,\n ),\n listedPages.map((page) => ({\n fileUrl: getUrlPath(page.inputPath, context.srcDir),\n urlPath: page.routePaths.urlPath,\n href: page.routePaths.href,\n })),\n [],\n );\n}\n\nasync function collectPageResults(\n context: BuildSsgContext,\n markdownFiles: string[],\n): Promise<CollectedPageResults> {\n const collected: CollectedPageResults = {\n pageResults: [],\n ogImageEntries: [],\n ogImageInputPaths: [],\n ogImageUrlMap: new Map(),\n errors: [],\n };\n\n for (const inputPath of markdownFiles) {\n try {\n const pageResult = await transformSsgPage(context, inputPath);\n collected.pageResults.push(pageResult);\n collectOgImageEntry(context, pageResult, collected);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n collected.errors.push(`Failed to process ${inputPath}: ${errorMessage}`);\n }\n }\n\n return collected;\n}\n\nfunction applyPublishState(\n context: BuildSsgContext,\n collected: CollectedPageResults,\n): { outputPages: PageProcessResult[]; listedPages: PageProcessResult[] } {\n const publishState = context.options.publishState;\n const { output, listed } = partitionPublishedPages(collected.pageResults, publishState);\n if (!publishState?.enabled) {\n return { outputPages: output, listedPages: listed };\n }\n\n const usedManualNav =\n Boolean(context.ssgOptions.navigation) || Boolean(context.ssgOptions.theme?.sidebar.length);\n if (usedManualNav) {\n context.navItems = filterNavGroups(\n context.navItems,\n hiddenNavKeys(collected.pageResults, listed),\n );\n } else {\n context.navItems = buildNavItems(\n listed.map((page) => page.inputPath),\n context.srcDir,\n context.base,\n context.ssgOptions.extension,\n );\n }\n\n const outputPaths = new Set(output.map((page) => page.inputPath));\n collected.ogImageEntries = collected.ogImageEntries.filter((_, index) =>\n outputPaths.has(collected.ogImageInputPaths[index] ?? \"\"),\n );\n collected.ogImageInputPaths = collected.ogImageInputPaths.filter((inputPath) =>\n outputPaths.has(inputPath),\n );\n for (const inputPath of collected.ogImageUrlMap.keys()) {\n if (!outputPaths.has(inputPath)) {\n collected.ogImageUrlMap.delete(inputPath);\n }\n }\n\n return { outputPages: output, listedPages: listed };\n}\n\nasync function transformSsgPage(\n context: BuildSsgContext,\n inputPath: string,\n): Promise<PageProcessResult> {\n const content = await fs.readFile(inputPath, \"utf-8\");\n const result = await transformMarkdown(content, inputPath, context.options, {\n convertMdLinks: true,\n baseUrl: context.base,\n sourcePath: inputPath,\n });\n const frontmatter = normalizeVitePressFrontmatter(result.frontmatter);\n const transformedHtml = await transformSsgHtml(result.html, context.options);\n const title = extractTitle(transformedHtml, frontmatter);\n\n return {\n inputPath,\n routePaths: getRoutePaths(\n inputPath,\n context.srcDir,\n context.outDir,\n context.base,\n context.ssgOptions.extension,\n context.ssgOptions.siteUrl,\n ),\n transformedHtml,\n title,\n description: frontmatter.description as string | undefined,\n lastUpdated: context.ssgOptions.lastUpdated\n ? (context.napi?.getGitLastUpdated(inputPath, context.root) ?? undefined)\n : undefined,\n contributors: contributorsForPage(context, inputPath),\n frontmatter,\n toc: result.toc,\n };\n}\n\nasync function transformSsgHtml(html: string, options: ResolvedOptions): Promise<string> {\n // Mermaid SVGs are protected before plugin transforms because some transforms\n // still use HTML parser/stringifier steps that can corrupt SVG foreignObject\n // markup. The protect/restore pair keeps the rest of the pipeline free to\n // operate on normal HTML strings.\n const { html: protectedHtml, svgs: mermaidSvgs } = protectMermaidSvgs(html);\n const pluginOptions: TransformAllOptions = {\n tabs: true,\n youtube: true,\n github: options.embeds.github,\n openGraph: options.embeds.openGraph,\n pm: options.embeds.pm,\n spotify: options.embeds.spotify,\n stackBlitz: options.embeds.stackBlitz,\n twitter: options.embeds.twitter,\n bluesky: options.embeds.bluesky,\n webContainer: options.embeds.webContainer,\n mermaid: true,\n githubToken: process.env.GITHUB_TOKEN,\n };\n\n let transformedHtml = await transformAllPlugins(protectedHtml, pluginOptions);\n if (hasIslands(transformedHtml)) {\n const islandResult = await transformIslands(transformedHtml);\n transformedHtml = islandResult.html;\n }\n\n return restoreMermaidSvgs(transformedHtml, mermaidSvgs);\n}\n\nfunction collectOgImageEntry(\n context: BuildSsgContext,\n pageResult: PageProcessResult,\n collected: CollectedPageResults,\n): void {\n if (!context.shouldGenerateOgImages) {\n return;\n }\n\n const { layout: _layout, ...frontmatterRest } = pageResult.frontmatter;\n collected.ogImageEntries.push({\n props: {\n ...frontmatterRest,\n title: pageResult.title,\n description: pageResult.description,\n siteName: context.siteName,\n },\n outputPath: pageResult.routePaths.ogImagePath,\n });\n collected.ogImageInputPaths.push(pageResult.inputPath);\n collected.ogImageUrlMap.set(pageResult.inputPath, pageResult.routePaths.ogImageUrl);\n}\n\nasync function generateOgImageAssets(\n context: BuildSsgContext,\n collected: CollectedPageResults,\n generatedFiles: string[],\n errors: string[],\n): Promise<void> {\n if (!context.shouldGenerateOgImages || collected.ogImageEntries.length === 0) {\n return;\n }\n\n try {\n const ogResults = await generateOgImages(\n collected.ogImageEntries,\n context.options.ogImageOptions,\n context.root,\n );\n if (clearMissingBrowserOgImages(ogResults, collected)) {\n return;\n }\n\n reportOgImageResults(ogResults, collected, generatedFiles, errors);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n console.warn(`[ox-content:og-image] Batch generation failed: ${errorMessage}`);\n collected.ogImageUrlMap.clear();\n }\n}\n\nfunction clearMissingBrowserOgImages(\n ogResults: Awaited<ReturnType<typeof generateOgImages>>,\n collected: CollectedPageResults,\n): boolean {\n const allMissingBrowser =\n ogResults.length > 0 && ogResults.every((result) => result.error === \"Chromium not available\");\n if (!allMissingBrowser) {\n return false;\n }\n\n for (const inputPath of collected.ogImageInputPaths) {\n collected.ogImageUrlMap.delete(inputPath);\n }\n return true;\n}\n\nfunction reportOgImageResults(\n ogResults: Awaited<ReturnType<typeof generateOgImages>>,\n collected: CollectedPageResults,\n generatedFiles: string[],\n errors: string[],\n): void {\n let ogSuccessCount = 0;\n\n for (let i = 0; i < ogResults.length; i++) {\n const result = ogResults[i];\n if (result.error) {\n errors.push(`OG image failed for ${result.outputPath}: ${result.error}`);\n collected.ogImageUrlMap.delete(collected.ogImageInputPaths[i]);\n } else {\n generatedFiles.push(result.outputPath);\n ogSuccessCount++;\n }\n }\n\n if (ogSuccessCount > 0) {\n const cachedCount = ogResults.filter((result) => result.cached && !result.error).length;\n console.log(\n `[ox-content:og-image] Generated ${ogSuccessCount} OG images` +\n (cachedCount > 0 ? ` (${cachedCount} from cache)` : \"\"),\n );\n }\n}\n\nasync function generateHtmlPages(\n context: BuildSsgContext,\n pageResults: PageProcessResult[],\n collected: CollectedPageResults,\n errors: string[],\n): Promise<GeneratedHtmlPage[]> {\n const generatedPages: GeneratedHtmlPage[] = [];\n\n for (const pageResult of pageResults) {\n try {\n generatedPages.push({\n inputPath: pageResult.inputPath,\n outputPath: pageResult.routePaths.outputPath,\n html: await renderSsgPage(context, pageResult, collected, pageResults),\n });\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n errors.push(`Failed to generate HTML for ${pageResult.inputPath}: ${errorMessage}`);\n }\n }\n\n return generatedPages;\n}\n\nasync function renderSsgPage(\n context: BuildSsgContext,\n pageResult: PageProcessResult,\n collected: CollectedPageResults,\n allPageResults: PageProcessResult[],\n): Promise<string> {\n const { ogImageUrlMap } = collected;\n const pageOgImage =\n context.shouldGenerateOgImages && ogImageUrlMap.has(pageResult.inputPath)\n ? ogImageUrlMap.get(pageResult.inputPath)\n : context.ssgOptions.ogImage;\n\n // A theme component owns the whole document, so it comes before both the\n // bare shell and the built-in renderer.\n if (context.ssgOptions.render) {\n const nav = context.versionNavigation\n ? rewriteVersionedNavGroups(context.navItems, context.versionNavigation)\n : context.navItems;\n return renderPage(toThemePageData(pageResult), {\n theme: context.ssgOptions.render,\n siteName: context.siteName,\n base: context.base,\n nav,\n pages: allPageResults.map(toThemePageData),\n });\n }\n\n if (context.ssgOptions.bare) {\n return generateBarePage({\n title: pageResult.title,\n content: pageResult.transformedHtml,\n lang:\n context.ssgOptions.lang ??\n getPageLocale(pageResult.routePaths.urlPath, context.options.i18n),\n description: pageResult.description,\n canonicalUrl: canonicalPageUrl(context, pageResult.routePaths.urlPath),\n siteName: context.ssgOptions.siteName,\n ogImage: pageOgImage,\n head: context.ssgOptions.head,\n bodyStart: context.ssgOptions.bodyStart,\n bodyEnd: context.ssgOptions.bodyEnd,\n });\n }\n\n const pageData = createSsgPageData(pageResult);\n const versionNavigation = context.versionNavigation;\n if (versionNavigation) {\n pageData.prev = rewritePagerOverride(pageData.prev, versionNavigation);\n pageData.next = rewritePagerOverride(pageData.next, versionNavigation);\n }\n\n const i18n = context.options.i18n;\n const pages = versionNavigation\n ? versionNavigation.pages\n : allPageResults.map((result) => ({\n path: result.routePaths.urlPath,\n href: result.routePaths.href,\n }));\n const localePath = versionNavigation\n ? unversionedPath(pageData.path, versionNavigation)\n : pageData.path;\n const locale = getPageLocale(localePath, i18n);\n const localeNav =\n i18n && locale\n ? {\n locale,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages,\n base: context.base,\n }\n : undefined;\n const localizedNav = localeNav\n ? localizeNavGroups(context.navItems, localeNav)\n : context.navItems;\n const navItems = versionNavigation\n ? rewriteVersionedNavGroups(localizedNav, versionNavigation)\n : localizedNav;\n const localizedTheme = context.ssgOptions.theme\n ? localeNav\n ? {\n ...context.ssgOptions.theme,\n nav: localizeHeaderNavItems(context.ssgOptions.theme.nav, localeNav),\n }\n : context.ssgOptions.theme\n : undefined;\n const theme =\n localizedTheme && versionNavigation\n ? {\n ...localizedTheme,\n nav: rewriteVersionedHeaderNavItems(localizedTheme.nav, versionNavigation),\n }\n : localizedTheme;\n const localePaths =\n context.ssgOptions.localeSwitcher && i18n\n ? buildLocalePaths({\n currentPath: localePath,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages,\n base: context.base,\n roots: versionNavigation\n ? versionedLocaleRoots(\n versionNavigation,\n i18n.locales,\n i18n.defaultLocale,\n i18n.hideDefaultLocale,\n )\n : undefined,\n })\n : undefined;\n\n return generateHtmlPage(\n pageData,\n navItems,\n context.siteName,\n context.base,\n pageOgImage,\n theme,\n locale,\n i18n ? i18n.locales : undefined,\n context.ssgOptions.pagination,\n context.ssgOptions.readerChrome,\n context.ssgOptions.breadcrumbs,\n context.ssgOptions.localeSwitcher,\n localePaths,\n context.ssgOptions.a11y,\n context.ssgOptions.team ?? { enabled: false, members: [] },\n context.ssgOptions.pageChrome,\n versionNavigation?.root.href,\n context.ssgOptions.jsonLd,\n context.ssgOptions.siteUrl,\n );\n}\n\nfunction rewritePagerOverride(\n pager: SsgPagerOverride | undefined,\n context: VersionNavigationContext,\n): SsgPagerOverride | undefined {\n return pager?.href ? { ...pager, href: rewriteVersionedHref(pager.href, context) } : pager;\n}\n\n/** Maps an internal page result onto the theme renderer's page shape. */\nfunction toThemePageData(pageResult: PageProcessResult): ThemePageData {\n return {\n title: pageResult.title,\n description: pageResult.description,\n html: pageResult.transformedHtml,\n toc: pageResult.toc,\n lastUpdated: pageResult.lastUpdated,\n contributors: pageResult.contributors,\n path: pageResult.inputPath,\n url: pageResult.routePaths.href,\n frontmatter: pageResult.frontmatter,\n layout:\n typeof pageResult.frontmatter.layout === \"string\" ? pageResult.frontmatter.layout : undefined,\n };\n}\n\n/**\n * Absolute URL of a page, or `undefined` when `ssg.siteUrl` is not set.\n *\n * Built the same way `get_og_image_url` builds the image URL next to it, so\n * the canonical link and `og:image` always agree about where the page lives.\n */\nfunction canonicalPageUrl(context: BuildSsgContext, urlPath: string): string | undefined {\n const siteUrl = context.ssgOptions.siteUrl?.replace(/\\/+$/, \"\");\n if (!siteUrl) {\n return undefined;\n }\n if (urlPath === \"/\" || urlPath === \"\") {\n return `${siteUrl}${context.base}`;\n }\n return `${siteUrl}${context.base}${urlPath}/`;\n}\n\nfunction createSsgPageData(pageResult: PageProcessResult): SsgPageData {\n const { frontmatter } = pageResult;\n const entryPage =\n frontmatter.layout === \"entry\"\n ? {\n hero: frontmatter.hero as HeroConfig | undefined,\n features: frontmatter.features as FeatureConfig[] | undefined,\n }\n : undefined;\n\n return {\n title: pageResult.title,\n description: pageResult.description,\n content: pageResult.transformedHtml,\n toc: pageResult.toc,\n lastUpdated: pageResult.lastUpdated,\n contributors: pageResult.contributors,\n frontmatter,\n path: pageResult.routePaths.urlPath,\n href: pageResult.routePaths.href,\n entryPage,\n prev: parseSsgPagerOverride(frontmatter.prev),\n next: parseSsgPagerOverride(frontmatter.next),\n breadcrumbs: frontmatter.breadcrumbs === false ? false : undefined,\n chrome: parsePageChromeFlags(frontmatter),\n };\n}\n\nasync function appendNotFoundPage(\n generatedPages: GeneratedHtmlPage[],\n context: BuildSsgContext,\n collected: CollectedPageResults,\n errors: string[],\n): Promise<void> {\n const notFound = context.ssgOptions.notFound;\n if (!notFound?.enabled) {\n return;\n }\n\n const sourcePath = resolveNotFoundSourcePath(context.srcDir, notFound.source);\n const outputPath = resolveNotFoundOutputPath(context.outDir, notFound.output);\n\n try {\n const markdown = (await fileExists(sourcePath))\n ? await fs.readFile(sourcePath, \"utf8\")\n : FALLBACK_NOT_FOUND_MARKDOWN;\n const pageResult = await transformNotFoundMarkdown(context, sourcePath, markdown);\n pageResult.routePaths = { ...pageResult.routePaths, outputPath, urlPath: \"\" };\n generatedPages.push({\n inputPath: sourcePath,\n outputPath,\n html: await renderSsgPage(context, pageResult, collected, collected.pageResults),\n });\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n errors.push(`Failed to generate 404 page: ${errorMessage}`);\n }\n}\n\nasync function fileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function transformNotFoundMarkdown(\n context: BuildSsgContext,\n inputPath: string,\n markdown: string,\n): Promise<PageProcessResult> {\n const result = await transformMarkdown(markdown, inputPath, context.options, {\n convertMdLinks: true,\n baseUrl: context.base,\n // The page is written at the output root (`404.html`), so relative links\n // must resolve as if authored by that root's index page.\n sourcePath: path.join(context.srcDir, \"index.md\"),\n });\n const frontmatter = normalizeVitePressFrontmatter(result.frontmatter);\n const transformedHtml = await transformSsgHtml(result.html, context.options);\n\n return {\n inputPath,\n routePaths: {\n outputPath: inputPath,\n urlPath: \"\",\n href: `${context.base}${context.ssgOptions.notFound?.output ?? \"404.html\"}`,\n ogImagePath: \"\",\n ogImageUrl: \"\",\n },\n transformedHtml,\n title: extractTitle(transformedHtml, frontmatter),\n description: typeof frontmatter.description === \"string\" ? frontmatter.description : undefined,\n frontmatter,\n toc: result.toc,\n };\n}\n\nasync function applyDocumentationVersions(\n generatedPages: GeneratedHtmlPage[],\n context: BuildSsgContext,\n errors: string[],\n): Promise<void> {\n const versions = context.options.versions;\n if (!versions?.enabled) {\n return;\n }\n for (const entry of snapshotEntries(versions)) {\n const snapSrc = resolveSnapshotDir(context.root, entry.dir ?? \"\");\n if (!snapSrc) {\n continue;\n }\n const files = await collectMarkdownFiles(snapSrc, context.options.extensions);\n if (files.length === 0) {\n continue;\n }\n const snapContext = await createBuildSsgContext(\n context.options,\n context.root,\n snapSrc,\n context.outDir,\n files,\n );\n const snapCollected = await collectPageResults(snapContext, files);\n applyPermalinkRoutes(snapContext, snapCollected);\n errors.push(...snapCollected.errors);\n const { outputPages, listedPages } = applyPublishState(snapContext, snapCollected);\n remapPermalinkNav(snapContext, listedPages);\n const unversionedRoutes = new Map(\n snapCollected.pageResults.map((page) => [page.inputPath, { ...page.routePaths }]),\n );\n for (const page of snapCollected.pageResults) {\n page.routePaths = {\n ...page.routePaths,\n ...prefixRoutePaths(page.routePaths, entry.prefix, context.outDir, context.base),\n };\n }\n snapContext.versionNavigation = createVersionNavigationContext({\n prefix: entry.prefix,\n base: context.base,\n pages: listedPages.flatMap((page) => {\n const route = unversionedRoutes.get(page.inputPath);\n return route\n ? [\n {\n path: route.urlPath,\n versionedPath: page.routePaths.urlPath,\n href: page.routePaths.href,\n sourcePath: getUrlPath(page.inputPath, snapContext.srcDir),\n aliases: pageAliases(page.frontmatter),\n },\n ]\n : [];\n }),\n redirects: snapContext.options.redirects?.map,\n });\n const snapPages = await generateHtmlPages(snapContext, outputPages, snapCollected, errors);\n await appendSectionIndexPages({\n generatedPages: snapPages,\n collectedPages: snapCollected.pageResults,\n listedPages,\n options: snapContext.ssgOptions.sectionIndex,\n outDir: snapContext.outDir,\n base: snapContext.base,\n extension: snapContext.ssgOptions.extension,\n errors,\n render: (page) =>\n renderSsgPage(snapContext, toSectionIndexProcessResult(page), snapCollected, listedPages),\n });\n generatedPages.push(...snapPages);\n if (context.options.search?.enabled) {\n try {\n await writeSnapshotSearchIndex({\n srcDir: snapSrc,\n outDir: context.outDir,\n prefix: entry.prefix,\n base: context.base,\n extensions: context.options.extensions,\n publishState: context.options.publishState,\n mdx: context.options.mdx,\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n errors.push(`Failed to write search index for ${entry.id}: ${message}`);\n }\n }\n }\n decorateVersionedPages(generatedPages, versions, context.outDir, context.base);\n}\n\nfunction pageAliases(frontmatter: Record<string, unknown>): string[] {\n const aliases = frontmatter.aliases;\n const values = typeof aliases === \"string\" ? [aliases] : Array.isArray(aliases) ? aliases : [];\n const resolved = values.filter((value): value is string => typeof value === \"string\");\n return typeof frontmatter.redirect === \"string\" ? [...resolved, frontmatter.redirect] : resolved;\n}\n\nasync function writeGeneratedPages(\n generatedPages: GeneratedHtmlPage[],\n context: BuildSsgContext,\n generatedFiles: string[],\n listedPages: PageProcessResult[],\n outputPages: PageProcessResult[],\n errors: string[],\n): Promise<void> {\n // Shared asset extraction needs the complete page set to maximize\n // de-duplication. Only after replacement do we write pages and record both\n // the generated assets and the rewritten HTML files.\n const optimizedOutput = await externalizeSharedPageAssets(\n generatedPages,\n context.outDir,\n context.base,\n );\n generatedFiles.push(...optimizedOutput.assets);\n\n const pwa = await writePwaFiles({\n outDir: context.outDir,\n siteUrl: context.ssgOptions.siteUrl,\n base: context.base,\n siteName: context.siteName,\n options: context.options.pwa,\n });\n generatedFiles.push(...pwa.files);\n if (pwa.warning) {\n errors.push(pwa.warning);\n console.warn(pwa.warning);\n } else if (!context.ssgOptions.bare && context.options.pwa?.enabled) {\n for (const page of optimizedOutput.pages) {\n page.html = injectPwaPageTags(page.html, {\n options: context.options.pwa,\n base: context.base,\n });\n }\n }\n\n for (const page of optimizedOutput.pages) {\n await fs.mkdir(path.dirname(page.outputPath), { recursive: true });\n await fs.writeFile(page.outputPath, page.html, \"utf-8\");\n generatedFiles.push(page.outputPath);\n }\n\n const siteMaps = await writeSiteMapFiles({\n outDir: context.outDir,\n siteUrl: context.ssgOptions.siteUrl,\n base: context.base,\n siteName: context.siteName,\n options: context.options.siteMaps,\n pages: sitemapPages(context, listedPages, outputPages),\n });\n generatedFiles.push(...siteMaps.files);\n if (siteMaps.warning) {\n errors.push(siteMaps.warning);\n console.warn(siteMaps.warning);\n }\n\n const redirects = await writeRedirectFiles({\n outDir: context.outDir,\n base: context.base,\n options: context.options.redirects,\n pages: outputPages.map((page) => ({\n dest: sitePathFromUrlPath(page.routePaths.urlPath),\n aliases: page.frontmatter.aliases,\n redirect: page.frontmatter.redirect,\n })),\n });\n generatedFiles.push(...redirects.files);\n\n const feeds = await writeFeedFiles({\n outDir: context.outDir,\n siteUrl: context.ssgOptions.siteUrl,\n base: context.base,\n siteName: context.siteName,\n options: context.options.feeds,\n publishState: context.options.publishState,\n collectionNames: Object.keys(context.options.collections?.collections ?? {}),\n collections: context.options.feeds?.enabled\n ? (await buildCollectionManifest(context.root, context.options)).collections\n : undefined,\n });\n generatedFiles.push(...feeds.files);\n if (feeds.warning) {\n errors.push(feeds.warning);\n console.warn(feeds.warning);\n }\n}\n\n/** Turns an SSG `urlPath` (`guide` or `/`) into a same-origin dest (`/guide`). */\nfunction sitePathFromUrlPath(urlPath: string): string {\n if (!urlPath || urlPath === \"/\") {\n return \"/\";\n }\n return urlPath.startsWith(\"/\") ? urlPath : `/${urlPath}`;\n}\n\nfunction sitemapPages(\n context: BuildSsgContext,\n listedPages: PageProcessResult[],\n outputPages: PageProcessResult[],\n): Array<{ loc: string; title: string; description?: string; draft: boolean; unlisted: boolean }> {\n const pages = context.options.publishState?.enabled ? listedPages : outputPages;\n const listedPaths = new Set(listedPages.map((page) => page.inputPath));\n return pages.map((page) => ({\n loc: canonicalPageUrl(context, page.routePaths.urlPath) ?? \"\",\n title: page.title,\n description: page.description,\n draft: page.frontmatter.draft === true,\n unlisted: Boolean(context.options.publishState?.enabled) && !listedPaths.has(page.inputPath),\n }));\n}\n","/**\n * Dev server middleware for ox-content SSG.\n *\n * Serves fully-rendered HTML pages (with navigation, theme, etc.)\n * during `vite dev`, matching the SSG build output.\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport type { Connect } from \"vite\";\nimport { transformMarkdown } from \"./transform\";\nimport { transformAllPlugins } from \"./plugins\";\nimport { resetTabGroupCounter } from \"./plugins\";\nimport { protectMermaidSvgs, restoreMermaidSvgs } from \"./plugins/mermaid-protect\";\nimport { transformIslands, hasIslands, resetIslandCounter } from \"./island\";\nimport {\n collectMarkdownFiles,\n buildNavItems,\n buildThemeNavItems,\n extractTitle,\n getUrlPath,\n getHref,\n generateHtmlPage,\n getPageLocale,\n formatTitle,\n parseSsgPagerOverride,\n resolveNavigationGroups,\n} from \"./ssg\";\nimport type { NavGroup, SsgPageData, SsgEntryPageConfig } from \"./ssg\";\nimport type { ResolvedOptions } from \"./types\";\nimport type { HeroConfig, FeatureConfig } from \"./types\";\nimport { normalizeVitePressFrontmatter } from \"./vitepress\";\nimport { parsePageChromeFlags } from \"./header-chrome\";\nimport { buildLocalePaths } from \"./locale-switcher\";\nimport { localizeHeaderNavItems, localizeNavGroups } from \"./locale-nav\";\nimport { isMarkdownFilePath } from \"./markdown\";\n\n/** File extensions to skip in the middleware. */\nconst SKIP_EXTENSIONS = new Set([\n \".js\",\n \".ts\",\n \".css\",\n \".scss\",\n \".less\",\n \".svg\",\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".gif\",\n \".webp\",\n \".ico\",\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".eot\",\n \".json\",\n \".map\",\n \".mp4\",\n \".webm\",\n \".mp3\",\n \".pdf\",\n]);\n\n/** Vite internal URL prefixes to skip. */\nconst VITE_INTERNAL_PREFIXES = [\"/@vite/\", \"/@fs/\", \"/@id/\", \"/__\"];\n\n/**\n * Check if a request URL should be skipped by the dev server middleware.\n */\nfunction shouldSkip(url: string): boolean {\n // Skip Vite internal URLs\n for (const prefix of VITE_INTERNAL_PREFIXES) {\n if (url.startsWith(prefix)) return true;\n }\n\n // Skip node_modules\n if (url.includes(\"/node_modules/\")) return true;\n\n // Skip requests with known static file extensions\n const extMatch = url.match(/\\.([a-zA-Z0-9]+)(?:\\?|$)/);\n if (extMatch) {\n const ext = \".\" + extMatch[1].toLowerCase();\n if (SKIP_EXTENSIONS.has(ext)) return true;\n }\n\n return false;\n}\n\n/**\n * Resolve a request URL to a markdown file path.\n * Returns null if no matching file exists.\n */\nasync function resolveMarkdownFile(\n url: string,\n srcDir: string,\n extensions: readonly string[],\n): Promise<string | null> {\n // Remove query string and hash\n let pathname = url.split(\"?\")[0].split(\"#\")[0];\n\n // Remove trailing /index.html\n if (pathname.endsWith(\"/index.html\")) {\n pathname = pathname.slice(0, -\"/index.html\".length) || \"/\";\n }\n\n // Remove trailing slash (except for root)\n if (pathname !== \"/\" && pathname.endsWith(\"/\")) {\n pathname = pathname.slice(0, -1);\n }\n\n const routePath = pathname === \"/\" ? \"\" : pathname.slice(1);\n const directCandidates =\n pathname === \"/\"\n ? extensions.map((extension) => `index${extension}`)\n : isMarkdownFilePath(routePath, extensions)\n ? [routePath]\n : extensions.map((extension) => `${routePath}${extension}`);\n\n for (const relativePath of directCandidates) {\n const filePath = path.join(srcDir, relativePath);\n try {\n await fs.access(filePath);\n return filePath;\n } catch {\n // Try the next extension.\n }\n }\n\n for (const extension of extensions) {\n const indexPath = path.join(srcDir, routePath, `index${extension}`);\n try {\n await fs.access(indexPath);\n return indexPath;\n } catch {\n // Try the next extension.\n }\n }\n\n return null;\n}\n\n/**\n * Inject Vite HMR client script into the HTML.\n */\nfunction injectViteHmrClient(html: string): string {\n const hmrScript = `<script type=\"module\" src=\"/@vite/client\"></script>\n<script type=\"module\">\nif (import.meta.hot) {\n const reexecuteBodyScripts = () => {\n const scripts = Array.from(document.body.querySelectorAll('script'));\n for (const script of scripts) {\n const nextScript = document.createElement('script');\n for (const attr of script.attributes) {\n nextScript.setAttribute(attr.name, attr.value);\n }\n nextScript.textContent = script.textContent;\n script.replaceWith(nextScript);\n }\n };\n\n const applyHotUpdate = async () => {\n const nextUrl = new URL(window.location.href);\n nextUrl.searchParams.set('__ox_hmr', String(Date.now()));\n\n const scrollX = window.scrollX;\n const scrollY = window.scrollY;\n const theme = document.documentElement.getAttribute('data-theme');\n\n const response = await fetch(nextUrl.toString(), {\n cache: 'no-store',\n headers: {\n 'x-ox-content-hmr': '1',\n },\n });\n\n if (!response.ok) {\n throw new Error('Failed to fetch updated page');\n }\n\n const nextHtml = await response.text();\n const nextDocument = new DOMParser().parseFromString(nextHtml, 'text/html');\n\n if (!nextDocument.body) {\n throw new Error('Updated page is missing a body');\n }\n\n document.title = nextDocument.title;\n document.body.innerHTML = nextDocument.body.innerHTML;\n reexecuteBodyScripts();\n\n if (theme) {\n document.documentElement.setAttribute('data-theme', theme);\n }\n\n window.scrollTo({ left: scrollX, top: scrollY });\n };\n\n let pendingUpdate = Promise.resolve();\n\n import.meta.hot.on('ox-content:update', () => {\n pendingUpdate = pendingUpdate\n .then(() => applyHotUpdate())\n .catch((error) => {\n console.warn('[ox-content] HMR patch failed, falling back to reload.', error);\n location.reload();\n });\n });\n}\n</script>`;\n\n return html.replace(\"</head>\", hmrScript + \"\\n</head>\");\n}\n\n/**\n * Dev server state for caching.\n */\ninterface DevServerCache {\n /** Cached navigation groups. Invalidated on file add/unlink. */\n navGroups: NavGroup[] | null;\n /** Cached urlPath → href pairs for locale sibling lookup. */\n localePages: Array<{ path: string; href: string }> | null;\n /** Cached rendered HTML keyed by absolute file path. */\n pages: Map<string, string>;\n /** Cached site name. Computed once. */\n siteName: string | null;\n}\n\n/**\n * Create a dev server cache instance.\n */\nexport function createDevServerCache(): DevServerCache {\n return {\n navGroups: null,\n localePages: null,\n pages: new Map(),\n siteName: null,\n };\n}\n\n/**\n * Invalidate navigation cache (called on file add/unlink).\n */\nexport function invalidateNavCache(cache: DevServerCache): void {\n cache.navGroups = null;\n cache.localePages = null;\n // Also clear all page caches since navigation HTML is embedded in pages\n cache.pages.clear();\n}\n\n/**\n * Invalidate page cache for a specific file (called on file change).\n */\nexport function invalidatePageCache(cache: DevServerCache, filePath: string): void {\n cache.pages.delete(filePath);\n}\n\n/**\n * Resolve site name from options or package.json.\n */\nasync function resolveSiteName(options: ResolvedOptions, root: string): Promise<string> {\n if (options.ssg.siteName) {\n return options.ssg.siteName;\n }\n\n try {\n const pkgPath = path.join(root, \"package.json\");\n const pkg = JSON.parse(await fs.readFile(pkgPath, \"utf-8\"));\n if (pkg.name) {\n return formatTitle(pkg.name);\n }\n } catch {\n // Use default\n }\n\n return \"Documentation\";\n}\n\n/**\n * Render a single markdown page to full HTML.\n */\nasync function renderPage(\n filePath: string,\n options: ResolvedOptions,\n navGroups: NavGroup[],\n siteName: string,\n base: string,\n root: string,\n localePages: Array<{ path: string; href: string }>,\n): Promise<string> {\n const srcDir = path.resolve(root, options.srcDir);\n\n // Reset counters for clean render\n resetTabGroupCounter();\n resetIslandCounter();\n\n // Read markdown content\n const content = await fs.readFile(filePath, \"utf-8\");\n\n // Transform markdown to HTML\n const result = await transformMarkdown(content, filePath, options, {\n convertMdLinks: true,\n baseUrl: base,\n sourcePath: filePath,\n });\n const frontmatter = normalizeVitePressFrontmatter(result.frontmatter);\n\n let transformedHtml = result.html;\n\n // Protect mermaid SVGs from rehype processing\n const { html: protectedHtml, svgs: mermaidSvgs } = protectMermaidSvgs(transformedHtml);\n transformedHtml = protectedHtml;\n\n // Transform all plugins\n transformedHtml = await transformAllPlugins(transformedHtml, {\n tabs: true,\n youtube: true,\n github: options.embeds.github,\n openGraph: options.embeds.openGraph,\n pm: options.embeds.pm,\n spotify: options.embeds.spotify,\n stackBlitz: options.embeds.stackBlitz,\n twitter: options.embeds.twitter,\n bluesky: options.embeds.bluesky,\n webContainer: options.embeds.webContainer,\n mermaid: true,\n githubToken: process.env.GITHUB_TOKEN,\n });\n\n // Transform Island components\n if (hasIslands(transformedHtml)) {\n const islandResult = await transformIslands(transformedHtml);\n transformedHtml = islandResult.html;\n }\n\n // Restore protected mermaid SVGs\n transformedHtml = restoreMermaidSvgs(transformedHtml, mermaidSvgs);\n\n // Extract title\n const title = extractTitle(transformedHtml, frontmatter);\n const description = frontmatter.description as string | undefined;\n\n // Check if this is an entry page\n let entryPage: SsgEntryPageConfig | undefined;\n if (frontmatter.layout === \"entry\") {\n entryPage = {\n hero: frontmatter.hero as HeroConfig | undefined,\n features: frontmatter.features as FeatureConfig[] | undefined,\n };\n }\n\n // Build page data\n const pageData: SsgPageData = {\n title,\n description,\n content: transformedHtml,\n toc: result.toc,\n frontmatter,\n path: getUrlPath(filePath, srcDir),\n href: getUrlPath(filePath, srcDir) || \"/\",\n entryPage,\n prev: parseSsgPagerOverride(frontmatter.prev),\n next: parseSsgPagerOverride(frontmatter.next),\n breadcrumbs: frontmatter.breadcrumbs === false ? false : undefined,\n chrome: parsePageChromeFlags(frontmatter),\n };\n\n const i18n = options.i18n;\n const locale = getPageLocale(pageData.path, i18n);\n const localeNav =\n i18n && locale\n ? {\n locale,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages: localePages,\n base,\n }\n : undefined;\n const localizedNav = localeNav ? localizeNavGroups(navGroups, localeNav) : navGroups;\n const theme = options.ssg.theme\n ? localeNav\n ? {\n ...options.ssg.theme,\n nav: localizeHeaderNavItems(options.ssg.theme.nav, localeNav),\n }\n : options.ssg.theme\n : undefined;\n const localePaths =\n options.ssg.localeSwitcher && i18n\n ? buildLocalePaths({\n currentPath: pageData.path,\n locales: i18n.locales,\n defaultLocale: i18n.defaultLocale,\n hideDefaultLocale: i18n.hideDefaultLocale,\n pages: localePages,\n base,\n })\n : undefined;\n\n // Generate full HTML page\n let html = await generateHtmlPage(\n pageData,\n localizedNav,\n siteName,\n base,\n options.ssg.ogImage,\n theme,\n locale,\n i18n ? i18n.locales : undefined,\n options.ssg.pagination,\n options.ssg.readerChrome,\n options.ssg.breadcrumbs,\n options.ssg.localeSwitcher,\n localePaths,\n options.ssg.a11y,\n options.ssg.team ?? { enabled: false, members: [] },\n options.ssg.pageChrome,\n undefined,\n options.ssg.jsonLd,\n options.ssg.siteUrl,\n );\n\n // Inject Vite HMR client for live reload\n html = injectViteHmrClient(html);\n\n return html;\n}\n\n/**\n * Create the dev server middleware for SSG page serving.\n */\nexport function createDevServerMiddleware(\n options: ResolvedOptions,\n root: string,\n cache: DevServerCache,\n): Connect.NextHandleFunction {\n const srcDir = path.resolve(root, options.srcDir);\n const base = options.base.endsWith(\"/\") ? options.base : options.base + \"/\";\n\n return async (req, res, next) => {\n const url = req.url;\n if (!url) return next();\n\n // Strip base from URL for routing\n let routeUrl = url;\n if (base !== \"/\" && routeUrl.startsWith(base)) {\n routeUrl = \"/\" + routeUrl.slice(base.length);\n }\n\n // Skip non-page requests\n if (shouldSkip(routeUrl)) return next();\n\n // Resolve markdown file\n const filePath = await resolveMarkdownFile(routeUrl, srcDir, options.extensions);\n if (!filePath) return next();\n\n try {\n // Check page cache\n const cached = cache.pages.get(filePath);\n if (cached) {\n res.setHeader(\"Content-Type\", \"text/html\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.end(cached);\n return;\n }\n\n // Resolve site name (cached after first call)\n if (!cache.siteName) {\n cache.siteName = await resolveSiteName(options, root);\n }\n\n // Build navigation if not cached\n if (!cache.navGroups || !cache.localePages) {\n const markdownFiles = await collectMarkdownFiles(srcDir, options.extensions);\n cache.localePages = markdownFiles.map((file) => ({\n path: getUrlPath(file, srcDir),\n href: getHref(file, srcDir, base, options.ssg.extension),\n }));\n cache.navGroups =\n resolveNavigationGroups(options.ssg.navigation, base, options.ssg.extension) ??\n (options.ssg.theme?.sidebar.length\n ? buildThemeNavItems(options.ssg.theme.sidebar, base, options.ssg.extension)\n : buildNavItems(markdownFiles, srcDir, base, options.ssg.extension));\n }\n\n const navGroups = cache.navGroups;\n const localePages = cache.localePages;\n if (!navGroups || !localePages) {\n return next();\n }\n\n // Render the page\n const html = await renderPage(\n filePath,\n options,\n navGroups,\n cache.siteName,\n base,\n root,\n localePages,\n );\n\n // Cache the result\n cache.pages.set(filePath, html);\n\n res.setHeader(\"Content-Type\", \"text/html\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.end(html);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.error(`[ox-content:dev] Failed to render ${filePath}:`, message);\n next();\n }\n };\n}\n","/**\n * OG Viewer - Dev tool for previewing Open Graph metadata\n *\n * Accessible at /__og-viewer during development.\n * Shows all pages with their OG metadata, validation warnings,\n * and social card previews.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { glob } from \"glob\";\nimport type { Plugin } from \"vite\";\nimport type { ResolvedOptions } from \"./types\";\nimport { normalizeVitePressFrontmatter } from \"./vitepress\";\nimport { markdownGlobPattern, stripMarkdownExtension } from \"./markdown\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\ninterface PageOgData {\n path: string;\n urlPath: string;\n title: string;\n description: string;\n author: string;\n tags: string[];\n ogImageUrl: string;\n warnings: { level: \"error\" | \"warning\"; message: string }[];\n}\n\n// =============================================================================\n// Data Collection\n// =============================================================================\n\nfunction parseFrontmatter(content: string): Record<string, unknown> {\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (!match) return {};\n\n const yaml = match[1];\n const result: Record<string, unknown> = {};\n\n for (const line of yaml.split(\"\\n\")) {\n const kv = line.match(/^(\\w[\\w-]*):\\s*(.*)$/);\n if (!kv) continue;\n const [, key, rawValue] = kv;\n let value: unknown = rawValue.trim();\n\n // Handle arrays (simple inline: [a, b])\n if (typeof value === \"string\" && value.startsWith(\"[\") && value.endsWith(\"]\")) {\n value = value\n .slice(1, -1)\n .split(\",\")\n .map((s) => s.trim().replace(/^['\"]|['\"]$/g, \"\"))\n .filter(Boolean);\n }\n // Strip quotes\n else if (typeof value === \"string\" && /^['\"].*['\"]$/.test(value)) {\n value = value.slice(1, -1);\n }\n // Booleans\n else if (value === \"true\") value = true;\n else if (value === \"false\") value = false;\n\n result[key] = value;\n }\n\n return result;\n}\n\nfunction extractTitle(content: string, frontmatter: Record<string, unknown>): string {\n if (typeof frontmatter.title === \"string\" && frontmatter.title) {\n return frontmatter.title;\n }\n // Fallback: first # heading\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1].trim() : \"\";\n}\n\nfunction getUrlPath(filePath: string, srcDir: string, extensions: readonly string[]): string {\n let rel = path.relative(srcDir, filePath).replace(/\\\\/g, \"/\");\n rel = stripMarkdownExtension(rel, extensions);\n if (rel === \"index\") return \"/\";\n if (rel.endsWith(\"/index\")) rel = rel.slice(0, -\"/index\".length);\n return \"/\" + rel;\n}\n\nfunction computeOgImageUrl(\n urlPath: string,\n base: string,\n siteUrl?: string,\n generateOgImage?: boolean,\n staticOgImage?: string,\n): string {\n if (!generateOgImage) return staticOgImage || \"\";\n\n const cleanBase = base.endsWith(\"/\") ? base : base + \"/\";\n let relativePath: string;\n if (urlPath === \"/\") {\n relativePath = `${cleanBase}og-image.png`;\n } else {\n relativePath = `${cleanBase}${urlPath.replace(/^\\//, \"\")}/og-image.png`;\n }\n\n if (siteUrl) {\n const cleanSiteUrl = siteUrl.replace(/\\/$/, \"\");\n return `${cleanSiteUrl}${relativePath}`;\n }\n return relativePath;\n}\n\nfunction validatePage(\n page: { title: string; description: string; ogImageUrl: string },\n options: ResolvedOptions,\n): { level: \"error\" | \"warning\"; message: string }[] {\n const warnings: { level: \"error\" | \"warning\"; message: string }[] = [];\n\n if (!page.title) {\n warnings.push({ level: \"error\", message: \"title is missing\" });\n } else if (page.title.length > 70) {\n warnings.push({ level: \"warning\", message: `title is too long (${page.title.length}/70)` });\n }\n\n if (!page.description) {\n warnings.push({ level: \"warning\", message: \"description is missing\" });\n } else if (page.description.length > 200) {\n warnings.push({\n level: \"warning\",\n message: `description is too long (${page.description.length}/200)`,\n });\n }\n\n const generateOgImage = options.ogImage || options.ssg.generateOgImage;\n if (generateOgImage && !options.ssg.siteUrl) {\n warnings.push({ level: \"warning\", message: \"ogImage enabled but siteUrl is not set\" });\n }\n\n return warnings;\n}\n\nasync function collectPages(options: ResolvedOptions, root: string): Promise<PageOgData[]> {\n const srcDir = path.resolve(root, options.srcDir);\n const files = await glob(markdownGlobPattern(srcDir, options.extensions), { absolute: true });\n\n const pages: PageOgData[] = [];\n const generateOgImage = options.ogImage || options.ssg.generateOgImage;\n\n for (const file of files.sort()) {\n const content = fs.readFileSync(file, \"utf-8\");\n const frontmatter = normalizeVitePressFrontmatter(parseFrontmatter(content));\n\n // Skip entry layout pages (they are landing pages, not content pages)\n if (frontmatter.layout === \"entry\") continue;\n\n const title = extractTitle(content, frontmatter);\n const description = typeof frontmatter.description === \"string\" ? frontmatter.description : \"\";\n const author = typeof frontmatter.author === \"string\" ? frontmatter.author : \"\";\n const tags = Array.isArray(frontmatter.tags)\n ? (frontmatter.tags as string[])\n : typeof frontmatter.tags === \"string\"\n ? [frontmatter.tags]\n : [];\n\n const urlPath = getUrlPath(file, srcDir, options.extensions);\n const ogImageUrl = computeOgImageUrl(\n urlPath,\n options.base,\n options.ssg.siteUrl,\n generateOgImage,\n options.ssg.ogImage,\n );\n\n const page = {\n path: path.relative(srcDir, file),\n urlPath,\n title,\n description,\n author,\n tags,\n ogImageUrl,\n warnings: [] as PageOgData[\"warnings\"],\n };\n page.warnings = validatePage(page, options);\n pages.push(page);\n }\n\n return pages;\n}\n\n// =============================================================================\n// HTML Rendering\n// =============================================================================\n\nfunction renderViewerHtml(pages: PageOgData[], options: ResolvedOptions): string {\n const generateOgImage = options.ogImage || options.ssg.generateOgImage;\n const totalWarnings = pages.reduce(\n (sum, p) => sum + p.warnings.filter((w) => w.level === \"warning\").length,\n 0,\n );\n const totalErrors = pages.reduce(\n (sum, p) => sum + p.warnings.filter((w) => w.level === \"error\").length,\n 0,\n );\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>OG Viewer - ox-content</title>\n <style>\n :root {\n --bg: #ffffff;\n --bg-card: #f5f7fb;\n --bg-preview: #ffffff;\n --text: #131a30;\n --text-muted: #4f607b;\n --border: #d2dbea;\n --accent: #4f6fae;\n --accent-light: #eef2fa;\n --error: #dc2626;\n --error-bg: #fef2f2;\n --warning: #d97706;\n --warning-bg: #fffbeb;\n --success: #16a34a;\n --tag-bg: #ecf3ff;\n --radius: 16px;\n }\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: #060816;\n --bg-card: #0d1528;\n --bg-preview: #10172d;\n --text: #ebf2ff;\n --text-muted: #8ea0bf;\n --border: #223252;\n --accent: #86a4da;\n --accent-light: #151730;\n --error: #f87171;\n --error-bg: #450a0a;\n --warning: #fbbf24;\n --warning-bg: #451a03;\n --success: #4ade80;\n --tag-bg: #131b33;\n }\n }\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { font-family: 'IBM Plex Sans', 'Avenir Next', 'Segoe UI', system-ui, sans-serif; background: radial-gradient(circle at top left, rgba(79,111,174,0.10), transparent 24%), radial-gradient(circle at 85% 14%, rgba(145,237,233,0.08), transparent 22%), var(--bg); color: var(--text); }\n .header { padding: 16px 24px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; }\n .header svg { width: 28px; height: 28px; color: var(--accent); }\n .header h1 { font-size: 18px; font-weight: 600; }\n .header h1 span { color: var(--text-muted); font-weight: 400; }\n .header-actions { margin-left: auto; }\n .btn { padding: 6px 14px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); color: var(--text); cursor: pointer; font-size: 13px; transition: all 0.15s; }\n .btn:hover { border-color: var(--accent); color: var(--accent); }\n .summary { padding: 12px 24px; display: flex; gap: 20px; border-bottom: 1px solid var(--border); font-size: 13px; color: var(--text-muted); flex-wrap: wrap; align-items: center; }\n .summary-item { display: flex; align-items: center; gap: 4px; }\n .summary-item strong { color: var(--text); }\n .summary-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }\n .dot-error { background: var(--error); }\n .dot-warning { background: var(--warning); }\n .dot-success { background: var(--success); }\n .toolbar { padding: 12px 24px; display: flex; gap: 8px; border-bottom: 1px solid var(--border); flex-wrap: wrap; align-items: center; }\n .filter-btn { padding: 4px 12px; border: 1px solid var(--border); border-radius: 16px; background: transparent; color: var(--text-muted); cursor: pointer; font-size: 12px; transition: all 0.15s; }\n .filter-btn.active { background: var(--accent); color: #fff; border-color: var(--accent); }\n .search-input { padding: 6px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font-size: 13px; flex: 1; min-width: 200px; }\n .search-input::placeholder { color: var(--text-muted); }\n .container { padding: 24px; display: flex; flex-direction: column; gap: 20px; max-width: 1200px; margin: 0 auto; }\n .card { border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg-card); overflow: hidden; }\n .card-header { padding: 16px; border-bottom: 1px solid var(--border); }\n .card-path { font-size: 12px; color: var(--text-muted); font-family: monospace; margin-bottom: 4px; }\n .card-title { font-size: 16px; font-weight: 600; }\n .card-desc { font-size: 13px; color: var(--text-muted); margin-top: 4px; }\n .card-meta { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; align-items: center; }\n .tag { padding: 2px 8px; background: var(--tag-bg); border-radius: 4px; font-size: 11px; color: var(--text-muted); }\n .card-warnings { padding: 8px 16px; display: flex; flex-direction: column; gap: 4px; }\n .warning-item { font-size: 12px; padding: 4px 8px; border-radius: 4px; }\n .warning-item.error { background: var(--error-bg); color: var(--error); }\n .warning-item.warning { background: var(--warning-bg); color: var(--warning); }\n .card-previews { padding: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }\n @media (max-width: 768px) { .card-previews { grid-template-columns: 1fr; } }\n .preview { border: 1px solid var(--border); border-radius: 6px; overflow: hidden; }\n .preview-label { padding: 6px 10px; font-size: 11px; font-weight: 600; color: var(--text-muted); background: var(--bg); border-bottom: 1px solid var(--border); text-transform: uppercase; letter-spacing: 0.5px; }\n .preview-card { background: var(--bg-preview); }\n .preview-img { width: 100%; aspect-ratio: 1200/630; background: linear-gradient(135deg, var(--accent-light), var(--bg-card)); display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 12px; overflow: hidden; }\n .preview-img img { width: 100%; height: 100%; object-fit: cover; }\n .preview-body { padding: 10px 12px; }\n .preview-url { font-size: 11px; color: var(--text-muted); margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .preview-title { font-size: 14px; font-weight: 600; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }\n .preview-desc { font-size: 12px; color: var(--text-muted); margin-top: 2px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }\n .empty { text-align: center; padding: 60px; color: var(--text-muted); }\n .spin { animation: spin 0.6s linear infinite; }\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n</head>\n<body>\n <div class=\"header\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"/></svg>\n <h1>OG Viewer <span>/ ox-content</span></h1>\n <div class=\"header-actions\">\n <button class=\"btn\" id=\"refresh-btn\" onclick=\"refresh()\">Refresh</button>\n </div>\n </div>\n <div class=\"summary\" id=\"summary\">\n <div class=\"summary-item\"><strong id=\"s-pages\">${pages.length}</strong>&nbsp;pages</div>\n <div class=\"summary-item\"><span class=\"summary-dot dot-error\"></span>&nbsp;<strong id=\"s-errors\">${totalErrors}</strong>&nbsp;errors</div>\n <div class=\"summary-item\"><span class=\"summary-dot dot-warning\"></span>&nbsp;<strong id=\"s-warnings\">${totalWarnings}</strong>&nbsp;warnings</div>\n <div class=\"summary-item\"><span class=\"summary-dot ${generateOgImage ? \"dot-success\" : \"dot-warning\"}\"></span>&nbsp;ogImage: <strong>${generateOgImage ? \"enabled\" : \"disabled\"}</strong></div>\n </div>\n <div class=\"toolbar\">\n <button class=\"filter-btn active\" data-filter=\"all\" onclick=\"setFilter('all')\">All</button>\n <button class=\"filter-btn\" data-filter=\"warnings\" onclick=\"setFilter('warnings')\">Warnings</button>\n <button class=\"filter-btn\" data-filter=\"errors\" onclick=\"setFilter('errors')\">Errors</button>\n <input class=\"search-input\" type=\"text\" placeholder=\"Search pages...\" oninput=\"applyFilters()\" id=\"search-input\">\n </div>\n <div class=\"container\" id=\"container\"></div>\n\n <script>\n let pages = ${JSON.stringify(pages)};\n let currentFilter = 'all';\n\n function setFilter(f) {\n currentFilter = f;\n document.querySelectorAll('.filter-btn').forEach(b => b.classList.toggle('active', b.dataset.filter === f));\n applyFilters();\n }\n\n function applyFilters() {\n const q = document.getElementById('search-input').value.toLowerCase();\n const filtered = pages.filter(p => {\n if (currentFilter === 'errors' && !p.warnings.some(w => w.level === 'error')) return false;\n if (currentFilter === 'warnings' && !p.warnings.length) return false;\n if (q && !p.path.toLowerCase().includes(q) && !p.title.toLowerCase().includes(q) && !p.description.toLowerCase().includes(q)) return false;\n return true;\n });\n renderCards(filtered);\n }\n\n function esc(s) {\n const d = document.createElement('div');\n d.textContent = s;\n return d.innerHTML;\n }\n\n function renderCards(list) {\n const c = document.getElementById('container');\n if (!list.length) {\n c.innerHTML = '<div class=\"empty\">No pages match the current filter.</div>';\n return;\n }\n c.innerHTML = list.map(p => {\n const warnings = p.warnings.map(w =>\n '<div class=\"warning-item ' + w.level + '\">' + (w.level === 'error' ? '\\\\u2716' : '\\\\u26A0') + ' ' + esc(w.message) + '</div>'\n ).join('');\n const tags = p.tags.map(t => '<span class=\"tag\">' + esc(t) + '</span>').join('');\n const author = p.author ? '<span class=\"tag\">by ' + esc(p.author) + '</span>' : '';\n const imgHtml = p.ogImageUrl\n ? '<img src=\"' + esc(p.ogImageUrl) + '\" onerror=\"this.parentNode.innerHTML=\\\\'No OG image\\\\'\">'\n : 'No OG image';\n const siteHost = ${JSON.stringify(options.ssg.siteUrl || \"example.com\")};\n return '<div class=\"card\">'\n + '<div class=\"card-header\">'\n + '<div class=\"card-path\">' + esc(p.path) + ' &rarr; ' + esc(p.urlPath) + '</div>'\n + '<div class=\"card-title\">' + (esc(p.title) || '<em style=\"color:var(--error)\">No title</em>') + '</div>'\n + (p.description ? '<div class=\"card-desc\">' + esc(p.description) + '</div>' : '')\n + (tags || author ? '<div class=\"card-meta\">' + author + tags + '</div>' : '')\n + '</div>'\n + (warnings ? '<div class=\"card-warnings\">' + warnings + '</div>' : '')\n + '<div class=\"card-previews\">'\n + '<div class=\"preview\"><div class=\"preview-label\">Twitter (summary_large_image)</div><div class=\"preview-card\"><div class=\"preview-img\">' + imgHtml + '</div><div class=\"preview-body\"><div class=\"preview-url\">' + esc(siteHost) + '</div><div class=\"preview-title\">' + esc(p.title) + '</div><div class=\"preview-desc\">' + esc(p.description) + '</div></div></div></div>'\n + '<div class=\"preview\"><div class=\"preview-label\">Facebook (Open Graph)</div><div class=\"preview-card\"><div class=\"preview-img\">' + imgHtml + '</div><div class=\"preview-body\"><div class=\"preview-url\">' + esc(siteHost) + '</div><div class=\"preview-title\">' + esc(p.title) + '</div><div class=\"preview-desc\">' + esc(p.description) + '</div></div></div></div>'\n + '</div>'\n + '</div>';\n }).join('');\n }\n\n async function refresh() {\n const btn = document.getElementById('refresh-btn');\n btn.textContent = 'Refreshing...';\n btn.disabled = true;\n try {\n const res = await fetch('/__og-viewer/api/pages');\n pages = await res.json();\n updateSummary();\n applyFilters();\n } catch(e) {\n console.error('Refresh failed:', e);\n } finally {\n btn.textContent = 'Refresh';\n btn.disabled = false;\n }\n }\n\n function updateSummary() {\n document.getElementById('s-pages').textContent = pages.length;\n document.getElementById('s-errors').textContent = pages.reduce((s,p) => s + p.warnings.filter(w => w.level === 'error').length, 0);\n document.getElementById('s-warnings').textContent = pages.reduce((s,p) => s + p.warnings.filter(w => w.level === 'warning').length, 0);\n }\n\n renderCards(pages);\n </script>\n</body>\n</html>`;\n}\n\n// =============================================================================\n// Plugin\n// =============================================================================\n\nexport function createOgViewerPlugin(options: ResolvedOptions): Plugin {\n return {\n name: \"ox-content:og-viewer\",\n apply: \"serve\",\n\n configureServer(server) {\n server.middlewares.use(async (req, res, next) => {\n if (req.url === \"/__og-viewer\" || req.url === \"/__og-viewer/\") {\n const root = server.config.root || process.cwd();\n try {\n const pages = await collectPages(options, root);\n const html = renderViewerHtml(pages, options);\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(html);\n } catch (err) {\n res.statusCode = 500;\n res.end(`OG Viewer error: ${err instanceof Error ? err.message : String(err)}`);\n }\n return;\n }\n\n if (req.url === \"/__og-viewer/api/pages\") {\n const root = server.config.root || process.cwd();\n try {\n const pages = await collectPages(options, root);\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(pages));\n } catch (err) {\n res.statusCode = 500;\n res.end(JSON.stringify({ error: String(err) }));\n }\n return;\n }\n\n next();\n });\n },\n };\n}\n","/**\n * i18n plugin for Ox Content.\n *\n * Provides:\n * - Dictionary loading and validation at build time\n * - Virtual module for i18n config\n * - Build-time i18n checking\n * - Locale-aware routing middleware for dev server\n */\n\nimport * as path from \"path\";\nimport * as fs from \"fs\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { importNapiModule } from \"./napi\";\nimport type { I18nOptions, ResolvedI18nOptions, LocaleConfig, ResolvedOptions } from \"./types\";\n\n/**\n * Resolves i18n options with defaults.\n */\nexport function resolveI18nOptions(\n options: I18nOptions | false | undefined,\n): ResolvedI18nOptions | false {\n if (options === false) return false;\n if (!options || !options.enabled) {\n return false;\n }\n\n const defaultLocale = options.defaultLocale ?? \"en\";\n const locales: LocaleConfig[] = options.locales ?? [{ code: defaultLocale, name: defaultLocale }];\n\n // Ensure default locale is in the locales list\n if (!locales.some((l) => l.code === defaultLocale)) {\n locales.unshift({ code: defaultLocale, name: defaultLocale });\n }\n\n return {\n enabled: true,\n dir: options.dir ?? \"content/i18n\",\n defaultLocale,\n locales,\n hideDefaultLocale: options.hideDefaultLocale ?? true,\n check: options.check ?? true,\n functionNames: options.functionNames ?? [\"t\", \"$t\"],\n };\n}\n\n/**\n * Creates the i18n sub-plugin for the Vite plugin array.\n */\nexport function createI18nPlugin(resolvedOptions: ResolvedOptions): Plugin {\n const i18nOptions = resolvedOptions.i18n;\n let root = process.cwd();\n\n return {\n name: \"ox-content:i18n\",\n\n configResolved(config) {\n root = config.root;\n },\n\n resolveId(id) {\n if (id === \"virtual:ox-content/i18n\") {\n return \"\\0virtual:ox-content/i18n\";\n }\n return null;\n },\n\n load(id) {\n if (id === \"\\0virtual:ox-content/i18n\") {\n if (!i18nOptions) {\n return `export const i18n = { enabled: false }; export default i18n;`;\n }\n\n return generateI18nModule(i18nOptions, root);\n }\n return null;\n },\n\n async buildStart() {\n if (!i18nOptions || !i18nOptions.check) return;\n\n const dictDir = path.resolve(root, i18nOptions.dir);\n if (!fs.existsSync(dictDir)) {\n console.warn(`[ox-content:i18n] Dictionary directory not found: ${dictDir}`);\n return;\n }\n\n try {\n const { checkI18nProject } = await importNapiModule();\n const checkResult = checkI18nProject(\n dictDir,\n [path.resolve(root, \"src\"), path.resolve(root, \"content\")],\n i18nOptions.functionNames,\n i18nOptions.defaultLocale,\n );\n if (checkResult.errorCount > 0 || checkResult.warningCount > 0) {\n for (const diag of checkResult.diagnostics) {\n if (diag.severity === \"error\") {\n console.error(`[ox-content:i18n] ${diag.message}`);\n } else if (diag.severity === \"warning\") {\n console.warn(`[ox-content:i18n] ${diag.message}`);\n }\n }\n }\n } catch {\n // NAPI binding not available; skip checks\n }\n },\n\n configureServer(server: ViteDevServer) {\n if (!i18nOptions) return;\n\n // Watch dictionary directory for changes\n const dictDir = path.resolve(root, i18nOptions.dir);\n if (fs.existsSync(dictDir)) {\n server.watcher.add(dictDir);\n\n server.watcher.on(\"change\", (filePath: string) => {\n if (!filePath.startsWith(dictDir)) return;\n if (!/\\.(json|yaml|yml)$/.test(filePath)) return;\n\n // Invalidate the virtual module\n const mod = server.moduleGraph.getModuleById(\"\\0virtual:ox-content/i18n\");\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n // Trigger full reload\n server.ws.send({ type: \"full-reload\" });\n });\n }\n\n // Add locale routing middleware\n server.middlewares.use((req, _res, next) => {\n if (!req.url) return next();\n\n // Parse locale from URL\n const url = req.url;\n const localeMatch = url.match(/^\\/([A-Za-z]{2,3}(?:-[A-Za-z0-9]+)*)(\\/|$)/);\n\n if (localeMatch) {\n const localeCode = localeMatch[1];\n const isKnown = i18nOptions.locales.some((l) => l.code === localeCode);\n if (isKnown) {\n // Set locale header for downstream middleware\n (req as any).__oxLocale = localeCode;\n }\n } else if (i18nOptions.hideDefaultLocale) {\n // No locale prefix: use default locale\n (req as any).__oxLocale = i18nOptions.defaultLocale;\n }\n\n next();\n });\n },\n };\n}\n\n/**\n * Generates the virtual module for i18n configuration.\n */\nexport function generateI18nModule(options: ResolvedI18nOptions, root: string): string {\n const dictDir = path.resolve(root, options.dir);\n const config = {\n defaultLocale: options.defaultLocale,\n locales: options.locales,\n hideDefaultLocale: options.hideDefaultLocale,\n };\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const napi = require(\"@ox-content/napi\") as {\n generateI18nModule?: (dictDir: string, runtimeConfig: typeof config) => string;\n };\n\n if (typeof napi.generateI18nModule === \"function\") {\n return napi.generateI18nModule(dictDir, config);\n }\n } catch (error) {\n throw new Error(\n `[ox-content:i18n] Failed to load @ox-content/napi for i18n module generation: ${String(error)}`,\n );\n }\n\n throw new Error(\n \"[ox-content:i18n] @ox-content/napi does not expose generateI18nModule. Please rebuild the NAPI package.\",\n );\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveImageOptions(\n options: OxContentOptions[\"images\"],\n): ResolvedOptions[\"images\"] {\n if (!options) return { enabled: false, lazy: true };\n if (options === true) return { enabled: true, lazy: true };\n return { enabled: true, lazy: options.lazy ?? true };\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveCardOptions(options: OxContentOptions[\"cards\"]): ResolvedOptions[\"cards\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveIncludeOptions(\n options: OxContentOptions[\"includes\"],\n): ResolvedOptions[\"includes\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: true, rootDir: options.rootDir };\n}\n","import type { OxContentOptions, ResolvedOptions } from \"./types\";\n\nexport function resolveStepsOptions(options: OxContentOptions[\"steps\"]): ResolvedOptions[\"steps\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n","import { importNapiModuleSync } from \"./napi\";\n\ntype NapiModule = typeof import(\"@ox-content/napi\");\ntype NativeIncrementalMarkdownParser = InstanceType<NapiModule[\"IncrementalMarkdownParser\"]>;\ntype NativeIncrementalMarkdownRenderer = InstanceType<NapiModule[\"IncrementalMarkdownRenderer\"]>;\ntype NativeParseResult = import(\"@ox-content/napi\").IncrementalMarkdownParseResult;\n\nexport interface IncrementalMarkdownParserOptions {\n /**\n * Enable GitHub Flavored Markdown extensions.\n * @default true\n */\n gfm?: boolean;\n\n /**\n * Enable MDX JSX, ESM, and expression nodes.\n * @default false\n */\n mdx?: boolean;\n\n /**\n * Enable footnotes.\n * @default true\n */\n footnotes?: boolean;\n\n /**\n * Enable task list items.\n * @default true\n */\n taskLists?: boolean;\n\n /**\n * Enable GFM tables.\n * @default true\n */\n tables?: boolean;\n\n /**\n * Enable strikethrough.\n * @default true\n */\n strikethrough?: boolean;\n\n /**\n * Enable Markdown autolinks.\n * @default true\n */\n autolinks?: boolean;\n}\n\nexport interface IncrementalMarkdownParseAppendOptions {\n /**\n * Commit the current chunk as the final stream input.\n * @default false\n */\n final?: boolean;\n\n /**\n * Include a provisional AST for the current replaceable tail.\n * The constructor-level value is reused when omitted on `append`.\n * @default false\n */\n includePendingAst?: boolean;\n\n /**\n * Temporarily close unmatched inline delimiters in the provisional AST.\n * @default true\n */\n completeInline?: boolean;\n}\n\nexport interface IncrementalMarkdownRendererOptions extends IncrementalMarkdownParserOptions {\n /**\n * Render the unstable tail as replaceable provisional HTML.\n * @default true\n */\n renderPending?: boolean;\n\n /**\n * Temporarily close unmatched inline delimiters in provisional HTML.\n * @default true\n */\n completeInline?: boolean;\n}\n\nexport interface IncrementalMarkdownRenderAppendOptions {\n /**\n * Commit the current chunk as the final stream input.\n * @default false\n */\n final?: boolean;\n\n /**\n * Render the unstable tail as replaceable provisional HTML.\n * The constructor-level value is reused when omitted on `append`.\n * @default true\n */\n renderPending?: boolean;\n\n /**\n * Temporarily close unmatched inline delimiters in provisional HTML.\n * @default true\n */\n completeInline?: boolean;\n}\n\nexport type IncrementalMarkdownRenderResult =\n import(\"@ox-content/napi\").IncrementalMarkdownRenderResult;\n\nexport interface IncrementalMarkdownParseResult<TAst = unknown> extends Omit<\n NativeParseResult,\n \"ast\" | \"pendingAst\"\n> {\n /** Parsed mdast for the newly committed Markdown prefix, or null when nothing committed. */\n ast: TAst | null;\n\n /** Raw mdast JSON for the newly committed Markdown prefix. */\n astJson: string;\n\n /** Provisional parsed mdast for the current replaceable tail, or null when not requested. */\n pendingAst: TAst | null;\n\n /** Raw provisional mdast JSON for the current replaceable tail. */\n pendingAstJson: string;\n}\n\nexport type MarkdownChunkSource = Iterable<string> | AsyncIterable<string>;\n\nfunction toNativeParserOptions(options: IncrementalMarkdownParserOptions = {}) {\n return {\n gfm: options.gfm ?? true,\n mdx: options.mdx,\n footnotes: options.footnotes,\n taskLists: options.taskLists,\n tables: options.tables,\n strikethrough: options.strikethrough,\n autolinks: options.autolinks,\n };\n}\n\nfunction parseAstJson<TAst>(json: string): TAst | null {\n return json ? (JSON.parse(json) as TAst) : null;\n}\n\nfunction normalizeParseResult<TAst>(\n result: NativeParseResult,\n): IncrementalMarkdownParseResult<TAst> {\n const { ast, pendingAst, ...rest } = result;\n return {\n ...rest,\n ast: parseAstJson<TAst>(ast),\n astJson: ast,\n pendingAst: parseAstJson<TAst>(pendingAst),\n pendingAstJson: pendingAst,\n };\n}\n\nexport class IncrementalMarkdownParser<TAst = unknown> {\n readonly #native: NativeIncrementalMarkdownParser;\n readonly #includePendingAst: boolean;\n readonly #completeInline: boolean;\n\n constructor(\n options: IncrementalMarkdownParserOptions & IncrementalMarkdownParseAppendOptions = {},\n ) {\n const napi = importNapiModuleSync();\n this.#native = new napi.IncrementalMarkdownParser(toNativeParserOptions(options));\n this.#includePendingAst = options.includePendingAst ?? false;\n this.#completeInline = options.completeInline ?? true;\n }\n\n append(\n chunk: string,\n options: IncrementalMarkdownParseAppendOptions = {},\n ): IncrementalMarkdownParseResult<TAst> {\n return normalizeParseResult<TAst>(\n this.#native.append(chunk, {\n isFinal: options.final ?? false,\n includePendingAst: options.includePendingAst ?? this.#includePendingAst,\n completeInline: options.completeInline ?? this.#completeInline,\n }),\n );\n }\n\n finish(\n options: IncrementalMarkdownParseAppendOptions = {},\n ): IncrementalMarkdownParseResult<TAst> {\n return normalizeParseResult<TAst>(\n this.#native.finish({\n includePendingAst: options.includePendingAst ?? this.#includePendingAst,\n completeInline: options.completeInline ?? this.#completeInline,\n }),\n );\n }\n\n reset(): void {\n this.#native.reset();\n }\n\n get pendingMarkdown(): string {\n return this.#native.pendingMarkdown;\n }\n\n get committedBytes(): number {\n return this.#native.committedBytes;\n }\n\n get totalBytes(): number {\n return this.#native.totalBytes;\n }\n}\n\nexport class IncrementalMarkdownRenderer {\n readonly #native: NativeIncrementalMarkdownRenderer;\n readonly #renderPending: boolean;\n readonly #completeInline: boolean;\n\n constructor(options: IncrementalMarkdownRendererOptions = {}) {\n const napi = importNapiModuleSync();\n this.#native = new napi.IncrementalMarkdownRenderer(toNativeParserOptions(options));\n this.#renderPending = options.renderPending ?? true;\n this.#completeInline = options.completeInline ?? true;\n }\n\n append(\n chunk: string,\n options: IncrementalMarkdownRenderAppendOptions = {},\n ): IncrementalMarkdownRenderResult {\n return this.#native.append(chunk, {\n isFinal: options.final ?? false,\n renderPending: options.renderPending ?? this.#renderPending,\n completeInline: options.completeInline ?? this.#completeInline,\n });\n }\n\n finish(): IncrementalMarkdownRenderResult {\n return this.#native.finish();\n }\n\n reset(): void {\n this.#native.reset();\n }\n\n get committedHtml(): string {\n return this.#native.committedHtml;\n }\n\n get pendingMarkdown(): string {\n return this.#native.pendingMarkdown;\n }\n}\n\nexport function createIncrementalMarkdownParser<TAst = unknown>(\n options?: IncrementalMarkdownParserOptions & IncrementalMarkdownParseAppendOptions,\n): IncrementalMarkdownParser<TAst> {\n return new IncrementalMarkdownParser<TAst>(options);\n}\n\nexport function createIncrementalMarkdownRenderer(\n options?: IncrementalMarkdownRendererOptions,\n): IncrementalMarkdownRenderer {\n return new IncrementalMarkdownRenderer(options);\n}\n\nexport async function* renderMarkdownStream(\n chunks: MarkdownChunkSource,\n options: IncrementalMarkdownRendererOptions = {},\n): AsyncGenerator<IncrementalMarkdownRenderResult> {\n const renderer = createIncrementalMarkdownRenderer(options);\n\n for await (const chunk of chunks) {\n yield renderer.append(chunk);\n }\n\n yield renderer.finish();\n}\n","/**\n * Discover registered MDX islands from the mdast tree or rendered HTML.\n *\n * Framework plugins use this instead of a source regex when MDX is on, so\n * nested JSX, expression attributes, and fragments stay visible. Names that\n * are not in the global `components` map and are not document-local import\n * bindings are left as static HTML.\n */\n\nimport { importNapiModule } from \"./napi\";\n\n/** Global component map: object, Map, or name list. */\nexport type ComponentRegistry =\n | Readonly<Record<string, unknown>>\n | ReadonlyMap<string, unknown>\n | Iterable<string>;\n\nconst OX_ISLAND_NAME = /data-ox-island=\"([^\"]+)\"/g;\n\n/**\n * Collect named MDX JSX tags from a parsed mdast tree (JSON from NAPI `parse()`).\n * Fragments (`name: null`) and non-JSX nodes are ignored. Walks nested children\n * so inner islands are found.\n */\nexport function collectMdxJsxNamesFromAst(ast: unknown): string[] {\n const names = new Set<string>();\n walkMdast(ast, names);\n return [...names];\n}\n\n/**\n * Collect `data-ox-island` names from Rust-rendered HTML.\n * Used when an AST walk is unavailable.\n */\nexport function collectMdxIslandNamesFromHtml(html: string): string[] {\n const names = new Set<string>();\n OX_ISLAND_NAME.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = OX_ISLAND_NAME.exec(html)) !== null) {\n const name = match[1];\n if (name) names.add(decodeHtmlAttr(name));\n }\n return [...names];\n}\n\n/** Keep names that exist on the global component map, in first-seen order. */\nexport function intersectRegisteredComponentNames(\n names: Iterable<string>,\n components: ComponentRegistry,\n): string[] {\n return intersectHydratableComponentNames(names, components);\n}\n\n/**\n * Keep names that are either globally registered or document-local bindings.\n */\nexport function intersectHydratableComponentNames(\n names: Iterable<string>,\n components: ComponentRegistry,\n localNames?: Iterable<string>,\n): string[] {\n const local = localNames ? new Set(localNames) : null;\n const used: string[] = [];\n for (const name of names) {\n if ((local?.has(name) || isRegisteredComponent(name, components)) && !used.includes(name)) {\n used.push(name);\n }\n }\n return used;\n}\n\nexport interface DiscoverRegisteredMdxComponentsInput {\n /** Markdown/MDX body (frontmatter already stripped). */\n source: string;\n /** Rendered HTML, used when `parse()` is missing or the AST walk fails. */\n html?: string;\n components: ComponentRegistry;\n /** Document-local import bindings. These override the global map for this file. */\n localNames?: Iterable<string>;\n}\n\n/**\n * Resolve registered island names for an MDX document.\n *\n * Prefers a NAPI `parse()` AST walk. Falls back to rendered `data-ox-island`\n * names so plugins still hydrate if #659 metadata is not present.\n */\nexport async function discoverRegisteredMdxComponents(\n input: DiscoverRegisteredMdxComponentsInput,\n): Promise<string[]> {\n const astNames = await tryCollectNamesFromParse(input.source);\n const names =\n astNames ?? (input.html !== undefined ? collectMdxIslandNamesFromHtml(input.html) : []);\n return intersectHydratableComponentNames(names, input.components, input.localNames);\n}\n\nexport function isRegisteredComponent(name: string, components: ComponentRegistry): boolean {\n if (isMapRegistry(components)) {\n return components.has(name);\n }\n if (isPlainObjectRegistry(components)) {\n return Object.prototype.hasOwnProperty.call(components, name);\n }\n for (const entry of components) {\n if (entry === name) return true;\n }\n return false;\n}\n\nasync function tryCollectNamesFromParse(source: string): Promise<string[] | null> {\n try {\n const napi = await importNapiModule();\n const parsed = napi.parse(source, { mdx: true, gfm: true });\n if (!parsed.ast) return null;\n return collectMdxJsxNamesFromAst(JSON.parse(parsed.ast) as unknown);\n } catch {\n return null;\n }\n}\n\nfunction walkMdast(node: unknown, names: Set<string>): void {\n if (!node || typeof node !== \"object\") return;\n\n const record = node as { type?: unknown; name?: unknown; children?: unknown };\n if (\n (record.type === \"mdxJsxFlowElement\" || record.type === \"mdxJsxTextElement\") &&\n typeof record.name === \"string\" &&\n record.name\n ) {\n names.add(record.name);\n }\n\n if (Array.isArray(record.children)) {\n for (const child of record.children) {\n walkMdast(child, names);\n }\n }\n}\n\nfunction isMapRegistry(value: ComponentRegistry): value is ReadonlyMap<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ReadonlyMap<string, unknown>).has === \"function\" &&\n typeof (value as ReadonlyMap<string, unknown>).get === \"function\"\n );\n}\n\nfunction isPlainObjectRegistry(\n value: ComponentRegistry,\n): value is Readonly<Record<string, unknown>> {\n return Object.prototype.toString.call(value) === \"[object Object]\";\n}\n\nfunction decodeHtmlAttr(value: string): string {\n return value\n .replaceAll(\"&quot;\", '\"')\n .replaceAll(\"&#39;\", \"'\")\n .replaceAll(\"&lt;\", \"<\")\n .replaceAll(\"&gt;\", \">\")\n .replaceAll(\"&amp;\", \"&\");\n}\n","/**\n * Resolve MDX component imports relative to the document that declared them.\n *\n * Only `./` and `../` specifiers become island bindings. Bare, package, and\n * remote specifiers are reported and ignored. A specifier that leaves the\n * configured content root is rejected with a diagnostic.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { MdxImport, MdxImportSpecifierKind } from \"./types\";\n\nexport interface ResolveDocumentComponentImportsInput {\n imports: readonly MdxImport[];\n documentPath: string;\n contentRoot?: string;\n srcDir?: string;\n}\n\nexport interface ResolvedDocumentComponentImport {\n localName: string;\n specifier: string;\n resolvedPath: string;\n importPathRelativeToDocument: string;\n imported: string;\n kind: Exclude<MdxImportSpecifierKind, \"namespace\">;\n}\n\nexport type DocumentImportDiagnosticCode = \"not-relative\" | \"escapes-root\" | \"duplicate-binding\";\n\nexport interface DocumentImportDiagnostic {\n code: DocumentImportDiagnosticCode;\n message: string;\n specifier: string;\n localName?: string;\n}\n\nexport interface ResolveDocumentComponentImportsResult {\n bindings: ResolvedDocumentComponentImport[];\n diagnostics: DocumentImportDiagnostic[];\n}\n\nexport function resolveContentRootPath(input: {\n contentRoot?: string;\n srcDir?: string;\n root?: string;\n}): string {\n if (input.contentRoot) {\n return path.resolve(input.contentRoot);\n }\n const root = input.root ?? process.cwd();\n return path.resolve(root, input.srcDir ?? \".\");\n}\n\nexport function stripViteQuery(id: string): string {\n return id.split(\"?\")[0].split(\"#\")[0];\n}\n\nexport function resolveDocumentComponentImports(\n input: ResolveDocumentComponentImportsInput,\n): ResolveDocumentComponentImportsResult {\n const documentPath = stripViteQuery(input.documentPath);\n const documentDir = path.dirname(documentPath);\n const contentRoot = resolveContentRootPath(input);\n const diagnostics: DocumentImportDiagnostic[] = [];\n const candidates: ResolvedDocumentComponentImport[] = [];\n\n for (const statement of input.imports) {\n const specifier = statement.source;\n if (!isRelativeSpecifier(specifier)) {\n diagnostics.push({\n code: \"not-relative\",\n message: `Document component import \"${specifier}\" is not relative and was ignored.`,\n specifier,\n });\n continue;\n }\n\n for (const spec of statement.specifiers) {\n if (spec.kind === \"namespace\") {\n continue;\n }\n\n const resolvedPath = resolveExistingPath(path.resolve(documentDir, specifier));\n if (!isInsideRoot(resolvedPath, contentRoot)) {\n diagnostics.push({\n code: \"escapes-root\",\n message: `Document component import \"${specifier}\" escapes the content root.`,\n specifier,\n localName: spec.local,\n });\n continue;\n }\n\n candidates.push({\n localName: spec.local,\n specifier,\n resolvedPath,\n importPathRelativeToDocument: toDocumentRelativeImport(documentDir, resolvedPath),\n imported: spec.imported,\n kind: spec.kind,\n });\n }\n }\n\n const counts = new Map<string, number>();\n for (const binding of candidates) {\n counts.set(binding.localName, (counts.get(binding.localName) ?? 0) + 1);\n }\n\n const bindings: ResolvedDocumentComponentImport[] = [];\n const reportedDuplicates = new Set<string>();\n for (const binding of candidates) {\n if ((counts.get(binding.localName) ?? 0) > 1) {\n if (!reportedDuplicates.has(binding.localName)) {\n reportedDuplicates.add(binding.localName);\n diagnostics.push({\n code: \"duplicate-binding\",\n message: `Document component name \"${binding.localName}\" is imported more than once.`,\n specifier: binding.specifier,\n localName: binding.localName,\n });\n }\n continue;\n }\n bindings.push(binding);\n }\n\n return { bindings, diagnostics };\n}\n\nfunction isRelativeSpecifier(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\");\n}\n\nfunction resolveExistingPath(filePath: string): string {\n try {\n return fs.realpathSync(filePath);\n } catch {\n return path.normalize(filePath);\n }\n}\n\nfunction isInsideRoot(resolvedPath: string, root: string): boolean {\n const relative = path.relative(resolveExistingPath(root), resolvedPath);\n return (\n relative === \"\" ||\n (!relative.startsWith(`..${path.sep}`) && relative !== \"..\" && !path.isAbsolute(relative))\n );\n}\n\nfunction toDocumentRelativeImport(documentDir: string, resolvedPath: string): string {\n const relative = path.relative(documentDir, resolvedPath).replace(/\\\\/g, \"/\");\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n","/**\n * Combine document-local import resolution with MDX island discovery.\n */\n\nimport {\n resolveContentRootPath,\n resolveDocumentComponentImports,\n type DocumentImportDiagnostic,\n type ResolvedDocumentComponentImport,\n type ResolveDocumentComponentImportsInput,\n} from \"./document-imports\";\nimport { discoverRegisteredMdxComponents, type ComponentRegistry } from \"./mdx-islands\";\nimport type { MdxImport } from \"./types\";\n\nexport interface DiscoverDocumentMdxIslandsInput {\n source: string;\n html?: string;\n components: ComponentRegistry;\n imports: readonly MdxImport[];\n documentPath: string;\n contentRoot?: string;\n srcDir?: string;\n root?: string;\n}\n\nexport interface DiscoverDocumentMdxIslandsResult {\n usedComponents: string[];\n localBindings: Map<string, ResolvedDocumentComponentImport>;\n diagnostics: DocumentImportDiagnostic[];\n}\n\nexport async function discoverDocumentMdxIslands(\n input: DiscoverDocumentMdxIslandsInput,\n): Promise<DiscoverDocumentMdxIslandsResult> {\n const resolved = resolveDocumentComponentImports({\n imports: input.imports,\n documentPath: input.documentPath,\n contentRoot: input.contentRoot ?? resolveContentRootPath(input),\n srcDir: input.srcDir,\n } satisfies ResolveDocumentComponentImportsInput);\n const localBindings = new Map(\n resolved.bindings.map((binding) => [binding.localName, binding] as const),\n );\n const usedComponents = await discoverRegisteredMdxComponents({\n source: input.source,\n html: input.html,\n components: input.components,\n localNames: localBindings.keys(),\n });\n return {\n usedComponents,\n localBindings,\n diagnostics: resolved.diagnostics,\n };\n}\n","/**\n * Emit static component imports for framework Markdown modules.\n *\n * Document-local bindings win over the global `components` map for that file\n * only. Two documents that bind the same local name therefore emit different\n * specifiers and do not share one module id.\n */\n\nimport path from \"node:path\";\nimport type { ResolvedDocumentComponentImport } from \"./document-imports\";\nimport { stripViteQuery } from \"./document-imports\";\n\nexport type GlobalComponentMap = Readonly<Record<string, string>> | ReadonlyMap<string, string>;\n\nexport interface RenderIslandComponentImportsInput {\n globalComponents: GlobalComponentMap;\n localBindings?: ReadonlyMap<string, ResolvedDocumentComponentImport>;\n documentPath: string;\n root?: string;\n}\n\nexport function renderIslandComponentImports(\n usedComponents: readonly string[],\n input: RenderIslandComponentImportsInput,\n): string {\n const documentDir = path.dirname(stripViteQuery(input.documentPath));\n const root = input.root || process.cwd();\n\n return usedComponents\n .map((name) => {\n const local = input.localBindings?.get(name);\n if (local) {\n return renderLocalImport(local);\n }\n const componentPath = getGlobalComponentPath(input.globalComponents, name);\n if (!componentPath) return \"\";\n return renderGlobalImport(name, componentPath, documentDir, root);\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction renderLocalImport(binding: ResolvedDocumentComponentImport): string {\n const specifier = binding.importPathRelativeToDocument.replace(/\\\\/g, \"/\");\n if (binding.kind === \"default\") {\n return `import ${binding.localName} from '${specifier}';`;\n }\n if (binding.imported === binding.localName) {\n return `import { ${binding.imported} } from '${specifier}';`;\n }\n return `import { ${binding.imported} as ${binding.localName} } from '${specifier}';`;\n}\n\nfunction renderGlobalImport(\n name: string,\n componentPath: string,\n documentDir: string,\n root: string,\n): string {\n const absolutePath = path.resolve(root, componentPath.replace(/^\\.\\//, \"\"));\n const relativePath = path.relative(documentDir, absolutePath).replace(/\\\\/g, \"/\");\n const importPath = relativePath.startsWith(\".\") ? relativePath : `./${relativePath}`;\n return `import ${name} from '${importPath}';`;\n}\n\nfunction getGlobalComponentPath(components: GlobalComponentMap, name: string): string | undefined {\n if (isMapRegistry(components)) {\n return components.get(name);\n }\n return Object.prototype.hasOwnProperty.call(components, name) ? components[name] : undefined;\n}\n\nfunction isMapRegistry(value: GlobalComponentMap): value is ReadonlyMap<string, string> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ReadonlyMap<string, string>).has === \"function\" &&\n typeof (value as ReadonlyMap<string, string>).get === \"function\"\n );\n}\n","/**\n * Optional adapter-side island SSR.\n *\n * Framework plugins may supply `renderIsland` to replace island inner HTML at\n * transform time. This helper stays framework-neutral and does not import a\n * framework SSR runtime.\n */\n\nexport type RenderIslandFn = (\n name: string,\n props: Record<string, unknown>,\n filePath: string,\n) => string | Promise<string>;\n\nconst RUST_PAYLOAD_KEYS = new Set([\"props\", \"expressions\", \"spreads\"]);\nconst PAYLOAD_SCRIPT = /^\\s*<script type=\"application\\/json\">[\\s\\S]*?<\\/script>/;\n\nexport async function applyIslandSsrHtml(\n html: string,\n renderIsland: RenderIslandFn,\n filePath: string,\n names?: Iterable<string>,\n): Promise<string> {\n const allowed = names ? new Set(names) : null;\n const islands = findIslandRanges(html);\n let output = html;\n\n for (const island of islands.toReversed()) {\n if (allowed && !allowed.has(island.name)) {\n continue;\n }\n const inner = output.slice(island.innerStart, island.closeStart);\n const scriptMatch = inner.match(PAYLOAD_SCRIPT);\n const script = scriptMatch?.[0] ?? \"\";\n const props = parseIslandProps(island.propsAttr, script);\n const ssrHtml = await renderIsland(island.name, props, filePath);\n output =\n output.slice(0, island.innerStart) + script + ssrHtml + output.slice(island.closeStart);\n }\n\n return output;\n}\n\ninterface IslandRange {\n name: string;\n innerStart: number;\n closeStart: number;\n propsAttr?: string;\n}\n\nfunction findIslandRanges(html: string): IslandRange[] {\n const ranges: IslandRange[] = [];\n const openRe = /<(div|span)\\b([^>]*\\bdata-ox-island=\"([^\"]+)\"[^>]*)>/gi;\n let match: RegExpExecArray | null;\n while ((match = openRe.exec(html)) !== null) {\n const tag = match[1];\n const name = decodeHtmlAttr(match[3] ?? \"\");\n if (!tag || !name) continue;\n const innerStart = match.index + match[0].length;\n const closeStart = findMatchingClose(html, innerStart, tag);\n ranges.push({\n name,\n innerStart,\n closeStart,\n propsAttr: matchAttr(match[2] ?? \"\", \"data-ox-props\"),\n });\n }\n return ranges;\n}\n\nfunction findMatchingClose(html: string, from: number, tag: string): number {\n const openNeedle = `<${tag}`;\n const closeNeedle = `</${tag}>`;\n let depth = 1;\n let cursor = from;\n while (cursor < html.length) {\n const nextOpen = indexOfTagOpen(html, openNeedle, cursor);\n const nextClose = html.indexOf(closeNeedle, cursor);\n if (nextClose === -1) return html.length;\n if (nextOpen !== -1 && nextOpen < nextClose) {\n depth += 1;\n cursor = nextOpen + openNeedle.length;\n } else {\n depth -= 1;\n if (depth === 0) return nextClose;\n cursor = nextClose + closeNeedle.length;\n }\n }\n return html.length;\n}\n\nfunction indexOfTagOpen(html: string, openNeedle: string, from: number): number {\n let cursor = from;\n while (cursor < html.length) {\n const index = html.indexOf(openNeedle, cursor);\n if (index === -1) return -1;\n const next = html[index + openNeedle.length];\n if (next === \" \" || next === \">\" || next === \"\\t\" || next === \"\\n\" || next === \"/\") {\n return index;\n }\n cursor = index + openNeedle.length;\n }\n return -1;\n}\n\nfunction matchAttr(attrs: string, name: string): string | undefined {\n const match = new RegExp(`\\\\b${name}=\"([^\"]*)\"`, \"i\").exec(attrs);\n return match?.[1] === undefined ? undefined : decodeHtmlAttr(match[1]);\n}\n\nfunction parseIslandProps(propsAttr: string | undefined, script: string): Record<string, unknown> {\n const fromAttr = propsAttr ? tryParseJson(propsAttr) : undefined;\n if (fromAttr) return unwrapIslandProps(fromAttr);\n const scriptBody = script.match(/<script type=\"application\\/json\">([\\s\\S]*?)<\\/script>/i)?.[1];\n return scriptBody ? unwrapIslandProps(tryParseJson(scriptBody) ?? {}) : {};\n}\n\nfunction tryParseJson(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n}\n\nfunction unwrapIslandProps(parsed: unknown): Record<string, unknown> {\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const record = parsed as Record<string, unknown>;\n const keys = Object.keys(record);\n if (\n keys.length > 0 &&\n keys.every((key) => RUST_PAYLOAD_KEYS.has(key)) &&\n record.props &&\n typeof record.props === \"object\" &&\n !Array.isArray(record.props)\n ) {\n return record.props as Record<string, unknown>;\n }\n return record;\n}\n\nfunction decodeHtmlAttr(value: string): string {\n return value\n .replaceAll(\"&quot;\", '\"')\n .replaceAll(\"&#39;\", \"'\")\n .replaceAll(\"&lt;\", \"<\")\n .replaceAll(\"&gt;\", \">\")\n .replaceAll(\"&amp;\", \"&\");\n}\n","import { importNapiModuleSync } from \"./napi\";\nimport type { ResolvedOptions, TocEntry } from \"./types\";\n\nexport type FrameworkRenderTarget = \"html\" | \"native\";\nexport type FrameworkCodegenTarget = \"react\" | \"vue\" | \"svelte\";\nexport type FrameworkCodegenMode = \"innerHtml\" | \"expression\" | \"renderFunction\" | \"component\";\n\nexport interface FrameworkMarkdownOptions {\n srcDir: string;\n outDir: string;\n base: string;\n extensions: string[];\n gfm: boolean;\n frontmatter?: boolean;\n toc: boolean;\n tocMaxDepth: number;\n codeAnnotations?: {\n enabled?: boolean;\n metaKey?: string;\n };\n embeds?: {\n github?: ResolvedOptions[\"embeds\"][\"github\"];\n openGraph?: ResolvedOptions[\"embeds\"][\"openGraph\"];\n };\n math?: boolean | { enabled?: boolean };\n mdx?: boolean;\n}\n\nexport interface FrameworkComponentIsland {\n name: string;\n props: Record<string, unknown>;\n id: string;\n content?: string;\n}\n\nexport interface FrameworkTransformData {\n html: string;\n frontmatter: Record<string, unknown>;\n toc: TocEntry[];\n}\n\nexport function createFrameworkMarkdownOptions(options: FrameworkMarkdownOptions): ResolvedOptions {\n return {\n srcDir: options.srcDir,\n outDir: options.outDir,\n base: options.base,\n extensions: options.extensions,\n ssg: {\n enabled: false,\n extension: \".html\",\n clean: false,\n bare: false,\n generateOgImage: false,\n lastUpdated: false,\n pagination: false,\n breadcrumbs: false,\n jsonLd: false,\n readerChrome: false,\n localeSwitcher: false,\n a11y: false,\n pageChrome: false,\n },\n siteMaps: { enabled: false, robots: true, llms: true },\n pwa: { enabled: false, offline: true },\n publishState: { enabled: false, includeDrafts: false },\n permalinks: { enabled: false },\n cascade: { enabled: false },\n redirects: {\n enabled: false,\n map: {},\n netlify: false,\n headers: false,\n json: false,\n allowExternal: false,\n },\n gfm: options.gfm,\n mdx: options.mdx,\n frontmatter: options.frontmatter ?? false,\n toc: options.toc,\n tocMaxDepth: options.tocMaxDepth,\n codeAnnotations: {\n enabled: options.codeAnnotations?.enabled ?? false,\n notation: \"attribute\",\n metaKey: options.codeAnnotations?.metaKey ?? \"annotate\",\n defaultLineNumbers: false,\n },\n footnotes: true,\n tables: true,\n taskLists: true,\n strikethrough: true,\n autolinks: options.gfm,\n highlight: false,\n mermaid: false,\n math: {\n enabled:\n options.math === true ||\n (typeof options.math === \"object\" && options.math.enabled !== false),\n },\n ogImage: false,\n ogImageOptions: {\n vuePlugin: \"vitejs\",\n width: 1200,\n height: 630,\n cache: true,\n concurrency: 1,\n },\n transformers: [],\n docs: false,\n ogViewer: false,\n search: {\n enabled: false,\n limit: 10,\n prefix: true,\n placeholder: \"Search...\",\n hotkey: \"k\",\n },\n collections: { enabled: false, collections: {} },\n embeds: {\n github: options.embeds?.github ?? {},\n openGraph: options.embeds?.openGraph ?? {},\n pm: false,\n spotify: false,\n stackBlitz: false,\n twitter: false,\n bluesky: false,\n webContainer: false,\n },\n i18n: false,\n wikiLinks: { enabled: false, baseUrl: options.base },\n emojiShortcodes: { enabled: false, custom: {} },\n attrs: { enabled: false },\n badges: { enabled: false },\n containers: { enabled: false, types: {} },\n images: { enabled: false, lazy: true },\n codeImports: { enabled: false },\n includes: { enabled: false },\n cards: { enabled: false },\n steps: { enabled: false },\n fileTree: { enabled: false, defaultOpen: true, icons: true },\n sanitize: { enabled: false },\n editThisPage: { enabled: false, branch: \"main\", label: \"Edit this page\" },\n cjkEmphasis: false,\n codeBlockLint: { enabled: false, requireLanguage: false, trailingSpaces: true, mode: \"warn\" },\n codeBlockTypecheck: {\n enabled: false,\n languages: [\"ts\", \"tsx\"],\n requireMeta: true,\n tsgoCommand: \"tsgo\",\n mode: \"warn\",\n },\n docsTests: {\n enabled: false,\n languages: [\"js\", \"jsx\", \"ts\", \"tsx\"],\n requireMeta: true,\n },\n } as ResolvedOptions;\n}\n\nexport function renderHtmlToReactCreateElement(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"react\", \"expression\", islands);\n}\n\nexport function renderHtmlToVueH(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"vue\", \"expression\", islands);\n}\n\nexport function renderHtmlToFrameworkCode(\n html: string,\n target: FrameworkCodegenTarget,\n mode: FrameworkCodegenMode,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return importNapiModuleSync().renderFrameworkComponentCode(\n html,\n target,\n toNapiIslands(islands),\n mode,\n );\n}\n\nexport function renderHtmlToReactComponent(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"react\", \"component\", islands);\n}\n\nexport function renderHtmlToVueComponent(\n html: string,\n islands: readonly FrameworkComponentIsland[] = [],\n): string {\n return renderHtmlToFrameworkCode(html, \"vue\", \"component\", islands);\n}\n\nexport function renderHtmlToSvelteComponent(html: string): string {\n return renderHtmlToFrameworkCode(html, \"svelte\", \"component\");\n}\n\nexport function escapeSvelteMarkup(html: string): string {\n return importNapiModuleSync().escapeSvelteMarkup(html);\n}\n\nfunction toNapiIslands(islands: readonly FrameworkComponentIsland[]) {\n return islands.map((island) => ({\n name: island.name,\n props: island.props,\n id: island.id,\n content: island.content,\n }));\n}\n","import { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { glob } from \"glob\";\nimport { extractDocsTests, type DocsTestOptions, type ExtractedCodeBlock } from \"./code-blocks\";\nimport { extractDocs, resolveDocsOptions } from \"./docs\";\nimport type { DocEntry, DocsOptions, ExtractedDocs, ResolvedDocsOptions } from \"./types\";\n\nexport interface CollectedDocsTest extends ExtractedCodeBlock {\n sourcePath: string;\n relativePath: string;\n index: number;\n}\n\nexport type DocsTestSource = \"markdown\" | \"jsdoc\";\n\nexport interface DocsTestHarnessOptions extends DocsTestOptions {\n /**\n * Source kind to scan for runnable examples.\n * - `markdown` scans Markdown files for fenced code blocks.\n * - `jsdoc` scans JSDoc/TSDoc `@example` blocks through ox-content's docs extractor.\n * @default \"markdown\"\n */\n source?: DocsTestSource;\n\n /**\n * Markdown glob patterns, or source-file include globs when `source` is `jsdoc`.\n */\n include?: string | string[];\n\n /**\n * Glob patterns to skip. For `jsdoc`, this is passed to docs extraction as `exclude`.\n */\n ignore?: string | string[];\n\n /**\n * Working directory used for globs and generated test files.\n * @default process.cwd()\n */\n cwd?: string;\n\n /**\n * Source directories to scan when `source` is `jsdoc`.\n * @default [\"./src\"]\n */\n src?: string | string[];\n\n /**\n * Additional docs extraction options for `jsdoc` source mode.\n */\n docs?: DocsOptions;\n}\n\nexport interface DocsTestFileOptions extends DocsTestHarnessOptions {\n /**\n * Directory for generated Vitest files.\n * @default \".cache/ox-content-docs-tests\"\n */\n generatedDir?: string;\n\n /**\n * Remove the generated directory before writing files.\n * @default true\n */\n clean?: boolean;\n\n /**\n * Optional code prepended to every generated test file.\n */\n setupCode?: string;\n\n /**\n * How each generated file should execute the docs block.\n * - `test` wraps the block in a generated Vitest test, similar to Cargo doctests.\n * - `module` writes the block as-is for snippets that declare their own tests.\n * @default \"test\"\n */\n executionMode?: \"test\" | \"module\";\n\n /**\n * Module used for the generated `test` import.\n * @default \"vitest\"\n */\n testImport?: string;\n\n /**\n * Optional static import specifier rewrites for generated test files.\n */\n importRewrites?: Record<string, string>;\n}\n\nexport interface WrittenDocsTestFile {\n filePath: string;\n sourcePath: string;\n relativePath: string;\n startLine: number;\n endLine: number;\n language: string;\n}\n\nexport interface DocsTestWriteResult {\n cwd: string;\n generatedDir: string;\n blocks: CollectedDocsTest[];\n files: WrittenDocsTestFile[];\n}\n\nexport interface RunDocsTestsOptions extends DocsTestFileOptions {\n /**\n * Vitest-compatible command to run.\n * @default \"vitest\"\n */\n vitestCommand?: string;\n\n /**\n * Arguments passed before generated test file paths.\n * @default [\"run\"]\n */\n vitestArgs?: string[];\n\n /**\n * Environment overrides for the Vitest child process.\n */\n env?: NodeJS.ProcessEnv;\n\n /**\n * Allow a scan that finds no runnable docs tests.\n * @default false\n */\n allowEmpty?: boolean;\n}\n\nexport interface DocsTestRunResult extends DocsTestWriteResult {\n command: string;\n args: string[];\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport class DocsTestRunError extends Error {\n readonly result: DocsTestRunResult;\n\n constructor(result: DocsTestRunResult) {\n const command = [result.command, ...result.args].join(\" \");\n super(`[ox-content] Docs tests failed with exit code ${result.exitCode}: ${command}`);\n this.name = \"DocsTestRunError\";\n this.result = result;\n }\n}\n\nexport async function collectDocsTests(\n options: DocsTestHarnessOptions,\n): Promise<CollectedDocsTest[]> {\n const cwd = path.resolve(options.cwd ?? process.cwd());\n if ((options.source ?? \"markdown\") === \"jsdoc\") {\n return collectJsdocDocsTests(options, cwd);\n }\n\n return collectMarkdownDocsTests(options, cwd);\n}\n\nasync function collectMarkdownDocsTests(\n options: DocsTestHarnessOptions,\n cwd: string,\n): Promise<CollectedDocsTest[]> {\n const include = toArray(options.include);\n const ignore = toArray(options.ignore);\n const files = new Map<string, string>();\n\n if (include.length === 0) {\n throw new Error(\"[ox-content] Docs test include patterns are required for markdown sources.\");\n }\n\n for (const pattern of include) {\n const matches = await glob(pattern, {\n absolute: true,\n cwd,\n ignore,\n nodir: true,\n });\n\n for (const filePath of matches) {\n const absolutePath = path.resolve(filePath);\n files.set(absolutePath, normalizePath(path.relative(cwd, absolutePath)));\n }\n }\n\n const blocks: CollectedDocsTest[] = [];\n let index = 0;\n for (const [sourcePath, relativePath] of [...files.entries()].sort((left, right) =>\n left[0].localeCompare(right[0]),\n )) {\n const source = await fs.readFile(sourcePath, \"utf-8\");\n const extracted = await extractDocsTests(source, {\n languages: options.languages,\n requireMeta: options.requireMeta,\n });\n\n for (const block of extracted) {\n blocks.push({\n ...block,\n sourcePath,\n relativePath,\n index,\n });\n index += 1;\n }\n }\n\n return blocks;\n}\n\nasync function collectJsdocDocsTests(\n options: DocsTestHarnessOptions,\n cwd: string,\n): Promise<CollectedDocsTest[]> {\n const docsOptions = resolveJsdocDocsOptions(options, cwd);\n const docs = await extractDocs(docsOptions.src, docsOptions);\n const blocks: CollectedDocsTest[] = [];\n let index = 0;\n\n for (const doc of sortDocs(docs)) {\n for (const entry of sortEntries(doc.entries)) {\n for (const example of entry.examples ?? []) {\n const extracted = await extractDocsTests(example, {\n languages: options.languages,\n requireMeta: options.requireMeta,\n });\n const sourcePath = resolveEntrySourcePath(entry, doc, cwd);\n const relativePath = relativeSourcePath(cwd, sourcePath);\n\n for (const block of extracted) {\n blocks.push({\n ...block,\n sourcePath,\n relativePath,\n startLine: entry.line,\n endLine: entry.endLine,\n index,\n });\n index += 1;\n }\n }\n }\n }\n\n return blocks;\n}\n\nfunction resolveJsdocDocsOptions(\n options: DocsTestHarnessOptions,\n cwd: string,\n): ResolvedDocsOptions {\n const docsOptions: DocsOptions = {\n ...options.docs,\n };\n\n if (options.src !== undefined) {\n docsOptions.src = toArray(options.src);\n }\n if (options.include !== undefined) {\n docsOptions.include = toArray(options.include);\n }\n if (options.ignore !== undefined) {\n docsOptions.exclude = toArray(options.ignore);\n }\n\n const resolved = resolveDocsOptions(docsOptions);\n return {\n ...resolved,\n src: resolved.src.map((sourceDir) => path.resolve(cwd, sourceDir)),\n entryPoints: resolved.entryPoints?.map((entryPoint) => ({\n ...entryPoint,\n path: path.resolve(cwd, entryPoint.path),\n })),\n };\n}\n\nfunction sortDocs(docs: ExtractedDocs[]): ExtractedDocs[] {\n return [...docs].sort((left, right) => left.file.localeCompare(right.file));\n}\n\nfunction sortEntries(entries: DocEntry[]): DocEntry[] {\n return [...entries].sort((left, right) => {\n const byFile = left.file.localeCompare(right.file);\n if (byFile !== 0) return byFile;\n const byLine = left.line - right.line;\n if (byLine !== 0) return byLine;\n return left.name.localeCompare(right.name);\n });\n}\n\nfunction resolveEntrySourcePath(entry: DocEntry, doc: ExtractedDocs, cwd: string): string {\n const sourcePath = entry.file || doc.file;\n return path.isAbsolute(sourcePath) ? path.resolve(sourcePath) : path.resolve(cwd, sourcePath);\n}\n\nfunction relativeSourcePath(cwd: string, sourcePath: string): string {\n const relativePath = path.relative(cwd, sourcePath);\n if (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n return normalizePath(relativePath);\n }\n return normalizePath(sourcePath);\n}\n\nexport async function writeDocsTestFiles(\n options: DocsTestFileOptions,\n): Promise<DocsTestWriteResult> {\n const cwd = path.resolve(options.cwd ?? process.cwd());\n const generatedDir = path.resolve(cwd, options.generatedDir ?? \".cache/ox-content-docs-tests\");\n const clean = options.clean ?? true;\n const blocks = await collectDocsTests({ ...options, cwd });\n\n if (clean) {\n await fs.rm(generatedDir, { recursive: true, force: true });\n }\n await fs.mkdir(generatedDir, { recursive: true });\n\n const files = await Promise.all(\n blocks.map(async (block) => {\n const filePath = path.join(generatedDir, docsTestFileName(block));\n await fs.writeFile(filePath, renderDocsTestFile(block, options), \"utf-8\");\n return {\n filePath,\n sourcePath: block.sourcePath,\n relativePath: block.relativePath,\n startLine: block.startLine,\n endLine: block.endLine,\n language: block.language,\n };\n }),\n );\n\n return {\n cwd,\n generatedDir,\n blocks,\n files,\n };\n}\n\nexport async function runDocsTests(options: RunDocsTestsOptions): Promise<DocsTestRunResult> {\n const writeResult = await writeDocsTestFiles(options);\n const command = options.vitestCommand ?? \"vitest\";\n const leadingArgs = options.vitestArgs ?? [\"run\"];\n const fileArgs = writeResult.files.map((file) => file.filePath);\n const args = [...leadingArgs, ...fileArgs];\n\n if (fileArgs.length === 0) {\n if (options.allowEmpty) {\n return {\n ...writeResult,\n command,\n args,\n exitCode: 0,\n stdout: \"\",\n stderr: \"\",\n };\n }\n throw new Error(\"[ox-content] No runnable docs test blocks were found.\");\n }\n\n const result = await runCommand(command, args, {\n cwd: writeResult.cwd,\n env: mergeEnv(options.env),\n });\n const runResult = {\n ...writeResult,\n command,\n args,\n ...result,\n };\n\n if (runResult.exitCode !== 0) {\n throw new DocsTestRunError(runResult);\n }\n\n return runResult;\n}\n\nfunction renderDocsTestFile(block: CollectedDocsTest, options: DocsTestFileOptions): string {\n const parts = [\n \"// Generated by @ox-content/vite-plugin docs test harness.\",\n `// Source: ${block.relativePath}:${block.startLine}-${block.endLine}`,\n \"\",\n ];\n const setupCode = options.setupCode?.trimEnd();\n const code = rewriteImports(block.code.trimEnd(), options.importRewrites);\n if (setupCode) {\n parts.push(setupCode, \"\");\n }\n if ((options.executionMode ?? \"test\") === \"module\") {\n parts.push(code, \"\");\n return parts.join(\"\\n\");\n }\n\n const { imports, body } = partitionImports(code);\n parts.push(\n `import { test } from ${JSON.stringify(\n rewriteSpecifier(options.testImport ?? \"vitest\", options.importRewrites),\n )};`,\n );\n if (imports.length > 0) {\n parts.push(...imports);\n }\n parts.push(\n \"\",\n `test(${JSON.stringify(`${block.relativePath}:${block.startLine}`)}, async () => {`,\n );\n if (body.trim().length > 0) {\n parts.push(indentCode(body.trimEnd()));\n }\n parts.push(\"});\", \"\");\n return parts.join(\"\\n\");\n}\n\nfunction partitionImports(source: string): { imports: string[]; body: string } {\n const imports: string[] = [];\n const body: string[] = [];\n const lines = source.split(/\\r?\\n/);\n let currentImport: string[] | undefined;\n\n for (const line of lines) {\n if (currentImport) {\n currentImport.push(line);\n if (endsImportDeclaration(line)) {\n imports.push(currentImport.join(\"\\n\"));\n currentImport = undefined;\n }\n continue;\n }\n\n if (startsStaticImport(line)) {\n if (endsImportDeclaration(line)) {\n imports.push(line);\n } else {\n currentImport = [line];\n }\n continue;\n }\n\n body.push(line);\n }\n\n if (currentImport) {\n body.push(...currentImport);\n }\n\n return { imports, body: body.join(\"\\n\") };\n}\n\nfunction startsStaticImport(line: string): boolean {\n const trimmed = line.trimStart();\n return trimmed.startsWith(\"import \") && !trimmed.startsWith(\"import(\");\n}\n\nfunction endsImportDeclaration(line: string): boolean {\n const trimmed = line.trim();\n return (\n trimmed.endsWith(\";\") ||\n /^import\\s+[\"'][^\"']+[\"']$/.test(trimmed) ||\n /\\sfrom\\s+[\"'][^\"']+[\"']$/.test(trimmed)\n );\n}\n\nfunction indentCode(source: string): string {\n return source\n .split(\"\\n\")\n .map((line) => (line.length > 0 ? ` ${line}` : line))\n .join(\"\\n\");\n}\n\nfunction rewriteImports(source: string, rewrites: Record<string, string> | undefined): string {\n if (!rewrites) {\n return source;\n }\n\n let result = source;\n for (const [from, to] of Object.entries(rewrites)) {\n const escaped = escapeRegExp(from);\n result = result\n .replace(new RegExp(`(from\\\\s+[\"'])${escaped}([\"'])`, \"g\"), `$1${to}$2`)\n .replace(new RegExp(`(import\\\\s+[\"'])${escaped}([\"'])`, \"g\"), `$1${to}$2`)\n .replace(new RegExp(`(import\\\\(\\\\s*[\"'])${escaped}([\"']\\\\s*\\\\))`, \"g\"), `$1${to}$2`);\n }\n return result;\n}\n\n/**\n * Applies the same import rewrite table to harness-owned imports.\n *\n * @internal\n * @example\n * ```ts docs-test\n * import { expect } from \"vitest\";\n * import { extractDocsTests } from \"../../src/code-blocks\";\n *\n * const markdown = [\n * \"```ts docs-test\",\n * \"expect(1 + 1).toBe(2);\",\n * \"```\",\n * ].join(\"\\n\");\n *\n * const blocks = await extractDocsTests(markdown);\n *\n * expect(blocks).toHaveLength(1);\n * expect(blocks[0]?.code).toMatchInlineSnapshot('\"expect(1 + 1).toBe(2);\"');\n * ```\n */\nfunction rewriteSpecifier(specifier: string, rewrites: Record<string, string> | undefined): string {\n return rewrites?.[specifier] ?? specifier;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction docsTestFileName(block: CollectedDocsTest): string {\n const baseName =\n block.relativePath\n .replace(/^\\.\\//, \"\")\n .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"docs-test\";\n return `${baseName}-L${block.startLine}-${block.index + 1}.test.${extensionForLanguage(\n block.language,\n )}`;\n}\n\nfunction extensionForLanguage(language: string): string {\n switch (language.toLowerCase()) {\n case \"jsx\":\n return \"jsx\";\n case \"tsx\":\n return \"tsx\";\n case \"mjs\":\n return \"mjs\";\n case \"mts\":\n return \"mts\";\n case \"js\":\n return \"js\";\n default:\n return \"ts\";\n }\n}\n\nfunction toArray(value: string | string[] | undefined): string[] {\n if (!value) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction normalizePath(value: string): string {\n return value.split(path.sep).join(\"/\");\n}\n\nfunction mergeEnv(overrides: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...process.env };\n for (const [key, value] of Object.entries(overrides ?? {})) {\n if (value === undefined) {\n delete env[key];\n } else {\n env[key] = value;\n }\n }\n return env;\n}\n\nfunction runCommand(\n command: string,\n args: string[],\n options: { cwd: string; env: NodeJS.ProcessEnv },\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: options.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n\n if (child.stdout) {\n child.stdout.setEncoding(\"utf-8\");\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n }\n if (child.stderr) {\n child.stderr.setEncoding(\"utf-8\");\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n }\n child.on(\"error\", reject);\n child.on(\"close\", (exitCode) => {\n resolve({ exitCode: exitCode ?? 1, stdout, stderr });\n });\n });\n}\n","import { createRequire } from \"node:module\";\nimport type { CSpellUserSettings, SpellCheckFileOptions, ValidationIssue } from \"cspell-lib\";\n\nconst require = createRequire(import.meta.url);\n\nconst SUPPORTED_MARKDOWN_LINT_LANGUAGES = [\"en\", \"ja\", \"zh\", \"fr\", \"de\", \"pl\"] as const;\nconst DEFAULT_LANGUAGES = [\"en\"] as const;\nconst DEFAULT_RULES = {\n duplicateHeadings: true,\n headingIncrement: true,\n maxConsecutiveBlankLines: 1,\n repeatedPunctuation: true,\n repeatedWords: true,\n spellcheck: true,\n trailingSpaces: true,\n} as const;\nconst DEFAULT_CSPELL_IMPORTS: Partial<Record<MarkdownLintLanguage, string>> = {\n de: \"@cspell/dict-de-de/cspell-ext.json\",\n en: \"@cspell/dict-en_us/cspell-ext.json\",\n fr: \"@cspell/dict-fr-fr/cspell-ext.json\",\n pl: \"@cspell/dict-pl_pl/cspell-ext.json\",\n};\n\nexport type MarkdownLintLanguage = (typeof SUPPORTED_MARKDOWN_LINT_LANGUAGES)[number];\nexport type MarkdownLintSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * Opt-in standard dictionary sources.\n *\n * The default provider uses CSpell dictionary packages because those packages\n * are actively maintained and expose locale-specific dictionaries in a stable\n * config format. Languages without a bundled preset can still be added through\n * custom `imports`.\n */\nexport interface MarkdownLintStandardDictionaryOptions {\n /**\n * Standard dictionary provider.\n * @default \"cspell\"\n */\n provider?: \"cspell\";\n\n /**\n * Languages whose default standard dictionaries should be enabled.\n *\n * Built-in preset package mappings currently exist for `en`, `fr`, `de`,\n * and `pl`. For other languages, use `imports`.\n *\n * @default []\n */\n languages?: MarkdownLintLanguage[];\n\n /**\n * Additional CSpell-compatible imports.\n *\n * This can point at installed packages like\n * `@cspell/dict-fr-fr/cspell-ext.json` or local CSpell config files.\n * @default []\n */\n imports?: string[];\n\n /**\n * Base URL or path used when resolving `imports`.\n *\n * @default new URL(\".\", import.meta.url)\n */\n resolveImportsRelativeTo?: string | URL;\n}\n\n/**\n * Additional dictionary configuration for the Markdown linter.\n */\nexport interface MarkdownLintDictionaryOptions {\n /**\n * Words ignored across all configured languages.\n * @default []\n */\n words?: string[];\n\n /**\n * Extra words to allow per language.\n * @default {}\n */\n byLanguage?: Partial<Record<MarkdownLintLanguage, string[]>>;\n\n /**\n * Words that should never produce diagnostics.\n * @default []\n */\n ignoredWords?: string[];\n\n /**\n * Opt-in standard dictionary datasets.\n *\n * By default the linter stays on a minimal built-in dictionary. Enable this\n * to load larger locale dictionaries from a standard external source.\n * @default false\n */\n standard?: MarkdownLintStandardDictionaryOptions | false;\n}\n\n/**\n * Rule switches for Markdown linting.\n */\nexport interface MarkdownLintRuleOptions {\n /**\n * Report headings that repeat the same visible text.\n * @default true\n */\n duplicateHeadings?: boolean;\n\n /**\n * Report heading depth jumps such as `#` -> `###`.\n * @default true\n */\n headingIncrement?: boolean;\n\n /**\n * Maximum number of blank lines allowed in a row.\n * @default 1\n */\n maxConsecutiveBlankLines?: number;\n\n /**\n * Report duplicated terminal punctuation such as `!!` or `??`.\n * @default true\n */\n repeatedPunctuation?: boolean;\n\n /**\n * Report adjacent repeated words in visible prose.\n * @default true\n */\n repeatedWords?: boolean;\n\n /**\n * Enable built-in multilingual spellchecking.\n * @default true\n */\n spellcheck?: boolean;\n\n /**\n * Report trailing spaces.\n * @default true\n */\n trailingSpaces?: boolean;\n}\n\n/**\n * Options for linting Markdown documents.\n */\nexport interface MarkdownLintOptions {\n /**\n * Languages enabled for spellchecking.\n *\n * When `dictionary.standard.languages` is provided and this option is\n * omitted, those languages are used instead.\n *\n * @default ['en']\n */\n languages?: MarkdownLintLanguage[];\n\n /**\n * Rule configuration.\n * Omitted fields use `MarkdownLintRuleOptions` defaults.\n * @default {}\n */\n rules?: MarkdownLintRuleOptions;\n\n /**\n * Built-in and opt-in standard dictionary overrides.\n * @default {}\n */\n dictionary?: MarkdownLintDictionaryOptions;\n\n /**\n * Enable MDX-aware syntax masking while linting visible prose.\n * File-oriented APIs infer this from `.mdx` when omitted.\n * @default false for content APIs; inferred for file APIs\n */\n mdx?: boolean;\n}\n\n/**\n * A single Markdown lint diagnostic.\n */\nexport interface MarkdownLintDiagnostic {\n /**\n * Stable rule identifier.\n */\n ruleId: string;\n\n /**\n * Diagnostic severity.\n */\n severity: MarkdownLintSeverity;\n\n /**\n * Human-readable explanation.\n */\n message: string;\n\n /**\n * 1-indexed line number.\n */\n line: number;\n\n /**\n * 1-indexed start column.\n */\n column: number;\n\n /**\n * 1-indexed end line.\n */\n endLine: number;\n\n /**\n * 1-indexed end column.\n */\n endColumn: number;\n\n /**\n * Language used for spellchecking, when relevant.\n */\n language?: MarkdownLintLanguage;\n\n /**\n * Suggested replacements, when available.\n */\n suggestions?: string[];\n}\n\n/**\n * Markdown lint report.\n */\nexport interface MarkdownLintResult {\n /**\n * All collected diagnostics.\n */\n diagnostics: MarkdownLintDiagnostic[];\n\n /**\n * Number of error diagnostics.\n */\n errorCount: number;\n\n /**\n * Number of warning diagnostics.\n */\n warningCount: number;\n\n /**\n * Number of info diagnostics.\n */\n infoCount: number;\n}\n\ninterface NormalizedStandardDictionaryOptions {\n imports: string[];\n languages: MarkdownLintLanguage[];\n provider: \"cspell\";\n resolveImportsRelativeTo: string | URL;\n}\n\ninterface InternalNormalizedMarkdownLintOptions {\n dictionary: Omit<MarkdownLintDictionaryOptions, \"standard\"> & {\n standard: NormalizedStandardDictionaryOptions | false;\n };\n languages: MarkdownLintLanguage[];\n mdx: boolean;\n rules: Required<MarkdownLintRuleOptions>;\n}\n\ninterface NapiMarkdownLintLanguageWords {\n language: MarkdownLintLanguage;\n words: string[];\n}\n\ninterface NapiMarkdownLintOptions {\n dictionary?: {\n byLanguage?: NapiMarkdownLintLanguageWords[];\n ignoredWords?: string[];\n words?: string[];\n };\n languages?: MarkdownLintLanguage[];\n mdx?: boolean;\n rules?: Required<MarkdownLintRuleOptions>;\n}\n\ninterface NapiMarkdownLintResult extends MarkdownLintResult {\n maskedDocument: string;\n}\n\ninterface NapiMarkdownLintModule {\n lintMarkdownDocuments?: (\n sources: string[],\n options?: NapiMarkdownLintOptions,\n ) => NapiMarkdownLintResult[];\n lintMarkdown: (source: string, options?: NapiMarkdownLintOptions) => NapiMarkdownLintResult;\n}\n\nlet napiBinding: NapiMarkdownLintModule | null | undefined;\nlet cspellLibPromise: Promise<typeof import(\"cspell-lib\")> | undefined;\n\n/**\n * Lints Markdown prose with the Rust-backed built-in rule engine.\n */\nexport function lintMarkdown(\n source: string,\n options: MarkdownLintOptions = {},\n): MarkdownLintResult {\n const normalizedOptions = normalizeLintOptions(options);\n return lintMarkdownWithNormalizedOptions(source, normalizedOptions);\n}\n\n/**\n * Async Markdown linter that supports opt-in standard dictionaries.\n */\nexport async function lintMarkdownAsync(\n source: string,\n options: MarkdownLintOptions = {},\n): Promise<MarkdownLintResult> {\n const normalizedOptions = normalizeLintOptions(options);\n const [result] = await lintMarkdownDocumentsWithNormalizedOptions([source], normalizedOptions);\n return result ?? createEmptyLintResult();\n}\n\n/**\n * Internal batched Markdown linting entry point used by file-based workflows.\n */\nexport async function lintMarkdownDocumentsAsync(\n sources: string[],\n options: MarkdownLintOptions = {},\n): Promise<MarkdownLintResult[]> {\n const normalizedOptions = normalizeLintOptions(options);\n return lintMarkdownDocumentsWithNormalizedOptions(sources, normalizedOptions);\n}\n\nfunction lintMarkdownWithNormalizedOptions(\n source: string,\n normalizedOptions: InternalNormalizedMarkdownLintOptions,\n): MarkdownLintResult {\n if (normalizedOptions.dictionary.standard) {\n throw new Error(\n \"[ox-content] lintMarkdownAsync is required when dictionary.standard is enabled.\",\n );\n }\n\n const napi = loadNapiBindingSync();\n return stripMaskedDocument(\n napi.lintMarkdown(source, toNapiMarkdownLintOptions(normalizedOptions)),\n );\n}\n\nasync function lintMarkdownDocumentsWithNormalizedOptions(\n sources: string[],\n normalizedOptions: InternalNormalizedMarkdownLintOptions,\n): Promise<MarkdownLintResult[]> {\n if (sources.length === 0) {\n return [];\n }\n\n const napi = loadNapiBindingSync();\n const napiOptions = toNapiMarkdownLintOptions(\n normalizedOptions,\n Boolean(normalizedOptions.dictionary.standard),\n );\n const builtInResults =\n typeof napi.lintMarkdownDocuments === \"function\"\n ? napi.lintMarkdownDocuments(sources, napiOptions)\n : sources.map((source) => napi.lintMarkdown(source, napiOptions));\n\n if (!normalizedOptions.rules.spellcheck || !normalizedOptions.dictionary.standard) {\n return builtInResults.map(stripMaskedDocument);\n }\n\n const standardDiagnostics = await runStandardSpellcheckDocuments(\n builtInResults.map((result) => result.maskedDocument),\n normalizedOptions,\n );\n\n return builtInResults.map((result, index) =>\n summarizeDiagnostics(\n sortDiagnostics(result.diagnostics.concat(standardDiagnostics[index] ?? [])),\n ),\n );\n}\n\nfunction loadNapiBindingSync(): NapiMarkdownLintModule {\n if (napiBinding) {\n return napiBinding;\n }\n\n if (napiBinding === null) {\n throw new Error(\n \"[ox-content] @ox-content/napi is required for Markdown linting. Please ensure the NAPI module is built.\",\n );\n }\n\n try {\n const loaded = require(\"@ox-content/napi\") as NapiMarkdownLintModule & {\n default?: Partial<NapiMarkdownLintModule>;\n };\n napiBinding =\n loaded.default && typeof loaded.default === \"object\"\n ? { ...loaded.default, ...loaded }\n : loaded;\n\n return napiBinding;\n } catch {\n napiBinding = null;\n throw new Error(\n \"[ox-content] @ox-content/napi is required for Markdown linting. Please ensure the NAPI module is built.\",\n );\n }\n}\n\nfunction toNapiMarkdownLintOptions(\n options: InternalNormalizedMarkdownLintOptions,\n disableBuiltinSpellcheck = false,\n): NapiMarkdownLintOptions {\n const byLanguage = Object.entries(options.dictionary.byLanguage ?? {}).map(\n ([language, words]): NapiMarkdownLintLanguageWords => ({\n language: language as MarkdownLintLanguage,\n words,\n }),\n );\n\n return {\n dictionary: {\n byLanguage,\n ignoredWords: options.dictionary.ignoredWords,\n words: options.dictionary.words,\n },\n languages: options.languages,\n mdx: options.mdx,\n rules: {\n ...options.rules,\n spellcheck: disableBuiltinSpellcheck ? false : options.rules.spellcheck,\n },\n };\n}\n\nfunction stripMaskedDocument(result: NapiMarkdownLintResult): MarkdownLintResult {\n return {\n diagnostics: result.diagnostics,\n errorCount: result.errorCount,\n infoCount: result.infoCount,\n warningCount: result.warningCount,\n };\n}\n\nfunction normalizeLintOptions(options: MarkdownLintOptions): InternalNormalizedMarkdownLintOptions {\n const standardDictionary =\n options.dictionary?.standard && typeof options.dictionary.standard === \"object\"\n ? options.dictionary.standard\n : undefined;\n const optionLanguages = options.languages?.filter((language): language is MarkdownLintLanguage =>\n SUPPORTED_MARKDOWN_LINT_LANGUAGES.includes(language),\n );\n const standardLanguages = standardDictionary?.languages?.filter(\n (language): language is MarkdownLintLanguage =>\n SUPPORTED_MARKDOWN_LINT_LANGUAGES.includes(language),\n );\n const languages: MarkdownLintLanguage[] = optionLanguages ??\n standardLanguages ?? [...DEFAULT_LANGUAGES];\n\n const standard = normalizeStandardDictionaryOptions(options.dictionary?.standard, languages);\n\n return {\n dictionary: {\n ...options.dictionary,\n standard,\n },\n languages: [...new Set(languages)],\n mdx: options.mdx ?? false,\n rules: {\n duplicateHeadings: options.rules?.duplicateHeadings ?? DEFAULT_RULES.duplicateHeadings,\n headingIncrement: options.rules?.headingIncrement ?? DEFAULT_RULES.headingIncrement,\n maxConsecutiveBlankLines:\n options.rules?.maxConsecutiveBlankLines ?? DEFAULT_RULES.maxConsecutiveBlankLines,\n repeatedPunctuation: options.rules?.repeatedPunctuation ?? DEFAULT_RULES.repeatedPunctuation,\n repeatedWords: options.rules?.repeatedWords ?? DEFAULT_RULES.repeatedWords,\n spellcheck: options.rules?.spellcheck ?? DEFAULT_RULES.spellcheck,\n trailingSpaces: options.rules?.trailingSpaces ?? DEFAULT_RULES.trailingSpaces,\n },\n };\n}\n\nfunction normalizeStandardDictionaryOptions(\n standard: MarkdownLintDictionaryOptions[\"standard\"],\n fallbackLanguages: MarkdownLintLanguage[],\n): NormalizedStandardDictionaryOptions | false {\n if (!standard) {\n return false;\n }\n\n const languages =\n standard.languages?.filter((language): language is MarkdownLintLanguage =>\n SUPPORTED_MARKDOWN_LINT_LANGUAGES.includes(language),\n ) ?? fallbackLanguages;\n const customImports = standard.imports ?? [];\n const missingPresetLanguages = languages.filter((language) => !DEFAULT_CSPELL_IMPORTS[language]);\n\n if (missingPresetLanguages.length > 0 && customImports.length === 0) {\n throw new Error(\n `[ox-content] No bundled standard dictionary preset exists for ${missingPresetLanguages.join(\n \", \",\n )}. Provide dictionary.standard.imports to enable those languages.`,\n );\n }\n\n const imports = [\n ...languages\n .map((language) => DEFAULT_CSPELL_IMPORTS[language])\n .filter((value): value is string => Boolean(value)),\n ...customImports,\n ];\n\n if (imports.length === 0) {\n throw new Error(\n \"[ox-content] dictionary.standard requires at least one bundled preset language or custom import.\",\n );\n }\n\n return {\n imports: [...new Set(imports)],\n languages: [...new Set(languages)],\n provider: standard.provider ?? \"cspell\",\n resolveImportsRelativeTo: standard.resolveImportsRelativeTo ?? new URL(\".\", import.meta.url),\n };\n}\n\nasync function runStandardSpellcheckDocuments(\n maskedDocuments: string[],\n options: InternalNormalizedMarkdownLintOptions,\n): Promise<MarkdownLintDiagnostic[][]> {\n const standard = options.dictionary.standard;\n\n if (!standard || maskedDocuments.length === 0) {\n return maskedDocuments.map(() => []);\n }\n\n try {\n const { spellCheckDocument } = await loadCspellLib();\n const locale = standard.languages.join(\",\");\n const settings = createStandardSpellcheckSettings(options, locale);\n const spellCheckOptions = {\n generateSuggestions: true,\n noConfigSearch: true,\n numSuggestions: 3,\n resolveImportsRelativeTo: standard.resolveImportsRelativeTo,\n } satisfies SpellCheckFileOptions & { resolveImportsRelativeTo: string | URL };\n\n return Promise.all(\n maskedDocuments.map(async (maskedDocument, index) => {\n if (maskedDocument.trim().length === 0) {\n return [];\n }\n\n const result = await spellCheckDocument(\n {\n languageId: \"plaintext\",\n locale,\n text: maskedDocument,\n uri: `file:///ox-content-lint-${index}.md`,\n },\n spellCheckOptions,\n settings,\n );\n\n // Precompute the document's newline offsets once so each issue's line\n // can be resolved with a binary search instead of a fresh O(N) scan\n // from offset 0 (which made line resolution O(issues * length)).\n const newlineOffsets: number[] = [];\n for (let i = 0; i < maskedDocument.length; i++) {\n if (maskedDocument.charCodeAt(i) === 10) {\n newlineOffsets.push(i);\n }\n }\n\n return result.issues.map((issue) =>\n mapStandardIssueToDiagnostic(issue, standard.languages, newlineOffsets),\n );\n }),\n );\n } catch (error) {\n const imports = standard.imports.join(\", \");\n const message =\n imports.length > 0\n ? `[ox-content] Failed to load standard dictionaries from ${imports}. Verify the imports and install the referenced CSpell packages.`\n : \"[ox-content] Failed to load the configured standard dictionaries.\";\n\n throw new Error(message, {\n cause: error,\n });\n }\n}\n\nfunction createStandardSpellcheckSettings(\n options: InternalNormalizedMarkdownLintOptions,\n locale: string,\n): CSpellUserSettings {\n return {\n import: options.dictionary.standard ? options.dictionary.standard.imports : [],\n ignoreWords: options.dictionary.ignoredWords,\n language: locale,\n version: \"0.2\",\n words: [\n ...(options.dictionary.words ?? []),\n ...Object.values(options.dictionary.byLanguage ?? {}).flat(),\n ],\n };\n}\n\nasync function loadCspellLib(): Promise<typeof import(\"cspell-lib\")> {\n // CSpell is optional and relatively heavy; lazy-load it only when standard\n // dictionaries are enabled, then reuse the same module promise for all files\n // in the lint run.\n cspellLibPromise ??= import(\"cspell-lib\");\n return cspellLibPromise;\n}\n\nfunction mapStandardIssueToDiagnostic(\n issue: ValidationIssue,\n languages: MarkdownLintLanguage[],\n newlineOffsets: number[],\n): MarkdownLintDiagnostic {\n const line = getLineNumberAtOffset(newlineOffsets, issue.line.offset);\n const column = issue.offset - issue.line.offset + 1;\n const length = issue.length ?? issue.text.length;\n\n return {\n column,\n endColumn: column + length,\n endLine: line,\n language: inferStandardIssueLanguage(issue.text, languages),\n line,\n message: `Unknown word \"${issue.text}\".`,\n ruleId: \"spellcheck\",\n severity: \"warning\",\n suggestions: issue.suggestions?.slice(0, 3),\n };\n}\n\nfunction getLineNumberAtOffset(newlineOffsets: number[], offset: number): number {\n // Line number = 1 + (count of newline offsets strictly less than `offset`).\n // This matches the old linear scan exactly: a newline can only exist at an\n // index < text.length, so counting positions `< offset` over the whole\n // document gives the same count for every `offset` (including past EOF).\n let lo = 0;\n let hi = newlineOffsets.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (newlineOffsets[mid] < offset) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n\n return lo + 1;\n}\n\nfunction inferStandardIssueLanguage(\n word: string,\n languages: MarkdownLintLanguage[],\n): MarkdownLintLanguage | undefined {\n if (/[\\p{Script=Hiragana}\\p{Script=Katakana}]/u.test(word) && languages.includes(\"ja\")) {\n return \"ja\";\n }\n\n if (/[\\p{Script=Han}]/u.test(word)) {\n if (languages.includes(\"zh\") && !languages.includes(\"ja\")) {\n return \"zh\";\n }\n if (languages.includes(\"ja\") && !languages.includes(\"zh\")) {\n return \"ja\";\n }\n }\n\n if (/[\\p{Script=Latin}]/u.test(word)) {\n const latinLanguages = languages.filter(\n (language): language is Exclude<MarkdownLintLanguage, \"ja\" | \"zh\"> =>\n language !== \"ja\" && language !== \"zh\",\n );\n\n if (latinLanguages.length === 1) {\n return latinLanguages[0];\n }\n\n return inferLatinLanguageFromCharacters(word, latinLanguages);\n }\n\n return undefined;\n}\n\nfunction inferLatinLanguageFromCharacters(\n word: string,\n languages: Exclude<MarkdownLintLanguage, \"ja\" | \"zh\">[],\n): Exclude<MarkdownLintLanguage, \"ja\" | \"zh\"> | undefined {\n if (languages.includes(\"pl\") && /[ąćęłńóśźż]/iu.test(word)) {\n return \"pl\";\n }\n\n if (languages.includes(\"de\") && /[äöüß]/iu.test(word)) {\n return \"de\";\n }\n\n if (languages.includes(\"fr\") && /[àâæçéèêëîïôœùûüÿ]/iu.test(word)) {\n return \"fr\";\n }\n\n return undefined;\n}\n\nfunction summarizeDiagnostics(diagnostics: MarkdownLintDiagnostic[]): MarkdownLintResult {\n let errorCount = 0;\n let warningCount = 0;\n let infoCount = 0;\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.severity === \"error\") {\n errorCount += 1;\n } else if (diagnostic.severity === \"warning\") {\n warningCount += 1;\n } else {\n infoCount += 1;\n }\n }\n\n return { diagnostics, errorCount, infoCount, warningCount };\n}\n\nfunction createEmptyLintResult(): MarkdownLintResult {\n return summarizeDiagnostics([]);\n}\n\nfunction sortDiagnostics(diagnostics: MarkdownLintDiagnostic[]): MarkdownLintDiagnostic[] {\n return [...diagnostics].sort((left, right) => {\n if (left.line !== right.line) {\n return left.line - right.line;\n }\n\n if (left.column !== right.column) {\n return left.column - right.column;\n }\n\n return left.ruleId.localeCompare(right.ruleId);\n });\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { glob } from \"glob\";\nimport {\n lintMarkdownDocumentsAsync,\n lintMarkdownAsync,\n type MarkdownLintDiagnostic,\n type MarkdownLintOptions,\n type MarkdownLintResult,\n} from \"./lint\";\nimport { resolveMdxForFilePath } from \"./markdown\";\n\nconst DEFAULT_LINT_FILE_INCLUDE = [\"**/*.md\", \"**/*.markdown\", \"**/*.mdx\"] as const;\nconst DEFAULT_LINT_FILE_EXCLUDE = [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\"] as const;\n\n/**\n * File-oriented Markdown lint options for end-user configuration.\n *\n * This extends the content-level lint options with project-level targeting,\n * so consumers can decide which files should be checked and which paths should\n * be ignored.\n */\nexport interface MarkdownLintFileOptions extends MarkdownLintOptions {\n /**\n * Base directory used to resolve `include` and `exclude` patterns.\n * @default process.cwd()\n */\n cwd?: string;\n\n /**\n * Glob patterns for files to lint.\n * @default ['**\\/*.md', '**\\/*.markdown', '**\\/*.mdx']\n */\n include?: string[];\n\n /**\n * Glob patterns for files to exclude from linting.\n * @default ['**\\/node_modules/**', '**\\/.git/**', '**\\/dist/**']\n */\n exclude?: string[];\n\n /**\n * Alias of `exclude`.\n * When omitted, only `exclude` is used.\n * @default undefined\n */\n ignore?: string[];\n}\n\n/**\n * A lint diagnostic annotated with file metadata.\n */\nexport interface MarkdownLintFileDiagnostic extends MarkdownLintDiagnostic {\n filePath: string;\n relativePath: string;\n}\n\n/**\n * Lint result for a single file.\n */\nexport interface MarkdownLintFileResult extends MarkdownLintResult {\n filePath: string;\n relativePath: string;\n skipped: boolean;\n}\n\n/**\n * Aggregated lint result for multiple files.\n */\nexport interface MarkdownLintFilesResult {\n checkedFileCount: number;\n diagnostics: MarkdownLintFileDiagnostic[];\n errorCount: number;\n files: MarkdownLintFileResult[];\n infoCount: number;\n warningCount: number;\n}\n\ninterface ResolvedMarkdownLintFileOptions {\n cwd: string;\n exclude: string[];\n include: string[];\n lintOptions: MarkdownLintOptions;\n}\n\ninterface MarkdownLintFileEntry {\n filePath: string;\n relativePath: string;\n}\n\n/**\n * Returns true if the file path is included by the configured glob filters.\n */\nexport function shouldLintMarkdownFile(\n filePath: string,\n options: MarkdownLintFileOptions = {},\n): boolean {\n const resolvedOptions = resolveMarkdownLintFileOptions(options);\n return shouldLintAbsoluteFile(path.resolve(resolvedOptions.cwd, filePath), resolvedOptions);\n}\n\n/**\n * Lints a single Markdown file using project-style include/exclude settings.\n *\n * If the file is filtered out by `include` / `exclude`, the returned result is\n * marked as `skipped` and contains no diagnostics.\n */\nexport async function lintMarkdownFile(\n filePath: string,\n options: MarkdownLintFileOptions = {},\n): Promise<MarkdownLintFileResult> {\n const resolvedOptions = resolveMarkdownLintFileOptions(options);\n return lintMarkdownFileWithResolvedOptions(\n path.resolve(resolvedOptions.cwd, filePath),\n resolvedOptions,\n );\n}\n\n/**\n * Lints all Markdown files matched by the configured include/exclude patterns.\n */\nexport async function lintMarkdownFiles(\n options: MarkdownLintFileOptions = {},\n): Promise<MarkdownLintFilesResult> {\n const resolvedOptions = resolveMarkdownLintFileOptions(options);\n const matchedFiles = await collectMarkdownLintFileEntries(resolvedOptions);\n const sources = await Promise.all(\n matchedFiles.map((file) => fs.readFile(file.filePath, \"utf-8\")),\n );\n const results = await lintMatchedMarkdownFiles(\n matchedFiles,\n sources,\n resolvedOptions.lintOptions,\n );\n\n const files = matchedFiles.map((file, index): MarkdownLintFileResult => ({\n ...(results[index] ?? createEmptyLintResult()),\n filePath: file.filePath,\n relativePath: file.relativePath,\n skipped: false,\n }));\n\n const diagnostics = files.flatMap((fileResult) =>\n fileResult.diagnostics.map((diagnostic): MarkdownLintFileDiagnostic => ({\n ...diagnostic,\n filePath: fileResult.filePath,\n relativePath: fileResult.relativePath,\n })),\n );\n\n return {\n checkedFileCount: files.length,\n diagnostics,\n errorCount: files.reduce((count, fileResult) => count + fileResult.errorCount, 0),\n files,\n infoCount: files.reduce((count, fileResult) => count + fileResult.infoCount, 0),\n warningCount: files.reduce((count, fileResult) => count + fileResult.warningCount, 0),\n };\n}\n\nfunction resolveMarkdownLintFileOptions(\n options: MarkdownLintFileOptions,\n): ResolvedMarkdownLintFileOptions {\n return {\n cwd: path.resolve(options.cwd ?? process.cwd()),\n exclude: [\n ...new Set([...(options.exclude ?? DEFAULT_LINT_FILE_EXCLUDE), ...(options.ignore ?? [])]),\n ],\n include: [...new Set(options.include ?? DEFAULT_LINT_FILE_INCLUDE)],\n lintOptions: {\n dictionary: options.dictionary,\n languages: options.languages,\n mdx: options.mdx,\n rules: options.rules,\n },\n };\n}\n\nasync function lintMarkdownFileWithResolvedOptions(\n filePath: string,\n options: ResolvedMarkdownLintFileOptions,\n): Promise<MarkdownLintFileResult> {\n const absoluteFilePath = path.resolve(filePath);\n const relativePath = normalizePath(path.relative(options.cwd, absoluteFilePath));\n\n if (!shouldLintAbsoluteFile(absoluteFilePath, options)) {\n return {\n ...createEmptyLintResult(),\n filePath: absoluteFilePath,\n relativePath,\n skipped: true,\n };\n }\n\n const source = await fs.readFile(absoluteFilePath, \"utf-8\");\n const result = await lintMarkdownAsync(source, {\n ...options.lintOptions,\n mdx: resolveMdxForFilePath(absoluteFilePath, options.lintOptions.mdx),\n });\n\n return {\n ...result,\n filePath: absoluteFilePath,\n relativePath,\n skipped: false,\n };\n}\n\nasync function collectMarkdownLintFileEntries(\n options: ResolvedMarkdownLintFileOptions,\n): Promise<MarkdownLintFileEntry[]> {\n const files = new Map<string, MarkdownLintFileEntry>();\n\n for (const pattern of options.include) {\n const matches = await glob(pattern, {\n absolute: true,\n cwd: options.cwd,\n ignore: options.exclude,\n nocase: true,\n nodir: true,\n });\n\n for (const filePath of matches) {\n const absoluteFilePath = path.resolve(filePath);\n if (shouldLintAbsoluteFile(absoluteFilePath, options)) {\n files.set(absoluteFilePath, {\n filePath: absoluteFilePath,\n relativePath: normalizePath(path.relative(options.cwd, absoluteFilePath)),\n });\n }\n }\n }\n\n return [...files.values()].sort((left, right) => left.filePath.localeCompare(right.filePath));\n}\n\nfunction shouldLintAbsoluteFile(\n filePath: string,\n options: ResolvedMarkdownLintFileOptions,\n): boolean {\n const absolutePath = normalizePath(path.resolve(filePath));\n const relativePath = normalizePath(path.relative(options.cwd, absolutePath));\n\n const matches = (patterns: string[]) =>\n patterns.some((pattern) => {\n const normalizedPattern = normalizePath(pattern);\n return [relativePath, absolutePath].some(\n (candidate) =>\n path.matchesGlob(candidate, normalizedPattern) ||\n path.matchesGlob(candidate.toLowerCase(), normalizedPattern.toLowerCase()),\n );\n });\n\n return matches(options.include) && !matches(options.exclude);\n}\n\nasync function lintMatchedMarkdownFiles(\n files: MarkdownLintFileEntry[],\n sources: string[],\n options: MarkdownLintOptions,\n): Promise<MarkdownLintResult[]> {\n const results = Array.from({ length: sources.length }, () => createEmptyLintResult());\n\n await Promise.all(\n [false, true].map(async (mdx) => {\n const indexes = files\n .map((file, index) => ({\n index,\n mdx: resolveMdxForFilePath(file.filePath, options.mdx),\n }))\n .filter((entry) => entry.mdx === mdx)\n .map((entry) => entry.index);\n if (indexes.length === 0) {\n return;\n }\n\n const groupResults = await lintMarkdownDocumentsAsync(\n indexes.map((index) => sources[index] ?? \"\"),\n { ...options, mdx },\n );\n for (const [groupIndex, result] of groupResults.entries()) {\n const sourceIndex = indexes[groupIndex];\n if (sourceIndex !== undefined) {\n results[sourceIndex] = result;\n }\n }\n }),\n );\n\n return results;\n}\n\nfunction normalizePath(value: string): string {\n return value.split(path.sep).join(\"/\");\n}\n\nfunction createEmptyLintResult(): MarkdownLintResult {\n return {\n diagnostics: [],\n errorCount: 0,\n infoCount: 0,\n warningCount: 0,\n };\n}\n","/**\n * Vite Plugin for Ox Content\n *\n * Uses Vite's Environment API for SSG-focused Markdown processing.\n * Provides separate environments for client and server rendering.\n */\n\nimport * as path from \"path\";\nimport type { Plugin, ViteDevServer, ResolvedConfig } from \"vite\";\nimport \"./virtual\";\nimport { createMarkdownEnvironment } from \"./environment\";\nimport { transformMarkdown } from \"./transform\";\nimport { extractDocs, generateMarkdown, writeDocs, resolveDocsOptions } from \"./docs\";\nimport { buildSsg, resolveSsgOptions } from \"./ssg\";\nimport { resolveSiteMapsOptions } from \"./site-maps\";\nimport { resolvePublishStateOptions } from \"./publish-state\";\nimport { resolveCascadeOptions, resolvePermalinksOptions } from \"./permalinks\";\nimport { resolveRedirectsOptions } from \"./redirects\";\nimport { notFoundSearchExcludeIds } from \"./not-found\";\nimport { resolveFeedsOptions } from \"./feeds\";\nimport { resolveBlogOptions } from \"./blog\";\nimport { resolvePwaOptions } from \"./pwa\";\nimport { resolveTaxonomiesOptions } from \"./taxonomies\";\nimport { resolveVersionsOptions } from \"./versions\";\nimport { PageResourceError, resolveResourcesOptions } from \"./resources\";\nimport { createKatexAssetsPlugin } from \"./plugins/math-assets\";\nimport {\n resolveSearchOptions,\n buildSearchIndex,\n writeSearchIndex,\n generateSearchModule,\n} from \"./search\";\nimport { resolveOgImageOptions } from \"./og-image\";\nimport {\n createDevServerMiddleware,\n createDevServerCache,\n invalidateNavCache,\n invalidatePageCache,\n} from \"./dev-server\";\nimport { createOgViewerPlugin } from \"./og-viewer\";\nimport { resolveI18nOptions, createI18nPlugin } from \"./i18n\";\nimport { isMarkdownFilePath, normalizeMarkdownExtensions } from \"./markdown\";\nimport { resolveImageOptions } from \"./resolve-image-options\";\nimport { generateCollectionsVirtualModule, resolveCollectionsOptions } from \"./collections\";\nimport type { BuiltinPmOptions, OxContentOptions, ResolvedOptions } from \"./types\";\nimport { resolveCardOptions } from \"./card-options\";\nimport { resolveFileTreeOptions } from \"./file-tree-options\";\nimport { resolveTypedHoverOptions } from \"./typed-hover\";\nimport { resolveIncludeOptions } from \"./include-options\";\nimport { resolveStepsOptions } from \"./step-options\";\nimport type { TwitterEmbedOptions } from \"./plugins\";\n\nexport type { OxContentOptions } from \"./types\";\nexport type { TwitterEmbedOptions } from \"./plugins\";\nexport type {\n CodeAnnotationSyntax,\n CodeAnnotationsOptions,\n ResolvedCodeAnnotationsOptions,\n WikiLinkOptions,\n ResolvedWikiLinkOptions,\n EmojiShortcodeOptions,\n ResolvedEmojiShortcodeOptions,\n MathOptions,\n ResolvedMathOptions,\n AttrsOptions,\n ResolvedAttrsOptions,\n BadgeOptions,\n ResolvedBadgeOptions,\n ContainerOptions,\n ContainerTypeOptions,\n ResolvedContainerOptions,\n ImageOptions,\n ResolvedImageOptions,\n ResourcesOptions,\n ResolvedResourcesOptions,\n CodeImportOptions,\n ResolvedCodeImportOptions,\n IncludeOptions,\n ResolvedIncludeOptions,\n CardOptions,\n ResolvedCardOptions,\n StepsOptions,\n ResolvedStepsOptions,\n FileTreeIconOptions,\n FileTreeOptions,\n ResolvedFileTreeOptions,\n SanitizeOptions,\n ResolvedSanitizeOptions,\n EditThisPageOptions,\n ResolvedEditThisPageOptions,\n CodeBlockLintOptions,\n ResolvedCodeBlockLintOptions,\n CodeBlockTypecheckOptions,\n ResolvedCodeBlockTypecheckOptions,\n TypedHoverOptions,\n ResolvedTypedHoverOptions,\n DocsTestOptions,\n ResolvedDocsTestOptions,\n MarkdownDisplayFormat,\n DocsOptions,\n ResolvedDocsOptions,\n DocEntry,\n ParamDoc,\n ReturnDoc,\n ExtractedDocs,\n SsgOptions,\n ResolvedSsgOptions,\n JsonLdOptions,\n JsonLdPublisherOptions,\n ResolvedJsonLd,\n A11yOptions,\n ResolvedA11y,\n ReaderChromeOptions,\n ResolvedReaderChrome,\n NotFoundOptions,\n ResolvedNotFoundOptions,\n TeamLink,\n TeamMember,\n TeamOptions,\n ResolvedTeamOptions,\n ContributorsOptions,\n ResolvedContributors,\n SiteMapsOptions,\n ResolvedSiteMapsOptions,\n PublishStateOptions,\n ResolvedPublishStateOptions,\n PermalinksOptions,\n ResolvedPermalinksOptions,\n CascadeOptions,\n ResolvedCascadeOptions,\n RedirectsOptions,\n ResolvedRedirectsOptions,\n BlogAuthor,\n BlogOptions,\n ResolvedBlogOptions,\n FeedFormat,\n FeedsOptions,\n ResolvedFeedsOptions,\n PwaOptions,\n ResolvedPwaOptions,\n TaxonomiesOptions,\n ResolvedTaxonomiesOptions,\n SearchOptions,\n ResolvedSearchOptions,\n SearchDocument,\n SearchResult,\n CollectionEntry,\n CollectionOptions,\n CollectionsOptions,\n ResolvedCollectionOptions,\n ResolvedCollectionsOptions,\n CollectionIncludeField,\n CollectionManifest,\n CollectionQueryBuilder,\n CollectionQueryOperator,\n // Entry page types\n HeroAction,\n HeroImage,\n HeroConfig,\n FeatureConfig,\n EntryPageConfig,\n SsgNavigationItem,\n SsgNavigationGroup,\n // i18n types\n I18nOptions,\n ResolvedI18nOptions,\n LocaleConfig,\n BuiltinEmbedOptions,\n ResolvedBuiltinEmbedOptions,\n BuiltinPmOptions,\n} from \"./types\";\n\n/**\n * Creates the Ox Content Vite plugin.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { oxContent } from '@ox-content/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [\n * oxContent({\n * srcDir: 'content',\n * gfm: true,\n * }),\n * ],\n * });\n * ```\n */\nexport function oxContent(options: OxContentOptions = {}): Plugin[] {\n const resolvedOptions = resolveOptions(options);\n let config: ResolvedConfig | undefined;\n const getRoot = () => config?.root || process.cwd();\n\n const ssgDevCache = createDevServerCache();\n const plugins: Plugin[] = [\n createMainPlugin(resolvedOptions, (resolvedConfig) => {\n config = resolvedConfig;\n }),\n createEnvironmentPlugin(resolvedOptions),\n createDocsPlugin(resolvedOptions, getRoot),\n createSsgPlugin(resolvedOptions, getRoot, ssgDevCache),\n createCollectionsPlugin(resolvedOptions, getRoot),\n createSearchPlugin(resolvedOptions, getRoot),\n ];\n\n if (resolvedOptions.math.enabled) {\n plugins.push(createKatexAssetsPlugin());\n }\n\n if (resolvedOptions.i18n) {\n plugins.push(createI18nPlugin(resolvedOptions));\n }\n\n if (resolvedOptions.ogViewer) {\n plugins.push(createOgViewerPlugin(resolvedOptions));\n }\n\n return plugins;\n}\n\nasync function regenerateDocs(resolvedOptions: ResolvedOptions, root: string): Promise<number> {\n const docsOptions = resolvedOptions.docs;\n if (!docsOptions || !docsOptions.enabled) {\n return 0;\n }\n\n const srcDirs = docsOptions.src.map((src) => path.resolve(root, src));\n const outDir = path.resolve(root, docsOptions.out);\n const extracted = await extractDocs(srcDirs, docsOptions);\n const generated = generateMarkdown(extracted, docsOptions);\n\n await writeDocs(generated, outDir, extracted, docsOptions);\n\n return Object.keys(generated).length;\n}\n\nfunction createMainPlugin(\n resolvedOptions: ResolvedOptions,\n setConfig: (config: ResolvedConfig) => void,\n): Plugin {\n return {\n name: \"ox-content\",\n\n configResolved: setConfig,\n\n configureServer(devServer) {\n devServer.middlewares.use(async (req, res, next) => {\n const url = req.url;\n if (!url || !isMarkdownFilePath(url, resolvedOptions.extensions)) {\n return next();\n }\n\n next();\n });\n },\n\n resolveId(id) {\n if (id === \"virtual:ox-content/config\" || id === \"virtual:ox-content/runtime\") {\n return \"\\0\" + id;\n }\n\n if (isMarkdownFilePath(id, resolvedOptions.extensions)) {\n return id;\n }\n\n return null;\n },\n\n async load(id) {\n if (id === \"\\0virtual:ox-content/config\" || id === \"\\0virtual:ox-content/runtime\") {\n const virtualPath = id.slice(\"\\0virtual:ox-content/\".length);\n return generateVirtualModule(virtualPath, resolvedOptions);\n }\n\n return null;\n },\n\n async transform(code, id) {\n if (!isMarkdownFilePath(id, resolvedOptions.extensions)) {\n return null;\n }\n\n const result = await transformMarkdown(code, id, resolvedOptions);\n return {\n code: result.code,\n map: null,\n };\n },\n\n async handleHotUpdate({ file, server }) {\n if (!isMarkdownFilePath(file, resolvedOptions.extensions)) {\n return;\n }\n\n server.ws.send({\n type: \"custom\",\n event: \"ox-content:update\",\n data: { file },\n });\n\n const modules = server.moduleGraph.getModulesByFile(file);\n return modules ? Array.from(modules) : [];\n },\n };\n}\n\nfunction createCollectionsPlugin(resolvedOptions: ResolvedOptions, getRoot: () => string): Plugin {\n const moduleId = \"\\0virtual:ox-content/collections\";\n let moduleCode: Promise<string> | undefined;\n\n const invalidate = (devServer: ViteDevServer) => {\n moduleCode = undefined;\n const mod = devServer.moduleGraph.getModuleById(moduleId);\n if (mod) {\n devServer.moduleGraph.invalidateModule(mod);\n devServer.ws.send({ type: \"full-reload\" });\n }\n };\n\n return {\n name: \"ox-content:collections\",\n\n resolveId(id) {\n return id === \"virtual:ox-content/collections\" ? moduleId : null;\n },\n\n async load(id) {\n if (id !== moduleId) {\n return null;\n }\n moduleCode ??= generateCollectionsVirtualModule(getRoot(), resolvedOptions);\n return moduleCode;\n },\n\n configureServer(devServer) {\n if (!resolvedOptions.collections.enabled) {\n return;\n }\n\n const srcDir = path.resolve(getRoot(), resolvedOptions.srcDir);\n devServer.watcher.add(srcDir);\n devServer.watcher.on(\"all\", (_event, file) => {\n if (file.startsWith(srcDir) && isMarkdownFilePath(file, resolvedOptions.extensions)) {\n invalidate(devServer);\n }\n });\n },\n };\n}\n\nfunction createEnvironmentPlugin(resolvedOptions: ResolvedOptions): Plugin {\n return {\n name: \"ox-content:environment\",\n\n config() {\n return {\n environments: {\n markdown: createMarkdownEnvironment(resolvedOptions),\n },\n };\n },\n };\n}\n\nfunction createDocsPlugin(resolvedOptions: ResolvedOptions, getRoot: () => string): Plugin {\n return {\n name: \"ox-content:docs\",\n\n async buildStart() {\n const docsOptions = resolvedOptions.docs;\n if (!docsOptions || !docsOptions.enabled) {\n return;\n }\n\n try {\n const count = await regenerateDocs(resolvedOptions, getRoot());\n console.log(`[ox-content] Generated ${count} documentation files to ${docsOptions.out}`);\n } catch (err) {\n console.warn(\"[ox-content] Failed to generate documentation:\", err);\n }\n },\n\n configureServer(devServer) {\n const docsOptions = resolvedOptions.docs;\n if (!docsOptions || !docsOptions.enabled) {\n return;\n }\n\n const root = getRoot();\n const srcDirs = docsOptions.src.map((src) => path.resolve(root, src));\n for (const srcDir of srcDirs) {\n devServer.watcher.add(srcDir);\n }\n\n devServer.watcher.on(\"all\", async (event, file) => {\n if (event !== \"add\" && event !== \"change\" && event !== \"unlink\") {\n return;\n }\n\n const isSourceFile = srcDirs.some(\n (srcDir) => file.startsWith(srcDir) && (file.endsWith(\".ts\") || file.endsWith(\".tsx\")),\n );\n if (!isSourceFile) {\n return;\n }\n\n try {\n await regenerateDocs(resolvedOptions, root);\n } catch {\n // Ignore errors during dev.\n }\n });\n },\n };\n}\n\nfunction createSsgPlugin(\n resolvedOptions: ResolvedOptions,\n getRoot: () => string,\n ssgDevCache: ReturnType<typeof createDevServerCache>,\n): Plugin {\n return {\n name: \"ox-content:ssg\",\n\n configureServer(devServer) {\n const ssgOptions = resolvedOptions.ssg;\n if (!ssgOptions.enabled) return;\n\n const root = getRoot();\n const srcDir = path.resolve(root, resolvedOptions.srcDir);\n devServer.middlewares.use(createDevServerMiddleware(resolvedOptions, root, ssgDevCache));\n\n devServer.watcher.on(\"add\", (file: string) => {\n notifySsgFileAddedOrRemoved(devServer, resolvedOptions, ssgDevCache, srcDir, file, \"add\");\n });\n devServer.watcher.on(\"unlink\", (file: string) => {\n notifySsgFileAddedOrRemoved(\n devServer,\n resolvedOptions,\n ssgDevCache,\n srcDir,\n file,\n \"unlink\",\n );\n });\n devServer.watcher.on(\"change\", (file: string) => {\n if (file.startsWith(srcDir) && isMarkdownFilePath(file, resolvedOptions.extensions)) {\n invalidatePageCache(ssgDevCache, file);\n }\n });\n },\n\n async closeBundle() {\n const ssgOptions = resolvedOptions.ssg;\n if (!ssgOptions.enabled) {\n return;\n }\n\n try {\n const result = await buildSsg(resolvedOptions, getRoot());\n if (result.files.length > 0) {\n console.log(`[ox-content] Generated ${result.files.length} output files`);\n }\n\n for (const error of result.errors) {\n console.warn(`[ox-content] ${error}`);\n }\n } catch (err) {\n console.error(\"[ox-content] SSG build failed:\", err);\n if (err instanceof PageResourceError) {\n throw err;\n }\n }\n },\n };\n}\n\nfunction notifySsgFileAddedOrRemoved(\n devServer: ViteDevServer,\n resolvedOptions: ResolvedOptions,\n ssgDevCache: ReturnType<typeof createDevServerCache>,\n srcDir: string,\n file: string,\n type: \"add\" | \"unlink\",\n): void {\n if (!file.startsWith(srcDir) || !isMarkdownFilePath(file, resolvedOptions.extensions)) {\n return;\n }\n\n invalidateNavCache(ssgDevCache);\n devServer.ws.send({\n type: \"custom\",\n event: \"ox-content:update\",\n data: { file, type },\n });\n}\n\nfunction searchPublishState(\n resolvedOptions: ResolvedOptions,\n command: \"build\" | \"serve\",\n): ResolvedOptions[\"publishState\"] {\n const publishState = resolvedOptions.publishState ?? {\n enabled: false,\n includeDrafts: false,\n };\n return {\n ...publishState,\n includeDrafts: publishState.includeDrafts || command === \"serve\",\n };\n}\n\nfunction createSearchPlugin(resolvedOptions: ResolvedOptions, getRoot: () => string): Plugin {\n let searchIndexJson = \"\";\n let command: \"build\" | \"serve\" = \"build\";\n\n return {\n name: \"ox-content:search\",\n\n config(_config, env) {\n command = env.command;\n },\n\n resolveId(id) {\n if (id === \"virtual:ox-content/search\") {\n return \"\\0virtual:ox-content/search\";\n }\n return null;\n },\n\n async load(id) {\n if (id !== \"\\0virtual:ox-content/search\") {\n return null;\n }\n\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled) {\n return \"export const search = () => []; export const searchOptions = { enabled: false }; export default { search, searchOptions };\";\n }\n\n const indexPath = resolvedOptions.base + \"search-index.json\";\n return generateSearchModule(searchOptions, indexPath);\n },\n\n async buildStart() {\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled) {\n return;\n }\n\n const srcDir = path.resolve(getRoot(), resolvedOptions.srcDir);\n try {\n searchIndexJson = await buildSearchIndex(\n srcDir,\n resolvedOptions.base,\n resolvedOptions.extensions,\n searchPublishState(resolvedOptions, command),\n notFoundSearchExcludeIds(resolvedOptions.ssg.notFound),\n resolvedOptions.mdx,\n );\n console.log(\"[ox-content] Search index built\");\n } catch (err) {\n console.warn(\"[ox-content] Failed to build search index:\", err);\n }\n },\n\n configureServer(devServer) {\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled) {\n return;\n }\n\n // The index is only written to disk by the static build (closeBundle);\n // without a dev handler the client's fetch falls through to the html\n // fallback and search reports the index unavailable. Serve it from\n // memory, rebuilt lazily after a Markdown change.\n const srcDir = path.resolve(getRoot(), resolvedOptions.srcDir);\n let stale = false;\n devServer.watcher.on(\"all\", (event, file) => {\n if (event !== \"add\" && event !== \"change\" && event !== \"unlink\") {\n return;\n }\n const relative = path.relative(srcDir, file);\n const isInsideSrcDir =\n relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n if (isInsideSrcDir && isMarkdownFilePath(file, resolvedOptions.extensions)) {\n stale = true;\n }\n });\n\n const indexPath = resolvedOptions.base + \"search-index.json\";\n devServer.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== indexPath) {\n return next();\n }\n try {\n if (stale || !searchIndexJson) {\n searchIndexJson = await buildSearchIndex(\n srcDir,\n resolvedOptions.base,\n resolvedOptions.extensions,\n searchPublishState(resolvedOptions, command),\n notFoundSearchExcludeIds(resolvedOptions.ssg.notFound),\n resolvedOptions.mdx,\n );\n stale = false;\n }\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(searchIndexJson);\n } catch (err) {\n next(err);\n }\n });\n },\n\n async closeBundle() {\n const searchOptions = resolvedOptions.search;\n if (!searchOptions.enabled || !searchIndexJson) {\n return;\n }\n\n const outDir = path.resolve(getRoot(), resolvedOptions.outDir);\n try {\n await writeSearchIndex(searchIndexJson, outDir);\n console.log(\"[ox-content] Search index written to\", path.join(outDir, \"search-index.json\"));\n } catch (err) {\n console.warn(\"[ox-content] Failed to write search index:\", err);\n }\n },\n };\n}\n\n/**\n * Resolves plugin options with defaults.\n */\nfunction resolveOptions(options: OxContentOptions): ResolvedOptions {\n return {\n srcDir: options.srcDir ?? \"content\",\n outDir: options.outDir ?? \"dist\",\n base: options.base ?? \"/\",\n extensions: normalizeMarkdownExtensions(options.extensions),\n ssg: resolveSsgOptions(options.ssg),\n siteMaps: resolveSiteMapsOptions(options.siteMaps),\n publishState: resolvePublishStateOptions(options.publishState),\n permalinks: resolvePermalinksOptions(options.permalinks),\n cascade: resolveCascadeOptions(options.cascade),\n redirects: resolveRedirectsOptions(options.redirects),\n blog: resolveBlogOptions(\n options.blog ??\n (typeof options.ssg === \"object\" && options.ssg ? options.ssg.blog : undefined),\n ),\n feeds: resolveFeedsOptions(options.feeds),\n pwa: resolvePwaOptions(options.pwa),\n taxonomies: resolveTaxonomiesOptions(options.taxonomies),\n versions: resolveVersionsOptions(options.versions),\n resources: resolveResourcesOptions(options.resources),\n gfm: options.gfm ?? true,\n mdx: options.mdx,\n footnotes: options.footnotes ?? true,\n tables: options.tables ?? true,\n taskLists: options.taskLists ?? true,\n strikethrough: options.strikethrough ?? true,\n autolinks: options.autolinks ?? options.gfm ?? true,\n highlight: options.highlight ?? false,\n codeAnnotations: resolveCodeAnnotationsOptions(options.codeAnnotations),\n wikiLinks: resolveWikiLinkOptions(options.wikiLinks, options.base ?? \"/\"),\n emojiShortcodes: resolveEmojiShortcodeOptions(options.emojiShortcodes),\n attrs: resolveAttrsOptions(options.attrs),\n badges: resolveBadgeOptions(options.badges),\n containers: resolveContainerOptions(options.containers),\n images: resolveImageOptions(options.images),\n codeImports: resolveCodeImportOptions(options.codeImports),\n includes: resolveIncludeOptions(options.includes),\n cards: resolveCardOptions(options.cards),\n steps: resolveStepsOptions(options.steps),\n fileTree: resolveFileTreeOptions(options.fileTree),\n sanitize: resolveSanitizeOptions(options.sanitize),\n editThisPage: resolveEditThisPageOptions(options.editThisPage),\n cjkEmphasis: options.cjkEmphasis ?? false,\n codeBlockLint: resolveCodeBlockLintOptions(options.codeBlockLint),\n codeBlockTypecheck: resolveCodeBlockTypecheckOptions(options.codeBlockTypecheck),\n typedHover: resolveTypedHoverOptions(options.typedHover),\n docsTests: resolveDocsTestOptions(options.docsTests),\n mermaid: options.mermaid ?? false,\n math: resolveMathOptions(options.math),\n frontmatter: options.frontmatter ?? true,\n toc: options.toc ?? true,\n tocMaxDepth: options.tocMaxDepth ?? 3,\n ogImage: options.ogImage ?? false,\n ogImageOptions: resolveOgImageOptions(options.ogImageOptions),\n transformers: options.transformers ?? [],\n docs: resolveDocsOptions(options.docs),\n search: resolveSearchOptions(options.search),\n collections: resolveCollectionsOptions(options.collections),\n ogViewer: options.ogViewer ?? true,\n embeds: resolveBuiltinEmbedOptions(options.embeds),\n i18n: resolveI18nOptions(options.i18n),\n };\n}\n\nexport function resolveBuiltinEmbedOptions(\n options: OxContentOptions[\"embeds\"],\n): ResolvedOptions[\"embeds\"] {\n if (options === false) {\n return {\n github: false,\n openGraph: false,\n pm: false,\n spotify: false,\n stackBlitz: false,\n twitter: false,\n bluesky: false,\n webContainer: false,\n };\n }\n\n return {\n github: resolveSingleEmbedOptions(options?.github),\n openGraph: resolveSingleEmbedOptions(options?.openGraph),\n pm: resolvePmOptions(options?.pm),\n spotify: options?.spotify === true,\n stackBlitz: options?.stackBlitz === true,\n twitter: resolveTwitterEmbedOptions(options?.twitter),\n bluesky: options?.bluesky === true,\n webContainer: options?.webContainer === true,\n };\n}\n\nfunction resolveSingleEmbedOptions<T extends object>(options: boolean | T | undefined): T | false {\n if (options === false) return false;\n if (options === true || options === undefined) return {} as T;\n return options;\n}\n\nfunction resolveTwitterEmbedOptions(\n options: boolean | TwitterEmbedOptions | undefined,\n): TwitterEmbedOptions | false {\n if (options === false || options === undefined) return false;\n if (options === true) return {};\n return options;\n}\n\nfunction resolvePmOptions(\n options: boolean | BuiltinPmOptions | undefined,\n): BuiltinPmOptions | false {\n if (options === false || options === undefined) return false;\n if (options === true) return {};\n return options;\n}\n\nfunction resolveWikiLinkOptions(\n options: OxContentOptions[\"wikiLinks\"],\n baseUrl: string,\n): ResolvedOptions[\"wikiLinks\"] {\n if (!options) return { enabled: false, baseUrl };\n if (options === true) return { enabled: true, baseUrl };\n return { enabled: true, baseUrl: options.baseUrl ?? baseUrl };\n}\n\nfunction resolveEmojiShortcodeOptions(\n options: OxContentOptions[\"emojiShortcodes\"],\n): ResolvedOptions[\"emojiShortcodes\"] {\n if (!options) return { enabled: false, custom: {} };\n if (options === true) return { enabled: true, custom: {} };\n return { enabled: true, custom: options.custom ?? {} };\n}\n\nexport function resolveMathOptions(options: OxContentOptions[\"math\"]): ResolvedOptions[\"math\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n\nfunction resolveAttrsOptions(options: OxContentOptions[\"attrs\"]): ResolvedOptions[\"attrs\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n\nexport function resolveBadgeOptions(\n options: OxContentOptions[\"badges\"],\n): ResolvedOptions[\"badges\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: options.enabled ?? true };\n}\n\nfunction resolveContainerOptions(\n options: OxContentOptions[\"containers\"],\n): ResolvedOptions[\"containers\"] {\n if (!options) return { enabled: false, types: {} };\n if (options === true) return { enabled: true, types: {} };\n return { enabled: options.enabled ?? true, types: options.types ?? {} };\n}\n\nfunction resolveCodeImportOptions(\n options: OxContentOptions[\"codeImports\"],\n): ResolvedOptions[\"codeImports\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return { enabled: true, rootDir: options.rootDir };\n}\n\nexport { resolveCardOptions } from \"./card-options\";\nexport { resolveIncludeOptions } from \"./include-options\";\nexport { resolveStepsOptions } from \"./step-options\";\nexport { resolveFileTreeOptions } from \"./file-tree-options\";\nexport { resolveTypedHoverOptions } from \"./typed-hover\";\n\nfunction resolveSanitizeOptions(\n options: OxContentOptions[\"sanitize\"],\n): ResolvedOptions[\"sanitize\"] {\n if (!options) return { enabled: false };\n if (options === true) return { enabled: true };\n return {\n enabled: true,\n allowedTags: options.allowedTags,\n allowedAttributes: options.allowedAttributes,\n allowedUrlSchemes: options.allowedUrlSchemes,\n };\n}\n\nfunction resolveEditThisPageOptions(\n options: OxContentOptions[\"editThisPage\"],\n): ResolvedOptions[\"editThisPage\"] {\n if (!options) return { enabled: false, branch: \"main\", label: \"Edit this page\" };\n if (options === true) return { enabled: false, branch: \"main\", label: \"Edit this page\" };\n return {\n enabled: Boolean(options.repoUrl),\n repoUrl: options.repoUrl,\n branch: options.branch ?? \"main\",\n rootDir: options.rootDir,\n label: options.label ?? \"Edit this page\",\n };\n}\n\nfunction resolveCodeBlockLintOptions(\n options: OxContentOptions[\"codeBlockLint\"],\n): ResolvedOptions[\"codeBlockLint\"] {\n if (!options) {\n return { enabled: false, requireLanguage: false, trailingSpaces: true, mode: \"warn\" };\n }\n if (options === true) {\n return { enabled: true, requireLanguage: false, trailingSpaces: true, mode: \"warn\" };\n }\n return {\n enabled: true,\n languages: options.languages,\n requireLanguage: options.requireLanguage ?? false,\n trailingSpaces: options.trailingSpaces ?? true,\n mode: options.mode ?? \"warn\",\n };\n}\n\nfunction resolveCodeBlockTypecheckOptions(\n options: OxContentOptions[\"codeBlockTypecheck\"],\n): ResolvedOptions[\"codeBlockTypecheck\"] {\n if (!options) {\n return {\n enabled: false,\n languages: [\"ts\", \"tsx\"],\n requireMeta: true,\n tsgoCommand: \"tsgo\",\n mode: \"warn\",\n };\n }\n if (options === true) {\n return {\n enabled: true,\n languages: [\"ts\", \"tsx\"],\n requireMeta: true,\n tsgoCommand: \"tsgo\",\n mode: \"warn\",\n };\n }\n return {\n enabled: true,\n languages: options.languages ?? [\"ts\", \"tsx\"],\n requireMeta: options.requireMeta ?? true,\n tsgoCommand: options.tsgoCommand ?? \"tsgo\",\n mode: options.mode ?? \"warn\",\n };\n}\n\nfunction resolveDocsTestOptions(\n options: OxContentOptions[\"docsTests\"],\n): ResolvedOptions[\"docsTests\"] {\n if (!options) return { enabled: false, languages: [\"js\", \"jsx\", \"ts\", \"tsx\"], requireMeta: true };\n if (options === true) {\n return { enabled: true, languages: [\"js\", \"jsx\", \"ts\", \"tsx\"], requireMeta: true };\n }\n return {\n enabled: true,\n languages: options.languages ?? [\"js\", \"jsx\", \"ts\", \"tsx\"],\n requireMeta: options.requireMeta ?? true,\n };\n}\n\nfunction resolveCodeAnnotationsOptions(\n options: OxContentOptions[\"codeAnnotations\"],\n): ResolvedOptions[\"codeAnnotations\"] {\n if (!options) {\n return {\n enabled: false,\n notation: \"attribute\",\n metaKey: \"annotate\",\n defaultLineNumbers: false,\n };\n }\n\n if (options === true) {\n return {\n enabled: true,\n notation: \"attribute\",\n metaKey: \"annotate\",\n defaultLineNumbers: false,\n };\n }\n\n return {\n enabled: true,\n notation: options.notation ?? \"attribute\",\n metaKey: options.metaKey ?? \"annotate\",\n defaultLineNumbers: options.defaultLineNumbers ?? false,\n };\n}\n\n/**\n * Generates virtual module content.\n */\nexport function generateVirtualModule(path: string, options: ResolvedOptions): string {\n if (path === \"config\") {\n return `export default ${JSON.stringify(options)};`;\n }\n\n if (path === \"runtime\") {\n const base = normalizeRuntimeBase(options.base);\n return `\n export const base = ${JSON.stringify(base)};\n export const runtimeConfig = { base };\n\n export function isExternalUrl(value) {\n return /^(?:https?:)?\\\\/\\\\//i.test(value) || /^(?:mailto|tel):/i.test(value);\n }\n\n export function withBase(pathname = \"\") {\n const value = String(pathname);\n if (!value || value === \"/\") return base;\n if (value.startsWith(\"#\") || isExternalUrl(value)) return value;\n return base + (value.startsWith(\"/\") ? value.slice(1) : value);\n }\n\n export function withoutBase(pathname = \"\") {\n const value = String(pathname);\n if (base === \"/\" || value.startsWith(\"#\") || isExternalUrl(value)) return value;\n const bareBase = base.slice(0, -1);\n if (value === bareBase) return \"/\";\n if (value.startsWith(base)) return \"/\" + value.slice(base.length);\n return value;\n }\n\n export function useMarkdown() {\n return {\n base,\n withBase,\n withoutBase,\n render: (content) => {\n return content;\n },\n };\n }\n `;\n }\n\n return \"export default {};\";\n}\n\nfunction normalizeRuntimeBase(base: string): string {\n const trimmed = base.trim();\n if (!trimmed || trimmed === \"/\") return \"/\";\n const withLeading = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n return withLeading.endsWith(\"/\") ? withLeading : `${withLeading}/`;\n}\n\n// Re-export types and utilities\nexport { createMarkdownEnvironment } from \"./environment\";\nexport {\n IncrementalMarkdownParser,\n IncrementalMarkdownRenderer,\n createIncrementalMarkdownParser,\n createIncrementalMarkdownRenderer,\n renderMarkdownStream,\n type IncrementalMarkdownParseAppendOptions,\n type IncrementalMarkdownParseResult,\n type IncrementalMarkdownParserOptions,\n type IncrementalMarkdownRenderAppendOptions,\n type IncrementalMarkdownRenderResult,\n type IncrementalMarkdownRendererOptions,\n type MarkdownChunkSource,\n} from \"./incremental\";\nexport { transformMarkdown } from \"./transform\";\nexport { isMdxFilePath, resolveMdxForFilePath } from \"./markdown\";\nexport {\n collectMdxIslandNamesFromHtml,\n collectMdxJsxNamesFromAst,\n discoverRegisteredMdxComponents,\n intersectHydratableComponentNames,\n intersectRegisteredComponentNames,\n isRegisteredComponent,\n type ComponentRegistry,\n type DiscoverRegisteredMdxComponentsInput,\n} from \"./mdx-islands\";\nexport {\n resolveContentRootPath,\n resolveDocumentComponentImports,\n stripViteQuery,\n type DocumentImportDiagnostic,\n type DocumentImportDiagnosticCode,\n type ResolveDocumentComponentImportsInput,\n type ResolveDocumentComponentImportsResult,\n type ResolvedDocumentComponentImport,\n} from \"./document-imports\";\nexport {\n discoverDocumentMdxIslands,\n type DiscoverDocumentMdxIslandsInput,\n type DiscoverDocumentMdxIslandsResult,\n} from \"./document-islands\";\nexport {\n renderIslandComponentImports,\n type GlobalComponentMap,\n type RenderIslandComponentImportsInput,\n} from \"./island-codegen\";\nexport { applyIslandSsrHtml, type RenderIslandFn } from \"./island-ssr\";\nexport { resolveImageOptions } from \"./resolve-image-options\";\nexport {\n createFrameworkMarkdownOptions,\n escapeSvelteMarkup,\n renderHtmlToFrameworkCode,\n renderHtmlToReactCreateElement,\n renderHtmlToReactComponent,\n renderHtmlToSvelteComponent,\n renderHtmlToVueComponent,\n renderHtmlToVueH,\n type FrameworkCodegenMode,\n type FrameworkCodegenTarget,\n type FrameworkComponentIsland,\n type FrameworkMarkdownOptions,\n type FrameworkRenderTarget,\n type FrameworkTransformData,\n} from \"./framework\";\nexport {\n extractCodeBlocks,\n extractDocsTests,\n lintCodeBlocks,\n typecheckCodeBlocks,\n type CodeBlockDiagnostic,\n type ExtractedCodeBlock,\n type TypecheckCodeBlockOptions,\n} from \"./code-blocks\";\nexport {\n collectDocsTests,\n DocsTestRunError,\n runDocsTests,\n writeDocsTestFiles,\n type CollectedDocsTest,\n type DocsTestFileOptions,\n type DocsTestHarnessOptions,\n type DocsTestRunResult,\n type DocsTestSource,\n type DocsTestWriteResult,\n type RunDocsTestsOptions,\n type WrittenDocsTestFile,\n} from \"./docs-tests\";\nexport { extractDocs, generateMarkdown, writeDocs, resolveDocsOptions } from \"./docs\";\nexport { lintMarkdown, lintMarkdownAsync } from \"./lint\";\nexport { lintMarkdownFile, lintMarkdownFiles, shouldLintMarkdownFile } from \"./lint-files\";\nexport type {\n MarkdownLintDiagnostic,\n MarkdownLintDictionaryOptions,\n MarkdownLintLanguage,\n MarkdownLintOptions,\n MarkdownLintResult,\n MarkdownLintRuleOptions,\n MarkdownLintSeverity,\n MarkdownLintStandardDictionaryOptions,\n} from \"./lint\";\nexport type {\n MarkdownLintFileDiagnostic as MarkdownLintBatchDiagnostic,\n MarkdownLintFileDiagnostic,\n MarkdownLintFileOptions,\n MarkdownLintFileResult,\n MarkdownLintFilesResult,\n MarkdownLintFileOptions as MarkdownLintProjectOptions,\n} from \"./lint-files\";\nexport { buildSsg, resolveSsgOptions, DEFAULT_HTML_TEMPLATE } from \"./ssg\";\nexport { resolveNotFoundOptions } from \"./not-found\";\nexport { resolveSiteMapsOptions } from \"./site-maps\";\nexport {\n classifyPublishState,\n resolvePublishStateOptions,\n partitionPublishedPages,\n} from \"./publish-state\";\nexport { resolvePermalinksOptions, resolveCascadeOptions } from \"./permalinks\";\nexport { resolveRedirectsOptions } from \"./redirects\";\nexport { resolveFeedsOptions } from \"./feeds\";\nexport { resolveBlogOptions, resolveBlogCollectionName, readingTimeMinutes } from \"./blog\";\nexport { resolvePwaOptions } from \"./pwa\";\nexport { resolveTaxonomiesOptions } from \"./taxonomies\";\nexport { resolveVersionsOptions } from \"./versions\";\nexport { resolveResourcesOptions, PageResourceError } from \"./resources\";\nexport { resolveTeamOptions } from \"./team\";\nexport { resolveSectionIndexOptions } from \"./section-index\";\nexport { resolveSearchOptions, buildSearchIndex, writeSearchIndex } from \"./search\";\nexport {\n buildCollectionManifest,\n defineCollection,\n defineCollections,\n generateCollectionsVirtualModule,\n resolveCollectionsOptions,\n} from \"./collections\";\nexport {\n DEFAULT_MARKDOWN_EXTENSIONS,\n normalizeMarkdownExtensions,\n isMarkdownFilePath,\n stripMarkdownExtension,\n} from \"./markdown\";\nexport { defineTheme, defaultTheme, mergeThemes, resolveTheme } from \"./theme\";\nexport {\n fromVitePressConfig,\n generateVitePressMigrationConfig,\n convertVitePressSidebar,\n convertVitePressNav,\n normalizeVitePressFrontmatter,\n} from \"./vitepress\";\nexport type {\n GenerateVitePressMigrationConfigOptions,\n VitePressConfig,\n VitePressThemeConfig,\n VitePressSidebar,\n VitePressSidebarItem,\n VitePressNavItem,\n VitePressSocialLink,\n VitePressFooter,\n VitePressLogo,\n} from \"./vitepress\";\nexport type {\n ThemeConfig,\n ThemeColors,\n ThemeLayout,\n ThemeFonts,\n ThemeEntryPage,\n ThemeHeader,\n ThemeFooter,\n ThemeTokens,\n SocialLinks,\n ThemeEmbed,\n ResolvedThemeConfig,\n HeaderNavItem,\n LocaleLabel,\n SidebarItem,\n ThemeAnnouncement,\n} from \"./theme\";\nexport type { PageChromeFlags } from \"./header-chrome\";\nexport {\n parsePageChromeFlags,\n resolveHeaderNavItems,\n resolveLocaleLabel,\n resolvePageChromeOption,\n} from \"./header-chrome\";\nexport * from \"./types\";\n\n// JSX Runtime\nexport { jsx, jsxs, Fragment, renderToString, raw, when, each } from \"./jsx-html\";\nexport type { JSXNode, JSXChild, JSXProps, JSXElementType } from \"./jsx-html\";\n\n// Page Context\nexport {\n usePageProps,\n useSiteConfig,\n useRenderContext,\n useNav,\n useIsActive,\n setRenderContext,\n clearRenderContext,\n generateFrontmatterTypes,\n inferType,\n} from \"./page-context\";\nexport type {\n BasePageProps,\n PageProps,\n SiteConfig,\n NavGroup,\n NavItem,\n RenderContext,\n FrontmatterSchema,\n} from \"./page-context\";\n\n// Theme Renderer\nexport {\n renderPage,\n renderAllPages,\n generateTypes,\n DefaultTheme,\n createTheme,\n} from \"./theme-renderer\";\nexport type { ThemeComponent, ThemeProps, PageData, ThemeRenderOptions } from \"./theme-renderer\";\n\n// Built-in Plugins (No-JS First)\nexport {\n transformTabs,\n generateTabsCSS,\n transformYouTube,\n extractVideoId,\n transformGitHub,\n fetchRepoData,\n fetchGitHubSource,\n collectGitHubRepos,\n collectGitHubSources,\n prefetchGitHubRepos,\n prefetchGitHubSources,\n parseGitHubPermalink,\n parseGitHubLineRange,\n transformOgp,\n fetchOgpData,\n collectOgpUrls,\n prefetchOgpData,\n transformMermaidStatic,\n mermaidClientScript,\n transformAllPlugins,\n} from \"./plugins\";\nexport type {\n YouTubeOptions,\n GitHubRepoData,\n GitHubSourceCommit,\n GitHubSourceData,\n GitHubSourceRef,\n GitHubLineRange,\n GitHubOptions,\n OgpData,\n OgpOptions,\n MermaidOptions,\n TransformAllOptions,\n} from \"./plugins\";\n\n// Island Architecture\nexport { transformIslands, hasIslands, extractIslandInfo, generateHydrationScript } from \"./island\";\nexport type { LoadStrategy, IslandInfo, ParseIslandsResult } from \"./island\";\n\n// OG Image\nexport { resolveOgImageOptions, generateOgImages } from \"./og-image\";\nexport { resolveI18nOptions, createI18nPlugin } from \"./i18n\";\nexport type {\n OgImageOptions as OgImagePluginOptions,\n ResolvedOgImageOptions,\n OgImageTemplateProps,\n OgImageTemplateFn,\n OgImagePageEntry,\n OgImageResult,\n OgBrowserSession,\n} from \"./og-image\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAa,8BAA8B;CAAC;CAAO;CAAa;AAAM;AAEtE,SAAgB,4BAA4B,YAA0C;CACpF,MAAM,SAAS,YAAY,SAAS,aAAa;CACjD,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,aAAuB,CAAC;CAE9B,KAAK,MAAM,aAAa,QAAQ;EAC9B,MAAM,QAAQ,UAAU,WAAW,GAAG,IAAI,YAAY,IAAI;EAC1D,MAAM,MAAM,MAAM,YAAY;EAC9B,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,WAAW,KAAK,KAAK;EACvB;CACF;CAEA,OAAO;AACT;AAEA,SAAgB,mBACd,UACA,aAAgC,6BACvB;CACT,MAAM,WAAW,SAAS,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,YAAY;CAClE,OAAO,WAAW,MAAM,cAAc,SAAS,SAAS,UAAU,YAAY,CAAC,CAAC;AAClF;;AAGA,SAAgB,cAAc,UAA2B;CAEvD,OADiB,SAAS,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,EACpC,CAAC,YAAY,CAAC,CAAC,SAAS,MAAM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