huayang/frontend/scripts/extract-page.mjs
2026-05-07 18:24:22 +08:00

49 lines
1.7 KiB
JavaScript

import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const [, , sourceHtmlArg, outputPrefixArg] = process.argv
if (!sourceHtmlArg || !outputPrefixArg) {
throw new Error(
'Usage: node scripts/extract-page.mjs <source-html-path> <output-prefix>\n' +
'Example: npm run extract:page -- ./snapshots/about.html about\n' +
'Writes src/generated/<prefix>-page-body.html, <prefix>-assets.json, <prefix>-inline-scripts.txt'
)
}
const currentFile = fileURLToPath(import.meta.url)
const rootDir = path.resolve(path.dirname(currentFile), '..')
const sourceHtmlPath = path.resolve(rootDir, sourceHtmlArg)
const outDir = path.resolve(rootDir, 'src', 'generated')
const html = fs.readFileSync(sourceHtmlPath, 'utf8')
const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i)
if (!bodyMatch) throw new Error(`Failed to extract <body> from ${sourceHtmlArg}`)
let bodyHtml = bodyMatch[1]
bodyHtml = bodyHtml.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
const links = Array.from(html.matchAll(/<link[^>]+href="([^"]+)"[^>]*>/gi)).map((m) => m[1])
const scripts = Array.from(html.matchAll(/<script[^>]+src="([^"]+)"[^>]*><\/script>/gi)).map(
(m) => m[1]
)
const inlineScripts = Array.from(
html.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)
)
.map((m) => m[1].trim())
.filter(Boolean)
fs.writeFileSync(path.join(outDir, `${outputPrefixArg}-page-body.html`), bodyHtml, 'utf8')
fs.writeFileSync(
path.join(outDir, `${outputPrefixArg}-assets.json`),
JSON.stringify({ scripts, links }, null, 2),
'utf8'
)
fs.writeFileSync(
path.join(outDir, `${outputPrefixArg}-inline-scripts.txt`),
inlineScripts.join('\n/*__INLINE_SPLIT__*/\n'),
'utf8'
)
console.log(`Generated files for ${outputPrefixArg}`)