trivium 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cache.ts ADDED
@@ -0,0 +1,297 @@
1
+ import { nowMs } from "./env.ts";
2
+ import { TriviumError } from "./errors.ts";
3
+ import {
4
+ closingLine,
5
+ elapsed,
6
+ fitted,
7
+ headerRow,
8
+ NOTE_INDENT,
9
+ type Outcome,
10
+ type Paint,
11
+ plural,
12
+ SCHEMA_VERSION,
13
+ SEPARATOR,
14
+ truncatePath,
15
+ withNotes,
16
+ } from "./format.ts";
17
+ import type { ResolvedConfig } from "./load-config.ts";
18
+ import { IMMUTABLE } from "./serve.ts";
19
+
20
+ interface CacheInput {
21
+ url: string;
22
+ config: ResolvedConfig;
23
+ }
24
+
25
+ const TEXT = /\.(js|mjs|css|svg|html|json)$/;
26
+ const MAX_AGE = /max-age=(\d+)/;
27
+ const YEAR_SECONDS = 31_536_000;
28
+ // The HTML must revalidate within this, or a deploy goes unseen for
29
+ // as long.
30
+ const STALE_SECONDS = 3600;
31
+ const REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/g;
32
+ const LEADING_SLASH = /^\//;
33
+ const RELATIVE = /["'`(]((?:\.\.?\/)+[\w./-]+\.\w+)["'`)]/g;
34
+
35
+ type Verdict = "ok" | "warn" | "fail";
36
+
37
+ interface FileCheck {
38
+ path: string;
39
+ verdict: Verdict;
40
+ status: number;
41
+ cacheControl: string;
42
+ encoding: string;
43
+ // A CDN's cache status (Cloudflare's), when there's one.
44
+ edge: string;
45
+ problems: string[];
46
+ }
47
+
48
+ // The verdict on one response's headers: a content-hashed asset should be
49
+ // cached a year and immutable; the HTML should revalidate, so a deploy
50
+ // shows up.
51
+ function judge(
52
+ path: string,
53
+ document: boolean,
54
+ hashed: boolean,
55
+ response: { status: number; ok: boolean; headers: Headers },
56
+ ): Omit<FileCheck, "path"> {
57
+ const cacheControl = response.headers.get("cache-control") ?? "";
58
+ const encoding = response.headers.get("content-encoding") ?? "";
59
+ const edge = response.headers.get("cf-cache-status") ?? "";
60
+ const maxAge = Number(MAX_AGE.exec(cacheControl)?.[1] ?? 0);
61
+ const problems: string[] = [];
62
+ let failed = false;
63
+ if (!response.ok) {
64
+ problems.push(`HTTP ${response.status}`);
65
+ failed = true;
66
+ } else if (document) {
67
+ if (cacheControl.includes("immutable") || maxAge >= STALE_SECONDS) {
68
+ problems.push("cached too long: a deploy stays hidden");
69
+ failed = true;
70
+ }
71
+ } else if (hashed) {
72
+ if (maxAge < YEAR_SECONDS) {
73
+ problems.push(`hashed but max-age=${maxAge}: every visit asks again`);
74
+ failed = true;
75
+ } else if (!cacheControl.includes("immutable")) {
76
+ problems.push("no immutable: a reload revalidates");
77
+ }
78
+ }
79
+ if (response.ok && (document || TEXT.test(path)) && encoding === "") {
80
+ problems.push("not compressed");
81
+ }
82
+ return {
83
+ verdict: failed ? "fail" : problems.length ? "warn" : "ok",
84
+ status: response.status,
85
+ cacheControl,
86
+ encoding,
87
+ edge,
88
+ problems,
89
+ };
90
+ }
91
+
92
+ // Crawls the page and every same-origin asset it can load: what the HTML
93
+ // links, and what those files reference in turn (lazy chunks, fonts,
94
+ // icons). A CDN's files follow that CDN's headers, so they're skipped.
95
+ export async function runCache(input: CacheInput): Promise<Outcome> {
96
+ const startMs = nowMs();
97
+ let page: URL;
98
+ try {
99
+ page = new URL(input.url);
100
+ } catch {
101
+ throw new TriviumError(
102
+ "TV_USAGE",
103
+ `trivium cache: ${JSON.stringify(input.url)} isn't a URL: pass the deployed page's http(s) URL`,
104
+ );
105
+ }
106
+ const dir = input.config.assets.path
107
+ .replace(LEADING_SLASH, "")
108
+ .replace(REGEX_SPECIAL, "\\$&");
109
+ // Only files under the assets path, quoted, in a template literal or in
110
+ // `url()`, since a CDN's files follow that CDN's headers, not the site's.
111
+ const asset = new RegExp(
112
+ String.raw`(?:^|["'\x60(\s,])\.?\/?(${dir}[\w.-]+\.\w+)`,
113
+ "g",
114
+ );
115
+ const hash = input.config.assets.hash;
116
+
117
+ const check = async (path: string, document: boolean) => {
118
+ let response: Response;
119
+ try {
120
+ response = await fetch(new URL(path, page), {
121
+ headers: { "accept-encoding": "br, gzip" },
122
+ });
123
+ } catch (error) {
124
+ const message = error instanceof Error ? error.message : String(error);
125
+ throw new TriviumError(
126
+ "TV_INPUT",
127
+ `trivium cache: ${new URL(path, page).href} didn't answer: ${message}`,
128
+ { cause: error },
129
+ );
130
+ }
131
+ const text = document || TEXT.test(path);
132
+ const body = text ? await response.text() : "";
133
+ if (!text) await response.arrayBuffer();
134
+ return {
135
+ row: { path, ...judge(path, document, hash.test(path), response) },
136
+ body,
137
+ };
138
+ };
139
+
140
+ const files: FileCheck[] = [];
141
+ const seen = new Set<string>();
142
+ const queue: string[] = [];
143
+ const add = (path: string) => {
144
+ if (!seen.has(path)) {
145
+ seen.add(path);
146
+ queue.push(path);
147
+ }
148
+ };
149
+ // A chunk's `import("./panel-[hash].js")` names no assets path, so
150
+ // relative references resolve against their own file instead.
151
+ const enqueue = (text: string, from: string) => {
152
+ for (const [, path] of text.matchAll(asset)) add(`/${path}`);
153
+ for (const [, path] of text.matchAll(RELATIVE)) {
154
+ const url = new URL(path ?? "", new URL(from, page));
155
+ if (
156
+ url.origin === page.origin &&
157
+ url.pathname.startsWith(input.config.assets.path)
158
+ ) {
159
+ add(url.pathname);
160
+ }
161
+ }
162
+ };
163
+ const html = await check(page.pathname, true);
164
+ files.push(html.row);
165
+ enqueue(html.body, page.pathname);
166
+ while (queue.length > 0) {
167
+ // Fetched together, since each answer may queue more and a crawl
168
+ // one by one would take a round trip per file.
169
+ const batch = queue.splice(0).sort();
170
+ for (const { row, body } of await Promise.all(
171
+ batch.map((p) => check(p, false)),
172
+ )) {
173
+ files.push(row);
174
+ enqueue(body, row.path);
175
+ }
176
+ }
177
+ const failed = files.filter((f) => f.verdict === "fail").length;
178
+ const warned = files.filter((f) => f.verdict === "warn").length;
179
+ const elapsedMs = nowMs() - startMs;
180
+ // The CDN's answers, summed, so they need no column of their own.
181
+ const edges = new Map<string, number>();
182
+ for (const f of files) {
183
+ if (f.edge !== "") edges.set(f.edge, (edges.get(f.edge) ?? 0) + 1);
184
+ }
185
+ const edge =
186
+ edges.size === 0
187
+ ? ""
188
+ : `${SEPARATOR}edge ${[...edges].map(([status, count]) => `${count} ${status}`).join(", ")}`;
189
+ const headerOf = (paint: Paint, human: boolean) =>
190
+ [
191
+ failed + warned === 0
192
+ ? `${paint.good(`${files.length} of ${plural(files.length, "file")}`)} cached as they should be`
193
+ : `${failed} of ${plural(files.length, "file")} failed${SEPARATOR}${warned} warned`,
194
+ paint.dim(`${page.href}${human ? edge : ""}`),
195
+ ].join("\n");
196
+ // Advice only for what failed, so a passing page's HTML isn't blamed.
197
+ const failing = files.filter((f) => f.verdict === "fail" && f.status < 400);
198
+ const fixes: string[] = [];
199
+ if (failing.some((f) => f.path !== page.pathname)) {
200
+ fixes.push(`For hashed assets, send \`Cache-Control: ${IMMUTABLE}\`.`);
201
+ }
202
+ if (failing.some((f) => f.path === page.pathname)) {
203
+ fixes.push(
204
+ "For the HTML, send `Cache-Control: no-cache`, or a max-age under an hour.",
205
+ );
206
+ }
207
+ return {
208
+ exitCode: failed > 0 ? 1 : 0,
209
+ json: {
210
+ schemaVersion: SCHEMA_VERSION,
211
+ ok: failed === 0,
212
+ command: "cache",
213
+ url: page.href,
214
+ config: input.config.file ?? null,
215
+ summary: { files: files.length, failed, warned },
216
+ files,
217
+ elapsedMs,
218
+ },
219
+ text(format, paint) {
220
+ const header = headerOf(paint, format === "human");
221
+ if (format === "agent") {
222
+ const lines = [header];
223
+ for (const f of files) {
224
+ if (f.verdict === "ok") continue;
225
+ lines.push(
226
+ `${f.verdict} ${f.path}: ${f.problems.join("; ")} (cache-control: ${f.cacheControl || "none"})`,
227
+ );
228
+ }
229
+ if (files.length > failed + warned) {
230
+ lines.push(
231
+ `ok: ${files.length - failed - warned} more; --format human lists them`,
232
+ );
233
+ }
234
+ lines.push(...fixes);
235
+ return lines.join("\n");
236
+ }
237
+ const verdictPaint = (verdict: Verdict) =>
238
+ verdict === "fail"
239
+ ? paint.bad
240
+ : verdict === "warn"
241
+ ? paint.warn
242
+ : paint.good;
243
+ // cache-control before the path, so a long path is what gets cut,
244
+ // in the middle; no encoding column, as a missing one is already
245
+ // a warning.
246
+ const lines = fitted(
247
+ [
248
+ headerRow(paint, ["", "cache-control", "path"]),
249
+ ...files.map((f) => [
250
+ verdictPaint(f.verdict)(f.verdict),
251
+ f.cacheControl === "" ? paint.dim("none") : f.cacheControl,
252
+ f.path,
253
+ ]),
254
+ ],
255
+ [],
256
+ truncatePath,
257
+ );
258
+ // A file's problems go under it, so a long reason can't push the
259
+ // row past 80 columns.
260
+ const notes = new Map<number, string[]>();
261
+ for (const [i, f] of files.entries()) {
262
+ if (f.problems.length > 0) {
263
+ notes.set(
264
+ i + 1,
265
+ f.problems.map(
266
+ (p) => `${NOTE_INDENT}${verdictPaint(f.verdict)(`└ ${p}`)}`,
267
+ ),
268
+ );
269
+ }
270
+ }
271
+ return [
272
+ header,
273
+ "",
274
+ ...withNotes(lines, notes),
275
+ ...(fixes.length > 0 ? ["", ...fixes] : []),
276
+ // A check only on a run that passed.
277
+ ...(failed > 0
278
+ ? []
279
+ : [
280
+ "",
281
+ // A warning withholds the pass, though it doesn't fail.
282
+ warned === 0
283
+ ? closingLine(
284
+ paint,
285
+ "Headers pass",
286
+ `checked ${plural(files.length, "file")} in ${elapsed(elapsedMs)}`,
287
+ )
288
+ : closingLine(
289
+ paint,
290
+ `checked ${plural(files.length, "file")} in ${elapsed(elapsedMs)}`,
291
+ `${warned} warned`,
292
+ ),
293
+ ]),
294
+ ].join("\n");
295
+ },
296
+ };
297
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bun
2
+ import { main } from "./main.ts";
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
package/src/compare.ts ADDED
@@ -0,0 +1,378 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+
4
+ import { nowMs } from "./env.ts";
5
+ import { TriviumError } from "./errors.ts";
6
+ import {
7
+ aligned,
8
+ branch,
9
+ byteSize,
10
+ closingLine,
11
+ elapsed,
12
+ headerRow,
13
+ MISSING,
14
+ NOTE_INDENT,
15
+ type Outcome,
16
+ type Paint,
17
+ paintChange,
18
+ plural,
19
+ SCHEMA_VERSION,
20
+ SEPARATOR,
21
+ signed,
22
+ withGutter,
23
+ withNotes,
24
+ } from "./format.ts";
25
+ import type { ResolvedConfig } from "./load-config.ts";
26
+ import {
27
+ contextLine,
28
+ medianRequests,
29
+ requestsLine,
30
+ summarizeMetric,
31
+ throttleLabel,
32
+ valueOf,
33
+ } from "./load.ts";
34
+ import type { Browser, Throttle } from "./page.ts";
35
+ import type { Progress } from "./progress.ts";
36
+ import { type BuildServer, serveBuild } from "./serve.ts";
37
+ import { alternatingOrder, isNoise, median } from "./stats.ts";
38
+ import { type LoadRun, measureLoad, metricsFor } from "./vitals.ts";
39
+
40
+ interface CompareInput {
41
+ targets: readonly [string, string];
42
+ cwd: string;
43
+ config: ResolvedConfig;
44
+ browser: Browser;
45
+ throttle: Throttle;
46
+ runs: number;
47
+ repeat: boolean;
48
+ progress: Progress;
49
+ // Serve B's hashed assets with a year-long immutable cache, so
50
+ // `compare dist dist --repeat --immutable` measures that header.
51
+ immutable: boolean;
52
+ }
53
+
54
+ const HTTP = /^https?:\/\//;
55
+
56
+ // The gains a win names first: the Core Web Vitals, then the timings
57
+ // that lead to them, so a supporting metric's -100% can't crowd out LCP.
58
+ const GAIN_ORDER = [
59
+ "lcp",
60
+ "tbt",
61
+ "cls",
62
+ "fcp",
63
+ "ttfb",
64
+ "ready",
65
+ "element",
66
+ "load",
67
+ "longestTask",
68
+ ];
69
+
70
+ // Rounded as it prints, so a 0.2 ms difference reads 0, never -0 (-3%).
71
+ const shownDelta = (unit: "ms" | "score", delta: number) =>
72
+ unit === "score" ? Number(delta.toFixed(3)) : Math.round(delta);
73
+
74
+ // `+12 ms (+4%)`; a difference that rounds to 0 has no percent, since
75
+ // 0 ms (+3%) would contradict itself.
76
+ function changeOf(m: {
77
+ unit: "ms" | "score";
78
+ delta: number | null;
79
+ deltaPercent: number | null;
80
+ }): string {
81
+ const delta = shownDelta(m.unit, m.delta ?? 0);
82
+ const pct =
83
+ m.deltaPercent === null || delta === 0
84
+ ? ""
85
+ : ` (${signed(Math.round(m.deltaPercent), String)}%)`;
86
+ return `${signed(delta, (n) => valueOf(m.unit, n))}${pct}`;
87
+ }
88
+
89
+ interface Side {
90
+ name: "A" | "B";
91
+ target: string;
92
+ url: string;
93
+ server?: BuildServer;
94
+ }
95
+
96
+ function openSide(
97
+ name: Side["name"],
98
+ target: string,
99
+ input: CompareInput,
100
+ ): Side {
101
+ if (HTTP.test(target)) return { name, target, url: target };
102
+ const dir = resolve(input.cwd, target);
103
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
104
+ throw new TriviumError(
105
+ "TV_INPUT",
106
+ `trivium compare: ${JSON.stringify(target)} is neither a URL nor a directory: pass a build directory or an http(s) URL`,
107
+ );
108
+ }
109
+ const immutable = name === "B" && input.immutable;
110
+ const server = serveBuild(dir, {
111
+ immutable,
112
+ assetsPath: input.config.assets.path,
113
+ });
114
+ return {
115
+ name,
116
+ target: immutable
117
+ ? `${target} (${input.config.assets.path}* immutable)`
118
+ : target,
119
+ url: server.url,
120
+ server,
121
+ };
122
+ }
123
+
124
+ export async function runCompare(input: CompareInput): Promise<Outcome> {
125
+ const startMs = nowMs();
126
+ const sides: Side[] = [];
127
+ try {
128
+ sides.push(openSide("A", input.targets[0], input));
129
+ sides.push(openSide("B", input.targets[1], input));
130
+ const options = {
131
+ browser: input.browser,
132
+ throttle: input.throttle,
133
+ repeat: input.repeat,
134
+ };
135
+ // One unrecorded load of each side first, so neither pays for a
136
+ // cold browser.
137
+ const total = 2 * input.runs + 2;
138
+ let done = 0;
139
+ for (const side of sides) {
140
+ input.progress.step(
141
+ `warming up ${side.name}${done === 0 ? ", starting the browser" : ""}`,
142
+ done++ / total,
143
+ );
144
+ await measureLoad(side.url, input.config, options);
145
+ }
146
+ const runs: [LoadRun[], LoadRun[]] = [[], []];
147
+ for (const s of alternatingOrder(input.runs)) {
148
+ const side = sides[s];
149
+ if (!side) continue;
150
+ input.progress.step(
151
+ `load ${done - 1} of ${total - 2}${SEPARATOR}${side.name}`,
152
+ done++ / total,
153
+ );
154
+ runs[s].push(await measureLoad(side.url, input.config, options));
155
+ }
156
+ return report(input, sides, runs, nowMs() - startMs);
157
+ } finally {
158
+ for (const side of sides) side.server?.stop();
159
+ }
160
+ }
161
+
162
+ function report(
163
+ input: CompareInput,
164
+ sides: readonly Side[],
165
+ [a, b]: readonly [LoadRun[], LoadRun[]],
166
+ elapsedMs: number,
167
+ ): Outcome {
168
+ const metrics = metricsFor(input.config).map((metric) => {
169
+ const values = (runs: readonly LoadRun[]) =>
170
+ runs.flatMap((r) => r.vitals[metric.key] ?? []);
171
+ const sa = summarizeMetric(metric, values(a), input.browser);
172
+ const sb = summarizeMetric(metric, values(b), input.browser);
173
+ if (sa.median === null || sb.median === null) {
174
+ return {
175
+ key: metric.key,
176
+ label: metric.label,
177
+ unit: metric.unit,
178
+ a: sa.median,
179
+ b: sb.median,
180
+ delta: null,
181
+ deltaPercent: null,
182
+ noise: null,
183
+ withinNoise: null,
184
+ reason: sa.reason ?? sb.reason ?? "the page reported none",
185
+ };
186
+ }
187
+ const delta = sb.median - sa.median;
188
+ const noise = Math.max(sa.noise ?? 0, sb.noise ?? 0);
189
+ return {
190
+ key: metric.key,
191
+ label: metric.label,
192
+ unit: metric.unit,
193
+ a: sa.median,
194
+ b: sb.median,
195
+ delta,
196
+ deltaPercent: sa.median === 0 ? null : (delta / sa.median) * 100,
197
+ noise,
198
+ withinNoise: isNoise(
199
+ delta,
200
+ noise,
201
+ sa.median,
202
+ metric.unit === "score" ? 0.001 : 1,
203
+ ),
204
+ };
205
+ });
206
+ const total = (runs: readonly LoadRun[]) =>
207
+ median(
208
+ runs.map((r) => Object.values(r.bytesByType).reduce((x, y) => x + y, 0)),
209
+ );
210
+ const transferredBytes = { a: total(a), b: total(b) };
211
+ const requests = { a: medianRequests(a), b: medianRequests(b) };
212
+ const changed = metrics.filter((m) => m.withinNoise === false).length;
213
+ const better = metrics.filter(
214
+ (m) => m.withinNoise === false && (m.delta ?? 0) < 0,
215
+ );
216
+ const worse = changed - better.length;
217
+ const compared = metrics.filter((m) => m.withinNoise !== null).length;
218
+ const visits = input.repeat ? "repeat visits" : "cold loads";
219
+ // Line 1 leads with the verdict in words, since a count of changed
220
+ // metrics doesn't say whether B is better.
221
+ const verdictOf = (paint: Paint) =>
222
+ changed === 0
223
+ ? `No change beyond the noise on ${plural(compared, "metric")}`
224
+ : worse === 0
225
+ ? `${paint.good("B is better")} on ${better.length} of ${plural(compared, "metric")}, worse on none`
226
+ : better.length === 0
227
+ ? `${paint.bad("B is worse")} on ${worse} of ${plural(compared, "metric")}`
228
+ : `B is ${paint.good("better")} on ${better.length} and ${paint.bad("worse")} on ${worse} of ${plural(compared, "metric")}`;
229
+ const headerOf = (paint: Paint) =>
230
+ [
231
+ verdictOf(paint),
232
+ paint.dim(
233
+ contextLine([
234
+ input.browser,
235
+ throttleLabel(input.throttle),
236
+ `median of ${input.runs} alternating ${visits} each`,
237
+ ]),
238
+ ),
239
+ ].join("\n");
240
+ return {
241
+ exitCode: 0,
242
+ json: {
243
+ schemaVersion: SCHEMA_VERSION,
244
+ ok: true,
245
+ command: "compare",
246
+ a: { target: sides[0]?.target ?? "", url: sides[0]?.url ?? "" },
247
+ b: { target: sides[1]?.target ?? "", url: sides[1]?.url ?? "" },
248
+ browser: input.browser,
249
+ throttle: input.throttle,
250
+ visit: input.repeat ? "repeat" : "cold",
251
+ runs: input.runs,
252
+ config: input.config.file ?? null,
253
+ summary: { compared, changed, better: better.length, worse },
254
+ metrics,
255
+ transferredBytes,
256
+ requests,
257
+ elapsedMs,
258
+ },
259
+ text(format, paint) {
260
+ const header = headerOf(paint);
261
+ const lines = [
262
+ header,
263
+ `A ${sides[0]?.target ?? ""}`,
264
+ `B ${sides[1]?.target ?? ""}`,
265
+ ];
266
+ if (format === "agent") {
267
+ for (const m of metrics) {
268
+ if (m.delta === null || m.a === null || m.b === null) {
269
+ lines.push(`${m.label} ${MISSING}: ${m.reason ?? ""}`);
270
+ continue;
271
+ }
272
+ const show = (n: number) => valueOf(m.unit, n);
273
+ lines.push(
274
+ `${m.label} ${show(m.a)} → ${show(m.b)}, ${changeOf(m)} ±${show(m.noise ?? 0)}${m.withinNoise ? ", within the noise" : ""}`,
275
+ );
276
+ }
277
+ lines.push(
278
+ `Transferred ${byteSize(transferredBytes.a)} → ${byteSize(transferredBytes.b)}`,
279
+ `Requests A ${requestsLine(requests.a)}`,
280
+ `Requests B ${requestsLine(requests.b)}`,
281
+ );
282
+ return lines.join("\n");
283
+ }
284
+ const rows: string[][] = [
285
+ headerRow(paint, ["", "A", "B", "B - A", "noise", ""]),
286
+ ];
287
+ // A reason goes under its row, so it can't widen the table.
288
+ const notes = new Map<number, string[]>();
289
+ // Only a metric that got worse is marked, since it's the one to fix.
290
+ const marks = new Map<number, (text: string) => string>();
291
+ for (const m of metrics) {
292
+ if (m.withinNoise === false && (m.delta ?? 0) > 0) {
293
+ marks.set(rows.length, paint.bad);
294
+ }
295
+ if (m.delta === null || m.a === null || m.b === null) {
296
+ notes.set(rows.length, [
297
+ `${NOTE_INDENT}${paint.dim(`└ ${m.reason ?? ""}`)}`,
298
+ ]);
299
+ rows.push([
300
+ m.label,
301
+ paint.dim(MISSING),
302
+ paint.dim(MISSING),
303
+ "",
304
+ "",
305
+ "",
306
+ ]);
307
+ continue;
308
+ }
309
+ const show = (n: number) => valueOf(m.unit, n);
310
+ rows.push([
311
+ m.label,
312
+ show(m.a),
313
+ show(m.b),
314
+ m.withinNoise
315
+ ? paint.dim(`~${changeOf(m)}`)
316
+ : paintChange(paint, m.delta)(changeOf(m)),
317
+ paint.dim(`±${show(m.noise ?? 0)}`),
318
+ "",
319
+ ]);
320
+ }
321
+ rows.push(
322
+ [
323
+ "Transferred",
324
+ byteSize(transferredBytes.a),
325
+ byteSize(transferredBytes.b),
326
+ "",
327
+ "",
328
+ "",
329
+ ],
330
+ ["Requests", "", "", "", "", ""],
331
+ ...(
332
+ [
333
+ ["downloaded", "network"],
334
+ ["revalidated", "revalidated"],
335
+ ["from cache", "cache"],
336
+ ] as const
337
+ ).map(([label, key], i, all) => [
338
+ paint.dim(`${branch(i, all.length)}${label}`),
339
+ paint.dim(String(requests.a[key])),
340
+ paint.dim(String(requests.b[key])),
341
+ "",
342
+ "",
343
+ "",
344
+ ]),
345
+ );
346
+ lines.push(
347
+ "",
348
+ ...withNotes(withGutter(aligned(rows, [1, 2, 3, 4]), marks), notes),
349
+ "",
350
+ paint.dim(
351
+ "~ within twice the run-to-run noise (median absolute deviation),",
352
+ ),
353
+ paint.dim(" under 2%, or too small to show"),
354
+ "",
355
+ // A clean win names its two biggest gains.
356
+ worse === 0 && better.length > 0
357
+ ? closingLine(
358
+ paint,
359
+ `B improves: ${[...better]
360
+ .sort(
361
+ (x, y) =>
362
+ GAIN_ORDER.indexOf(x.key) - GAIN_ORDER.indexOf(y.key),
363
+ )
364
+ .slice(0, 2)
365
+ .map((m) => `${m.label} ${changeOf(m)}`)
366
+ .join(SEPARATOR)}`,
367
+ `measured in ${elapsed(elapsedMs)}`,
368
+ )
369
+ : closingLine(
370
+ paint,
371
+ `measured in ${elapsed(elapsedMs)}`,
372
+ `${2 * input.runs + 2} loads, A and B alternating`,
373
+ ),
374
+ );
375
+ return lines.join("\n");
376
+ },
377
+ };
378
+ }