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/load.ts ADDED
@@ -0,0 +1,300 @@
1
+ import { nowMs } from "./env.ts";
2
+ import {
3
+ aligned,
4
+ branch,
5
+ byteSize,
6
+ closingLine,
7
+ elapsed,
8
+ MISSING,
9
+ ms,
10
+ NOTE_INDENT,
11
+ type Outcome,
12
+ type Paint,
13
+ paintRating,
14
+ plural,
15
+ ratingLabel,
16
+ SCHEMA_VERSION,
17
+ SEPARATOR,
18
+ withGutter,
19
+ withNotes,
20
+ } from "./format.ts";
21
+ import type { ResolvedConfig } from "./load-config.ts";
22
+ import type { Browser, Throttle } from "./page.ts";
23
+ import type { Progress } from "./progress.ts";
24
+ import { median, medianAbsoluteDeviation } from "./stats.ts";
25
+ import {
26
+ type LoadRun,
27
+ measureLoad,
28
+ type Metric,
29
+ metricsFor,
30
+ type Rating,
31
+ ratingOf,
32
+ type Requests,
33
+ unavailableReason,
34
+ } from "./vitals.ts";
35
+
36
+ interface LoadInput {
37
+ url: string;
38
+ config: ResolvedConfig;
39
+ browser: Browser;
40
+ throttle: Throttle;
41
+ runs: number;
42
+ repeat: boolean;
43
+ progress: Progress;
44
+ }
45
+
46
+ interface MetricSummary {
47
+ key: string;
48
+ label: string;
49
+ unit: Metric["unit"];
50
+ median: number | null;
51
+ noise: number | null;
52
+ samples: number;
53
+ rating?: Rating;
54
+ // Why there's no value: the browser can't measure it, or the page
55
+ // never reported it.
56
+ reason?: string;
57
+ }
58
+
59
+ export function summarizeMetric(
60
+ metric: Metric,
61
+ values: readonly number[],
62
+ browser: Browser,
63
+ ): MetricSummary {
64
+ const reason =
65
+ unavailableReason(browser, metric.key) ??
66
+ (values.length === 0 ? "the page reported none" : undefined);
67
+ const rating = values.length
68
+ ? ratingOf(metric.key, median(values))
69
+ : undefined;
70
+ return {
71
+ key: metric.key,
72
+ label: metric.label,
73
+ unit: metric.unit,
74
+ median: values.length ? median(values) : null,
75
+ noise: values.length ? medianAbsoluteDeviation(values) : null,
76
+ samples: values.length,
77
+ ...(rating !== undefined && { rating }),
78
+ ...(reason !== undefined && { reason }),
79
+ };
80
+ }
81
+
82
+ // LCP, CLS and TBT lead the output, since the verdict comes before the
83
+ // detail (cli.md); TBT stands in for INP, which a load can't measure.
84
+ function verdictOf(
85
+ metrics: readonly MetricSummary[],
86
+ paint: Paint,
87
+ human: boolean,
88
+ ): string {
89
+ return ["lcp", "cls", "tbt"]
90
+ .flatMap((key) => metrics.filter((m) => m.key === key))
91
+ .map((m) =>
92
+ m.median === null
93
+ ? `${m.label} ${paint.dim(MISSING)}`
94
+ : `${m.label} ${valueOf(m.unit, m.median)} ${paintRating(paint, m.rating)(human ? ratingLabel(m.rating) : (m.rating ?? ""))}`.trimEnd(),
95
+ )
96
+ .join(SEPARATOR);
97
+ }
98
+
99
+ // Where, in what and how many go on their own line, so the verdict
100
+ // above it stays within 80 columns.
101
+ export function contextLine(parts: readonly string[]): string {
102
+ return parts.filter(Boolean).join(SEPARATOR);
103
+ }
104
+
105
+ // The bytes by type, without the empty ones: a favicon's 404 is noise.
106
+ function transferredDetail(bytesByType: Record<string, number>): string {
107
+ return (
108
+ Object.entries(bytesByType)
109
+ .filter(([, bytes]) => bytes > 0)
110
+ .map(([type, bytes]) => `${type} ${byteSize(bytes)}`)
111
+ .join(", ") || "nothing"
112
+ );
113
+ }
114
+
115
+ export const valueOf = (unit: Metric["unit"], value: number): string =>
116
+ unit === "score" ? value.toFixed(3) : ms(value);
117
+
118
+ export const requestsLine = (r: Requests): string =>
119
+ `${r.network} downloaded, ${r.revalidated} revalidated (304), ${r.cache} from cache`;
120
+
121
+ export const medianRequests = (runs: readonly LoadRun[]): Requests => ({
122
+ network: median(runs.map((r) => r.requests.network)),
123
+ revalidated: median(runs.map((r) => r.requests.revalidated)),
124
+ cache: median(runs.map((r) => r.requests.cache)),
125
+ });
126
+
127
+ function medianBytesByType(runs: readonly LoadRun[]): Record<string, number> {
128
+ const types = [
129
+ ...new Set(runs.flatMap((r) => Object.keys(r.bytesByType))),
130
+ ].sort();
131
+ return Object.fromEntries(
132
+ types.map((type) => [
133
+ type,
134
+ median(runs.map((r) => r.bytesByType[type] ?? 0)),
135
+ ]),
136
+ );
137
+ }
138
+
139
+ // LCP and CLS are the Core Web Vitals a load measures; TBT stands in
140
+ // for INP, which needs interactions.
141
+ function allVitalsGood(metrics: readonly MetricSummary[]): boolean {
142
+ return ["lcp", "cls", "tbt"].every((key) =>
143
+ metrics.some((m) => m.key === key && m.rating === "good"),
144
+ );
145
+ }
146
+
147
+ export const throttleLabel = (throttle: Throttle): string =>
148
+ throttle === "none" ? "no throttling" : `${throttle} throttling`;
149
+
150
+ export async function runLoad(input: LoadInput): Promise<Outcome> {
151
+ const startMs = nowMs();
152
+ const runs: LoadRun[] = [];
153
+ for (let i = 0; i < input.runs; i++) {
154
+ const lcps = runs.flatMap((r) => r.vitals.lcp ?? []);
155
+ input.progress.step(
156
+ i === 0
157
+ ? `load 1 of ${input.runs}, starting the browser`
158
+ : `load ${i + 1} of ${input.runs}${lcps.length > 0 ? `${SEPARATOR}LCP so far ${ms(median(lcps))}` : ""}`,
159
+ i / input.runs,
160
+ );
161
+ runs.push(
162
+ await measureLoad(input.url, input.config, {
163
+ browser: input.browser,
164
+ throttle: input.throttle,
165
+ repeat: input.repeat,
166
+ }),
167
+ );
168
+ }
169
+ const metrics = metricsFor(input.config).map((metric) =>
170
+ summarizeMetric(
171
+ metric,
172
+ runs.flatMap((r) => r.vitals[metric.key] ?? []),
173
+ input.browser,
174
+ ),
175
+ );
176
+ const bytesByType = medianBytesByType(runs);
177
+ const transferredBytes = Object.values(bytesByType).reduce(
178
+ (a, b) => a + b,
179
+ 0,
180
+ );
181
+ const requests = medianRequests(runs);
182
+ const visit = input.repeat ? "repeat visit" : "cold load";
183
+ const elapsedMs = nowMs() - startMs;
184
+ const headerOf = (paint: Paint, human: boolean) =>
185
+ [
186
+ verdictOf(metrics, paint, human),
187
+ paint.dim(
188
+ contextLine([
189
+ input.url,
190
+ input.browser,
191
+ throttleLabel(input.throttle),
192
+ `median of ${plural(input.runs, visit)}`,
193
+ ]),
194
+ ),
195
+ ].join("\n");
196
+ const transferred = transferredDetail(bytesByType);
197
+ return {
198
+ exitCode: 0,
199
+ json: {
200
+ schemaVersion: SCHEMA_VERSION,
201
+ ok: true,
202
+ command: "load",
203
+ url: input.url,
204
+ browser: input.browser,
205
+ throttle: input.throttle,
206
+ visit: input.repeat ? "repeat" : "cold",
207
+ runs: input.runs,
208
+ config: input.config.file ?? null,
209
+ metrics,
210
+ bytesByType,
211
+ transferredBytes,
212
+ requests,
213
+ elapsedMs,
214
+ },
215
+ text(format, paint) {
216
+ const header = headerOf(paint, format === "human");
217
+ if (format === "agent") {
218
+ return [
219
+ header,
220
+ ...metrics.map((m) =>
221
+ m.median === null
222
+ ? `${m.label} ${MISSING}: ${m.reason ?? ""}`
223
+ : `${m.label} ${valueOf(m.unit, m.median)}${m.samples < 2 ? "" : ` ±${valueOf(m.unit, m.noise ?? 0)}`}${m.rating ? ` ${m.rating}` : ""}`,
224
+ ),
225
+ `Transferred ${byteSize(transferredBytes)} (${transferred})`,
226
+ `Requests ${requestsLine(requests)}`,
227
+ ].join("\n");
228
+ }
229
+ // A reason goes under its row, so a long one can't push the table
230
+ // past 80 columns.
231
+ const notes = new Map<number, string[]>();
232
+ const marks = new Map<number, (text: string) => string>();
233
+ const rows = metrics.map((m, i) => {
234
+ if (m.rating !== undefined && m.rating !== "good") {
235
+ marks.set(i, paintRating(paint, m.rating));
236
+ }
237
+ if (m.median === null) {
238
+ notes.set(i, [`${NOTE_INDENT}${paint.dim(`└ ${m.reason ?? ""}`)}`]);
239
+ return [m.label, paint.dim(MISSING), "", ""];
240
+ }
241
+ return [
242
+ m.label,
243
+ valueOf(m.unit, m.median),
244
+ // Noise needs two runs.
245
+ m.samples < 2 ? "" : paint.dim(`±${valueOf(m.unit, m.noise ?? 0)}`),
246
+ paintRating(paint, m.rating)(ratingLabel(m.rating)),
247
+ ];
248
+ });
249
+ // One row per type, so each size lines up under the total.
250
+ const types = Object.entries(bytesByType).filter(([, size]) => size > 0);
251
+ rows.push(["Transferred", byteSize(transferredBytes), "", ""]);
252
+ for (const [i, [type, size]] of types.entries()) {
253
+ rows.push([
254
+ paint.dim(`${branch(i, types.length)}${type}`),
255
+ paint.dim(byteSize(size)),
256
+ "",
257
+ "",
258
+ ]);
259
+ }
260
+ const answered = [
261
+ ["downloaded", requests.network],
262
+ ["revalidated", requests.revalidated],
263
+ ["from cache", requests.cache],
264
+ ] as const;
265
+ rows.push([
266
+ "Requests",
267
+ String(requests.network + requests.revalidated + requests.cache),
268
+ "",
269
+ "",
270
+ ]);
271
+ for (const [i, [label, count]] of answered.entries()) {
272
+ rows.push([
273
+ paint.dim(`${branch(i, answered.length)}${label}`),
274
+ paint.dim(String(count)),
275
+ "",
276
+ "",
277
+ ]);
278
+ }
279
+ return [
280
+ header,
281
+ "",
282
+ ...withNotes(withGutter(aligned(rows, [1, 2]), marks), notes),
283
+ "",
284
+ // Success said in words, when every Core Web Vital was measured
285
+ // and each is good.
286
+ allVitalsGood(metrics)
287
+ ? closingLine(
288
+ paint,
289
+ "Vitals pass",
290
+ `measured in ${elapsed(elapsedMs)}${SEPARATOR}${plural(input.runs, input.repeat ? "repeat visit" : "load")}`,
291
+ )
292
+ : closingLine(
293
+ paint,
294
+ `measured in ${elapsed(elapsedMs)}`,
295
+ plural(input.runs, input.repeat ? "repeat visit" : "load"),
296
+ ),
297
+ ].join("\n");
298
+ },
299
+ };
300
+ }
package/src/main.ts ADDED
@@ -0,0 +1,241 @@
1
+ import { version } from "../package.json";
2
+ import { agentVariable, defaultFormat } from "./agent.ts";
3
+ import { type Args, commandIn, formatIn, parseArgs } from "./args.ts";
4
+ import { runBundle } from "./bundle.ts";
5
+ import { runCache } from "./cache.ts";
6
+ import { runCompare } from "./compare.ts";
7
+ import { nowMs, processEnv, workingDirectory } from "./env.ts";
8
+ import { toTriviumError, TriviumError } from "./errors.ts";
9
+ import {
10
+ createPaint,
11
+ type Format,
12
+ FORMATS,
13
+ type Outcome,
14
+ type Paint,
15
+ PLAIN,
16
+ SCHEMA_VERSION,
17
+ } from "./format.ts";
18
+ import { helpText } from "./help.ts";
19
+ import { runInteractions } from "./interactions.ts";
20
+ import { loadConfig, type ResolvedConfig } from "./load-config.ts";
21
+ import { runLoad } from "./load.ts";
22
+ import type { Throttle } from "./page.ts";
23
+ import { createProgress, type Progress, SILENT } from "./progress.ts";
24
+
25
+ interface Io {
26
+ stdout(text: string): void;
27
+ stderr(text: string): void;
28
+ // Whether stdout and stderr are terminals, the default for color.
29
+ isTerminal?: boolean;
30
+ stderrIsTerminal?: boolean;
31
+ // Writes to stderr without a newline, for the progress line.
32
+ progressWrite?: (text: string) => void;
33
+ }
34
+
35
+ const DEFAULT_RUNS = { load: 5, compare: 7, interactions: 3 } as const;
36
+
37
+ function urlOf(args: Args, config: ResolvedConfig): string {
38
+ const url = args.positionals[0] ?? config.url;
39
+ if (url === undefined) {
40
+ throw new TriviumError(
41
+ "TV_USAGE",
42
+ `trivium ${args.command ?? ""}: no URL: pass one, or set url in ${config.file ?? "trivium.config.ts"}`,
43
+ );
44
+ }
45
+ return url;
46
+ }
47
+
48
+ // Throttling needs CDP, which only Chrome has: on WebKit the default is
49
+ // none, and asking for a preset is an error, before any work.
50
+ const throttleOf = (args: Args): Throttle =>
51
+ args.throttle ?? (args.browser === "chrome" ? "mobile" : "none");
52
+
53
+ async function run(
54
+ args: Args,
55
+ cwd: string,
56
+ progress: Progress,
57
+ ): Promise<Outcome> {
58
+ const config = await loadConfig(args.config, cwd);
59
+ const browser = args.browser;
60
+ const throttle = throttleOf(args);
61
+ if (browser === "webkit" && throttle !== "none") {
62
+ throw new TriviumError(
63
+ "TV_UNSUPPORTED",
64
+ `trivium ${args.command ?? ""}: --throttle ${throttle} needs Chrome: WebKit has no CDP to throttle with; pass --browser chrome, or --throttle none`,
65
+ );
66
+ }
67
+ switch (args.command) {
68
+ case "load":
69
+ return runLoad({
70
+ url: urlOf(args, config),
71
+ config,
72
+ browser,
73
+ throttle,
74
+ runs: args.runs ?? DEFAULT_RUNS.load,
75
+ repeat: args.repeat,
76
+ progress,
77
+ });
78
+ case "compare":
79
+ return runCompare({
80
+ targets: [args.positionals[0] ?? "", args.positionals[1] ?? ""],
81
+ cwd,
82
+ config,
83
+ browser,
84
+ throttle,
85
+ runs: args.runs ?? DEFAULT_RUNS.compare,
86
+ repeat: args.repeat,
87
+ immutable: args.immutable,
88
+ progress,
89
+ });
90
+ case "interactions":
91
+ return runInteractions({
92
+ url: urlOf(args, config),
93
+ config,
94
+ browser,
95
+ throttle,
96
+ runs: args.runs ?? DEFAULT_RUNS.interactions,
97
+ early: args.early,
98
+ progress,
99
+ });
100
+ case "bundle":
101
+ return runBundle({
102
+ dir: args.positionals[0] ?? "dist",
103
+ base: args.base,
104
+ all: args.all,
105
+ cwd,
106
+ config,
107
+ });
108
+ case "cache":
109
+ return runCache({ url: urlOf(args, config), config });
110
+ case undefined:
111
+ throw new TriviumError(
112
+ "TV_USAGE",
113
+ "trivium: name a command; see trivium --help",
114
+ );
115
+ }
116
+ }
117
+
118
+ // Color on a terminal unless NO_COLOR (no-color.org) or a coding agent
119
+ // says otherwise; --color and --no-color win over both.
120
+ function wantsColor(
121
+ forced: boolean | undefined,
122
+ terminal: boolean | undefined,
123
+ env: Readonly<Record<string, string | undefined>>,
124
+ ): boolean {
125
+ return (
126
+ forced ??
127
+ (terminal === true &&
128
+ (env.NO_COLOR ?? "") === "" &&
129
+ agentVariable(env) === undefined)
130
+ );
131
+ }
132
+
133
+ // The forced color from argv even when the rest doesn't parse, so a usage
134
+ // error honors --no-color.
135
+ const forcedIn = (argv: readonly string[]): boolean | undefined =>
136
+ argv.includes("--no-color")
137
+ ? false
138
+ : argv.includes("--color")
139
+ ? true
140
+ : undefined;
141
+
142
+ // The prefix that names the command in red, and the pointer to --help in
143
+ // gray, so the problem stands out from the advice.
144
+ const ERROR_PREFIX = /^(trivium[^:]*:)/;
145
+ const ERROR_POINTER = /(; see trivium[^;]*--help)$/;
146
+ const paintError = (message: string, paint: Paint) =>
147
+ message
148
+ .replace(ERROR_PREFIX, (prefix) => paint.bad(prefix))
149
+ .replace(ERROR_POINTER, (pointer) => paint.dim(pointer));
150
+
151
+ function printError(
152
+ error: TriviumError,
153
+ format: Format | undefined,
154
+ io: Io,
155
+ paint: Paint,
156
+ ): void {
157
+ if (format === "json") {
158
+ io.stdout(
159
+ JSON.stringify({
160
+ schemaVersion: SCHEMA_VERSION,
161
+ ok: false,
162
+ error: { kind: error.kind, code: error.code, message: error.message },
163
+ }),
164
+ );
165
+ } else
166
+ io.stderr(
167
+ format === "agent" ? error.message : paintError(error.message, paint),
168
+ );
169
+ }
170
+
171
+ // Takes the arguments after the binary; `io`, `env` and `cwd` are
172
+ // parameters so a test runs it in-process.
173
+ export async function main(
174
+ argv: readonly string[],
175
+ io: Io = {
176
+ stdout: (text) => process.stdout.write(`${text}\n`),
177
+ stderr: (text) => process.stderr.write(`${text}\n`),
178
+ isTerminal: process.stdout.isTTY === true,
179
+ stderrIsTerminal: process.stderr.isTTY === true,
180
+ progressWrite: (text) => void process.stderr.write(text),
181
+ },
182
+ env: Readonly<Record<string, string | undefined>> = processEnv(),
183
+ cwd: string = workingDirectory(),
184
+ ): Promise<0 | 1 | 2> {
185
+ const errorPaint = wantsColor(forcedIn(argv), io.stderrIsTerminal, env)
186
+ ? createPaint()
187
+ : PLAIN;
188
+ let args: Args;
189
+ try {
190
+ args = parseArgs(argv);
191
+ } catch (error) {
192
+ printError(toTriviumError(error), formatIn(argv), io, errorPaint);
193
+ return 2;
194
+ }
195
+ const outPaint = wantsColor(args.color, io.isTerminal, env)
196
+ ? createPaint()
197
+ : PLAIN;
198
+ if (args.help) {
199
+ io.stdout(helpText(commandIn(argv), outPaint));
200
+ return 0;
201
+ }
202
+ if (args.version) {
203
+ io.stdout(version);
204
+ return 0;
205
+ }
206
+ let format = args.format;
207
+ if (format === undefined) {
208
+ const chosen = defaultFormat(env, FORMATS);
209
+ if ("error" in chosen) {
210
+ io.stderr(chosen.error);
211
+ return 2;
212
+ }
213
+ format = chosen.format;
214
+ if (chosen.notice !== undefined) io.stderr(chosen.notice);
215
+ }
216
+ // The progress line goes where a person watches: stderr on a
217
+ // terminal, never for a coding agent or a format a program reads.
218
+ const progress =
219
+ io.progressWrite !== undefined &&
220
+ io.stderrIsTerminal === true &&
221
+ format === "human" &&
222
+ agentVariable(env) === undefined
223
+ ? createProgress(io.progressWrite, errorPaint, nowMs)
224
+ : SILENT;
225
+ try {
226
+ const outcome = await run(args, cwd, progress).finally(() =>
227
+ progress.clear(),
228
+ );
229
+ // Color is for the human format only: the agent format and JSON are
230
+ // read by programs.
231
+ io.stdout(
232
+ format === "json"
233
+ ? JSON.stringify(outcome.json)
234
+ : outcome.text(format, format === "human" ? outPaint : PLAIN),
235
+ );
236
+ return outcome.exitCode;
237
+ } catch (error) {
238
+ printError(toTriviumError(error), format, io, errorPaint);
239
+ return 2;
240
+ }
241
+ }