-
Notifications
You must be signed in to change notification settings - Fork 3
/
lighthousePersist.ts
313 lines (275 loc) · 7.86 KB
/
lighthousePersist.ts
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import fs from 'fs';
import { chromeLauncher } from './helpers/chromeLauncher';
import AWS from 'aws-sdk';
import config from './config';
import defaultOptions from './options';
import upload from './helpers/upload';
import getOpportunities from './helpers/getOpportunities';
import getPageSpeedInsightsApiResult from './helpers/getPageSpeedInsightsApiResult';
import loadLighthouse from './helpers/loadLighthouse';
import loadReportGenerator from './helpers/loadReportGenerator';
interface OpportunitiesInterface {
id: string;
result: {
description: string;
details: {
headings: {
key: string;
label: string;
valueType: string;
}[];
items: {
fromProtocol: boolean;
isCrossOrigin: boolean;
node: any;
totalBytes: number;
url: string;
wastedBytes: number;
wastedWebpBytes: number;
}[];
overallSavingsMs: number;
overallSavingsBytes: number;
type: string;
};
displayValue: string;
id: string;
numericUnit: string;
numericValue: number;
rating: string;
score: number;
scoreDisplayMode: string;
title: string;
warnings: string[];
};
weight: number;
}
interface LoadingExperienceMetricInterface {
percentile: number;
distributions: {
max: number;
min: number;
proportion: number;
}[];
category: string;
}
interface LoadingExperienceInterface {
id: string;
initial_url: string;
metrics: {
CUMULATIVE_LAYOUT_SHIFT_SCORE: LoadingExperienceMetricInterface;
FIRST_CONTENTFUL_PAINT_MS: LoadingExperienceMetricInterface;
FIRST_INPUT_DELAY_MS: LoadingExperienceMetricInterface;
LARGEST_CONTENTFUL_PAINT_MS: LoadingExperienceMetricInterface;
};
overall_category: string;
}
interface LighthousePersistResultInterface {
finalScreenshot?: string;
loadingExperience?: LoadingExperienceInterface;
localReport?: string;
originLoadingExperience?: LoadingExperienceInterface;
result: any;
report?: string;
opportunities?: OpportunitiesInterface[];
}
const PROTOCOL_TIMEOUT = 'PROTOCOL_TIMEOUT';
const createTimeout = (time: number) =>
new Promise((resolve) => {
setTimeout(resolve, time, PROTOCOL_TIMEOUT);
});
// https://github.com/GoogleChrome/lighthouse/blob/master/docs/readme.md#using-programmatically
export default async ({
awsAccessKeyId: accessKeyId,
awsBucket: Bucket,
awsRegion: region,
awsSecretAccessKey: secretAccessKey,
config: customConfig,
finalScreenshotAwsBucket,
isExperimental,
launchedChrome,
options: customOptions,
outputDirectory,
updateReport,
psiKey,
timeout,
url,
verbose,
}: {
awsAccessKeyId?: string;
awsBucket?: string;
awsRegion?: string;
awsSecretAccessKey?: string;
config?: any;
finalScreenshotAwsBucket?: string;
isExperimental?: boolean;
launchedChrome?: any;
options?: any;
outputDirectory?: string;
updateReport?: (input: any) => void;
psiKey?: string;
timeout?: number;
url: string;
verbose?: boolean;
}): Promise<LighthousePersistResultInterface> => {
// will upload to S3?
const isS3 = !!(accessKeyId && region && secretAccessKey);
// if a URL, output directory, or S3 creds are missing - we got a problem.
if (!outputDirectory && !url && !isS3) {
throw new Error('Missing required params.');
}
// the default config combined with overriding query params
const fullConfig = {
...config,
...customConfig,
};
const options = {
...defaultOptions,
...customOptions,
};
// we need to kill chrome if something goes wrong, so we pull it up
// into the function scope to be accessible in the catch block.
let chrome = launchedChrome;
try {
let results;
let loadingExperience;
let originLoadingExperience;
// this changed in Lighthouse 7, but we should try to support those
// who don't know about this obscure change.
const formFactor =
fullConfig.settings.formFactor || fullConfig.settings.emulatedFormFactor;
// if we're getting results from the PageSpeed Insights API... else
// run Lighthouse directly
if (psiKey) {
const strategy = formFactor === 'desktop' ? 'DESKTOP' : 'MOBILE';
const psiResults = await getPageSpeedInsightsApiResult({
psiKey,
strategy,
url,
});
if (psiResults.error) {
throw Error(psiResults.error.message);
}
const ReportGenerator = await loadReportGenerator();
results = {
lhr: psiResults.lighthouseResult,
report: ReportGenerator.generateReportHtml(psiResults.lighthouseResult),
};
if (psiResults.loadingExperience) {
loadingExperience = psiResults.loadingExperience;
}
if (psiResults.originLoadingExperience) {
originLoadingExperience = psiResults.originLoadingExperience;
}
} else {
if (!chrome) {
chrome = await chromeLauncher({
chromeFlags: options.chromeFlags,
port: options.port,
});
}
if (verbose) {
console.log('Chrome running on port', chrome.port);
}
options.output = 'html';
const lighthouse = await loadLighthouse();
results = !timeout
? await lighthouse(url, options, fullConfig)
: await Promise.race([
createTimeout(timeout),
lighthouse(url, options, fullConfig),
]);
if (results === PROTOCOL_TIMEOUT) {
throw Error(PROTOCOL_TIMEOUT);
}
await chrome.kill();
}
// a remote URL
let report;
// a local file path
let localReport;
// the final thumbnail image
let finalScreenshot;
const reportContent = !updateReport
? results.report
: updateReport(results.report);
if (isS3) {
if (Bucket && reportContent) {
// upload to S3
const s3Response = await upload({
s3bucket: new AWS.S3({
accessKeyId,
region,
secretAccessKey,
}),
params: {
ACL: 'public-read',
Body: reportContent,
Bucket,
ContentType: 'text/html',
Key: `report-${Date.now()}.html`,
},
});
report = s3Response?.Location;
}
if (finalScreenshotAwsBucket) {
const finalScreenshotData =
results?.lhr?.audits?.['final-screenshot']?.details?.data;
if (finalScreenshotData) {
const buffer = Buffer.from(
finalScreenshotData.replace('data:image/jpeg;base64,', ''),
'base64',
);
const s3Response = await upload({
s3bucket: new AWS.S3({
accessKeyId,
region,
secretAccessKey,
}),
params: {
ACL: 'public-read',
Body: buffer,
Bucket: finalScreenshotAwsBucket,
ContentEncoding: 'base64',
ContentType: 'image/jpeg',
Key: `final-screenshot-${Date.now()}.jpg`,
},
});
finalScreenshot = s3Response.Location;
}
}
}
if (outputDirectory) {
localReport = `${outputDirectory}/report-${Date.now()}.html`;
fs.writeFileSync(localReport, reportContent);
}
const parsedResult = JSON.parse(JSON.stringify(results.lhr));
let opportunities = [];
if (isExperimental && parsedResult?.categories?.performance?.auditRefs) {
try {
opportunities = await getOpportunities(parsedResult);
} catch (error) {
console.error(error);
}
}
return {
finalScreenshot,
loadingExperience,
localReport,
originLoadingExperience,
result: parsedResult,
report,
// experimental features
...(!isExperimental
? {}
: {
opportunities,
}),
};
} catch (error) {
// make sure we kill chrome
if (chrome) {
await chrome.kill();
}
throw error;
}
};