browser-commander 0.16.0

Universal browser automation library that supports multiple browser engines with a unified API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import readline from "node:readline";

let engineName = null;
let browser = null;
let context = null;
let page = null;
let verbose = false;

const rl = readline.createInterface({
  input: process.stdin,
  crlfDelay: Infinity,
});

function log(message) {
  if (verbose) {
    console.error(`[browser-commander:${engineName ?? "bridge"}] ${message}`);
  }
}

function serializeResult(value) {
  return value === undefined ? null : value;
}

function compactObject(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return value;
  }

  const entries = Object.entries(value)
    .filter(([, entryValue]) => entryValue !== null && entryValue !== undefined)
    .map(([key, entryValue]) => [key, compactObject(entryValue)])
    .filter(([, entryValue]) => {
      return (
        !entryValue ||
        typeof entryValue !== "object" ||
        Array.isArray(entryValue) ||
        Object.keys(entryValue).length > 0
      );
    });

  return Object.fromEntries(entries);
}

function send(response) {
  process.stdout.write(`${JSON.stringify(response)}\n`);
}

function ensurePage() {
  if (!page) {
    throw new Error("Browser page is not initialized. Send launch or connect first.");
  }
  return page;
}

function chromeArgs(params) {
  const args = [...(params.args ?? [])];
  if (params.sandbox === false) {
    for (const flag of ["--no-sandbox", "--disable-setuid-sandbox"]) {
      if (!args.includes(flag)) {
        args.push(flag);
      }
    }
  }
  return args;
}

// The Rust side already merged the caller's exclusions with the ones
// fingerprint parity needs, so this bridge forwards the list verbatim. Adding
// "--enable-automation" here would override a caller who deliberately turned
// parity off.
function ignoredDefaultArgs(params) {
  if (params.ignoreDefaultArgs === true) {
    return true;
  }
  return [...(params.ignoreDefaultArgs ?? [])];
}

// The environment the browser process gets: the bridge's own, plus the
// restrictions' variables and the caller's. The bridge's process.env is never
// modified, so nothing leaks into later launches.
function browserEnv(params) {
  if (params.env === null || params.env === undefined) {
    return undefined;
  }
  return { ...process.env, ...params.env };
}

// A fresh profile can open a tab (What's New, a welcome page) that takes the
// foreground after startup, so the tab the person would be looking at wins
// over the first one in creation order.
async function pickForegroundPage(pages) {
  for (const candidate of pages) {
    try {
      const state = await candidate.evaluate(() => document.visibilityState);
      if (state === "visible") {
        return candidate;
      }
    } catch (error) {
      log(`visibilityState failed: ${error.message}`);
    }
  }
  return pages[0];
}

function elementInfo(selector) {
  const el = document.querySelector(selector);
  if (!el) {
    return null;
  }

  const rect = el.getBoundingClientRect();
  const style = window.getComputedStyle(el);
  const isVisible =
    style.display !== "none" &&
    style.visibility !== "hidden" &&
    rect.width > 0 &&
    rect.height > 0;

  return {
    tagName: el.tagName,
    textContent: el.textContent,
    isVisible,
    isEnabled: !el.disabled,
    boundingBox: isVisible ? [rect.x, rect.y, rect.width, rect.height] : null,
  };
}

async function launchPlaywright(params) {
  const { chromium } = await import("playwright");
  const contextOptions = {
    headless: params.headless,
    slowMo: params.slowMo,
    chromiumSandbox: params.sandbox !== false,
    viewport: null,
    args: chromeArgs(params),
    ignoreDefaultArgs: ignoredDefaultArgs(params),
  };

  if (params.colorScheme !== null && params.colorScheme !== undefined) {
    contextOptions.colorScheme = params.colorScheme;
  }
  if (params.channel !== null && params.channel !== undefined) {
    contextOptions.channel = params.channel;
  }
  if (params.executablePath !== null && params.executablePath !== undefined) {
    contextOptions.executablePath = params.executablePath;
  }
  const env = browserEnv(params);
  if (env !== undefined) {
    contextOptions.env = env;
  }

  context = await chromium.launchPersistentContext(
    params.userDataDir,
    contextOptions,
  );
  const pages = context.pages();
  page = pages[0] ?? (await context.newPage());
  browser = context;
}

async function launchPuppeteer(params) {
  const puppeteer = await import("puppeteer");
  const launchOptions = {
    headless: params.headless,
    slowMo: params.slowMo,
    defaultViewport: null,
    args: chromeArgs(params),
    userDataDir: params.userDataDir,
  };
  const env = browserEnv(params);
  if (env !== undefined) {
    launchOptions.env = env;
  }
  const ignoredArgs = ignoredDefaultArgs(params);
  if (ignoredArgs === true || ignoredArgs.length > 0) {
    launchOptions.ignoreDefaultArgs = ignoredArgs;
  }
  if (params.channel !== null && params.channel !== undefined) {
    launchOptions.channel = params.channel;
  }
  if (params.executablePath !== null && params.executablePath !== undefined) {
    launchOptions.executablePath = params.executablePath;
  }
  browser = await puppeteer.default.launch(launchOptions);
  const pages = await browser.pages();
  page = pages[0] ?? (await browser.newPage());

  if (params.colorScheme !== null && params.colorScheme !== undefined) {
    await applyColorScheme(params.colorScheme);
  }
}

