/** * Lighthouse, mobile (WEBSITE-1.0-PLAN §13, ROADMAP §11 "Checks"): the demo church's home page, an * event and the messages page in each template, with the template's defaults. SEO 100, * accessibility 95+, performance 90+. Lighthouse's default run is a phone on a throttled * connection (simulated), against the production build the other specs use; each page is measured * three times (LIGHTHOUSE_RUNS), with the CPU slowdown calibrated to this machine * (calibratedSlowdown), and the median run counts. Its reports go to * e2e/lighthouse/ (not kept in git) for a look when a score drops. */ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { chromium, expect, test } from "@playwright/test"; import * as chromeLauncher from "chrome-launcher"; import lighthouse from "lighthouse"; const BACKEND = "http://127.0.0.1:5310"; const SITE = "http://localhost:3310"; const TEMPLATES = ["heritage", "bold", "community", "clean"] as const; const MIN = { seo: 1, accessibility: 0.95, performance: 0.9 } as const; const RUNS = Number(process.env.LIGHTHOUSE_RUNS ?? 3); /** * Lighthouse's 4× CPU slowdown stands a fast desktop (its benchmark about 1500) in for a mid-range * phone. On a slower or busy machine the same 4× makes a far slower phone than the target, and the * score measures the machine: here the benchmark moved from 1450 to 460 between runs a minute * apart. So a quick probe reads the benchmark first and the slowdown is scaled to it (at least ×1), * as Lighthouse's throttling notes advise; the thresholds stay the same. */ const slowdownFor = (index: number) => Math.round(Math.min(4, Math.max(1, (4 * index) / 1500)) * 10) / 10; async function calibratedSlowdown(url: string): Promise { const probe = await lighthouse(`${SITE}${url}`, { port: chrome.port, logLevel: "error", onlyAudits: ["viewport"] }); return slowdownFor(probe?.lhr.environment.benchmarkIndex ?? 1500); } /** * One measured run, calibrated. The machine can slow down between the probe and the run; a run * whose own benchmark called for a much smaller slowdown than it used is taken again (twice at most). */ async function measure(url: string) { let r; for (let attempt = 0; attempt < 3; attempt++) { const slowdown = await calibratedSlowdown(url); r = await lighthouse(`${SITE}${url}`, { port: chrome.port, output: "html", logLevel: "error", onlyCategories: Object.keys(MIN), throttling: { cpuSlowdownMultiplier: slowdown } as never }); if (!r || slowdown <= slowdownFor(r.lhr.environment.benchmarkIndex) * 1.3) break; } return r; } const reports = path.join(path.dirname(fileURLToPath(import.meta.url)), "lighthouse"); test.describe.configure({ timeout: 600_000 }); let chrome: chromeLauncher.LaunchedChrome; test.beforeAll(async () => { fs.mkdirSync(reports, { recursive: true }); chrome = await chromeLauncher.launch({ chromePath: chromium.executablePath(), chromeFlags: ["--headless=new", "--no-first-run"] }); }); test.afterAll(async () => { await chrome?.kill(); }); for (const template of TEMPLATES) { test(`${template}: home, an event and the messages, on a phone`, async ({ request, page }) => { expect((await request.post(`${BACKEND}/test/demo?template=${template}`)).ok()).toBeTruthy(); await page.goto("/events"); const event = await page.locator('main a[href^="/events/"]').first().getAttribute("href"); expect(event).toBeTruthy(); const failed: string[] = []; for (const [name, url] of [["home", "/"], ["event", event!], ["messages", "/messages"]] as const) { // Once to warm the server, then measured RUNS times; the median run (by performance) counts, // as Lighthouse advises: one run's total blocking time moves by 200ms+ on a busy machine. await request.get(url); const runs = []; for (let n = 0; n < RUNS; n++) { const r = await measure(url); expect(r, `${template} ${name}`).toBeTruthy(); runs.push(r!); } runs.sort((a, b) => (a.lhr.categories.performance?.score ?? 0) - (b.lhr.categories.performance?.score ?? 0)); const result = runs[Math.floor(RUNS / 2)]; fs.writeFileSync(path.join(reports, `${template}-${name}.html`), String(result!.report)); const scores = Object.fromEntries(Object.keys(MIN).map((c) => [c, result!.lhr.categories[c]?.score ?? 0])); const env = result!.lhr.environment; console.log(`[lighthouse] ${template} ${name}: ${Object.entries(scores).map(([c, s]) => `${c} ${Math.round(s * 100)}`).join(", ")} (benchmark ${Math.round(env.benchmarkIndex)}, CPU ×${result!.lhr.configSettings.throttling.cpuSlowdownMultiplier})`); for (const [c, min] of Object.entries(MIN)) { if (scores[c]! < min) { const audits = Object.values(result!.lhr.audits).filter((a) => a.score !== null && a.score < 0.9 && (result!.lhr.categories[c]?.auditRefs ?? []).some((r) => r.id === a.id && r.weight > 0)); failed.push(`${template} ${name} ${c} ${Math.round(scores[c]! * 100)} < ${min * 100}: ${audits.map((a) => `${a.id}${a.displayValue ? ` (${a.displayValue})` : ""}`).join(", ")}`); } } } expect(failed).toEqual([]); }); }