omowright 0.0.0 → 0.1.0
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/LICENSE +21 -0
- package/README.md +282 -2
- package/TOOLS.md +366 -0
- package/bin/omowright-cloak.mjs +112 -0
- package/package.json +57 -4
- package/presets/agent-events/SKILL.md +75 -0
- package/presets/captcha/SKILL.md +129 -0
- package/presets/chrome/SKILL.md +84 -0
- package/presets/cloak-bridge/SKILL.md +43 -0
- package/presets/network/SKILL.md +126 -0
- package/presets/visual-browse/SKILL.md +103 -0
- package/skills/omowright/SKILL.md +193 -0
- package/skills/omowright/references/1password.md +118 -0
- package/skills/omowright/references/browserskill.md +186 -0
- package/skills/omowright/references/eval-kernel.md +100 -0
- package/skills/omowright/references/frames-layers-human.md +123 -0
- package/skills/omowright/references/quickstart.md +96 -0
- package/skills/omowright/references/stealth.md +174 -0
- package/src/agent-tabs.js +160 -0
- package/src/bridge-schemas.js +44 -0
- package/src/bridge-transport.js +57 -0
- package/src/browser-process.js +122 -0
- package/src/bsk/browser-signals.js +90 -0
- package/src/bsk/browsers.js +114 -0
- package/src/bsk/connect.js +45 -0
- package/src/bsk/daemon-info.js +100 -0
- package/src/bsk/external-extension.js +110 -0
- package/src/bsk/identify-browser.js +88 -0
- package/src/bsk/install-cli.js +81 -0
- package/src/bsk/ipc-client.js +236 -0
- package/src/bsk/onboard.js +133 -0
- package/src/bsk/screenshot.js +49 -0
- package/src/bsk/session.js +131 -0
- package/src/bsk/snapshot.js +56 -0
- package/src/bsk/targets.js +25 -0
- package/src/captcha-wait.js +74 -0
- package/src/captcha.js +142 -0
- package/src/cdp-errors.js +23 -0
- package/src/cdp-methods.js +61 -0
- package/src/chrome-profile.js +176 -0
- package/src/chrome.js +192 -0
- package/src/cloak-profile.js +266 -0
- package/src/connection.js +135 -0
- package/src/cookies.js +29 -0
- package/src/core.js +1710 -0
- package/src/cua.js +74 -0
- package/src/dialog-policy.js +80 -0
- package/src/emulate.js +127 -0
- package/src/events.js +111 -0
- package/src/frames-snapshot.js +138 -0
- package/src/har.js +103 -0
- package/src/human-handoff.js +122 -0
- package/src/index.js +86 -0
- package/src/injected.js +3 -0
- package/src/instance-lock.js +230 -0
- package/src/instances.js +493 -0
- package/src/internal-capability.js +1 -0
- package/src/launch-endpoint.js +185 -0
- package/src/layers.js +138 -0
- package/src/llm.js +201 -0
- package/src/lock-file.js +130 -0
- package/src/native-host-win32.js +201 -0
- package/src/network-events.js +201 -0
- package/src/network-snoop.js +229 -0
- package/src/open-shadow-query.js +22 -0
- package/src/owner-only.js +109 -0
- package/src/page-bundle.js +1397 -0
- package/src/page-routes.js +94 -0
- package/src/pipe.js +391 -0
- package/src/routes.js +256 -0
- package/src/running-browser.js +85 -0
- package/src/scroll-collect.js +73 -0
- package/src/serial-emitter.js +17 -0
- package/src/shared-connections.js +278 -0
- package/src/snapshot-diff.js +75 -0
- package/src/trace.js +183 -0
- package/src/url-match.js +148 -0
- package/src/viewport.js +12 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createRoutes } from "./routes.js";
|
|
3
|
+
|
|
4
|
+
const predicates = new WeakMap();
|
|
5
|
+
const handlers = new WeakMap();
|
|
6
|
+
const abortReasons = {
|
|
7
|
+
aborted: "Aborted", accessdenied: "AccessDenied", addressunreachable: "AddressUnreachable",
|
|
8
|
+
blockedbyclient: "BlockedByClient", blockedbyresponse: "BlockedByResponse",
|
|
9
|
+
connectionaborted: "ConnectionAborted", connectionclosed: "ConnectionClosed",
|
|
10
|
+
connectionfailed: "ConnectionFailed", connectionrefused: "ConnectionRefused",
|
|
11
|
+
connectionreset: "ConnectionReset", internetdisconnected: "InternetDisconnected",
|
|
12
|
+
namenotresolved: "NameNotResolved", timedout: "TimedOut", failed: "Failed",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function urlMatcher(match) {
|
|
16
|
+
if (typeof match === "function") {
|
|
17
|
+
if (!predicates.has(match)) predicates.set(match, request => match(new URL(request.url)));
|
|
18
|
+
return predicates.get(match);
|
|
19
|
+
}
|
|
20
|
+
if (match instanceof RegExp) {
|
|
21
|
+
// Avoid stateful /g and /y matching while keeping unroute's pattern identity.
|
|
22
|
+
return new RegExp(match.source, match.flags.replace(/[gy]/g, ""));
|
|
23
|
+
}
|
|
24
|
+
if (typeof match !== "string") throw new TypeError("url must be a glob string, RegExp or predicate");
|
|
25
|
+
let source = "";
|
|
26
|
+
let groups = 0;
|
|
27
|
+
for (let index = 0; index < match.length; index += 1) {
|
|
28
|
+
const char = match[index];
|
|
29
|
+
if (char === "\\") {
|
|
30
|
+
const literal = match[++index] ?? "\\";
|
|
31
|
+
source += literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
32
|
+
} else if (char === "*") {
|
|
33
|
+
const start = index;
|
|
34
|
+
while (match[index + 1] === "*") index += 1;
|
|
35
|
+
const deep = index > start && (start === 0 || match[start - 1] === "/") &&
|
|
36
|
+
(index + 1 === match.length || match[index + 1] === "/");
|
|
37
|
+
if (deep && match[index + 1] === "/") {
|
|
38
|
+
source += "(?:.*/)?";
|
|
39
|
+
index += 1;
|
|
40
|
+
} else source += deep ? ".*" : "[^/]*";
|
|
41
|
+
} else if (char === "{") { source += "(?:"; groups += 1; }
|
|
42
|
+
else if (char === "}" && groups > 0) { source += ")"; groups -= 1; }
|
|
43
|
+
else if (char === "," && groups > 0) source += "|";
|
|
44
|
+
else source += char.replace(/[.*+?^$()|[\]\\]/g, "\\$&");
|
|
45
|
+
}
|
|
46
|
+
return new RegExp(`^${source}$`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function adaptHandler(handler) {
|
|
50
|
+
if (typeof handler !== "function") throw new TypeError("handler must be a function");
|
|
51
|
+
if (!handlers.has(handler)) handlers.set(handler, raw => {
|
|
52
|
+
const request = {
|
|
53
|
+
url: () => raw.request.url,
|
|
54
|
+
method: () => raw.request.method,
|
|
55
|
+
headers: () => Object.fromEntries(Object.entries(raw.request.headers).map(([key, value]) => [key.toLowerCase(), value])),
|
|
56
|
+
postData: () => raw.request.postData ?? null,
|
|
57
|
+
resourceType: () => raw.request.resourceType?.toLowerCase(),
|
|
58
|
+
};
|
|
59
|
+
const route = {
|
|
60
|
+
request: () => request,
|
|
61
|
+
continue: overrides => raw.continue(overrides),
|
|
62
|
+
fallback: () => raw.fallback(),
|
|
63
|
+
abort(errorCode = "failed") {
|
|
64
|
+
const reason = abortReasons[errorCode];
|
|
65
|
+
if (!reason) throw new TypeError(`Unknown error code: ${errorCode}`);
|
|
66
|
+
return raw.abort(reason);
|
|
67
|
+
},
|
|
68
|
+
async fulfill(options = {}) {
|
|
69
|
+
let { body, contentType } = options;
|
|
70
|
+
if (options.json !== undefined) {
|
|
71
|
+
body = JSON.stringify(options.json);
|
|
72
|
+
contentType ??= "application/json";
|
|
73
|
+
} else if (options.path !== undefined) {
|
|
74
|
+
body = await readFile(options.path);
|
|
75
|
+
}
|
|
76
|
+
return raw.fulfill({ ...options, body, contentType });
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
return handler(route, request);
|
|
80
|
+
});
|
|
81
|
+
return handlers.get(handler);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function pageRoute(page, match, handler, options = {}) {
|
|
85
|
+
return createRoutes(page).route(urlMatcher(match), adaptHandler(handler), { times: options.times, prepend: true });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function pageUnroute(page, match, handler) {
|
|
89
|
+
return createRoutes(page).unroute(urlMatcher(match), handler === undefined ? undefined : adaptHandler(handler));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function pageUnrouteAll(page) {
|
|
93
|
+
return createRoutes(page).unroute();
|
|
94
|
+
}
|
package/src/pipe.js
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { finished } from "node:stream/promises";
|
|
3
|
+
import {
|
|
4
|
+
browserSpawnDetached,
|
|
5
|
+
profileDirFromArgs,
|
|
6
|
+
reapOrphanedBrowser,
|
|
7
|
+
removeBrowserPidFile,
|
|
8
|
+
terminateChild,
|
|
9
|
+
writeBrowserPidFile,
|
|
10
|
+
} from "./browser-process.js";
|
|
11
|
+
import { BrowserConnection } from "./connection.js";
|
|
12
|
+
import { Dialog, answerWithPolicy, normalizeDialogPolicy } from "./dialog-policy.js";
|
|
13
|
+
import { targetCreationCapability } from "./internal-capability.js";
|
|
14
|
+
import { SerialEmitter as Emittery } from "./serial-emitter.js";
|
|
15
|
+
import { CdpCommandTimeoutError, CdpPipeClosedError, CdpSessionDetachedError, CdpSessionCrashedError } from "./cdp-errors.js";
|
|
16
|
+
export { CdpCommandTimeoutError, CdpPipeClosedError, CdpSessionDetachedError, CdpSessionCrashedError } from "./cdp-errors.js";
|
|
17
|
+
|
|
18
|
+
const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
|
|
19
|
+
const DEFAULT_READINESS_TIMEOUT_MS = 10_000;
|
|
20
|
+
const GRACEFUL_CLOSE_TIMEOUT_MS = 2_000;
|
|
21
|
+
const STDIO_TAIL_LIMIT = 16_384;
|
|
22
|
+
const EXIT_STDERR_DRAIN_MS = 1_000;
|
|
23
|
+
|
|
24
|
+
export class PipeCdpClient {
|
|
25
|
+
#child;
|
|
26
|
+
#writeStream;
|
|
27
|
+
#readStream;
|
|
28
|
+
#buffer = Buffer.alloc(0);
|
|
29
|
+
#seq = 1;
|
|
30
|
+
#pending = new Map();
|
|
31
|
+
#closedSessions = new Set();
|
|
32
|
+
#sessionTargets = new Map();
|
|
33
|
+
#launch;
|
|
34
|
+
#launchId;
|
|
35
|
+
#launchedAt = 0;
|
|
36
|
+
#receivedBytes = 0;
|
|
37
|
+
#malformedFrameCount = 0;
|
|
38
|
+
#events = new Emittery();
|
|
39
|
+
#connected = false;
|
|
40
|
+
#commandTimeoutMs;
|
|
41
|
+
#readinessTimeoutMs;
|
|
42
|
+
#browserPath;
|
|
43
|
+
#browserArgs;
|
|
44
|
+
#spawnOptions;
|
|
45
|
+
#stdioTail = "";
|
|
46
|
+
#stderrHead = "";
|
|
47
|
+
#dialogPolicy;
|
|
48
|
+
transportEvents = new Emittery();
|
|
49
|
+
logId;
|
|
50
|
+
|
|
51
|
+
constructor({ browserPath, browserArgs = [], spawnOptions = {}, commandTimeoutMs, readinessTimeoutMs, logId, dialogPolicy }) {
|
|
52
|
+
if (!browserPath) throw new TypeError("PipeCdpClient requires browserPath");
|
|
53
|
+
this.#browserPath = browserPath;
|
|
54
|
+
this.#browserArgs = browserArgs;
|
|
55
|
+
this.#spawnOptions = spawnOptions;
|
|
56
|
+
this.#commandTimeoutMs = commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
|
|
57
|
+
this.#readinessTimeoutMs = readinessTimeoutMs ?? DEFAULT_READINESS_TIMEOUT_MS;
|
|
58
|
+
this.logId = logId ?? `cdp-pipe-${Date.now()}`;
|
|
59
|
+
this.#dialogPolicy = normalizeDialogPolicy(dialogPolicy);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get isConnected() { return this.#connected; }
|
|
63
|
+
get isHeadless() { return this.#browserArgs.some(arg => /^--headless(?:=|$)/.test(arg)); }
|
|
64
|
+
get childProcess() { return this.#child; }
|
|
65
|
+
get dialogPolicy() { return this.#dialogPolicy; }
|
|
66
|
+
|
|
67
|
+
setDialogPolicy(policy) {
|
|
68
|
+
this.#dialogPolicy = normalizeDialogPolicy(policy);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async ensureConnected() {
|
|
72
|
+
if (this.#connected) return;
|
|
73
|
+
// Never inherit stdout/stderr: Chromium writes startup noise to both (e.g.
|
|
74
|
+
// the PartitionAlloc shim's "Trying to load the allocator multiple times"
|
|
75
|
+
// line and GoogleUpdater child logs), and inherited fds would spray it raw
|
|
76
|
+
// onto the caller's tty (it corrupted the senpi TUI). Pipe + drain into a
|
|
77
|
+
// bounded tail kept for launch diagnostics.
|
|
78
|
+
const stdio = ["ignore", "pipe", "pipe", "pipe", "pipe"];
|
|
79
|
+
const profileDir = profileDirFromArgs(this.#browserArgs);
|
|
80
|
+
await reapOrphanedBrowser(profileDir);
|
|
81
|
+
this.#child = spawn(this.#browserPath, [...this.#browserArgs, "--remote-debugging-pipe"], {
|
|
82
|
+
detached: browserSpawnDetached,
|
|
83
|
+
...this.#spawnOptions,
|
|
84
|
+
stdio,
|
|
85
|
+
});
|
|
86
|
+
const browserPid = this.#child.pid;
|
|
87
|
+
// A helper process can keep an old launch's pipe open after that browser is
|
|
88
|
+
// gone; its late events must never touch the launch that replaced it.
|
|
89
|
+
const launch = {};
|
|
90
|
+
this.#launch = launch;
|
|
91
|
+
const owned = listener => (...args) => { if (this.#launch === launch) listener(...args); };
|
|
92
|
+
this.#launchId = `${this.logId}:${browserPid}`;
|
|
93
|
+
this.#launchedAt = performance.now();
|
|
94
|
+
this.#receivedBytes = 0;
|
|
95
|
+
this.#malformedFrameCount = 0;
|
|
96
|
+
this.#buffer = Buffer.alloc(0);
|
|
97
|
+
this.#sessionTargets.clear();
|
|
98
|
+
this.#closedSessions.clear();
|
|
99
|
+
this.#child.once("exit", () => removeBrowserPidFile(profileDir, browserPid));
|
|
100
|
+
this.#stdioTail = "";
|
|
101
|
+
this.#stderrHead = "";
|
|
102
|
+
const stderr = this.#child.stderr;
|
|
103
|
+
for (const stream of [this.#child.stdout, stderr]) {
|
|
104
|
+
if (!stream) continue;
|
|
105
|
+
stream.setEncoding("utf8");
|
|
106
|
+
stream.on("data", (chunk) => {
|
|
107
|
+
this.#stdioTail = (this.#stdioTail + chunk).slice(-STDIO_TAIL_LIMIT);
|
|
108
|
+
if (stream === stderr) this.#stderrHead = (this.#stderrHead + chunk).slice(0, STDIO_TAIL_LIMIT);
|
|
109
|
+
});
|
|
110
|
+
stream.on("error", () => {});
|
|
111
|
+
}
|
|
112
|
+
this.#writeStream = this.#child.stdio[3];
|
|
113
|
+
this.#readStream = this.#child.stdio[4];
|
|
114
|
+
this.#readStream.on("data", owned(chunk => this.#onData(chunk)));
|
|
115
|
+
for (const event of ["end", "close"]) {
|
|
116
|
+
this.#readStream.on(event, owned(() => this.#failCommands(CdpPipeClosedError, `CDP pipe read stream ${event}`)));
|
|
117
|
+
}
|
|
118
|
+
// A killed browser resets its end of the CDP pipes (ECONNRESET/EPIPE on Linux);
|
|
119
|
+
// without a listener Node rethrows that as an uncaught exception in the caller.
|
|
120
|
+
for (const stream of [this.#writeStream, this.#readStream]) {
|
|
121
|
+
stream.on("error", owned(error => this.#failAll(Error(`CDP pipe error: ${error.code ?? error.message}`))));
|
|
122
|
+
}
|
|
123
|
+
this.#child.on("exit", owned(() => {
|
|
124
|
+
this.#connected = false;
|
|
125
|
+
this.#failAll(Error("CDP pipe browser exited"));
|
|
126
|
+
this.transportEvents.emit("disconnected").catch(() => {});
|
|
127
|
+
}));
|
|
128
|
+
try {
|
|
129
|
+
await writeBrowserPidFile(profileDir, browserPid);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
await this.#quitFailedLaunch();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
this.#connected = true;
|
|
135
|
+
try {
|
|
136
|
+
await this.#awaitReady();
|
|
137
|
+
await this.#dispatch("Target.setDiscoverTargets", { discover: true }).catch(() => {});
|
|
138
|
+
await this.transportEvents.emit("connected");
|
|
139
|
+
} catch (error) {
|
|
140
|
+
await this.#quitFailedLaunch();
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Never leave a browser the caller holds no handle to: a rejected launch hands
|
|
146
|
+
// back no client, so quit it (SIGTERM, then the bounded grace) before reporting.
|
|
147
|
+
async #quitFailedLaunch() {
|
|
148
|
+
const child = this.#child;
|
|
149
|
+
this.#child = undefined;
|
|
150
|
+
this.#connected = false;
|
|
151
|
+
this.#failAll(Error("CDP pipe launch failed"));
|
|
152
|
+
await terminateChild(child);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Probes go through #dispatch, never send(): send() would relaunch a browser
|
|
156
|
+
// that exited mid-check, each relaunch with a fresh budget (#123). A browser
|
|
157
|
+
// that exits fails the launch at once, naming the exit.
|
|
158
|
+
async #awaitReady() {
|
|
159
|
+
const child = this.#child;
|
|
160
|
+
const deadline = Date.now() + this.#readinessTimeoutMs;
|
|
161
|
+
const exited = child.exitCode !== null || child.signalCode !== null
|
|
162
|
+
? Promise.resolve("exited")
|
|
163
|
+
: new Promise(resolve => child.once("exit", () => resolve("exited")));
|
|
164
|
+
let lastError;
|
|
165
|
+
while (Date.now() < deadline) {
|
|
166
|
+
try {
|
|
167
|
+
const outcome = await Promise.race([
|
|
168
|
+
this.#dispatch("Browser.getVersion", undefined, undefined, { timeoutMs: 1000 }),
|
|
169
|
+
exited,
|
|
170
|
+
]);
|
|
171
|
+
if (outcome !== "exited") return;
|
|
172
|
+
} catch (error) {
|
|
173
|
+
lastError = error;
|
|
174
|
+
}
|
|
175
|
+
if (child.exitCode !== null || child.signalCode !== null) throw await this.#exitedBeforeReady(child, deadline);
|
|
176
|
+
await Promise.race([new Promise(resolve => setTimeout(resolve, 100)), exited]);
|
|
177
|
+
}
|
|
178
|
+
const reason = lastError ? String(lastError.message ?? lastError) : "no response";
|
|
179
|
+
const tail = this.#stdioTail.trim();
|
|
180
|
+
throw Error(
|
|
181
|
+
`Browser did not become ready over the CDP pipe (${reason})` +
|
|
182
|
+
(tail ? `\nBrowser stdio tail:\n${tail}` : ""),
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async #exitedBeforeReady(child, deadline) {
|
|
187
|
+
// stderr can still hold unread output when "exit" fires; drain it. Bounded:
|
|
188
|
+
// a surviving grandchild may hold the write end open indefinitely.
|
|
189
|
+
if (child.stderr) {
|
|
190
|
+
let timer;
|
|
191
|
+
await Promise.race([
|
|
192
|
+
finished(child.stderr).catch(() => {}),
|
|
193
|
+
new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, Math.min(EXIT_STDERR_DRAIN_MS, deadline - Date.now()))); }),
|
|
194
|
+
]);
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
}
|
|
197
|
+
const how = child.signalCode ? `signal ${child.signalCode}` : `exit code ${child.exitCode}`;
|
|
198
|
+
const firstLine = this.#stderrHead.split("\n").map(line => line.trim()).find(Boolean);
|
|
199
|
+
const tail = this.#stdioTail.trim();
|
|
200
|
+
return Error(
|
|
201
|
+
`Browser exited before it became ready over the CDP pipe (${how})` +
|
|
202
|
+
(firstLine ? `: ${firstLine}` : "") +
|
|
203
|
+
(tail && tail !== firstLine ? `\nBrowser stdio tail:\n${tail}` : ""),
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async send(method, params, sessionId, opts = {}) {
|
|
208
|
+
if (method === "Target.createTarget" && opts.capability !== targetCreationCapability) throw Error("Target.createTarget is reserved for createAgentTabs");
|
|
209
|
+
if (String(method).startsWith("OmO.")) {
|
|
210
|
+
throw Error(`Extension commands are unavailable over pipe transport: ${method}`);
|
|
211
|
+
}
|
|
212
|
+
await this.ensureConnected();
|
|
213
|
+
return this.#dispatch(method, params, sessionId, opts);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async #dispatch(method, params, sessionId, opts = {}) {
|
|
217
|
+
const id = this.#seq++;
|
|
218
|
+
const msg = { id, method };
|
|
219
|
+
if (params !== undefined) msg.params = params;
|
|
220
|
+
if (sessionId) msg.sessionId = sessionId;
|
|
221
|
+
const entry = {
|
|
222
|
+
method, sessionId, targetId: params?.targetId ?? this.#sessionTargets.get(sessionId),
|
|
223
|
+
sentAt: performance.now(), receivedBytes: this.#receivedBytes,
|
|
224
|
+
};
|
|
225
|
+
if (this.#closedSessions.has(sessionId) && method !== "Page.close") {
|
|
226
|
+
throw this.#commandError(CdpSessionDetachedError, "Page closed", entry);
|
|
227
|
+
}
|
|
228
|
+
if (this.#readStream.readableEnded || this.#readStream.destroyed) {
|
|
229
|
+
throw this.#commandError(CdpPipeClosedError, "CDP pipe read stream closed", entry);
|
|
230
|
+
}
|
|
231
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
232
|
+
const timeoutMs = opts.timeoutMs ?? this.#commandTimeoutMs;
|
|
233
|
+
const timeout = timeoutMs > 0
|
|
234
|
+
? setTimeout(() => {
|
|
235
|
+
this.#pending.delete(id);
|
|
236
|
+
reject(this.#commandError(CdpCommandTimeoutError, "CDP command timeout", entry));
|
|
237
|
+
}, timeoutMs)
|
|
238
|
+
: undefined;
|
|
239
|
+
this.#pending.set(id, { ...entry, resolve, reject, timeout });
|
|
240
|
+
this.#writeStream.write(JSON.stringify(msg) + "\0");
|
|
241
|
+
return promise;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
on(method, fn) {
|
|
245
|
+
return this.#events.on(method, ({ data }) => fn(data.payload, data.meta));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async discoverTargets() {
|
|
249
|
+
const { targetInfos } = await this.send("Target.getTargets");
|
|
250
|
+
return targetInfos.map(t => ({
|
|
251
|
+
id: t.targetId,
|
|
252
|
+
type: t.type,
|
|
253
|
+
url: t.url ?? "",
|
|
254
|
+
title: t.title ?? "",
|
|
255
|
+
description: t.description,
|
|
256
|
+
faviconUrl: t.faviconUrl,
|
|
257
|
+
parentId: t.openerId,
|
|
258
|
+
}));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
closeSession(sessionId) {
|
|
263
|
+
this.#closedSessions.add(sessionId);
|
|
264
|
+
this.#failCommands(CdpSessionDetachedError, "Page closed", sessionId);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async close() {
|
|
268
|
+
const child = this.#child;
|
|
269
|
+
this.#child = undefined;
|
|
270
|
+
if (child && child.exitCode === null) {
|
|
271
|
+
const exited = new Promise(resolve => child.once("exit", resolve));
|
|
272
|
+
let quitRequested = false;
|
|
273
|
+
if (this.#connected) {
|
|
274
|
+
await Promise.race([
|
|
275
|
+
this.send("Browser.close", undefined, undefined, {
|
|
276
|
+
timeoutMs: GRACEFUL_CLOSE_TIMEOUT_MS,
|
|
277
|
+
}).then(() => { quitRequested = true; }, () => {}),
|
|
278
|
+
exited,
|
|
279
|
+
]);
|
|
280
|
+
}
|
|
281
|
+
this.#connected = false;
|
|
282
|
+
this.#failAll(Error("CDP pipe client closed"));
|
|
283
|
+
if (child.exitCode === null) {
|
|
284
|
+
await Promise.race([
|
|
285
|
+
exited,
|
|
286
|
+
new Promise(resolve => setTimeout(resolve, GRACEFUL_CLOSE_TIMEOUT_MS)),
|
|
287
|
+
]);
|
|
288
|
+
}
|
|
289
|
+
await terminateChild(child, { quitRequested });
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
this.#connected = false;
|
|
293
|
+
this.#failAll(Error("CDP pipe client closed"));
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
#onData(chunk) {
|
|
297
|
+
this.#receivedBytes += chunk.length;
|
|
298
|
+
this.#buffer = Buffer.concat([this.#buffer, chunk]);
|
|
299
|
+
let idx;
|
|
300
|
+
while ((idx = this.#buffer.indexOf(0)) !== -1) {
|
|
301
|
+
const raw = this.#buffer.subarray(0, idx).toString("utf8");
|
|
302
|
+
this.#buffer = this.#buffer.subarray(idx + 1);
|
|
303
|
+
if (raw.length === 0) continue;
|
|
304
|
+
let msg;
|
|
305
|
+
try { msg = JSON.parse(raw); } catch { this.#malformedFrameCount++; continue; }
|
|
306
|
+
this._handleTransportMessage(msg);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
_handleTransportMessage(msg) {
|
|
311
|
+
if (typeof msg.id === "number") {
|
|
312
|
+
const entry = this.#pending.get(msg.id);
|
|
313
|
+
if (!entry) return;
|
|
314
|
+
this.#pending.delete(msg.id);
|
|
315
|
+
if (entry.timeout) clearTimeout(entry.timeout);
|
|
316
|
+
if (msg.error) {
|
|
317
|
+
const err = Error(msg.error.message ?? `CDP command failed: ${entry.method}`);
|
|
318
|
+
err.code = msg.error.code;
|
|
319
|
+
err.data = msg.error.data;
|
|
320
|
+
entry.reject(err);
|
|
321
|
+
} else {
|
|
322
|
+
if (entry.method === "Target.attachToTarget" && msg.result?.sessionId) {
|
|
323
|
+
this.#sessionTargets.set(msg.result.sessionId, entry.targetId);
|
|
324
|
+
}
|
|
325
|
+
entry.resolve(msg.result);
|
|
326
|
+
}
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (typeof msg.method === "string") {
|
|
330
|
+
if (msg.method === "Target.attachedToTarget") {
|
|
331
|
+
this.#sessionTargets.set(msg.params.sessionId, msg.params.targetInfo.targetId);
|
|
332
|
+
} else if (msg.method === "Target.detachedFromTarget" && msg.params?.sessionId) {
|
|
333
|
+
this.#failCommands(CdpSessionDetachedError, "CDP session detached", msg.params.sessionId);
|
|
334
|
+
this.#sessionTargets.delete(msg.params.sessionId);
|
|
335
|
+
} else if (msg.method === "Inspector.targetCrashed" && msg.sessionId) {
|
|
336
|
+
this.#failCommands(CdpSessionCrashedError, "CDP session crashed", msg.sessionId);
|
|
337
|
+
this.#sessionTargets.delete(msg.sessionId);
|
|
338
|
+
}
|
|
339
|
+
const meta = { sessionId: msg.sessionId };
|
|
340
|
+
if (msg.method === "Page.javascriptDialogOpening" && msg.sessionId) {
|
|
341
|
+
meta.dialog = new Dialog(msg.params, action => this.send("Page.handleJavaScriptDialog", action, msg.sessionId));
|
|
342
|
+
}
|
|
343
|
+
const emitted = this.#events.emit(msg.method, { data: { payload: msg.params, meta } }).catch(() => {});
|
|
344
|
+
return meta.dialog
|
|
345
|
+
? emitted.then(() => answerWithPolicy(meta.dialog, this.#dialogPolicy, msg.params)).catch(() => {})
|
|
346
|
+
: undefined;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
#commandError(ErrorType, reason, entry) {
|
|
351
|
+
const now = performance.now();
|
|
352
|
+
const receivedBytesSinceSend = this.#receivedBytes - entry.receivedBytes;
|
|
353
|
+
const details = {
|
|
354
|
+
method: entry.method, launchId: this.#launchId,
|
|
355
|
+
sessionId: entry.sessionId ?? null,
|
|
356
|
+
targetId: entry.targetId ?? this.#sessionTargets.get(entry.sessionId) ?? null,
|
|
357
|
+
elapsedSinceLaunchMs: Math.round(now - this.#launchedAt),
|
|
358
|
+
commandElapsedMs: Math.round(now - entry.sentAt),
|
|
359
|
+
receivedReplyBytes: receivedBytesSinceSend > 0, receivedBytesSinceSend,
|
|
360
|
+
malformedFrameCount: this.#malformedFrameCount,
|
|
361
|
+
};
|
|
362
|
+
const context = Object.entries(details).map(([key, value]) => `${key}=${value}`).join(", ");
|
|
363
|
+
return new ErrorType(`${reason}: ${entry.method} (${context})`, details);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
#failCommands(ErrorType, reason, sessionId) {
|
|
367
|
+
for (const [id, entry] of this.#pending) {
|
|
368
|
+
if (sessionId !== undefined && entry.sessionId !== sessionId) continue;
|
|
369
|
+
if (entry.timeout) clearTimeout(entry.timeout);
|
|
370
|
+
this.#pending.delete(id);
|
|
371
|
+
entry.reject(this.#commandError(ErrorType, reason, entry));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
#failAll(err) {
|
|
376
|
+
for (const entry of this.#pending.values()) {
|
|
377
|
+
if (entry.timeout) clearTimeout(entry.timeout);
|
|
378
|
+
entry.reject(err);
|
|
379
|
+
}
|
|
380
|
+
this.#pending.clear();
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
export async function connectPipe({ browserPath, browserArgs = [], spawnOptions, storageRoot, commandTimeoutMs, readinessTimeoutMs, logId, dialogPolicy } = {}) {
|
|
385
|
+
const client = new PipeCdpClient({ browserPath, browserArgs, spawnOptions, commandTimeoutMs, readinessTimeoutMs, logId, dialogPolicy });
|
|
386
|
+
await client.ensureConnected();
|
|
387
|
+
const connection = new BrowserConnection(client, { storageRoot });
|
|
388
|
+
await connection.initialize();
|
|
389
|
+
connection.browserProcess = client.childProcess;
|
|
390
|
+
return connection;
|
|
391
|
+
}
|