sokko-g/scripts/measure-public-assets.mjs
Shinuwa ca39b76282
All checks were successful
Deploy Sokko G / deploy (push) Successful in 20s
Standardize public images on WebP and add conversion tooling
2026-10-23 12:12:02 +02:00

139 lines
6 KiB
JavaScript

// Rôle : mesure les octets chargés par l'accueil et Aniimo sur le build servi par le serveur Node.
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import { platform } from "node:os";
import { basename, join } from "node:path";
import { gzipSync } from "node:zlib";
import assert from "node:assert/strict";
import { chromium } from "@playwright/test";
import { createStaticServer } from "../server.mjs";
const label = String(process.argv[2] || "current").replace(/[^a-z0-9_-]+/gi, "-");
const viewport = { width: 1440, height: 900 };
const budgets = {
publicImageBytes: 25_000_000,
cssGzipBytes: 70_000,
routeTransferBytes: {
"home-cold": 1_750_000,
"aniimo-after-home": 3_000_000
}
};
async function listFiles(root) {
const entries = await readdir(root, { withFileTypes: true });
return (await Promise.all(entries.map(async (entry) => {
const path = join(root, entry.name);
return entry.isDirectory() ? listFiles(path) : [path];
}))).flat();
}
async function measureEntries(page, includeDocument) {
return page.evaluate(({ withDocument }) => {
const resources = performance.getEntriesByType("resource");
const entries = withDocument ? [...performance.getEntriesByType("navigation"), ...resources] : resources;
const summarize = (values) => ({
requests: values.length,
transferBytes: values.reduce((sum, entry) => sum + entry.transferSize, 0),
encodedBytes: values.reduce((sum, entry) => sum + entry.encodedBodySize, 0),
decodedBytes: values.reduce((sum, entry) => sum + entry.decodedBodySize, 0)
});
return {
...summarize(entries),
images: summarize(resources.filter((entry) => entry.initiatorType === "img" || /\.(?:png|webp|jpe?g)(?:\?|$)/i.test(entry.name))),
styles: summarize(resources.filter((entry) => entry.initiatorType === "link" && /\.css(?:\?|$)/i.test(entry.name))),
largestTransfers: [...resources]
.sort((left, right) => right.transferSize - left.transferSize)
.slice(0, 10)
.map((entry) => ({ path: new URL(entry.name).pathname, transferBytes: entry.transferSize }))
};
}, { withDocument: includeDocument });
}
async function routeReport(page, { name, route, selector, includeDocument }) {
if (!includeDocument) await page.evaluate(() => performance.clearResourceTimings());
await page.goto(route, { waitUntil: "networkidle" });
await page.locator(selector).first().waitFor({ state: "visible" });
await page.waitForTimeout(500);
const metrics = await measureEntries(page, includeDocument);
const images = await page.locator("img").evaluateAll(async (nodes) => {
const loaded = nodes.filter((node) => node.complete && node.naturalWidth > 0);
await Promise.all(loaded.map((node) => node.decode()));
return { present: nodes.length, decoded: loaded.length };
});
return { name, route, ...metrics, imageElements: images };
}
const imageFiles = await listFiles("website/public/static/img");
const cssFiles = (await listFiles("website/dist/assets")).filter((file) => file.endsWith(".css"));
const server = createStaticServer();
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
let browser;
try {
const address = server.address();
const baseURL = `http://127.0.0.1:${address.port}`;
browser = await chromium.launch();
const context = await browser.newContext({ viewport, serviceWorkers: "block" });
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("requestfailed", (request) => errors.push(`${request.url()}: ${request.failure()?.errorText || "request failed"}`));
const routes = [];
routes.push(await routeReport(page, {
name: "home-cold",
route: `${baseURL}/#/`,
selector: ".home-page, .hero",
includeDocument: true
}));
routes.push(await routeReport(page, {
name: "aniimo-after-home",
route: `${baseURL}/#/games/aniimo/aniimos`,
selector: ".aniimo-grid .aniimo-card",
includeDocument: false
}));
assert.deepEqual(errors, []);
const css = await Promise.all(cssFiles.map(async (file) => {
const content = await readFile(file);
return { file: basename(file), bytes: content.length, gzipBytes: gzipSync(content).length };
}));
const report = {
measuredAt: new Date().toISOString(),
label,
platform: platform(),
browser: browser.version(),
viewport,
protocol: "HTTP/1.1 local server.mjs, fresh browser context, no throttling",
budgets,
repository: {
publicImageFiles: imageFiles.length,
publicImageBytes: (await Promise.all(imageFiles.map((file) => stat(file)))).reduce((sum, entry) => sum + entry.size, 0),
css
},
routes
};
await mkdir(".local/performance", { recursive: true });
const output = `.local/performance/public-assets-${label}.json`;
await writeFile(output, `${JSON.stringify(report, null, 2)}\n`);
console.table(routes.map((route) => ({
route: route.name,
requests: route.requests,
transferBytes: route.transferBytes,
imageRequests: route.images.requests,
imageTransferBytes: route.images.transferBytes
})));
console.log(`CSS: ${css.map((entry) => `${entry.file} ${entry.bytes} bytes (${entry.gzipBytes} gzip)`).join(", ")}`);
console.log(`Public images: ${report.repository.publicImageFiles} files, ${report.repository.publicImageBytes} bytes`);
console.log(`Report: ${output}`);
assert.ok(report.repository.publicImageBytes <= budgets.publicImageBytes, `Public images exceed ${budgets.publicImageBytes} bytes`);
assert.ok(css.every((entry) => entry.gzipBytes <= budgets.cssGzipBytes), `A CSS bundle exceeds ${budgets.cssGzipBytes} gzip bytes`);
for (const route of routes) {
assert.ok(route.transferBytes <= budgets.routeTransferBytes[route.name], `${route.name} exceeds ${budgets.routeTransferBytes[route.name]} transfer bytes`);
}
} finally {
await browser?.close();
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
}