import { ProjectFile } from '../types'; export interface ParsedFile { name: string; language: ProjectFile['language']; content: string; } /** * Infer file language from extension or block language tag */ export function inferLanguage(nameOrLang: string): ProjectFile['language'] { const lower = nameOrLang.toLowerCase(); if (lower.endsWith('.html') || lower === 'html') return 'html'; if (lower.endsWith('.css') || lower === 'css') return 'css'; if (lower.endsWith('.js') || lower.endsWith('.jsx') || lower === 'javascript' || lower === 'js') return 'javascript'; if (lower.endsWith('.ts') || lower.endsWith('.tsx') || lower === 'typescript' || lower === 'ts') return 'typescript'; if (lower.endsWith('.json') || lower === 'json') return 'json'; return 'markdown'; } /** * Robust line-by-line markdown code block extractor */ export function parseMarkdownCodeFiles(markdown: string): ParsedFile[] { const files: ParsedFile[] = []; const lines = markdown.split('\n'); let insideBlock = false; let currentLang = ''; let currentFilename = ''; let currentContent: string[] = []; let lastHeading = ''; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const trimmed = line.trim(); // Check for headings like "# index.html" or "### style.css" const headingMatch = trimmed.match(/^#{1,6}\s+([a-zA-Z0-9_\-\.\/]+\.[a-zA-Z0-9]+)\s*$/i); if (headingMatch && !insideBlock) { lastHeading = headingMatch[1].trim(); continue; } if (trimmed.startsWith('```')) { if (!insideBlock) { // Opening fence insideBlock = true; currentContent = []; const headerInfo = trimmed.replace(/^```/, '').trim(); // Extract language and potential filename from headerInfo // Examples: // "html " // "css /* file: style.css */" // "javascript // file: app.js" // "html index.html" // "html" let lang = ''; let detectedFilename = ''; // Clean out comment delimiters const cleaned = headerInfo .replace(/|\/\*|\*\/|\/\/|#/g, '') .replace(/file\s*:\s*/i, '') .trim(); const parts = cleaned.split(/\s+/).filter(Boolean); if (parts.length >= 2) { lang = parts[0]; detectedFilename = parts[1]; } else if (parts.length === 1) { if (parts[0].includes('.')) { detectedFilename = parts[0]; lang = inferLanguage(parts[0]); } else { lang = parts[0]; } } if (!detectedFilename && lastHeading) { detectedFilename = lastHeading; } currentLang = lang || 'html'; currentFilename = detectedFilename; lastHeading = ''; // Consume heading } else { // Closing fence insideBlock = false; const rawBody = currentContent.join('\n').trim(); if (rawBody) { let finalName = currentFilename; if (!finalName) { if (currentLang === 'html' || rawBody.includes('(); for (const f of files) { fileMap.set(f.name, f); } return Array.from(fileMap.values()); } /** * Combines project files into a runnable standalone HTML string with console bridge */ export function assemblePreviewHtml(files: ProjectFile[]): string { const htmlFile = files.find(f => f.name.endsWith('.html')) || { content: '