#!/usr/bin/env node import fs from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { extractSharePreviewMeta, injectOgTags, renderWechatSharePreviewHtml, } from '../mindspace-og-tags.mjs'; const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); async function loadHtmlSource(input) { if (/^https?:\/\//i.test(input)) { const res = await fetch(input); if (!res.ok) throw new Error(`HTTP ${res.status} for ${input}`); return { html: await res.text(), pageUrl: input.split('#')[0] }; } const filePath = path.resolve(process.cwd(), input); const html = await fs.readFile(filePath, 'utf8'); const pageUrl = pathToFileURL(filePath).toString(); return { html, pageUrl }; } async function main() { const input = process.argv[2]; const origin = (process.argv[3] || 'https://m.tkmind.cn').replace(/\/$/, ''); if (!input) { console.error('用法: node scripts/wechat-share-preview.mjs <页面路径或URL> [origin]'); process.exit(1); } const { html: rawHtml, pageUrl } = await loadHtmlSource(input); const pageDirUrl = pageUrl.includes('/') ? `${pageUrl.slice(0, pageUrl.lastIndexOf('/') + 1)}` : `${origin}/`; const html = injectOgTags(rawHtml, { origin, pageUrl, pageDirUrl }); const preview = extractSharePreviewMeta(html, { origin, pageUrl, pageDirUrl }); const outDir = path.join(root, 'public', 'dev'); await fs.mkdir(outDir, { recursive: true }); const outPath = path.join(outDir, 'wechat-share-preview.generated.html'); await fs.writeFile( outPath, renderWechatSharePreviewHtml(preview, { note: '由 scripts/wechat-share-preview.mjs 生成,可离线查看卡片布局。', }), 'utf8', ); console.log(`预览已写入 ${outPath}`); console.log(`title: ${preview.title}`); console.log(`description: ${preview.description}`); console.log(`site: ${preview.siteName}`); console.log(`image: ${preview.imageUrl || '(none)'}`); } main().catch((err) => { console.error(err); process.exit(1); });