|
| 1 | +import { |
| 2 | + type Config, |
| 3 | + type IcuMessage, |
| 4 | + Audit as LHAudit, |
| 5 | + defaultConfig, |
| 6 | +} from 'lighthouse'; |
| 7 | +import { Audit, Group } from '@code-pushup/models'; |
| 8 | + |
| 9 | +export const LIGHTHOUSE_PLUGIN_SLUG = 'lighthouse'; |
| 10 | +export const LIGHTHOUSE_REPORT_NAME = 'lighthouse-report.json'; |
| 11 | + |
| 12 | +const { audits, categories } = defaultConfig; |
| 13 | + |
| 14 | +export const GROUPS: Group[] = Object.entries(categories ?? {}).map( |
| 15 | + ([id, category]) => ({ |
| 16 | + slug: id, |
| 17 | + title: getMetaString(category.title), |
| 18 | + ...(category.description && { |
| 19 | + description: getMetaString(category.description), |
| 20 | + }), |
| 21 | + refs: category.auditRefs.map(ref => ({ slug: ref.id, weight: ref.weight })), |
| 22 | + }), |
| 23 | +); |
| 24 | + |
| 25 | +export const AUDITS: Audit[] = await Promise.all( |
| 26 | + (audits ?? []).map(async value => { |
| 27 | + const audit = await loadLighthouseAudit(value); |
| 28 | + return { |
| 29 | + slug: audit.meta.id, |
| 30 | + title: getMetaString(audit.meta.title), |
| 31 | + description: getMetaString(audit.meta.description), |
| 32 | + }; |
| 33 | + }), |
| 34 | +); |
| 35 | + |
| 36 | +function getMetaString(value: string | IcuMessage): string { |
| 37 | + if (typeof value === 'string') { |
| 38 | + return value; |
| 39 | + } |
| 40 | + return value.formattedDefault; |
| 41 | +} |
| 42 | + |
| 43 | +async function loadLighthouseAudit( |
| 44 | + value: Config.AuditJson, |
| 45 | +): Promise<typeof LHAudit> { |
| 46 | + // the passed value directly includes the implementation as JS object |
| 47 | + // shape: { implementation: typeof LHAudit; options?: {}; } |
| 48 | + if (typeof value === 'object' && 'implementation' in value) { |
| 49 | + return value.implementation; |
| 50 | + } |
| 51 | + // the passed value is a `LH.Audit` class instance |
| 52 | + // shape: LHAudit |
| 53 | + if (typeof value === 'function') { |
| 54 | + return value; |
| 55 | + } |
| 56 | + // the passed value is the path directly |
| 57 | + // shape: string |
| 58 | + // otherwise it is a JS object maintaining a `path` property |
| 59 | + // shape: { path: string, options?: {}; } |
| 60 | + const path = typeof value === 'string' ? value : value.path; |
| 61 | + const module = (await import(`lighthouse/core/audits/${path}.js`)) as { |
| 62 | + default: typeof LHAudit; |
| 63 | + }; |
| 64 | + return module.default; |
| 65 | +} |
0 commit comments