Node.js library

Everything the brokit command does is also a Node.js library: start Chrome, open pages, give them real input, read from them, take screenshots, run scenarios, compare images. The command is built from these same functions, so what works in a scenario works from a script.

brokit is an ES module with no dependencies. It needs Node.js 22.4 or newer and a Chrome, Chromium or Edge (see Chrome). Import what you need:

JavaScript
import { launch, serve, runScenario, diffImages } from 'brokit';

Use the library when a check needs more than a scenario file gives: your own test runner, a script that makes screenshots for a README, an agent's tool. For checks that only need some logic, a JS scenario is simpler: brokit check runs it, with baselines and reports.

A first script#

This serves a folder, opens its page, signs in, reads the greeting and saves a screenshot:

JavaScript
import { writeFile } from 'node:fs/promises';
import { launch, serve } from 'brokit';

const server = await serve('public'); // or use your dev server's URL
const browser = await launch();
try {
  const page = await browser.newPage({ size: '1280x800' });
  await page.goto(server.url, { ready: "document.readyState === 'complete'" });
  await page.click({ selector: '#email' });
  await page.type('ana@example.com');
  await page.key('Enter');
  await page.waitFor("document.querySelector('#greeting').textContent !== ''");
  const greeting = await page.eval("document.querySelector('#greeting').textContent");
  console.log(greeting); // Welcome, ana@example.com
  const { png } = await page.screenshot();
  await writeFile('signed-in.png', png);
} finally {
  await browser.close();
  await server.close();
}

Close the browser in a finally: it ends Chrome and removes its throwaway profile. Until it's closed, Chrome keeps your script running. If the script throws or calls process.exit() first, brokit still kills the Chrome it started as the process exits.

launch and Browser#

launch(options)#

launch(options) starts a headless Chrome and resolves to a Browser. All options are optional:

OptionDefaultWhat it is
chromethe one brokit choosesthe path to a browser
gpu'default'how Chrome draws: 'default', 'software' (the same pixels on every machine) or 'hardware'; see GPU_MODES
jsFlagsnullV8 flags, as one string: '--expose-gc --max-old-space-size=512'
chromeFlags[]more Chrome flags, as a list
profilea throwaway foldera profile folder to use and keep
transport'pipe''pipe', or 'port' for a browser build that can't talk over a pipe (also set by BROKIT_CHROME_TRANSPORT)
startTimeout20000ms to wait for Chrome to answer
JavaScript
const browser = await launch({ gpu: 'software' });

Chrome runs headless, with its sandbox on, and talks to brokit over a pipe, so no other program can connect to it. Flags must look like flags (--name or --name=value, no spaces); --no-sandbox, --remote-debugging-* and --user-data-dir are refused.

launch throws when:

browser.newPage(options)#

Opens a tab at about:blank and resolves to a Page. Then call page.goto(url).

OptionDefaultWhat it is
size'1280x800'the viewport in CSS pixels: '393x852' or [393, 852]
dpr1device pixels per CSS pixel, from 0 to 10
mobilefalsea phone: a mobile viewport, touch, no scrollbars
colorSchemeChrome's'light' or 'dark', as prefers-color-scheme sees it
reducedMotionChrome's'reduce' or 'no-preference', as prefers-reduced-motion sees it
JavaScript
const phone = await browser.newPage({ size: '393x852', dpr: 3, mobile: true, colorScheme: 'dark' });

One page at a time is a tab in Chrome's window. A page opened while another is open gets a window of its own, so both keep drawing frames (Chrome gives a tab behind another none). Windows cost more, so close a page when you're done with it.

Other Browser members#

Page#

A Page is a tab. You get one from browser.newPage(). Every step a scenario can have is a method here, with the same names and options, plus a few for reading the page. Every method is async.

