methods.ts 4.12 KiB
import lighthouse, { LighthouseConfig } from 'lighthouse';
import waitOn from 'wait-on';
import puppeteer from 'puppeteer';
import { Audit, AuditListItem } from './models';
import { persistAudit, retrieveAuditList, retrieveAuditCount } from './db';
import parentLogger from '../../logger';
import { DbConnectionType } from '../../db';
import { InvalidRequestError } from '../../errors';
import { listResponseFactory } from '../listHelpers';
const DEFAULT_UP_TIMEOUT = 180000;
const DEFAULT_CHROME_PORT = 9222;
const DEFAULT_CHROME_PATH = process.env.CHROME_PATH;
const HTTP_RE = /^https?:\/\//;
export {
  retrieveAuditById as getAudit,
  deleteAuditById as deleteAudit,
} from './db';
export interface AuditOptions {
  awaitAuditCompleted?: boolean;
  upTimeout?: number;
  chromePort?: number;
  chromePath?: string;
  lighthouseConfig?: LighthouseConfig;
/**
 * trigger the audit, storing it as an in-progress row in the db, and running the
 * actual audit non-blocking in the background.
 * @param url: string
 * @param conn: DbConnection
 * @param options: AuditOptions
 * @returns Promise<Audit>
export async function triggerAudit(
  conn: DbConnectionType,
  url: string,
  options: AuditOptions = {},
): Promise<Audit> {
  if (!url)
    throw new InvalidRequestError(
      'No URL provided. URL is required for auditing.',
  if (!HTTP_RE.test(url))
    throw new InvalidRequestError(
      `URL "${url}" does not contain a protocol (http or https).`,
  const audit = Audit.buildForUrl(url);
  await persistAudit(conn, audit);
  if (options.awaitAuditCompleted) {
    await runAudit(audit, options);
    await persistAudit(conn, audit);
  } else {
    // run in background
    runAudit(audit, options).then(() => persistAudit(conn, audit));
  return audit;
/**
 * trigger the audit, storing it as an in-progress row in the db, and running the
 * actual audit non-blocking in the background.