async function connectPlaywright(params) {
  const { chromium } = await import("playwright");
  browser = await chromium.connectOverCDP(
    params.cdpEndpoint ?? params.wsEndpoint,
    compactObject({
      slowMo: params.slowMo,
      timeout: params.timeout,
    }),
  );
  context = browser.contexts()[0];
  if (!context) {
    throw new Error("Connected browser did not expose a default context");
  }
  const pages = context.pages();
  page = (await pickForegroundPage(pages)) ?? (await context.newPage());
  if (params.seedCookies?.length) {
    await context.addCookies(params.seedCookies);
  }
}

async function connectPuppeteer(params) {
  const puppeteer = await import("puppeteer");
  browser = await puppeteer.default.connect({
    ...compactObject({
      browserURL: params.cdpEndpoint,
      browserWSEndpoint: params.wsEndpoint,
      slowMo: params.slowMo,
      protocolTimeout: params.protocolTimeout,
    }),
    // Null disables Puppeteer's viewport emulation and must survive compaction.
    defaultViewport: null,
  });
  const pages = await browser.pages();
  page = (await pickForegroundPage(pages)) ?? (await browser.newPage());
  if (params.seedCookies?.length) {
    await page.setCookie(...params.seedCookies);
  }
}

async function applyColorScheme(colorScheme) {
  const currentPage = ensurePage();
  if (engineName === "playwright") {
    await currentPage.emulateMedia({ colorScheme });
  } else {
    await currentPage.emulateMediaFeatures(
      colorScheme === null
        ? []
        : [{ name: "prefers-color-scheme", value: colorScheme }],
    );
  }
}

function restoreOriginLocalStorage(origins) {
  const entry = origins.find(
    (item) => item.origin === globalThis.location.origin,
  );
  if (!entry) return;
  for (const item of entry.localStorage) {
    globalThis.localStorage.setItem(item.name, item.value);
  }
}

async function restoreStorageState(state) {
  const cookies = state.cookies ?? [];
  const origins = state.origins ?? [];
  if (engineName === "playwright") {
    if (cookies.length) await context.addCookies(cookies);
    if (origins.length) {
      await context.addInitScript(restoreOriginLocalStorage, origins);
      await Promise.all(
        context.pages().map((current) =>
          current.evaluate(restoreOriginLocalStorage, origins),
        ),
      );
    }
  } else {
    if (cookies.length) await page.setCookie(...cookies);
    if (origins.length) {
      await page.evaluateOnNewDocument(restoreOriginLocalStorage, origins);
      await page.evaluate(restoreOriginLocalStorage, origins);
    }
  }
}

async function exportStorageState() {
  if (engineName === "playwright") return context.storageState();
  const cookies = await page.cookies();
  const origin = new URL(page.url()).origin;
  const origins = [];
  if (origin !== "null") {
    const localStorage = await page.evaluate(() =>
      Array.from({ length: globalThis.localStorage.length }, (_, index) => {
        const name = globalThis.localStorage.key(index);
        return { name, value: globalThis.localStorage.getItem(name) };
      }),
    );
    origins.push({ origin, localStorage });
  }
  return { cookies, origins };
}

async function handleLaunch(params) {
  engineName = params.engine;
  verbose = Boolean(params.verbose);

  if (engineName === "playwright") {
    await launchPlaywright(params);
  } else if (engineName === "puppeteer") {
    await launchPuppeteer(params);
  } else {
    throw new Error(`Unsupported bridge engine: ${engineName}`);
  }

  try {
    await page.bringToFront();
  } catch (error) {
    log(`bringToFront failed: ${error.message}`);
  }

  return { engine: engineName };
}

async function handleConnect(params) {
  engineName = params.engine;
  verbose = Boolean(params.verbose);

  if (engineName === "playwright") {
    await connectPlaywright(params);
  } else if (engineName === "puppeteer") {
    await connectPuppeteer(params);
  } else {
    throw new Error(`Unsupported bridge engine: ${engineName}`);
  }

  if (params.colorScheme !== null && params.colorScheme !== undefined) {
    try {
      await applyColorScheme(params.colorScheme);
    } catch (error) {
      log(`colorScheme failed: ${error.message}`);
    }
  }

  try {
    await page.bringToFront();
  } catch (error) {
    log(`bringToFront failed: ${error.message}`);
  }

  return { engine: engineName };
}