MethodDoes
goto(url, options)opens a URL and waits until the page is ready
eval(expression, options)evaluates JS in the page; its value
title()document.title
rect(selector)where an element is: { x, y, width, height }
point(p)a point as [x, y]
move(p)moves the mouse
click(p, options)clicks: button, count, modifiers
dblclick(p, modifiers)double-clicks
drag(from, to, options)presses, moves in steps, releases
wheel(p, options)turns the wheel: dy, dx
key(spec, modifiers)presses a key: 'Enter', 'Ctrl+Shift+Z'
type(text, options)types text at once, or a key per character
ime(text, caret)an input method composing text
tap(p)a finger tap
swipe(from, to, options)a finger drag, then lifted
emulate(options)changes the screen: size, dpr, mobile, scale, color scheme, motion
safeArea([top, right, bottom, left])a phone's notch and bars
wait(ms)waits that many ms
frames(n)waits for the page's next frames
waitFor(expression, options)waits until an expression is truthy
still(options)waits until nothing is animating or scrolling
screenshot(options)a PNG of the viewport, an element, the whole page or the page's own pixels
startProfile(), stopProfile()samples the page's main thread
send(method, params, timeout)a raw DevTools Protocol call
close()closes the tab

Two steps have no method of their own: expect (in a script, check values yourself, or run it with runStep) and a screenshot's baseline (see Baselines).

After each input (mouse, wheel, key, typing, input method, touch, safe area) the page gets a frame before the method resolves, so the next call sees what the input changed. Set page.settle = false to skip that wait.

Points#

Every method that takes a point p takes any of:

They're the same points as in steps. A selector that matches nothing, or an element with no size (hidden), throws.

JavaScript
await page.click([200, 120]);
await page.click({ selector: '#go' });
await page.click({ selector: '#chart', offset: [10, 20] });
await page.move('[innerWidth / 2, 100]');
console.log(await page.point({ selector: '#go' })); // [ 285.46, 73.59 ]

goto#

page.goto(url, options) opens url and waits until the page is ready:

OptionDefaultReady when
readythis expression is truthy (awaited if it's a promise)
readyTitledocument.title is this
(neither)the load event, then no network requests for idle ms; a page whose network never goes quiet is taken as ready 5 s after load
idle500ms of no network requests, without ready or readyTitle
timeout30000ms before it gives up and throws

Either way it then waits for the page's fonts and two frames, so what's on screen is the page as it settled. It resolves to { by, ms, note? }: how it knew the page was ready, how long it took, and a note when the network never went quiet.

JavaScript
const ready = await page.goto('http://localhost:3000/', { ready: 'window.app?.ready' });
console.log(ready); // { by: 'ready: window.app?.ready', ms: 123 }

It throws when the page can't be loaded at all (couldn't load ...: net::ERR_CONNECTION_REFUSED) or isn't ready in time (not ready after 30000 ms: ...). An HTTP error such as a 404 doesn't throw: it's added to page.errors.

Note: page.goto opens any URL you give it. The rule that brokit opens only pages on this computer unless you allow a host is in checkUrl, which runScenario and the brokit command apply. Call it yourself for URLs you didn't write.

Reading the page#

JavaScript
const count = await page.eval("document.querySelectorAll('#list div').length");
const header = await page.rect('header');
const user = await page.eval('fetch("/user.json").then((r) => r.json())');

eval takes an expression, not a function. To pass values in, put them in the string with JSON.stringify:

JavaScript
const name = 'ana@example.com';
await page.eval(`document.querySelector('#email').value = ${JSON.stringify(name)}`);

Mouse#

JavaScript
await page.click({ selector: '#go' }, { button: 'right' });
await page.click({ selector: '#email' }, { count: 3 }); // a triple click
await page.drag([100, 300], [400, 300], { steps: 20, shift: true });
await page.wheel({ selector: '#list' }, { dy: 300 });

Keyboard and text#

page.key(spec, { shift, ctrl, alt, meta }) presses and releases a key, holding any modifiers. spec is a character ('a', 'A', 'é'), a key name ('Enter', 'Tab', 'Escape', 'ArrowUp', 'PageDown', 'F5', in any case; also Esc, Del, Up, Down, Left, Right, Space, Return), or a combination: 'Ctrl+Shift+Z', 'Shift+Tab', 'Alt+F4'. 'Mod+a' is Cmd+A on macOS and Ctrl+A elsewhere. Keys are those of a US keyboard; a key name brokit doesn't know throws.

