import fs from 'fs/promises'; import path from 'path'; import axios from 'axios'; const CONTENT_DIR = path.join(process.cwd(), 'content'); const ASSETS_DIR = path.join(process.cwd(), 'public', 'media', 'visual-links'); async function downloadImage(url: string, filename: string): Promise { const filepath = path.join(ASSETS_DIR, filename); try { const response = await axios.get(url, { responseType: 'arraybuffer' }); await fs.writeFile(filepath, response.data); return `/media/visual-links/${filename}`; } catch (err: any) { console.error(`Failed to download ${url}:`, err.message); throw err; } } async function processMdxFile(filepath: string) { let content = await fs.readFile(filepath, 'utf-8'); let modified = false; const linkPreviewRegex = //g; let match; let newContent = content; // Need to correctly parse the JSON inside data={...} // The regex above matches `` // Actually, we can just regex for "image":"https://..." const imageRegex = /"image":\s*"([^"]+)"/g; while ((match = linkPreviewRegex.exec(content)) !== null) { const dataString = match[1] + '}'; try { const data = JSON.parse(dataString); if (data.image && data.image.startsWith('http')) { const url = new URL(data.image); let ext = path.extname(url.pathname); if (!ext) ext = '.jpg'; // Fallback const filename = `${data.id || Math.random().toString(36).substring(7)}${ext}`; console.log(`Downloading ${data.image} to ${filename}...`); const newUrl = await downloadImage(data.image, filename); const oldImageString = `"image":"${data.image}"`; const newImageString = `"image":"${newUrl}"`; newContent = newContent.replace(oldImageString, newImageString); modified = true; } } catch (err) { console.warn(`Could not parse data string in ${filepath}:`, dataString); } } if (modified) { await fs.writeFile(filepath, newContent, 'utf-8'); console.log(`✅ Updated ${filepath}`); } } async function walk(dir: string) { const files = await fs.readdir(dir); for (const file of files) { const filepath = path.join(dir, file); const stat = await fs.stat(filepath); if (stat.isDirectory()) { await walk(filepath); } else if (file.endsWith('.mdx')) { await processMdxFile(filepath); } } } async function main() { await fs.mkdir(ASSETS_DIR, { recursive: true }); await walk(CONTENT_DIR); } main().catch(console.error);