Files
e-tib.com/scripts/migrate-visual-links.ts
Marc Mintel 26d325df44
Some checks failed
Build & Deploy / 🔍 Prepare (push) Successful in 38s
Build & Deploy / 🧪 QA (push) Successful in 1m22s
Build & Deploy / 🏗️ Build (push) Successful in 4m27s
Build & Deploy / 🚀 Deploy (push) Failing after 39s
Build & Deploy / 🧪 Post-Deploy Verification (push) Has been skipped
Build & Deploy / 🔔 Notify (push) Successful in 2s
fix(config): ensure analytics URL has protocol to prevent build crash
2026-05-12 13:01:18 +02:00

81 lines
2.6 KiB
TypeScript

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<string> {
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 = /<Block type="visualLinkPreview" data={([^}]+)}} \/>/g;
let match;
let newContent = content;
// Need to correctly parse the JSON inside data={...}
// The regex above matches `<Block type="visualLinkPreview" data={{"url":"...","image":"..."}} />`
// 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);