|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const glob = require('glob'); |
| 4 | +const https = require('https'); |
| 5 | +const http = require('http'); |
| 6 | + |
| 7 | +// Helper function to fetch content from URL |
| 8 | +function fetchUrl(url) { |
| 9 | + return new Promise((resolve, reject) => { |
| 10 | + const client = url.startsWith('https:') ? https : http; |
| 11 | + |
| 12 | + client.get(url, (res) => { |
| 13 | + if (res.statusCode !== 200) { |
| 14 | + reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`)); |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + let data = ''; |
| 19 | + res.on('data', chunk => data += chunk); |
| 20 | + res.on('end', () => resolve(data)); |
| 21 | + }).on('error', reject); |
| 22 | + }); |
| 23 | +} |
| 24 | + |
| 25 | +// Helper function to extract snippet from content using comment markers |
| 26 | +function extractSnippet(content, snippetId = null) { |
| 27 | + const lines = content.split('\n'); |
| 28 | + |
| 29 | + // Define comment patterns for different languages |
| 30 | + const commentPatterns = [ |
| 31 | + // Hash-style comments (Python, Ruby, Shell, YAML, etc.) |
| 32 | + { start: `#docs-start${snippetId ? `-${snippetId}` : ''}`, end: `#docs-end${snippetId ? `-${snippetId}` : ''}` }, |
| 33 | + // Double-slash comments (JavaScript, Java, C++, etc.) |
| 34 | + { start: `//docs-start${snippetId ? `-${snippetId}` : ''}`, end: `//docs-end${snippetId ? `-${snippetId}` : ''}` }, |
| 35 | + // Block comments (CSS, SQL, etc.) |
| 36 | + { start: `/*docs-start${snippetId ? `-${snippetId}` : ''}*/`, end: `/*docs-end${snippetId ? `-${snippetId}` : ''}*/` }, |
| 37 | + // XML/HTML comments |
| 38 | + { start: `<!--docs-start${snippetId ? `-${snippetId}` : ''}-->`, end: `<!--docs-end${snippetId ? `-${snippetId}` : ''}-->` } |
| 39 | + ]; |
| 40 | + |
| 41 | + for (const pattern of commentPatterns) { |
| 42 | + let startIndex = -1; |
| 43 | + let endIndex = -1; |
| 44 | + |
| 45 | + for (let i = 0; i < lines.length; i++) { |
| 46 | + const line = lines[i].trim(); |
| 47 | + if (line.includes(pattern.start)) { |
| 48 | + startIndex = i + 1; // Start from the line after the start marker |
| 49 | + } else if (line.includes(pattern.end) && startIndex !== -1) { |
| 50 | + endIndex = i; // End at the line before the end marker |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) { |
| 56 | + return lines.slice(startIndex, endIndex).join('\n'); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // If no snippet markers found, return original content |
| 61 | + return content; |
| 62 | +} |
| 63 | + |
| 64 | +function codeImportPlugin(context, options) { |
| 65 | + return { |
| 66 | + name: 'code-import-plugin', |
| 67 | + async loadContent() { |
| 68 | + // Find all markdown files in docs directory that might contain code imports |
| 69 | + const docsPath = path.join(context.siteDir, 'docs'); |
| 70 | + |
| 71 | + const markdownFiles = [ |
| 72 | + ...glob.sync('**/*.md', { cwd: docsPath, absolute: true }), |
| 73 | + ...glob.sync('**/*.mdx', { cwd: docsPath, absolute: true }), |
| 74 | + ]; |
| 75 | + |
| 76 | + // Process each markdown file for code imports |
| 77 | + const processedFiles = []; |
| 78 | + |
| 79 | + for (const filePath of markdownFiles) { |
| 80 | + try { |
| 81 | + let content = fs.readFileSync(filePath, 'utf8'); |
| 82 | + let modified = false; |
| 83 | + |
| 84 | + // Process code blocks with file= or url= syntax |
| 85 | + const fileUrlRegex = /```(\w+)?\s*((?:file|url)=[^\s\n]+)([^\n]*)\n([^`]*?)```/g; |
| 86 | + const matches = [...content.matchAll(fileUrlRegex)]; |
| 87 | + |
| 88 | + for (const match of matches) { |
| 89 | + const [fullMatch, lang, param, additionalMeta, existingContent] = match; |
| 90 | + |
| 91 | + // Parse snippet parameter from additional metadata |
| 92 | + const snippetMatch = additionalMeta.match(/snippet=(\w+)/); |
| 93 | + const snippetId = snippetMatch ? snippetMatch[1] : null; |
| 94 | + |
| 95 | + try { |
| 96 | + let importedContent; |
| 97 | + |
| 98 | + if (param.startsWith('file=')) { |
| 99 | + // Handle file import |
| 100 | + const importPath = param.replace('file=', ''); |
| 101 | + const absoluteImportPath = path.resolve(context.siteDir, importPath); |
| 102 | + const rawContent = fs.readFileSync(absoluteImportPath, 'utf8'); |
| 103 | + importedContent = extractSnippet(rawContent, snippetId); |
| 104 | + } else if (param.startsWith('url=')) { |
| 105 | + // Handle URL import |
| 106 | + const url = param.replace('url=', ''); |
| 107 | + try { |
| 108 | + const rawContent = await fetchUrl(url); |
| 109 | + importedContent = extractSnippet(rawContent, snippetId); |
| 110 | + } catch (urlError) { |
| 111 | + console.warn(`Could not fetch URL ${url} in ${filePath}: ${urlError.message}`); |
| 112 | + continue; // Skip this replacement if URL fetch fails |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // Preserve the complete metadata |
| 117 | + const fullMeta = `${param}${additionalMeta}`; |
| 118 | + const metaStr = fullMeta ? ` ${fullMeta}` : ''; |
| 119 | + const replacement = `\`\`\`${lang || ''}${metaStr}\n${importedContent}\n\`\`\``; |
| 120 | + |
| 121 | + content = content.replace(fullMatch, replacement); |
| 122 | + modified = true; |
| 123 | + |
| 124 | + } catch (error) { |
| 125 | + console.warn(`Could not process ${param} in ${filePath}: ${error.message}`); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + if (modified) { |
| 130 | + processedFiles.push({ |
| 131 | + path: filePath, |
| 132 | + content: content, |
| 133 | + originalPath: filePath |
| 134 | + }); |
| 135 | + } |
| 136 | + } catch (error) { |
| 137 | + console.warn(`Error processing file ${filePath}: ${error.message}`); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + return { processedFiles }; |
| 142 | + }, |
| 143 | + |
| 144 | + async contentLoaded({ content, actions }) { |
| 145 | + const { processedFiles } = content; |
| 146 | + |
| 147 | + // Write processed files back to disk during build |
| 148 | + for (const file of processedFiles) { |
| 149 | + try { |
| 150 | + fs.writeFileSync(file.path, file.content, 'utf8'); |
| 151 | + console.log(`Processed code imports in: ${path.relative(context.siteDir, file.path)}`); |
| 152 | + } catch (error) { |
| 153 | + console.error(`Error writing processed file ${file.path}: ${error.message}`); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + }; |
| 158 | +} |
| 159 | + |
| 160 | +module.exports = codeImportPlugin; |
0 commit comments