launchChromium

tcmts.cli.shot.launchChromium · #4dqjataq · function · runs on the server

uses node:url

Headless Chromium, through the Playwright tcm ships: the Chrome installed, as tcm's browser tests use; else Playwright's own Chromium, which its installer downloads the first time there's neither.

import type { ShotBrowser } from "#codebase/tcmts/cli/shot";
import { dim } from "#codebase/tcmts/cli/style";
import { UsageError } from "#codebase/tcmts/cli/ui";
import { shippedPackage } from "#codebase/tcmts/loader/packages";
import { spawnSync } from "node:child_process";
import path from "node:path";
import { pathToFileURL } from "node:url";

export async function launchChromium(): Promise<ShotBrowser> {
  const own = shippedPackage("playwright");
  if (!own)
    throw new UsageError(
      "this tcm has no Playwright beside it: a tcm installed from its package does",
    );
  const mod = (await import(pathToFileURL(path.join(own.dir, "index.mjs")).href)) as {
    chromium?: { launch(o: Record<string, unknown>): Promise<ShotBrowser> };
    default?: { chromium: { launch(o: Record<string, unknown>): Promise<ShotBrowser> } };
  };
  const chromium = (mod.chromium ?? mod.default!.chromium)!;
  for (const o of [{ channel: "chrome" }, {}]) {
    try {
      return await chromium.launch({ headless: true, ...o });
    } catch {
      // (the next way)
    }
  }
  console.error(dim("no Chrome here: getting Playwright's Chromium (once)…"));
  const got = spawnSync(process.execPath, [path.join(own.dir, "cli.js"), "install", "chromium"], {
    encoding: "utf8",
  });
  if (got.status !== 0)
    throw new Error(
      `couldn't get Chromium (playwright install chromium):\n${got.stdout}${got.stderr}`,
    );
  return chromium.launch({ headless: true });
}

uses

used by