@howaboua/pi-browser 0.0.2 → 0.0.4

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +4 -0
  3. package/dist/index.js +5 -5
  4. package/dist/remote-worker.js +985 -139
  5. package/dist/src/browser/bounds.d.ts +1 -1
  6. package/dist/src/browser/bounds.js +6 -3
  7. package/dist/src/browser/help.js +17 -6
  8. package/dist/src/browser/operation-executor.js +15 -1
  9. package/dist/src/browser/operation.d.ts +25 -2
  10. package/dist/src/browser/operation.js +5 -0
  11. package/dist/src/browser/parse-operation.js +61 -2
  12. package/dist/src/browser/remote.d.ts +1 -1
  13. package/dist/src/browser/remote.js +2 -2
  14. package/dist/src/browser/runtime.d.ts +8 -3
  15. package/dist/src/browser/runtime.js +91 -25
  16. package/dist/src/browser/worker-server.js +12 -6
  17. package/dist/src/browser-parameters.d.ts +10 -0
  18. package/dist/src/browser-parameters.js +32 -0
  19. package/dist/src/browser-tool.d.ts +10 -0
  20. package/dist/src/browser-tool.js +3 -12
  21. package/dist/src/cdp/actions/click.d.ts +2 -0
  22. package/dist/src/cdp/actions/click.js +1 -1
  23. package/dist/src/cdp/actions/fill.d.ts +8 -0
  24. package/dist/src/cdp/actions/fill.js +175 -0
  25. package/dist/src/cdp/actions/key.d.ts +20 -0
  26. package/dist/src/cdp/actions/key.js +166 -0
  27. package/dist/src/cdp/actions/wait.d.ts +9 -0
  28. package/dist/src/cdp/actions/wait.js +95 -0
  29. package/dist/src/cdp/pages.d.ts +2 -1
  30. package/dist/src/cdp/pages.js +8 -4
  31. package/dist/src/cdp/session.d.ts +7 -1
  32. package/dist/src/cdp/session.js +79 -27
  33. package/dist/src/cdp/snapshot-contract.d.ts +4 -0
  34. package/dist/src/cdp/snapshot.js +67 -11
  35. package/dist/src/cdp/tabs.d.ts +32 -0
  36. package/dist/src/cdp/tabs.js +226 -0
  37. package/dist/src/cdp/types.d.ts +2 -0
  38. package/index.ts +5 -11
  39. package/package.json +5 -5
  40. package/src/browser/bounds.ts +7 -2
  41. package/src/browser/help.ts +18 -6
  42. package/src/browser/operation-executor.ts +34 -0
  43. package/src/browser/operation.ts +19 -1
  44. package/src/browser/parse-operation.ts +63 -2
  45. package/src/browser/remote.ts +2 -1
  46. package/src/browser/runtime.ts +115 -26
  47. package/src/browser/worker-server.ts +24 -7
  48. package/src/browser-parameters.ts +34 -0
  49. package/src/browser-tool.ts +3 -13
  50. package/src/cdp/actions/click.ts +1 -1
  51. package/src/cdp/actions/fill.ts +246 -0
  52. package/src/cdp/actions/key.ts +202 -0
  53. package/src/cdp/actions/wait.ts +117 -0
  54. package/src/cdp/pages.ts +9 -6
  55. package/src/cdp/session.ts +98 -46
  56. package/src/cdp/snapshot-contract.ts +4 -0
  57. package/src/cdp/snapshot.ts +86 -17
  58. package/src/cdp/tabs.ts +292 -0
  59. package/src/cdp/types.ts +2 -0
