Skill Tracer
Skills › Anatomy › anatomy › chrome-port.mjs

chrome-port.mjs

36 lines · scripts/chrome-port.mjs at 1482e84

1import { rmSync } from "node:fs";
2
3export async function chromePort(chrome, profile) {
4 try {
5 return await new Promise((done, fail) => {
6 let text = "";
7 const clean = () => {
8 clearTimeout(timer);
9 chrome.stderr.off("data", data);
10 chrome.off("error", error);
11 chrome.off("exit", exited);
12 };
13 const error = (cause) => {
14 clean();
15 fail(cause);
16 };
17 const exited = (code, signal) => error(new Error(`Chrome exited before startup: ${code ?? signal}`));
18 const data = (chunk) => {
19 text += chunk;
20 const match = text.match(/DevTools listening on ws:\/\/[^:]+:(\d+)\//);
21 if (match) {
22 clean();
23 done(Number(match[1]));
24 }
25 };
26 const timer = setTimeout(() => error(new Error("Chrome did not start")), 20000);
27 chrome.stderr.on("data", data);
28 chrome.on("error", error);
29 chrome.on("exit", exited);
30 });
31 } catch (error) {
32 chrome.kill("SIGKILL");
33 rmSync(profile, { recursive: true, force: true });
34 throw error;
35 }