-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbudget.js
More file actions
237 lines (222 loc) · 7.03 KB
/
Copy pathbudget.js
File metadata and controls
237 lines (222 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { readFile } from 'node:fs/promises';
import { linkFor } from './links.js';
/**
* Budget thresholds applied when the budget file omits them.
* Chosen to pass on a well-built page on a mid-range laptop.
*/
export const DEFAULT_BUDGET = Object.freeze({
droppedFramePercent: 5,
p95FrameMs: 16.7,
p99FrameMs: 33,
worstFrameMs: 50,
longestStallMs: 100,
longTasks: 0,
totalBlockingMs: 50,
maxLayers: 60,
forcedReflows: 0,
nonCompositorAnimations: 0,
styleRecalcMs: 100,
mainThreadMs: 1500,
});
/**
* Every checkable budget key, with the analysis path it reads and how to read it.
* `higherIsWorse` is always true here — each metric is a ceiling.
*/
const CHECKS = [
{
key: 'droppedFramePercent',
label: 'Dropped frames',
unit: '%',
read: (a) => a.frames.droppedFramePercent,
link: 'devtools',
why: 'Frames that never reached the screen. Above a few percent, scrolling visibly stutters.',
},
{
key: 'p95FrameMs',
label: 'p95 frame duration',
unit: 'ms',
read: (a) => a.frames.p95Ms,
link: 'mainThreadJank',
why: 'The slow tail of frame times. One frame in twenty is at least this slow.',
},
{
key: 'p99FrameMs',
label: 'p99 frame duration',
unit: 'ms',
read: (a) => a.frames.p99Ms,
link: 'mainThreadJank',
why: 'The worst 1% of frames — where users notice hitching during a fast scroll.',
},
{
key: 'worstFrameMs',
label: 'Worst frame',
unit: 'ms',
read: (a) => a.frames.worstFrameMs,
link: 'mainThreadJank',
why: 'The single slowest frame in the scroll.',
},
{
key: 'longestStallMs',
label: 'Longest stall',
unit: 'ms',
read: (a) => a.frames.longestStallMs,
link: 'renderingPipeline',
why: 'The longest period where the screen did not update while scrolling continued.',
},
{
key: 'longTasks',
label: 'Long tasks (>50ms)',
unit: '',
read: (a) => a.longTasks.count,
link: 'mainThreadJank',
why: 'Main-thread tasks long enough to block input and delay the next frame.',
},
{
key: 'totalBlockingMs',
label: 'Total blocking time',
unit: 'ms',
read: (a) => a.longTasks.totalBlockingMs,
link: 'coreWebVitals',
why: 'Time beyond 50ms across all long tasks — the same idea as TBT, measured during scroll.',
},
{
key: 'maxLayers',
label: 'Composited layers',
unit: '',
read: (a) => a.layers.layersAfter,
link: 'compositorSafe',
why: 'Each layer costs memory and compositing work; too many is slower than too few.',
},
{
key: 'forcedReflows',
label: 'Forced synchronous layouts',
unit: '',
read: (a) => a.forcedReflows.count,
link: 'mainThreadJank',
why: 'Script read geometry after mutating the DOM, forcing layout mid-task.',
},
{
key: 'nonCompositorAnimations',
label: 'Non-compositor animations',
unit: '',
read: (a) => a.animations.nonCompositorCount,
link: 'transformVsTopLeft',
why: 'Animations touching layout- or paint-triggering properties cannot run on the compositor.',
},
{
key: 'styleRecalcMs',
label: 'Style recalculation',
unit: 'ms',
read: (a) => a.styleRecalcs.totalMs,
link: 'renderingPipeline',
why: 'Time spent recomputing styles during the scroll.',
},
{
key: 'mainThreadMs',
label: 'Main-thread busy time',
unit: 'ms',
read: (a) => a.threads.mainThreadMs,
link: 'mainThreadJank',
why: 'Total main-thread work during the scroll. Compositor-only scrolling keeps this near zero.',
},
];
/**
* Load a budget file, filling in defaults for anything it omits.
*
* A budget file is JSON with any subset of the keys in {@link DEFAULT_BUDGET}.
* A `null` value disables that check.
*
* @param {string} [path] Path to a `scroll-budget.json`. Omit for defaults only.
* @returns {Promise<Record<string, number|null>>} The effective budget.
* @throws {Error} When the file cannot be read or contains invalid JSON/keys.
*/
export async function loadBudget(path) {
if (!path) return { ...DEFAULT_BUDGET };
let raw;
try {
raw = await readFile(path, 'utf8');
} catch (cause) {
throw new Error(`Cannot read budget file: ${path}`, { cause });
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (cause) {
throw new Error(`Budget file is not valid JSON: ${path}`, { cause });
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error(`Budget file must contain a JSON object: ${path}`);
}
const known = new Set(Object.keys(DEFAULT_BUDGET));
for (const [key, value] of Object.entries(parsed)) {
if (key === '$schema') continue;
if (!known.has(key)) {
throw new Error(
`Unknown budget key "${key}". Valid keys: ${[...known].sort().join(', ')}`
);
}
if (value !== null && (typeof value !== 'number' || Number.isNaN(value))) {
throw new Error(`Budget "${key}" must be a number or null, got: ${JSON.stringify(value)}`);
}
}
const { $schema, ...thresholds } = parsed;
return { ...DEFAULT_BUDGET, ...thresholds };
}
/**
* @typedef {object} BudgetResult
* @property {string} key Budget key.
* @property {string} label Human-readable name.
* @property {number} actual Measured value.
* @property {number} budget Threshold it was compared against.
* @property {string} unit Display unit (`ms`, `%` or empty).
* @property {boolean} passed Whether the measurement is within budget.
* @property {string} why What the metric means.
* @property {string} learnMore Article URL explaining the check.
*/
/**
* @typedef {object} BudgetReport
* @property {boolean} passed True when no enabled check was exceeded.
* @property {number} failures Number of exceeded checks.
* @property {BudgetResult[]} results One entry per enabled check.
*/
/**
* Evaluate an analysis against a budget.
*
* @param {import('./analyze/index.js').Analysis} analysis Result of {@link import('./analyze/index.js').analyze}.
* @param {Record<string, number|null>} [budget] Thresholds; defaults to {@link DEFAULT_BUDGET}.
* @returns {BudgetReport} Pass/fail per check plus an overall verdict.
*/
export function evaluateBudget(analysis, budget = DEFAULT_BUDGET) {
const results = [];
for (const check of CHECKS) {
const threshold = budget[check.key];
if (threshold === null || threshold === undefined) continue;
const actual = check.read(analysis);
results.push({
key: check.key,
label: check.label,
actual,
budget: threshold,
unit: check.unit,
passed: actual <= threshold,
why: check.why,
learnMore: linkFor(check.link),
});
}
const failures = results.filter((r) => !r.passed).length;
return { passed: failures === 0, failures, results };
}
/**
* The static catalogue of checks, for documentation and reporters.
*
* @returns {{key:string,label:string,unit:string,why:string,learnMore:string}[]} Check metadata.
*/
export function describeChecks() {
return CHECKS.map(({ key, label, unit, why, link }) => ({
key,
label,
unit,
why,
learnMore: linkFor(link),
}));
}