async function handleCommand(method, params) {
  switch (method) {
    case "launch":
      return await handleLaunch(params);
    case "connect":
      return await handleConnect(params);
    case "restoreStorageState":
      await restoreStorageState(params.state);
      return null;
    case "exportStorageState":
      return await exportStorageState();
    case "close":
      if (browser) {
        await browser.close();
      }
      return null;
    case "url":
      return ensurePage().url();
    case "goto":
      await ensurePage().goto(params.url, { waitUntil: "load" });
      return null;
    case "querySelector":
      return await ensurePage().evaluate(elementInfo, params.selector);
    case "querySelectorAll":
      return await ensurePage().evaluate((selector) => {
        return Array.from(document.querySelectorAll(selector), (el) => {
          const rect = el.getBoundingClientRect();
          const style = window.getComputedStyle(el);
          const isVisible =
            style.display !== "none" &&
            style.visibility !== "hidden" &&
            rect.width > 0 &&
            rect.height > 0;

          return {
            tagName: el.tagName,
            textContent: el.textContent,
            isVisible,
            isEnabled: !el.disabled,
            boundingBox: isVisible
              ? [rect.x, rect.y, rect.width, rect.height]
              : null,
          };
        });
      }, params.selector);
    case "count":
      return await ensurePage().evaluate(
        (selector) => document.querySelectorAll(selector).length,
        params.selector,
      );
    case "click":
      await ensurePage().click(params.selector);
      return null;
    case "fill":
      if (engineName === "playwright") {
        await ensurePage().fill(params.selector, params.text);
      } else {
        await ensurePage().$eval(
          params.selector,
          (el, text) => {
            el.value = text;
            el.dispatchEvent(new Event("input", { bubbles: true }));
            el.dispatchEvent(new Event("change", { bubbles: true }));
          },
          params.text,
        );
      }
      return null;
    case "typeText":
      await ensurePage().focus(params.selector);
      await ensurePage().keyboard.type(params.text);
      return null;
    case "textContent":
      return await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        return el ? el.textContent : null;
      }, params.selector);
    case "inputValue":
      return await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        return el && "value" in el ? el.value : null;
      }, params.selector);
    case "getAttribute":
      return await ensurePage().evaluate(
        ({ selector, attribute }) => {
          const el = document.querySelector(selector);
          return el ? el.getAttribute(attribute) : null;
        },
        { selector: params.selector, attribute: params.attribute },
      );
    case "isVisible":
      return Boolean(
        (await ensurePage().evaluate(elementInfo, params.selector))?.isVisible,
      );
    case "isEnabled":
      return await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        return el ? !el.disabled : false;
      }, params.selector);
    case "waitForSelector":
      if (engineName === "playwright") {
        await ensurePage().waitForSelector(params.selector, {
          state: "visible",
          timeout: params.timeoutMs,
        });
      } else {
        await ensurePage().waitForSelector(params.selector, {
          visible: true,
          timeout: params.timeoutMs,
        });
      }
      return null;
    case "scrollIntoView":
      await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        if (!el) {
          throw new Error(`Element not found: ${selector}`);
        }
        el.scrollIntoView({ block: "center", inline: "center" });
      }, params.selector);
      return null;
    case "readBrowserVersionPage": {
      const versionPage = await (context ?? browser).newPage();
      try {
        await versionPage.goto("chrome://version");
        const ready = () => document.getElementById("command_line")?.textContent;
        if (engineName === "playwright") {
          await versionPage.waitForFunction(ready, null, { timeout: 10000 });
        } else {
          await versionPage.waitForFunction(ready, { timeout: 10000 });
        }
        return await versionPage.evaluate(params.script);
      } finally {
        await versionPage.close();
      }
    }
    case "evaluate":
      return serializeResult(await ensurePage().evaluate(params.script));
    case "screenshot":
      return Buffer.from(await ensurePage().screenshot()).toString("base64");
    case "pdf":
      return Buffer.from(
        await ensurePage().pdf(compactObject(params)),
      ).toString("base64");
    case "bringToFront":
      await ensurePage().bringToFront();
      return null;
    case "waitForNavigation":
      if (engineName === "playwright") {
        await ensurePage().waitForLoadState("load", {
          timeout: params.timeoutMs,
        });
      } else {
        await ensurePage().waitForNavigation({
          timeout: params.timeoutMs,
          waitUntil: "load",
        });
      }
      return null;
    case "keyboardPress":
      await ensurePage().keyboard.press(params.key);
      return null;
    case "keyboardType":
      await ensurePage().keyboard.type(params.text);
      return null;
    case "keyboardDown":
      await ensurePage().keyboard.down(params.key);
      return null;
    case "keyboardUp":
      await ensurePage().keyboard.up(params.key);
      return null;
    default:
      throw new Error(`Unknown bridge method: ${method}`);
  }
}

rl.on("line", async (line) => {
  let request;
  try {
    request = JSON.parse(line);
    const result = await handleCommand(request.method, request.params ?? {});
    send({ id: request.id, ok: true, result: serializeResult(result) });
  } catch (error) {
    send({
      id: request?.id ?? 0,
      ok: false,
      error: error?.stack ?? error?.message ?? String(error),
    });
  }
});

process.on("SIGTERM", async () => {
  try {
    if (browser) {
      await browser.close();
    }
  } finally {
    process.exit(0);
  }
});