Public: anyone can read this; the crew can change it.

A weight budget test caps the JavaScript and CSS a page ships and requires sizes on every image #282

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/deal-clock:mason/271-a-weight-budget-test-caps-the-javascript → main 4 commits fork 1 thread · 1 unresolved

  • Merged. mason/271-a-weight-budget-test-caps-the-javascript was merged into main as d124019.

Review

Sign in to review this change.
3 files changed +90 −2
src/pages/deal.ts +1 −1
@@ -413,7 +413,7 @@ export function dealPage(input: {
413413 })
414414 : ""
415415 }`;
416 return layout({ body, who, agent, waiting: input.waiting, path, heading: deal.address, notice, open: opened?.hrefs });
416 return layout({ body, who, agent, sheets: false, waiting: input.waiting, path, heading: deal.address, notice, open: opened?.hrefs });
417417 }
418418
419419 /** What the form was last sent with, what was wrong with it, and the dates it would make. */
src/pages/layout.ts +3 −1
@@ -45,6 +45,8 @@ export function layout(input: {
4545 waiting?: number | undefined;
4646 /** Whether the page keeps its regions live; false for a page with none. */
4747 live?: boolean;
48 /** Whether the page has dates that open a sheet in place; false for a page that shows its sheets already. */
49 sheets?: boolean;
4850 /** A page handed to someone outside the app: the brand only, no sign-in, footer or script. */
4951 plain?: boolean;
5052 /** A class on <body>, for styles that belong to one page only. */
@@ -79,7 +81,7 @@ export function layout(input: {
7981 <meta name="twitter:description" content="${escape(description)}">
8082 <link rel="stylesheet" href="${tokensHref}">
8183 <link rel="stylesheet" href="${asset("app.css")}">
82 ${plain || input.live === false ? "" : `<script type="module" src="${asset("live.js")}"></script><script type="module" src="${asset("sheets.js")}"></script>`}
84 ${plain || input.live === false ? "" : `<script type="module" src="${asset("live.js")}"></script>${input.sheets === false ? "" : `<script type="module" src="${asset("sheets.js")}"></script>`}`}
8385 <body${bodyClass === undefined ? "" : ` class="${escape(bodyClass)}"`}>
8486 <div class="page">
8587 <a class="skip" href="#content">Skip to content</a>
src/weight.test.ts added +86
@@ -0,0 +1,86 @@
1 /** What a page weighs: the scripts and styles it ships stay under a cap, a page links only the scripts it uses, and nothing that paints has no size. */
2 import { afterAll, expect, test } from "bun:test";
3 import { mkdtempSync, readdirSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { forgetRationing } from "./security.ts";
7 import { serve } from "./server.ts";
8 import { sign } from "./who.ts";
9
10 const KEY = "a-key-only-the-forge-holds";
11 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-weight-")), identityKey: KEY });
12 const base = `http://${server.hostname}:${server.port}`;
13 afterAll(() => server.stop(true));
14 const identity = `u1|alice|admin|${Date.now() + 600_000}`;
15 const admin = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
16 const get = async (path: string): Promise<string> => {
17 forgetRationing();
18 return (await fetch(base + path, { headers: admin })).text();
19 };
20
21 /** Measured at 28 196 bytes (app.css 22 663, live.js 2 491, sheets.js 1 545, review.js 667, print.js 332); the cap is that plus about 10 percent. Raise it on purpose, in a pull that says why. */
22 const CAP_BYTES = 31_000;
23
24 test("the JavaScript and CSS the app serves stay under the weight cap", async () => {
25 const files = readdirSync(join(import.meta.dir, "..", "static")).filter((f) => f === "app.css" || f.endsWith(".js"));
26 expect(files.sort()).toEqual(["app.css", "live.js", "print.js", "review.js", "sheets.js"]);
27 let total = 0;
28 for (const f of files) {
29 const res = await fetch(`${base}/static/${f}`);
30 total += (await res.arrayBuffer()).byteLength;
31 }
32 expect(total).toBeLessThanOrEqual(CAP_BYTES);
33 });
34
35 test("static files are served with the immutable cache header when linked by content", async () => {
36 const html = await get("/");
37 const links = [...html.matchAll(/(?:src|href)="(\/static\/[^"]+\?v=[0-9a-f]+)"/g)].map((m) => m[1]!);
38 expect(links.length).toBeGreaterThan(2);
39 for (const l of links) expect((await fetch(base + l)).headers.get("cache-control")).toBe("public, max-age=31536000, immutable");
40 });
41
42 /** What each script needs on the page before it does anything. A new script in static/ has no rule here and fails as "not known": add its rule with it. */
43 const needs: Record<string, RegExp> = {
44 "live.js": /data-live=|id="live-status"/,
45 "sheets.js": /<a\b[^>]*data-sheet=/,
46 "print.js": /data-print/,
47 "review.js": /data-keys/,
48 };
49
50 /** The img and svg tags in `html` with neither width and height attributes nor an inline width, height or aspect-ratio. */
51 function unsized(html: string): string[] {
52 return [...html.matchAll(/<(?:img|svg)\b[^>]*>/g)]
53 .map((m) => m[0])
54 .filter((tag) => !(/\swidth=/.test(tag) && /\sheight=/.test(tag)) && !/\sstyle="[^"]*(width|height|aspect-ratio)/.test(tag));
55 }
56
57 const ids = async (): Promise<number[]> => ((await (await fetch(base + "/api/deals", { headers: admin })).json()) as { id: number }[]).map((d) => d.id);
58
59 test("every page of the tour links only the scripts it uses and sizes every image", async () => {
60 const deals = await ids();
61 expect(deals.length).toBeGreaterThan(1);
62 const paths = ["/", "/week", "/people", "/profile", "/review", ...deals.flatMap((i) => [`/deals/${i}`, `/deals/${i}/timeline`, `/deals/${i}/sheets`])];
63 const unused: string[] = [];
64 const unsizedFound: string[] = [];
65 for (const path of paths) {
66 const html = await get(path);
67 for (const m of html.matchAll(/<script\b[^>]*\bsrc="\/static\/([^"?]+)/g)) {
68 const name = m[1]!;
69 // The script's own tag is not a use of it.
70 const body = html.replace(/<script\b[^>]*><\/script>/g, "");
71 if (!needs[name]) unused.push(`${path}: ${name} is not known`);
72 else if (!needs[name]!.test(body)) unused.push(`${path}: ${name}`);
73 }
74 for (const tag of unsized(html)) unsizedFound.push(`${path}: ${tag.slice(0, 80)}`);
75 }
76 expect(unused).toEqual([]);
outdated

This test is a tautology: it runs a regex over a string it built itself and never calls the code in the tour test, so it cannot fail when the real check breaks. Extract the image-size rule into a function, use it in the tour test, and test that function here with unsized and sized tags (img and svg).

77 expect(unsizedFound).toEqual([]);
78 });
79
80 test("the sizing rule flags an img or svg with no size and passes a sized one", () => {
81 expect(unsized('<img src="/a.png">')).toEqual(['<img src="/a.png">']);
82 expect(unsized('<svg viewBox="0 0 1 1">')).toEqual(['<svg viewBox="0 0 1 1">']);
83 expect(unsized('<img src="/a.png" width="8" height="8"><svg width="1" height="1"></svg>')).toEqual([]);
84 expect(unsized('<img src="/a.png" style="aspect-ratio: 1">')).toEqual([]);
85 expect(unsized("<p>no pictures</p>")).toEqual([]);
86 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs