thuthi-plugin 0.0.0-stage → 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/.claude-plugin/marketplace.json +55 -0
- package/README.md +13 -2
- package/bin/parallel-browser.js +109 -0
- package/extension/background.js +1329 -0
- package/extension/config.json +1 -0
- package/extension/guard.js +44 -0
- package/extension/manifest.json +10 -0
- package/extension/overlay.js +104 -0
- package/extension/popup.html +34 -0
- package/extension/popup.js +39 -0
- package/extension-reloader/manifest.json +13 -0
- package/extension-reloader/sw.js +17 -0
- package/package.json +13 -4
- package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
- package/plugins/thuthi/context.md +3 -0
- package/plugins/thuthi/hooks/hooks.json +15 -0
- package/plugins/thuthi/skills/setup/SKILL.md +55 -0
- package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
- package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
- package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
- package/plugins/thuthi/tools/legacy_launcher.py +65 -0
- package/plugins/thuthi/tools/statusline/statusline.py +8 -0
- package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-accounts/bin/claude-switch +5 -0
- package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
- package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
- package/plugins/thuthi-accounts/lib/tls.py +68 -0
- package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
- package/plugins/thuthi-accounts/setup_check.py +21 -0
- package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
- package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
- package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
- package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
- package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
- package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-agenda-picker/context.md +3 -0
- package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
- package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
- package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
- package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
- package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
- package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
- package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-browser/context.md +3 -0
- package/plugins/thuthi-browser/hooks/hooks.json +15 -0
- package/plugins/thuthi-browser/lib/pbpage.py +397 -0
- package/plugins/thuthi-browser/setup_check.py +93 -0
- package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
- package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
- package/plugins/thuthi-demo-video/setup_check.py +14 -0
- package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
- package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
- package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-orca/context.md +5 -0
- package/plugins/thuthi-orca/hooks/hooks.json +18 -0
- package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
- package/plugins/thuthi-orca/setup_check.py +12 -0
- package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
- package/runtime/client.js +69 -0
- package/runtime/daemon.js +503 -0
- package/runtime/focus-monitor.js +53 -0
- package/runtime/keys.js +86 -0
- package/runtime/owner.js +64 -0
- package/runtime/recorder.js +267 -0
- package/runtime/relay.js +95 -0
- package/runtime/session.js +1599 -0
|
@@ -0,0 +1,1599 @@
|
|
|
1
|
+
// Agent-facing Session: one tab group inside the dedicated agent window of the user's browser.
|
|
2
|
+
// Every browser interaction goes through the extension relay (directly or via the daemon), so
|
|
3
|
+
// the guard rails apply. Nothing here ever focuses a window or activates a tab.
|
|
4
|
+
import { EventEmitter } from 'node:events';
|
|
5
|
+
import { writeFile } from 'node:fs/promises';
|
|
6
|
+
import { inspect } from 'node:util';
|
|
7
|
+
import { Recorder } from './recorder.js';
|
|
8
|
+
import { parseKey } from './keys.js';
|
|
9
|
+
import { parseOwner } from './owner.js';
|
|
10
|
+
|
|
11
|
+
const FORBIDDEN_IN_RUNTIME = new Set(['Page.bringToFront', 'Target.activateTarget']);
|
|
12
|
+
/** The shape of a session handle. Anything else given to session() is a display label. */
|
|
13
|
+
// What a session is called in front of the user, and what an agent must hold to drive it.
|
|
14
|
+
// The id is public (session.list shows every session's); the handle carries the capability.
|
|
15
|
+
export const SESSION_ID = /^pb-[0-9a-f]{8}$/;
|
|
16
|
+
export const SESSION_HANDLE = /^pb-[0-9a-f]{8}-[0-9a-f]{32}$/;
|
|
17
|
+
const INTERACTIVE_ROLES = new Set(['button', 'link', 'textbox', 'searchbox', 'combobox', 'checkbox', 'radio', 'switch', 'slider', 'spinbutton', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'tab', 'option', 'listbox', 'textarea']);
|
|
18
|
+
const SKIP_ROLES = new Set(['none', 'generic', 'InlineTextBox', 'LineBreak', 'presentation', 'Ignored']);
|
|
19
|
+
|
|
20
|
+
export class ElementError extends Error {
|
|
21
|
+
constructor(message, kind = 'permanent') { super(message); this.kind = kind; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What snapshot() returns: an array with one line per element, which also reads as the text of
|
|
26
|
+
* those lines. Agents treat it both ways (2026-10 transcripts: 549 scripts used array methods,
|
|
27
|
+
* 157 called split/includes/match on it as a string), so both work. console.log prints the plain
|
|
28
|
+
* lines instead of a quoted array cut off after 100 items, and `${snap}` / out(snap) give the text.
|
|
29
|
+
*/
|
|
30
|
+
export class Snapshot extends Array {
|
|
31
|
+
get text() { return this.join('\n'); }
|
|
32
|
+
toString() { return this.text; }
|
|
33
|
+
[Symbol.toPrimitive]() { return this.text; }
|
|
34
|
+
[inspect.custom]() { return this.text; }
|
|
35
|
+
split(...a) { return this.text.split(...a); }
|
|
36
|
+
/** A string is looked up in the text (so a part of a line matches); anything else as an element. */
|
|
37
|
+
includes(v, from) { return typeof v === 'string' ? this.text.includes(v) : super.includes(v, from); }
|
|
38
|
+
match(re) { return this.text.match(re); }
|
|
39
|
+
matchAll(re) { return this.text.matchAll(re); }
|
|
40
|
+
replace(a, b) { return this.text.replace(a, b); }
|
|
41
|
+
replaceAll(a, b) { return this.text.replaceAll(a, b); }
|
|
42
|
+
search(re) { return this.text.search(re); }
|
|
43
|
+
trim() { return this.text.trim(); }
|
|
44
|
+
startsWith(v) { return this.text.startsWith(v); }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Thrown when the user has taken control: the agent may still look, but not act. */
|
|
48
|
+
export class SessionPausedError extends Error {
|
|
49
|
+
constructor(message) { super(message); this.name = 'SessionPausedError'; this.paused = true; }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class Session extends EventEmitter {
|
|
53
|
+
/** @param {{call:Function,on:Function,off:Function,isDaemon?:boolean}} relay */
|
|
54
|
+
constructor(relay, info) {
|
|
55
|
+
super();
|
|
56
|
+
this.relay = relay;
|
|
57
|
+
this.id = info.sessionId;
|
|
58
|
+
this.key = info.key;
|
|
59
|
+
this.name = info.name;
|
|
60
|
+
this.color = info.color;
|
|
61
|
+
this.windowId = info.windowId;
|
|
62
|
+
this.placement = info.placement || 'shared';
|
|
63
|
+
this.groupId = info.groupId;
|
|
64
|
+
this.tabId = info.tabId;
|
|
65
|
+
this.closed = false;
|
|
66
|
+
this.paused = false;
|
|
67
|
+
this.pausedBy = null; // 'user' when they pressed the button, 'agent' when we handed over
|
|
68
|
+
this.recorder = null;
|
|
69
|
+
// Input.dispatch* 좌표에 곱할 배율. 화면 크기 흉내에 scale (< 1) 을 걸면 브라우저는 입력 좌표를 축소된 창 기준으로
|
|
70
|
+
// 읽는다 (CSS 좌표 c 를 맞히려면 c × scale 을 보낸다, 2026-10-09 실측). 기본 1 이라 다른 사용처는 그대로다.
|
|
71
|
+
this.inputScale = 1;
|
|
72
|
+
this.viewport = null; // { width, height, dpr, scale } once setViewport() ran; re-applied to new tabs
|
|
73
|
+
this.dialogs = [];
|
|
74
|
+
this.dialogHandler = null;
|
|
75
|
+
this.pendingFiles = null;
|
|
76
|
+
this.fileChoosers = [];
|
|
77
|
+
this.credentials = null;
|
|
78
|
+
this.authAttempts = new Map();
|
|
79
|
+
this.inflight = new Map(); // tabId -> Map(requestId -> startedAt)
|
|
80
|
+
this.enabledTabs = new Set();
|
|
81
|
+
this.replacedTabs = new Map(); // old tab id -> the one the browser swapped in (tab.replaced)
|
|
82
|
+
// Frame inventory for the current tab. Same-origin frames are reachable through an
|
|
83
|
+
// execution context of the tab's own CDP session; cross-origin ones (OOPIF) are separate
|
|
84
|
+
// debuggee targets the extension attaches to.
|
|
85
|
+
// Execution contexts per debuggee ('tab' or a frame target id), then per frame. A nested
|
|
86
|
+
// frame needs its own context id; the root frame of a debuggee is its default context.
|
|
87
|
+
this.contexts = new Map(); // targetKey -> Map(frameId -> contextId)
|
|
88
|
+
this.frames = []; // [{ frameId, url, kind, targetKey, targetId?, contextId?, offset }]
|
|
89
|
+
this.framesFresh = false;
|
|
90
|
+
this.on('Runtime.executionContextCreated', (p, _tabId, targetId) => {
|
|
91
|
+
const a = p.context.auxData;
|
|
92
|
+
if (!a?.isDefault || !a.frameId) return;
|
|
93
|
+
const key = targetId || 'tab';
|
|
94
|
+
if (!this.contexts.has(key)) this.contexts.set(key, new Map());
|
|
95
|
+
this.contexts.get(key).set(a.frameId, p.context.id);
|
|
96
|
+
});
|
|
97
|
+
this.on('Runtime.executionContextsCleared', (_p, _tabId, targetId) => { this.contexts.delete(targetId || 'tab'); this.framesFresh = false; });
|
|
98
|
+
this.on('Page.frameNavigated', () => { this.framesFresh = false; });
|
|
99
|
+
this.onEvent = (p) => this.#handleEvent(p);
|
|
100
|
+
this.onTakeover = (p) => this.#handleTakeover(p);
|
|
101
|
+
this.onResumed = (p) => { if (p.sessionId === this.id) { this.paused = false; this.pausedBy = null; this.emit('resumed', p); } };
|
|
102
|
+
this.onReplaced = (p) => this.#handleReplaced(p);
|
|
103
|
+
relay.on('event:cdp.event', this.onEvent);
|
|
104
|
+
relay.on('event:session.takeover', this.onTakeover);
|
|
105
|
+
relay.on('event:session.resumed', this.onResumed);
|
|
106
|
+
relay.on('event:tab.replaced', this.onReplaced);
|
|
107
|
+
this.on('Page.javascriptDialogOpening', (d, tabId) => this.#handleDialog(d, tabId));
|
|
108
|
+
this.on('Page.fileChooserOpened', (d, tabId) => this.#handleFileChooser(d, tabId));
|
|
109
|
+
this.on('Fetch.requestPaused', (d, tabId) => this.cdp('Fetch.continueRequest', { requestId: d.requestId }, { tabId }).catch(() => {}));
|
|
110
|
+
this.on('Fetch.authRequired', (d, tabId) => this.#handleAuth(d, tabId));
|
|
111
|
+
this.on('Network.requestWillBeSent', (d, tabId) => this.#track(tabId).set(d.requestId, Date.now()));
|
|
112
|
+
this.on('Network.loadingFinished', (d, tabId) => this.#track(tabId).delete(d.requestId));
|
|
113
|
+
this.on('Network.loadingFailed', (d, tabId) => this.#track(tabId).delete(d.requestId));
|
|
114
|
+
this.on('Network.requestServedFromCache', (d, tabId) => this.#track(tabId).delete(d.requestId));
|
|
115
|
+
// Requests of the previous document often never report finished; a committed main-frame
|
|
116
|
+
// navigation retires them, otherwise waitForNetworkIdle could never reach zero.
|
|
117
|
+
this.on('Page.frameNavigated', (d, tabId) => { if (!d.frame?.parentId) this.#track(tabId).clear(); });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------- lifecycle ----------
|
|
121
|
+
|
|
122
|
+
/** placement: 'shared' (tab group in the ONE dedicated agent window, default) | 'window' | 'group' */
|
|
123
|
+
static async create(relay, { name, color, bounds, budget, placement = 'shared', windowId } = {}) {
|
|
124
|
+
const info = await relay.call('session.create', { name, color, bounds, budget, placement, windowId });
|
|
125
|
+
const s = new Session(relay, { ...info, name: name || `session-${info.sessionId}` });
|
|
126
|
+
await s.#ensureTab(s.tabId);
|
|
127
|
+
await s.status('ready');
|
|
128
|
+
return s;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The one way agents address a session. A full handle (`pb-xxxxxxxx-<key>`) resumes exactly
|
|
133
|
+
* that session; anything else is a display label and always creates a NEW one. Neither a name
|
|
134
|
+
* nor a bare id is a handle: two agents sharing this browser must not be able to reach each
|
|
135
|
+
* other's tabs, by accident or on purpose.
|
|
136
|
+
*/
|
|
137
|
+
static async open(relay, handleOrName, opts = {}) {
|
|
138
|
+
const v = String(handleOrName || '');
|
|
139
|
+
if (SESSION_HANDLE.test(v)) return Session.attach(relay, v);
|
|
140
|
+
if (SESSION_ID.test(v)) {
|
|
141
|
+
throw new Error(`${v} is a display id, not a handle. Resuming needs the full handle printed when the session was created, and only its creator was given it — sessions started by another agent cannot be attached at all.`);
|
|
142
|
+
}
|
|
143
|
+
return Session.create(relay, { ...opts, name: handleOrName });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Resume a session from the handle its creator was given. */
|
|
147
|
+
static async attach(relay, handle) {
|
|
148
|
+
if (!SESSION_HANDLE.test(String(handle || ''))) throw new Error(`not a session handle: ${handle}`);
|
|
149
|
+
const [, id, key] = String(handle).match(/^(pb-[0-9a-f]{8})-([0-9a-f]{32})$/);
|
|
150
|
+
let existing;
|
|
151
|
+
try {
|
|
152
|
+
existing = await relay.call('session.attach', { sessionId: id, key });
|
|
153
|
+
} catch (e) {
|
|
154
|
+
if (/unknown session/.test(e.message)) throw new Error(`no session ${id} (it may have been closed; sessions cannot be listed, so make a new one)`);
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
if (!existing.tabIds.length) throw new Error(`session ${id} has no tabs left`);
|
|
158
|
+
const s = new Session(relay, {
|
|
159
|
+
sessionId: existing.id, key, name: existing.name, color: existing.color,
|
|
160
|
+
windowId: existing.windowId, placement: existing.placement, groupId: existing.groupId, tabId: existing.tabIds[0],
|
|
161
|
+
});
|
|
162
|
+
s.paused = existing.paused;
|
|
163
|
+
await s.#ensureTab(s.tabId);
|
|
164
|
+
return s;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async #ensureTab(tabId) {
|
|
168
|
+
this.framesFresh = false;
|
|
169
|
+
if (this.enabledTabs.has(tabId)) return;
|
|
170
|
+
this.enabledTabs.add(tabId);
|
|
171
|
+
const o = { tabId };
|
|
172
|
+
await this.cdp('Page.enable', {}, o);
|
|
173
|
+
await this.cdp('Runtime.enable', {}, o);
|
|
174
|
+
await this.cdp('DOM.enable', {}, o);
|
|
175
|
+
await this.cdp('Network.enable', {}, o);
|
|
176
|
+
// Pages believe they are focused although the window never is; this also keeps the tab
|
|
177
|
+
// rendering (rAF, screenshots, screencast) while minimized, occluded or in the background.
|
|
178
|
+
await this.cdp('Emulation.setFocusEmulationEnabled', { enabled: true }, o);
|
|
179
|
+
await this.cdp('Page.setInterceptFileChooserDialog', { enabled: true }, o).catch(() => {});
|
|
180
|
+
if (this.credentials) await this.#enableAuth(tabId);
|
|
181
|
+
if (this.viewport) await this.#applyViewport(tabId);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The handle to keep: it is the only thing that can drive this session again later. */
|
|
185
|
+
get handle() { return `${this.id}-${this.key}`; }
|
|
186
|
+
|
|
187
|
+
/** Every session-scoped call proves ownership; the extension rejects it otherwise. */
|
|
188
|
+
call(method, params = {}, opts) {
|
|
189
|
+
return this.relay.call(method, { sessionId: this.id, key: this.key, ...params }, opts);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
cdp(method, params = {}, { tabId = this.tabId, targetId, timeout = 30000 } = {}) {
|
|
193
|
+
if (FORBIDDEN_IN_RUNTIME.has(method)) return Promise.reject(new Error(`${method} is forbidden: it would steal focus`));
|
|
194
|
+
const addr = targetId ? { targetId } : { tabId };
|
|
195
|
+
return this.call('cdp', { ...addr, method, params }, { timeout })
|
|
196
|
+
.catch((e) => { throw /^session paused:/.test(e.message) ? new SessionPausedError(e.message) : e; });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
status(text) { return this.call('session.status', { text }); }
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Ask the user to take the wheel — a login, a captcha, a confirmation the agent must not make
|
|
203
|
+
* on its own. The session pauses exactly as if they had taken it, so every page-changing
|
|
204
|
+
* command throws, but the overlay says the agent handed it over rather than that someone
|
|
205
|
+
* grabbed it. Say what you need in `message`; it is what the user reads.
|
|
206
|
+
*/
|
|
207
|
+
async handOff(message) {
|
|
208
|
+
this.paused = true;
|
|
209
|
+
this.pausedBy = 'agent';
|
|
210
|
+
return this.call('session.handOff', { message: message || '사용자 확인 필요' });
|
|
211
|
+
}
|
|
212
|
+
resume() { this.paused = false; this.pausedBy = null; return this.call('session.resume'); }
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Add a process whose exit closes this session. session() sets one already (the agent that ran
|
|
216
|
+
* the script; see the `owner` option), so call this only to add another: a session stays until
|
|
217
|
+
* every owner is gone, then closes within seconds — paused or not. Needs the daemon (the CLI).
|
|
218
|
+
*/
|
|
219
|
+
setOwner(owner) {
|
|
220
|
+
const pid = parseOwner(owner);
|
|
221
|
+
if (pid === null || !this.relay.isDaemon) return Promise.resolve({ owner: null });
|
|
222
|
+
return this.call('session.owner', { owner: pid });
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Removed (0.21.0): it took a session out of the watch for good, and those tabs were never closed
|
|
226
|
+
// (in four days of logs 11 of 15 uses were closed minutes later by the agent that kept them, and
|
|
227
|
+
// one stayed forever). A session already stays open for as long as its agent runs. Left as a
|
|
228
|
+
// no-op so a script written from an older Skill does not die on it.
|
|
229
|
+
keepOpen = () => { console.error('note: keepOpen() was removed and does nothing. A session stays open while the agent that opened it is running and closes within seconds of it exiting.'); return Promise.resolve({ owner: null }); };
|
|
230
|
+
|
|
231
|
+
async close() {
|
|
232
|
+
if (this.closed) return;
|
|
233
|
+
this.closed = true;
|
|
234
|
+
this.relay.off('event:cdp.event', this.onEvent);
|
|
235
|
+
this.relay.off('event:session.takeover', this.onTakeover);
|
|
236
|
+
this.relay.off('event:session.resumed', this.onResumed);
|
|
237
|
+
this.relay.off('event:tab.replaced', this.onReplaced);
|
|
238
|
+
try { await this.call('session.close'); } catch { /* browser may be gone */ }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ---------- events ----------
|
|
242
|
+
|
|
243
|
+
#handleEvent(p) {
|
|
244
|
+
if (p.sessionId !== this.id) return;
|
|
245
|
+
this.emit(p.method, p.params, p.tabId ?? this.tabId, p.targetId);
|
|
246
|
+
this.emit('cdp', p);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
#handleTakeover(p) {
|
|
250
|
+
if (p.sessionId !== this.id) return;
|
|
251
|
+
this.paused = true;
|
|
252
|
+
this.pausedBy = 'user';
|
|
253
|
+
this.emit('takeover', p);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The browser swapped one of our tabs for a new one (a discarded tab brought back). The page was
|
|
258
|
+
* reloaded, so enabled domains and the emulated screen size are gone: follow the new id and set
|
|
259
|
+
* them up again. The old id still works for calls (the extension maps it), so code holding it
|
|
260
|
+
* keeps going.
|
|
261
|
+
*/
|
|
262
|
+
#handleReplaced({ sessionId, oldTabId, tabId }) {
|
|
263
|
+
if (sessionId !== this.id) return;
|
|
264
|
+
this.replacedTabs.set(oldTabId, tabId);
|
|
265
|
+
if (this.tabId === oldTabId) this.tabId = tabId;
|
|
266
|
+
this.inflight.delete(oldTabId);
|
|
267
|
+
if (this.enabledTabs.delete(oldTabId)) this.#ensureTab(tabId).catch(() => {});
|
|
268
|
+
this.emit('tab.replaced', { oldTabId, tabId });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
#track(tabId) {
|
|
272
|
+
if (!this.inflight.has(tabId)) this.inflight.set(tabId, new Map());
|
|
273
|
+
return this.inflight.get(tabId);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** In-flight requests, ignoring ones stuck long enough that they will never settle. */
|
|
277
|
+
#inflightCount(tabId, staleMs = 10000) {
|
|
278
|
+
const m = this.#track(tabId);
|
|
279
|
+
const now = Date.now();
|
|
280
|
+
for (const [id, at] of m) if (now - at > staleMs) m.delete(id);
|
|
281
|
+
return m.size;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** JS dialogs block the page until answered. Default: beforeunload accepted, everything else dismissed. */
|
|
285
|
+
onDialog(fn) { this.dialogHandler = fn; }
|
|
286
|
+
|
|
287
|
+
async #handleDialog(d, tabId) {
|
|
288
|
+
const record = { type: d.type, message: d.message, url: d.url, at: Date.now() };
|
|
289
|
+
this.dialogs.push(record);
|
|
290
|
+
let decision = { accept: d.type === 'beforeunload' };
|
|
291
|
+
try { if (this.dialogHandler) decision = (await this.dialogHandler(d)) || decision; } catch { /* keep default */ }
|
|
292
|
+
record.decision = decision;
|
|
293
|
+
this.emit('dialog', record);
|
|
294
|
+
await this.cdp('Page.handleJavaScriptDialog', { accept: !!decision.accept, promptText: decision.promptText }, { tabId }).catch(() => {});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Files to hand to the next file chooser the page opens (e.g. after clicking "Upload"). */
|
|
298
|
+
expectUpload(files) { this.pendingFiles = [].concat(files); }
|
|
299
|
+
|
|
300
|
+
async #handleFileChooser(d, tabId) {
|
|
301
|
+
const record = { mode: d.mode, at: Date.now(), served: false };
|
|
302
|
+
this.fileChoosers.push(record);
|
|
303
|
+
if (this.pendingFiles) {
|
|
304
|
+
const files = this.pendingFiles;
|
|
305
|
+
this.pendingFiles = null;
|
|
306
|
+
await this.cdp('DOM.setFileInputFiles', { files, backendNodeId: d.backendNodeId }, { tabId }).catch((e) => { record.error = e.message; });
|
|
307
|
+
record.served = true;
|
|
308
|
+
record.files = files;
|
|
309
|
+
}
|
|
310
|
+
this.emit('filechooser', record);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** HTTP basic/digest auth: answered from these credentials; without them the browser would show a blocking prompt. */
|
|
314
|
+
async setHttpCredentials(credentials) {
|
|
315
|
+
this.credentials = credentials;
|
|
316
|
+
for (const tabId of this.enabledTabs) await this.#enableAuth(tabId);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async clearHttpCredentials() {
|
|
320
|
+
this.credentials = null;
|
|
321
|
+
for (const tabId of this.enabledTabs) await this.cdp('Fetch.disable', {}, { tabId }).catch(() => {});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
#enableAuth(tabId) {
|
|
325
|
+
return this.cdp('Fetch.enable', { handleAuthRequests: true, patterns: [{ urlPattern: '*', requestStage: 'Request' }] }, { tabId });
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async #handleAuth(d, tabId) {
|
|
329
|
+
const key = `${tabId}:${d.authChallenge?.origin}:${d.authChallenge?.realm}`;
|
|
330
|
+
const n = (this.authAttempts.get(key) || 0) + 1;
|
|
331
|
+
this.authAttempts.set(key, n);
|
|
332
|
+
const ok = this.credentials && n <= 2;
|
|
333
|
+
const authChallengeResponse = ok ? { response: 'ProvideCredentials', username: this.credentials.username, password: this.credentials.password } : { response: 'CancelAuth' };
|
|
334
|
+
this.emit('auth', { origin: d.authChallenge?.origin, realm: d.authChallenge?.realm, provided: !!ok });
|
|
335
|
+
await this.cdp('Fetch.continueWithAuth', { requestId: d.requestId, authChallengeResponse }, { tabId }).catch(() => {});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ---------- tabs ----------
|
|
339
|
+
|
|
340
|
+
async tabs() { return (await this.call('session.tabs')).tabs; }
|
|
341
|
+
|
|
342
|
+
/** Point subsequent calls at another tab of this session (no focus change, purely internal). */
|
|
343
|
+
async use(tabId) {
|
|
344
|
+
while (this.replacedTabs.has(tabId)) tabId = this.replacedTabs.get(tabId);
|
|
345
|
+
const t = (await this.tabs()).find((x) => x.tabId === tabId);
|
|
346
|
+
if (!t) throw new Error(`tab ${tabId} is not part of session ${this.name}`);
|
|
347
|
+
this.tabId = tabId;
|
|
348
|
+
await this.#ensureTab(tabId);
|
|
349
|
+
return t;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async newTab(url) {
|
|
353
|
+
const { tabId } = await this.call('tab.create', { url });
|
|
354
|
+
await this.#ensureTab(tabId);
|
|
355
|
+
return tabId;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async closeTab(tabId = this.tabId) {
|
|
359
|
+
await this.call('tab.close', { tabId });
|
|
360
|
+
this.enabledTabs.delete(tabId);
|
|
361
|
+
if (tabId === this.tabId) { const rest = await this.tabs(); if (rest[0]) this.tabId = rest[0].tabId; }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ---------- navigation ----------
|
|
365
|
+
|
|
366
|
+
async goto(url, { timeout = 30000, waitUntil = 'load' } = {}) {
|
|
367
|
+
await this.status(`opening ${hostOf(url)}`);
|
|
368
|
+
const loaded = new Promise((resolve) => {
|
|
369
|
+
const h = (_p, tabId) => { if (tabId === this.tabId) { this.off('Page.loadEventFired', h); resolve(); } };
|
|
370
|
+
this.on('Page.loadEventFired', h);
|
|
371
|
+
});
|
|
372
|
+
const res = await this.cdp('Page.navigate', { url });
|
|
373
|
+
if (res.errorText) throw new Error(`navigation failed: ${res.errorText}`);
|
|
374
|
+
if (waitUntil !== 'none') {
|
|
375
|
+
await withTimeout(loaded, timeout, `load timeout ${timeout}ms: ${url}`);
|
|
376
|
+
if (waitUntil === 'networkidle') await this.waitForNetworkIdle({ timeout });
|
|
377
|
+
}
|
|
378
|
+
await this.status(`on ${hostOf(url)}`);
|
|
379
|
+
return res;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async reload() { await this.cdp('Page.reload'); await this.waitForLoad(); }
|
|
383
|
+
async back() { return this.#history(-1); }
|
|
384
|
+
async forward() { return this.#history(1); }
|
|
385
|
+
|
|
386
|
+
async #history(delta) {
|
|
387
|
+
const { currentIndex, entries } = await this.cdp('Page.getNavigationHistory');
|
|
388
|
+
const entry = entries[currentIndex + delta];
|
|
389
|
+
if (!entry) throw new Error('no history entry in that direction');
|
|
390
|
+
await this.cdp('Page.navigateToHistoryEntry', { entryId: entry.id });
|
|
391
|
+
await this.waitForLoad();
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
url() { return this.evaluate('location.href'); }
|
|
395
|
+
title() { return this.evaluate('document.title'); }
|
|
396
|
+
|
|
397
|
+
// ---------- observation ----------
|
|
398
|
+
|
|
399
|
+
async evaluate(expression, arg) {
|
|
400
|
+
const r = typeof expression === 'function'
|
|
401
|
+
? await this.cdp('Runtime.evaluate', { expression: `(${expression.toString()})(${JSON.stringify(arg ?? null)})`, awaitPromise: true, returnByValue: true })
|
|
402
|
+
: await this.cdp('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
|
|
403
|
+
if (r.exceptionDetails) throw new Error(`evaluate failed: ${r.exceptionDetails.text} ${r.exceptionDetails.exception?.description || ''}`);
|
|
404
|
+
return r.result.value;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Compact accessibility snapshot. Refs (@N) are backend node ids usable as targets.
|
|
409
|
+
* scope: 'page' (everything, default) | 'viewport' (only what is on screen) | 'subtree'
|
|
410
|
+
* (below `root`, which is a ref or selector). Viewport scope is the cheap one to reach for on
|
|
411
|
+
* a long page: it is what the user would see, at a fraction of the tokens.
|
|
412
|
+
* Returns a Snapshot: an array of lines (`.filter`, `.find`, `.length` count lines) that also
|
|
413
|
+
* acts as their text (`.split('\n')`, `.includes('Save')`, `.match(re)`, `.text`, `${snap}`).
|
|
414
|
+
* console.log(snap) and out(snap) print every line.
|
|
415
|
+
*/
|
|
416
|
+
async snapshot({ interactiveOnly = false, max = 400, frames = true, scope = 'page', root = null } = {}) {
|
|
417
|
+
if (scope === 'subtree') {
|
|
418
|
+
if (!root) throw new Error("snapshot({ scope: 'subtree' }) needs a root ref or selector");
|
|
419
|
+
return this.#subtreeSnapshot(root, { interactiveOnly, max });
|
|
420
|
+
}
|
|
421
|
+
const out = [];
|
|
422
|
+
const list = frames ? await this.#framesFor() : [(await this.#framesFor())[0]];
|
|
423
|
+
for (const frame of list) {
|
|
424
|
+
const params = frame.kind === 'cross-origin' ? {} : frame.frameId ? { frameId: frame.frameId } : {};
|
|
425
|
+
const res = await this.cdp('Accessibility.getFullAXTree', params, this.#frameCall(frame)).catch(() => null);
|
|
426
|
+
if (!res) continue;
|
|
427
|
+
let nodes = res.nodes;
|
|
428
|
+
if (scope === 'viewport') {
|
|
429
|
+
const visible = await this.#backendIdsInViewport(frame);
|
|
430
|
+
if (visible) nodes = nodes.filter((n) => n.backendDOMNodeId === undefined || visible.has(n.backendDOMNodeId));
|
|
431
|
+
}
|
|
432
|
+
const lines = this.#formatAX(nodes, { interactiveOnly, max: max - out.length, indent: frame.kind === 'top' ? '' : ' ' });
|
|
433
|
+
if (!lines.length) continue;
|
|
434
|
+
if (frame.kind !== 'top') out.push(`--- iframe ${frame.kind === 'cross-origin' ? '(cross-origin) ' : ''}${frame.url || frame.frameId}`);
|
|
435
|
+
out.push(...lines);
|
|
436
|
+
if (out.length >= max) break;
|
|
437
|
+
}
|
|
438
|
+
return Snapshot.from(out);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
async #subtreeSnapshot(root, { interactiveOnly, max }) {
|
|
442
|
+
const { objectId, frame } = await this.#resolve(root);
|
|
443
|
+
const at = this.#frameCall(frame);
|
|
444
|
+
const { node } = await this.cdp('DOM.describeNode', { objectId }, at);
|
|
445
|
+
const params = frame.kind === 'cross-origin' ? {} : frame.frameId ? { frameId: frame.frameId } : {};
|
|
446
|
+
const { nodes } = await this.cdp('Accessibility.getFullAXTree', params, at);
|
|
447
|
+
// getPartialAXTree also hands back ancestors and siblings, so walk the real tree instead.
|
|
448
|
+
const byId = new Map(nodes.map((n) => [n.nodeId, n]));
|
|
449
|
+
const start = nodes.find((n) => n.backendDOMNodeId === node.backendNodeId);
|
|
450
|
+
if (!start) throw new ElementError(`${root}: no accessibility node for that element`, 'transient');
|
|
451
|
+
const subtree = [];
|
|
452
|
+
const walk = (n) => { if (!n) return; subtree.push(n); for (const id of n.childIds || []) walk(byId.get(id)); };
|
|
453
|
+
walk(start);
|
|
454
|
+
return Snapshot.from(this.#formatAX(subtree, { interactiveOnly, max, indent: '' }));
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Backend node ids of elements currently inside the viewport of one frame. */
|
|
458
|
+
async #backendIdsInViewport(frame) {
|
|
459
|
+
const at = this.#frameCall(frame);
|
|
460
|
+
const MARK = 'data-pb-vp';
|
|
461
|
+
const marked = await this.cdp('Runtime.evaluate', {
|
|
462
|
+
returnByValue: true, ...this.#evalArgs(frame),
|
|
463
|
+
expression: `(() => {
|
|
464
|
+
let n = 0;
|
|
465
|
+
for (const el of document.querySelectorAll('[${MARK}]')) el.removeAttribute('${MARK}');
|
|
466
|
+
for (const el of document.querySelectorAll('*')) {
|
|
467
|
+
const r = el.getBoundingClientRect();
|
|
468
|
+
if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth) continue;
|
|
469
|
+
if (r.width === 0 && r.height === 0) continue;
|
|
470
|
+
el.setAttribute('${MARK}', ''); n++;
|
|
471
|
+
}
|
|
472
|
+
return n;
|
|
473
|
+
})()`,
|
|
474
|
+
}, at).catch(() => null);
|
|
475
|
+
if (!marked?.result?.value) return null;
|
|
476
|
+
const ids = new Set();
|
|
477
|
+
try {
|
|
478
|
+
const doc = await this.cdp('DOM.getDocument', { depth: -1, pierce: true }, at);
|
|
479
|
+
const walk = (n) => {
|
|
480
|
+
const attrs = n.attributes || [];
|
|
481
|
+
for (let i = 0; i < attrs.length; i += 2) if (attrs[i] === MARK) ids.add(n.backendNodeId);
|
|
482
|
+
for (const c of n.children || []) walk(c);
|
|
483
|
+
if (n.contentDocument) walk(n.contentDocument);
|
|
484
|
+
for (const sr of n.shadowRoots || []) walk(sr);
|
|
485
|
+
};
|
|
486
|
+
walk(doc.root);
|
|
487
|
+
} catch { return null; }
|
|
488
|
+
await this.cdp('Runtime.evaluate', { expression: `document.querySelectorAll('[${MARK}]').forEach((el) => el.removeAttribute('${MARK}'))`, ...this.#evalArgs(frame) }, at).catch(() => {});
|
|
489
|
+
return ids;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
#formatAX(nodes, { interactiveOnly, max, indent }) {
|
|
493
|
+
const out = [];
|
|
494
|
+
let lastText = '';
|
|
495
|
+
for (const n of nodes) {
|
|
496
|
+
if (n.ignored) continue;
|
|
497
|
+
const role = n.role?.value;
|
|
498
|
+
const name = (n.name?.value || '').trim();
|
|
499
|
+
if (!role || SKIP_ROLES.has(role)) continue;
|
|
500
|
+
const interactive = INTERACTIVE_ROLES.has(role);
|
|
501
|
+
if (interactiveOnly && !interactive) continue;
|
|
502
|
+
if (role === 'StaticText') {
|
|
503
|
+
if (!name || name === lastText) continue;
|
|
504
|
+
lastText = name;
|
|
505
|
+
out.push(`${indent} "${name.slice(0, 120)}"`);
|
|
506
|
+
} else {
|
|
507
|
+
if (!name && !interactive && role !== 'RootWebArea') continue;
|
|
508
|
+
const props = [];
|
|
509
|
+
for (const p of n.properties || []) {
|
|
510
|
+
if (p.name === 'focused' && p.value?.value) props.push('focused');
|
|
511
|
+
if (p.name === 'checked' && p.value?.value !== 'false') props.push(`checked=${p.value.value}`);
|
|
512
|
+
if (p.name === 'disabled' && p.value?.value) props.push('disabled');
|
|
513
|
+
if (p.name === 'expanded') props.push(`expanded=${p.value?.value}`);
|
|
514
|
+
if (p.name === 'selected' && p.value?.value) props.push('selected');
|
|
515
|
+
}
|
|
516
|
+
const value = n.value?.value;
|
|
517
|
+
if (value !== undefined && value !== '') props.push(`value=${JSON.stringify(String(value).slice(0, 60))}`);
|
|
518
|
+
out.push(`${indent}@${n.backendDOMNodeId} ${role}${name ? ` "${name.slice(0, 80)}"` : ''}${props.length ? ` [${props.join(', ')}]` : ''}`);
|
|
519
|
+
}
|
|
520
|
+
if (out.length >= max) { out.push(`${indent}... (truncated)`); break; }
|
|
521
|
+
}
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Evaluate inside one iframe, picked by a CSS selector on its <iframe> element. Usually the
|
|
527
|
+
* frame's own script world; a frame that was already there when this script started is reached
|
|
528
|
+
* through a separate world that sees its DOM, location and fetch but not the page's variables.
|
|
529
|
+
*/
|
|
530
|
+
async evaluateInFrame(iframeSelector, expression) {
|
|
531
|
+
const frames = await this.#framesFor();
|
|
532
|
+
const frame = await this.#resolvePinnedFrame(iframeSelector, frames);
|
|
533
|
+
const r = await this.cdp('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, ...this.#evalArgs(frame) }, this.#frameCall(frame));
|
|
534
|
+
if (r.exceptionDetails) throw new Error(`evaluate failed: ${r.exceptionDetails.text}`);
|
|
535
|
+
return r.result.value;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** Frames of the current tab, as the runtime sees them. */
|
|
539
|
+
async frameList() {
|
|
540
|
+
return (await this.#framesFor()).map(({ frameId, url, kind, targetId, offset }) => ({ frameId, url, kind, targetId, offset }));
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
text(target) {
|
|
544
|
+
if (!target) return this.evaluate('document.body ? document.body.innerText : ""');
|
|
545
|
+
return this.#withElement(target, 'function(){ return this.innerText ?? this.textContent }');
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
content() { return this.evaluate('document.documentElement.outerHTML'); }
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* screenshot(path, opts) or screenshot({ path, ...opts }) (the Playwright form works too).
|
|
552
|
+
* scale: 'css' (default) saves one image pixel per CSS pixel, so a retina screen does not
|
|
553
|
+
* double the file and the tokens it costs to look at; 'device' keeps every device pixel.
|
|
554
|
+
* format: 'png' (default) | 'jpeg' (with quality, 0-100). Returns { path, width, height, bytes, ms }.
|
|
555
|
+
*/
|
|
556
|
+
async screenshot(path, { timeout = 10000, fullPage = false, format, quality, scale = 'css' } = {}) {
|
|
557
|
+
if (path && typeof path === 'object') return this.screenshot(path.path ?? null, path);
|
|
558
|
+
const t0 = Date.now();
|
|
559
|
+
format ??= /\.jpe?g$/i.test(path || '') ? 'jpeg' : 'png';
|
|
560
|
+
const params = { format };
|
|
561
|
+
if (format === 'jpeg' && quality !== undefined) params.quality = quality;
|
|
562
|
+
const { cssContentSize } = await this.cdp('Page.getLayoutMetrics');
|
|
563
|
+
const [iw, ih, x0, y0, ratio] = await this.evaluate('[innerWidth, innerHeight, scrollX, scrollY, devicePixelRatio]');
|
|
564
|
+
const dpr = scale === 'device' ? 1 : ratio;
|
|
565
|
+
const k = dpr > 1 ? 1 / dpr : 1;
|
|
566
|
+
let size = { width: iw, height: ih };
|
|
567
|
+
if (fullPage) {
|
|
568
|
+
size = { width: Math.ceil(cssContentSize.width), height: Math.ceil(cssContentSize.height) };
|
|
569
|
+
params.clip = { x: 0, y: 0, ...size, scale: k };
|
|
570
|
+
params.captureBeyondViewport = true;
|
|
571
|
+
} else if (k !== 1) {
|
|
572
|
+
// A clip is in document coordinates, so it starts where the page is scrolled to.
|
|
573
|
+
params.clip = { x: x0, y: y0, width: iw, height: ih, scale: k };
|
|
574
|
+
}
|
|
575
|
+
const r = await this.cdp('Page.captureScreenshot', params, { timeout });
|
|
576
|
+
if (path) await writeFile(path, Buffer.from(r.data, 'base64'));
|
|
577
|
+
const px = scale === 'device' ? {} : size;
|
|
578
|
+
return { path, ...px, bytes: r.data.length, ms: Date.now() - t0 };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
async cookies() { return (await this.cdp('Network.getCookies')).cookies; }
|
|
582
|
+
|
|
583
|
+
/** fetch() inside the page, so the site's cookies and origin apply. */
|
|
584
|
+
fetch(url, init = {}) {
|
|
585
|
+
return this.evaluate(`fetch(${JSON.stringify(url)}, ${JSON.stringify(init)}).then(async r => ({ status: r.status, ok: r.ok, headers: Object.fromEntries(r.headers), body: await r.text() }))`);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// ---------- frames ----------
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Frame inventory for the current tab, to any depth. Frames that share a process with their
|
|
592
|
+
* parent are reached through an execution context of the same debuggee; cross-origin ones
|
|
593
|
+
* (out-of-process) are separate targets the extension attaches to, and may themselves contain
|
|
594
|
+
* further frames. Offsets accumulate so every frame knows where it sits in the top-level
|
|
595
|
+
* viewport.
|
|
596
|
+
*/
|
|
597
|
+
async refreshFrames() {
|
|
598
|
+
const frames = [];
|
|
599
|
+
const seen = new Set();
|
|
600
|
+
|
|
601
|
+
/** Walk one debuggee's frame tree, then follow its cross-origin children. */
|
|
602
|
+
const walkTarget = async (targetId, rootOffset, depth) => {
|
|
603
|
+
const targetKey = targetId || 'tab';
|
|
604
|
+
const at = targetId ? { targetId } : {};
|
|
605
|
+
let tree;
|
|
606
|
+
try { tree = await this.cdp('Page.getFrameTree', {}, at); } catch { return; }
|
|
607
|
+
|
|
608
|
+
const inThisTarget = [];
|
|
609
|
+
const visit = (node, parent) => {
|
|
610
|
+
const frameId = node.frame.id;
|
|
611
|
+
if (seen.has(frameId)) return;
|
|
612
|
+
seen.add(frameId);
|
|
613
|
+
const f = {
|
|
614
|
+
frameId, url: node.frame.url, targetKey, targetId,
|
|
615
|
+
// Boxes measured in this debuggee are relative to its root frame, which sits here.
|
|
616
|
+
targetOffset: { ...rootOffset },
|
|
617
|
+
kind: !parent ? (targetId ? 'cross-origin' : 'top') : 'same-origin',
|
|
618
|
+
contextId: parent ? this.contexts.get(targetKey)?.get(frameId) : undefined,
|
|
619
|
+
parentFrameId: parent?.frameId ?? null,
|
|
620
|
+
offset: parent ? null : { ...rootOffset },
|
|
621
|
+
depth: parent ? parent.depth + 1 : depth,
|
|
622
|
+
};
|
|
623
|
+
frames.push(f);
|
|
624
|
+
inThisTarget.push(f);
|
|
625
|
+
for (const c of node.childFrames || []) visit(c, f);
|
|
626
|
+
};
|
|
627
|
+
visit(tree.frameTree, null);
|
|
628
|
+
|
|
629
|
+
// A nested frame's context id is only known from an event this process saw, and every CLI
|
|
630
|
+
// run is a new process attaching to a page that already exists. Without one, an evaluate
|
|
631
|
+
// "in that frame" ran in the debuggee's default context instead — the top document: every
|
|
632
|
+
// match was found twice, and evaluateInFrame acted on the wrong page (2026-09-30, 2026-10-16
|
|
633
|
+
// two POSTs sent from it, 2026-11-24). Ask for a context of that frame; a frame that gives
|
|
634
|
+
// none is left out rather than answered for by its parent.
|
|
635
|
+
for (const f of inThisTarget) {
|
|
636
|
+
if (f.kind !== 'same-origin' || f.contextId !== undefined) continue;
|
|
637
|
+
try {
|
|
638
|
+
const r = await this.cdp('Page.createIsolatedWorld', { frameId: f.frameId, worldName: 'parallel-browser' }, at);
|
|
639
|
+
if (r?.executionContextId === undefined) throw new Error('no context');
|
|
640
|
+
f.contextId = r.executionContextId;
|
|
641
|
+
f.isolated = true; // sees the frame's DOM, not the page's own script variables
|
|
642
|
+
} catch { f.unreachable = true; }
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Offsets and cross-origin children, frame by frame.
|
|
646
|
+
for (const f of inThisTarget) {
|
|
647
|
+
if (f.unreachable) continue;
|
|
648
|
+
const owners = await this.#iframeOwners(f);
|
|
649
|
+
for (const o of owners) {
|
|
650
|
+
if (!o.frameId) continue;
|
|
651
|
+
// A box measured in the tab debuggee is already in top-level coordinates; one measured
|
|
652
|
+
// inside a frame target is local to that target, so add where that target sits.
|
|
653
|
+
const abs = targetId ? { x: rootOffset.x + o.offset.x, y: rootOffset.y + o.offset.y } : { ...o.offset };
|
|
654
|
+
const known = frames.find((x) => x.frameId === o.frameId);
|
|
655
|
+
if (known) { known.offset ??= abs; continue; }
|
|
656
|
+
if (!/^https?:/.test(o.url || '')) continue;
|
|
657
|
+
let attached = [];
|
|
658
|
+
try { attached = (await this.call('frames.discover', { urls: [o.url] })).frames; } catch { continue; }
|
|
659
|
+
const t = attached.find((x) => x.frameId === o.frameId) || attached.find((x) => x.url === o.url);
|
|
660
|
+
if (!t || seen.has(t.frameId)) continue;
|
|
661
|
+
await walkTarget(t.targetId, abs, (f.depth ?? 0) + 1);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
await walkTarget(null, { x: 0, y: 0 }, 0);
|
|
667
|
+
for (const f of frames) f.offset ??= { x: 0, y: 0 };
|
|
668
|
+
this.frames = frames;
|
|
669
|
+
this.framesFresh = true;
|
|
670
|
+
return frames;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** <iframe>/<frame> elements inside one frame: their frame id, src and content-box origin. */
|
|
674
|
+
async #iframeOwners(frame) {
|
|
675
|
+
const at = this.#frameCall(frame);
|
|
676
|
+
const { result } = await this.cdp('Runtime.evaluate', { expression: '[...document.querySelectorAll("iframe,frame")]', returnByValue: false, ...this.#evalArgs(frame) }, at).catch(() => ({ result: {} }));
|
|
677
|
+
if (!result?.objectId) return [];
|
|
678
|
+
const props = await this.cdp('Runtime.getProperties', { objectId: result.objectId, ownProperties: true }, at);
|
|
679
|
+
const owners = [];
|
|
680
|
+
for (const p of props.result) {
|
|
681
|
+
if (!/^\d+$/.test(p.name) || !p.value?.objectId) continue;
|
|
682
|
+
try {
|
|
683
|
+
const { node } = await this.cdp('DOM.describeNode', { objectId: p.value.objectId }, at);
|
|
684
|
+
const box = await this.cdp('DOM.getBoxModel', { objectId: p.value.objectId }, at).catch(() => null);
|
|
685
|
+
const c = box?.model?.content;
|
|
686
|
+
const attrs = node.attributes || [];
|
|
687
|
+
owners.push({ frameId: node.frameId, url: attrs[attrs.indexOf('src') + 1] || null, offset: c ? { x: c[0], y: c[1] } : { x: 0, y: 0 } });
|
|
688
|
+
} catch { /* detached iframe */ }
|
|
689
|
+
}
|
|
690
|
+
return owners;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
async #framesFor() {
|
|
694
|
+
if (!this.framesFresh || !this.frames.length) await this.refreshFrames();
|
|
695
|
+
return this.frames.filter((f) => !f.unreachable);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** Which debuggee runs a command for a given frame. */
|
|
699
|
+
#frameCall(frame) {
|
|
700
|
+
return frame?.targetId ? { targetId: frame.targetId } : {};
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** Which execution context inside that debuggee. The root frame uses the default one. */
|
|
704
|
+
#evalArgs(frame) {
|
|
705
|
+
return frame?.contextId !== undefined && frame.kind === 'same-origin' ? { contextId: frame.contextId } : {};
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// ---------- element resolution ----------
|
|
709
|
+
|
|
710
|
+
/** @returns {{objectId:string, frame:object}} */
|
|
711
|
+
async #resolve(target) {
|
|
712
|
+
if (target && typeof target === 'object' && target.objectId) return { objectId: target.objectId, frame: target.frame || this.frames[0] || { kind: 'top', offset: { x: 0, y: 0 } } };
|
|
713
|
+
let t = String(target).trim();
|
|
714
|
+
|
|
715
|
+
// frame=<css> >> <selector> pins the search to one iframe
|
|
716
|
+
let pinned = null;
|
|
717
|
+
const m = t.match(/^frame=(.+?)\s*>>\s*(.+)$/);
|
|
718
|
+
if (m) { pinned = m[1].trim(); t = m[2].trim(); }
|
|
719
|
+
|
|
720
|
+
const ref = t.match(/^@(\d+)$/) || t.match(/^ref=(\d+)$/);
|
|
721
|
+
if (ref) {
|
|
722
|
+
const frames = await this.#framesFor();
|
|
723
|
+
for (const frame of frames) {
|
|
724
|
+
try {
|
|
725
|
+
const { object } = await this.cdp('DOM.resolveNode', { backendNodeId: +ref[1] }, this.#frameCall(frame));
|
|
726
|
+
if (object?.objectId) return { objectId: object.objectId, frame };
|
|
727
|
+
} catch { /* not in this frame */ }
|
|
728
|
+
}
|
|
729
|
+
throw new ElementError(`ref ${t} is stale (re-snapshot)`, 'permanent');
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// `>> nth=N` picks one deliberately out of several matches (N from 0, or -1 for the last).
|
|
733
|
+
let nth = null;
|
|
734
|
+
const nthMatch = t.match(/^(.*?)\s*>>\s*nth=(-?\d+)\s*$/);
|
|
735
|
+
if (nthMatch) { t = nthMatch[1].trim(); nth = Number(nthMatch[2]); }
|
|
736
|
+
|
|
737
|
+
const expression = selectorExpr(t, { all: true });
|
|
738
|
+
|
|
739
|
+
let frames = await this.#framesFor();
|
|
740
|
+
if (pinned) {
|
|
741
|
+
const owner = await this.#resolvePinnedFrame(pinned, frames);
|
|
742
|
+
frames = [owner];
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// Every frame is searched, not just the first one that matches: picking the first hit
|
|
746
|
+
// silently is how automation ends up operating the wrong element.
|
|
747
|
+
const candidates = [];
|
|
748
|
+
let badSelector = null;
|
|
749
|
+
for (const frame of frames) {
|
|
750
|
+
const r = await this.cdp('Runtime.evaluate', { expression, returnByValue: false, ...this.#evalArgs(frame) }, this.#frameCall(frame)).catch((e) => ({ callError: e.message }));
|
|
751
|
+
if (process.env.PC_DEBUG_RESOLVE) {
|
|
752
|
+
console.error(` resolve ${t} in ${frame.kind} ${frame.url} -> ${r?.callError ? 'ERR' : r?.exceptionDetails ? 'EXC' : r?.result?.objectId ? 'array' : 'none'}`);
|
|
753
|
+
}
|
|
754
|
+
if (!r || r.callError) continue;
|
|
755
|
+
if (r.exceptionDetails) { badSelector ??= r.exceptionDetails.text; continue; }
|
|
756
|
+
if (!r.result.objectId) continue;
|
|
757
|
+
const props = await this.cdp('Runtime.getProperties', { objectId: r.result.objectId, ownProperties: true }, this.#frameCall(frame)).catch(() => null);
|
|
758
|
+
for (const p of props?.result || []) {
|
|
759
|
+
if (!/^\d+$/.test(p.name) || !p.value?.objectId) continue;
|
|
760
|
+
candidates.push({ objectId: p.value.objectId, frame });
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (badSelector) throw new ElementError(`bad selector ${t}: ${badSelector}`, 'permanent');
|
|
764
|
+
if (!candidates.length) throw new ElementError(`no element for ${t}${pinned ? ` in frame ${pinned}` : ''}`, 'transient');
|
|
765
|
+
|
|
766
|
+
if (nth !== null) {
|
|
767
|
+
const picked = nth < 0 ? candidates[candidates.length + nth] : candidates[nth];
|
|
768
|
+
if (!picked) throw new ElementError(`${t} >> nth=${nth}: only ${candidates.length} match${candidates.length === 1 ? '' : 'es'}`, 'permanent');
|
|
769
|
+
return picked;
|
|
770
|
+
}
|
|
771
|
+
if (candidates.length === 1) return candidates[0];
|
|
772
|
+
|
|
773
|
+
// Several matches: keep the ones a user could actually act on before calling it ambiguous.
|
|
774
|
+
const actionable = [];
|
|
775
|
+
for (const c of candidates) {
|
|
776
|
+
const ok = await this.#describeCandidate(c);
|
|
777
|
+
if (ok.actionable) actionable.push({ ...c, described: ok });
|
|
778
|
+
}
|
|
779
|
+
const pool = actionable.length ? actionable : candidates;
|
|
780
|
+
if (pool.length === 1) return pool[0];
|
|
781
|
+
|
|
782
|
+
const shown = [];
|
|
783
|
+
for (const c of pool.slice(0, 5)) {
|
|
784
|
+
const d = c.described || (await this.#describeCandidate(c));
|
|
785
|
+
shown.push(` ${d.label}${c.frame.kind === 'top' ? '' : ` [in ${c.frame.kind} frame ${c.frame.url || ''}]`}`);
|
|
786
|
+
}
|
|
787
|
+
throw new ElementError(
|
|
788
|
+
`${t} matches ${pool.length} elements; refine it or add ">> nth=N"\n${shown.join('\n')}${pool.length > 5 ? `\n ... and ${pool.length - 5} more` : ''}`,
|
|
789
|
+
'permanent',
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** A short human label for one candidate, plus whether it is worth acting on. */
|
|
794
|
+
async #describeCandidate(c) {
|
|
795
|
+
const r = await this.cdp('Runtime.callFunctionOn', {
|
|
796
|
+
objectId: c.objectId, returnByValue: true, functionDeclaration: `function(){
|
|
797
|
+
const rect = this.getBoundingClientRect();
|
|
798
|
+
const st = getComputedStyle(this);
|
|
799
|
+
const visible = rect.width > 0 && rect.height > 0 && st.visibility !== 'hidden' && st.display !== 'none';
|
|
800
|
+
const text = (this.innerText || this.value || this.getAttribute('aria-label') || this.placeholder || '').replace(/\\s+/g, ' ').trim().slice(0, 40);
|
|
801
|
+
const id = this.id ? '#' + this.id : '';
|
|
802
|
+
const cls = typeof this.className === 'string' && this.className ? '.' + this.className.trim().split(/\\s+/).slice(0, 2).join('.') : '';
|
|
803
|
+
return { actionable: visible && !this.disabled, label: '<' + this.tagName.toLowerCase() + id + cls + '>' + (text ? ' "' + text + '"' : '') };
|
|
804
|
+
}`,
|
|
805
|
+
}, this.#frameCall(c.frame)).catch(() => null);
|
|
806
|
+
return r?.result?.value || { actionable: true, label: '<unknown>' };
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
async #resolvePinnedFrame(selector, frames) {
|
|
810
|
+
const r = await this.cdp('Runtime.evaluate', { expression: `document.querySelector(${JSON.stringify(selector)})`, returnByValue: false });
|
|
811
|
+
if (!r.result?.objectId) throw new ElementError(`no iframe matches ${selector}`, 'transient');
|
|
812
|
+
const { node } = await this.cdp('DOM.describeNode', { objectId: r.result.objectId });
|
|
813
|
+
const frame = frames.find((f) => f.frameId === node.frameId);
|
|
814
|
+
if (!frame) throw new ElementError(`iframe ${selector} is not reachable (cross-origin and not attached)`, 'permanent');
|
|
815
|
+
return frame;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
async #withElement(target, fnSource, args = []) {
|
|
819
|
+
const { objectId, frame } = await this.#resolve(target);
|
|
820
|
+
const r = await this.cdp('Runtime.callFunctionOn', { objectId, functionDeclaration: fnSource, arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise: true }, this.#frameCall(frame));
|
|
821
|
+
if (r.exceptionDetails) throw new Error(`element call failed: ${r.exceptionDetails.text} ${r.exceptionDetails.exception?.description || ''}`);
|
|
822
|
+
return r.result.value;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/** Scrolls into view, checks visibility and hit target, returns the click point in
|
|
826
|
+
* top-level viewport coordinates (the space Input.dispatch* expects). */
|
|
827
|
+
async #actionPoint(target, { hitCheck = true } = {}) {
|
|
828
|
+
const { objectId, frame } = await this.#resolve(target);
|
|
829
|
+
const at = this.#frameCall(frame);
|
|
830
|
+
await this.cdp('DOM.scrollIntoViewIfNeeded', { objectId }, at).catch(() => {});
|
|
831
|
+
// Visibility and hit testing must happen inside the element's own frame, in frame-local
|
|
832
|
+
// coordinates, because that is what document.elementFromPoint() understands there.
|
|
833
|
+
const r = await this.cdp('Runtime.callFunctionOn', {
|
|
834
|
+
objectId, returnByValue: true, functionDeclaration: `function(hitCheck){
|
|
835
|
+
const rects = this.getClientRects(); if (!rects.length) return { error: 'not rendered' };
|
|
836
|
+
const st = getComputedStyle(this); if (st.visibility === 'hidden' || st.display === 'none') return { error: 'hidden' };
|
|
837
|
+
const r = this.getBoundingClientRect();
|
|
838
|
+
if (r.width === 0 || r.height === 0) return { error: 'zero size' };
|
|
839
|
+
const x = Math.min(Math.max(r.left + r.width / 2, 0), innerWidth - 1), y = Math.min(Math.max(r.top + r.height / 2, 0), innerHeight - 1);
|
|
840
|
+
if (this.disabled) return { error: 'disabled', x, y };
|
|
841
|
+
if (hitCheck) {
|
|
842
|
+
// Our own overlay holds the take-control button, which does accept clicks and sits in
|
|
843
|
+
// the top layer above everything. Take it out while hit testing so it can never stand
|
|
844
|
+
// between the agent and the page. display:none is not enough on its own: the top layer
|
|
845
|
+
// is still reported by elementFromPoint, so the overlay has to leave it as well.
|
|
846
|
+
const ov = document.getElementById('__parallel_browser_overlay__');
|
|
847
|
+
const ovPrev = ov ? ov.style.display : null;
|
|
848
|
+
let reopen = false;
|
|
849
|
+
if (ov) {
|
|
850
|
+
try { if (ov.matches(':popover-open')) { ov.hidePopover(); reopen = true; } } catch (e) { /* not a popover here */ }
|
|
851
|
+
ov.style.display = 'none';
|
|
852
|
+
}
|
|
853
|
+
// elementFromPoint stops at a shadow host, so descend into shadow roots to find what
|
|
854
|
+
// the user would actually hit.
|
|
855
|
+
let top = document.elementFromPoint(x, y);
|
|
856
|
+
// The descent hit-tests again, so the overlay has to stay out until it is finished —
|
|
857
|
+
// restoring here would let ShadowRoot.elementFromPoint retarget to the overlay and
|
|
858
|
+
// report our own marker as the thing covering the element.
|
|
859
|
+
while (top && top.shadowRoot) {
|
|
860
|
+
const inner = top.shadowRoot.elementFromPoint(x, y);
|
|
861
|
+
if (!inner || inner === top) break;
|
|
862
|
+
top = inner;
|
|
863
|
+
}
|
|
864
|
+
if (ov) {
|
|
865
|
+
ov.style.display = ovPrev;
|
|
866
|
+
try { if (reopen) ov.showPopover(); } catch (e) { /* page took it away */ }
|
|
867
|
+
}
|
|
868
|
+
if (!top) return { error: 'off screen', x, y };
|
|
869
|
+
// A host of the shadow tree this element lives in counts as hitting the element.
|
|
870
|
+
let isHost = false;
|
|
871
|
+
for (let r = this.getRootNode(); r && r !== document && r.host; r = r.host.getRootNode()) {
|
|
872
|
+
if (r.host === top) { isHost = true; break; }
|
|
873
|
+
}
|
|
874
|
+
const okHit = top === this || this.contains(top) || top.contains(this) || isHost || (top.tagName === 'LABEL' && top.control === this);
|
|
875
|
+
if (!okHit) {
|
|
876
|
+
const cls = typeof top.className === 'string' && top.className.trim() ? '.' + top.className.trim().split(/\s+/).slice(0, 2).join('.') : '';
|
|
877
|
+
const said = (top.innerText || top.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim().slice(0, 40);
|
|
878
|
+
return { error: 'covered by <' + top.tagName.toLowerCase() + (top.id ? '#' + top.id : '') + cls + '>' + (said ? ' "' + said + '"' : '') + ' (a dialog, toast or overlay is on top: close it or wait for it to go, then act again)', x, y };
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return { x, y, tag: this.tagName };
|
|
882
|
+
}`, arguments: [{ value: hitCheck }],
|
|
883
|
+
}, at);
|
|
884
|
+
const v = r.result.value;
|
|
885
|
+
if (v.error) throw new ElementError(`${target}: ${v.error}`, v.error === 'disabled' ? 'permanent' : 'transient');
|
|
886
|
+
|
|
887
|
+
// What a box model means depends on which debuggee measured it, not on the frame's kind:
|
|
888
|
+
// the tab session reports top-level coordinates even for nested same-origin frames, while a
|
|
889
|
+
// frame target reports coordinates relative to that target's own root frame.
|
|
890
|
+
const off = frame.targetKey === 'tab' || !frame.targetKey ? { x: 0, y: 0 } : (frame.targetOffset || frame.offset || { x: 0, y: 0 });
|
|
891
|
+
const box = await this.cdp('DOM.getBoxModel', { objectId }, at).catch(() => null);
|
|
892
|
+
const q = box?.model?.content;
|
|
893
|
+
if (q) {
|
|
894
|
+
const cx = (q[0] + q[2] + q[4] + q[6]) / 4, cy = (q[1] + q[3] + q[5] + q[7]) / 4;
|
|
895
|
+
return { ...v, x: cx + off.x, y: cy + off.y, frame };
|
|
896
|
+
}
|
|
897
|
+
// No box model: fall back to the frame-local rect plus where the frame itself sits.
|
|
898
|
+
const fallback = frame.kind === 'top' ? { x: 0, y: 0 } : (frame.offset || { x: 0, y: 0 });
|
|
899
|
+
return { ...v, x: v.x + fallback.x, y: v.y + fallback.y, frame };
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
// ---------- actions ----------
|
|
903
|
+
|
|
904
|
+
async click(target, { button = 'left', clickCount = 1, modifiers = 0, timeout = 10000 } = {}) {
|
|
905
|
+
if (typeof target === 'number' && typeof arguments[1] === 'number') return this.clickAt(target, arguments[1]);
|
|
906
|
+
const { x, y } = await this.#retry(() => this.#actionPoint(target), timeout);
|
|
907
|
+
await this.status(`click ${short(target)}`);
|
|
908
|
+
await this.#mouse('mouseMoved', x, y, { button: 'none', modifiers });
|
|
909
|
+
await this.#mouse('mousePressed', x, y, { button, clickCount, modifiers });
|
|
910
|
+
await this.#mouse('mouseReleased', x, y, { button, clickCount, modifiers });
|
|
911
|
+
return { x, y };
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
dblclick(target, opts = {}) { return this.click(target, { ...opts, clickCount: 2 }); }
|
|
915
|
+
|
|
916
|
+
async clickAt(x, y) {
|
|
917
|
+
await this.#mouse('mouseMoved', x, y, { button: 'none' });
|
|
918
|
+
await this.#mouse('mousePressed', x, y, { button: 'left', clickCount: 1 });
|
|
919
|
+
await this.#mouse('mouseReleased', x, y, { button: 'left', clickCount: 1 });
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
async hover(target, { timeout = 10000 } = {}) {
|
|
923
|
+
const { x, y } = await this.#retry(() => this.#actionPoint(target, { hitCheck: false }), timeout);
|
|
924
|
+
await this.#mouse('mouseMoved', x, y, { button: 'none' });
|
|
925
|
+
return { x, y };
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
#mouse(type, x, y, { button = 'left', clickCount = 0, modifiers = 0 } = {}) {
|
|
929
|
+
const k = this.inputScale;
|
|
930
|
+
return this.cdp('Input.dispatchMouseEvent', { type, x: x * k, y: y * k, button, clickCount, modifiers });
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* Make the page see a width × height screen (CSS px), like Playwright's viewport. The window is
|
|
935
|
+
* left alone: the page is laid out at that size whatever the window, and screenshots and
|
|
936
|
+
* recordings capture all of it (2026-10-29, Edge 155: a 669×407 tab area recorded 1792×848
|
|
937
|
+
* whole, 2× on retina) — while the tab is behind: the window's front tab is recorded at the
|
|
938
|
+
* window's real size, cropped, which is why the agent window keeps a blank tab in front.
|
|
939
|
+
* Applies to every tab of this session, including ones opened later.
|
|
940
|
+
* `fitWindow: true` also grows the agent window to hold it; `shrink: true` draws it scaled into
|
|
941
|
+
* the tab area and scales input to match. Neither is needed for screenshots or recordings.
|
|
942
|
+
* Returns { width, height, dpr, scale, tabArea: [w, h] }.
|
|
943
|
+
*/
|
|
944
|
+
async setViewport(width, height, { dpr = 1, fitWindow = false, shrink = false } = {}) {
|
|
945
|
+
if (width && typeof width === 'object') return this.setViewport(width.width, width.height, width);
|
|
946
|
+
width = Math.round(Number(width)); height = Math.round(Number(height));
|
|
947
|
+
if (!(width > 0 && height > 0)) throw new Error(`setViewport needs a width and a height, got ${width}×${height}`);
|
|
948
|
+
let area = await this.#tabArea();
|
|
949
|
+
if (fitWindow && (area.width < width || area.height < height)) area = await this.fitWindow(width, height);
|
|
950
|
+
const scale = shrink ? Math.min(area.width / width, area.height / height, 1) : 1;
|
|
951
|
+
this.viewport = { width, height, dpr, scale };
|
|
952
|
+
for (const tabId of this.enabledTabs) await this.#applyViewport(tabId);
|
|
953
|
+
return { ...this.viewport, tabArea: [area.width, area.height] };
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** Back to the real tab area: no emulated screen size, input unscaled. */
|
|
957
|
+
async clearViewport() {
|
|
958
|
+
this.viewport = null;
|
|
959
|
+
this.inputScale = 1;
|
|
960
|
+
for (const tabId of this.enabledTabs) await this.cdp('Emulation.clearDeviceMetricsOverride', {}, { tabId }).catch(() => {});
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* Grow (never shrink) the window this session draws in until its tab area is at least
|
|
965
|
+
* width × height CSS px, as far as the screen allows. It is resized in place: no focus, no
|
|
966
|
+
* raising. Returns the tab area it ended with. Sessions placed in the user's own window
|
|
967
|
+
* (placement 'group') leave that window alone.
|
|
968
|
+
*/
|
|
969
|
+
async fitWindow(width, height) {
|
|
970
|
+
const area = await this.#tabArea();
|
|
971
|
+
if (this.placement === 'group' || (area.width >= width && area.height >= height)) return area;
|
|
972
|
+
const w = await this.call('window.get');
|
|
973
|
+
if (w.state !== 'normal') return area; // minimized / maximized / fullscreen: leave it
|
|
974
|
+
const scr = await this.evaluate('({ l: screen.availLeft ?? 0, t: screen.availTop ?? 0, w: screen.availWidth, h: screen.availHeight })');
|
|
975
|
+
// Stop short of the whole screen: a window exactly the screen's size becomes 'maximized'
|
|
976
|
+
// (2026-10-29, Edge on macOS), and a maximized window is not resized again.
|
|
977
|
+
const nw = Math.min(Math.max(w.width, w.width - area.width + width), scr.w - 16);
|
|
978
|
+
const nh = Math.min(Math.max(w.height, w.height - area.height + height), scr.h - 16);
|
|
979
|
+
if (nw === w.width && nh === w.height) return area;
|
|
980
|
+
const left = Math.max(scr.l, Math.min(w.left, scr.l + scr.w - nw));
|
|
981
|
+
const top = Math.max(scr.t, Math.min(w.top, scr.t + scr.h - nh));
|
|
982
|
+
await this.call('window.setBounds', { left, top, width: nw, height: nh });
|
|
983
|
+
// A window behind others is resized at once, but a tab that is not being painted keeps
|
|
984
|
+
// reporting its old size until it is (2026-10-29: innerWidth stayed 998 for 3 s after the
|
|
985
|
+
// window grew; a new tab, a screenshot or a recording sees the new size). So wait a little,
|
|
986
|
+
// then trust the window: the tab area is the window less the browser's own bars.
|
|
987
|
+
for (let i = 0; i < 10; i++) {
|
|
988
|
+
await sleep(50);
|
|
989
|
+
const now = await this.#tabArea();
|
|
990
|
+
if (now.width !== area.width || now.height !== area.height) return now;
|
|
991
|
+
}
|
|
992
|
+
return { width: nw - (w.width - area.width), height: nh - (w.height - area.height), estimated: true };
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/** The real tab area in CSS px, measured without any emulated screen size. */
|
|
996
|
+
async #tabArea() {
|
|
997
|
+
if (this.viewport) await this.cdp('Emulation.clearDeviceMetricsOverride').catch(() => {});
|
|
998
|
+
const [width, height] = await this.evaluate('[innerWidth, innerHeight]');
|
|
999
|
+
if (this.viewport) await this.#applyViewport(this.tabId);
|
|
1000
|
+
return { width, height };
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
async #applyViewport(tabId) {
|
|
1004
|
+
const v = this.viewport;
|
|
1005
|
+
const params = { width: v.width, height: v.height, deviceScaleFactor: v.dpr, mobile: false };
|
|
1006
|
+
if (v.scale < 1) params.scale = v.scale;
|
|
1007
|
+
await this.cdp('Emulation.setDeviceMetricsOverride', params, { tabId });
|
|
1008
|
+
this.inputScale = v.scale;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/** 화면 크기 흉내에 scale 을 걸었을 때 그 값을 준다. 클릭 · 이동 · 휠 · 끌기 좌표가 CSS 좌표 그대로 맞는다. */
|
|
1012
|
+
setInputScale(scale = 1) {
|
|
1013
|
+
this.inputScale = Number(scale) > 0 ? Number(scale) : 1;
|
|
1014
|
+
return { inputScale: this.inputScale };
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
async #focusAndSelect(target) {
|
|
1018
|
+
const { objectId, frame } = await this.#resolve(target);
|
|
1019
|
+
const at = this.#frameCall(frame);
|
|
1020
|
+
// DOM.focus goes through the browser rather than page script, so it also focuses the chain
|
|
1021
|
+
// of frames the element sits in — which element.focus() cannot do from inside a subframe.
|
|
1022
|
+
await this.cdp('DOM.focus', { objectId }, at).catch(() => {});
|
|
1023
|
+
const r = await this.cdp('Runtime.callFunctionOn', {
|
|
1024
|
+
objectId, returnByValue: true, functionDeclaration: `function(){
|
|
1025
|
+
// document.activeElement reports the shadow host, so descend to the real focused node.
|
|
1026
|
+
const deepActive = () => { let a = document.activeElement; while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement; return a; };
|
|
1027
|
+
if (deepActive() !== this) this.focus();
|
|
1028
|
+
if (typeof this.select === 'function' && !/^(checkbox|radio|file|button|submit|range|color)$/i.test(this.type || '')) { try { this.select(); } catch (e) {} }
|
|
1029
|
+
else if (this.isContentEditable) { const s = getSelection(); s.selectAllChildren(this); }
|
|
1030
|
+
const a = deepActive();
|
|
1031
|
+
return { tag: this.tagName, type: this.type || '', editable: this.isContentEditable, focused: a === this, active: a ? a.tagName + (a.id ? '#' + a.id : '') : 'none', docFocused: document.hasFocus() };
|
|
1032
|
+
}`,
|
|
1033
|
+
}, at);
|
|
1034
|
+
if (r.exceptionDetails) throw new Error(`focus failed: ${r.exceptionDetails.text}`);
|
|
1035
|
+
return { ...r.result.value, frame };
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/** Replace the element's value with text, firing real input events (works with React/Vue). */
|
|
1039
|
+
async fill(target, text, { timeout = 10000 } = {}) {
|
|
1040
|
+
const point = await this.#retry(() => this.#actionPoint(target, { hitCheck: false }), timeout);
|
|
1041
|
+
await this.status(`fill ${short(target)}`);
|
|
1042
|
+
let info = await this.#focusAndSelect(target);
|
|
1043
|
+
if (!info.focused) {
|
|
1044
|
+
// Inside a nested or out-of-process frame, focus() alone does not always take: the whole
|
|
1045
|
+
// chain of frames has to be focused. A real click does that the way a user would.
|
|
1046
|
+
await this.#mouse('mouseMoved', point.x, point.y, { button: 'none' });
|
|
1047
|
+
await this.#mouse('mousePressed', point.x, point.y, { button: 'left', clickCount: 1 });
|
|
1048
|
+
await this.#mouse('mouseReleased', point.x, point.y, { button: 'left', clickCount: 1 });
|
|
1049
|
+
info = await this.#focusAndSelect(target);
|
|
1050
|
+
}
|
|
1051
|
+
if (!info.focused) throw new ElementError(`${target}: could not focus (frame ${info.frame?.kind} ${info.frame?.url || ''}, active element ${info.active}, document focused ${info.docFocused})`, 'permanent');
|
|
1052
|
+
const nonText = /^(date|datetime-local|time|month|week|number|range|color)$/i.test(info.type) || info.tag === 'SELECT';
|
|
1053
|
+
if (!nonText) {
|
|
1054
|
+
await this.cdp('Input.insertText', { text: String(text) });
|
|
1055
|
+
const value = await this.#withElement(target, 'function(){ return this.isContentEditable ? this.textContent : this.value }');
|
|
1056
|
+
if (value === String(text)) return;
|
|
1057
|
+
}
|
|
1058
|
+
// fallback: native setter + synthetic events (also the path for date/number inputs)
|
|
1059
|
+
await this.#withElement(target, `function(v){
|
|
1060
|
+
const proto = this.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : this.tagName === 'SELECT' ? HTMLSelectElement.prototype : HTMLInputElement.prototype;
|
|
1061
|
+
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
|
|
1062
|
+
if (this.isContentEditable) this.textContent = v; else if (setter) setter.call(this, v); else this.value = v;
|
|
1063
|
+
this.dispatchEvent(new Event('input', { bubbles: true })); this.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1064
|
+
}`, [String(text)]);
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/** Type into whatever is focused (call click/fill first). */
|
|
1068
|
+
async type(text, { delay = 0 } = {}) {
|
|
1069
|
+
if (!delay) return this.cdp('Input.insertText', { text: String(text) });
|
|
1070
|
+
for (const ch of String(text)) { await this.cdp('Input.insertText', { text: ch }); await sleep(delay); }
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/** press('Enter') on whatever is focused, or press('#search', 'Enter') to focus it first. */
|
|
1074
|
+
async press(comboOrTarget, maybeCombo) {
|
|
1075
|
+
if (maybeCombo !== undefined) { await this.focus(comboOrTarget); return this.keyboard.press(maybeCombo); }
|
|
1076
|
+
return this.keyboard.press(comboOrTarget);
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
/** Move focus to an element without clicking it. */
|
|
1080
|
+
async focus(target, { timeout = 10000 } = {}) {
|
|
1081
|
+
const info = await this.#retry(() => this.#focusAndSelect(target), timeout);
|
|
1082
|
+
if (!info.focused) throw new ElementError(`${target}: could not focus (active element ${info.active})`, 'permanent');
|
|
1083
|
+
return info;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/** Low-level keyboard: hold modifiers, send raw keys, insert or paste text. */
|
|
1087
|
+
get keyboard() {
|
|
1088
|
+
const dispatch = (params) => this.cdp('Input.dispatchKeyEvent', params);
|
|
1089
|
+
const self = this;
|
|
1090
|
+
return {
|
|
1091
|
+
async down(combo) {
|
|
1092
|
+
const k = parseKey(combo);
|
|
1093
|
+
await dispatch({ type: k.text ? 'keyDown' : 'rawKeyDown', key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode, modifiers: k.modifiers, text: k.text, unmodifiedText: k.text, commands: k.commands });
|
|
1094
|
+
},
|
|
1095
|
+
async up(combo) {
|
|
1096
|
+
const k = parseKey(combo);
|
|
1097
|
+
await dispatch({ type: 'keyUp', key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode, modifiers: k.modifiers });
|
|
1098
|
+
},
|
|
1099
|
+
async press(combo) { await this.down(combo); await this.up(combo); },
|
|
1100
|
+
insertText(text) { return self.cdp('Input.insertText', { text: String(text) }); },
|
|
1101
|
+
/** A real paste event carrying `text`, for editors that read the clipboard rather than keys. */
|
|
1102
|
+
async paste(text) {
|
|
1103
|
+
const r = await self.cdp('Runtime.evaluate', {
|
|
1104
|
+
returnByValue: true, awaitPromise: true,
|
|
1105
|
+
expression: `(() => {
|
|
1106
|
+
const el = (() => { let a = document.activeElement; while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement; return a; })();
|
|
1107
|
+
if (!el) return 'no focused element';
|
|
1108
|
+
const dt = new DataTransfer();
|
|
1109
|
+
dt.setData('text/plain', ${JSON.stringify(String(text))});
|
|
1110
|
+
const ev = new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: dt });
|
|
1111
|
+
const handled = !el.dispatchEvent(ev);
|
|
1112
|
+
if (!handled) {
|
|
1113
|
+
if (typeof el.setRangeText === 'function') { el.setRangeText(${JSON.stringify(String(text))}, el.selectionStart ?? el.value.length, el.selectionEnd ?? el.value.length, 'end'); }
|
|
1114
|
+
else if (el.isContentEditable) { document.execCommand('insertText', false, ${JSON.stringify(String(text))}); }
|
|
1115
|
+
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
1116
|
+
}
|
|
1117
|
+
return 'ok';
|
|
1118
|
+
})()`,
|
|
1119
|
+
});
|
|
1120
|
+
if (r.result.value !== 'ok') throw new Error(`paste failed: ${r.result.value}`);
|
|
1121
|
+
},
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/** Low-level mouse, in top-level viewport coordinates. The pointer keeps its position
|
|
1126
|
+
* between calls, so move() then down() acts where you moved to. */
|
|
1127
|
+
get mouse() {
|
|
1128
|
+
if (this.mouseApi) return this.mouseApi;
|
|
1129
|
+
const self = this;
|
|
1130
|
+
const last = (this.mouseAt ??= { x: 0, y: 0 });
|
|
1131
|
+
this.mouseApi = {
|
|
1132
|
+
async move(x, y, { steps = 1, button = 'none' } = {}) {
|
|
1133
|
+
const from = { x: last.x, y: last.y };
|
|
1134
|
+
for (let i = 1; i <= steps; i++) {
|
|
1135
|
+
await self.#mouse('mouseMoved', from.x + ((x - from.x) * i) / steps, from.y + ((y - from.y) * i) / steps, { button });
|
|
1136
|
+
}
|
|
1137
|
+
last.x = x; last.y = y;
|
|
1138
|
+
},
|
|
1139
|
+
async down({ button = 'left', clickCount = 1 } = {}) { await self.#mouse('mousePressed', last.x, last.y, { button, clickCount }); },
|
|
1140
|
+
async up({ button = 'left', clickCount = 1 } = {}) { await self.#mouse('mouseReleased', last.x, last.y, { button, clickCount }); },
|
|
1141
|
+
async click(x, y, { button = 'left', clickCount = 1 } = {}) {
|
|
1142
|
+
await this.move(x, y);
|
|
1143
|
+
await this.down({ button, clickCount });
|
|
1144
|
+
await this.up({ button, clickCount });
|
|
1145
|
+
},
|
|
1146
|
+
wheel(deltaX, deltaY) { return self.cdp('Input.dispatchMouseEvent', { type: 'mouseWheel', x: last.x * self.inputScale, y: last.y * self.inputScale, deltaX, deltaY }); },
|
|
1147
|
+
position() { return { ...last }; },
|
|
1148
|
+
};
|
|
1149
|
+
return this.mouseApi;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/** select('#color', 'b') or select('#color', ['a','b']) — matches option value, then label. */
|
|
1153
|
+
async select(target, values) {
|
|
1154
|
+
const wanted = [].concat(values).map(String);
|
|
1155
|
+
const picked = await this.#withElement(target, `function(wanted){
|
|
1156
|
+
if (this.tagName !== 'SELECT') throw new Error('not a <select>');
|
|
1157
|
+
const picked = [];
|
|
1158
|
+
for (const o of this.options) { const hit = wanted.includes(o.value) || wanted.includes(o.label) || wanted.includes(o.text.trim()); o.selected = hit; if (hit) picked.push(o.value); if (hit && !this.multiple) break; }
|
|
1159
|
+
this.dispatchEvent(new Event('input', { bubbles: true })); this.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1160
|
+
return picked;
|
|
1161
|
+
}`, [wanted]);
|
|
1162
|
+
if (!picked.length) throw new ElementError(`${target}: no option matched ${wanted.join(', ')}`, 'permanent');
|
|
1163
|
+
return picked;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
async check(target) { return this.#setChecked(target, true); }
|
|
1167
|
+
async uncheck(target) { return this.#setChecked(target, false); }
|
|
1168
|
+
|
|
1169
|
+
async #setChecked(target, state) {
|
|
1170
|
+
// A native input says `checked`; a custom one (button[role=checkbox], Radix and the like) only
|
|
1171
|
+
// says aria-checked, and reading `checked` there is always false: the click worked and this
|
|
1172
|
+
// reported that it had not (2026-11-24, three of six runs; clicking again unchecked the box).
|
|
1173
|
+
const read = `function(){
|
|
1174
|
+
if (this.matches('input[type=checkbox],input[type=radio]')) return this.checked;
|
|
1175
|
+
const a = this.getAttribute('aria-checked');
|
|
1176
|
+
return a !== null ? a === 'true' : !!this.checked;
|
|
1177
|
+
}`;
|
|
1178
|
+
if ((await this.#withElement(target, read)) === state) return;
|
|
1179
|
+
await this.click(target);
|
|
1180
|
+
// Frameworks update the attribute on their next render, not inside the click.
|
|
1181
|
+
for (const deadline = Date.now() + 1000; ;) {
|
|
1182
|
+
if ((await this.#withElement(target, read)) === state) return;
|
|
1183
|
+
if (Date.now() > deadline) break;
|
|
1184
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1185
|
+
}
|
|
1186
|
+
throw new ElementError(`${target}: click did not change checked state`, 'permanent');
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
async scroll(targetOrDelta, { x = 0, y = 400 } = {}) {
|
|
1190
|
+
if (targetOrDelta && typeof targetOrDelta === 'object' && !targetOrDelta.objectId) ({ x = 0, y = 400 } = targetOrDelta);
|
|
1191
|
+
else if (targetOrDelta) {
|
|
1192
|
+
const { objectId, frame } = await this.#resolve(targetOrDelta);
|
|
1193
|
+
await this.cdp('DOM.scrollIntoViewIfNeeded', { objectId }, this.#frameCall(frame));
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
await this.cdp('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 10, y: 10, deltaX: x, deltaY: y });
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/** setInputFiles('#file', ['/abs/path.pdf']) — for a visible <input type=file>. */
|
|
1200
|
+
async setInputFiles(target, files) {
|
|
1201
|
+
const { objectId, frame } = await this.#resolve(target);
|
|
1202
|
+
await this.cdp('DOM.setFileInputFiles', { objectId, files: [].concat(files) }, this.#frameCall(frame));
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
// ---------- drag and drop ----------
|
|
1206
|
+
|
|
1207
|
+
/**
|
|
1208
|
+
* Real mouse-driven drag. Chrome's own drag controller runs, so HTML5 dataTransfer,
|
|
1209
|
+
* sortable lists and pointer-event libraries all see what they expect.
|
|
1210
|
+
* `intercept: true` additionally captures the drag payload and replays it as explicit
|
|
1211
|
+
* drag events, which is what you want when the drop target inspects dataTransfer.
|
|
1212
|
+
*/
|
|
1213
|
+
async dragAndDrop(source, target, { steps = 10, hold = 80, settle = 120, intercept = false, timeout = 10000, sourceOffset, targetOffset } = {}) {
|
|
1214
|
+
const a = await this.#retry(() => this.#actionPoint(source, { hitCheck: false }), timeout);
|
|
1215
|
+
const b = await this.#retry(() => this.#actionPoint(target, { hitCheck: false }), timeout);
|
|
1216
|
+
// Sortable lists decide "before or after" from where inside the target you release, so
|
|
1217
|
+
// aiming at the exact centre is often ambiguous; offsets let the caller pick a side.
|
|
1218
|
+
if (sourceOffset) { a.x += sourceOffset.dx || 0; a.y += sourceOffset.dy || 0; }
|
|
1219
|
+
if (targetOffset) { b.x += targetOffset.dx || 0; b.y += targetOffset.dy || 0; }
|
|
1220
|
+
await this.status(`drag ${short(source)} → ${short(target)}`);
|
|
1221
|
+
let payload = null;
|
|
1222
|
+
const onIntercept = (p) => { payload = p.data; };
|
|
1223
|
+
if (intercept) { this.on('Input.dragIntercepted', onIntercept); await this.cdp('Input.setInterceptDrags', { enabled: true }); }
|
|
1224
|
+
try {
|
|
1225
|
+
await this.#mouse('mouseMoved', a.x, a.y, { button: 'none' });
|
|
1226
|
+
await this.#mouse('mousePressed', a.x, a.y, { button: 'left', clickCount: 1 });
|
|
1227
|
+
await sleep(hold);
|
|
1228
|
+
// Several intermediate moves: sortable libraries need movement to start a drag and to
|
|
1229
|
+
// compute the insertion point, and a single jump is often ignored entirely.
|
|
1230
|
+
for (let i = 1; i <= steps; i++) {
|
|
1231
|
+
const x = a.x + ((b.x - a.x) * i) / steps;
|
|
1232
|
+
const y = a.y + ((b.y - a.y) * i) / steps;
|
|
1233
|
+
await this.#mouse('mouseMoved', x, y, { button: 'left' });
|
|
1234
|
+
if (intercept && payload) break;
|
|
1235
|
+
await sleep(Math.max(8, Math.round(settle / steps)));
|
|
1236
|
+
}
|
|
1237
|
+
if (intercept) {
|
|
1238
|
+
if (!payload) throw new Error('drag was not intercepted (the source may not be draggable)');
|
|
1239
|
+
for (const type of ['dragEnter', 'dragOver', 'drop']) {
|
|
1240
|
+
await this.cdp('Input.dispatchDragEvent', { type, x: b.x * this.inputScale, y: b.y * this.inputScale, data: payload });
|
|
1241
|
+
await sleep(60);
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
await sleep(settle);
|
|
1245
|
+
await this.#mouse('mouseReleased', b.x, b.y, { button: 'left', clickCount: 1 });
|
|
1246
|
+
await sleep(settle);
|
|
1247
|
+
} finally {
|
|
1248
|
+
if (intercept) { this.off('Input.dragIntercepted', onIntercept); await this.cdp('Input.setInterceptDrags', { enabled: false }).catch(() => {}); }
|
|
1249
|
+
}
|
|
1250
|
+
return { from: { x: a.x, y: a.y }, to: { x: b.x, y: b.y }, payload: payload && { items: payload.items?.map((i) => i.mimeType), files: payload.files } };
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/** Drop files from disk onto an element, the way a user dragging from Finder would. */
|
|
1254
|
+
async dropFiles(target, files, { timeout = 10000 } = {}) {
|
|
1255
|
+
const b = await this.#retry(() => this.#actionPoint(target, { hitCheck: false }), timeout);
|
|
1256
|
+
const data = { items: [], files: [].concat(files), dragOperationsMask: 1 };
|
|
1257
|
+
for (const type of ['dragEnter', 'dragOver', 'drop']) {
|
|
1258
|
+
await this.cdp('Input.dispatchDragEvent', { type, x: b.x * this.inputScale, y: b.y * this.inputScale, data });
|
|
1259
|
+
await sleep(60);
|
|
1260
|
+
}
|
|
1261
|
+
return { at: { x: b.x, y: b.y }, files: data.files };
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
/** Last-resort fallback: synthesize HTML5 drag events in the page (no real mouse involved). */
|
|
1265
|
+
async dragAndDropSynthetic(source, target, { types = { 'text/plain': '' } } = {}) {
|
|
1266
|
+
const src = await this.#resolve(source);
|
|
1267
|
+
const dst = await this.#resolve(target);
|
|
1268
|
+
if (src.frame !== dst.frame) throw new Error('synthetic drag needs both elements in the same frame');
|
|
1269
|
+
const r = await this.cdp('Runtime.callFunctionOn', {
|
|
1270
|
+
objectId: src.objectId, returnByValue: true, awaitPromise: true,
|
|
1271
|
+
functionDeclaration: `function(dstSelectorHolder, types){
|
|
1272
|
+
const dt = new DataTransfer();
|
|
1273
|
+
for (const [k, v] of Object.entries(types)) dt.setData(k, v);
|
|
1274
|
+
const dst = dstSelectorHolder;
|
|
1275
|
+
this.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
1276
|
+
dst.dispatchEvent(new DragEvent('dragenter', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
1277
|
+
dst.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
1278
|
+
dst.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
1279
|
+
this.dispatchEvent(new DragEvent('dragend', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
1280
|
+
return true;
|
|
1281
|
+
}`,
|
|
1282
|
+
arguments: [{ objectId: dst.objectId }, { value: types }],
|
|
1283
|
+
}, this.#frameCall(src.frame));
|
|
1284
|
+
if (r.exceptionDetails) throw new Error(`synthetic drag failed: ${r.exceptionDetails.text}`);
|
|
1285
|
+
return true;
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
// ---------- waits ----------
|
|
1289
|
+
|
|
1290
|
+
async #retry(fn, timeout, interval = 100) {
|
|
1291
|
+
const deadline = Date.now() + timeout;
|
|
1292
|
+
let last;
|
|
1293
|
+
for (;;) {
|
|
1294
|
+
try { return await fn(); } catch (e) {
|
|
1295
|
+
last = e;
|
|
1296
|
+
if (e instanceof ElementError && e.kind === 'permanent') throw e;
|
|
1297
|
+
if (Date.now() > deadline) throw e;
|
|
1298
|
+
await sleep(interval);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
/** waitFor('#late') | waitFor('text=Done', { state: 'hidden' }) — states: visible (default), attached, hidden, detached */
|
|
1304
|
+
async waitFor(target, { state = 'visible', timeout = 15000 } = {}) {
|
|
1305
|
+
const deadline = Date.now() + timeout;
|
|
1306
|
+
for (;;) {
|
|
1307
|
+
let present = false, visible = false;
|
|
1308
|
+
try {
|
|
1309
|
+
const v = await this.#withElement(target, `function(){ const r = this.getBoundingClientRect(); const st = getComputedStyle(this); return { visible: r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none' } }`);
|
|
1310
|
+
present = true; visible = v.visible;
|
|
1311
|
+
} catch (e) { if (!(e instanceof ElementError)) throw e; }
|
|
1312
|
+
if (state === 'attached' && present) return true;
|
|
1313
|
+
if (state === 'visible' && visible) return true;
|
|
1314
|
+
if (state === 'hidden' && (!present || !visible)) return true;
|
|
1315
|
+
if (state === 'detached' && !present) return true;
|
|
1316
|
+
if (Date.now() > deadline) throw new ElementError(`waitFor(${target}, ${state}) timed out after ${timeout}ms`, 'transient');
|
|
1317
|
+
await sleep(100);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
async waitForFunction(expression, { timeout = 15000, interval = 100 } = {}) {
|
|
1322
|
+
const deadline = Date.now() + timeout;
|
|
1323
|
+
for (;;) {
|
|
1324
|
+
const v = await this.evaluate(expression);
|
|
1325
|
+
if (v) return v;
|
|
1326
|
+
if (Date.now() > deadline) throw new Error(`waitForFunction timed out after ${timeout}ms`);
|
|
1327
|
+
await sleep(interval);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
async waitForURL(pattern, { timeout = 15000 } = {}) {
|
|
1332
|
+
const test = pattern instanceof RegExp ? (u) => pattern.test(u) : (u) => u.includes(pattern);
|
|
1333
|
+
const deadline = Date.now() + timeout;
|
|
1334
|
+
for (;;) {
|
|
1335
|
+
const u = await this.url();
|
|
1336
|
+
if (test(u)) return u;
|
|
1337
|
+
if (Date.now() > deadline) throw new Error(`waitForURL(${pattern}) timed out; current ${u}`);
|
|
1338
|
+
await sleep(100);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
async waitForLoad({ timeout = 30000 } = {}) {
|
|
1343
|
+
return this.waitForFunction('document.readyState === "complete"', { timeout });
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
async waitForNetworkIdle({ idle = 500, timeout = 30000 } = {}) {
|
|
1347
|
+
const deadline = Date.now() + timeout;
|
|
1348
|
+
let quietSince = null;
|
|
1349
|
+
for (;;) {
|
|
1350
|
+
const n = this.#inflightCount(this.tabId);
|
|
1351
|
+
if (n === 0) { quietSince ??= Date.now(); if (Date.now() - quietSince >= idle) return; } else quietSince = null;
|
|
1352
|
+
if (Date.now() > deadline) throw new Error(`waitForNetworkIdle timed out (${n} requests in flight)`);
|
|
1353
|
+
await sleep(50);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
async waitForDialog({ timeout = 15000 } = {}) {
|
|
1358
|
+
return withTimeout(new Promise((r) => this.once('dialog', r)), timeout, 'no dialog appeared');
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// ---------- recording ----------
|
|
1362
|
+
|
|
1363
|
+
/**
|
|
1364
|
+
* Start filming this tab. `dir` is a working folder (it holds the video while it is being
|
|
1365
|
+
* written, and is removed by stopRecording). The video is encoded as it is filmed, so nothing
|
|
1366
|
+
* piles up on disk however long it runs. Frames are at most `width` × `height` (default
|
|
1367
|
+
* 1920×1080; the page's own size when that is smaller — `setViewport(1920, 1080)` first for a
|
|
1368
|
+
* full-size video, or a phone size for a mobile one), at most `fps` a second (default 30), and
|
|
1369
|
+
* only while the page changes. The daemon owns the recording, so a later invocation can stop it.
|
|
1370
|
+
*/
|
|
1371
|
+
async startRecording(dir, { width, height, fps, crf } = {}) {
|
|
1372
|
+
if (this.relay.isDaemon) return this.call('record.start', { tabId: this.tabId, dir, width, height, fps, crf });
|
|
1373
|
+
this.recorder = new Recorder(this, { dir, width, height, fps, crf });
|
|
1374
|
+
await this.recorder.start();
|
|
1375
|
+
return { started: true };
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
/**
|
|
1379
|
+
* Stop filming and write the video to `outMp4` (absolute path). Returns { frames, received,
|
|
1380
|
+
* dropped, seconds, fps, width, height, t0, tEnd, pauses, visibility, events, mp4, bytes }: `t0` and `tEnd`
|
|
1381
|
+
* are when second 0 and the end of the video were (epoch seconds), `events` the address changes
|
|
1382
|
+
* and frame-size changes on the way. Quick, whatever the length. On a very slow disk it returns
|
|
1383
|
+
* after `wait` ms with `encoding: true`; `waitForRecording(outMp4)` then waits for the file.
|
|
1384
|
+
*/
|
|
1385
|
+
async stopRecording(outMp4, { wait = 100000 } = {}) {
|
|
1386
|
+
if (this.relay.isDaemon) {
|
|
1387
|
+
const r = await this.call('record.stop', { tabId: this.tabId, out: outMp4, wait }, { timeout: wait + 20000 });
|
|
1388
|
+
if (r?.encoding) console.error(`note: ${outMp4} is still being written. \`await s.waitForRecording('${outMp4}')\` waits for it.`);
|
|
1389
|
+
return r;
|
|
1390
|
+
}
|
|
1391
|
+
const r = this.recorder;
|
|
1392
|
+
this.recorder = null;
|
|
1393
|
+
return r ? r.stop(outMp4) : null;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
/**
|
|
1397
|
+
* Keep at most `fps` frames a second from now on (1–60). A page with a spinner sends frames all
|
|
1398
|
+
* the time and costs CPU for each one kept: drop to 1–5 while only waiting, back to 30 to show something.
|
|
1399
|
+
*/
|
|
1400
|
+
setRecordingFps(fps) {
|
|
1401
|
+
if (this.relay.isDaemon) return this.call('record.fps', { tabId: this.tabId, fps });
|
|
1402
|
+
if (!this.recorder) throw new Error('not recording this tab');
|
|
1403
|
+
return this.recorder.setFps(fps);
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
/** Stop filming until resumeRecording(). The time in between is left out of the video; nothing runs meanwhile. */
|
|
1407
|
+
pauseRecording() {
|
|
1408
|
+
if (this.relay.isDaemon) return this.call('record.pause', { tabId: this.tabId });
|
|
1409
|
+
if (!this.recorder) throw new Error('not recording this tab');
|
|
1410
|
+
return this.recorder.pause();
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
/** Film again after pauseRecording(). */
|
|
1414
|
+
resumeRecording() {
|
|
1415
|
+
if (this.relay.isDaemon) return this.call('record.resume', { tabId: this.tabId });
|
|
1416
|
+
if (!this.recorder) throw new Error('not recording this tab');
|
|
1417
|
+
return this.recorder.unpause();
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
/** Save what the recording shows right now (its latest frame) as a JPEG at `path`. Returns { path, width, height }. */
|
|
1421
|
+
recordingFrame(path) {
|
|
1422
|
+
if (this.relay.isDaemon) return this.call('record.frame', { tabId: this.tabId, out: path });
|
|
1423
|
+
if (!this.recorder) throw new Error('not recording this tab');
|
|
1424
|
+
return this.recorder.frameTo(path);
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
/** Whether the video of `stopRecording(outMp4)` is written: the same result, `encoding: true` while it is not. */
|
|
1428
|
+
recordingStatus(outMp4) { return this.call('record.status', { out: outMp4 }); }
|
|
1429
|
+
|
|
1430
|
+
/** Wait until that video is finished, up to `timeout` ms (default 30 minutes). Throws if the encoding failed. */
|
|
1431
|
+
async waitForRecording(outMp4, { timeout = 30 * 60 * 1000 } = {}) {
|
|
1432
|
+
const deadline = Date.now() + timeout;
|
|
1433
|
+
for (;;) {
|
|
1434
|
+
const left = deadline - Date.now();
|
|
1435
|
+
const r = await this.call('record.status', { out: outMp4, wait: Math.max(0, Math.min(left, 25000)) }, { timeout: 45000 });
|
|
1436
|
+
if (r.error) throw new Error(`could not write ${outMp4}: ${r.error}`);
|
|
1437
|
+
if (!r.encoding) return r;
|
|
1438
|
+
if (left <= 0) throw new Error(`${outMp4} is still being written after ${timeout} ms`);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/** Minimizing is free; un-minimizing takes the user's focus, so it needs `allowFocus`. */
|
|
1443
|
+
async setWindowState(state, { allowFocus = false } = {}) {
|
|
1444
|
+
return this.call('window.setState', { state, allowFocus });
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
// ---------- helpers ----------
|
|
1449
|
+
|
|
1450
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1451
|
+
const short = (t) => String(t).slice(0, 40);
|
|
1452
|
+
const hostOf = (url) => { try { return new URL(url).host || url; } catch { return url; } };
|
|
1453
|
+
function withTimeout(promise, ms, message) {
|
|
1454
|
+
let timer;
|
|
1455
|
+
return Promise.race([promise, new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(message)), ms); })]).finally(() => clearTimeout(timer));
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
/**
|
|
1459
|
+
* Walks the DOM including open shadow roots. Everything the selector helpers see goes through
|
|
1460
|
+
* this, so a control inside a web component is found the same way as one in the light DOM.
|
|
1461
|
+
* Closed shadow roots are invisible to page JavaScript; reach those through a snapshot ref.
|
|
1462
|
+
*/
|
|
1463
|
+
const DEEP_PRELUDE = `
|
|
1464
|
+
// Our own status overlay lives in the page and shows the selector being acted on, so it
|
|
1465
|
+
// would otherwise match the very text we are searching for. It is never a target.
|
|
1466
|
+
const __ours = (el) => !!(el && el.closest && el.closest('[data-parallel-browser]'));
|
|
1467
|
+
const __all = (root) => {
|
|
1468
|
+
const out = [];
|
|
1469
|
+
const visit = (node) => {
|
|
1470
|
+
const els = node.querySelectorAll ? node.querySelectorAll('*') : [];
|
|
1471
|
+
for (const el of els) { if (__ours(el)) continue; out.push(el); if (el.shadowRoot) visit(el.shadowRoot); }
|
|
1472
|
+
};
|
|
1473
|
+
visit(root || document);
|
|
1474
|
+
return out;
|
|
1475
|
+
};
|
|
1476
|
+
const __deepQuery = (root, sel) => {
|
|
1477
|
+
const direct = root.querySelector ? root.querySelector(sel) : null;
|
|
1478
|
+
if (direct && !__ours(direct)) return direct;
|
|
1479
|
+
for (const el of __all(root)) { try { if (el.matches(sel)) return el; } catch (e) { return null; } }
|
|
1480
|
+
return null;
|
|
1481
|
+
};
|
|
1482
|
+
const __deepQueryAll = (root, sel) => {
|
|
1483
|
+
const out = new Set();
|
|
1484
|
+
if (root.querySelectorAll) for (const el of root.querySelectorAll(sel)) if (!__ours(el)) out.add(el);
|
|
1485
|
+
for (const el of __all(root)) { try { if (el.matches(sel)) out.add(el); } catch (e) { /* bad selector */ } }
|
|
1486
|
+
return [...out];
|
|
1487
|
+
};
|
|
1488
|
+
`;
|
|
1489
|
+
|
|
1490
|
+
/** Builds the page-side expression for one selector. `all` returns every match, not the first. */
|
|
1491
|
+
function selectorExpr(t, { all = false } = {}) {
|
|
1492
|
+
const one =
|
|
1493
|
+
t.startsWith('text=') ? findByTextExpr(t.slice(5))
|
|
1494
|
+
: t.startsWith('xpath=') ? `document.evaluate(${JSON.stringify(t.slice(6))}, document, null, 9, null).singleNodeValue`
|
|
1495
|
+
: t.startsWith('css=') ? findByCssExpr(t.slice(4))
|
|
1496
|
+
: t.startsWith('role=') ? findByRoleExpr(t.slice(5))
|
|
1497
|
+
: t.startsWith('label=') ? findByLabelExpr(t.slice(6))
|
|
1498
|
+
: findByCssExpr(t);
|
|
1499
|
+
if (!all) return one;
|
|
1500
|
+
const many =
|
|
1501
|
+
t.startsWith('text=') ? findByTextExpr(t.slice(5), true)
|
|
1502
|
+
: t.startsWith('xpath=') ? `(() => { const r = document.evaluate(${JSON.stringify(t.slice(6))}, document, null, 7, null); return Array.from({ length: r.snapshotLength }, (_, i) => r.snapshotItem(i)); })()`
|
|
1503
|
+
: t.startsWith('css=') ? findByCssExpr(t.slice(4), true)
|
|
1504
|
+
: t.startsWith('role=') ? findByRoleExpr(t.slice(5), true)
|
|
1505
|
+
: t.startsWith('label=') ? `(() => { const e = ${findByLabelExpr(t.slice(6))}; return e ? [e] : []; })()`
|
|
1506
|
+
: findByCssExpr(t, true);
|
|
1507
|
+
return many;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
/** CSS with optional `>>>` shadow-piercing combinators: 'my-app >>> .row button'. */
|
|
1511
|
+
function findByCssExpr(selector, all = false) {
|
|
1512
|
+
return `(() => {
|
|
1513
|
+
${DEEP_PRELUDE}
|
|
1514
|
+
const parts = ${JSON.stringify(selector)}.split('>>>').map((p) => p.trim()).filter(Boolean);
|
|
1515
|
+
let roots = [document];
|
|
1516
|
+
for (let i = 0; i < parts.length; i++) {
|
|
1517
|
+
const hits = [];
|
|
1518
|
+
for (const root of roots) hits.push(...__deepQueryAll(root, parts[i]));
|
|
1519
|
+
if (!hits.length) return ${all ? '[]' : 'null'};
|
|
1520
|
+
if (i === parts.length - 1) return ${all ? '[...new Set(hits)]' : 'hits[0]'};
|
|
1521
|
+
roots = hits.map((el) => el.shadowRoot || el);
|
|
1522
|
+
}
|
|
1523
|
+
return ${all ? '[]' : 'null'};
|
|
1524
|
+
})()`;
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/**
|
|
1528
|
+
* Element whose visible text matches. A wrapper and the control inside it usually carry the
|
|
1529
|
+
* same text, and clicking the wrapper's centre can miss the control entirely, so only the
|
|
1530
|
+
* innermost matches are considered; then exact text wins, then an interactive element.
|
|
1531
|
+
*/
|
|
1532
|
+
function findByTextExpr(text, all = false) {
|
|
1533
|
+
return `(() => {
|
|
1534
|
+
${DEEP_PRELUDE}
|
|
1535
|
+
const want = ${JSON.stringify(text)}.trim(); const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
1536
|
+
const vis = (el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
|
|
1537
|
+
const textOf = (el) => norm(el.innerText ?? el.textContent);
|
|
1538
|
+
const alt = (el) => [norm(el.value), norm(el.getAttribute('aria-label')), norm(el.placeholder), norm(el.title)];
|
|
1539
|
+
const matches = [];
|
|
1540
|
+
for (const el of __all(document)) {
|
|
1541
|
+
if (/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|HEAD|LINK|META)$/.test(el.tagName)) continue;
|
|
1542
|
+
if (!vis(el)) continue;
|
|
1543
|
+
if (textOf(el).includes(want) || alt(el).some((v) => v.includes(want))) matches.push(el);
|
|
1544
|
+
}
|
|
1545
|
+
if (!matches.length) return null;
|
|
1546
|
+
const holds = (a, b) => a.contains(b) || (a.shadowRoot && a.shadowRoot.contains(b));
|
|
1547
|
+
const innermost = matches.filter((el) => !matches.some((o) => o !== el && holds(el, o)));
|
|
1548
|
+
const pool = innermost.length ? innermost : matches;
|
|
1549
|
+
const exact = pool.filter((el) => textOf(el) === want || alt(el).some((v) => v === want));
|
|
1550
|
+
const finalPool = exact.length ? exact : pool;
|
|
1551
|
+
const INTERACTIVE = 'button, a[href], [role=button], [role=link], input, select, textarea, label, summary, [onclick], [tabindex]';
|
|
1552
|
+
const CONTROL = 'button, a[href], [role=button], [role=link], label, summary, [onclick]';
|
|
1553
|
+
// a matched text node inside a control resolves to the control itself
|
|
1554
|
+
const lift = (e) => e.closest(CONTROL) || e;
|
|
1555
|
+
${all
|
|
1556
|
+
? 'return [...new Set(finalPool.map(lift))];'
|
|
1557
|
+
: `const el = finalPool.find((e) => e.matches(INTERACTIVE)) || finalPool[0];
|
|
1558
|
+
return lift(el);`}
|
|
1559
|
+
})()`;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
function findByRoleExpr(spec, all = false) {
|
|
1563
|
+
const m = spec.match(/^([a-z]+)(?:\[name=(?:"([^"]*)"|'([^']*)'|([^\]]*))\])?$/i);
|
|
1564
|
+
if (!m) throw new Error(`bad role selector: ${spec}`);
|
|
1565
|
+
const role = m[1].toLowerCase();
|
|
1566
|
+
const name = m[2] ?? m[3] ?? m[4] ?? null;
|
|
1567
|
+
const implicit = {
|
|
1568
|
+
button: 'button, input[type=button], input[type=submit], input[type=reset], [role=button]',
|
|
1569
|
+
link: 'a[href], [role=link]',
|
|
1570
|
+
textbox: 'input:not([type]), input[type=text], input[type=email], input[type=password], input[type=search], input[type=url], input[type=tel], input[type=number], textarea, [role=textbox], [contenteditable=true]',
|
|
1571
|
+
checkbox: 'input[type=checkbox], [role=checkbox]',
|
|
1572
|
+
radio: 'input[type=radio], [role=radio]',
|
|
1573
|
+
combobox: 'select, [role=combobox]',
|
|
1574
|
+
heading: 'h1,h2,h3,h4,h5,h6,[role=heading]',
|
|
1575
|
+
tab: '[role=tab]', menuitem: '[role=menuitem]', option: 'option,[role=option]', img: 'img,[role=img]',
|
|
1576
|
+
}[role] || `[role=${role}]`;
|
|
1577
|
+
return `(() => {
|
|
1578
|
+
${DEEP_PRELUDE}
|
|
1579
|
+
const want = ${JSON.stringify(name)}; const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
1580
|
+
const accName = (el) => norm(el.getAttribute('aria-label') || (el.labels && [...el.labels].map(l => l.innerText).join(' ')) || el.innerText || el.value || el.alt || el.title || el.placeholder);
|
|
1581
|
+
const els = __deepQueryAll(document, ${JSON.stringify(implicit)}).filter(el => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; });
|
|
1582
|
+
${all
|
|
1583
|
+
? `if (want === null) return els;
|
|
1584
|
+
const exact = els.filter(el => accName(el) === want);
|
|
1585
|
+
return exact.length ? exact : els.filter(el => accName(el).includes(want));`
|
|
1586
|
+
: `if (want === null) return els[0] || null;
|
|
1587
|
+
return els.find(el => accName(el) === want) || els.find(el => accName(el).includes(want)) || null;`}
|
|
1588
|
+
})()`;
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
function findByLabelExpr(label) {
|
|
1592
|
+
return `(() => {
|
|
1593
|
+
${DEEP_PRELUDE}
|
|
1594
|
+
const want = ${JSON.stringify(label)}.trim(); const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
1595
|
+
for (const l of __deepQueryAll(document, 'label')) { if (norm(l.innerText).includes(want) && l.control) return l.control; }
|
|
1596
|
+
const esc = want.replace(/"/g, '\\\\"');
|
|
1597
|
+
return __deepQuery(document, '[aria-label="' + esc + '"]') || __deepQuery(document, '[placeholder="' + esc + '"]');
|
|
1598
|
+
})()`;
|
|
1599
|
+
}
|