-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathlighthouse.ts
More file actions
155 lines (140 loc) · 3.84 KB
/
lighthouse.ts
File metadata and controls
155 lines (140 loc) · 3.84 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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import path from 'node:path';
import {
snapshot,
navigation,
generateReport,
zod,
type Flags,
type RunnerResult,
type OutputMode,
} from '../third_party/index.js';
import {ToolCategory} from './categories.js';
import {startTrace} from './performance.js';
import {definePageTool} from './ToolDefinition.js';
export const lighthouseAudit = definePageTool({
name: 'lighthouse_audit',
description: `Get Lighthouse score and reports for accessibility, SEO and best practices. This excludes performance. For performance audits, run ${startTrace.name}`,
annotations: {
category: ToolCategory.DEBUGGING,
readOnlyHint: true,
},
schema: {
mode: zod
.enum(['navigation', 'snapshot'])
.default('navigation')
.describe(
'"navigation" reloads & audits. "snapshot" analyzes current state.',
),
device: zod
.enum(['desktop', 'mobile'])
.default('desktop')
.describe('Device to emulate.'),
outputDirPath: zod
.string()
.optional()
.describe('Directory for reports. If omitted, uses temporary files.'),
},
handler: async (request, response, context) => {
const page = request.page;
const categories = ['accessibility', 'seo', 'best-practices'];
const formats = ['json', 'html'] as OutputMode[];
const {
mode = 'navigation',
device = 'desktop',
outputDirPath,
} = request.params;
const flags: Flags = {
onlyCategories: categories,
output: formats,
// Default 30 second timeout for page load.
maxWaitForLoad: 30_000,
};
if (device === 'desktop') {
flags.formFactor = 'desktop';
flags.screenEmulation = {
mobile: false,
width: 1350,
height: 940,
deviceScaleFactor: 1,
disabled: false,
};
} else {
flags.formFactor = 'mobile';
flags.screenEmulation = {
mobile: true,
width: 412,
height: 823,
deviceScaleFactor: 1.75,
disabled: false,
};
}
let result: RunnerResult | undefined;
try {
if (mode === 'navigation') {
result = await navigation(page.pptrPage, page.pptrPage.url(), {
flags,
});
} else {
result = await snapshot(page.pptrPage, {
flags,
});
}
if (!result) {
throw new Error('Lighthouse audit failed.');
}
} finally {
await context.restoreEmulation(page);
}
const lhr = result.lhr;
const reportPaths: string[] = [];
const encoder = new TextEncoder();
for (const format of formats) {
const report = generateReport(lhr, format);
const data = encoder.encode(report);
if (outputDirPath) {
const reportPath = path.join(outputDirPath, `report.${format}`);
const {filename} = await context.saveFile(data, reportPath);
reportPaths.push(filename);
} else {
const {filepath} = await context.saveTemporaryFile(
data,
`report.${format}`,
);
reportPaths.push(filepath);
}
}
const categoryScores = Object.values(lhr.categories).map(c => ({
id: c.id,
title: c.title,
score: c.score,
}));
const failedAudits = Object.values(lhr.audits).filter(
a => a.score !== null && a.score < 1,
).length;
const passedAudits = Object.values(lhr.audits).filter(
a => a.score === 1,
).length;
const output = {
summary: {
mode,
device,
url: lhr.mainDocumentUrl,
scores: categoryScores,
audits: {
failed: failedAudits,
passed: passedAudits,
},
timing: {
total: lhr.timing.total,
},
},
reports: reportPaths,
};
response.attachLighthouseResult(output);
},
});