-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathutils.ts
More file actions
232 lines (209 loc) · 6.36 KB
/
Copy pathutils.ts
File metadata and controls
232 lines (209 loc) · 6.36 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
import ansis 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,
logger,
pluginWorkDir,
readJsonFile,
stringifyError,
} 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 filterAuditOutputs(
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: unknown) {
super(
`Failed to parse ${ansis.bold(slug)} audit's details - ${stringifyError(error)}`,
);
}
}
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);
}
}
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, preset } = options;
if (configPath != null) {
// Resolve the config file path relative to where cli was called.
return logger.task(
`Loading lighthouse config from ${configPath}`,
async () => {
const message = `Loaded lighthouse config from ${configPath}`;
if (configPath.endsWith('.json')) {
return { message, result: await readJsonFile<Config>(configPath) };
}
if (/\.(ts|js|mjs)$/.test(configPath)) {
return {
message,
result: await importModule<Config>({
filepath: configPath,
}),
};
}
throw new Error(
`Unknown Lighthouse config file extension in ${configPath}`,
);
},
);
}
if (preset != null) {
const supportedPresets: Record<
NonNullable<LighthouseCliFlags['preset']>,
Config
> = {
desktop: desktopConfig,
perf: perfConfig,
experimental: experimentalConfig,
};
// in reality, the preset could be a string not included in the type definition
const config: Config | undefined = supportedPresets[preset];
if (config) {
logger.info(`Loaded config from ${ansis.bold(preset)} preset`);
return config;
} else {
logger.warn(`Preset "${preset}" 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'];
const localPath = path.join(pluginWorkDir(LIGHTHOUSE_PLUGIN_SLUG), 'tmp');
// eslint-disable-next-line functional/immutable-data
process.env['TEMP'] = localPath;
logger.debug(
`Temporarily overwriting TEMP environment variable with ${localPath} to prevent permissions error on cleanup`,
);
try {
return await fn();
} finally {
// eslint-disable-next-line functional/immutable-data
process.env['TEMP'] = originalTmpDir;
logger.debug(
`Restored TEMP environment variable to original value ${originalTmpDir}`,
);
}
};
}