page.type(text, { perKey }) types text. By default it goes in as one insertion, as a paste or an input method's commit does: an input event, no key events. With perKey: true it presses a key for each character ('\n' presses Enter).

page.ime(text, caret) is an input method composing text, shown underlined and not yet committed, with the caret at caret characters (default: the end). Commit it with type, cancel it with ime('').

JavaScript
await page.click({ selector: '#email' });
await page.type('ana@example.com');
await page.key('Mod+a');
await page.key('Backspace');
await page.type('ana', { perKey: true });
await page.ime('かな');
await page.type('仮名'); // commits
await page.key('Tab', { shift: true });

Touch#

Touch works on any page; a mobile page has it from the start.

JavaScript
await page.tap({ selector: '#go' });
await page.swipe({ selector: '#list' }, [200, 100], { ms: 300 });

Screen#

page.emulate(options) changes the screen as DevTools' device mode does. What you leave out stays as it was.

OptionWhat it is
size'393x852' or [393, 852]
dprdevice pixels per CSS pixel, from 0 to 10
mobilea phone: mobile viewport, touch, no scrollbars
scalethe page drawn smaller, as device mode's "fit to window" (0 to 10)
colorScheme'light' or 'dark'
reducedMotion'reduce' or 'no-preference'
JavaScript
await page.emulate({ size: '393x852', dpr: 3, mobile: true });
await page.emulate({ colorScheme: 'dark' });
console.log(page.viewport); // { width: 393, height: 852, dpr: 3, mobile: true }

page.viewport is the current screen: { width, height, dpr, mobile }.

page.safeArea([top, right, bottom, left]) sets a phone's notch and bars in CSS pixels, as env(safe-area-inset-*) sees them. The page needs viewport-fit=cover in its viewport meta tag, as on a real phone.

JavaScript
await page.safeArea([47, 0, 34, 0]);

Waiting#

JavaScript
await page.click({ selector: '#go' });
await page.waitFor("document.querySelector('#greeting').textContent !== ''", { timeout: 5000 });
await page.frames(2);
const { moving, endless } = await page.still();

still can't see motion a page draws in its own requestAnimationFrame loop, or motion inside iframes; wait for those with waitFor.

screenshot#

page.screenshot(options) resolves to { png, width, height }: the PNG file's bytes (a Buffer) and its size in device pixels. It saves nothing; write png to a file if you want one.

OptionDefaultWhat it takes
(none)the viewport, as the browser shows it
selectorjust that element (from beyond the viewport if it reaches outside it)
fullPagefalsethe whole page, beyond the viewport
scale1drawn that much smaller or larger: 0.5, or 1 / 3 for a 3x phone seen at 1x
stilltruewaits until the page is still first (see still()); false takes it at once; a number waits at most that many ms
fromwhat the page itself gives (see below); taken at once
JavaScript
import { writeFile } from 'node:fs/promises';

const shot = await page.screenshot();
await writeFile('page.png', shot.png);
const { png, width, height } = await page.screenshot({ selector: 'header', scale: 0.5 });
const whole = await page.screenshot({ fullPage: true });

The wait for stillness costs nothing on a page that's already still: brokit looks before the shot, watches while it's taken, and only waits and takes it again if something moved. When it waited, the result also has moving (what still moved when the time ran out) and, whenever there are any, endless (animations that never end), as lists of descriptions.

A page taller than Chrome draws at once (8192 device pixels) is captured in strips and joined; one wider than that, beyond the viewport, throws.

The page's own pixels. With from, the screenshot is what an expression in the page gives: a canvas, an OffscreenCanvas, ImageData, a PNG data URL, or { width, height, base64 } of RGBA pixels. That's the canvas's own pixels, at its own size, whatever the screen. A WebGL canvas reads back empty unless it was made with preserveDrawingBuffer: true; take one with selector instead.

