50 lines
3.4 KiB
JavaScript
50 lines
3.4 KiB
JavaScript
// Canonical CMS renderer adapter. The site tools use an identical, versioned copy.
|
|
import { readFile, writeFile, readdir, stat } from 'node:fs/promises';
|
|
import { join, posix } from 'node:path';
|
|
const safePath = p => typeof p === 'string' && /^assets\/[a-zA-Z0-9_./-]+$/.test(p) && !p.split('/').some(s => s === '..' || s.startsWith('.'));
|
|
const escape = s => s.replace(/&/g, '&').replace(/"/g, '"');
|
|
export function responsiveHtml(html, manifest, pagePath = 'index.html', used = null) {
|
|
if (!manifest || manifest.version !== 1) return html;
|
|
// Leave inline JS, JSON, styles and comments byte-for-byte intact.
|
|
return html.replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>|<style\b[^>]*>[\s\S]*?<\/style\s*>|<!--[\s\S]*?-->|<img\b[^>]*>/gi, tag => {
|
|
if (!/^<img\b/i.test(tag)) return tag;
|
|
const m = tag.match(/\ssrc\s*=\s*(["'])(.*?)\1/i); if (!m) return tag;
|
|
const source = m[2]; if (/^(?:[a-z]+:|\/\/)/i.test(source)) return tag;
|
|
const clean = source.split(/[?#]/)[0];
|
|
const key = clean.startsWith('/') ? clean.slice(1) : posix.normalize(posix.join(posix.dirname(pagePath), clean));
|
|
const record = manifest.images?.[key]; if (!record?.variants?.length) return tag;
|
|
used?.add(record);
|
|
const variants = record.variants;
|
|
if (!variants.every(v => safePath(v.path) && Number.isInteger(v.width) && v.width > 0 && Number.isInteger(v.height) && v.height > 0)) throw new Error('Invalid responsive image manifest');
|
|
const url = p => './' + posix.relative(posix.dirname(pagePath), p);
|
|
const largest = variants.at(-1);
|
|
let next = tag.replace(m[0], ` src="${escape(url(largest.path))}"`);
|
|
for (const attr of ['srcset', 'sizes', 'width', 'height']) next = next.replace(new RegExp(`\\s${attr}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>]+)`, 'gi'), '');
|
|
// Existing explicit sizes (e.g. icons) take precedence over the broad fallback.
|
|
const sizes = tag.match(/\ssizes\s*=\s*(["'])(.*?)\1/i)?.[2] || (/class=["'][^"']*\blogo\b/i.test(tag) ? '64px' : '(max-width: 767px) 86vw, 1280px');
|
|
const attrs = ` srcset="${variants.map(v => `${escape(url(v.path))} ${v.width}w`).join(', ')}" sizes="${escape(sizes)}" width="${largest.width}" height="${largest.height}"`;
|
|
return next.replace(/\s*\/?>(\s*)$/, `${attrs}>$1`);
|
|
});
|
|
}
|
|
export async function applyResponsiveImages(root) {
|
|
let manifest;
|
|
try { manifest = JSON.parse(await readFile(join(root, 'content/media-variants.json'), 'utf8')); }
|
|
catch (e) { if (e.code === 'ENOENT') return; throw e; }
|
|
if (manifest.version !== 1 || !manifest.images) throw new Error('Invalid media manifest');
|
|
async function walk(dir, prefix = '') {
|
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
if (entry.name.startsWith('.') || ['node_modules', 'templates', 'tools', 'content', 'test', 'docs'].includes(entry.name)) continue;
|
|
const path = join(dir, entry.name), relative = prefix + entry.name;
|
|
if (entry.isDirectory() && entry.name !== 'assets') await walk(path, relative + '/');
|
|
else if (entry.isFile() && entry.name.endsWith('.html')) {
|
|
const source = await readFile(path, 'utf8'), used = new Set(), next = responsiveHtml(source, manifest, relative, used);
|
|
for (const record of used) for (const v of record.variants) {
|
|
if (!safePath(v.path) || !(await stat(join(root, v.path))).isFile()) throw new Error('Missing responsive image');
|
|
}
|
|
if (next !== source) await writeFile(path, next);
|
|
}
|
|
}
|
|
}
|
|
await walk(root);
|
|
}
|