@howaboua/pi-browser 0.0.3 → 0.0.5
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/CHANGELOG.md +18 -0
- package/README.md +4 -0
- package/dist/index.js +2 -2
- package/dist/remote-worker.js +1026 -176
- package/dist/src/browser/bounds.d.ts +1 -1
- package/dist/src/browser/bounds.js +13 -4
- package/dist/src/browser/help.js +11 -6
- package/dist/src/browser/operation-executor.js +15 -1
- package/dist/src/browser/operation.d.ts +25 -2
- package/dist/src/browser/operation.js +5 -0
- package/dist/src/browser/parse-operation.js +61 -2
- package/dist/src/browser/remote.d.ts +1 -1
- package/dist/src/browser/remote.js +2 -2
- package/dist/src/browser/runtime.d.ts +8 -3
- package/dist/src/browser/runtime.js +91 -25
- package/dist/src/browser/worker-server.js +12 -6
- package/dist/src/browser-parameters.d.ts +10 -0
- package/dist/src/browser-parameters.js +34 -5
- package/dist/src/browser-tool.d.ts +10 -0
- package/dist/src/browser-tool.js +2 -1
- package/dist/src/cdp/actions/click.d.ts +2 -0
- package/dist/src/cdp/actions/click.js +1 -1
- package/dist/src/cdp/actions/element.js +4 -0
- package/dist/src/cdp/actions/fill.d.ts +8 -0
- package/dist/src/cdp/actions/fill.js +175 -0
- package/dist/src/cdp/actions/key.d.ts +20 -0
- package/dist/src/cdp/actions/key.js +166 -0
- package/dist/src/cdp/actions/wait.d.ts +9 -0
- package/dist/src/cdp/actions/wait.js +95 -0
- package/dist/src/cdp/pages.d.ts +2 -1
- package/dist/src/cdp/pages.js +8 -4
- package/dist/src/cdp/session.d.ts +7 -1
- package/dist/src/cdp/session.js +79 -27
- package/dist/src/cdp/snapshot-contract.d.ts +6 -0
- package/dist/src/cdp/snapshot.js +72 -11
- package/dist/src/cdp/tabs.d.ts +32 -0
- package/dist/src/cdp/tabs.js +226 -0
- package/dist/src/cdp/types.d.ts +2 -0
- package/index.ts +2 -2
- package/package.json +5 -5
- package/src/browser/bounds.ts +14 -3
- package/src/browser/help.ts +12 -6
- package/src/browser/operation-executor.ts +34 -0
- package/src/browser/operation.ts +19 -1
- package/src/browser/parse-operation.ts +63 -2
- package/src/browser/remote.ts +2 -1
- package/src/browser/runtime.ts +115 -26
- package/src/browser/worker-server.ts +24 -7
- package/src/browser-parameters.ts +131 -96
- package/src/browser-tool.ts +2 -1
- package/src/cdp/actions/click.ts +1 -1
- package/src/cdp/actions/element.ts +4 -0
- package/src/cdp/actions/fill.ts +246 -0
- package/src/cdp/actions/key.ts +202 -0
- package/src/cdp/actions/wait.ts +117 -0
- package/src/cdp/pages.ts +9 -6
- package/src/cdp/session.ts +98 -46
- package/src/cdp/snapshot-contract.ts +6 -0
- package/src/cdp/snapshot.ts +92 -17
- package/src/cdp/tabs.ts +292 -0
- package/src/cdp/types.ts +2 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import type { CdpConnection } from "../types.js";
|
|
2
|
+
|
|
3
|
+
const MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 } as const;
|
|
4
|
+
type Modifier = keyof typeof MODIFIERS;
|
|
5
|
+
const ALIASES: Record<string, Modifier> = {
|
|
6
|
+
Ctrl: "Control",
|
|
7
|
+
Cmd: "Meta",
|
|
8
|
+
Option: "Alt",
|
|
9
|
+
};
|
|
10
|
+
const NAMED_KEYS: Record<string, number> = {
|
|
11
|
+
Backspace: 8,
|
|
12
|
+
Tab: 9,
|
|
13
|
+
Enter: 13,
|
|
14
|
+
Escape: 27,
|
|
15
|
+
Space: 32,
|
|
16
|
+
PageUp: 33,
|
|
17
|
+
PageDown: 34,
|
|
18
|
+
End: 35,
|
|
19
|
+
Home: 36,
|
|
20
|
+
ArrowLeft: 37,
|
|
21
|
+
ArrowUp: 38,
|
|
22
|
+
ArrowRight: 39,
|
|
23
|
+
ArrowDown: 40,
|
|
24
|
+
Insert: 45,
|
|
25
|
+
Delete: 46,
|
|
26
|
+
};
|
|
27
|
+
const PUNCTUATION: Record<string, { code: string; keyCode: number }> = {
|
|
28
|
+
"`~": { code: "Backquote", keyCode: 192 },
|
|
29
|
+
"-_": { code: "Minus", keyCode: 189 },
|
|
30
|
+
"=+": { code: "Equal", keyCode: 187 },
|
|
31
|
+
"[{": { code: "BracketLeft", keyCode: 219 },
|
|
32
|
+
"]}": { code: "BracketRight", keyCode: 221 },
|
|
33
|
+
"\\|": { code: "Backslash", keyCode: 220 },
|
|
34
|
+
";:": { code: "Semicolon", keyCode: 186 },
|
|
35
|
+
"'\"": { code: "Quote", keyCode: 222 },
|
|
36
|
+
",<": { code: "Comma", keyCode: 188 },
|
|
37
|
+
".>": { code: "Period", keyCode: 190 },
|
|
38
|
+
"/?": { code: "Slash", keyCode: 191 },
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
interface Key {
|
|
42
|
+
key: string;
|
|
43
|
+
code: string;
|
|
44
|
+
windowsVirtualKeyCode: number;
|
|
45
|
+
text?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function keyDefinition(name: string, shift: boolean): Key {
|
|
49
|
+
const namedCode = Object.hasOwn(NAMED_KEYS, name)
|
|
50
|
+
? NAMED_KEYS[name]
|
|
51
|
+
: undefined;
|
|
52
|
+
if (namedCode !== undefined) {
|
|
53
|
+
return {
|
|
54
|
+
key: name === "Space" ? " " : name,
|
|
55
|
+
code: name,
|
|
56
|
+
windowsVirtualKeyCode: namedCode,
|
|
57
|
+
...(name === "Enter"
|
|
58
|
+
? { text: "\r" }
|
|
59
|
+
: name === "Space"
|
|
60
|
+
? { text: " " }
|
|
61
|
+
: {}),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (/^F(?:[1-9]|1[0-2])$/.test(name)) {
|
|
65
|
+
return {
|
|
66
|
+
key: name,
|
|
67
|
+
code: name,
|
|
68
|
+
windowsVirtualKeyCode: 111 + Number(name.slice(1)),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const key = name === "Plus" ? "+" : name;
|
|
72
|
+
if ([...key].length !== 1) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`Unknown key ${name}; use a character, Enter, Tab, Escape, arrows, or a chord such as Control+a`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
if (/^[a-z]$/i.test(key)) {
|
|
78
|
+
const text = shift ? key.toUpperCase() : key;
|
|
79
|
+
return {
|
|
80
|
+
key: text,
|
|
81
|
+
code: `Key${key.toUpperCase()}`,
|
|
82
|
+
windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
|
|
83
|
+
text,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
const digit = "0123456789".indexOf(key);
|
|
87
|
+
const shiftedDigit = ")!@#$%^&*(".indexOf(key);
|
|
88
|
+
if (digit >= 0 || shiftedDigit >= 0) {
|
|
89
|
+
const number = digit >= 0 ? digit : shiftedDigit;
|
|
90
|
+
const text = shift && digit >= 0 ? ")!@#$%^&*(".charAt(number) : key;
|
|
91
|
+
return {
|
|
92
|
+
key: text,
|
|
93
|
+
code: `Digit${number}`,
|
|
94
|
+
windowsVirtualKeyCode: 48 + number,
|
|
95
|
+
text,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
for (const [characters, definition] of Object.entries(PUNCTUATION)) {
|
|
99
|
+
if (!characters.includes(key)) continue;
|
|
100
|
+
const text = shift ? characters.charAt(1) : key;
|
|
101
|
+
return {
|
|
102
|
+
key: text,
|
|
103
|
+
code: definition.code,
|
|
104
|
+
windowsVirtualKeyCode: definition.keyCode,
|
|
105
|
+
text,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { key, code: "", windowsVirtualKeyCode: 0, text: key };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function parseKeyChord(chord: string): {
|
|
112
|
+
modifiers: Modifier[];
|
|
113
|
+
key: Key;
|
|
114
|
+
} {
|
|
115
|
+
const parts =
|
|
116
|
+
chord === "+" ? ["Plus"] : chord.split("+").map((part) => part.trim());
|
|
117
|
+
const name = parts.pop();
|
|
118
|
+
if (!name) throw new Error("Missing key; use Plus for + in a chord");
|
|
119
|
+
const modifiers: Modifier[] = [];
|
|
120
|
+
for (const part of parts) {
|
|
121
|
+
const modifier = ALIASES[part] ?? part;
|
|
122
|
+
if (!Object.hasOwn(MODIFIERS, modifier))
|
|
123
|
+
throw new Error(
|
|
124
|
+
`Unknown modifier ${part}; use Control, Alt, Shift, or Meta`,
|
|
125
|
+
);
|
|
126
|
+
const valid = modifier as Modifier;
|
|
127
|
+
if (modifiers.includes(valid)) throw new Error(`Repeated modifier ${part}`);
|
|
128
|
+
modifiers.push(valid);
|
|
129
|
+
}
|
|
130
|
+
return { modifiers, key: keyDefinition(name, modifiers.includes("Shift")) };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function pressKey(
|
|
134
|
+
cdp: CdpConnection,
|
|
135
|
+
sessionId: string,
|
|
136
|
+
chord: string,
|
|
137
|
+
signal?: AbortSignal,
|
|
138
|
+
): Promise<string> {
|
|
139
|
+
const { modifiers, key } = parseKeyChord(chord);
|
|
140
|
+
const held: Array<{ key: Key; bit: number }> = [];
|
|
141
|
+
let mask = 0;
|
|
142
|
+
let failure: unknown;
|
|
143
|
+
try {
|
|
144
|
+
for (const modifier of modifiers) {
|
|
145
|
+
signal?.throwIfAborted();
|
|
146
|
+
const bit = MODIFIERS[modifier];
|
|
147
|
+
const keyCode = { Alt: 18, Control: 17, Meta: 91, Shift: 16 }[modifier];
|
|
148
|
+
const modifierKey = {
|
|
149
|
+
key: modifier,
|
|
150
|
+
code: `${modifier}Left`,
|
|
151
|
+
windowsVirtualKeyCode: keyCode,
|
|
152
|
+
};
|
|
153
|
+
mask |= bit;
|
|
154
|
+
held.push({ key: modifierKey, bit });
|
|
155
|
+
await cdp.send(
|
|
156
|
+
"Input.dispatchKeyEvent",
|
|
157
|
+
{ ...modifierKey, type: "rawKeyDown", modifiers: mask },
|
|
158
|
+
sessionId,
|
|
159
|
+
signal,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
signal?.throwIfAborted();
|
|
163
|
+
held.push({ key, bit: 0 });
|
|
164
|
+
const { text, ...identity } = key;
|
|
165
|
+
const insertsText = text !== undefined && (mask & ~MODIFIERS.Shift) === 0;
|
|
166
|
+
await cdp.send(
|
|
167
|
+
"Input.dispatchKeyEvent",
|
|
168
|
+
{
|
|
169
|
+
...identity,
|
|
170
|
+
type: insertsText ? "keyDown" : "rawKeyDown",
|
|
171
|
+
modifiers: mask,
|
|
172
|
+
...(insertsText ? { text } : {}),
|
|
173
|
+
},
|
|
174
|
+
sessionId,
|
|
175
|
+
signal,
|
|
176
|
+
);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
failure = error;
|
|
179
|
+
} finally {
|
|
180
|
+
for (const heldKey of held.reverse()) {
|
|
181
|
+
mask &= ~heldKey.bit;
|
|
182
|
+
const { text: _text, ...identity } = heldKey.key;
|
|
183
|
+
try {
|
|
184
|
+
await cdp.send(
|
|
185
|
+
"Input.dispatchKeyEvent",
|
|
186
|
+
{ ...identity, type: "keyUp", modifiers: mask },
|
|
187
|
+
sessionId,
|
|
188
|
+
);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
failure = failure
|
|
191
|
+
? new AggregateError(
|
|
192
|
+
[failure, error],
|
|
193
|
+
"Key press failed; key release also failed",
|
|
194
|
+
)
|
|
195
|
+
: error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (failure) throw failure;
|
|
200
|
+
signal?.throwIfAborted();
|
|
201
|
+
return `Pressed ${chord}`;
|
|
202
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { sleep } from "../discovery.js";
|
|
2
|
+
import { evaluate } from "../evaluate.js";
|
|
3
|
+
import type { CdpConnection } from "../types.js";
|
|
4
|
+
import { errorMessage } from "../types.js";
|
|
5
|
+
|
|
6
|
+
export type WaitCondition =
|
|
7
|
+
| { selector: string }
|
|
8
|
+
| { text: string }
|
|
9
|
+
| { url_includes: string };
|
|
10
|
+
|
|
11
|
+
const POLL_INTERVAL_MS = 100;
|
|
12
|
+
const SUMMARY_LENGTH = 120;
|
|
13
|
+
const NAVIGATION_CONTEXT_ERRORS = [
|
|
14
|
+
/(?:^|: )Execution context was destroyed\b/i,
|
|
15
|
+
/(?:^|: )Cannot find context with specified id\b/i,
|
|
16
|
+
/(?:^|: )Cannot find (?:default )?execution context\b/i,
|
|
17
|
+
/(?:^|: )No execution context with given id\b/i,
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
function conditionDetails(condition: WaitCondition): {
|
|
21
|
+
expression: string;
|
|
22
|
+
label: string;
|
|
23
|
+
matched: string;
|
|
24
|
+
} {
|
|
25
|
+
if ("selector" in condition) {
|
|
26
|
+
return {
|
|
27
|
+
expression: `document.querySelector(${JSON.stringify(condition.selector)}) !== null`,
|
|
28
|
+
label: `selector ${summary(condition.selector)}`,
|
|
29
|
+
matched: `Matched selector ${summary(condition.selector)}`,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
if ("text" in condition) {
|
|
33
|
+
return {
|
|
34
|
+
expression: `document.body?.innerText.includes(${JSON.stringify(condition.text)}) ?? false`,
|
|
35
|
+
label: `text ${summary(condition.text)}`,
|
|
36
|
+
matched: `Matched text ${summary(condition.text)}`,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
expression: `location.href.includes(${JSON.stringify(condition.url_includes)})`,
|
|
41
|
+
label: `URL containing ${summary(condition.url_includes)}`,
|
|
42
|
+
matched: `Matched URL containing ${summary(condition.url_includes)}`,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function summary(value: string): string {
|
|
47
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
48
|
+
const bounded =
|
|
49
|
+
normalized.length > SUMMARY_LENGTH
|
|
50
|
+
? `${normalized.slice(0, SUMMARY_LENGTH - 3)}...`
|
|
51
|
+
: normalized;
|
|
52
|
+
return JSON.stringify(bounded);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isNavigationContextError(error: unknown): boolean {
|
|
56
|
+
const message = errorMessage(error);
|
|
57
|
+
return NAVIGATION_CONTEXT_ERRORS.some((pattern) => pattern.test(message));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function waitForCondition(
|
|
61
|
+
cdp: CdpConnection,
|
|
62
|
+
sessionId: string,
|
|
63
|
+
condition: WaitCondition,
|
|
64
|
+
timeoutMs: number,
|
|
65
|
+
signal?: AbortSignal,
|
|
66
|
+
): Promise<string> {
|
|
67
|
+
const details = conditionDetails(condition);
|
|
68
|
+
const timeoutError = new Error(
|
|
69
|
+
`Timed out after ${timeoutMs}ms waiting for ${details.label}`,
|
|
70
|
+
);
|
|
71
|
+
const deadline = Date.now() + timeoutMs;
|
|
72
|
+
const controller = new AbortController();
|
|
73
|
+
let timedOut = false;
|
|
74
|
+
const abort = () => {
|
|
75
|
+
controller.abort(signal?.reason ?? new Error("Wait aborted"));
|
|
76
|
+
};
|
|
77
|
+
if (signal?.aborted) {
|
|
78
|
+
abort();
|
|
79
|
+
} else {
|
|
80
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
81
|
+
}
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
timedOut = true;
|
|
84
|
+
controller.abort(timeoutError);
|
|
85
|
+
}, timeoutMs);
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
while (Date.now() < deadline) {
|
|
89
|
+
try {
|
|
90
|
+
const matched = await evaluate(
|
|
91
|
+
cdp,
|
|
92
|
+
sessionId,
|
|
93
|
+
details.expression,
|
|
94
|
+
controller.signal,
|
|
95
|
+
);
|
|
96
|
+
if (matched === true) return details.matched;
|
|
97
|
+
if (matched !== false) {
|
|
98
|
+
throw new Error("Wait condition returned a non-boolean result");
|
|
99
|
+
}
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
102
|
+
if (!isNavigationContextError(error)) throw error;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const remaining = deadline - Date.now();
|
|
106
|
+
if (remaining <= 0) break;
|
|
107
|
+
await sleep(Math.min(POLL_INTERVAL_MS, remaining), controller.signal);
|
|
108
|
+
}
|
|
109
|
+
throw timeoutError;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (timedOut) throw timeoutError;
|
|
112
|
+
throw error;
|
|
113
|
+
} finally {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
signal?.removeEventListener("abort", abort);
|
|
116
|
+
}
|
|
117
|
+
}
|
package/src/cdp/pages.ts
CHANGED
|
@@ -9,10 +9,13 @@ function pageInfo(value: unknown): PageInfo {
|
|
|
9
9
|
title: typeof record["title"] === "string" ? record["title"] : "",
|
|
10
10
|
url: asString(record["url"], "target URL"),
|
|
11
11
|
...(typeof record["type"] === "string" ? { type: record["type"] } : {}),
|
|
12
|
+
...(typeof record["openerId"] === "string"
|
|
13
|
+
? { openerId: record["openerId"] }
|
|
14
|
+
: {}),
|
|
12
15
|
};
|
|
13
16
|
}
|
|
14
17
|
|
|
15
|
-
export async function
|
|
18
|
+
export async function getPageTargets(
|
|
16
19
|
cdp: CdpConnection,
|
|
17
20
|
signal?: AbortSignal,
|
|
18
21
|
): Promise<PageInfo[]> {
|
|
@@ -24,11 +27,11 @@ export async function getPages(
|
|
|
24
27
|
if (!Array.isArray(targetInfos)) {
|
|
25
28
|
throw new Error("Target.getTargets response has no targetInfos");
|
|
26
29
|
}
|
|
27
|
-
return targetInfos
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
return targetInfos.map(pageInfo).filter((target) => target.type === "page");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function getDisplayedPages(targets: PageInfo[]): PageInfo[] {
|
|
34
|
+
return targets.filter((target) => !target.url.startsWith("chrome://"));
|
|
32
35
|
}
|
|
33
36
|
|
|
34
37
|
export async function waitForOpenedTarget(
|
package/src/cdp/session.ts
CHANGED
|
@@ -4,11 +4,10 @@ import {
|
|
|
4
4
|
getWebSocketUrl,
|
|
5
5
|
resolvePrefix,
|
|
6
6
|
} from "./discovery.js";
|
|
7
|
-
import { getPages, waitForOpenedTarget } from "./pages.js";
|
|
8
7
|
import { waitForTurn } from "./serial.js";
|
|
8
|
+
import { BrowserTabs } from "./tabs.js";
|
|
9
9
|
import type { ElementRefs, PageInfo } from "./types.js";
|
|
10
10
|
import { asRecord } from "./types.js";
|
|
11
|
-
import { assertHttpUrl } from "./url.js";
|
|
12
11
|
|
|
13
12
|
const TAB_IDLE_MS = 20 * 60 * 1_000;
|
|
14
13
|
|
|
@@ -25,6 +24,11 @@ interface PendingConnection<T> {
|
|
|
25
24
|
value?: T;
|
|
26
25
|
}
|
|
27
26
|
|
|
27
|
+
interface BrowserConnection {
|
|
28
|
+
cdp: CdpClient;
|
|
29
|
+
tabs: BrowserTabs;
|
|
30
|
+
}
|
|
31
|
+
|
|
28
32
|
class TabBridge {
|
|
29
33
|
readonly elementRefs: ElementRefs = new Map();
|
|
30
34
|
readonly targetId: string;
|
|
@@ -33,6 +37,7 @@ class TabBridge {
|
|
|
33
37
|
private tail = Promise.resolve();
|
|
34
38
|
private idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
35
39
|
private closed = false;
|
|
40
|
+
private backgroundRendering: boolean | undefined = false;
|
|
36
41
|
private readonly onClose: () => void;
|
|
37
42
|
|
|
38
43
|
private constructor(
|
|
@@ -114,6 +119,23 @@ class TabBridge {
|
|
|
114
119
|
}
|
|
115
120
|
}
|
|
116
121
|
|
|
122
|
+
async setBackgroundRendering(
|
|
123
|
+
enabled: boolean,
|
|
124
|
+
signal?: AbortSignal,
|
|
125
|
+
): Promise<void> {
|
|
126
|
+
if (this.backgroundRendering === enabled) return;
|
|
127
|
+
// An interrupted command may already have applied. Keep the state unknown
|
|
128
|
+
// until Chrome acknowledges it, so the next action reestablishes it.
|
|
129
|
+
this.backgroundRendering = undefined;
|
|
130
|
+
await this.cdp.send(
|
|
131
|
+
"Emulation.setFocusEmulationEnabled",
|
|
132
|
+
{ enabled },
|
|
133
|
+
this.sessionId,
|
|
134
|
+
signal,
|
|
135
|
+
);
|
|
136
|
+
this.backgroundRendering = enabled;
|
|
137
|
+
}
|
|
138
|
+
|
|
117
139
|
close(detach = true): void {
|
|
118
140
|
if (this.closed) return;
|
|
119
141
|
this.closed = true;
|
|
@@ -143,16 +165,24 @@ class TabBridge {
|
|
|
143
165
|
}
|
|
144
166
|
|
|
145
167
|
export class BrowserCdpSession {
|
|
146
|
-
private
|
|
147
|
-
private
|
|
168
|
+
private closing: Promise<void> | undefined;
|
|
169
|
+
private root: BrowserConnection | undefined;
|
|
170
|
+
private rootPending: PendingConnection<BrowserConnection> | undefined;
|
|
171
|
+
private readonly ownerId: string;
|
|
172
|
+
private readonly ownershipDirectory: string;
|
|
148
173
|
private readonly tabs = new Map<string, TabBridge>();
|
|
149
174
|
private readonly tabPromises = new Map<
|
|
150
175
|
string,
|
|
151
176
|
PendingConnection<TabBridge>
|
|
152
177
|
>();
|
|
153
178
|
|
|
179
|
+
constructor(ownerId: string, ownershipDirectory: string) {
|
|
180
|
+
this.ownerId = ownerId;
|
|
181
|
+
this.ownershipDirectory = ownershipDirectory;
|
|
182
|
+
}
|
|
183
|
+
|
|
154
184
|
async pages(signal?: AbortSignal): Promise<PageInfo[]> {
|
|
155
|
-
return
|
|
185
|
+
return (await this.rootConnection(signal)).tabs.list(signal);
|
|
156
186
|
}
|
|
157
187
|
|
|
158
188
|
async open(
|
|
@@ -161,32 +191,25 @@ export class BrowserCdpSession {
|
|
|
161
191
|
): Promise<{
|
|
162
192
|
refId: string;
|
|
163
193
|
}> {
|
|
164
|
-
|
|
194
|
+
return (await this.rootConnection(signal)).tabs.open(url, signal);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async show(refId: string, signal?: AbortSignal): Promise<string> {
|
|
198
|
+
return (await this.rootConnection(signal)).tabs.show(refId, signal);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async closeTab(refId: string, signal?: AbortSignal): Promise<string> {
|
|
165
202
|
const root = await this.rootConnection(signal);
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
);
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
url,
|
|
177
|
-
5_000,
|
|
178
|
-
signal,
|
|
179
|
-
);
|
|
180
|
-
const pages = await getPages(root, signal);
|
|
181
|
-
if (!pages.some((candidate) => candidate.targetId === page.targetId)) {
|
|
182
|
-
pages.push(page);
|
|
183
|
-
}
|
|
184
|
-
const prefixLength = getDisplayPrefixLength(
|
|
185
|
-
pages.map((candidate) => candidate.targetId),
|
|
186
|
-
);
|
|
187
|
-
return {
|
|
188
|
-
refId: page.targetId.slice(0, prefixLength),
|
|
189
|
-
};
|
|
203
|
+
const resolved = await root.tabs.resolve(refId, signal);
|
|
204
|
+
const targetId = resolved.page.targetId;
|
|
205
|
+
this.stopPendingTab(targetId, "Tab is closing");
|
|
206
|
+
const bridge = this.tabs.get(targetId);
|
|
207
|
+
const close = () => root.tabs.close(targetId, signal);
|
|
208
|
+
const closed = bridge
|
|
209
|
+
? await bridge.run(resolved.refId, signal, close)
|
|
210
|
+
: await close();
|
|
211
|
+
bridge?.close(false);
|
|
212
|
+
return closed.refId;
|
|
190
213
|
}
|
|
191
214
|
|
|
192
215
|
async withTab<T>(
|
|
@@ -237,7 +260,14 @@ export class BrowserCdpSession {
|
|
|
237
260
|
const prefixLength = getDisplayPrefixLength(
|
|
238
261
|
pages.map((page) => page.targetId),
|
|
239
262
|
);
|
|
240
|
-
|
|
263
|
+
const owned = pages.some(
|
|
264
|
+
(page) => page.targetId === targetId && page.owned === true,
|
|
265
|
+
);
|
|
266
|
+
const current = bridge;
|
|
267
|
+
return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
|
|
268
|
+
await current.setBackgroundRendering(owned, signal);
|
|
269
|
+
return action(tab);
|
|
270
|
+
});
|
|
241
271
|
}
|
|
242
272
|
|
|
243
273
|
async stop(refId?: string): Promise<void> {
|
|
@@ -260,7 +290,8 @@ export class BrowserCdpSession {
|
|
|
260
290
|
this.tabs.delete(targetId);
|
|
261
291
|
}
|
|
262
292
|
|
|
263
|
-
close(): void {
|
|
293
|
+
close(): Promise<void> {
|
|
294
|
+
if (this.closing) return this.closing;
|
|
264
295
|
for (const targetId of this.tabPromises.keys()) {
|
|
265
296
|
this.stopPendingTab(targetId, "Browser session closed");
|
|
266
297
|
}
|
|
@@ -268,18 +299,27 @@ export class BrowserCdpSession {
|
|
|
268
299
|
this.tabs.clear();
|
|
269
300
|
const rootPending = this.rootPending;
|
|
270
301
|
this.rootPending = undefined;
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
void rootPending.promise.then(
|
|
274
|
-
(client) => client.close(),
|
|
275
|
-
() => undefined,
|
|
276
|
-
);
|
|
277
|
-
}
|
|
278
|
-
this.root?.close();
|
|
302
|
+
rootPending?.controller.abort(new Error("Browser session closed"));
|
|
303
|
+
const root = this.root;
|
|
279
304
|
this.root = undefined;
|
|
305
|
+
this.closing = (async () => {
|
|
306
|
+
const connected = await rootPending?.promise.catch(() => undefined);
|
|
307
|
+
for (const connection of new Set([root, connected])) {
|
|
308
|
+
if (!connection) continue;
|
|
309
|
+
try {
|
|
310
|
+
await connection.tabs.shutdown();
|
|
311
|
+
} finally {
|
|
312
|
+
connection.cdp.close();
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
})();
|
|
316
|
+
return this.closing;
|
|
280
317
|
}
|
|
281
318
|
|
|
282
|
-
private async rootConnection(
|
|
319
|
+
private async rootConnection(
|
|
320
|
+
signal?: AbortSignal,
|
|
321
|
+
): Promise<BrowserConnection> {
|
|
322
|
+
if (this.closing) throw new Error("Browser session closed");
|
|
283
323
|
if (this.root) return this.root;
|
|
284
324
|
let pending = this.rootPending;
|
|
285
325
|
if (!pending) {
|
|
@@ -332,14 +372,26 @@ export class BrowserCdpSession {
|
|
|
332
372
|
);
|
|
333
373
|
}
|
|
334
374
|
|
|
335
|
-
private async connectRoot(signal: AbortSignal): Promise<
|
|
375
|
+
private async connectRoot(signal: AbortSignal): Promise<BrowserConnection> {
|
|
336
376
|
const client = new CdpClient();
|
|
337
|
-
|
|
338
|
-
|
|
377
|
+
const url = await getWebSocketUrl();
|
|
378
|
+
try {
|
|
379
|
+
await client.connect(url, signal);
|
|
380
|
+
signal.throwIfAborted();
|
|
381
|
+
if (this.closing) throw new Error("Browser session closed");
|
|
382
|
+
} catch (error) {
|
|
383
|
+
client.close();
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
const connection = {
|
|
387
|
+
cdp: client,
|
|
388
|
+
tabs: new BrowserTabs(client, this.ownerId, this.ownershipDirectory, url),
|
|
389
|
+
};
|
|
390
|
+
this.root = connection;
|
|
339
391
|
client.onClose(() => {
|
|
340
|
-
if (this.root !==
|
|
392
|
+
if (this.root !== connection) return;
|
|
341
393
|
this.root = undefined;
|
|
342
394
|
});
|
|
343
|
-
return
|
|
395
|
+
return connection;
|
|
344
396
|
}
|
|
345
397
|
}
|
|
@@ -16,7 +16,13 @@ export interface SnapshotElement {
|
|
|
16
16
|
id: number;
|
|
17
17
|
role: string;
|
|
18
18
|
name?: string | undefined;
|
|
19
|
+
href?: string | undefined;
|
|
20
|
+
href_omitted?: true | undefined;
|
|
19
21
|
value?: unknown;
|
|
22
|
+
checked?: boolean | "mixed" | undefined;
|
|
23
|
+
selected?: boolean | undefined;
|
|
24
|
+
expanded?: boolean | undefined;
|
|
25
|
+
disabled?: boolean | undefined;
|
|
20
26
|
}
|
|
21
27
|
|
|
22
28
|
export interface SnapshotResult {
|