JavaScript
const chart = await page.screenshot({ from: "document.querySelector('#chart')" });
console.log(chart.width, chart.height); // 120 60

Profiling#

page.startProfile() starts sampling the page's main thread (every 100 µs); page.stopProfile() stops and resolves to the profile, an object you can save as a .cpuprofile file and open in Chrome DevTools' Performance panel.

JavaScript
import { writeFile } from 'node:fs/promises';

await page.startProfile();
await page.click({ selector: '#go' });
await writeFile('click.cpuprofile', JSON.stringify(await page.stopProfile()));

Raw protocol calls#

page.send(method, params, timeout) sends any Chrome DevTools Protocol call to this page and resolves to its result. It's for what brokit has no method for. timeout is in ms (default 30000); an error from Chrome rejects with its message.

JavaScript
await page.send('Emulation.setTimezoneOverride', { timezoneId: 'Asia/Tokyo' });
const { cssContentSize } = await page.send('Page.getLayoutMetrics');

Calls on the browser rather than a page go through browser.connection.send(method, params).

Console and errors#

A page keeps what it logged and what went wrong, from the moment it was opened:

Both keep at most 1000 entries, and they aren't cleared by goto. page.close() closes the tab.

JavaScript
await page.goto(url);
if (page.errors.length) throw new Error(page.errors.join('\n'));
for (const { type, text } of page.console) console.log(type, text);

Running scenarios#

A scenario is a page, its screen and its steps, as a JSON object. These functions run one, check one, and find and load scenario files, as brokit run and brokit check do.

runScenario#

runScenario(browser, scenario, options) opens the scenario's page in a new tab, waits until it's ready, runs its steps (or its run function), closes the tab, and resolves to what happened. It doesn't throw when the page fails; look at result.ok. It throws only for a scenario that isn't valid or a URL that isn't allowed (see checkUrl).

OptionDefaultWhat it is
basewhat a relative url is resolved against, such as server.url
allowHosts[]hosts not on this computer that may be opened
outDir'brokit-out'where screenshot steps save their images (name.png)
timeout30000ms to be ready, when the scenario gives none
baselines{ dir, update }: where baseline screenshots are, and what to write; see Baselines
filethe scenario's file, so a JS scenario's error says which line it came from
screenshota file for a screenshot of the viewport after the last step
cpuProfilea file for a profile of the page's main thread, the whole run
onReadycalled with goto's result when the page is ready
onStepcalled with each step's entry as it finishes
JavaScript
import { launch, serve, runScenario } from 'brokit';

const server = await serve('public');
const browser = await launch({ gpu: 'software' });
try {
  const result = await runScenario(
    browser,
    {
      url: '/',
      viewport: { size: '393x852', dpr: 3, mobile: true },
      ready: 'window.app?.ready',
      steps: [
        { tap: { selector: '#email' } },
        { type: 'ana@example.com' },
        { key: 'Enter' },
        { expect: "document.querySelector('#greeting').textContent", equals: 'Welcome, ana@example.com' },
        { screenshot: 'signed-in' },
      ],
    },
    { base: server.url, onStep: (s) => console.log(s.ok ? '✓' : '✗', s.label) },
  );
  console.log(result.ok ? 'passed' : 'FAILED');
} finally {
  await browser.close();
  await server.close();
}

A scenario can have a run function in place of steps. It gets { page, expect, step, screenshot }, as a JS scenario's default export does:

JavaScript
const result = await runScenario(browser, {
  url: '/',
  run: async ({ page, expect, screenshot }) => {
    const header = await page.rect('header');
    expect.atLeast(header.height, 30, 'header height');
    await screenshot('home');
  },
}, { base: server.url });

The result#

Here is the result of a run where one expectation failed:

