sokko-g/scripts/measure-public-assets.mjs
Shinuwa 22b397ebfa Document Sokko G's architecture and folders, and move JavaScript file headers to JSDoc @file blocks
Add ARCHITECTURE.md (layers, flows, folder map, glossary), CONTRIBUTING.md
(setup and step-by-step recipes) and a README in each main folder, with an
index of docs/. Convert the 511 JavaScript headers from "// Rôle :" lines to
JSDoc @file blocks, define a three-level header template in website/AGENTS.md
and check the header in tests/file-headers.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:42:13 +01:00

161 lines
7.3 KiB
JavaScript

/**
* @file Mesure les octets chargés par l'accueil et Aniimo sur le build servi par le serveur Node, et le stock
* d'images du dépôt.
*/
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import { platform } from "node:os";
import { basename, join, relative, sep } 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 };
// Deux familles distinctes : ce qu'un visiteur télécharge (transfert par route, CSS), et ce que le dépôt livre sans que tout
// soit téléchargé (stock d'images). Le stock grandit avec chaque collection Sokko TCG : seul le poids de chaque fichier est plafonné.
const budgets = {
transfer: {
cssGzipBytes: 75_000,
routeBytes: {
"home-cold": 1_750_000,
"aniimo-after-home": 3_000_000
}
},
storage: {
maxImageFileBytes: 1_000_000
}
};
const IMAGE_ROOT = "website/public/static/img";
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 Promise.all((await listFiles(IMAGE_ROOT)).map(async (file) => ({ file, bytes: (await stat(file)).size })));
// Répartition par premier dossier : les images à la racine forment le groupe « (racine) ».
const imageAreas = Object.entries(imageFiles.reduce((areas, { file, bytes }) => {
const parts = relative(IMAGE_ROOT, file).split(sep);
const area = parts.length > 1 ? parts[0] : "(racine)";
areas[area] = { files: (areas[area]?.files || 0) + 1, bytes: (areas[area]?.bytes || 0) + bytes };
return areas;
}, {})).sort(([, left], [, right]) => right.bytes - left.bytes).map(([area, totals]) => ({ area, ...totals }));
const oversizedImages = imageFiles.filter(({ bytes }) => bytes > budgets.storage.maxImageFileBytes).map(({ file, bytes }) => ({ file: relative(IMAGE_ROOT, file), bytes }));
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: imageFiles.reduce((sum, { bytes }) => sum + bytes, 0),
imageAreas,
largestImages: [...imageFiles].sort((left, right) => right.bytes - left.bytes).slice(0, 5).map(({ file, bytes }) => ({ file: relative(IMAGE_ROOT, file), bytes })),
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(`Stored images (not a download): ${report.repository.publicImageFiles} files, ${report.repository.publicImageBytes} bytes`);
console.table(imageAreas);
console.log(`Report: ${output}`);
assert.ok(css.every((entry) => entry.gzipBytes <= budgets.transfer.cssGzipBytes), `A CSS bundle exceeds ${budgets.transfer.cssGzipBytes} gzip bytes`);
for (const route of routes) {
assert.ok(route.transferBytes <= budgets.transfer.routeBytes[route.name], `${route.name} exceeds ${budgets.transfer.routeBytes[route.name]} transfer bytes`);
}
assert.deepEqual(oversizedImages, [], `Images over ${budgets.storage.maxImageFileBytes} bytes: convert or resize them (docs/PERFORMANCE.md)`);
} finally {
await browser?.close();
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
}