-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathrunner.ts
More file actions
83 lines (72 loc) · 2.48 KB
/
runner.ts
File metadata and controls
83 lines (72 loc) · 2.48 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
import type { Config, RunnerResult } from 'lighthouse';
import { runLighthouse } from 'lighthouse/cli/run.js';
import path from 'node:path';
import type { AuditOutputs, RunnerFunction } from '@code-pushup/models';
import { ensureDirectoryExists, ui } from '@code-pushup/utils';
import { orderSlug, shouldExpandForUrls } from '../processing.js';
import type { LighthouseOptions } from '../types.js';
import { DEFAULT_CLI_FLAGS } from './constants.js';
import type { LighthouseCliFlags } from './types.js';
import {
enrichFlags,
getConfig,
normalizeAuditOutputs,
toAuditOutputs,
withLocalTmpDir,
} from './utils.js';
export function createRunnerFunction(
urls: string[],
flags: LighthouseCliFlags = DEFAULT_CLI_FLAGS,
): RunnerFunction {
return withLocalTmpDir(async (): Promise<AuditOutputs> => {
const config = await getConfig(flags);
const normalizationFlags = enrichFlags(flags);
const isSingleUrl = !shouldExpandForUrls(urls.length);
const allResults = await urls.reduce(async (prev, url, index) => {
const acc = await prev;
try {
const enrichedFlags = isSingleUrl
? normalizationFlags
: enrichFlags(flags, index + 1);
const auditOutputs = await runLighthouseForUrl(
url,
enrichedFlags,
config,
);
const processedOutputs = isSingleUrl
? auditOutputs
: auditOutputs.map(audit => ({
...audit,
slug: orderSlug(audit.slug, index),
}));
return [...acc, ...processedOutputs];
} catch (error) {
ui().logger.warning((error as Error).message);
return acc;
}
}, Promise.resolve<AuditOutputs>([]));
if (allResults.length === 0) {
throw new Error(
isSingleUrl
? 'Lighthouse did not produce a result.'
: 'Lighthouse failed to produce results for all URLs.',
);
}
return normalizeAuditOutputs(allResults, normalizationFlags);
});
}
async function runLighthouseForUrl(
url: string,
flags: LighthouseOptions,
config: Config | undefined,
): Promise<AuditOutputs> {
if (flags.outputPath) {
await ensureDirectoryExists(path.dirname(flags.outputPath));
}
const runnerResult: unknown = await runLighthouse(url, flags, config);
if (runnerResult == null) {
throw new Error(`Lighthouse did not produce a result for URL: ${url}`);
}
const { lhr } = runnerResult as RunnerResult;
return toAuditOutputs(Object.values(lhr.audits), flags);
}