JSON
{
  "url": "http://127.0.0.1:43983/",
  "ok": false,
  "ms": 713,
  "ready": { "by": "ready: window.app?.ready", "ms": 114 },
  "steps": [
    { "action": "click", "label": "click #email", "ok": true, "ms": 33 },
    {
      "action": "expect",
      "label": "expect document.querySelector('#greeting').textContent equals \"Welcome, x\"",
      "ok": false,
      "value": "Welcome, ana",
      "error": "expected \"Welcome, x\", got \"Welcome, ana\"",
      "ms": 206
    },
    { "action": "eval", "label": "eval document.title", "ok": true, "value": "Sign in", "ms": 1 },
    { "action": "screenshot", "label": "screenshot done", "ok": true, "file": "/home/ana/app/brokit-out/done.png", "size": [1280, 800], "baseline": "new", "ms": 258 }
  ],
  "console": [],
  "errors": [],
  "title": "Sign in",
  "report": "/"
}

A failed action (a click on something that isn't there) stops the steps, since what follows would act on the wrong page. A failed expect or baseline doesn't.

Baselines#

A screenshot step with "baseline": true is compared with baselines.dir/name.png. baselines.update says what may be written:

The brokit command picks 'none' when the CI variable is set. The library doesn't look: pass what you want. Whatever update says, a page with errors (an HTTP error, an uncaught exception) never becomes a baseline. The tolerance is the step's, else the scenario's, else { max: 2 }. When a screenshot differs, its difference image is written next to it in outDir. A screenshot with baseline: true and no baselines option fails.

These help put baselines where brokit check does:

compareBaseline(options) is the comparison itself, for screenshots you take with page.screenshot:

OptionWhat it is
dir, namethe baseline is dir/name.png
pngthe screenshot's bytes
outDirwhere the difference image goes; needed whenever a baseline exists
tolerance, ignoreas in diffImages; no tolerance means pixel-exact
update'missing' (default), 'all' or 'none', as above
unfita reason this screenshot mustn't become a baseline (the page had errors); then nothing is written

It resolves to { status, baseline, diff?, message? }. status is 'match', 'new' (written), 'updated' (replaced), 'missing' or 'differs'; the last two are failures, and message says why.

JavaScript
import { compareBaseline } from 'brokit';

const { png } = await page.screenshot({ selector: 'header' });
const r = await compareBaseline({ dir: 'baselines', name: 'header', png, outDir: 'brokit-out', tolerance: { max: 2 } });
if (r.status === 'differs' || r.status === 'missing') console.log(r.message, r.diff ?? '');

Scenario files#

Note: loadScenario on a .mjs file runs it: it's code, with your permissions. Only load files you trust; see JS scenarios.

A small brokit check of your own:

JavaScript
import { launch, serve, findScenarios, loadScenario, runScenario, baselineDir, scenarioName } from 'brokit';

const server = await serve('public');
const browser = await launch({ gpu: 'software' });
let failed = 0;
try {
  for (const file of await findScenarios(['checks'])) {
    const name = scenarioName(file);
    const result = await runScenario(browser, await loadScenario(file), {
      base: server.url,
      file,
      outDir: `brokit-out/${name}`,
      baselines: { dir: baselineDir(file), update: process.env.CI ? 'none' : 'missing' },
    });
    console.log(result.ok ? '✓' : '✗', name, `${result.ms} ms`);
    for (const s of result.steps) if (!s.ok) console.log('   ', s.label, '→', s.error);
    for (const e of result.errors) console.log('   ', e);
    if (!result.ok) failed++;
  }
} finally {
  await browser.close();
  await server.close();
}
process.exitCode = failed ? 1 : 0;

Single steps#

JavaScript
import { writeFile } from 'node:fs/promises';
import { runStep } from 'brokit';

await runStep(page, { drag: [100, 300, 400, 300], steps: 20 });
const { value } = await runStep(page, { expect: "document.querySelectorAll('#list div').length", atLeast: 1 });
const ctx = { save: async (name, png) => (await writeFile(`${name}.png`, png), `${name}.png`) };
await runStep(page, { screenshot: 'list', selector: '#list' }, ctx);

checkUrl#

checkUrl(url, { base, allowHosts }) returns url resolved against base, after checking that brokit may open it: http or https, and on this computer (localhost, 127.0.0.1, [::1], *.localhost) unless its host is in allowHosts. Otherwise it throws: staging.example.com isn't on this computer; allow it with --allow-host staging.example.com.

JavaScript
checkUrl('/form.html', { base: 'http://localhost:5173/' }); // 'http://localhost:5173/form.html'
checkUrl('https://staging.example.com/', { allowHosts: ['staging.example.com'] });

Images#

An image is { width, height, data }, with data a Buffer of 8-bit RGBA pixels, row by row.

A pixel's difference is its largest difference in any channel, alpha included (0 to 255). The tolerance says how much is allowed; every limit given must hold, and none means the images must be identical:

ToleranceHolds when
{ max: 2 }no pixel differs by more than 2
{ mean: 0.5 }the mean difference is at most 0.5
{ '>8': '0.1%' }at most 0.1 % of the pixels differ by more than 8
{ '>0': 20 }at most 20 pixels differ at all

ignore is a list of regions left out, [x, y, width, height] in image pixels.

JavaScript
import { readFile, writeFile } from 'node:fs/promises';
import { decodePng, encodePng, diffImages } from 'brokit';

const before = decodePng(await readFile('before.png'));
const after = decodePng(await readFile('after.png'));
const d = diffImages(before, after, { tolerance: { max: 2 }, ignore: [[0, 0, 200, 40]] });
console.log(d.pass ? 'the same' : d.failures.join('; '));
console.log(d.pixels, `mean ${d.mean}, worst ${d.worst}`);
if (d.image) await writeFile('diff.png', encodePng(d.image));

diffImages returns:

Images of different sizes don't pass; the result then has size, otherSize and failures, and no image.

Serving files#

serve(dir, { port, isolate }) serves a folder on 127.0.0.1 and resolves to { url, port, root, close }:

JavaScript
import { serve } from 'brokit';

const server = await serve('public', { isolate: true });
console.log(`${server.url}index.html`);
await server.close();

Only files inside the folder are served: no .., no symbolic links that lead out, no dotfiles (.env, .git), no directory listings (a folder serves its index.html). Only GET and HEAD, nothing cached, and requests for another host name (a DNS rebinding attack) are refused. isolate: true adds the cross-origin isolation headers that SharedArrayBuffer needs. A folder that doesn't exist throws.

Chrome#

These find, install and check the Chrome brokit uses; Chrome says how brokit chooses one.

JavaScript
import { chooseChrome, installChrome, launch } from 'brokit';

let { path, source, problem } = chooseChrome();
if (!path) {
  console.log(problem);
  ({ path } = await installChrome('stable', {
    onProgress: ({ phase, done, total }) => process.stdout.write(`\r${phase} ${done}/${total}`),
  }));
  source = 'installed just now';
}
console.log(`Chrome at ${path} (${source})`);
const browser = await launch({ chrome: path });
await browser.close();
JavaScript
import { doctor } from 'brokit';

const { ok, checks } = await doctor();
for (const c of checks) console.log(c.status, c.name, c.detail, c.fix ? `→ ${c.fix}` : '');
process.exitCode = ok ? 0 : 1;

Low-level#

These are exported because the rest is built on them. Most scripts never need them.

JavaScript
import { parseKey, parseSize, mismatch } from 'brokit';

parseKey('Ctrl+Shift+Z').modifiers; // 10 (Ctrl 2 + Shift 8)
parseSize('393x852'); // [393, 852]
mismatch('Welcome, ana', { matches: '^Welcome' }); // null
mismatch(58.2, { near: 59, within: 0.5 }); // 'expected 59 ± 0.5, got 58.2'

The exports are listed in index.mjs, and come from chrome.mjs (launch, Browser, Connection), page.mjs (Page), actions.mjs (steps), run.mjs and load.mjs (scenarios), baseline.mjs, png.mjs, diff.mjs, serve.mjs, install.mjs, doctor.mjs.

Edit this page on GitHub