|
| 1 | +import fs from 'node:fs'; |
| 2 | +import pathlib from 'node:path'; |
| 3 | +import { parseArgs } from 'node:util'; |
| 4 | +import { JSDOM, VirtualConsole } from 'jsdom'; |
| 5 | + |
| 6 | +const { positionals: cliArgs, values: cliOpts } = parseArgs({ |
| 7 | + allowPositionals: true, |
| 8 | + options: { |
| 9 | + strict: { type: 'boolean' }, |
| 10 | + }, |
| 11 | +}); |
| 12 | +if (cliArgs.length < 3) { |
| 13 | + const self = pathlib.relative(process.cwd(), process.argv[1]); |
| 14 | + console.error(`Usage: node ${self} [--strict] <template.html> <data.json> <file.html>... |
| 15 | +
|
| 16 | +{{identifier}} substrings in template.html are replaced from data.json, then |
| 17 | +the result is inserted at the start of the body element in each file.html.`); |
| 18 | + process.exit(64); |
| 19 | +} |
| 20 | + |
| 21 | +const main = async (args, options) => { |
| 22 | + const [templateFile, dataFile, ...files] = args; |
| 23 | + const { strict } = options; |
| 24 | + |
| 25 | + // Evaluate the template and parse it into nodes for inserting. |
| 26 | + // Everything will be prepended to body elements except metadata elements, |
| 27 | + // which will be appended to head elements. |
| 28 | + // https://html.spec.whatwg.org/multipage/dom.html#metadata-content-2 |
| 29 | + const metadataNames = |
| 30 | + 'base, link, meta, noscript, script, style, template, title' |
| 31 | + .toUpperCase() |
| 32 | + .split(', '); |
| 33 | + const template = fs.readFileSync(templateFile, 'utf8'); |
| 34 | + const { default: data } = |
| 35 | + await import(pathlib.resolve(dataFile), { with: { type: 'json' } }); |
| 36 | + const namePatt = /[{][{]([\p{ID_Start}$_][\p{ID_Continue}$]*)[}][}]/gu; |
| 37 | + const resolved = template.replaceAll(namePatt, (_, name) => { |
| 38 | + if (Object.hasOwn(data, name)) return data[name]; |
| 39 | + if (strict) throw Error(`no data for {{${name}}}`); |
| 40 | + return ''; |
| 41 | + }); |
| 42 | + const headInserts = [], bodyInserts = []; |
| 43 | + let insertDom = JSDOM.fragment(resolved); |
| 44 | + for (const node of insertDom.childNodes) { |
| 45 | + if (metadataNames.includes(node.nodeName)) headInserts.push(node); |
| 46 | + else bodyInserts.push(node); |
| 47 | + } |
| 48 | + |
| 49 | + // Perform the insertions, suppressing JSDOM warnings from e.g. unsupported |
| 50 | + // CSS features. |
| 51 | + const virtualConsole = new VirtualConsole(); |
| 52 | + virtualConsole.on('error', () => {}); |
| 53 | + const jsdomOpts = { contentType: 'text/html; charset=utf-8', virtualConsole }; |
| 54 | + const getInserts = |
| 55 | + files.length > 1 ? nodes => nodes.map(n => n.cloneNode(true)) : x => x; |
| 56 | + const results = await Promise.allSettled(files.map(async file => { |
| 57 | + let dom = await JSDOM.fromFile(file, jsdomOpts); |
| 58 | + const { head, body } = dom.window.document; |
| 59 | + if (headInserts.length > 0) head.append(...getInserts(headInserts)); |
| 60 | + if (bodyInserts.length > 0) body.prepend(...getInserts(bodyInserts)); |
| 61 | + fs.writeFileSync(file, dom.serialize(), 'utf8'); |
| 62 | + })); |
| 63 | + |
| 64 | + const failures = results.flatMap(result => |
| 65 | + result.status === 'fulfilled' ? [] : [result.reason], |
| 66 | + ); |
| 67 | + if (failures.length > 0) throw AggregateError(failures); |
| 68 | +}; |
| 69 | + |
| 70 | +main(cliArgs, cliOpts).catch(err => { |
| 71 | + console.error(err); |
| 72 | + process.exit(1); |
| 73 | +}); |
0 commit comments