-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathparse.ts
More file actions
260 lines (228 loc) · 7 KB
/
parse.ts
File metadata and controls
260 lines (228 loc) · 7 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {logger} from '../logger.js';
import {DevTools} from '../third_party/index.js';
const engine = DevTools.TraceEngine.TraceModel.Model.createWithAllHandlers();
export interface TraceResult {
parsedTrace: DevTools.TraceEngine.TraceModel.ParsedTrace;
insights: DevTools.TraceEngine.Insights.Types.TraceInsightSets | null;
}
export function traceResultIsSuccess(
x: TraceResult | TraceParseError,
): x is TraceResult {
return 'parsedTrace' in x;
}
export interface TraceParseError {
error: string;
}
export async function parseRawTraceBuffer(
buffer: Uint8Array<ArrayBufferLike> | undefined,
): Promise<TraceResult | TraceParseError> {
engine.resetProcessor();
if (!buffer) {
return {
error: 'No buffer was provided.',
};
}
const asString = new TextDecoder().decode(buffer);
if (!asString) {
return {
error: 'Decoding the trace buffer returned an empty string.',
};
}
try {
const data = JSON.parse(asString) as
| {
traceEvents: DevTools.TraceEngine.Types.Events.Event[];
}
| DevTools.TraceEngine.Types.Events.Event[];
const events = Array.isArray(data) ? data : data.traceEvents;
await engine.parse(events);
const parsedTrace = engine.parsedTrace();
if (!parsedTrace) {
return {
error: 'No parsed trace was returned from the trace engine.',
};
}
const insights = parsedTrace?.insights ?? null;
return {
parsedTrace,
insights,
};
} catch (e) {
const errorText = e instanceof Error ? e.message : JSON.stringify(e);
logger(`Unexpected error parsing trace: ${errorText}`);
return {
error: errorText,
};
}
}
const extraFormatDescriptions = `Information on performance traces may contain main thread activity represented as call frames and network requests.
${DevTools.PerformanceTraceFormatter.callFrameDataFormatDescription}
${DevTools.PerformanceTraceFormatter.networkDataFormatDescription}`;
type Rating = 'good' | 'needs-improvement' | 'poor';
/**
* Rate a timing-based Web Vitals metric value (in ms) against its thresholds.
* Thresholds are from https://web.dev/articles/vitals
*/
export function rateTimingMetric(
metric: string,
valueMs: number,
): Rating | null {
const thresholds: Record<string, {good: number; poor: number}> = {
LCP: {good: 2500, poor: 4000},
FCP: {good: 1800, poor: 3000},
INP: {good: 200, poor: 500},
TTFB: {good: 800, poor: 1800},
};
const t = thresholds[metric];
if (!t) {
return null;
}
if (valueMs <= t.good) {
return 'good';
}
if (valueMs >= t.poor) {
return 'poor';
}
return 'needs-improvement';
}
export function rateCLS(value: number): Rating {
if (value <= 0.1) {
return 'good';
}
if (value >= 0.25) {
return 'poor';
}
return 'needs-improvement';
}
/**
* Build a CrUX field metrics section with ratings included directly,
* using the structured data from the trace insights rather than
* regex post-processing.
*/
function buildRatedCruxSection(result: TraceResult): string[] | null {
const parsedTrace = result.parsedTrace;
const insights = result.insights;
if (!insights) {
return null;
}
// Find the first insight set with CrUX data.
for (const insightSet of insights.values()) {
try {
const cruxScope =
DevTools.CrUXManager.instance().getSelectedScope();
const fieldMetrics =
DevTools.TraceEngine.Insights.Common.getFieldMetricsForInsightSet(
insightSet,
parsedTrace.metadata,
cruxScope,
);
if (!fieldMetrics) {
continue;
}
const {lcp: fieldLcp, inp: fieldInp, cls: fieldCls} = fieldMetrics;
if (!fieldLcp && !fieldInp && !fieldCls) {
continue;
}
const parts: string[] = [];
parts.push('Metrics (field / real users):');
if (fieldLcp) {
const ms = Math.round(fieldLcp.value / 1000);
const rating = rateTimingMetric('LCP', ms);
const ratingStr = rating ? ` [${rating}]` : '';
parts.push(
` - LCP: ${ms} ms (scope: ${fieldLcp.pageScope})${ratingStr}`,
);
}
if (fieldInp) {
const ms = Math.round(fieldInp.value / 1000);
const rating = rateTimingMetric('INP', ms);
const ratingStr = rating ? ` [${rating}]` : '';
parts.push(
` - INP: ${ms} ms (scope: ${fieldInp.pageScope})${ratingStr}`,
);
}
if (fieldCls) {
const clsValue = fieldCls.value;
const rating = rateCLS(clsValue);
parts.push(
` - CLS: ${clsValue.toFixed(2)} (scope: ${fieldCls.pageScope}) [${rating}]`,
);
}
return parts;
} catch {
continue;
}
}
return null;
}
export function getTraceSummary(result: TraceResult): string {
const focus = DevTools.AgentFocus.fromParsedTrace(result.parsedTrace);
const formatter = new DevTools.PerformanceTraceFormatter(focus);
let summaryText = formatter.formatTraceSummary();
// Replace the CrUX section in the formatter output with our rated version.
const ratedCrux = buildRatedCruxSection(result);
if (ratedCrux) {
const lines = summaryText.split('\n');
const cruxHeaderIdx = lines.findIndex(l =>
l.startsWith('Metrics (field / real users):'),
);
if (cruxHeaderIdx !== -1) {
// Find the end of the CrUX section (next non-indented line or section header).
let endIdx = cruxHeaderIdx + 1;
while (
endIdx < lines.length &&
(lines[endIdx].startsWith(' - ') || lines[endIdx].startsWith(' - '))
) {
endIdx++;
}
lines.splice(
cruxHeaderIdx,
endIdx - cruxHeaderIdx,
...ratedCrux,
);
summaryText = lines.join('\n');
}
}
return `## Summary of Performance trace findings:
${summaryText}
## Details on call tree & network request formats:
${extraFormatDescriptions}`;
}
export type InsightName =
keyof DevTools.TraceEngine.Insights.Types.InsightModels;
export type InsightOutput = {output: string} | {error: string};
export function getInsightOutput(
result: TraceResult,
insightSetId: string,
insightName: InsightName,
): InsightOutput {
if (!result.insights) {
return {
error: 'No Performance insights are available for this trace.',
};
}
const insightSet = result.insights.get(insightSetId);
if (!insightSet) {
return {
error:
'No Performance Insights for the given insight set id. Only use ids given in the "Available insight sets" list.',
};
}
const matchingInsight =
insightName in insightSet.model ? insightSet.model[insightName] : null;
if (!matchingInsight) {
return {
error: `No Insight with the name ${insightName} found. Double check the name you provided is accurate and try again.`,
};
}
const formatter = new DevTools.PerformanceInsightFormatter(
DevTools.AgentFocus.fromParsedTrace(result.parsedTrace),
matchingInsight,
);
return {output: formatter.formatInsight()};
}