-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathutils.ts
More file actions
201 lines (182 loc) · 5.67 KB
/
utils.ts
File metadata and controls
201 lines (182 loc) · 5.67 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
import { bold } from 'ansis';
import type { Config, FormattedIcu } from 'lighthouse';
import log from 'lighthouse-logger';
import desktopConfig from 'lighthouse/core/config/desktop-config.js';
import experimentalConfig from 'lighthouse/core/config/experimental-config.js';
import perfConfig from 'lighthouse/core/config/perf-config.js';
import type Details from 'lighthouse/types/lhr/audit-details';
import type { Result } from 'lighthouse/types/lhr/audit-result';
import os from 'node:os';
import path from 'node:path';
import type { AuditOutput, AuditOutputs } from '@code-pushup/models';
import {
formatReportScore,
importModule,
pluginWorkDir,
readJsonFile,
ui,
} from '@code-pushup/utils';
import { LIGHTHOUSE_PLUGIN_SLUG } from '../constants.js';
import type { LighthouseOptions } from '../types.js';
import { logUnsupportedDetails, toAuditDetails } from './details/details.js';
import type { LighthouseCliFlags } from './types.js';
export function normalizeAuditOutputs(
auditOutputs: AuditOutputs,
flags: LighthouseOptions = { skipAudits: [] },
): AuditOutputs {
const toSkip = new Set(flags.skipAudits ?? []);
return auditOutputs.filter(({ slug }) => !toSkip.has(slug));
}
export class LighthouseAuditParsingError extends Error {
constructor(slug: string, error: Error) {
super(`\nAudit ${bold(slug)} failed parsing details: \n${error.message}`);
}
}
function formatBaseAuditOutput(lhrAudit: Result): AuditOutput {
const {
id: slug,
score,
numericValue,
displayValue,
scoreDisplayMode,
} = lhrAudit;
return {
slug,
score: score ?? 1,
value: numericValue ?? score ?? 0,
displayValue:
displayValue ??
(scoreDisplayMode === 'binary'
? score === 1
? 'passed'
: 'failed'
: score
? `${formatReportScore(score)}%`
: undefined),
};
}
function processAuditDetails(
auditOutput: AuditOutput,
details: FormattedIcu<Details>,
): AuditOutput {
try {
const parsedDetails = toAuditDetails(details);
return Object.keys(parsedDetails).length > 0
? { ...auditOutput, details: parsedDetails }
: auditOutput;
} catch (error) {
throw new LighthouseAuditParsingError(auditOutput.slug, error as Error);
}
}
export function toAuditOutputs(
lhrAudits: Result[],
{ verbose = false }: { verbose?: boolean } = {},
): AuditOutputs {
if (verbose) {
logUnsupportedDetails(lhrAudits);
}
return lhrAudits.map(audit => {
const auditOutput = formatBaseAuditOutput(audit);
return audit.details == null
? auditOutput
: processAuditDetails(auditOutput, audit.details);
});
}
export type LighthouseLogLevel =
| 'verbose'
| 'error'
| 'info'
| 'silent'
| 'warn'
| undefined;
export function determineAndSetLogLevel({
verbose,
quiet,
}: {
verbose?: boolean;
quiet?: boolean;
} = {}): LighthouseLogLevel {
// eslint-disable-next-line functional/no-let
let logLevel: LighthouseLogLevel = 'info';
// set logging preferences
if (verbose) {
logLevel = 'verbose';
} else if (quiet) {
logLevel = 'silent';
}
log.setLevel(logLevel);
return logLevel;
}
export type ConfigOptions = Partial<
Pick<LighthouseCliFlags, 'configPath' | 'preset'>
>;
export async function getConfig(
options: ConfigOptions = {},
): Promise<Config | undefined> {
const { configPath: filepath, preset } = options;
if (filepath != null) {
if (filepath.endsWith('.json')) {
// Resolve the config file path relative to where cli was called.
return readJsonFile<Config>(filepath);
} else if (/\.(ts|js|mjs)$/.test(filepath)) {
return importModule<Config>({ filepath, format: 'esm' });
} else {
ui().logger.info(`Format of file ${filepath} not supported`);
}
} else if (preset != null) {
switch (preset) {
case 'desktop':
return desktopConfig;
case 'perf':
return perfConfig as Config;
case 'experimental':
return experimentalConfig as Config;
default:
// as preset is a string literal the default case here is normally caught by TS and not possible to happen. Now in reality it can happen and preset could be a string not included in the literal.
// Therefore, we have to use `as string`. Otherwise, it will consider preset as type never
ui().logger.info(`Preset "${preset as string}" is not supported`);
}
}
return undefined;
}
export function enrichFlags(
flags: LighthouseCliFlags,
urlIndex?: number,
): LighthouseOptions {
const { outputPath, ...parsedFlags }: Partial<LighthouseCliFlags> = flags;
const logLevel = determineAndSetLogLevel(parsedFlags);
const urlSpecificOutputPath =
urlIndex && outputPath
? outputPath.replace(/(\.[^.]+)?$/, `-${urlIndex}$1`)
: outputPath;
return {
...parsedFlags,
logLevel,
outputPath: urlSpecificOutputPath,
};
}
/**
* Wraps Lighthouse runner with `TEMP` directory override for Windows, to prevent permissions error on cleanup.
*
* `Runtime error encountered: EPERM, Permission denied: \\?\C:\Users\RUNNER~1\AppData\Local\Temp\lighthouse.57724617 '\\?\C:\Users\RUNNER~1\AppData\Local\Temp\lighthouse.57724617'`
*
* @param fn Async function which runs Lighthouse.
* @returns Wrapped function which overrides `TEMP` environment variable, before cleaning up afterwards.
*/
export function withLocalTmpDir<T>(fn: () => Promise<T>): () => Promise<T> {
if (os.platform() !== 'win32') {
return fn;
}
return async () => {
const originalTmpDir = process.env['TEMP'];
process.env['TEMP'] = path.join(
pluginWorkDir(LIGHTHOUSE_PLUGIN_SLUG),
'tmp',
);
try {
return await fn();
} finally {
process.env['TEMP'] = originalTmpDir;
}
};
}