@generativereality/browser-automation 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +29 -13
- package/dist/index.js +1713 -472
- package/package.json +7 -3
- package/scripts/windows-guest/README.md +40 -0
- package/scripts/windows-guest/cleanup.ps1 +5 -0
- package/scripts/windows-guest/rawpipe.mjs +16 -0
- package/scripts/windows-guest/run-in-session.ps1 +8 -0
- package/scripts/windows-guest/test.ps1 +59 -0
- package/skills/browser/SKILL.md +79 -43
- package/skills/browser/references/page-recipes.md +13 -22
- package/skills/browser/references/windows.md +7 -6
package/dist/index.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import updateNotifier from "update-notifier";
|
|
3
3
|
import { cli, define } from "gunshi";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { createServer } from "node:net";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { accessSync, appendFileSync, chmodSync, closeSync, constants, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { createConnection, createServer } from "node:net";
|
|
7
7
|
import { homedir, tmpdir } from "node:os";
|
|
8
|
+
import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
8
9
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
9
10
|
import consola, { consola as consola$1 } from "consola";
|
|
10
11
|
import { fileURLToPath } from "node:url";
|
|
11
12
|
//#region package.json
|
|
12
13
|
var name = "@generativereality/browser-automation";
|
|
13
|
-
var version = "0.
|
|
14
|
-
var description = "
|
|
14
|
+
var version = "0.7.1";
|
|
15
|
+
var description = "Let many Claude Code sessions use your own signed-in Chrome at once, each in its own tab, without stealing your screen. Daemonless CLI over per-target CDP: persistent profile and extensions, no MCP server, nothing long-lived to crash.";
|
|
15
16
|
var package_default = {
|
|
16
17
|
name,
|
|
17
18
|
version,
|
|
@@ -40,7 +41,11 @@ var package_default = {
|
|
|
40
41
|
"cdp",
|
|
41
42
|
"chrome-devtools-protocol",
|
|
42
43
|
"playwright-alternative",
|
|
43
|
-
"ai-agents"
|
|
44
|
+
"ai-agents",
|
|
45
|
+
"chrome",
|
|
46
|
+
"claude-code-plugin",
|
|
47
|
+
"parallel-agents",
|
|
48
|
+
"cli"
|
|
44
49
|
],
|
|
45
50
|
author: "motin",
|
|
46
51
|
license: "MIT",
|
|
@@ -256,6 +261,78 @@ function cdpHost() {
|
|
|
256
261
|
return process.env.BROWSER_AUTOMATION_CDP || `http://localhost:${cdpPort()}`;
|
|
257
262
|
}
|
|
258
263
|
/**
|
|
264
|
+
* Pipe or port.
|
|
265
|
+
*
|
|
266
|
+
* The port is reachable by every process on the machine and has no
|
|
267
|
+
* authentication, so anything local could drive this user's signed-in browser.
|
|
268
|
+
* The pipe is not reachable at all except through the broker's socket, which
|
|
269
|
+
* lives in a 0700 directory under ~ and is itself 0600.
|
|
270
|
+
*
|
|
271
|
+
* Port stays only where somebody asked for it: `BROWSER_AUTOMATION_CDP` names one
|
|
272
|
+
* explicitly (a browser somebody else started, the test fakes). It does not
|
|
273
|
+
* apply to a login context, which is always this CLI's own Chrome, on its own
|
|
274
|
+
* broker. Windows and contexts were on the port until 0.7.0.
|
|
275
|
+
*/
|
|
276
|
+
function usesPipe() {
|
|
277
|
+
if (activeContext()) return true;
|
|
278
|
+
return !process.env.BROWSER_AUTOMATION_CDP;
|
|
279
|
+
}
|
|
280
|
+
function baseDir() {
|
|
281
|
+
return process.env.BROWSER_AUTOMATION_HOME || join(homedir(), ".browser-automation");
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* The broker's directory: state file, lock, broker and Chrome logs, and (macOS,
|
|
285
|
+
* Linux) the socket. 0700. A login context's is its own folder, beside its profile.
|
|
286
|
+
*/
|
|
287
|
+
function brokerDir() {
|
|
288
|
+
const ctx = activeContext();
|
|
289
|
+
return ctx ? join(contextsDir(), ctx.name) : baseDir();
|
|
290
|
+
}
|
|
291
|
+
/** The state file a broker writes once it serves: pids, profile, and where it listens. */
|
|
292
|
+
function brokerStatePath(dir = brokerDir()) {
|
|
293
|
+
return join(dir, "broker.json");
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Where the broker for the active Chrome listens.
|
|
297
|
+
*
|
|
298
|
+
* macOS and Linux: a Unix socket in the broker's 0700 directory. Its path is
|
|
299
|
+
* capped at 104 bytes on macOS, and a context's folder can be longer than that
|
|
300
|
+
* allows (a 64-character name), so a long one gets a short socket in a 0700
|
|
301
|
+
* folder of its own, named after the directory it stands for.
|
|
302
|
+
*
|
|
303
|
+
* Windows: a named pipe. Named pipes have no directory to protect them, so the
|
|
304
|
+
* broker picks a random name when it starts and records it in its state file,
|
|
305
|
+
* which only this user can read. Nobody else can guess the name, so nobody can
|
|
306
|
+
* create it first and wait for us to connect, and the pipe's default ACL keeps
|
|
307
|
+
* other accounts from opening it for writing. Measured on Windows 11 ARM64
|
|
308
|
+
* (Node 22, 2026-10-27): full control for this user, SYSTEM and Administrators;
|
|
309
|
+
* Read only for Everyone and Anonymous, which drives nothing: a read-only
|
|
310
|
+
* connection cannot send the line that attaches it, and each connection is its
|
|
311
|
+
* own pipe instance. Before a broker has written its state, this is a name that
|
|
312
|
+
* answers nothing.
|
|
313
|
+
*/
|
|
314
|
+
function socketPath() {
|
|
315
|
+
if (process.env.BROWSER_AUTOMATION_SOCKET && !activeContext()) return process.env.BROWSER_AUTOMATION_SOCKET;
|
|
316
|
+
const dir = brokerDir();
|
|
317
|
+
if (process.platform === "win32") {
|
|
318
|
+
try {
|
|
319
|
+
const st = JSON.parse(readFileSync(brokerStatePath(dir), "utf8"));
|
|
320
|
+
if (typeof st.socket === "string" && st.socket.startsWith("\\\\.\\pipe\\")) return st.socket;
|
|
321
|
+
} catch {}
|
|
322
|
+
return "\\\\.\\pipe\\browser-automation-not-running";
|
|
323
|
+
}
|
|
324
|
+
const p = join(dir, "cdp.sock");
|
|
325
|
+
if (Buffer.byteLength(p) <= 100) return p;
|
|
326
|
+
return join(baseDir(), "sockets", `${createHash("sha256").update(dir).digest("hex").slice(0, 16)}.sock`);
|
|
327
|
+
}
|
|
328
|
+
/** What to call the browser we are driving, in messages. */
|
|
329
|
+
function endpointLabel() {
|
|
330
|
+
return usesPipe() ? `the browser behind ${socketPath()}` : cdpHost();
|
|
331
|
+
}
|
|
332
|
+
/** Endpoints handed around in place of webSocketDebuggerUrl when on the pipe. */
|
|
333
|
+
const PIPE_BROWSER = "pipe:browser";
|
|
334
|
+
const pipePage = (targetId) => `pipe:target:${targetId}`;
|
|
335
|
+
/**
|
|
259
336
|
* Ports for login contexts, decided here like every other port. A block well
|
|
260
337
|
* above the per-user range (BASE_PORT … BASE_PORT+999), so a context can never
|
|
261
338
|
* land on another account's Chrome. The first free one not already given to a
|
|
@@ -283,7 +360,7 @@ async function allocateContextPort(taken) {
|
|
|
283
360
|
var TargetGoneError = class extends Error {
|
|
284
361
|
targetId;
|
|
285
362
|
constructor(targetId) {
|
|
286
|
-
super(`target ${targetId} not found on ${
|
|
363
|
+
super(`target ${targetId} not found on ${endpointLabel()} (tab closed or Chrome restarted)`);
|
|
287
364
|
this.targetId = targetId;
|
|
288
365
|
this.name = "TargetGoneError";
|
|
289
366
|
}
|
|
@@ -294,10 +371,23 @@ async function httpJson(path) {
|
|
|
294
371
|
return await res.json();
|
|
295
372
|
}
|
|
296
373
|
async function browserWsUrl() {
|
|
374
|
+
if (usesPipe()) return PIPE_BROWSER;
|
|
297
375
|
return (await httpJson("/json/version")).webSocketDebuggerUrl;
|
|
298
376
|
}
|
|
377
|
+
/** `Browser.getVersion`, from either transport. Throws when nothing answers. */
|
|
378
|
+
async function browserVersion(timeout = 5e3) {
|
|
379
|
+
if (!usesPipe()) return { product: (await httpJson("/json/version")).Browser };
|
|
380
|
+
return withBrowser((s) => s.send("Browser.getVersion", {}, timeout), timeout);
|
|
381
|
+
}
|
|
299
382
|
async function listTargets() {
|
|
300
|
-
return httpJson("/json/list");
|
|
383
|
+
if (!usesPipe()) return httpJson("/json/list");
|
|
384
|
+
return (await withBrowser((s) => s.send("Target.getTargets"))).targetInfos.filter((t) => t.type !== "browser_ui" && t.type !== "browser").map((t) => ({
|
|
385
|
+
id: t.targetId,
|
|
386
|
+
type: t.type,
|
|
387
|
+
title: t.title,
|
|
388
|
+
url: t.url,
|
|
389
|
+
webSocketDebuggerUrl: pipePage(t.targetId)
|
|
390
|
+
}));
|
|
301
391
|
}
|
|
302
392
|
async function listPageTargets() {
|
|
303
393
|
return (await listTargets()).filter((t) => t.type === "page");
|
|
@@ -306,8 +396,10 @@ async function listPageTargets() {
|
|
|
306
396
|
async function targetWsUrl(targetId) {
|
|
307
397
|
return (await listTargets()).find((t) => t.id === targetId)?.webSocketDebuggerUrl ?? null;
|
|
308
398
|
}
|
|
309
|
-
/** Open a CDP session to an arbitrary webSocketDebuggerUrl (page or browser)
|
|
399
|
+
/** Open a CDP session to an arbitrary webSocketDebuggerUrl (page or browser), or
|
|
400
|
+
* to a `pipe:` endpoint from this module, which goes through the broker. */
|
|
310
401
|
function connect(wsUrl, { timeout = 15e3 } = {}) {
|
|
402
|
+
if (wsUrl.startsWith("pipe:")) return connectPipe(wsUrl, timeout);
|
|
311
403
|
return new Promise((resolve, reject) => {
|
|
312
404
|
const ws = new WebSocket(wsUrl);
|
|
313
405
|
let nextId = 1;
|
|
@@ -378,6 +470,109 @@ function connect(wsUrl, { timeout = 15e3 } = {}) {
|
|
|
378
470
|
});
|
|
379
471
|
});
|
|
380
472
|
}
|
|
473
|
+
/**
|
|
474
|
+
* One connection to the broker, bound to one target (or to the browser).
|
|
475
|
+
*
|
|
476
|
+
* The broker speaks CDP's own JSON, one message per line, after a one-line
|
|
477
|
+
* handshake naming what to attach to. It answers the handshake once the session
|
|
478
|
+
* exists, so a tab that has gone fails here, as a closed tab's WebSocket would.
|
|
479
|
+
*/
|
|
480
|
+
function connectPipe(endpoint, timeout) {
|
|
481
|
+
const attach = endpoint === PIPE_BROWSER ? { attach: "browser" } : {
|
|
482
|
+
attach: "target",
|
|
483
|
+
targetId: endpoint.slice(12)
|
|
484
|
+
};
|
|
485
|
+
return new Promise((resolve, reject) => {
|
|
486
|
+
const sock = createConnection(socketPath());
|
|
487
|
+
let nextId = 1;
|
|
488
|
+
let ready = false;
|
|
489
|
+
let buf = "";
|
|
490
|
+
const pending = /* @__PURE__ */ new Map();
|
|
491
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
492
|
+
const fail = (e) => {
|
|
493
|
+
for (const p of pending.values()) p.reject(e);
|
|
494
|
+
pending.clear();
|
|
495
|
+
};
|
|
496
|
+
const openTimer = setTimeout(() => {
|
|
497
|
+
sock.destroy();
|
|
498
|
+
reject(/* @__PURE__ */ new Error(`CDP connect timeout ${timeout}ms to ${socketPath()}`));
|
|
499
|
+
}, timeout);
|
|
500
|
+
sock.setEncoding("utf8");
|
|
501
|
+
sock.on("connect", () => sock.write(JSON.stringify(attach) + "\n"));
|
|
502
|
+
sock.on("data", (chunk) => {
|
|
503
|
+
buf += chunk;
|
|
504
|
+
let nl;
|
|
505
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
506
|
+
const line = buf.slice(0, nl);
|
|
507
|
+
buf = buf.slice(nl + 1);
|
|
508
|
+
let msg;
|
|
509
|
+
try {
|
|
510
|
+
msg = JSON.parse(line);
|
|
511
|
+
} catch {
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (!ready) {
|
|
515
|
+
clearTimeout(openTimer);
|
|
516
|
+
if (msg.error) {
|
|
517
|
+
sock.destroy();
|
|
518
|
+
reject(new Error(String(msg.error)));
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
ready = true;
|
|
522
|
+
resolve(session);
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (typeof msg.id === "number" && pending.has(msg.id)) {
|
|
526
|
+
const p = pending.get(msg.id);
|
|
527
|
+
pending.delete(msg.id);
|
|
528
|
+
if (msg.error) p.reject(/* @__PURE__ */ new Error(`${p.method}: ${msg.error.message ?? JSON.stringify(msg.error)}`));
|
|
529
|
+
else p.resolve(msg.result);
|
|
530
|
+
} else if (msg.method) for (const cb of listeners.get(msg.method) ?? []) cb(msg.params);
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
sock.on("error", (e) => {
|
|
534
|
+
clearTimeout(openTimer);
|
|
535
|
+
const err = e?.code === "ENOENT" || e?.code === "ECONNREFUSED" ? /* @__PURE__ */ new Error(`no browser on ${socketPath()} — run: browser-automation launch`) : /* @__PURE__ */ new Error(`socket error on ${socketPath()}: ${e?.message ?? e}`);
|
|
536
|
+
if (!ready) reject(err);
|
|
537
|
+
fail(err);
|
|
538
|
+
});
|
|
539
|
+
sock.on("close", () => fail(/* @__PURE__ */ new Error("the browser connection closed (tab closed or Chrome quit)")));
|
|
540
|
+
const session = {
|
|
541
|
+
send(method, params = {}, timeoutMs = 3e4) {
|
|
542
|
+
return new Promise((res, rej) => {
|
|
543
|
+
const id = nextId++;
|
|
544
|
+
const t = setTimeout(() => {
|
|
545
|
+
if (pending.delete(id)) rej(/* @__PURE__ */ new Error(`CDP ${method} timed out after ${timeoutMs}ms`));
|
|
546
|
+
}, timeoutMs);
|
|
547
|
+
pending.set(id, {
|
|
548
|
+
resolve: (v) => {
|
|
549
|
+
clearTimeout(t);
|
|
550
|
+
res(v);
|
|
551
|
+
},
|
|
552
|
+
reject: (e) => {
|
|
553
|
+
clearTimeout(t);
|
|
554
|
+
rej(e);
|
|
555
|
+
},
|
|
556
|
+
method
|
|
557
|
+
});
|
|
558
|
+
sock.write(JSON.stringify({
|
|
559
|
+
id,
|
|
560
|
+
method,
|
|
561
|
+
params
|
|
562
|
+
}) + "\n");
|
|
563
|
+
});
|
|
564
|
+
},
|
|
565
|
+
on(method, cb) {
|
|
566
|
+
const arr = listeners.get(method) ?? [];
|
|
567
|
+
arr.push(cb);
|
|
568
|
+
listeners.set(method, arr);
|
|
569
|
+
},
|
|
570
|
+
close() {
|
|
571
|
+
sock.end();
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
});
|
|
575
|
+
}
|
|
381
576
|
/** Run `fn` against a session bound to a single page target, then close it. */
|
|
382
577
|
async function withPage(targetId, fn) {
|
|
383
578
|
const wsUrl = await targetWsUrl(targetId);
|
|
@@ -620,7 +815,7 @@ function resolveProfile() {
|
|
|
620
815
|
};
|
|
621
816
|
}
|
|
622
817
|
/** Is any Chrome of ours running with this --user-data-dir? */
|
|
623
|
-
function
|
|
818
|
+
function profileInUse(dir) {
|
|
624
819
|
try {
|
|
625
820
|
execFileSync("pgrep", [
|
|
626
821
|
"-u",
|
|
@@ -652,7 +847,7 @@ function migrateProfile() {
|
|
|
652
847
|
dir: legacy,
|
|
653
848
|
detail: `this process may not read ${legacy}. On macOS that is the app-data permission ("… would like to access data from other apps") for the app this is running under. Run \`browser-automation profile --migrate\` once from a terminal that can reach it, and every host will use the new location from then on.`
|
|
654
849
|
};
|
|
655
|
-
if (
|
|
850
|
+
if (profileInUse(legacy)) return {
|
|
656
851
|
outcome: "in-use",
|
|
657
852
|
dir: legacy,
|
|
658
853
|
detail: `a running Chrome has ${legacy} open, and a profile is never moved underneath one. It moves on the next launch after that Chrome quits — or now, with \`browser-automation launch --restart\`.`
|
|
@@ -715,7 +910,69 @@ const CACHES = new Set([
|
|
|
715
910
|
"OptGuideOnDeviceClassifierModel",
|
|
716
911
|
"OnDeviceHeadSuggestModel"
|
|
717
912
|
]);
|
|
718
|
-
|
|
913
|
+
/**
|
|
914
|
+
* What a site — and the person's accounts on it — leaves in a profile, by
|
|
915
|
+
* path under Default/. Left out of an extensions-only copy. Extension data
|
|
916
|
+
* lives elsewhere (Extensions/, Local Extension Settings/, Extension State/,
|
|
917
|
+
* Extension Cookies, Service Worker/Database + ScriptCache) and is kept.
|
|
918
|
+
*/
|
|
919
|
+
const SITE_DATA = new Set([
|
|
920
|
+
"Cookies",
|
|
921
|
+
"Cookies-journal",
|
|
922
|
+
"Login Data",
|
|
923
|
+
"Login Data-journal",
|
|
924
|
+
"Login Data For Account",
|
|
925
|
+
"Login Data For Account-journal",
|
|
926
|
+
"Account Web Data",
|
|
927
|
+
"Account Web Data-journal",
|
|
928
|
+
"Web Data",
|
|
929
|
+
"Web Data-journal",
|
|
930
|
+
"Local Storage",
|
|
931
|
+
"Session Storage",
|
|
932
|
+
"IndexedDB",
|
|
933
|
+
"WebStorage",
|
|
934
|
+
"Storage",
|
|
935
|
+
"File System",
|
|
936
|
+
"blob_storage",
|
|
937
|
+
"Sessions",
|
|
938
|
+
"Sessions_Encrypted",
|
|
939
|
+
"History",
|
|
940
|
+
"History-journal",
|
|
941
|
+
"Top Sites",
|
|
942
|
+
"Top Sites-journal",
|
|
943
|
+
"Visited Links",
|
|
944
|
+
"Favicons",
|
|
945
|
+
"Favicons-journal",
|
|
946
|
+
"Shortcuts",
|
|
947
|
+
"Shortcuts-journal",
|
|
948
|
+
"Network Action Predictor",
|
|
949
|
+
"Network Action Predictor-journal",
|
|
950
|
+
"Trust Tokens",
|
|
951
|
+
"Trust Tokens-journal",
|
|
952
|
+
"Reporting and NEL",
|
|
953
|
+
"Reporting and NEL-journal",
|
|
954
|
+
"Network Persistent State",
|
|
955
|
+
"DIPS",
|
|
956
|
+
"DIPS-wal",
|
|
957
|
+
"Sync Data",
|
|
958
|
+
"Device Bound Sessions",
|
|
959
|
+
"Device Bound Sessions-journal",
|
|
960
|
+
"passkey_enclave_state",
|
|
961
|
+
join("Service Worker", "CacheStorage"),
|
|
962
|
+
...[
|
|
963
|
+
"Cookies",
|
|
964
|
+
"Cookies-journal",
|
|
965
|
+
"Network Persistent State",
|
|
966
|
+
"Reporting and NEL",
|
|
967
|
+
"Reporting and NEL-journal",
|
|
968
|
+
"Trust Tokens",
|
|
969
|
+
"Trust Tokens-journal",
|
|
970
|
+
"Device Bound Sessions",
|
|
971
|
+
"Device Bound Sessions-journal",
|
|
972
|
+
"SCT Auditing Pending Reports"
|
|
973
|
+
].map((f) => join("Network", f))
|
|
974
|
+
]);
|
|
975
|
+
function keep(src, root, mode) {
|
|
719
976
|
const rel = relative(root, src);
|
|
720
977
|
if (rel === "") return true;
|
|
721
978
|
const parts = rel.split(sep);
|
|
@@ -723,17 +980,12 @@ function keep(src, root) {
|
|
|
723
980
|
const name = basename(src);
|
|
724
981
|
if (CACHES.has(name)) return false;
|
|
725
982
|
if (name.startsWith("Singleton") || name === "LOCK" || name === "RunningChromeVersion" || name === "DevToolsActivePort") return false;
|
|
983
|
+
if (mode === "extensions" && parts[0] === "Default" && SITE_DATA.has(parts.slice(1).join(sep))) return false;
|
|
726
984
|
return true;
|
|
727
985
|
}
|
|
728
986
|
const vanished = (e) => e?.code === "ENOENT";
|
|
729
|
-
/**
|
|
730
|
-
|
|
731
|
-
* files under us — database journals, temp files. Node's cpSync aborts on the
|
|
732
|
-
* first one: the first live copy (then the opt-in `--clone-profile`) died 878 MB in, leaving a
|
|
733
|
-
* half-copied profile and no context (2026-10-24). A file that vanished
|
|
734
|
-
* between listing and copying is one Chrome no longer needed, so skip it.
|
|
735
|
-
*/
|
|
736
|
-
function copyTree(src, dst, root) {
|
|
987
|
+
/** Recursive copy that skips files the running automation Chrome deletes under us. */
|
|
988
|
+
function copyTree(src, dst, root, mode) {
|
|
737
989
|
mkdirSync(dst, { recursive: true });
|
|
738
990
|
let entries;
|
|
739
991
|
try {
|
|
@@ -745,9 +997,9 @@ function copyTree(src, dst, root) {
|
|
|
745
997
|
for (const ent of entries) {
|
|
746
998
|
const s = join(src, ent.name);
|
|
747
999
|
const d = join(dst, ent.name);
|
|
748
|
-
if (!keep(s, root)) continue;
|
|
1000
|
+
if (!keep(s, root, mode)) continue;
|
|
749
1001
|
try {
|
|
750
|
-
if (ent.isDirectory()) copyTree(s, d, root);
|
|
1002
|
+
if (ent.isDirectory()) copyTree(s, d, root, mode);
|
|
751
1003
|
else if (ent.isSymbolicLink()) symlinkSync(readlinkSync(s), d);
|
|
752
1004
|
else if (ent.isFile()) copyFileSync(s, d);
|
|
753
1005
|
} catch (e) {
|
|
@@ -755,12 +1007,68 @@ function copyTree(src, dst, root) {
|
|
|
755
1007
|
}
|
|
756
1008
|
}
|
|
757
1009
|
}
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
1010
|
+
function readJson(path) {
|
|
1011
|
+
try {
|
|
1012
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
1013
|
+
} catch {
|
|
1014
|
+
return {};
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
function writeJson(path, value) {
|
|
1018
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
1019
|
+
writeFileSync(tmp, JSON.stringify(value));
|
|
1020
|
+
renameSync(tmp, path);
|
|
1021
|
+
}
|
|
1022
|
+
/** Take Chrome's own Google sign-in out of a copied profile: the copy must not be the person's account. */
|
|
1023
|
+
function signOutOfChrome(profileRoot) {
|
|
1024
|
+
const prefsPath = join(profileRoot, "Default", "Preferences");
|
|
1025
|
+
const prefs = readJson(prefsPath);
|
|
1026
|
+
for (const k of [
|
|
1027
|
+
"account_info",
|
|
1028
|
+
"google",
|
|
1029
|
+
"signin",
|
|
1030
|
+
"sync",
|
|
1031
|
+
"gaia_cookie",
|
|
1032
|
+
"account_tracker_service_last_update"
|
|
1033
|
+
]) delete prefs[k];
|
|
1034
|
+
writeJson(prefsPath, prefs);
|
|
1035
|
+
const statePath = join(profileRoot, "Local State");
|
|
1036
|
+
if (existsSync(statePath)) {
|
|
1037
|
+
const state = readJson(statePath);
|
|
1038
|
+
const cache = state.profile?.info_cache?.Default;
|
|
1039
|
+
if (cache) {
|
|
1040
|
+
for (const k of [
|
|
1041
|
+
"gaia_id",
|
|
1042
|
+
"gaia_name",
|
|
1043
|
+
"gaia_given_name",
|
|
1044
|
+
"user_name",
|
|
1045
|
+
"hosted_domain",
|
|
1046
|
+
"gaia_picture_file_name",
|
|
1047
|
+
"last_downloaded_gaia_picture_url_with_size",
|
|
1048
|
+
"is_consented_primary_account"
|
|
1049
|
+
]) delete cache[k];
|
|
1050
|
+
writeJson(statePath, state);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
/** Seed `to` (empty) from the automation profile `from`. Throws if `to` already holds a profile. */
|
|
1055
|
+
function seedProfile(from, to, mode) {
|
|
1056
|
+
if (existsSync(to) && readdirSync(to).length) throw new Error(`${to} is not empty; only a new context is seeded`);
|
|
1057
|
+
if (mode === "empty" || !existsSync(join(from, "Default"))) {
|
|
1058
|
+
mkdirSync(join(to, "Default"), { recursive: true });
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
762
1061
|
try {
|
|
763
|
-
copyTree(from, to, from);
|
|
1062
|
+
copyTree(from, to, from, mode);
|
|
1063
|
+
if (mode === "extensions") signOutOfChrome(to);
|
|
1064
|
+
const prefsPath = join(to, "Default", "Preferences");
|
|
1065
|
+
const prefs = readJson(prefsPath);
|
|
1066
|
+
prefs.profile = {
|
|
1067
|
+
...prefs.profile ?? {},
|
|
1068
|
+
exit_type: "Normal",
|
|
1069
|
+
exited_cleanly: true
|
|
1070
|
+
};
|
|
1071
|
+
writeJson(prefsPath, prefs);
|
|
764
1072
|
} catch (e) {
|
|
765
1073
|
rmSync(to, {
|
|
766
1074
|
recursive: true,
|
|
@@ -769,6 +1077,82 @@ function cloneProfile(from, to) {
|
|
|
769
1077
|
throw e;
|
|
770
1078
|
}
|
|
771
1079
|
}
|
|
1080
|
+
/** Distinct colours for contexts, in order of creation. ARGB. */
|
|
1081
|
+
const CONTEXT_COLORS = [
|
|
1082
|
+
{
|
|
1083
|
+
name: "purple",
|
|
1084
|
+
argb: 4286259106
|
|
1085
|
+
},
|
|
1086
|
+
{
|
|
1087
|
+
name: "teal",
|
|
1088
|
+
argb: 4278225275
|
|
1089
|
+
},
|
|
1090
|
+
{
|
|
1091
|
+
name: "orange",
|
|
1092
|
+
argb: 4293880832
|
|
1093
|
+
},
|
|
1094
|
+
{
|
|
1095
|
+
name: "blue",
|
|
1096
|
+
argb: 4279592384
|
|
1097
|
+
},
|
|
1098
|
+
{
|
|
1099
|
+
name: "rose",
|
|
1100
|
+
argb: 4290910299
|
|
1101
|
+
},
|
|
1102
|
+
{
|
|
1103
|
+
name: "green",
|
|
1104
|
+
argb: 4281236786
|
|
1105
|
+
},
|
|
1106
|
+
{
|
|
1107
|
+
name: "brown",
|
|
1108
|
+
argb: 4285353025
|
|
1109
|
+
},
|
|
1110
|
+
{
|
|
1111
|
+
name: "indigo",
|
|
1112
|
+
argb: 4281944491
|
|
1113
|
+
}
|
|
1114
|
+
];
|
|
1115
|
+
/**
|
|
1116
|
+
* Name the profile after its context and give it its colour. Only while the
|
|
1117
|
+
* context's Chrome is NOT running: Chrome holds these in memory and would
|
|
1118
|
+
* write its own copy back over them.
|
|
1119
|
+
*/
|
|
1120
|
+
function personalizeProfile(profileRoot, name, argb) {
|
|
1121
|
+
const prefsDir = join(profileRoot, "Default");
|
|
1122
|
+
mkdirSync(prefsDir, { recursive: true });
|
|
1123
|
+
const prefsPath = join(prefsDir, "Preferences");
|
|
1124
|
+
const prefs = readJson(prefsPath);
|
|
1125
|
+
prefs.profile = {
|
|
1126
|
+
...prefs.profile ?? {},
|
|
1127
|
+
name
|
|
1128
|
+
};
|
|
1129
|
+
prefs.browser = {
|
|
1130
|
+
...prefs.browser ?? {},
|
|
1131
|
+
theme: {
|
|
1132
|
+
...prefs.browser?.theme ?? {},
|
|
1133
|
+
user_color2: argb | 0,
|
|
1134
|
+
color_variant2: 3
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
prefs.extensions = {
|
|
1138
|
+
...prefs.extensions ?? {},
|
|
1139
|
+
theme: {
|
|
1140
|
+
...prefs.extensions?.theme ?? {},
|
|
1141
|
+
id: "user_color_theme_id"
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
writeJson(prefsPath, prefs);
|
|
1145
|
+
const statePath = join(profileRoot, "Local State");
|
|
1146
|
+
const state = readJson(statePath);
|
|
1147
|
+
state.profile ??= {};
|
|
1148
|
+
state.profile.info_cache ??= {};
|
|
1149
|
+
state.profile.info_cache.Default = {
|
|
1150
|
+
...state.profile.info_cache.Default ?? {},
|
|
1151
|
+
name,
|
|
1152
|
+
is_using_default_name: false
|
|
1153
|
+
};
|
|
1154
|
+
writeJson(statePath, state);
|
|
1155
|
+
}
|
|
772
1156
|
//#endregion
|
|
773
1157
|
//#region src/core/session.ts
|
|
774
1158
|
const DIR = join(homedir(), ".browser-automation", "sessions");
|
|
@@ -829,7 +1213,7 @@ var ContextError = class extends Error {};
|
|
|
829
1213
|
function takeContextFlag(argv) {
|
|
830
1214
|
const out = [];
|
|
831
1215
|
let name;
|
|
832
|
-
let
|
|
1216
|
+
let seed;
|
|
833
1217
|
for (let i = 0; i < argv.length; i++) {
|
|
834
1218
|
const a = argv[i];
|
|
835
1219
|
if (a === "--") {
|
|
@@ -847,8 +1231,10 @@ function takeContextFlag(argv) {
|
|
|
847
1231
|
name = a.slice(10);
|
|
848
1232
|
continue;
|
|
849
1233
|
}
|
|
850
|
-
if (a === "--empty-profile") {
|
|
851
|
-
|
|
1234
|
+
if (a === "--empty-profile" || a === "--full-copy") {
|
|
1235
|
+
const m = a === "--empty-profile" ? "empty" : "full";
|
|
1236
|
+
if (seed && seed !== m) throw new ContextError("--empty-profile and --full-copy contradict each other");
|
|
1237
|
+
seed = m;
|
|
852
1238
|
continue;
|
|
853
1239
|
}
|
|
854
1240
|
out.push(a);
|
|
@@ -856,7 +1242,7 @@ function takeContextFlag(argv) {
|
|
|
856
1242
|
return {
|
|
857
1243
|
argv: out,
|
|
858
1244
|
name,
|
|
859
|
-
|
|
1245
|
+
seed
|
|
860
1246
|
};
|
|
861
1247
|
}
|
|
862
1248
|
/** The `-s`/`--session` value, or the default — only when the tab is chosen by session (no -m/-t/-F). */
|
|
@@ -877,42 +1263,54 @@ function sessionOf(argv) {
|
|
|
877
1263
|
* create one, and set BROWSER_AUTOMATION_CONTEXT. Returns argv without the flag.
|
|
878
1264
|
*/
|
|
879
1265
|
async function selectContext(sub, rawArgv) {
|
|
880
|
-
const { argv, name: flag,
|
|
881
|
-
const asked = flag ?? (process.env.BAC_CONTEXT || void 0);
|
|
1266
|
+
const { argv, name: flag, seed } = takeContextFlag(rawArgv);
|
|
882
1267
|
const session = sub && !SESSIONLESS.has(sub) ? sessionOf(argv) : null;
|
|
883
1268
|
const st = session ? loadSession(session) : null;
|
|
884
|
-
if (
|
|
885
|
-
const name =
|
|
1269
|
+
if (flag !== void 0 && st && (st.context ?? void 0) !== flag) throw new ContextError(`session "${st.name}" belongs to ${st.context ? `context "${st.context}"` : "your own Chrome"}, not "${flag}" — use another session name (-s), or forget this one first: browser-automation close -s ${st.name}`);
|
|
1270
|
+
const name = flag ?? (st ? st.context : void 0) ?? (st ? void 0 : process.env.BAC_CONTEXT || void 0);
|
|
886
1271
|
if (!name) {
|
|
887
|
-
if (
|
|
1272
|
+
if (seed) throw new ContextError(`--${seed === "empty" ? "empty-profile" : "full-copy"} is for a NEW login context: use it with --context <name>`);
|
|
888
1273
|
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
889
1274
|
return argv;
|
|
890
1275
|
}
|
|
891
1276
|
if (!validContextName(name)) throw new ContextError(`invalid context name "${name}": letters, digits, '.', '_' or '-' (max 64), starting with a letter or digit`);
|
|
892
1277
|
if (!loadContextRecord(name)) {
|
|
893
1278
|
if (!sub || !CREATES.has(sub)) throw new ContextError(`no context named "${name}" — open one with: browser-automation new -s <session> --context ${name} <url>`);
|
|
894
|
-
const
|
|
1279
|
+
const records = listContextRecords();
|
|
1280
|
+
const port = await allocateContextPort(records.map((r) => r.port));
|
|
895
1281
|
const profileDir = contextProfileDir(name);
|
|
1282
|
+
const color = nextContextColor(records);
|
|
896
1283
|
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
897
1284
|
const from = resolveProfile().dir;
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
}
|
|
905
|
-
}
|
|
1285
|
+
const mode = seed ?? "extensions";
|
|
1286
|
+
console.error(SEED_NOTE[mode](name, from, color.name));
|
|
1287
|
+
try {
|
|
1288
|
+
seedProfile(from, profileDir, mode);
|
|
1289
|
+
personalizeProfile(profileDir, name, color.argb);
|
|
1290
|
+
} catch (e) {
|
|
1291
|
+
throw new ContextError(`could not set up the profile for context "${name}": ${e instanceof Error ? e.message : String(e)} — nothing was kept; run it again, or pass --empty-profile`);
|
|
1292
|
+
}
|
|
906
1293
|
saveContextRecord({
|
|
907
1294
|
name,
|
|
908
1295
|
port,
|
|
909
1296
|
profileDir,
|
|
1297
|
+
color: color.name,
|
|
910
1298
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
911
1299
|
});
|
|
912
|
-
} else if (
|
|
1300
|
+
} else if (seed) console.error(`Context "${name}" already exists, so --${seed === "empty" ? "empty-profile" : "full-copy"} does nothing; its profile is left as it is.`);
|
|
913
1301
|
process.env.BROWSER_AUTOMATION_CONTEXT = name;
|
|
914
1302
|
return argv;
|
|
915
1303
|
}
|
|
1304
|
+
const SEED_NOTE = {
|
|
1305
|
+
extensions: (name, from, color) => `Context "${name}" (a ${color} window): copying the EXTENSIONS of the automation profile (${from}) — a password manager stays signed in — but no site logins, cookies or history, and not signed in to Chrome. (--full-copy takes the logins too; --empty-profile takes nothing.)`,
|
|
1306
|
+
full: (name, from, color) => `Context "${name}" (a ${color} window): a FULL copy of the automation profile (${from}), caches left out — every login and cookie comes along, including Chrome's own Google sign-in, which may then be the default Google account there. Sign out of any account this context is not for.`,
|
|
1307
|
+
empty: (name, _from, color) => `Context "${name}" (a ${color} window): an empty profile — no extensions, no logins.`
|
|
1308
|
+
};
|
|
1309
|
+
/** The first palette colour no context has yet; after that, round the palette. */
|
|
1310
|
+
function nextContextColor(records) {
|
|
1311
|
+
const used = new Set(records.map((r) => r.color));
|
|
1312
|
+
return CONTEXT_COLORS.find((c) => !used.has(c.name)) ?? CONTEXT_COLORS[records.length % CONTEXT_COLORS.length];
|
|
1313
|
+
}
|
|
916
1314
|
//#endregion
|
|
917
1315
|
//#region src/core/target.ts
|
|
918
1316
|
async function resolveLiveTarget(name, { create = true } = {}) {
|
|
@@ -1135,145 +1533,908 @@ async function ensureRenderer(targetId, { grace, budget, allowWake = !process.en
|
|
|
1135
1533
|
};
|
|
1136
1534
|
}
|
|
1137
1535
|
//#endregion
|
|
1138
|
-
//#region src/core/
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
/** How many times we ask before we are willing to call a browser broken. */
|
|
1142
|
-
const DEFAULT_ATTEMPTS = 3;
|
|
1143
|
-
/** Breathing room between attempts — a browser mid-GC deserves a second look. */
|
|
1144
|
-
const RETRY_PAUSE = 400;
|
|
1145
|
-
/**
|
|
1146
|
-
* The verdict, from the probe and the corroborations — and from nothing else.
|
|
1147
|
-
*
|
|
1148
|
-
* Pure, and separate from the probing, because this is the decision that was
|
|
1149
|
-
* wrong: every failure used to become 'wedged' by default. Now 'wedged'
|
|
1150
|
-
* requires `rendezvous === false`, which is the only thing that has ever
|
|
1151
|
-
* actually meant it.
|
|
1152
|
-
*/
|
|
1153
|
-
function rendererVerdict(outcome, e) {
|
|
1154
|
-
if (outcome === "ok") return "healthy";
|
|
1155
|
-
if (e?.rendezvous === false) return "wedged";
|
|
1156
|
-
if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
|
|
1157
|
-
return "unknown";
|
|
1536
|
+
//#region src/core/broker.ts
|
|
1537
|
+
function statePath(dir) {
|
|
1538
|
+
return join(dir, "broker.json");
|
|
1158
1539
|
}
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
* tool opens tabs AND gets the same wake treatment. A probe that is harsher
|
|
1166
|
-
* on itself than `goto` is on a real tab reports failures `goto` would not
|
|
1167
|
-
* have had.
|
|
1168
|
-
* 2. It retries with a doubling budget. One 5s timeout is not evidence of a
|
|
1169
|
-
* permanent condition; it is evidence of 5 seconds.
|
|
1170
|
-
* 3. It stops early when the Mach name is ABSENT — the one state where more
|
|
1171
|
-
* waiting is genuinely pointless — so the real failure is still reported
|
|
1172
|
-
* fast while a slow browser gets the benefit of the doubt.
|
|
1173
|
-
*/
|
|
1174
|
-
async function probeRenderer({ timeout, attempts } = {}) {
|
|
1175
|
-
const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
|
|
1176
|
-
const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
|
|
1177
|
-
const started = Date.now();
|
|
1178
|
-
let pageTargets = 0;
|
|
1540
|
+
const windows = process.platform === "win32";
|
|
1541
|
+
/** A named pipe nobody can predict, so nobody can create it before we do. */
|
|
1542
|
+
function windowsPipeName() {
|
|
1543
|
+
return `\\\\.\\pipe\\browser-automation-${randomUUID()}`;
|
|
1544
|
+
}
|
|
1545
|
+
function servedSocket(dir) {
|
|
1179
1546
|
try {
|
|
1180
|
-
|
|
1181
|
-
} catch {
|
|
1182
|
-
|
|
1183
|
-
let evidence;
|
|
1184
|
-
for (let i = 0; i < maxAttempts; i++) {
|
|
1185
|
-
const budget = base * 2 ** i;
|
|
1186
|
-
tries.push(await probeOnce(budget));
|
|
1187
|
-
if (tries[tries.length - 1].outcome === "ok") return finish({
|
|
1188
|
-
ok: true,
|
|
1189
|
-
started,
|
|
1190
|
-
pageTargets,
|
|
1191
|
-
tries,
|
|
1192
|
-
evidence
|
|
1193
|
-
});
|
|
1194
|
-
evidence ??= gatherEvidence();
|
|
1195
|
-
if (evidence.rendezvous === false) break;
|
|
1196
|
-
if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
|
|
1547
|
+
return JSON.parse(readFileSync(statePath(dir), "utf8")).socket ?? null;
|
|
1548
|
+
} catch {
|
|
1549
|
+
return null;
|
|
1197
1550
|
}
|
|
1198
|
-
return finish({
|
|
1199
|
-
ok: false,
|
|
1200
|
-
started,
|
|
1201
|
-
pageTargets,
|
|
1202
|
-
tries,
|
|
1203
|
-
evidence
|
|
1204
|
-
});
|
|
1205
1551
|
}
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
evidence
|
|
1217
|
-
};
|
|
1218
|
-
recordProbe(health);
|
|
1219
|
-
return health;
|
|
1552
|
+
/** The flags Chrome is started with. The profile flag is also how `ps` finds it. */
|
|
1553
|
+
function chromeArgs(profile, extra = []) {
|
|
1554
|
+
return [
|
|
1555
|
+
"--remote-debugging-pipe",
|
|
1556
|
+
`--user-data-dir=${profile}`,
|
|
1557
|
+
"--no-first-run",
|
|
1558
|
+
"--no-default-browser-check",
|
|
1559
|
+
...extra,
|
|
1560
|
+
"about:blank"
|
|
1561
|
+
];
|
|
1220
1562
|
}
|
|
1221
|
-
/**
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1563
|
+
/** Does something answer on this socket? Connect-and-close; no CDP. */
|
|
1564
|
+
function socketAnswers(socket, timeout = 1e3) {
|
|
1565
|
+
return new Promise((resolve) => {
|
|
1566
|
+
const s = createConnection(socket);
|
|
1567
|
+
const t = setTimeout(() => {
|
|
1568
|
+
s.destroy();
|
|
1569
|
+
resolve(false);
|
|
1570
|
+
}, timeout);
|
|
1571
|
+
s.on("connect", () => {
|
|
1572
|
+
clearTimeout(t);
|
|
1573
|
+
s.destroy();
|
|
1574
|
+
resolve(true);
|
|
1575
|
+
});
|
|
1576
|
+
s.on("error", () => {
|
|
1577
|
+
clearTimeout(t);
|
|
1578
|
+
resolve(false);
|
|
1579
|
+
});
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
const alive$2 = (pid) => {
|
|
1225
1583
|
try {
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
budget,
|
|
1231
|
-
ms: Date.now() - started,
|
|
1232
|
-
woke: false,
|
|
1233
|
-
reason: `could not create a target at all: ${e?.message ?? e}`
|
|
1234
|
-
};
|
|
1584
|
+
process.kill(pid, 0);
|
|
1585
|
+
return true;
|
|
1586
|
+
} catch {
|
|
1587
|
+
return false;
|
|
1235
1588
|
}
|
|
1589
|
+
};
|
|
1590
|
+
/**
|
|
1591
|
+
* Become the one broker for this directory, or learn that another one is. Two
|
|
1592
|
+
* `launch` runs at once (two tabs both finding no browser) each start a broker,
|
|
1593
|
+
* and before either listens, the socket check below passes for both: both then
|
|
1594
|
+
* spawn Chrome on the same profile, one Chrome hands off to the other through
|
|
1595
|
+
* the profile lock and exits, and one broker's listen fails. An O_EXCL pid file
|
|
1596
|
+
* taken before Chrome is spawned leaves exactly one. A lock whose pid is gone
|
|
1597
|
+
* was left by a broker that died, and is taken over.
|
|
1598
|
+
*
|
|
1599
|
+
* The pid is written to a file of our own first and linked into place, so the
|
|
1600
|
+
* lock never exists without it. Created empty and written after, a broker that
|
|
1601
|
+
* read it in between found no pid, took it for a dead broker's, and took the
|
|
1602
|
+
* lock as well: two brokers, and the second one's listen failed.
|
|
1603
|
+
*/
|
|
1604
|
+
function takeLock(lock) {
|
|
1605
|
+
const mine = `${lock}.${process.pid}`;
|
|
1606
|
+
writeFileSync(mine, `${process.pid}\n`, { mode: 384 });
|
|
1236
1607
|
try {
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
})
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1608
|
+
for (let attempt = 0; attempt < 2; attempt++) try {
|
|
1609
|
+
linkSync(mine, lock);
|
|
1610
|
+
return true;
|
|
1611
|
+
} catch (e) {
|
|
1612
|
+
if (e.code !== "EEXIST") throw e;
|
|
1613
|
+
let pid = NaN;
|
|
1614
|
+
try {
|
|
1615
|
+
pid = Number.parseInt(readFileSync(lock, "utf8"), 10);
|
|
1616
|
+
} catch (r) {
|
|
1617
|
+
if (r.code !== "ENOENT") throw r;
|
|
1618
|
+
}
|
|
1619
|
+
if (Number.isInteger(pid) && pid > 0 && alive$2(pid)) return false;
|
|
1620
|
+
rmSync(lock, { force: true });
|
|
1621
|
+
}
|
|
1622
|
+
return false;
|
|
1248
1623
|
} finally {
|
|
1249
|
-
|
|
1624
|
+
rmSync(mine, { force: true });
|
|
1250
1625
|
}
|
|
1251
1626
|
}
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1627
|
+
const sleep$5 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1628
|
+
async function runBroker(o) {
|
|
1629
|
+
process.umask(63);
|
|
1630
|
+
const dir = o.dir;
|
|
1631
|
+
for (const d of windows ? [dir] : [dir, dirname(o.socket)]) {
|
|
1632
|
+
mkdirSync(d, {
|
|
1633
|
+
recursive: true,
|
|
1634
|
+
mode: 448
|
|
1635
|
+
});
|
|
1636
|
+
chmodSync(d, 448);
|
|
1637
|
+
}
|
|
1638
|
+
const lock = join(dir, "broker.lock");
|
|
1639
|
+
if (!takeLock(lock)) {
|
|
1640
|
+
for (let i = 0; i < 240; i++) {
|
|
1641
|
+
const theirs = windows ? servedSocket(dir) : o.socket;
|
|
1642
|
+
if (theirs && await socketAnswers(theirs)) return;
|
|
1643
|
+
await sleep$5(250);
|
|
1644
|
+
}
|
|
1645
|
+
throw new Error(`another broker holds ${lock}, but nothing answered on ${o.socket} within 60s`);
|
|
1646
|
+
}
|
|
1647
|
+
const releaseLock = () => {
|
|
1648
|
+
try {
|
|
1649
|
+
if (readFileSync(lock, "utf8").trim() === String(process.pid)) rmSync(lock, { force: true });
|
|
1650
|
+
} catch {}
|
|
1651
|
+
};
|
|
1652
|
+
try {
|
|
1653
|
+
await serve(o, releaseLock);
|
|
1654
|
+
} finally {
|
|
1655
|
+
releaseLock();
|
|
1656
|
+
}
|
|
1262
1657
|
}
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1658
|
+
async function serve(o, releaseLock) {
|
|
1659
|
+
const dir = o.dir;
|
|
1660
|
+
if (!windows && existsSync(o.socket)) {
|
|
1661
|
+
if (await socketAnswers(o.socket)) throw new Error(`a broker is already serving ${o.socket}`);
|
|
1662
|
+
rmSync(o.socket, { force: true });
|
|
1663
|
+
}
|
|
1664
|
+
const logFd = openSync(o.log, "a", 384);
|
|
1665
|
+
const chrome = spawn(o.chrome, chromeArgs(o.profile, o.extraArgs), { stdio: [
|
|
1666
|
+
"ignore",
|
|
1667
|
+
logFd,
|
|
1668
|
+
logFd,
|
|
1669
|
+
"pipe",
|
|
1670
|
+
"pipe"
|
|
1671
|
+
] });
|
|
1672
|
+
closeSync(logFd);
|
|
1673
|
+
const toChrome = chrome.stdio[3];
|
|
1674
|
+
const fromChrome = chrome.stdio[4];
|
|
1675
|
+
let nextId = 1;
|
|
1676
|
+
const relayed = /* @__PURE__ */ new Map();
|
|
1677
|
+
const own = /* @__PURE__ */ new Map();
|
|
1678
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
1679
|
+
const clients = /* @__PURE__ */ new Set();
|
|
1680
|
+
const socks = /* @__PURE__ */ new Set();
|
|
1681
|
+
const toPipe = (msg) => toChrome.write(JSON.stringify(msg) + "\0");
|
|
1682
|
+
const ask = (method, params) => new Promise((resolve) => {
|
|
1683
|
+
const id = nextId++;
|
|
1684
|
+
own.set(id, resolve);
|
|
1685
|
+
toPipe({
|
|
1686
|
+
id,
|
|
1687
|
+
method,
|
|
1688
|
+
params
|
|
1689
|
+
});
|
|
1690
|
+
});
|
|
1691
|
+
const tell = (c, msg) => {
|
|
1692
|
+
if (!c.sock.destroyed) c.sock.write(JSON.stringify(msg) + "\n");
|
|
1693
|
+
};
|
|
1694
|
+
let buf = "";
|
|
1695
|
+
fromChrome.setEncoding("utf8");
|
|
1696
|
+
fromChrome.on("data", (chunk) => {
|
|
1697
|
+
buf += chunk;
|
|
1698
|
+
let end;
|
|
1699
|
+
while ((end = buf.indexOf("\0")) >= 0) {
|
|
1700
|
+
const raw = buf.slice(0, end);
|
|
1701
|
+
buf = buf.slice(end + 1);
|
|
1702
|
+
let msg;
|
|
1703
|
+
try {
|
|
1704
|
+
msg = JSON.parse(raw);
|
|
1705
|
+
} catch {
|
|
1706
|
+
continue;
|
|
1707
|
+
}
|
|
1708
|
+
if (typeof msg.id === "number") {
|
|
1709
|
+
const mine = own.get(msg.id);
|
|
1710
|
+
if (mine) {
|
|
1711
|
+
own.delete(msg.id);
|
|
1712
|
+
mine(msg);
|
|
1713
|
+
continue;
|
|
1714
|
+
}
|
|
1715
|
+
const r = relayed.get(msg.id);
|
|
1716
|
+
if (!r) continue;
|
|
1717
|
+
relayed.delete(msg.id);
|
|
1718
|
+
const { sessionId: _drop, ...rest } = msg;
|
|
1719
|
+
tell(r.client, {
|
|
1720
|
+
...rest,
|
|
1721
|
+
id: r.id
|
|
1722
|
+
});
|
|
1723
|
+
continue;
|
|
1724
|
+
}
|
|
1725
|
+
if (msg.sessionId) {
|
|
1726
|
+
const c = bySession.get(msg.sessionId);
|
|
1727
|
+
if (c) tell(c, {
|
|
1728
|
+
method: msg.method,
|
|
1729
|
+
params: msg.params
|
|
1730
|
+
});
|
|
1731
|
+
continue;
|
|
1732
|
+
}
|
|
1733
|
+
if (msg.method === "Target.detachedFromTarget") {
|
|
1734
|
+
const c = bySession.get(msg.params?.sessionId);
|
|
1735
|
+
if (c) {
|
|
1736
|
+
bySession.delete(msg.params.sessionId);
|
|
1737
|
+
c.sessionId = null;
|
|
1738
|
+
c.sock.end();
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
for (const c of clients) if (c.browser) tell(c, {
|
|
1742
|
+
method: msg.method,
|
|
1743
|
+
params: msg.params
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
});
|
|
1747
|
+
const server = createServer((sock) => {
|
|
1748
|
+
socks.add(sock);
|
|
1749
|
+
sock.on("close", () => socks.delete(sock));
|
|
1750
|
+
const c = {
|
|
1751
|
+
sock,
|
|
1752
|
+
sessionId: null,
|
|
1753
|
+
browser: false
|
|
1754
|
+
};
|
|
1755
|
+
let attached = false;
|
|
1756
|
+
let pending = "";
|
|
1757
|
+
sock.setEncoding("utf8");
|
|
1758
|
+
sock.on("data", async (chunk) => {
|
|
1759
|
+
pending += chunk;
|
|
1760
|
+
let nl;
|
|
1761
|
+
while ((nl = pending.indexOf("\n")) >= 0) {
|
|
1762
|
+
const line = pending.slice(0, nl);
|
|
1763
|
+
pending = pending.slice(nl + 1);
|
|
1764
|
+
let msg;
|
|
1765
|
+
try {
|
|
1766
|
+
msg = JSON.parse(line);
|
|
1767
|
+
} catch {
|
|
1768
|
+
sock.destroy();
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
if (!attached) {
|
|
1772
|
+
attached = true;
|
|
1773
|
+
sock.pause();
|
|
1774
|
+
if (msg.attach === "browser") c.browser = true;
|
|
1775
|
+
else if (msg.attach === "target" && typeof msg.targetId === "string") {
|
|
1776
|
+
const r = await ask("Target.attachToTarget", {
|
|
1777
|
+
targetId: msg.targetId,
|
|
1778
|
+
flatten: true
|
|
1779
|
+
});
|
|
1780
|
+
if (sock.destroyed) {
|
|
1781
|
+
if (!r.error) toPipe({
|
|
1782
|
+
id: nextId++,
|
|
1783
|
+
method: "Target.detachFromTarget",
|
|
1784
|
+
params: { sessionId: r.result.sessionId }
|
|
1785
|
+
});
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
if (r.error) {
|
|
1789
|
+
tell(c, { error: `target ${msg.targetId}: ${r.error.message}` });
|
|
1790
|
+
sock.end();
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
c.sessionId = r.result.sessionId;
|
|
1794
|
+
bySession.set(c.sessionId, c);
|
|
1795
|
+
} else {
|
|
1796
|
+
tell(c, { error: "first line must be {\"attach\":\"browser\"} or {\"attach\":\"target\",\"targetId\":…}" });
|
|
1797
|
+
sock.end();
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
clients.add(c);
|
|
1801
|
+
tell(c, { attached: true });
|
|
1802
|
+
sock.resume();
|
|
1803
|
+
continue;
|
|
1804
|
+
}
|
|
1805
|
+
if (typeof msg.id !== "number" || typeof msg.method !== "string") continue;
|
|
1806
|
+
const id = nextId++;
|
|
1807
|
+
relayed.set(id, {
|
|
1808
|
+
client: c,
|
|
1809
|
+
id: msg.id
|
|
1810
|
+
});
|
|
1811
|
+
toPipe({
|
|
1812
|
+
id,
|
|
1813
|
+
method: msg.method,
|
|
1814
|
+
params: msg.params ?? {},
|
|
1815
|
+
...c.sessionId ? { sessionId: c.sessionId } : {}
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
});
|
|
1819
|
+
const gone = () => {
|
|
1820
|
+
if (!clients.delete(c)) return;
|
|
1821
|
+
for (const [id, r] of relayed) if (r.client === c) relayed.delete(id);
|
|
1822
|
+
if (c.sessionId) {
|
|
1823
|
+
bySession.delete(c.sessionId);
|
|
1824
|
+
toPipe({
|
|
1825
|
+
id: nextId++,
|
|
1826
|
+
method: "Target.detachFromTarget",
|
|
1827
|
+
params: { sessionId: c.sessionId }
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
};
|
|
1831
|
+
sock.on("close", gone);
|
|
1832
|
+
sock.on("error", gone);
|
|
1833
|
+
});
|
|
1834
|
+
await new Promise((resolve, reject) => {
|
|
1835
|
+
server.once("error", reject);
|
|
1836
|
+
server.listen(o.socket, () => resolve());
|
|
1837
|
+
});
|
|
1838
|
+
if (!windows) chmodSync(o.socket, 384);
|
|
1839
|
+
const state = {
|
|
1840
|
+
brokerPid: process.pid,
|
|
1841
|
+
chromePid: chrome.pid ?? -1,
|
|
1842
|
+
profile: o.profile,
|
|
1843
|
+
socket: o.socket,
|
|
1844
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1845
|
+
};
|
|
1846
|
+
writeFileSync(statePath(dir), JSON.stringify(state, null, 2) + "\n", { mode: 384 });
|
|
1847
|
+
const cleanup = () => {
|
|
1848
|
+
server.close();
|
|
1849
|
+
for (const s of socks) s.destroy();
|
|
1850
|
+
if (!windows) rmSync(o.socket, { force: true });
|
|
1851
|
+
rmSync(statePath(dir), { force: true });
|
|
1852
|
+
releaseLock();
|
|
1853
|
+
};
|
|
1854
|
+
const stop = () => {
|
|
1855
|
+
toPipe({
|
|
1856
|
+
id: nextId++,
|
|
1857
|
+
method: "Browser.close",
|
|
1858
|
+
params: {}
|
|
1859
|
+
});
|
|
1860
|
+
setTimeout(() => toChrome.end(), 1e4).unref();
|
|
1861
|
+
setTimeout(() => chrome.kill("SIGKILL"), 2e4).unref();
|
|
1862
|
+
};
|
|
1863
|
+
process.on("SIGTERM", stop);
|
|
1864
|
+
process.on("SIGINT", stop);
|
|
1865
|
+
await new Promise((resolve) => {
|
|
1866
|
+
chrome.on("exit", () => resolve());
|
|
1867
|
+
chrome.on("error", (e) => {
|
|
1868
|
+
appendFileSync(o.log, `browser-automation broker: could not start ${o.chrome}: ${e.message}\n`);
|
|
1869
|
+
resolve();
|
|
1870
|
+
});
|
|
1871
|
+
});
|
|
1872
|
+
cleanup();
|
|
1873
|
+
}
|
|
1874
|
+
//#endregion
|
|
1875
|
+
//#region src/core/chrome-path.ts
|
|
1876
|
+
function executable(p) {
|
|
1877
|
+
try {
|
|
1878
|
+
if (!statSync(p).isFile()) return false;
|
|
1879
|
+
if (process.platform === "win32") return true;
|
|
1880
|
+
accessSync(p, constants.X_OK);
|
|
1881
|
+
return true;
|
|
1882
|
+
} catch {
|
|
1883
|
+
return false;
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
const MAC_BINARY = join("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
|
|
1887
|
+
function platformCandidates() {
|
|
1888
|
+
if (process.platform === "darwin") return [{
|
|
1889
|
+
path: join(process.env.BROWSER_AUTOMATION_TEST_SYSTEM_APPS || "/Applications", MAC_BINARY),
|
|
1890
|
+
source: "/Applications"
|
|
1891
|
+
}, {
|
|
1892
|
+
path: join(homedir(), "Applications", MAC_BINARY),
|
|
1893
|
+
source: "~/Applications"
|
|
1894
|
+
}];
|
|
1895
|
+
if (process.platform === "win32") {
|
|
1896
|
+
const out = [];
|
|
1897
|
+
const exe = join("Google", "Chrome", "Application", "chrome.exe");
|
|
1898
|
+
if (process.env.PROGRAMFILES) out.push({
|
|
1899
|
+
path: join(process.env.PROGRAMFILES, exe),
|
|
1900
|
+
source: "Program Files"
|
|
1901
|
+
});
|
|
1902
|
+
if (process.env["PROGRAMFILES(X86)"]) out.push({
|
|
1903
|
+
path: join(process.env["PROGRAMFILES(X86)"], exe),
|
|
1904
|
+
source: "Program Files (x86)"
|
|
1905
|
+
});
|
|
1906
|
+
if (process.env.LOCALAPPDATA) out.push({
|
|
1907
|
+
path: join(process.env.LOCALAPPDATA, exe),
|
|
1908
|
+
source: "%LOCALAPPDATA%"
|
|
1909
|
+
});
|
|
1910
|
+
return out;
|
|
1911
|
+
}
|
|
1912
|
+
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
|
|
1913
|
+
return [
|
|
1914
|
+
"google-chrome",
|
|
1915
|
+
"google-chrome-stable",
|
|
1916
|
+
"chromium",
|
|
1917
|
+
"chromium-browser"
|
|
1918
|
+
].flatMap((name) => dirs.map((d) => ({
|
|
1919
|
+
path: join(d, name),
|
|
1920
|
+
source: `PATH (${name})`
|
|
1921
|
+
})));
|
|
1922
|
+
}
|
|
1923
|
+
function chromeExecutable() {
|
|
1924
|
+
let ignored;
|
|
1925
|
+
for (const name of ["BROWSER_AUTOMATION_CHROME", "CHROME"]) {
|
|
1926
|
+
const v = process.env[name];
|
|
1927
|
+
if (!v) continue;
|
|
1928
|
+
if (executable(v)) return {
|
|
1929
|
+
path: v,
|
|
1930
|
+
source: name
|
|
1931
|
+
};
|
|
1932
|
+
ignored ??= `${name}=${v} is not an executable file`;
|
|
1933
|
+
}
|
|
1934
|
+
const hit = platformCandidates().find((c) => executable(c.path));
|
|
1935
|
+
return hit ? {
|
|
1936
|
+
path: hit.path,
|
|
1937
|
+
source: hit.source,
|
|
1938
|
+
ignored
|
|
1939
|
+
} : {
|
|
1940
|
+
path: null,
|
|
1941
|
+
source: "not found",
|
|
1942
|
+
ignored
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
/** Where we looked, for a "not found" message. */
|
|
1946
|
+
function chromeSearchDescription() {
|
|
1947
|
+
if (process.platform === "darwin") return "/Applications and ~/Applications";
|
|
1948
|
+
if (process.platform === "win32") return "Program Files, Program Files (x86) and %LOCALAPPDATA%";
|
|
1949
|
+
return "google-chrome, google-chrome-stable, chromium and chromium-browser on PATH";
|
|
1950
|
+
}
|
|
1951
|
+
//#endregion
|
|
1952
|
+
//#region src/core/launch-windows.ts
|
|
1953
|
+
const sleep$4 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1954
|
+
/** chrome.exe — decided in one place for every platform (core/chrome-path.ts). */
|
|
1955
|
+
function windowsChromeExe() {
|
|
1956
|
+
return chromeExecutable().path;
|
|
1957
|
+
}
|
|
1958
|
+
/** Is anything answering CDP on this port? (The script's `is_up`.) */
|
|
1959
|
+
async function cdpUp(port) {
|
|
1960
|
+
try {
|
|
1961
|
+
return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2e3) })).ok;
|
|
1962
|
+
} catch {
|
|
1963
|
+
return false;
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* pid of OUR automation Chrome's browser process on this port, or 0.
|
|
1968
|
+
*
|
|
1969
|
+
* PowerShell for the command lines: Node cannot read another process's command
|
|
1970
|
+
* line on Windows, and `wmic` is gone from Windows 11 25H2.
|
|
1971
|
+
*/
|
|
1972
|
+
function ourChromePid(port) {
|
|
1973
|
+
return ourChromeProcess(port)?.pid ?? 0;
|
|
1974
|
+
}
|
|
1975
|
+
/**
|
|
1976
|
+
* OUR Chrome's browser process on this port, with the profile it was started
|
|
1977
|
+
* on, or null. The command line comes back base64'd, so a profile path with
|
|
1978
|
+
* spaces or non-ASCII characters survives the console's code page.
|
|
1979
|
+
*/
|
|
1980
|
+
function ourChromeProcess(port) {
|
|
1981
|
+
const script = [
|
|
1982
|
+
"$ProgressPreference = 'SilentlyContinue'",
|
|
1983
|
+
`$re = '--remote-debugging-port=${port}(\\s|"|$)'`,
|
|
1984
|
+
"$sid = [System.Diagnostics.Process]::GetCurrentProcess().SessionId",
|
|
1985
|
+
"$b = Get-CimInstance Win32_Process -Filter \"Name = 'chrome.exe'\" |",
|
|
1986
|
+
" Where-Object { $_.SessionId -eq $sid -and $_.CommandLine -and $_.CommandLine -match $re -and $_.CommandLine -notmatch '--type=' } |",
|
|
1987
|
+
" Select-Object -First 1",
|
|
1988
|
+
"if ($b) { Write-Output ('BA-PID ' + [int]$b.ProcessId + ' ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($b.CommandLine))) } else { Write-Output 'BA-PID 0' }"
|
|
1989
|
+
].join("\n");
|
|
1990
|
+
try {
|
|
1991
|
+
const out = execFileSync("powershell.exe", [
|
|
1992
|
+
"-NoProfile",
|
|
1993
|
+
"-NonInteractive",
|
|
1994
|
+
"-ExecutionPolicy",
|
|
1995
|
+
"Bypass",
|
|
1996
|
+
"-EncodedCommand",
|
|
1997
|
+
Buffer.from(script, "utf16le").toString("base64")
|
|
1998
|
+
], {
|
|
1999
|
+
encoding: "utf8",
|
|
2000
|
+
stdio: [
|
|
2001
|
+
"ignore",
|
|
2002
|
+
"pipe",
|
|
2003
|
+
"ignore"
|
|
2004
|
+
],
|
|
2005
|
+
timeout: 2e4,
|
|
2006
|
+
windowsHide: true
|
|
2007
|
+
});
|
|
2008
|
+
const m = /^BA-PID (\d+)(?: (\S+))?\s*$/m.exec(out);
|
|
2009
|
+
const pid = Number(m?.[1] ?? 0);
|
|
2010
|
+
if (!pid) return null;
|
|
2011
|
+
return {
|
|
2012
|
+
pid,
|
|
2013
|
+
profile: userDataDir(m?.[2] ? Buffer.from(m[2], "base64").toString("utf8") : "")
|
|
2014
|
+
};
|
|
2015
|
+
} catch {
|
|
2016
|
+
return null;
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
/** --user-data-dir from a Windows command line, quoted ("--user-data-dir=C:\a b") or not. Pure. */
|
|
2020
|
+
function userDataDir(cmd) {
|
|
2021
|
+
const quoted = /"--user-data-dir=([^"]+)"/.exec(cmd) ?? /--user-data-dir="([^"]+)"/.exec(cmd);
|
|
2022
|
+
if (quoted) return quoted[1];
|
|
2023
|
+
return /--user-data-dir=(\S+)/.exec(cmd)?.[1] ?? null;
|
|
2024
|
+
}
|
|
2025
|
+
/**
|
|
2026
|
+
* Quit OUR Chrome on this port, from before the move to the pipe, through the
|
|
2027
|
+
* PORT (never closeBrowser(), which would address the pipe browser), and wait
|
|
2028
|
+
* for it to exit. taskkill only if it will not go.
|
|
2029
|
+
*/
|
|
2030
|
+
async function stopPortChrome(port, quit, say) {
|
|
2031
|
+
const pid = ourChromePid(port);
|
|
2032
|
+
if (!pid) return;
|
|
2033
|
+
await quit().catch(() => {});
|
|
2034
|
+
for (let i = 0; i < 60 && alive$1(pid); i++) await sleep$4(250);
|
|
2035
|
+
if (alive$1(pid)) {
|
|
2036
|
+
say(`Chrome (pid ${pid}) did not exit within 15s of being asked to quit; ending it.`);
|
|
2037
|
+
try {
|
|
2038
|
+
execFileSync("taskkill", [
|
|
2039
|
+
"/PID",
|
|
2040
|
+
String(pid),
|
|
2041
|
+
"/T",
|
|
2042
|
+
"/F"
|
|
2043
|
+
], { stdio: "ignore" });
|
|
2044
|
+
} catch {}
|
|
2045
|
+
for (let i = 0; i < 20 && alive$1(pid); i++) await sleep$4(250);
|
|
2046
|
+
}
|
|
2047
|
+
if (alive$1(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not starting another on its profile.`);
|
|
2048
|
+
}
|
|
2049
|
+
function alive$1(pid) {
|
|
2050
|
+
try {
|
|
2051
|
+
process.kill(pid, 0);
|
|
2052
|
+
return true;
|
|
2053
|
+
} catch {
|
|
2054
|
+
return false;
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
/**
|
|
2058
|
+
* Quit OUR Chrome on this port and wait until it has really exited.
|
|
2059
|
+
*
|
|
2060
|
+
* CDP Browser.close first — Chrome's own quit, which flushes the profile that
|
|
2061
|
+
* holds the logins. On Windows the process does exit after it (unlike macOS,
|
|
2062
|
+
* where it lingers windowless). taskkill /F only if it will not go.
|
|
2063
|
+
*/
|
|
2064
|
+
async function stopOurChrome(port, say) {
|
|
2065
|
+
const pid = ourChromePid(port);
|
|
2066
|
+
if (!pid) return await cdpUp(port) ? "not-ours" : "none";
|
|
2067
|
+
await closeBrowser().catch(() => {});
|
|
2068
|
+
for (let i = 0; i < 40 && alive$1(pid); i++) await sleep$4(250);
|
|
2069
|
+
if (alive$1(pid)) {
|
|
2070
|
+
say(`Chrome (pid ${pid}) did not exit within 10s of being asked to quit; ending it.`);
|
|
2071
|
+
try {
|
|
2072
|
+
execFileSync("taskkill", [
|
|
2073
|
+
"/PID",
|
|
2074
|
+
String(pid),
|
|
2075
|
+
"/T",
|
|
2076
|
+
"/F"
|
|
2077
|
+
], { stdio: "ignore" });
|
|
2078
|
+
} catch {}
|
|
2079
|
+
for (let i = 0; i < 20 && alive$1(pid); i++) await sleep$4(250);
|
|
2080
|
+
}
|
|
2081
|
+
if (alive$1(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not relaunching on top of it.`);
|
|
2082
|
+
for (let i = 0; i < 20 && await cdpUp(port); i++) await sleep$4(250);
|
|
2083
|
+
return "stopped";
|
|
2084
|
+
}
|
|
2085
|
+
/** Start the automation Chrome unless ours is already serving the port. */
|
|
2086
|
+
async function startChrome(port, profile, log) {
|
|
2087
|
+
if (await cdpUp(port)) return ourChromePid(port) ? { outcome: "already-running" } : { outcome: "not-ours" };
|
|
2088
|
+
const exe = windowsChromeExe();
|
|
2089
|
+
if (!exe) return { outcome: "no-chrome" };
|
|
2090
|
+
mkdirSync(profile, { recursive: true });
|
|
2091
|
+
mkdirSync(dirname(log), { recursive: true });
|
|
2092
|
+
try {
|
|
2093
|
+
if (statSync(log).size > 0) renameSync(log, `${log}.prev`);
|
|
2094
|
+
} catch {}
|
|
2095
|
+
const fd = openSync(log, "a");
|
|
2096
|
+
spawn(exe, [
|
|
2097
|
+
`--remote-debugging-port=${port}`,
|
|
2098
|
+
`--user-data-dir=${profile}`,
|
|
2099
|
+
"--no-first-run",
|
|
2100
|
+
"--no-default-browser-check",
|
|
2101
|
+
"about:blank"
|
|
2102
|
+
], {
|
|
2103
|
+
detached: true,
|
|
2104
|
+
stdio: [
|
|
2105
|
+
"ignore",
|
|
2106
|
+
fd,
|
|
2107
|
+
fd
|
|
2108
|
+
]
|
|
2109
|
+
}).unref();
|
|
2110
|
+
const started = Date.now();
|
|
2111
|
+
for (let i = 0; i < 240; i++) {
|
|
2112
|
+
if (await cdpUp(port)) return {
|
|
2113
|
+
outcome: "launched",
|
|
2114
|
+
seconds: Math.round((Date.now() - started) / 1e3)
|
|
2115
|
+
};
|
|
2116
|
+
await sleep$4(250);
|
|
2117
|
+
}
|
|
2118
|
+
return {
|
|
2119
|
+
outcome: "timeout",
|
|
2120
|
+
log
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
//#endregion
|
|
2124
|
+
//#region src/core/launch-pipe.ts
|
|
2125
|
+
const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2126
|
+
function brokerLogPath() {
|
|
2127
|
+
return join(brokerDir(), "broker.log");
|
|
2128
|
+
}
|
|
2129
|
+
function brokerState() {
|
|
2130
|
+
try {
|
|
2131
|
+
return JSON.parse(readFileSync(brokerStatePath(), "utf8"));
|
|
2132
|
+
} catch {
|
|
2133
|
+
return null;
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
function alive(pid) {
|
|
2137
|
+
if (!pid || pid < 1) return false;
|
|
2138
|
+
try {
|
|
2139
|
+
process.kill(pid, 0);
|
|
2140
|
+
return true;
|
|
2141
|
+
} catch {
|
|
2142
|
+
return false;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
/** A browser answers on the socket: the broker is there AND Chrome replies. */
|
|
2146
|
+
async function pipeUp(timeout = 3e3) {
|
|
2147
|
+
if (!await socketAnswers(socketPath(), timeout)) return false;
|
|
2148
|
+
return browserVersion(timeout).then(() => true, () => false);
|
|
2149
|
+
}
|
|
2150
|
+
/**
|
|
2151
|
+
* Is this user's Chrome from before the move still running on the port?
|
|
2152
|
+
*
|
|
2153
|
+
* It holds the profile, so a pipe Chrome cannot open it alongside — and it is
|
|
2154
|
+
* the very exposure the move exists to close. `launch` says so and stops;
|
|
2155
|
+
* `launch --restart` quits it.
|
|
2156
|
+
*/
|
|
2157
|
+
function portChromeRunning() {
|
|
2158
|
+
if (process.platform === "win32") return ourChromeProcess(cdpPort()) !== null;
|
|
2159
|
+
try {
|
|
2160
|
+
execFileSync("pgrep", [
|
|
2161
|
+
"-u",
|
|
2162
|
+
String(process.getuid?.() ?? -1),
|
|
2163
|
+
"-f",
|
|
2164
|
+
"--",
|
|
2165
|
+
`--remote-debugging-port=${cdpPort()}`
|
|
2166
|
+
], { stdio: "ignore" });
|
|
2167
|
+
return true;
|
|
2168
|
+
} catch {
|
|
2169
|
+
return false;
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
/**
|
|
2173
|
+
* The --user-data-dir of this user's browser on the port, read off its command
|
|
2174
|
+
* line. The launch script's `--stop` waits for THAT profile's lock to go before
|
|
2175
|
+
* it escalates; given the wrong one it sees no lock, decides the profile is
|
|
2176
|
+
* released, and SIGKILLs a browser mid-flush.
|
|
2177
|
+
*/
|
|
2178
|
+
function portChromeProfile() {
|
|
2179
|
+
if (process.platform === "win32") return ourChromeProcess(cdpPort())?.profile ?? null;
|
|
2180
|
+
let out;
|
|
2181
|
+
try {
|
|
2182
|
+
out = execFileSync("ps", ["-Ao", "uid=,command="], {
|
|
2183
|
+
encoding: "utf8",
|
|
2184
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
2185
|
+
stdio: [
|
|
2186
|
+
"ignore",
|
|
2187
|
+
"pipe",
|
|
2188
|
+
"ignore"
|
|
2189
|
+
]
|
|
2190
|
+
});
|
|
2191
|
+
} catch {
|
|
2192
|
+
return null;
|
|
2193
|
+
}
|
|
2194
|
+
const uid = String(process.getuid?.() ?? -1);
|
|
2195
|
+
for (const line of out.split("\n")) {
|
|
2196
|
+
const m = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
2197
|
+
if (!m || m[1] !== uid) continue;
|
|
2198
|
+
const cmd = m[2];
|
|
2199
|
+
if (!cmd.includes(`--remote-debugging-port=${cdpPort()}`) || cmd.includes("--type=")) continue;
|
|
2200
|
+
const d = /--user-data-dir=(.+?)(?= --|$)/.exec(cmd);
|
|
2201
|
+
if (d) return d[1];
|
|
2202
|
+
}
|
|
2203
|
+
return null;
|
|
2204
|
+
}
|
|
2205
|
+
/** Ask the browser on the port to quit the way its menu does, so it flushes its profile. */
|
|
2206
|
+
async function quitPortChrome() {
|
|
2207
|
+
const ws = (await (await fetch(`http://127.0.0.1:${cdpPort()}/json/version`, { signal: AbortSignal.timeout(2e3) })).json()).webSocketDebuggerUrl;
|
|
2208
|
+
const s = await connect(ws, { timeout: 3e3 });
|
|
2209
|
+
try {
|
|
2210
|
+
await s.send("Browser.close", {}, 3e3).catch(() => {});
|
|
2211
|
+
} finally {
|
|
2212
|
+
s.close();
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
/** Start the broker detached, and wait until Chrome answers through it. */
|
|
2216
|
+
async function startBroker(chrome, profile, chromeLog) {
|
|
2217
|
+
const start = Date.now();
|
|
2218
|
+
mkdirSync(brokerDir(), {
|
|
2219
|
+
recursive: true,
|
|
2220
|
+
mode: 448
|
|
2221
|
+
});
|
|
2222
|
+
const logFd = openSync(brokerLogPath(), "a", 384);
|
|
2223
|
+
const ctx = activeContextName();
|
|
2224
|
+
const { BAC_CONTEXT: _project, ...env } = process.env;
|
|
2225
|
+
const child = spawn(process.execPath, [
|
|
2226
|
+
process.argv[1],
|
|
2227
|
+
"broker",
|
|
2228
|
+
"--chrome",
|
|
2229
|
+
chrome,
|
|
2230
|
+
"--profile",
|
|
2231
|
+
profile,
|
|
2232
|
+
"--log",
|
|
2233
|
+
chromeLog,
|
|
2234
|
+
...ctx ? ["--context", ctx] : []
|
|
2235
|
+
], {
|
|
2236
|
+
detached: true,
|
|
2237
|
+
stdio: [
|
|
2238
|
+
"ignore",
|
|
2239
|
+
logFd,
|
|
2240
|
+
logFd
|
|
2241
|
+
],
|
|
2242
|
+
windowsHide: true,
|
|
2243
|
+
env
|
|
2244
|
+
});
|
|
2245
|
+
child.unref();
|
|
2246
|
+
for (let i = 0; i < 240; i++) {
|
|
2247
|
+
if (await pipeUp(1e3)) return {
|
|
2248
|
+
ok: true,
|
|
2249
|
+
seconds: Math.round((Date.now() - start) / 1e3)
|
|
2250
|
+
};
|
|
2251
|
+
if (child.exitCode !== null) break;
|
|
2252
|
+
await sleep$3(250);
|
|
2253
|
+
}
|
|
2254
|
+
return {
|
|
2255
|
+
ok: false,
|
|
2256
|
+
reason: `Chrome did not answer on ${socketPath()} within 60s.${refusedDevTools(chromeLog)} Broker log: ${brokerLogPath()}; Chrome's log: ${chromeLog}`
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
/**
|
|
2260
|
+
* Chrome runs, but refused DevTools on the pipe, and says why only in its log.
|
|
2261
|
+
* It refuses remote debugging on its DEFAULT profile, and decides which that is
|
|
2262
|
+
* from its app-data folder: on Windows with USERPROFILE pointed elsewhere it
|
|
2263
|
+
* could not find that folder, took our profile for its default, and the launch
|
|
2264
|
+
* timed out with nothing else to go on (2026-10-27).
|
|
2265
|
+
*/
|
|
2266
|
+
function refusedDevTools(chromeLog) {
|
|
2267
|
+
let tail = "";
|
|
2268
|
+
try {
|
|
2269
|
+
tail = readFileSync(chromeLog, "utf8").slice(-16384);
|
|
2270
|
+
} catch {
|
|
2271
|
+
return "";
|
|
2272
|
+
}
|
|
2273
|
+
if (!tail.includes("requires a non-default data directory")) return "";
|
|
2274
|
+
return ` Chrome refused DevTools: it took this profile for its default one ("DevTools remote debugging requires a non-default data directory"). It decides that from its own app-data folder, so this happens when it cannot find that folder: check that ${process.platform === "win32" ? "USERPROFILE and LOCALAPPDATA are" : "HOME is"} this account's own.`;
|
|
2275
|
+
}
|
|
2276
|
+
/**
|
|
2277
|
+
* Quit the pipe Chrome and wait for the broker to go, which is when Chrome has
|
|
2278
|
+
* exited and released the profile. Browser.close first, so the profile is
|
|
2279
|
+
* flushed; the broker's own SIGTERM path next; SIGKILL only after that.
|
|
2280
|
+
*/
|
|
2281
|
+
async function stopBroker(log) {
|
|
2282
|
+
const st = brokerState();
|
|
2283
|
+
await closeBrowser().catch(() => {});
|
|
2284
|
+
const gone = () => !alive(st?.brokerPid) && !alive(st?.chromePid) && !existsSync(brokerStatePath());
|
|
2285
|
+
for (let i = 0; i < 60 && !gone(); i++) await sleep$3(250);
|
|
2286
|
+
if (gone()) return;
|
|
2287
|
+
if (alive(st?.brokerPid)) {
|
|
2288
|
+
log("Chrome did not quit within 15s of being asked; asking the broker to stop it.");
|
|
2289
|
+
process.kill(st.brokerPid, "SIGTERM");
|
|
2290
|
+
for (let i = 0; i < 100 && !gone(); i++) await sleep$3(250);
|
|
2291
|
+
}
|
|
2292
|
+
if (gone()) return;
|
|
2293
|
+
log("Still running after 40s; sending SIGKILL.");
|
|
2294
|
+
for (const pid of [st?.chromePid, st?.brokerPid]) if (alive(pid)) process.kill(pid, "SIGKILL");
|
|
2295
|
+
for (let i = 0; i < 20 && (alive(st?.chromePid) || alive(st?.brokerPid)); i++) await sleep$3(250);
|
|
2296
|
+
if (alive(st?.chromePid)) throw new Error(`Chrome (pid ${st?.chromePid}) would not exit, even on SIGKILL. Not relaunching on top of it.`);
|
|
2297
|
+
}
|
|
2298
|
+
//#endregion
|
|
2299
|
+
//#region src/core/renderer-health.ts
|
|
2300
|
+
/** First attempt's budget. Later attempts double it. */
|
|
2301
|
+
const DEFAULT_TIMEOUT = 5e3;
|
|
2302
|
+
/** How many times we ask before we are willing to call a browser broken. */
|
|
2303
|
+
const DEFAULT_ATTEMPTS = 3;
|
|
2304
|
+
/** Breathing room between attempts — a browser mid-GC deserves a second look. */
|
|
2305
|
+
const RETRY_PAUSE = 400;
|
|
2306
|
+
/**
|
|
2307
|
+
* The verdict, from the probe and the corroborations — and from nothing else.
|
|
2308
|
+
*
|
|
2309
|
+
* Pure, and separate from the probing, because this is the decision that was
|
|
2310
|
+
* wrong: every failure used to become 'wedged' by default. Now 'wedged'
|
|
2311
|
+
* requires `rendezvous === false`, which is the only thing that has ever
|
|
2312
|
+
* actually meant it.
|
|
2313
|
+
*/
|
|
2314
|
+
function rendererVerdict(outcome, e) {
|
|
2315
|
+
if (outcome === "ok") return "healthy";
|
|
2316
|
+
if (e?.rendezvous === false) return "wedged";
|
|
2317
|
+
if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
|
|
2318
|
+
return "unknown";
|
|
2319
|
+
}
|
|
2320
|
+
/**
|
|
2321
|
+
* Create a throwaway tab, make its renderer prove it is alive, close it.
|
|
2322
|
+
*
|
|
2323
|
+
* Three things changed after 2026-09-11, and each of them is load-bearing:
|
|
2324
|
+
*
|
|
2325
|
+
* 1. It goes through `ensureRenderer`, so the probe opens its tab the way the
|
|
2326
|
+
* tool opens tabs AND gets the same wake treatment. A probe that is harsher
|
|
2327
|
+
* on itself than `goto` is on a real tab reports failures `goto` would not
|
|
2328
|
+
* have had.
|
|
2329
|
+
* 2. It retries with a doubling budget. One 5s timeout is not evidence of a
|
|
2330
|
+
* permanent condition; it is evidence of 5 seconds.
|
|
2331
|
+
* 3. It stops early when the Mach name is ABSENT — the one state where more
|
|
2332
|
+
* waiting is genuinely pointless — so the real failure is still reported
|
|
2333
|
+
* fast while a slow browser gets the benefit of the doubt.
|
|
2334
|
+
*/
|
|
2335
|
+
async function probeRenderer({ timeout, attempts } = {}) {
|
|
2336
|
+
const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
|
|
2337
|
+
const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
|
|
2338
|
+
const started = Date.now();
|
|
2339
|
+
let pageTargets = 0;
|
|
2340
|
+
try {
|
|
2341
|
+
pageTargets = (await listPageTargets()).length;
|
|
2342
|
+
} catch {}
|
|
2343
|
+
const tries = [];
|
|
2344
|
+
let evidence;
|
|
2345
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
2346
|
+
const budget = base * 2 ** i;
|
|
2347
|
+
tries.push(await probeOnce(budget));
|
|
2348
|
+
if (tries[tries.length - 1].outcome === "ok") return finish({
|
|
2349
|
+
ok: true,
|
|
2350
|
+
started,
|
|
2351
|
+
pageTargets,
|
|
2352
|
+
tries,
|
|
2353
|
+
evidence
|
|
2354
|
+
});
|
|
2355
|
+
evidence ??= gatherEvidence();
|
|
2356
|
+
if (evidence.rendezvous === false) break;
|
|
2357
|
+
if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
|
|
2358
|
+
}
|
|
2359
|
+
return finish({
|
|
2360
|
+
ok: false,
|
|
2361
|
+
started,
|
|
2362
|
+
pageTargets,
|
|
2363
|
+
tries,
|
|
2364
|
+
evidence
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
function finish({ ok, started, pageTargets, tries, evidence }) {
|
|
2368
|
+
const last = tries[tries.length - 1];
|
|
2369
|
+
const health = {
|
|
2370
|
+
ok,
|
|
2371
|
+
ms: Date.now() - started,
|
|
2372
|
+
pageTargets,
|
|
2373
|
+
reason: last?.reason,
|
|
2374
|
+
outcome: last?.outcome ?? "error",
|
|
2375
|
+
verdict: rendererVerdict(last?.outcome ?? "error", evidence),
|
|
2376
|
+
attempts: tries,
|
|
2377
|
+
evidence
|
|
2378
|
+
};
|
|
2379
|
+
recordProbe(health);
|
|
2380
|
+
return health;
|
|
2381
|
+
}
|
|
2382
|
+
/** One create -> ensure -> close cycle. */
|
|
2383
|
+
async function probeOnce(budget) {
|
|
2384
|
+
const started = Date.now();
|
|
2385
|
+
let targetId;
|
|
2386
|
+
try {
|
|
2387
|
+
targetId = await createTab("about:blank", { timeout: budget });
|
|
2388
|
+
} catch (e) {
|
|
2389
|
+
return {
|
|
2390
|
+
outcome: "error",
|
|
2391
|
+
budget,
|
|
2392
|
+
ms: Date.now() - started,
|
|
2393
|
+
woke: false,
|
|
2394
|
+
reason: `could not create a target at all: ${e?.message ?? e}`
|
|
2395
|
+
};
|
|
2396
|
+
}
|
|
2397
|
+
try {
|
|
2398
|
+
const r = await ensureRenderer(targetId, {
|
|
2399
|
+
grace: budget,
|
|
2400
|
+
budget
|
|
2401
|
+
});
|
|
2402
|
+
return {
|
|
2403
|
+
outcome: r.outcome,
|
|
2404
|
+
budget,
|
|
2405
|
+
ms: Date.now() - started,
|
|
2406
|
+
woke: r.woke,
|
|
2407
|
+
reason: r.reason
|
|
2408
|
+
};
|
|
2409
|
+
} finally {
|
|
2410
|
+
if (targetId) await closeTab(targetId).catch(() => {});
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
/**
|
|
2414
|
+
* Ask an EXISTING target's renderer to prove it is alive.
|
|
2415
|
+
*
|
|
2416
|
+
* Kept returning `string | null` because that is what `gc` wants (a reason to
|
|
2417
|
+
* print beside a tab it is about to close). New callers should prefer
|
|
2418
|
+
* `askRenderer`, which says WHICH failure it was.
|
|
2419
|
+
*/
|
|
2420
|
+
async function renderersAnswer(targetId, timeout = DEFAULT_TIMEOUT) {
|
|
2421
|
+
const r = await askRenderer(targetId, timeout);
|
|
2422
|
+
return r.outcome === "ok" ? null : r.reason ?? r.outcome;
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* The port we are actually talking to.
|
|
2426
|
+
*
|
|
2427
|
+
* NOT always `cdpPort()`: `BROWSER_AUTOMATION_CDP` points the CLI at an
|
|
2428
|
+
* arbitrary host:port, and everything here that shells out to `ps` or
|
|
2429
|
+
* `launchctl` has to ask about THAT browser. Using the uid-derived port instead
|
|
2430
|
+
* finds the user's default Chrome and cheerfully reports its health as if it
|
|
2431
|
+
* were the one being driven — caught while testing this module against a second
|
|
2432
|
+
* Chrome, where a perfectly healthy browser was accused of having lost a
|
|
2433
|
+
* bootstrap name that in fact belonged to a different pid.
|
|
2434
|
+
*/
|
|
2435
|
+
function targetPort() {
|
|
2436
|
+
const explicit = process.env.BROWSER_AUTOMATION_CDP;
|
|
2437
|
+
if (explicit) try {
|
|
1277
2438
|
const p = Number(new URL(explicit).port);
|
|
1278
2439
|
if (Number.isInteger(p) && p > 0) return p;
|
|
1279
2440
|
} catch {}
|
|
@@ -1299,7 +2460,7 @@ function chromeProcesses() {
|
|
|
1299
2460
|
const uid = String(process.getuid?.() ?? -1);
|
|
1300
2461
|
let out;
|
|
1301
2462
|
try {
|
|
1302
|
-
out = execFileSync("ps", ["-Ao", "pid=,uid=,command="], {
|
|
2463
|
+
out = execFileSync("ps", ["-Ao", "pid=,ppid=,uid=,command="], {
|
|
1303
2464
|
encoding: "utf8",
|
|
1304
2465
|
maxBuffer: 64 * 1024 * 1024,
|
|
1305
2466
|
stdio: [
|
|
@@ -1314,10 +2475,28 @@ function chromeProcesses() {
|
|
|
1314
2475
|
renderers: null
|
|
1315
2476
|
};
|
|
1316
2477
|
}
|
|
2478
|
+
if (usesPipe()) {
|
|
2479
|
+
const st = brokerState();
|
|
2480
|
+
const browser = st && out.split("\n").some((l) => new RegExp(`^\\s*${st.chromePid}\\s`).test(l)) ? st.chromePid : null;
|
|
2481
|
+
if (browser === null) return {
|
|
2482
|
+
browser: null,
|
|
2483
|
+
renderers: null
|
|
2484
|
+
};
|
|
2485
|
+
let renderers = 0;
|
|
2486
|
+
for (const line of out.split("\n")) {
|
|
2487
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
2488
|
+
if (!m || m[3] !== uid || !/--type=renderer\b/.test(m[4])) continue;
|
|
2489
|
+
if (Number(m[2]) === browser || m[4].includes(`--user-data-dir=${st.profile}`)) renderers++;
|
|
2490
|
+
}
|
|
2491
|
+
return {
|
|
2492
|
+
browser,
|
|
2493
|
+
renderers
|
|
2494
|
+
};
|
|
2495
|
+
}
|
|
1317
2496
|
let browser = null;
|
|
1318
2497
|
let renderers = 0;
|
|
1319
2498
|
for (const line of out.split("\n")) {
|
|
1320
|
-
const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
2499
|
+
const m = /^\s*(\d+)\s+\d+\s+(\d+)\s+(.*)$/.exec(line);
|
|
1321
2500
|
if (!m) continue;
|
|
1322
2501
|
const [, pid, u, cmd] = m;
|
|
1323
2502
|
if (u !== uid || !cmd.includes(flag)) continue;
|
|
@@ -1370,7 +2549,9 @@ function gatherEvidence() {
|
|
|
1370
2549
|
/** Where `launch` writes Chrome's stdout/stderr — Chrome logs the real reason there. */
|
|
1371
2550
|
function chromeLogPath() {
|
|
1372
2551
|
const tmp = process.platform === "win32" ? tmpdir() : process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
|
|
1373
|
-
|
|
2552
|
+
if (process.env.BROWSER_AUTOMATION_LOG) return process.env.BROWSER_AUTOMATION_LOG;
|
|
2553
|
+
if (usesPipe()) return join(brokerDir(), "chrome.log");
|
|
2554
|
+
return `${tmp}/chrome-${targetPort()}.log`;
|
|
1374
2555
|
}
|
|
1375
2556
|
function probeLogPath() {
|
|
1376
2557
|
return process.env.BROWSER_AUTOMATION_PROBE_LOG || join(homedir(), ".browser-automation", "renderer-probes.jsonl");
|
|
@@ -1641,16 +2822,12 @@ function describeNotShown(outcome) {
|
|
|
1641
2822
|
//#endregion
|
|
1642
2823
|
//#region src/core/context-launch.ts
|
|
1643
2824
|
async function reachable() {
|
|
1644
|
-
|
|
1645
|
-
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
1646
|
-
} catch {
|
|
1647
|
-
return false;
|
|
1648
|
-
}
|
|
2825
|
+
return pipeUp(1500);
|
|
1649
2826
|
}
|
|
1650
2827
|
async function ensureContextChrome() {
|
|
1651
2828
|
const ctx = activeContext();
|
|
1652
2829
|
if (!ctx || await reachable()) return;
|
|
1653
|
-
consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile
|
|
2830
|
+
consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile. Whatever you sign in to or install there is kept.`);
|
|
1654
2831
|
if (spawnSync(process.execPath, [
|
|
1655
2832
|
process.argv[1],
|
|
1656
2833
|
"launch",
|
|
@@ -1658,6 +2835,24 @@ async function ensureContextChrome() {
|
|
|
1658
2835
|
ctx.name
|
|
1659
2836
|
], { stdio: "inherit" }).status !== 0 || !await reachable()) throw new Error(`could not start the Chrome for context "${ctx.name}" — try: browser-automation launch --context ${ctx.name}`);
|
|
1660
2837
|
}
|
|
2838
|
+
/**
|
|
2839
|
+
* Give a context made before 0.6.1 its window name and colour
|
|
2840
|
+
* (core/profile-clone.ts), the next time its Chrome is about to start. Only
|
|
2841
|
+
* while that Chrome is not running — it would write its own settings back
|
|
2842
|
+
* over these — and only once: a colour the person picked afterwards is theirs.
|
|
2843
|
+
*/
|
|
2844
|
+
async function personalizeIfNeeded() {
|
|
2845
|
+
const ctx = activeContext();
|
|
2846
|
+
if (!ctx || ctx.color || await reachable()) return;
|
|
2847
|
+
const used = new Set(listContextRecords().map((r) => r.color));
|
|
2848
|
+
const color = CONTEXT_COLORS.find((c) => !used.has(c.name)) ?? CONTEXT_COLORS[0];
|
|
2849
|
+
personalizeProfile(ctx.profileDir, ctx.name, color.argb);
|
|
2850
|
+
saveContextRecord({
|
|
2851
|
+
...ctx,
|
|
2852
|
+
color: color.name
|
|
2853
|
+
});
|
|
2854
|
+
consola$1.info(`Context "${ctx.name}": its window is ${color.name} from now on, and its profile is named "${ctx.name}".`);
|
|
2855
|
+
}
|
|
1661
2856
|
//#endregion
|
|
1662
2857
|
//#region src/commands/new.ts
|
|
1663
2858
|
const newCommand = define({
|
|
@@ -1957,7 +3152,67 @@ function clickExpr(ref) {
|
|
|
1957
3152
|
const el=__baFind(${r});
|
|
1958
3153
|
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
1959
3154
|
el.scrollIntoView({block:'center',inline:'center'});
|
|
3155
|
+
const tag=el.tagName.toLowerCase();
|
|
3156
|
+
if(el.getAttribute('role')==='option'&&el.closest('[data-radix-select-viewport]')){
|
|
3157
|
+
el.focus({preventScroll:true});
|
|
3158
|
+
const k={key:'Enter',code:'Enter',keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,view:window};
|
|
3159
|
+
el.dispatchEvent(new KeyboardEvent('keydown',k));
|
|
3160
|
+
el.dispatchEvent(new KeyboardEvent('keyup',k));
|
|
3161
|
+
return {ok:true,tag,via:'keyboard'};
|
|
3162
|
+
}
|
|
3163
|
+
const b=el.getBoundingClientRect();
|
|
3164
|
+
const x=b.left+b.width/2,y=b.top+b.height/2;
|
|
3165
|
+
const o={bubbles:true,cancelable:true,composed:true,view:window,clientX:x,clientY:y,screenX:x,screenY:y,button:0,buttons:1,detail:1,pointerId:1,pointerType:'mouse',isPrimary:true};
|
|
3166
|
+
const up={...o,buttons:0};
|
|
3167
|
+
el.dispatchEvent(new PointerEvent('pointerover',o));
|
|
3168
|
+
el.dispatchEvent(new PointerEvent('pointerenter',{...o,bubbles:false,cancelable:false}));
|
|
3169
|
+
el.dispatchEvent(new MouseEvent('mouseover',o));
|
|
3170
|
+
const down=el.dispatchEvent(new PointerEvent('pointerdown',o));
|
|
3171
|
+
if(down&&el.dispatchEvent(new MouseEvent('mousedown',o))&&typeof el.focus==='function')el.focus({preventScroll:true});
|
|
3172
|
+
el.dispatchEvent(new PointerEvent('pointerup',up));
|
|
3173
|
+
if(down)el.dispatchEvent(new MouseEvent('mouseup',up));
|
|
1960
3174
|
el.click();
|
|
3175
|
+
return {ok:true,tag};
|
|
3176
|
+
})()`;
|
|
3177
|
+
}
|
|
3178
|
+
const KEY_CODES = {
|
|
3179
|
+
Enter: 13,
|
|
3180
|
+
Escape: 27,
|
|
3181
|
+
Tab: 9,
|
|
3182
|
+
" ": 32,
|
|
3183
|
+
Backspace: 8,
|
|
3184
|
+
Delete: 46,
|
|
3185
|
+
ArrowUp: 38,
|
|
3186
|
+
ArrowDown: 40,
|
|
3187
|
+
ArrowLeft: 37,
|
|
3188
|
+
ArrowRight: 39,
|
|
3189
|
+
Home: 36,
|
|
3190
|
+
End: 35,
|
|
3191
|
+
PageUp: 33,
|
|
3192
|
+
PageDown: 34
|
|
3193
|
+
};
|
|
3194
|
+
function keyExpr(ref, key) {
|
|
3195
|
+
const r = JSON.stringify(ref);
|
|
3196
|
+
const name = key === "Space" ? " " : key;
|
|
3197
|
+
const keyCode = KEY_CODES[name] ?? (name.length === 1 ? name.toUpperCase().charCodeAt(0) : 0);
|
|
3198
|
+
const code = name === " " ? "Space" : /^[a-z]$/i.test(name) ? `Key${name.toUpperCase()}` : /^[0-9]$/.test(name) ? `Digit${name}` : name;
|
|
3199
|
+
return WALK + `(() => {
|
|
3200
|
+
const el=__baFind(${r});
|
|
3201
|
+
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
3202
|
+
el.scrollIntoView({block:'center',inline:'center'});
|
|
3203
|
+
if(typeof el.focus==='function')el.focus({preventScroll:true});
|
|
3204
|
+
const t=document.activeElement&&el.contains(document.activeElement)?document.activeElement:el;
|
|
3205
|
+
const k={...${JSON.stringify({
|
|
3206
|
+
key: name,
|
|
3207
|
+
code,
|
|
3208
|
+
keyCode,
|
|
3209
|
+
which: keyCode,
|
|
3210
|
+
bubbles: true,
|
|
3211
|
+
cancelable: true,
|
|
3212
|
+
composed: true
|
|
3213
|
+
})},view:window};
|
|
3214
|
+
t.dispatchEvent(new KeyboardEvent('keydown',k));
|
|
3215
|
+
t.dispatchEvent(new KeyboardEvent('keyup',k));
|
|
1961
3216
|
return {ok:true,tag:el.tagName.toLowerCase()};
|
|
1962
3217
|
})()`;
|
|
1963
3218
|
}
|
|
@@ -2127,7 +3382,7 @@ const snapshotCommand = define({
|
|
|
2127
3382
|
});
|
|
2128
3383
|
//#endregion
|
|
2129
3384
|
//#region src/commands/click.ts
|
|
2130
|
-
const sleep$
|
|
3385
|
+
const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2131
3386
|
const clickCommand = define({
|
|
2132
3387
|
name: "click",
|
|
2133
3388
|
description: "Click an element by ref (from the latest snapshot)",
|
|
@@ -2139,7 +3394,7 @@ const clickCommand = define({
|
|
|
2139
3394
|
},
|
|
2140
3395
|
trusted: {
|
|
2141
3396
|
type: "boolean",
|
|
2142
|
-
description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched el.click(). Makes the renderer treat the tab as focused+visible and WAITS until it reports so (CDP input no-ops on a backgrounded tab) — without selecting the tab in its window, so the person's own tab keeps their typing, then waits for the element to be actionable (stable position + unoccluded hit-test) before pressing — mirroring Playwright.
|
|
3397
|
+
description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched pointer + mouse sequence and el.click(). The default needs no focus and already drives Radix/headless-UI triggers and items; use this only for widgets that check isTrusted. Makes the renderer treat the tab as focused+visible and WAITS until it reports so (CDP input no-ops on a backgrounded tab) — without selecting the tab in its window, so the person's own tab keeps their typing, then waits for the element to be actionable (stable position + unoccluded hit-test) before pressing — mirroring Playwright. Canonical case: artdeco dropdown menu items (LinkedIn More→Connect), which demand isTrusted and animate in, so a default click, or an immediate trusted click on stale coordinates, only highlights them without firing."
|
|
2143
3398
|
}
|
|
2144
3399
|
},
|
|
2145
3400
|
async run(ctx) {
|
|
@@ -2168,7 +3423,7 @@ const clickCommand = define({
|
|
|
2168
3423
|
while (Date.now() < focusDeadline) {
|
|
2169
3424
|
const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
|
|
2170
3425
|
if (f && f.f && f.v === "visible") break;
|
|
2171
|
-
await sleep$
|
|
3426
|
+
await sleep$2(50);
|
|
2172
3427
|
}
|
|
2173
3428
|
let prev = null;
|
|
2174
3429
|
let point = null;
|
|
@@ -2194,7 +3449,7 @@ const clickCommand = define({
|
|
|
2194
3449
|
x: a.x,
|
|
2195
3450
|
y: a.y
|
|
2196
3451
|
};
|
|
2197
|
-
await sleep$
|
|
3452
|
+
await sleep$2(60);
|
|
2198
3453
|
}
|
|
2199
3454
|
if (!point) {
|
|
2200
3455
|
consola$1.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
|
|
@@ -2209,7 +3464,7 @@ const clickCommand = define({
|
|
|
2209
3464
|
buttons: 0,
|
|
2210
3465
|
pointerType: "mouse"
|
|
2211
3466
|
});
|
|
2212
|
-
await sleep$
|
|
3467
|
+
await sleep$2(20);
|
|
2213
3468
|
await s.send("Input.dispatchMouseEvent", {
|
|
2214
3469
|
type: "mousePressed",
|
|
2215
3470
|
x,
|
|
@@ -2239,7 +3494,42 @@ const clickCommand = define({
|
|
|
2239
3494
|
consola$1.error(r.err);
|
|
2240
3495
|
process.exit(1);
|
|
2241
3496
|
}
|
|
2242
|
-
consola$1.success(`clicked ${ref} <${r.tag}
|
|
3497
|
+
consola$1.success(`clicked ${ref} <${r.tag}>${r.via ? ` (${r.via})` : ""}`);
|
|
3498
|
+
}
|
|
3499
|
+
});
|
|
3500
|
+
//#endregion
|
|
3501
|
+
//#region src/commands/key.ts
|
|
3502
|
+
const keyCommand = define({
|
|
3503
|
+
name: "key",
|
|
3504
|
+
description: "Press one key on an element by ref: focus it, then dispatch keydown + keyup (Enter, Escape, ArrowDown, Space, a character…), without bringing the tab to the front",
|
|
3505
|
+
args: {
|
|
3506
|
+
...targetArgs,
|
|
3507
|
+
ref: {
|
|
3508
|
+
type: "positional",
|
|
3509
|
+
description: "Element ref, e.g. e7"
|
|
3510
|
+
},
|
|
3511
|
+
key: {
|
|
3512
|
+
type: "positional",
|
|
3513
|
+
description: "An event.key name: Enter, Escape, Tab, ArrowDown, Space, or one character"
|
|
3514
|
+
}
|
|
3515
|
+
},
|
|
3516
|
+
async run(ctx) {
|
|
3517
|
+
const ref = ctx.positionals[1];
|
|
3518
|
+
const key = ctx.positionals[2];
|
|
3519
|
+
if (!ref || !isValidRef(ref)) {
|
|
3520
|
+
consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
|
|
3521
|
+
process.exit(1);
|
|
3522
|
+
}
|
|
3523
|
+
if (!key) {
|
|
3524
|
+
consola$1.error("A key is required, e.g. `browser-automation key e7 Enter`");
|
|
3525
|
+
process.exit(1);
|
|
3526
|
+
}
|
|
3527
|
+
const r = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), keyExpr(ref, key));
|
|
3528
|
+
if (r.err) {
|
|
3529
|
+
consola$1.error(r.err);
|
|
3530
|
+
process.exit(1);
|
|
3531
|
+
}
|
|
3532
|
+
consola$1.success(`pressed ${key} on ${ref} <${r.tag}>`);
|
|
2243
3533
|
}
|
|
2244
3534
|
});
|
|
2245
3535
|
//#endregion
|
|
@@ -2343,7 +3633,7 @@ const readCommand = define({
|
|
|
2343
3633
|
});
|
|
2344
3634
|
//#endregion
|
|
2345
3635
|
//#region src/commands/focus.ts
|
|
2346
|
-
const sleep$
|
|
3636
|
+
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2347
3637
|
/**
|
|
2348
3638
|
* Make a tab believe it is the visible one.
|
|
2349
3639
|
*
|
|
@@ -2413,7 +3703,7 @@ const focusCommand = define({
|
|
|
2413
3703
|
returnByValue: true
|
|
2414
3704
|
})).result?.value ?? last;
|
|
2415
3705
|
if (last.focused && last.visibility === "visible") break;
|
|
2416
|
-
await sleep$
|
|
3706
|
+
await sleep$1(50);
|
|
2417
3707
|
}
|
|
2418
3708
|
return last;
|
|
2419
3709
|
});
|
|
@@ -2779,7 +4069,7 @@ const uploadCommand = define({
|
|
|
2779
4069
|
});
|
|
2780
4070
|
//#endregion
|
|
2781
4071
|
//#region src/commands/drop.ts
|
|
2782
|
-
const sleep
|
|
4072
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2783
4073
|
/** Resolve each path to absolute and verify it's an existing file. */
|
|
2784
4074
|
function absFiles(paths) {
|
|
2785
4075
|
return paths.map((p) => {
|
|
@@ -2881,7 +4171,7 @@ const dropCommand = define({
|
|
|
2881
4171
|
while (Date.now() < focusDeadline) {
|
|
2882
4172
|
const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
|
|
2883
4173
|
if (f && f.f && f.v === "visible") break;
|
|
2884
|
-
await sleep
|
|
4174
|
+
await sleep(50);
|
|
2885
4175
|
}
|
|
2886
4176
|
let prev = null;
|
|
2887
4177
|
let point = null;
|
|
@@ -2907,7 +4197,7 @@ const dropCommand = define({
|
|
|
2907
4197
|
x: a.x,
|
|
2908
4198
|
y: a.y
|
|
2909
4199
|
};
|
|
2910
|
-
await sleep
|
|
4200
|
+
await sleep(60);
|
|
2911
4201
|
}
|
|
2912
4202
|
if (!point) {
|
|
2913
4203
|
consola$1.error(`<${ref}> not actionable for a drop: ${lastReason}`);
|
|
@@ -2931,7 +4221,7 @@ const dropCommand = define({
|
|
|
2931
4221
|
y,
|
|
2932
4222
|
data
|
|
2933
4223
|
});
|
|
2934
|
-
await sleep
|
|
4224
|
+
await sleep(20);
|
|
2935
4225
|
await s.send("Input.dispatchDragEvent", {
|
|
2936
4226
|
type: "drop",
|
|
2937
4227
|
x,
|
|
@@ -3154,7 +4444,8 @@ const listCommand = define({
|
|
|
3154
4444
|
} else if (sessions.length) consola$1.log(`# sessions (0 live)`);
|
|
3155
4445
|
if (stale.length && !ctx.values.all) consola$1.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
|
|
3156
4446
|
if (sessions.length) consola$1.log("");
|
|
3157
|
-
|
|
4447
|
+
const ctxName = activeContextName();
|
|
4448
|
+
consola$1.log(`# open tabs (${targets.length}) in ${ctxName ? `context "${ctxName}"'s Chrome` : "your automation Chrome"} ${usesPipe() ? "" : ` (:${cdpPort()})`} — address with -t <id> or -m <substr>`);
|
|
3158
4449
|
for (const t of targets) {
|
|
3159
4450
|
const owner = sessions.find((s) => s.targetId === t.id);
|
|
3160
4451
|
const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
|
|
@@ -3189,273 +4480,68 @@ const closeCommand = define({
|
|
|
3189
4480
|
targetId = await resolveExistingTargetId(opts);
|
|
3190
4481
|
} catch (e) {
|
|
3191
4482
|
consola$1.warn(e instanceof Error ? e.message : String(e));
|
|
3192
|
-
return;
|
|
3193
|
-
}
|
|
3194
|
-
if (ctx.values.tab) {
|
|
3195
|
-
const ok = await closeTab(targetId).catch(() => false);
|
|
3196
|
-
consola$1.log(ok ? `Closed tab ${targetId.slice(0, 12)}….` : `Tab ${targetId.slice(0, 12)}… was already gone.`);
|
|
3197
|
-
}
|
|
3198
|
-
const forgotten = [];
|
|
3199
|
-
for (const s of listSessions()) if (s.targetId === targetId) {
|
|
3200
|
-
deleteSession(s.name);
|
|
3201
|
-
forgotten.push(s.name);
|
|
3202
|
-
}
|
|
3203
|
-
if (!opts.match && !opts.target) {
|
|
3204
|
-
const name = opts.session || defaultSessionName();
|
|
3205
|
-
if (!forgotten.includes(name)) {
|
|
3206
|
-
deleteSession(name);
|
|
3207
|
-
forgotten.push(name);
|
|
3208
|
-
}
|
|
3209
|
-
}
|
|
3210
|
-
if (forgotten.length) consola$1.success(`Forgot session(s): ${forgotten.join(", ")}.`);
|
|
3211
|
-
else if (!ctx.values.tab) consola$1.info("No session bound to that tab and --tab not given — nothing to do.");
|
|
3212
|
-
}
|
|
3213
|
-
});
|
|
3214
|
-
//#endregion
|
|
3215
|
-
//#region src/commands/bind.ts
|
|
3216
|
-
const bindCommand = define({
|
|
3217
|
-
name: "bind",
|
|
3218
|
-
description: "Adopt an already-open tab into a session name (pick it with -m <substr> or -t <id>)",
|
|
3219
|
-
args: { ...targetArgs },
|
|
3220
|
-
async run(ctx) {
|
|
3221
|
-
const name = ctx.values.session || defaultSessionName();
|
|
3222
|
-
const match = ctx.values.match;
|
|
3223
|
-
const target = ctx.values.target;
|
|
3224
|
-
if (!match && !target) {
|
|
3225
|
-
consola$1.error("Pick the tab to adopt with -m <url/title substr> or -t <targetId>. See `browser-automation list`.");
|
|
3226
|
-
process.exit(1);
|
|
3227
|
-
}
|
|
3228
|
-
let targetId;
|
|
3229
|
-
let url;
|
|
3230
|
-
if (target) {
|
|
3231
|
-
targetId = await resolveTargetIdArg(target);
|
|
3232
|
-
url = (await listPageTargets()).find((p) => p.id === targetId)?.url;
|
|
3233
|
-
} else {
|
|
3234
|
-
const hit = await matchOne(match, ctx.values.first);
|
|
3235
|
-
targetId = hit.id;
|
|
3236
|
-
url = hit.url;
|
|
3237
|
-
}
|
|
3238
|
-
saveSession({
|
|
3239
|
-
name,
|
|
3240
|
-
targetId,
|
|
3241
|
-
url,
|
|
3242
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3243
|
-
});
|
|
3244
|
-
consola$1.success(`Bound session "${name}" → ${url ?? targetId}`);
|
|
3245
|
-
}
|
|
3246
|
-
});
|
|
3247
|
-
//#endregion
|
|
3248
|
-
//#region src/core/paths.ts
|
|
3249
|
-
function packageRoot() {
|
|
3250
|
-
return dirname(dirname(fileURLToPath(import.meta.url)));
|
|
3251
|
-
}
|
|
3252
|
-
function launchScriptPath() {
|
|
3253
|
-
return join(packageRoot(), "scripts", "launch-chrome.sh");
|
|
3254
|
-
}
|
|
3255
|
-
//#endregion
|
|
3256
|
-
//#region src/core/chrome-path.ts
|
|
3257
|
-
function executable(p) {
|
|
3258
|
-
try {
|
|
3259
|
-
if (!statSync(p).isFile()) return false;
|
|
3260
|
-
if (process.platform === "win32") return true;
|
|
3261
|
-
accessSync(p, constants.X_OK);
|
|
3262
|
-
return true;
|
|
3263
|
-
} catch {
|
|
3264
|
-
return false;
|
|
3265
|
-
}
|
|
3266
|
-
}
|
|
3267
|
-
const MAC_BINARY = join("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
|
|
3268
|
-
function platformCandidates() {
|
|
3269
|
-
if (process.platform === "darwin") return [{
|
|
3270
|
-
path: join(process.env.BROWSER_AUTOMATION_TEST_SYSTEM_APPS || "/Applications", MAC_BINARY),
|
|
3271
|
-
source: "/Applications"
|
|
3272
|
-
}, {
|
|
3273
|
-
path: join(homedir(), "Applications", MAC_BINARY),
|
|
3274
|
-
source: "~/Applications"
|
|
3275
|
-
}];
|
|
3276
|
-
if (process.platform === "win32") {
|
|
3277
|
-
const out = [];
|
|
3278
|
-
const exe = join("Google", "Chrome", "Application", "chrome.exe");
|
|
3279
|
-
if (process.env.PROGRAMFILES) out.push({
|
|
3280
|
-
path: join(process.env.PROGRAMFILES, exe),
|
|
3281
|
-
source: "Program Files"
|
|
3282
|
-
});
|
|
3283
|
-
if (process.env["PROGRAMFILES(X86)"]) out.push({
|
|
3284
|
-
path: join(process.env["PROGRAMFILES(X86)"], exe),
|
|
3285
|
-
source: "Program Files (x86)"
|
|
3286
|
-
});
|
|
3287
|
-
if (process.env.LOCALAPPDATA) out.push({
|
|
3288
|
-
path: join(process.env.LOCALAPPDATA, exe),
|
|
3289
|
-
source: "%LOCALAPPDATA%"
|
|
3290
|
-
});
|
|
3291
|
-
return out;
|
|
3292
|
-
}
|
|
3293
|
-
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
|
|
3294
|
-
return [
|
|
3295
|
-
"google-chrome",
|
|
3296
|
-
"google-chrome-stable",
|
|
3297
|
-
"chromium",
|
|
3298
|
-
"chromium-browser"
|
|
3299
|
-
].flatMap((name) => dirs.map((d) => ({
|
|
3300
|
-
path: join(d, name),
|
|
3301
|
-
source: `PATH (${name})`
|
|
3302
|
-
})));
|
|
3303
|
-
}
|
|
3304
|
-
function chromeExecutable() {
|
|
3305
|
-
let ignored;
|
|
3306
|
-
for (const name of ["BROWSER_AUTOMATION_CHROME", "CHROME"]) {
|
|
3307
|
-
const v = process.env[name];
|
|
3308
|
-
if (!v) continue;
|
|
3309
|
-
if (executable(v)) return {
|
|
3310
|
-
path: v,
|
|
3311
|
-
source: name
|
|
3312
|
-
};
|
|
3313
|
-
ignored ??= `${name}=${v} is not an executable file`;
|
|
4483
|
+
return;
|
|
4484
|
+
}
|
|
4485
|
+
if (ctx.values.tab) {
|
|
4486
|
+
const ok = await closeTab(targetId).catch(() => false);
|
|
4487
|
+
consola$1.log(ok ? `Closed tab ${targetId.slice(0, 12)}….` : `Tab ${targetId.slice(0, 12)}… was already gone.`);
|
|
4488
|
+
}
|
|
4489
|
+
const forgotten = [];
|
|
4490
|
+
for (const s of listSessions()) if (s.targetId === targetId) {
|
|
4491
|
+
deleteSession(s.name);
|
|
4492
|
+
forgotten.push(s.name);
|
|
4493
|
+
}
|
|
4494
|
+
if (!opts.match && !opts.target) {
|
|
4495
|
+
const name = opts.session || defaultSessionName();
|
|
4496
|
+
if (!forgotten.includes(name)) {
|
|
4497
|
+
deleteSession(name);
|
|
4498
|
+
forgotten.push(name);
|
|
4499
|
+
}
|
|
4500
|
+
}
|
|
4501
|
+
if (forgotten.length) consola$1.success(`Forgot session(s): ${forgotten.join(", ")}.`);
|
|
4502
|
+
else if (!ctx.values.tab) consola$1.info("No session bound to that tab and --tab not given — nothing to do.");
|
|
3314
4503
|
}
|
|
3315
|
-
|
|
3316
|
-
return hit ? {
|
|
3317
|
-
path: hit.path,
|
|
3318
|
-
source: hit.source,
|
|
3319
|
-
ignored
|
|
3320
|
-
} : {
|
|
3321
|
-
path: null,
|
|
3322
|
-
source: "not found",
|
|
3323
|
-
ignored
|
|
3324
|
-
};
|
|
3325
|
-
}
|
|
3326
|
-
/** Where we looked, for a "not found" message. */
|
|
3327
|
-
function chromeSearchDescription() {
|
|
3328
|
-
if (process.platform === "darwin") return "/Applications and ~/Applications";
|
|
3329
|
-
if (process.platform === "win32") return "Program Files, Program Files (x86) and %LOCALAPPDATA%";
|
|
3330
|
-
return "google-chrome, google-chrome-stable, chromium and chromium-browser on PATH";
|
|
3331
|
-
}
|
|
4504
|
+
});
|
|
3332
4505
|
//#endregion
|
|
3333
|
-
//#region src/
|
|
3334
|
-
const
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
"Write-Output ('BA-PID ' + [int]$b)"
|
|
3362
|
-
].join("\n");
|
|
3363
|
-
try {
|
|
3364
|
-
const out = execFileSync("powershell.exe", [
|
|
3365
|
-
"-NoProfile",
|
|
3366
|
-
"-NonInteractive",
|
|
3367
|
-
"-ExecutionPolicy",
|
|
3368
|
-
"Bypass",
|
|
3369
|
-
"-EncodedCommand",
|
|
3370
|
-
Buffer.from(script, "utf16le").toString("base64")
|
|
3371
|
-
], {
|
|
3372
|
-
encoding: "utf8",
|
|
3373
|
-
stdio: [
|
|
3374
|
-
"ignore",
|
|
3375
|
-
"pipe",
|
|
3376
|
-
"ignore"
|
|
3377
|
-
],
|
|
3378
|
-
timeout: 2e4,
|
|
3379
|
-
windowsHide: true
|
|
4506
|
+
//#region src/commands/bind.ts
|
|
4507
|
+
const bindCommand = define({
|
|
4508
|
+
name: "bind",
|
|
4509
|
+
description: "Adopt an already-open tab into a session name (pick it with -m <substr> or -t <id>)",
|
|
4510
|
+
args: { ...targetArgs },
|
|
4511
|
+
async run(ctx) {
|
|
4512
|
+
const name = ctx.values.session || defaultSessionName();
|
|
4513
|
+
const match = ctx.values.match;
|
|
4514
|
+
const target = ctx.values.target;
|
|
4515
|
+
if (!match && !target) {
|
|
4516
|
+
consola$1.error("Pick the tab to adopt with -m <url/title substr> or -t <targetId>. See `browser-automation list`.");
|
|
4517
|
+
process.exit(1);
|
|
4518
|
+
}
|
|
4519
|
+
let targetId;
|
|
4520
|
+
let url;
|
|
4521
|
+
if (target) {
|
|
4522
|
+
targetId = await resolveTargetIdArg(target);
|
|
4523
|
+
url = (await listPageTargets()).find((p) => p.id === targetId)?.url;
|
|
4524
|
+
} else {
|
|
4525
|
+
const hit = await matchOne(match, ctx.values.first);
|
|
4526
|
+
targetId = hit.id;
|
|
4527
|
+
url = hit.url;
|
|
4528
|
+
}
|
|
4529
|
+
saveSession({
|
|
4530
|
+
name,
|
|
4531
|
+
targetId,
|
|
4532
|
+
url,
|
|
4533
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3380
4534
|
});
|
|
3381
|
-
|
|
3382
|
-
} catch {
|
|
3383
|
-
return 0;
|
|
3384
|
-
}
|
|
3385
|
-
}
|
|
3386
|
-
function alive(pid) {
|
|
3387
|
-
try {
|
|
3388
|
-
process.kill(pid, 0);
|
|
3389
|
-
return true;
|
|
3390
|
-
} catch {
|
|
3391
|
-
return false;
|
|
3392
|
-
}
|
|
3393
|
-
}
|
|
3394
|
-
/**
|
|
3395
|
-
* Quit OUR Chrome on this port and wait until it has really exited.
|
|
3396
|
-
*
|
|
3397
|
-
* CDP Browser.close first — Chrome's own quit, which flushes the profile that
|
|
3398
|
-
* holds the logins. On Windows the process does exit after it (unlike macOS,
|
|
3399
|
-
* where it lingers windowless). taskkill /F only if it will not go.
|
|
3400
|
-
*/
|
|
3401
|
-
async function stopOurChrome(port, say) {
|
|
3402
|
-
const pid = ourChromePid(port);
|
|
3403
|
-
if (!pid) return await cdpUp(port) ? "not-ours" : "none";
|
|
3404
|
-
await closeBrowser().catch(() => {});
|
|
3405
|
-
for (let i = 0; i < 40 && alive(pid); i++) await sleep(250);
|
|
3406
|
-
if (alive(pid)) {
|
|
3407
|
-
say(`Chrome (pid ${pid}) did not exit within 10s of being asked to quit; ending it.`);
|
|
3408
|
-
try {
|
|
3409
|
-
execFileSync("taskkill", [
|
|
3410
|
-
"/PID",
|
|
3411
|
-
String(pid),
|
|
3412
|
-
"/T",
|
|
3413
|
-
"/F"
|
|
3414
|
-
], { stdio: "ignore" });
|
|
3415
|
-
} catch {}
|
|
3416
|
-
for (let i = 0; i < 20 && alive(pid); i++) await sleep(250);
|
|
4535
|
+
consola$1.success(`Bound session "${name}" → ${url ?? targetId}`);
|
|
3417
4536
|
}
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
|
|
4537
|
+
});
|
|
4538
|
+
//#endregion
|
|
4539
|
+
//#region src/core/paths.ts
|
|
4540
|
+
function packageRoot() {
|
|
4541
|
+
return dirname(dirname(fileURLToPath(import.meta.url)));
|
|
3421
4542
|
}
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
if (await cdpUp(port)) return ourChromePid(port) ? { outcome: "already-running" } : { outcome: "not-ours" };
|
|
3425
|
-
const exe = windowsChromeExe();
|
|
3426
|
-
if (!exe) return { outcome: "no-chrome" };
|
|
3427
|
-
mkdirSync(profile, { recursive: true });
|
|
3428
|
-
mkdirSync(dirname(log), { recursive: true });
|
|
3429
|
-
try {
|
|
3430
|
-
if (statSync(log).size > 0) renameSync(log, `${log}.prev`);
|
|
3431
|
-
} catch {}
|
|
3432
|
-
const fd = openSync(log, "a");
|
|
3433
|
-
spawn(exe, [
|
|
3434
|
-
`--remote-debugging-port=${port}`,
|
|
3435
|
-
`--user-data-dir=${profile}`,
|
|
3436
|
-
"--no-first-run",
|
|
3437
|
-
"--no-default-browser-check",
|
|
3438
|
-
"about:blank"
|
|
3439
|
-
], {
|
|
3440
|
-
detached: true,
|
|
3441
|
-
stdio: [
|
|
3442
|
-
"ignore",
|
|
3443
|
-
fd,
|
|
3444
|
-
fd
|
|
3445
|
-
]
|
|
3446
|
-
}).unref();
|
|
3447
|
-
const started = Date.now();
|
|
3448
|
-
for (let i = 0; i < 240; i++) {
|
|
3449
|
-
if (await cdpUp(port)) return {
|
|
3450
|
-
outcome: "launched",
|
|
3451
|
-
seconds: Math.round((Date.now() - started) / 1e3)
|
|
3452
|
-
};
|
|
3453
|
-
await sleep(250);
|
|
3454
|
-
}
|
|
3455
|
-
return {
|
|
3456
|
-
outcome: "timeout",
|
|
3457
|
-
log
|
|
3458
|
-
};
|
|
4543
|
+
function launchScriptPath() {
|
|
4544
|
+
return join(packageRoot(), "scripts", "launch-chrome.sh");
|
|
3459
4545
|
}
|
|
3460
4546
|
//#endregion
|
|
3461
4547
|
//#region src/commands/launch.ts
|
|
@@ -3473,7 +4559,10 @@ const launchCommand = define({
|
|
|
3473
4559
|
}
|
|
3474
4560
|
},
|
|
3475
4561
|
async run(ctx) {
|
|
3476
|
-
if (
|
|
4562
|
+
if (usesPipe()) {
|
|
4563
|
+
if (!await launchPipe(ctx.values.status === true, ctx.values.restart === true)) process.exit(1);
|
|
4564
|
+
if (ctx.values.status) return;
|
|
4565
|
+
} else if (process.platform === "win32") {
|
|
3477
4566
|
if (!await launchWindows(ctx.values.status === true, ctx.values.restart === true)) process.exit(1);
|
|
3478
4567
|
if (ctx.values.status) return;
|
|
3479
4568
|
} else {
|
|
@@ -3511,6 +4600,7 @@ const launchCommand = define({
|
|
|
3511
4600
|
if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
|
|
3512
4601
|
else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
|
|
3513
4602
|
else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
|
|
4603
|
+
if (!ctx.values.status) await personalizeIfNeeded();
|
|
3514
4604
|
const chrome = chromeExecutable();
|
|
3515
4605
|
if (chrome.ignored) consola$1.warn(`Ignoring ${chrome.ignored}.`);
|
|
3516
4606
|
const r = bash([
|
|
@@ -3568,6 +4658,7 @@ async function launchWindows(statusOnly, restart) {
|
|
|
3568
4658
|
const m = migrateProfile();
|
|
3569
4659
|
if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
|
|
3570
4660
|
else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
|
|
4661
|
+
await personalizeIfNeeded();
|
|
3571
4662
|
const r = await startChrome(port, m.dir, chromeLogPath());
|
|
3572
4663
|
switch (r.outcome) {
|
|
3573
4664
|
case "already-running":
|
|
@@ -3590,6 +4681,94 @@ async function launchWindows(statusOnly, restart) {
|
|
|
3590
4681
|
return false;
|
|
3591
4682
|
}
|
|
3592
4683
|
}
|
|
4684
|
+
/** Two profile paths are the same folder (Windows paths ignore case and slash direction). */
|
|
4685
|
+
function sameDir(a, b) {
|
|
4686
|
+
if (process.platform !== "win32") return a === b;
|
|
4687
|
+
const n = (p) => resolve(p).toLowerCase();
|
|
4688
|
+
return n(a) === n(b);
|
|
4689
|
+
}
|
|
4690
|
+
/**
|
|
4691
|
+
* Chrome on the DevTools pipe, behind the broker: every platform, and every
|
|
4692
|
+
* login context (its own broker). Returns false on a failure that must stop
|
|
4693
|
+
* `launch` before the health check.
|
|
4694
|
+
*/
|
|
4695
|
+
async function launchPipe(statusOnly, restart) {
|
|
4696
|
+
const sock = () => socketPath();
|
|
4697
|
+
const ctxName = activeContextName();
|
|
4698
|
+
const driveIt = `Drive it with: browser-automation goto -s <session>${ctxName ? ` --context ${ctxName} <url> (a session opened in it follows it; later commands need no --context)` : " <url>"}`;
|
|
4699
|
+
if (statusOnly) {
|
|
4700
|
+
const up = await pipeUp();
|
|
4701
|
+
consola$1.log(up ? `Chrome is up on the pipe (${sock()})` : `Chrome is NOT running (nothing answers on ${sock()})`);
|
|
4702
|
+
return up;
|
|
4703
|
+
}
|
|
4704
|
+
if (portChromeRunning()) {
|
|
4705
|
+
const theirs = portChromeProfile();
|
|
4706
|
+
const mine = resolveProfile().dir;
|
|
4707
|
+
const where = `port ${cdpPort()}${theirs ? ` (profile ${theirs})` : ""}`;
|
|
4708
|
+
if (!theirs || !sameDir(theirs, mine)) consola$1.warn(`This account also has a browser listening on ${where}; anything on this computer can drive it. It is not this one, so it is left alone.`);
|
|
4709
|
+
else if (!restart) {
|
|
4710
|
+
consola$1.error(`This browser is still running on ${where}, from before the move to the pipe, and anything on this computer can drive it. Switch it over:\n browser-automation launch --restart\nThat quits it (closing its tabs; logins are kept) and starts it again on the pipe.`);
|
|
4711
|
+
return false;
|
|
4712
|
+
} else {
|
|
4713
|
+
consola$1.info(`Quitting this browser on ${where} to start it again on the pipe.`);
|
|
4714
|
+
if (process.platform === "win32") try {
|
|
4715
|
+
await stopPortChrome(cdpPort(), quitPortChrome, (s) => consola$1.warn(s));
|
|
4716
|
+
} catch (e) {
|
|
4717
|
+
consola$1.error(String(e?.message ?? e));
|
|
4718
|
+
return false;
|
|
4719
|
+
}
|
|
4720
|
+
else {
|
|
4721
|
+
await quitPortChrome().catch(() => {});
|
|
4722
|
+
if (spawnSync("bash", [
|
|
4723
|
+
launchScriptPath(),
|
|
4724
|
+
"--port",
|
|
4725
|
+
String(cdpPort()),
|
|
4726
|
+
"--stop",
|
|
4727
|
+
"--profile",
|
|
4728
|
+
theirs
|
|
4729
|
+
], { stdio: "inherit" }).status !== 0) return false;
|
|
4730
|
+
}
|
|
4731
|
+
}
|
|
4732
|
+
}
|
|
4733
|
+
if (await pipeUp()) {
|
|
4734
|
+
if (!restart) {
|
|
4735
|
+
consola$1.log(`Already running on the pipe (${sock()}).`);
|
|
4736
|
+
consola$1.log(driveIt);
|
|
4737
|
+
return true;
|
|
4738
|
+
}
|
|
4739
|
+
const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
|
|
4740
|
+
consola$1.info(`Restarting Chrome — closing ${tabs ?? "?"} open tab(s).`);
|
|
4741
|
+
try {
|
|
4742
|
+
await stopBroker((s) => consola$1.warn(s));
|
|
4743
|
+
} catch (e) {
|
|
4744
|
+
consola$1.error(String(e?.message ?? e));
|
|
4745
|
+
return false;
|
|
4746
|
+
}
|
|
4747
|
+
}
|
|
4748
|
+
const m = migrateProfile();
|
|
4749
|
+
if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
|
|
4750
|
+
else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
|
|
4751
|
+
await personalizeIfNeeded();
|
|
4752
|
+
if (process.platform === "darwin" && m.dir === legacyProfileDir()) {
|
|
4753
|
+
consola$1.error(`The profile is still inside Chrome's own folder (${m.dir}), where macOS refuses a Chrome started with the DevTools pipe.${m.detail ? ` ${m.detail}` : ""}`);
|
|
4754
|
+
return false;
|
|
4755
|
+
}
|
|
4756
|
+
const chrome = chromeExecutable();
|
|
4757
|
+
if (chrome.ignored) consola$1.warn(`Ignoring ${chrome.ignored}.`);
|
|
4758
|
+
if (!chrome.path) {
|
|
4759
|
+
consola$1.error("Chrome not found. Install it, or set BROWSER_AUTOMATION_CHROME to its binary.");
|
|
4760
|
+
return false;
|
|
4761
|
+
}
|
|
4762
|
+
const r = await startBroker(chrome.path, m.dir, chromeLogPath());
|
|
4763
|
+
if (!r.ok) {
|
|
4764
|
+
consola$1.error(r.reason);
|
|
4765
|
+
return false;
|
|
4766
|
+
}
|
|
4767
|
+
consola$1.log(`Chrome launched on the pipe in ${r.seconds}s (profile: ${m.dir}, ${process.platform === "win32" ? "pipe" : "socket"}: ${sock()}, log: ${chromeLogPath()})`);
|
|
4768
|
+
consola$1.log(`No debugging port is open: only this account can reach it, through the ${process.platform === "win32" ? "named pipe" : "socket"}.`);
|
|
4769
|
+
consola$1.log(driveIt);
|
|
4770
|
+
return true;
|
|
4771
|
+
}
|
|
3593
4772
|
//#endregion
|
|
3594
4773
|
//#region src/commands/doctor.ts
|
|
3595
4774
|
/**
|
|
@@ -3626,7 +4805,10 @@ const doctorCommand = define({
|
|
|
3626
4805
|
const bad = (m) => consola$1.log(` ✗ ${m}`);
|
|
3627
4806
|
if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
|
|
3628
4807
|
else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
|
|
3629
|
-
|
|
4808
|
+
if (usesPipe()) {
|
|
4809
|
+
consola$1.log(` • Transport: DevTools pipe, served on ${socketPath()} — no debugging port open`);
|
|
4810
|
+
if (portChromeRunning()) bad(`a Chrome of yours is still listening on port ${cdpPort()} (from before the pipe): anything on this computer can drive it. Switch it over: browser-automation launch --restart`);
|
|
4811
|
+
} else consola$1.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
|
|
3630
4812
|
const profile = resolveProfile();
|
|
3631
4813
|
consola$1.log(` • Profile: ${profile.dir}`);
|
|
3632
4814
|
if (profile.source === "legacy") {
|
|
@@ -3638,7 +4820,13 @@ const doctorCommand = define({
|
|
|
3638
4820
|
else bad(`Chrome binary: not found (looked in ${chromeSearchDescription()}) — \`launch\` cannot start one. Install Chrome, or set CHROME.`);
|
|
3639
4821
|
if (chrome.ignored) consola$1.log(` ⚠ ignoring ${chrome.ignored}`);
|
|
3640
4822
|
let version;
|
|
3641
|
-
try {
|
|
4823
|
+
if (usesPipe()) try {
|
|
4824
|
+
ok(`Chrome reachable: ${(await browserVersion()).product}`);
|
|
4825
|
+
} catch {
|
|
4826
|
+
bad(`No browser on ${socketPath()} — run: browser-automation launch`);
|
|
4827
|
+
return;
|
|
4828
|
+
}
|
|
4829
|
+
else try {
|
|
3642
4830
|
version = await (await fetch(`${cdpHost()}/json/version`)).json();
|
|
3643
4831
|
if (!portIsOurs()) {
|
|
3644
4832
|
bad(`something on port ${cdpPort()} is serving CDP (${version.Browser}) but this account did not start it — it is another user's Chrome, and anything you drive would happen in their browser. Quit Chrome in that account, or set BROWSER_AUTOMATION_PORT to a free port.`);
|
|
@@ -3833,21 +5021,70 @@ const profileCommand = define({
|
|
|
3833
5021
|
}
|
|
3834
5022
|
});
|
|
3835
5023
|
//#endregion
|
|
5024
|
+
//#region src/commands/broker.ts
|
|
5025
|
+
const brokerCommand = define({
|
|
5026
|
+
name: "broker",
|
|
5027
|
+
description: "Internal: hold Chrome's DevTools pipe and serve it on this user's socket. `launch` starts it.",
|
|
5028
|
+
args: {
|
|
5029
|
+
chrome: {
|
|
5030
|
+
type: "string",
|
|
5031
|
+
description: "Chrome binary",
|
|
5032
|
+
required: true
|
|
5033
|
+
},
|
|
5034
|
+
profile: {
|
|
5035
|
+
type: "string",
|
|
5036
|
+
description: "--user-data-dir",
|
|
5037
|
+
required: true
|
|
5038
|
+
},
|
|
5039
|
+
log: {
|
|
5040
|
+
type: "string",
|
|
5041
|
+
description: "Chrome's stdout/stderr",
|
|
5042
|
+
required: true
|
|
5043
|
+
}
|
|
5044
|
+
},
|
|
5045
|
+
async run(ctx) {
|
|
5046
|
+
await runBroker({
|
|
5047
|
+
chrome: ctx.values.chrome,
|
|
5048
|
+
profile: ctx.values.profile,
|
|
5049
|
+
log: ctx.values.log,
|
|
5050
|
+
dir: brokerDir(),
|
|
5051
|
+
socket: process.platform === "win32" ? windowsPipeName() : socketPath()
|
|
5052
|
+
});
|
|
5053
|
+
}
|
|
5054
|
+
});
|
|
5055
|
+
//#endregion
|
|
3836
5056
|
//#region src/commands/context.ts
|
|
3837
|
-
|
|
5057
|
+
/** Run `fn` as if `name` (or, when undefined, the user's own automation Chrome) were the active context. */
|
|
5058
|
+
async function asChrome(name, fn) {
|
|
5059
|
+
const saved = process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
5060
|
+
if (name) process.env.BROWSER_AUTOMATION_CONTEXT = name;
|
|
5061
|
+
else delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
5062
|
+
try {
|
|
5063
|
+
return await fn();
|
|
5064
|
+
} finally {
|
|
5065
|
+
if (saved === void 0) delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
5066
|
+
else process.env.BROWSER_AUTOMATION_CONTEXT = saved;
|
|
5067
|
+
}
|
|
5068
|
+
}
|
|
5069
|
+
/** Is the active Chrome up? Over its pipe, or, for the person's own with BROWSER_AUTOMATION_CDP set, its port. */
|
|
5070
|
+
async function up() {
|
|
5071
|
+
if (usesPipe()) return pipeUp(1500);
|
|
3838
5072
|
try {
|
|
3839
|
-
return (await fetch(
|
|
5073
|
+
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
3840
5074
|
} catch {
|
|
3841
5075
|
return false;
|
|
3842
5076
|
}
|
|
3843
5077
|
}
|
|
5078
|
+
async function running(r) {
|
|
5079
|
+
return asChrome(r.name, up);
|
|
5080
|
+
}
|
|
3844
5081
|
/**
|
|
3845
5082
|
* Login contexts (core/context-store.ts): a separate Chrome per extra account,
|
|
3846
5083
|
* started by `new`/`goto --context <name>`. This lists, stops and forgets them.
|
|
3847
5084
|
*/
|
|
3848
5085
|
const contextCommand = define({
|
|
3849
5086
|
name: "context",
|
|
3850
|
-
description: "Login contexts — a separate Chrome (own profile, own
|
|
5087
|
+
description: "Login contexts — a separate Chrome (own profile, own pipe, own window) per extra account, so a second login sits next to your own; opened by `new`/`goto --context <name>`, which start it on demand. `context` lists them; `context stop <name>` quits one; `context forget <name>` removes it (its sessions too), keeping its profile unless --delete-profile.",
|
|
3851
5088
|
args: { "delete-profile": {
|
|
3852
5089
|
type: "boolean",
|
|
3853
5090
|
description: "With forget: also delete the context's Chrome profile — its logins and extensions. Not undoable."
|
|
@@ -3857,16 +5094,18 @@ const contextCommand = define({
|
|
|
3857
5094
|
const name = ctx.positionals[2];
|
|
3858
5095
|
if (action === "list" || action === "ls") {
|
|
3859
5096
|
const all = listContextRecords();
|
|
3860
|
-
if (!all.length) {
|
|
3861
|
-
consola$1.log("No login contexts. Open one with: browser-automation new -s <session> --context <name> <url>");
|
|
3862
|
-
return;
|
|
3863
|
-
}
|
|
3864
5097
|
const sessions = listAllSessions();
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
const
|
|
3868
|
-
|
|
3869
|
-
|
|
5098
|
+
const project = process.env.BAC_CONTEXT || void 0;
|
|
5099
|
+
const row = async (label, name, color) => asChrome(name, async () => {
|
|
5100
|
+
const on = await up();
|
|
5101
|
+
const pid = on ? browserPid() : null;
|
|
5102
|
+
const users = sessions.filter((s) => (s.context ?? void 0) === name).map((s) => s.name);
|
|
5103
|
+
return ` ${label.padEnd(22)} [${on ? "running" : "stopped"}]${pid ? ` pid ${pid}` : ""}${color ? ` ${color} window` : ""}${name && name === project ? " ← BAC_CONTEXT" : ""}${users.length > 6 ? ` ${users.length} sessions` : users.length ? ` sessions: ${users.join(", ")}` : ""}`;
|
|
5104
|
+
});
|
|
5105
|
+
consola$1.log(`# Chromes driven by browser-automation, each on its own pipe — login contexts' profiles under ${contextsDir()}`);
|
|
5106
|
+
consola$1.log(await row("(your automation Chrome)", void 0, void 0));
|
|
5107
|
+
for (const r of all) consola$1.log(await row(r.name, r.name, r.color));
|
|
5108
|
+
if (!all.length) consola$1.log(" No login contexts yet. Open one with: browser-automation new -s <session> --context <name> <url>");
|
|
3870
5109
|
return;
|
|
3871
5110
|
}
|
|
3872
5111
|
const r = name ? loadContextRecord(name) : null;
|
|
@@ -3920,6 +5159,7 @@ const subCommands = new Map([
|
|
|
3920
5159
|
["snapshot", snapshotCommand],
|
|
3921
5160
|
["snap", snapshotCommand],
|
|
3922
5161
|
["click", clickCommand],
|
|
5162
|
+
["key", keyCommand],
|
|
3923
5163
|
["fill", fillCommand],
|
|
3924
5164
|
["read", readCommand],
|
|
3925
5165
|
["focus", focusCommand],
|
|
@@ -3941,6 +5181,7 @@ const subCommands = new Map([
|
|
|
3941
5181
|
["prune", gcCommand],
|
|
3942
5182
|
["port", portCommand],
|
|
3943
5183
|
["profile", profileCommand],
|
|
5184
|
+
["broker", brokerCommand],
|
|
3944
5185
|
["context", contextCommand]
|
|
3945
5186
|
]);
|
|
3946
5187
|
function withRealPositionals(cmd, real) {
|