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/README.md +156 -2
- package/docs/agents.md +71 -0
- package/docs/config.md +81 -0
- package/docs/glossary.md +105 -0
- package/docs/measuring.md +46 -0
- package/docs/name.md +62 -0
- package/index.d.ts +44 -0
- package/package.json +34 -3
- package/src/agent.ts +45 -0
- package/src/args.ts +297 -0
- package/src/bundle.ts +319 -0
- package/src/cache.ts +297 -0
- package/src/cli.ts +4 -0
- package/src/compare.ts +378 -0
- package/src/config.ts +49 -0
- package/src/env.ts +16 -0
- package/src/errors.ts +46 -0
- package/src/format.ts +314 -0
- package/src/help.ts +172 -0
- package/src/index.ts +2 -0
- package/src/interactions.ts +398 -0
- package/src/load-config.ts +208 -0
- package/src/load.ts +300 -0
- package/src/main.ts +241 -0
- package/src/page.ts +263 -0
- package/src/progress.ts +48 -0
- package/src/serve.ts +58 -0
- package/src/stats.ts +37 -0
- package/src/suggest.ts +44 -0
- package/src/vitals.ts +304 -0
- package/index.ts +0 -1
package/src/vitals.ts
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import type { ResolvedConfig } from "./load-config.ts";
|
|
2
|
+
import { type Browser, openPage, type Throttle, waitFor } from "./page.ts";
|
|
3
|
+
|
|
4
|
+
type MetricKey =
|
|
5
|
+
| "ttfb"
|
|
6
|
+
| "fcp"
|
|
7
|
+
| "lcp"
|
|
8
|
+
| "cls"
|
|
9
|
+
| "tbt"
|
|
10
|
+
| "longestTask"
|
|
11
|
+
| "ready"
|
|
12
|
+
| "element"
|
|
13
|
+
| "load";
|
|
14
|
+
|
|
15
|
+
export interface Metric {
|
|
16
|
+
key: MetricKey;
|
|
17
|
+
label: string;
|
|
18
|
+
// CLS is a score; the rest are milliseconds.
|
|
19
|
+
unit: "ms" | "score";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type Vitals = Partial<Record<MetricKey, number>>;
|
|
23
|
+
|
|
24
|
+
export interface Requests {
|
|
25
|
+
network: number;
|
|
26
|
+
revalidated: number;
|
|
27
|
+
cache: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface LoadRun {
|
|
31
|
+
vitals: Vitals;
|
|
32
|
+
bytesByType: Record<string, number>;
|
|
33
|
+
requests: Requests;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Entry types WebKit doesn't report, so neither are the metrics built on
|
|
37
|
+
// them: checked on macOS's WebKit, whose supportedEntryTypes lack both.
|
|
38
|
+
const WEBKIT_LACKS = new Map<MetricKey, string>([
|
|
39
|
+
["cls", "WebKit reports no layout-shift entries"],
|
|
40
|
+
["tbt", "WebKit reports no longtask entries"],
|
|
41
|
+
["longestTask", "WebKit reports no longtask entries"],
|
|
42
|
+
["element", "WebKit can't run a script before the page's own"],
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
const capitalize = (text: string) =>
|
|
46
|
+
(text[0]?.toUpperCase() ?? "") + text.slice(1);
|
|
47
|
+
|
|
48
|
+
export function metricsFor(config: ResolvedConfig): Metric[] {
|
|
49
|
+
const metrics: Metric[] = [
|
|
50
|
+
{ key: "ttfb", label: "TTFB", unit: "ms" },
|
|
51
|
+
{ key: "fcp", label: "FCP", unit: "ms" },
|
|
52
|
+
{ key: "lcp", label: "LCP", unit: "ms" },
|
|
53
|
+
{ key: "cls", label: "CLS", unit: "score" },
|
|
54
|
+
{ key: "tbt", label: "TBT", unit: "ms" },
|
|
55
|
+
{ key: "longestTask", label: "Longest task", unit: "ms" },
|
|
56
|
+
{
|
|
57
|
+
key: "ready",
|
|
58
|
+
label:
|
|
59
|
+
config.readyMark === undefined
|
|
60
|
+
? "Ready (load)"
|
|
61
|
+
: capitalize(config.readyMark),
|
|
62
|
+
unit: "ms",
|
|
63
|
+
},
|
|
64
|
+
{ key: "load", label: "Load", unit: "ms" },
|
|
65
|
+
];
|
|
66
|
+
if (config.element) {
|
|
67
|
+
metrics.push({
|
|
68
|
+
key: "element",
|
|
69
|
+
label: capitalize(config.element.label),
|
|
70
|
+
unit: "ms",
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return metrics;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type Rating = "good" | "needs-improvement" | "poor";
|
|
77
|
+
|
|
78
|
+
// spec: web.dev's thresholds for TTFB, FCP, LCP, CLS and INP, and
|
|
79
|
+
// Lighthouse's mobile scoring for TBT, which has no field threshold:
|
|
80
|
+
// good up to the first, poor past the second.
|
|
81
|
+
const THRESHOLDS = new Map<MetricKey | "inp", readonly [number, number]>([
|
|
82
|
+
["ttfb", [800, 1800]],
|
|
83
|
+
["fcp", [1800, 3000]],
|
|
84
|
+
["lcp", [2500, 4000]],
|
|
85
|
+
["cls", [0.1, 0.25]],
|
|
86
|
+
["tbt", [200, 600]],
|
|
87
|
+
["inp", [200, 500]],
|
|
88
|
+
]);
|
|
89
|
+
|
|
90
|
+
// Undefined for a metric with no published threshold, such as `load`,
|
|
91
|
+
// so trivium never invents one.
|
|
92
|
+
export function ratingOf(
|
|
93
|
+
key: MetricKey | "inp",
|
|
94
|
+
value: number,
|
|
95
|
+
): Rating | undefined {
|
|
96
|
+
const bounds = THRESHOLDS.get(key);
|
|
97
|
+
if (bounds === undefined) return undefined;
|
|
98
|
+
return value <= bounds[0]
|
|
99
|
+
? "good"
|
|
100
|
+
: value <= bounds[1]
|
|
101
|
+
? "needs-improvement"
|
|
102
|
+
: "poor";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Why `browser` can't measure `key`, or undefined when it can.
|
|
106
|
+
export function unavailableReason(
|
|
107
|
+
browser: Browser,
|
|
108
|
+
key: MetricKey,
|
|
109
|
+
): string | undefined {
|
|
110
|
+
return browser === "webkit" ? WEBKIT_LACKS.get(key) : undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// The ready state in a person's words, since a timeout's message is
|
|
114
|
+
// read by someone who didn't write the page-side expression.
|
|
115
|
+
export function readyName(config: ResolvedConfig): string {
|
|
116
|
+
return config.readyMark === undefined
|
|
117
|
+
? "load"
|
|
118
|
+
: `its ready mark, ${JSON.stringify(config.readyMark)}`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// A page without a ready mark is ready at `load`, since nothing else
|
|
122
|
+
// says when it's interactive.
|
|
123
|
+
export function readyExpression(config: ResolvedConfig): string {
|
|
124
|
+
return config.readyMark === undefined
|
|
125
|
+
? `document.readyState === "complete"`
|
|
126
|
+
: `performance.getEntriesByName(${JSON.stringify(config.readyMark)}).length > 0 || document.readyState === "complete"`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const readyTime = (config: ResolvedConfig) =>
|
|
130
|
+
config.readyMark === undefined
|
|
131
|
+
? `performance.getEntriesByType("navigation")[0]?.loadEventEnd`
|
|
132
|
+
: `performance.getEntriesByName(${JSON.stringify(config.readyMark)})[0]?.startTime`;
|
|
133
|
+
|
|
134
|
+
// Raw entries only, since late ones keep arriving until the page settles.
|
|
135
|
+
// Each observer is its own try: an entry type a browser lacks can throw.
|
|
136
|
+
function observer(config: ResolvedConfig): string {
|
|
137
|
+
const element = config.element
|
|
138
|
+
? `new MutationObserver((_, o) => {
|
|
139
|
+
if (document.querySelector(${JSON.stringify(config.element.selector)})) { v.element = performance.now(); o.disconnect(); }
|
|
140
|
+
}).observe(document, { subtree: true, childList: true });`
|
|
141
|
+
: "";
|
|
142
|
+
return `
|
|
143
|
+
window.__vitals = { lcp: 0, shifts: [], tasks: [] };
|
|
144
|
+
const v = window.__vitals;
|
|
145
|
+
const watch = (type, each) => {
|
|
146
|
+
try { new PerformanceObserver((l) => { for (const e of l.getEntries()) each(e); }).observe({ type, buffered: true }); } catch {}
|
|
147
|
+
};
|
|
148
|
+
watch("paint", (e) => { if (e.name === "first-contentful-paint") v.fcp = e.startTime; });
|
|
149
|
+
watch("largest-contentful-paint", (e) => { v.lcp = e.startTime; });
|
|
150
|
+
watch("layout-shift", (e) => { if (!e.hadRecentInput) v.shifts.push([e.startTime, e.value]); });
|
|
151
|
+
watch("longtask", (e) => { v.tasks.push([e.startTime, e.duration]); });
|
|
152
|
+
${element}
|
|
153
|
+
`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const summarize = (config: ResolvedConfig) => `(() => {
|
|
157
|
+
const v = window.__vitals;
|
|
158
|
+
const nav = performance.getEntriesByType("navigation")[0];
|
|
159
|
+
// CLS is the largest session window, never the sum: shifts under 1 s
|
|
160
|
+
// apart, at most 5 s long.
|
|
161
|
+
let cls = 0, session = 0, first = 0, last = -Infinity;
|
|
162
|
+
for (const [t, value] of v.shifts) {
|
|
163
|
+
if (t - last > 1000 || t - first > 5000) { session = 0; first = t; }
|
|
164
|
+
session += value; last = t; cls = Math.max(cls, session);
|
|
165
|
+
}
|
|
166
|
+
// TBT counts only a long task's time over 50 ms, from first paint on.
|
|
167
|
+
const after = v.tasks.filter(([t]) => t >= v.fcp);
|
|
168
|
+
return {
|
|
169
|
+
ttfb: nav ? nav.responseStart : undefined,
|
|
170
|
+
fcp: v.fcp,
|
|
171
|
+
lcp: v.lcp || undefined,
|
|
172
|
+
cls,
|
|
173
|
+
tbt: after.reduce((sum, [, d]) => sum + Math.max(0, d - 50), 0),
|
|
174
|
+
longestTask: Math.max(0, ...v.tasks.map(([, d]) => d)),
|
|
175
|
+
ready: ${readyTime(config)},
|
|
176
|
+
element: v.element,
|
|
177
|
+
load: nav ? nav.loadEventEnd : undefined,
|
|
178
|
+
};
|
|
179
|
+
})()`;
|
|
180
|
+
|
|
181
|
+
// WebKit's bytes and requests, from Resource Timing: same-origin only,
|
|
182
|
+
// since a cross-origin entry without Timing-Allow-Origin reads 0 bytes.
|
|
183
|
+
// A response off the network carries headers, so 0 bytes is the cache.
|
|
184
|
+
const RESOURCES = `(() => {
|
|
185
|
+
const type = (e) => {
|
|
186
|
+
if (e.entryType === "navigation") return "Document";
|
|
187
|
+
const path = new URL(e.name).pathname;
|
|
188
|
+
if (/\\.m?js$/.test(path)) return "Script";
|
|
189
|
+
if (/\\.css$/.test(path)) return "Stylesheet";
|
|
190
|
+
if (/\\.(woff2?|ttf|otf)$/.test(path)) return "Font";
|
|
191
|
+
if (/\\.(png|jpe?g|gif|webp|avif|svg|ico)$/.test(path)) return "Image";
|
|
192
|
+
return e.initiatorType === "fetch" || e.initiatorType === "xmlhttprequest" ? "Fetch" : "Other";
|
|
193
|
+
};
|
|
194
|
+
const entries = [...performance.getEntriesByType("navigation"), ...performance.getEntriesByType("resource")]
|
|
195
|
+
.filter((e) => new URL(e.name).origin === location.origin);
|
|
196
|
+
return entries.map((e) => ({ type: type(e), bytes: e.transferSize, status: e.responseStatus ?? 0 }));
|
|
197
|
+
})()`;
|
|
198
|
+
|
|
199
|
+
interface Resource {
|
|
200
|
+
type: string;
|
|
201
|
+
bytes: number;
|
|
202
|
+
status: number;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const SCRIPT_URL = /\.js(\?|$)/;
|
|
206
|
+
|
|
207
|
+
interface CdpResponse {
|
|
208
|
+
requestId: string;
|
|
209
|
+
type: string;
|
|
210
|
+
response: { url: string; status: number; fromDiskCache?: boolean };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
interface LoadOptions {
|
|
214
|
+
browser: Browser;
|
|
215
|
+
throttle: Throttle;
|
|
216
|
+
// A second visit with a warm cache, instead of a cold first one.
|
|
217
|
+
repeat: boolean;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// A fresh view per load, since a reused one keeps fonts and
|
|
221
|
+
// compiled code.
|
|
222
|
+
export async function measureLoad(
|
|
223
|
+
url: string,
|
|
224
|
+
config: ResolvedConfig,
|
|
225
|
+
options: LoadOptions,
|
|
226
|
+
): Promise<LoadRun> {
|
|
227
|
+
const page = await openPage({
|
|
228
|
+
browser: options.browser,
|
|
229
|
+
throttle: options.throttle,
|
|
230
|
+
initScript: observer(config),
|
|
231
|
+
cache: options.repeat,
|
|
232
|
+
});
|
|
233
|
+
try {
|
|
234
|
+
const bytesByType: Record<string, number> = {};
|
|
235
|
+
const requests: Requests = { network: 0, revalidated: 0, cache: 0 };
|
|
236
|
+
let measuring = !options.repeat;
|
|
237
|
+
if (page.browser === "chrome") {
|
|
238
|
+
const types = new Map<string, string>();
|
|
239
|
+
const servedFromCache = new Set<string>();
|
|
240
|
+
page.view.addEventListener<{ requestId: string }>(
|
|
241
|
+
"Network.requestServedFromCache",
|
|
242
|
+
(event) => servedFromCache.add(event.data.requestId),
|
|
243
|
+
);
|
|
244
|
+
page.view.addEventListener<CdpResponse>(
|
|
245
|
+
"Network.responseReceived",
|
|
246
|
+
({ data }) => {
|
|
247
|
+
if (!measuring || data.response.url.startsWith("data:")) return;
|
|
248
|
+
// A `<link rel="prefetch">` is typed "Other", so a script URL
|
|
249
|
+
// names it.
|
|
250
|
+
const prefetched =
|
|
251
|
+
data.type === "Other" && SCRIPT_URL.test(data.response.url);
|
|
252
|
+
types.set(
|
|
253
|
+
data.requestId,
|
|
254
|
+
prefetched ? "Script (prefetched)" : data.type,
|
|
255
|
+
);
|
|
256
|
+
if (
|
|
257
|
+
servedFromCache.has(data.requestId) ||
|
|
258
|
+
data.response.fromDiskCache === true
|
|
259
|
+
) {
|
|
260
|
+
requests.cache++;
|
|
261
|
+
} else if (data.response.status === 304) requests.revalidated++;
|
|
262
|
+
else requests.network++;
|
|
263
|
+
},
|
|
264
|
+
);
|
|
265
|
+
page.view.addEventListener<{
|
|
266
|
+
requestId: string;
|
|
267
|
+
encodedDataLength: number;
|
|
268
|
+
}>("Network.loadingFinished", ({ data }) => {
|
|
269
|
+
const type = types.get(data.requestId);
|
|
270
|
+
if (type !== undefined) {
|
|
271
|
+
bytesByType[type] = (bytesByType[type] ?? 0) + data.encodedDataLength;
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
if (options.repeat) {
|
|
276
|
+
await page.navigate(url);
|
|
277
|
+
await waitFor(page.view, `document.readyState === "complete"`, "load");
|
|
278
|
+
// Idle-time prefetches fill the cache too.
|
|
279
|
+
await page.settle();
|
|
280
|
+
measuring = true;
|
|
281
|
+
}
|
|
282
|
+
await page.navigate(url);
|
|
283
|
+
await waitFor(
|
|
284
|
+
page.view,
|
|
285
|
+
"window.__vitals?.fcp !== undefined",
|
|
286
|
+
"a first paint",
|
|
287
|
+
);
|
|
288
|
+
// Late work, such as hydration and idle-time imports, finishes first.
|
|
289
|
+
await page.settle();
|
|
290
|
+
const vitals = await page.view.evaluate<Vitals>(summarize(config));
|
|
291
|
+
if (page.browser === "webkit") {
|
|
292
|
+
for (const r of await page.view.evaluate<Resource[]>(RESOURCES)) {
|
|
293
|
+
if (r.status === 304) requests.revalidated++;
|
|
294
|
+
else if (r.bytes === 0) requests.cache++;
|
|
295
|
+
else requests.network++;
|
|
296
|
+
bytesByType[r.type] = (bytesByType[r.type] ?? 0) + r.bytes;
|
|
297
|
+
}
|
|
298
|
+
for (const key of WEBKIT_LACKS.keys()) delete vitals[key];
|
|
299
|
+
}
|
|
300
|
+
return { vitals, bytesByType, requests };
|
|
301
|
+
} finally {
|
|
302
|
+
page.close();
|
|
303
|
+
}
|
|
304
|
+
}
|
package/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|