import type { MDXData } from "./utils"; import { formatDate } from "./utils"; /** * Converts MDX content to clean markdown format for AI tools * Handles YAML frontmatter generation and component serialization */ export function convertMdxToMarkdown(data: MDXData): string { let output = ""; // Step 0: Generate YAML frontmatter from metadata const { metadata, content } = data; output += "---\n"; output += `title: "${metadata.title}"\n`; if (metadata.publishedAt) { output += `date: ${formatDate(metadata.publishedAt)}\n`; } if (metadata.author) { output += `author: "${metadata.author}"\n`; } if (metadata.description) { output += `description: "${metadata.description}"\n`; } if (metadata.category) { output += `category: "${metadata.category}"\n`; } if (metadata.image) { output += `image: "${metadata.image}"\n`; } output += "---\n\n"; // Step 1: Strip import statements (confirmed: always at top of file) let markdown = content.replace(/^import\s+.*$/gm, ""); // Step 2: Convert to markdown links markdown = markdown.replace( /]*>([\s\S]*?)<\/ButtonLink>/g, (_match, href, children) => { // Extract plain text from children (remove any nested tags) const text = children.replace(/<[^>]*>/g, "").trim(); return `[${text}](${href})`; }, ); // Step 3: Convert to markdown images // Handle with alt attribute markdown = markdown.replace( /]*\s+)?src="([^"]*)"(?:[^>]*\s+)?alt="([^"]*)"[^>]*\/?>/g, (_match, src, alt) => { return `![${alt}](${src})`; }, ); // Handle without alt attribute markdown = markdown.replace( /]*\s+)?src="([^"]*)"[^>]*\/?>/g, (_match, src) => { return `![](${src})`; }, ); // Step 4: Replace components with a note to use GFM tables // TODO: Convert Table components in MDX source files to GFM tables markdown = markdown.replace(//g, () => { return ""; }); // Step 5: Convert
to native HTML
/ (always closed) markdown = markdown.replace( /]*>([\s\S]*?)<\/Details>/g, (_match, summary, content) => { return `
\n ${summary}\n ${content.trim()}\n
`; }, ); // Step 6: Replace interactive components with HTML comments markdown = markdown.replace( /]*(?:\/>|>[\s\S]*?<\/StatusPageExample>)/g, "", ); markdown = markdown.replace( /]*(?:\/>|>[\s\S]*?<\/SimpleChart>)/g, "", ); // Step 7: Convert