@@ -0,0 +1,246 @@
1
+ import type { CdpConnection, ElementRefs } from "../types.js";
2
+ import { asRecord } from "../types.js";
3
+ import { clickBackendNode } from "./click.js";
4
+ import {
5
+ backendCenter,
6
+ requireElementRef,
7
+ withBackendObject,
8
+ } from "./element.js";
9
+ import { pressKey } from "./key.js";
10
+ import { selectorBackendNode } from "./selector.js";
11
+
12
+ // Runs in the element's realm. Native setters bypass framework value trackers;
13
+ // input/change events notify controlled form components of the replacement.
14
+ function prepareFill(this: HTMLElement, value: string | boolean) {
15
+ if (!this.isConnected) throw new Error("Element detached; run open again");
16
+ if (
17
+ this.matches(":disabled") ||
18
+ this.getAttribute("aria-disabled") === "true" ||
19
+ this.closest("[inert]")
20
+ ) {
21
+ throw new Error("Element is disabled or inert");
22
+ }
23
+ const input = this instanceof HTMLInputElement;
24
+ const textarea = this instanceof HTMLTextAreaElement;
25
+ const select = this instanceof HTMLSelectElement;
26
+ if ((input || textarea) && this.readOnly)
27
+ throw new Error("Element is read-only");
28
+ const toggle = input && (this.type === "checkbox" || this.type === "radio");
29
+ if (toggle) {
30
+ if (typeof value !== "boolean")
31
+ throw new Error("Checkbox/radio requires a boolean value");
32
+ if (this.type === "radio" && !value && this.checked) {
33
+ throw new Error(
34
+ "Select another radio option with value true instead of unchecking this one",
35
+ );
36
+ }
37
+ const indeterminate = this.type === "checkbox" && this.indeterminate;
38
+ if (indeterminate && this.checked === value) {
39
+ const setter = Object.getOwnPropertyDescriptor(
40
+ HTMLInputElement.prototype,
41
+ "checked",
42
+ )?.set;
43
+ if (!setter) throw new Error("Checkbox has no native checked setter");
44
+ // A click clears indeterminate and toggles checked. Start from the
45
+ // opposite state so that single click lands on the requested value.
46
+ setter.call(this, !value);
47
+ }
48
+ return {
49
+ kind: "checked",
50
+ expected: value,
51
+ needsClick: this.checked !== value || indeterminate,
52
+ };
53
+ }
54
+ if (typeof value !== "string")
55
+ throw new Error("Text fields and selects require a string value");
56
+ if (
57
+ input &&
58
+ ![
59
+ "text",
60
+ "search",
61
+ "email",
62
+ "url",
63
+ "tel",
64
+ "password",
65
+ "number",
66
+ "date",
67
+ "time",
68
+ "datetime-local",
69
+ "month",
70
+ "week",
71
+ ].includes(this.type)
72
+ ) {
73
+ throw new Error(`Input type ${this.type} does not support fill`);
74
+ }
75
+ if (!input && !textarea && !select && !this.isContentEditable) {
76
+ throw new Error("Element is not an editable form control");
77
+ }
78
+ let replacement = value;
79
+ if (select) {
80
+ if (this.multiple) throw new Error("fill requires a single-select control");
81
+ const options = Array.from(this.options);
82
+ const byValue = options.filter((option) => option.value === value);
83
+ const matches = byValue.length
84
+ ? byValue
85
+ : options.filter((option) => option.label.trim() === value);
86
+ const option = matches[0];
87
+ if (matches.length !== 1 || !option)
88
+ throw new Error("Option value/label must match exactly one option");
89
+ if (option.matches(":disabled")) throw new Error("Option is disabled");
90
+ replacement = option.value;
91
+ }
92
+ this.focus({ preventScroll: true });
93
+ const root = this.getRootNode() as Document | ShadowRoot;
94
+ if (!this.isConnected || root.activeElement !== this) {
95
+ throw new Error("Could not focus element; fill was not sent");
96
+ }
97
+ if (!input && !textarea && !select) {
98
+ const selection = this.ownerDocument.getSelection();
99
+ if (!selection) throw new Error("Could not select editable text");
100
+ const range = this.ownerDocument.createRange();
101
+ range.selectNodeContents(this);
102
+ selection.removeAllRanges();
103
+ selection.addRange(range);
104
+ return { kind: "contenteditable", expected: value };
105
+ }
106
+ const prototype = input
107
+ ? HTMLInputElement.prototype
108
+ : textarea
109
+ ? HTMLTextAreaElement.prototype
110
+ : HTMLSelectElement.prototype;
111
+ const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
112
+ if (!setter) throw new Error("Form control has no native value setter");
113
+ if (input || textarea) {
114
+ const probe = this.cloneNode(false) as
115
+ | HTMLInputElement
116
+ | HTMLTextAreaElement;
117
+ setter.call(probe, replacement);
118
+ if (probe.value !== replacement)
119
+ throw new Error(
120
+ "Value is not accepted by this control; fill was not sent",
121
+ );
122
+ }
123
+ setter.call(this, replacement);
124
+ this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
125
+ this.dispatchEvent(new Event("change", { bubbles: true }));
126
+ return { kind: "value", expected: replacement };
127
+ }
128
+
129
+ async function callElement(
130
+ cdp: CdpConnection,
131
+ sessionId: string,
132
+ objectId: string,
133
+ declaration: string,
134
+ value: unknown,
135
+ signal?: AbortSignal,
136
+ ): Promise<Record<string, unknown>> {
137
+ const response = asRecord(
138
+ await cdp.send(
139
+ "Runtime.callFunctionOn",
140
+ {
141
+ objectId,
142
+ functionDeclaration: declaration,
143
+ arguments: [{ value }],
144
+ returnByValue: true,
145
+ },
146
+ sessionId,
147
+ signal,
148
+ ),
149
+ );
150
+ if (response["exceptionDetails"]) {
151
+ const details = asRecord(response["exceptionDetails"]);
152
+ const exception = details["exception"]
153
+ ? asRecord(details["exception"])
154
+ : {};
155
+ throw new Error(
156
+ typeof exception["description"] === "string"
157
+ ? exception["description"]
158
+ : "Fill failed; run open to inspect the control before retrying",
159
+ );
160
+ }
161
+ return asRecord(asRecord(response["result"])["value"], "fill result");
162
+ }
163
+
164
+ export async function fillElement(
165
+ cdp: CdpConnection,
166
+ sessionId: string,
167
+ elementRefs: ElementRefs,
168
+ target: { id: number; selector?: never } | { selector: string; id?: never },
169
+ value: string | boolean,
170
+ signal?: AbortSignal,
171
+ ): Promise<string> {
172
+ const backendNodeId =
173
+ target.id !== undefined
174
+ ? requireElementRef(elementRefs, target.id).backendNodeId
175
+ : await selectorBackendNode(cdp, sessionId, target.selector, signal);
176
+ await backendCenter(cdp, sessionId, backendNodeId, true, signal);
177
+ return withBackendObject(
178
+ cdp,
179
+ sessionId,
180
+ backendNodeId,
181
+ async (objectId) => {
182
+ const prepared = await callElement(
183
+ cdp,
184
+ sessionId,
185
+ objectId,
186
+ prepareFill.toString(),
187
+ value,
188
+ signal,
189
+ );
190
+ if (prepared["kind"] === "checked" && prepared["needsClick"] === true) {
191
+ await clickBackendNode(cdp, sessionId, backendNodeId, signal);
192
+ } else if (prepared["kind"] === "contenteditable") {
193
+ const focused = await callElement(
194
+ cdp,
195
+ sessionId,
196
+ objectId,
197
+ `function() {
198
+ const selection = this.ownerDocument.getSelection();
199
+ return { ok: this.isConnected && this.getRootNode().activeElement === this &&
200
+ selection && this.contains(selection.anchorNode) && this.contains(selection.focusNode) };
201
+ }`,
202
+ null,
203
+ signal,
204
+ );
205
+ if (focused["ok"] !== true)
206
+ throw new Error("Focus or selection changed; fill was not sent");
207
+ if (value === "") await pressKey(cdp, sessionId, "Backspace", signal);
208
+ else
209
+ await cdp.send(
210
+ "Input.insertText",
211
+ { text: value },
212
+ sessionId,
213
+ signal,
214
+ );
215
+ }
216
+ const verified = await callElement(
217
+ cdp,
218
+ sessionId,
219
+ objectId,
220
+ `function(expected) {
221
+ if (!this.isConnected) return { ok: false };
222
+ const toggle = this instanceof HTMLInputElement && (this.type === 'checkbox' || this.type === 'radio');
223
+ // Editable DOM has no value property. Native editing introduces NBSPs
224
+ // and block/BR nodes, so compare equivalent rendered text, not markup.
225
+ if (this.isContentEditable) {
226
+ const normalize = text => text.replace(/\\s+/g, ' ').trim();
227
+ return { ok: normalize(this.innerText) === normalize(expected) };
228
+ }
229
+ const actual = toggle ? this.checked : this.value;
230
+ return { ok: actual === expected && (!toggle || !this.indeterminate) };
231
+ }`,
232
+ prepared["expected"],
233
+ signal,
234
+ );
235
+ if (verified["ok"] !== true) {
236
+ throw new Error(
237
+ "Fill did not retain the requested value; run open to inspect the control before retrying",
238
+ );
239
+ }
240
+ return target.id === undefined
241
+ ? "Filled selected element"
242
+ : `Filled element ${target.id}`;
243
+ },
244
+ signal,
245
+ );
246
+ }
@@ -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 getPages(
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
- .map(pageInfo)
29
- .filter(
30
- (target) => target.type === "page" && !target.url.startsWith("chrome://"),
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(