perf(site): serve responsive WebP and compressed Hub videos

This commit is contained in:
DCCONSTRUCTIONS
2026-11-06 03:24:43 +03:00
parent 1b4fe33957
commit f7951374a8
204 changed files with 2438 additions and 128 deletions
+4
View File
@@ -1,3 +1,4 @@
import { applyResponsiveImages } from "./responsive-images.mjs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -459,6 +460,7 @@ async function renderBlock(block, renderCounts) {
description: "", imageSrc: "", imageAlt: "", videoSrc: "", posterSrc: "", ...item,
detailsHref: safeArticleHref(item.detailsHref),
detailsLabel: typeof item.detailsLabel === "string" && item.detailsLabel.trim() ? item.detailsLabel.trim() : "Подробнее",
imageSizes: ["photo-gallery", "scenario-gallery"].includes(block.content.mediaKind) ? "(max-width: 767px) 82vw, 560px" : "(max-width: 767px) 86vw, 1280px",
imageLinkEnabled: block.content.openImagesInFullscreen === true,
imageLinkDisabled: block.content.openImagesInFullscreen !== true,
}));
@@ -544,3 +546,5 @@ await writeFile(outputPath, output);
await writeSeoFiles(page);
console.log(`Rendered ${page.slug} -> ${outputPath}`);
await applyResponsiveImages(repoRoot);
+3
View File
@@ -1,3 +1,4 @@
import { applyResponsiveImages } from "./responsive-images.mjs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -783,3 +784,5 @@ for (const [from, to] of Object.entries(redirects)) {
}
await writeFile(join(repoRoot, ".htaccess"), `# Generated legacy URL redirects\n${rules.join("\n")}\n`);
console.log(`Rendered ${records.length + 1} knowledge pages -> /${knowledgeBasePath()}/`);
await applyResponsiveImages(repoRoot);
+49
View File
@@ -0,0 +1,49 @@
// 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);
}
+6 -1
View File
@@ -2,7 +2,7 @@ from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlsplit,unquote
from collections import Counter
import json,re,subprocess
import json,re,subprocess,hashlib
r=Path(__file__).resolve().parents[1];fail=[];assets=set();anchors=[]
class Page(HTMLParser):
def __init__(self):super().__init__();self.ids=[];self.refs=[];self.h1=0;self.scripts=[];self.ld=False;self.text=[];self.script=False;self.canonical=[]
@@ -51,6 +51,11 @@ def videos(data):
if src.endswith(('.mp4','.mov','.webm')):result.add(src)
return result
oldvideos=videos(old);newvideos=videos(new)
video_manifest = json.loads((r/'content/media-video-variants.json').read_text()) if (r/'content/media-video-variants.json').exists() else {'videos': []}
for item in video_manifest['videos']:
assert hashlib.sha256((r/item['original']).read_bytes()).hexdigest() == item['sha256Original']
assert hashlib.sha256((r/item['output']).read_bytes()).hexdigest() == item['sha256Output']
if './'+item['output'] in newvideos: newvideos.add('./'+item['source'])
assert oldvideos<=newvideos,oldvideos-newvideos
knowledge=json.loads((r/'content/knowledge.json').read_text())
def active_nodes(nodes):