@d0nj/dsh-browser 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +69 -2
- package/cordis.patch.yml +11 -0
- package/dist/cdp.d.ts +84 -0
- package/dist/cdp.js +222 -0
- package/dist/console.d.ts +49 -0
- package/dist/console.js +72 -0
- package/dist/host.d.ts +71 -0
- package/dist/host.js +222 -0
- package/dist/idle.d.ts +22 -0
- package/dist/idle.js +47 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +112 -0
- package/dist/keys.d.ts +43 -0
- package/dist/keys.js +124 -0
- package/dist/launch.d.ts +108 -0
- package/dist/launch.js +260 -0
- package/dist/snapshot.d.ts +66 -0
- package/dist/snapshot.js +220 -0
- package/dist/tab.d.ts +183 -0
- package/dist/tab.js +580 -0
- package/dist/tool.d.ts +71 -0
- package/dist/tool.js +444 -0
- package/dist/ws.d.ts +66 -0
- package/dist/ws.js +290 -0
- package/icon.svg +15 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +71 -3
package/dist/tab.js
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
import { ConsoleBuffer, describeRemoteObject } from './console.js';
|
|
2
|
+
import { parseKeyChord } from './keys.js';
|
|
3
|
+
import { renderAccessibilityTree } from './snapshot.js';
|
|
4
|
+
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
5
|
+
const SCROLL_AND_MEASURE = `function () {
|
|
6
|
+
const element = this;
|
|
7
|
+
if (!(element instanceof Element)) return { ok: false, reason: 'not-an-element' };
|
|
8
|
+
element.scrollIntoView({ block: 'center', inline: 'center' });
|
|
9
|
+
const rect = element.getBoundingClientRect();
|
|
10
|
+
const style = window.getComputedStyle(element);
|
|
11
|
+
return {
|
|
12
|
+
ok: true,
|
|
13
|
+
x: rect.left + rect.width / 2,
|
|
14
|
+
y: rect.top + rect.height / 2,
|
|
15
|
+
width: rect.width,
|
|
16
|
+
height: rect.height,
|
|
17
|
+
visible: rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number.parseFloat(style.opacity || '1') > 0,
|
|
18
|
+
disabled: ('disabled' in element && element.disabled === true) || element.getAttribute('aria-disabled') === 'true',
|
|
19
|
+
tag: element.tagName.toLowerCase(),
|
|
20
|
+
};
|
|
21
|
+
}`;
|
|
22
|
+
const MEASURE_DOCUMENT_BOX = `function () {
|
|
23
|
+
const element = this;
|
|
24
|
+
if (!(element instanceof Element)) return { ok: false, reason: 'not-an-element' };
|
|
25
|
+
element.scrollIntoView({ block: 'center', inline: 'center' });
|
|
26
|
+
const rect = element.getBoundingClientRect();
|
|
27
|
+
return { ok: true, x: rect.left + window.scrollX, y: rect.top + window.scrollY, width: rect.width, height: rect.height };
|
|
28
|
+
}`;
|
|
29
|
+
const FOCUS_FOR_TYPING = `function (clear) {
|
|
30
|
+
const element = this;
|
|
31
|
+
if (!(element instanceof Element)) return { ok: false, reason: 'not-an-element' };
|
|
32
|
+
element.scrollIntoView({ block: 'center', inline: 'center' });
|
|
33
|
+
if (element instanceof HTMLElement) element.focus({ preventScroll: true });
|
|
34
|
+
if (!clear) return { ok: true };
|
|
35
|
+
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
|
|
36
|
+
const prototype = element instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
|
37
|
+
const setter = Object.getOwnPropertyDescriptor(prototype, 'value')?.set;
|
|
38
|
+
setter === undefined ? (element.value = '') : setter.call(element, '');
|
|
39
|
+
element.dispatchEvent(new Event('input', { bubbles: true }));
|
|
40
|
+
return { ok: true };
|
|
41
|
+
}
|
|
42
|
+
if (element.isContentEditable) {
|
|
43
|
+
const range = document.createRange();
|
|
44
|
+
range.selectNodeContents(element);
|
|
45
|
+
const selection = window.getSelection();
|
|
46
|
+
selection?.removeAllRanges();
|
|
47
|
+
selection?.addRange(range);
|
|
48
|
+
return { ok: true };
|
|
49
|
+
}
|
|
50
|
+
return { ok: true };
|
|
51
|
+
}`;
|
|
52
|
+
const SELECT_OPTIONS = `function (values) {
|
|
53
|
+
const element = this;
|
|
54
|
+
if (!(element instanceof HTMLSelectElement)) return { ok: false, reason: 'not-a-select' };
|
|
55
|
+
const wanted = new Set(values);
|
|
56
|
+
let changed = false;
|
|
57
|
+
for (const option of Array.from(element.options)) {
|
|
58
|
+
const selected = wanted.has(option.value) || wanted.has(option.label);
|
|
59
|
+
if (option.selected !== selected) {
|
|
60
|
+
option.selected = selected;
|
|
61
|
+
changed = true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (changed) {
|
|
65
|
+
element.dispatchEvent(new Event('input', { bubbles: true }));
|
|
66
|
+
element.dispatchEvent(new Event('change', { bubbles: true }));
|
|
67
|
+
}
|
|
68
|
+
return { ok: true, selected: Array.from(element.selectedOptions).map((option) => option.label || option.value) };
|
|
69
|
+
}`;
|
|
70
|
+
const BUTTON_MASK = { left: 1, right: 2, middle: 4 };
|
|
71
|
+
/** Schemes a navigation may use; anything else is refused before it reaches Chrome. */
|
|
72
|
+
const ALLOWED_SCHEMES = new Set(['http', 'https', 'file', 'about', 'data']);
|
|
73
|
+
/**
|
|
74
|
+
* Normalize model-supplied link text into an absolute URL.
|
|
75
|
+
* @param input - absolute URL, bare host, or `localhost:port`.
|
|
76
|
+
* @returns the URL to navigate to.
|
|
77
|
+
*/
|
|
78
|
+
export function normalizeUrl(input) {
|
|
79
|
+
const trimmed = input.trim();
|
|
80
|
+
if (trimmed === '')
|
|
81
|
+
throw new Error('url is required: pass an absolute URL such as https://example.com');
|
|
82
|
+
if (/^javascript:/iu.test(trimmed))
|
|
83
|
+
throw new Error('javascript: URLs are not allowed; use evaluate to run page JavaScript');
|
|
84
|
+
const scheme = /^([a-z][a-z0-9+.-]*):/iu.exec(trimmed)?.[1]?.toLowerCase();
|
|
85
|
+
if (scheme !== undefined && ALLOWED_SCHEMES.has(scheme))
|
|
86
|
+
return new URL(trimmed).toString();
|
|
87
|
+
const hostLike = /^(\[[0-9a-f:]+\]|localhost|127\.0\.0\.1|[\w-]+(?:\.[\w-]+)+)(?::\d+)?(?:\/|$)/iu.test(trimmed);
|
|
88
|
+
if (hostLike) {
|
|
89
|
+
const loopback = /^(?:localhost|127\.0\.0\.1|\[::1\])/iu.test(trimmed);
|
|
90
|
+
try {
|
|
91
|
+
return new URL(`${loopback ? 'http' : 'https'}://${trimmed}`).toString();
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// Fall through to the unsupported-scheme or not-a-URL message.
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (scheme !== undefined)
|
|
98
|
+
throw new Error(`"${trimmed}" uses the unsupported ${scheme}: scheme; pass an http(s) URL or a bare host such as example.com`);
|
|
99
|
+
throw new Error(`"${trimmed}" is not a URL; pass an absolute URL such as https://example.com/search?q=cats`);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Interpret a model-supplied selector, accepting the ref spellings agents copy
|
|
103
|
+
* out of a snapshot (`e12`, `@e12`, `aria-ref=e12`).
|
|
104
|
+
* @param selector - raw selector text.
|
|
105
|
+
* @returns the ref it names, when it names one.
|
|
106
|
+
*/
|
|
107
|
+
export function refFromSelector(selector) {
|
|
108
|
+
const trimmed = selector.trim();
|
|
109
|
+
const explicit = /^(?:aria-ref=|aria-ref\/|@)(e\d+)$/iu.exec(trimmed);
|
|
110
|
+
if (explicit?.[1] !== undefined)
|
|
111
|
+
return explicit[1];
|
|
112
|
+
return /^(e\d+)$/u.test(trimmed) ? trimmed : undefined;
|
|
113
|
+
}
|
|
114
|
+
/** One attached tab. */
|
|
115
|
+
export class Tab {
|
|
116
|
+
name;
|
|
117
|
+
targetId;
|
|
118
|
+
sessionId;
|
|
119
|
+
#cdp;
|
|
120
|
+
#settings;
|
|
121
|
+
#console = new ConsoleBuffer();
|
|
122
|
+
#disposers = [];
|
|
123
|
+
#refs = new Map();
|
|
124
|
+
#documentGeneration = 0;
|
|
125
|
+
#closed = false;
|
|
126
|
+
constructor(cdp, targetId, sessionId, name, settings) {
|
|
127
|
+
this.#cdp = cdp;
|
|
128
|
+
this.targetId = targetId;
|
|
129
|
+
this.sessionId = sessionId;
|
|
130
|
+
this.name = name;
|
|
131
|
+
this.#settings = settings;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Attach to one page target and enable the domains this tab uses.
|
|
135
|
+
* @param cdp - browser-level connection.
|
|
136
|
+
* @param targetId - page target to attach to.
|
|
137
|
+
* @param name - tab name the model addresses.
|
|
138
|
+
* @param settings - viewport, dialogs, and timeouts.
|
|
139
|
+
* @returns the ready tab.
|
|
140
|
+
*/
|
|
141
|
+
static async attach(cdp, targetId, name, settings) {
|
|
142
|
+
const { sessionId } = await cdp.send('Target.attachToTarget', { targetId, flatten: true });
|
|
143
|
+
const tab = new Tab(cdp, targetId, sessionId, name, settings);
|
|
144
|
+
await tab.#initialize();
|
|
145
|
+
return tab;
|
|
146
|
+
}
|
|
147
|
+
/** Whether the tab can still be used. */
|
|
148
|
+
get closed() {
|
|
149
|
+
return this.#closed;
|
|
150
|
+
}
|
|
151
|
+
/** The tab's captured console and page errors. */
|
|
152
|
+
get consoleBuffer() {
|
|
153
|
+
return this.#console;
|
|
154
|
+
}
|
|
155
|
+
async #initialize() {
|
|
156
|
+
const sessionId = this.sessionId;
|
|
157
|
+
await this.#cdp.send('Page.enable', {}, sessionId);
|
|
158
|
+
await this.#cdp.send('Runtime.enable', {}, sessionId);
|
|
159
|
+
await this.#cdp.send('Log.enable', {}, sessionId);
|
|
160
|
+
await this.#cdp.send('Accessibility.enable', {}, sessionId);
|
|
161
|
+
await this.#cdp.send('Emulation.setDeviceMetricsOverride', { width: this.#settings.viewport.width, height: this.#settings.viewport.height, deviceScaleFactor: 1, mobile: false }, sessionId);
|
|
162
|
+
this.#disposers.push(this.#cdp.on('Runtime.consoleAPICalled', (event) => this.#onConsole(event.params), sessionId), this.#cdp.on('Runtime.exceptionThrown', (event) => this.#onException(event.params), sessionId), this.#cdp.on('Log.entryAdded', (event) => this.#onLogEntry(event.params), sessionId), this.#cdp.on('Page.javascriptDialogOpening', (event) => void this.#onDialog(event.params), sessionId), this.#cdp.on('Page.frameNavigated', (event) => {
|
|
163
|
+
const frame = event.params.frame;
|
|
164
|
+
if (frame?.parentId !== undefined)
|
|
165
|
+
return;
|
|
166
|
+
this.#documentGeneration++;
|
|
167
|
+
this.#refs.clear();
|
|
168
|
+
}, sessionId), this.#cdp.on('Inspector.targetCrashed', () => {
|
|
169
|
+
this.#closed = true;
|
|
170
|
+
}, sessionId), this.#cdp.on('Target.detachedFromTarget', (event) => {
|
|
171
|
+
if (event.params.sessionId === sessionId)
|
|
172
|
+
this.#closed = true;
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
/** Detach and stop listening. */
|
|
176
|
+
async dispose() {
|
|
177
|
+
this.#closed = true;
|
|
178
|
+
for (const dispose of this.#disposers.splice(0))
|
|
179
|
+
dispose();
|
|
180
|
+
await this.#cdp.send('Target.detachFromTarget', { sessionId: this.sessionId }).catch(() => undefined);
|
|
181
|
+
}
|
|
182
|
+
#onConsole(params) {
|
|
183
|
+
const type = typeof params.type === 'string' ? params.type : 'log';
|
|
184
|
+
const args = Array.isArray(params.args) ? params.args : [];
|
|
185
|
+
const text = args.map((argument) => describeRemoteObject(argument)).filter((part) => part !== '').join(' ');
|
|
186
|
+
this.#console.push(type === 'warning' ? 'warning' : type, text);
|
|
187
|
+
}
|
|
188
|
+
#onException(params) {
|
|
189
|
+
const details = params.exceptionDetails;
|
|
190
|
+
const description = describeRemoteObject(details?.exception) || details?.text || 'uncaught exception';
|
|
191
|
+
this.#console.push('pageerror', details?.url === undefined ? description : `${description} (${details.url})`);
|
|
192
|
+
}
|
|
193
|
+
#onLogEntry(params) {
|
|
194
|
+
const entry = params.entry;
|
|
195
|
+
const level = entry?.level === 'warning' ? 'warning' : (entry?.level ?? 'log');
|
|
196
|
+
const text = entry?.text ?? '';
|
|
197
|
+
this.#console.push(level, entry?.url === undefined ? text : `${text} (${entry.url})`);
|
|
198
|
+
}
|
|
199
|
+
async #onDialog(params) {
|
|
200
|
+
const type = typeof params.type === 'string' ? params.type : 'dialog';
|
|
201
|
+
const message = typeof params.message === 'string' ? params.message : '';
|
|
202
|
+
const accept = this.#settings.dialogs === 'accept';
|
|
203
|
+
this.#console.push('dialog', `${type}: ${message}`);
|
|
204
|
+
await this.#cdp.send('Page.handleJavaScriptDialog', { accept }, this.sessionId).catch(() => undefined);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Evaluate one expression in the page.
|
|
208
|
+
* @param expression - JavaScript expression.
|
|
209
|
+
* @param timeoutMs - execution budget.
|
|
210
|
+
* @returns the deserialized value.
|
|
211
|
+
*/
|
|
212
|
+
async evaluate(expression, timeoutMs = 30_000) {
|
|
213
|
+
const response = await this.#cdp.send('Runtime.evaluate', {
|
|
214
|
+
expression,
|
|
215
|
+
returnByValue: true,
|
|
216
|
+
awaitPromise: true,
|
|
217
|
+
userGesture: true,
|
|
218
|
+
}, this.sessionId, timeoutMs);
|
|
219
|
+
if (response.exceptionDetails !== undefined) {
|
|
220
|
+
throw new Error(response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? 'the page threw an exception');
|
|
221
|
+
}
|
|
222
|
+
return response.result?.value;
|
|
223
|
+
}
|
|
224
|
+
async #callOn(objectId, functionDeclaration, args = []) {
|
|
225
|
+
const response = await this.#cdp.send('Runtime.callFunctionOn', {
|
|
226
|
+
objectId,
|
|
227
|
+
functionDeclaration,
|
|
228
|
+
returnByValue: true,
|
|
229
|
+
awaitPromise: true,
|
|
230
|
+
arguments: args.map((value) => ({ value })),
|
|
231
|
+
}, this.sessionId);
|
|
232
|
+
if (response.exceptionDetails !== undefined) {
|
|
233
|
+
throw new Error(response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? 'the element threw an exception');
|
|
234
|
+
}
|
|
235
|
+
if (response.result?.value === undefined)
|
|
236
|
+
throw new Error('the element returned no value');
|
|
237
|
+
return response.result.value;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Current URL and title.
|
|
241
|
+
* @returns page identity, or empty strings when the page is unreachable.
|
|
242
|
+
*/
|
|
243
|
+
async info() {
|
|
244
|
+
try {
|
|
245
|
+
const value = await this.evaluate('({ url: location.href, title: document.title })', 5_000);
|
|
246
|
+
return { url: value.url ?? '', title: value.title ?? '' };
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
return { url: '', title: '' };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Navigate the tab.
|
|
254
|
+
* @param input - URL, bare host, or localhost address.
|
|
255
|
+
* @param timeoutMs - load budget.
|
|
256
|
+
* @returns the committed URL.
|
|
257
|
+
*/
|
|
258
|
+
async navigate(input, timeoutMs = this.#settings.navigateTimeoutMs) {
|
|
259
|
+
const url = normalizeUrl(input);
|
|
260
|
+
const committed = this.#cdp
|
|
261
|
+
.waitFor('Page.frameNavigated', {
|
|
262
|
+
sessionId: this.sessionId,
|
|
263
|
+
timeoutMs,
|
|
264
|
+
predicate: (params) => params.frame?.parentId === undefined,
|
|
265
|
+
})
|
|
266
|
+
.catch(() => undefined);
|
|
267
|
+
const result = await this.#cdp.send('Page.navigate', { url }, this.sessionId, timeoutMs);
|
|
268
|
+
if (typeof result.errorText === 'string' && result.errorText !== '')
|
|
269
|
+
throw new Error(`cannot open ${url}: ${result.errorText}`);
|
|
270
|
+
await committed;
|
|
271
|
+
await this.#waitForReady(timeoutMs);
|
|
272
|
+
return url;
|
|
273
|
+
}
|
|
274
|
+
/** Go back one history entry. */
|
|
275
|
+
async back(timeoutMs = this.#settings.navigateTimeoutMs) {
|
|
276
|
+
await this.#travel(-1, timeoutMs);
|
|
277
|
+
}
|
|
278
|
+
/** Go forward one history entry. */
|
|
279
|
+
async forward(timeoutMs = this.#settings.navigateTimeoutMs) {
|
|
280
|
+
await this.#travel(1, timeoutMs);
|
|
281
|
+
}
|
|
282
|
+
async #travel(offset, timeoutMs) {
|
|
283
|
+
const history = await this.#cdp.send('Page.getNavigationHistory', {}, this.sessionId);
|
|
284
|
+
const target = history.currentIndex + offset;
|
|
285
|
+
if (target < 0 || target >= history.entries.length)
|
|
286
|
+
return;
|
|
287
|
+
const committed = this.#cdp
|
|
288
|
+
.waitFor('Page.frameNavigated', {
|
|
289
|
+
sessionId: this.sessionId,
|
|
290
|
+
timeoutMs,
|
|
291
|
+
predicate: (params) => params.frame?.parentId === undefined,
|
|
292
|
+
})
|
|
293
|
+
.catch(() => undefined);
|
|
294
|
+
await this.#cdp.send('Page.navigateToHistoryEntry', { entryId: history.entries[target].id }, this.sessionId, timeoutMs);
|
|
295
|
+
await committed;
|
|
296
|
+
await this.#waitForReady(timeoutMs);
|
|
297
|
+
}
|
|
298
|
+
/** Reload the current document. */
|
|
299
|
+
async reload(timeoutMs = this.#settings.navigateTimeoutMs) {
|
|
300
|
+
const committed = this.#cdp
|
|
301
|
+
.waitFor('Page.frameNavigated', {
|
|
302
|
+
sessionId: this.sessionId,
|
|
303
|
+
timeoutMs,
|
|
304
|
+
predicate: (params) => params.frame?.parentId === undefined,
|
|
305
|
+
})
|
|
306
|
+
.catch(() => undefined);
|
|
307
|
+
await this.#cdp.send('Page.reload', {}, this.sessionId, timeoutMs);
|
|
308
|
+
await committed;
|
|
309
|
+
await this.#waitForReady(timeoutMs);
|
|
310
|
+
}
|
|
311
|
+
async #waitForReady(timeoutMs) {
|
|
312
|
+
const deadline = Date.now() + timeoutMs;
|
|
313
|
+
for (;;) {
|
|
314
|
+
try {
|
|
315
|
+
const state = await this.evaluate('document.readyState', 5_000);
|
|
316
|
+
if (state === 'complete')
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
// The execution context is replaced while a navigation commits.
|
|
321
|
+
}
|
|
322
|
+
if (Date.now() >= deadline)
|
|
323
|
+
return;
|
|
324
|
+
await delay(100);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async #resolveElement(target) {
|
|
328
|
+
const ref = target.ref ?? (target.selector === undefined ? undefined : refFromSelector(target.selector));
|
|
329
|
+
if (ref !== undefined) {
|
|
330
|
+
const backendNodeId = this.#refs.get(ref);
|
|
331
|
+
if (backendNodeId === undefined) {
|
|
332
|
+
throw new Error(`unknown ref "${ref}" in tab "${this.name}": refs are numbered per snapshot and cleared when the page navigates. Call snapshot (or any action that returns one) and use a ref from that output.`);
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
const resolved = await this.#cdp.send('DOM.resolveNode', { backendNodeId, objectGroup: 'dsh-browser' }, this.sessionId);
|
|
336
|
+
if (resolved.object.objectId === undefined)
|
|
337
|
+
throw new Error('no object');
|
|
338
|
+
return { objectId: resolved.object.objectId, label: `ref "${ref}"` };
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
throw new Error(`ref "${ref}" no longer exists in tab "${this.name}": the page changed since the snapshot. Take a new snapshot and use a current ref.`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const selector = target.selector?.trim() ?? '';
|
|
345
|
+
if (selector === '')
|
|
346
|
+
throw new Error('name the target with ref (from a snapshot) or selector');
|
|
347
|
+
const response = await this.#cdp.send('Runtime.evaluate', {
|
|
348
|
+
expression: `document.querySelector(${JSON.stringify(selector)})`,
|
|
349
|
+
returnByValue: false,
|
|
350
|
+
}, this.sessionId);
|
|
351
|
+
if (response.exceptionDetails !== undefined) {
|
|
352
|
+
throw new Error(`selector "${selector}" is not a valid CSS selector: ${response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? 'parse error'}`);
|
|
353
|
+
}
|
|
354
|
+
const objectId = response.result?.objectId;
|
|
355
|
+
if (objectId === undefined || response.result?.subtype === 'null') {
|
|
356
|
+
throw new Error(`selector "${selector}" matched no element in tab "${this.name}"; take a snapshot to find a ref, or check the selector`);
|
|
357
|
+
}
|
|
358
|
+
return { objectId, label: `selector "${selector}"` };
|
|
359
|
+
}
|
|
360
|
+
async #box(objectId) {
|
|
361
|
+
return this.#callOn(objectId, SCROLL_AND_MEASURE);
|
|
362
|
+
}
|
|
363
|
+
async #dispatchMouse(type, x, y, button, clickCount) {
|
|
364
|
+
await this.#cdp.send('Input.dispatchMouseEvent', {
|
|
365
|
+
type,
|
|
366
|
+
x: Math.round(x),
|
|
367
|
+
y: Math.round(y),
|
|
368
|
+
button,
|
|
369
|
+
clickCount,
|
|
370
|
+
buttons: type === 'mousePressed' ? BUTTON_MASK[button] : 0,
|
|
371
|
+
}, this.sessionId);
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Click an element with real mouse events at its centre.
|
|
375
|
+
* @param target - snapshot ref or selector.
|
|
376
|
+
* @param options - button and click count.
|
|
377
|
+
*/
|
|
378
|
+
async click(target, options = {}) {
|
|
379
|
+
const { objectId, label } = await this.#resolveElement(target);
|
|
380
|
+
const box = await this.#box(objectId);
|
|
381
|
+
if (box.ok !== true)
|
|
382
|
+
throw new Error(`cannot click ${label}: the target is not an element`);
|
|
383
|
+
if (box.visible !== true)
|
|
384
|
+
throw new Error(`cannot click ${label}: the element is not visible (hidden, zero size, or transparent); take a snapshot to pick a visible target`);
|
|
385
|
+
const button = options.button ?? 'left';
|
|
386
|
+
const clickCount = options.clickCount ?? 1;
|
|
387
|
+
await this.#dispatchMouse('mouseMoved', box.x, box.y, button, 0);
|
|
388
|
+
await this.#dispatchMouse('mousePressed', box.x, box.y, button, clickCount);
|
|
389
|
+
await this.#dispatchMouse('mouseReleased', box.x, box.y, button, clickCount);
|
|
390
|
+
await this.#settle();
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Move the pointer over an element without clicking.
|
|
394
|
+
* @param target - snapshot ref or selector.
|
|
395
|
+
*/
|
|
396
|
+
async hover(target) {
|
|
397
|
+
const { objectId, label } = await this.#resolveElement(target);
|
|
398
|
+
const box = await this.#box(objectId);
|
|
399
|
+
if (box.ok !== true || box.visible !== true)
|
|
400
|
+
throw new Error(`cannot hover ${label}: the element is not visible`);
|
|
401
|
+
await this.#dispatchMouse('mouseMoved', box.x, box.y, 'left', 0);
|
|
402
|
+
await delay(100);
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Focus a field and type into it.
|
|
406
|
+
* @param target - snapshot ref or selector.
|
|
407
|
+
* @param text - text to insert.
|
|
408
|
+
* @param options - `clear` replaces the current value (default true); `submit` presses Enter.
|
|
409
|
+
*/
|
|
410
|
+
async type(target, text, options = {}) {
|
|
411
|
+
const { objectId, label } = await this.#resolveElement(target);
|
|
412
|
+
const box = await this.#box(objectId);
|
|
413
|
+
if (box.ok === true && box.visible !== true)
|
|
414
|
+
throw new Error(`cannot type into ${label}: the element is not visible`);
|
|
415
|
+
const focused = await this.#callOn(objectId, FOCUS_FOR_TYPING, [options.clear !== false]);
|
|
416
|
+
if (focused.ok !== true)
|
|
417
|
+
throw new Error(`cannot type into ${label}: ${focused.reason ?? 'the element cannot take focus'}`);
|
|
418
|
+
if (text !== '')
|
|
419
|
+
await this.#cdp.send('Input.insertText', { text }, this.sessionId);
|
|
420
|
+
if (options.submit === true)
|
|
421
|
+
await this.press('Enter');
|
|
422
|
+
else
|
|
423
|
+
await this.#settle();
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Press one key or chord in the focused element, or after focusing a target.
|
|
427
|
+
* @param key - chord such as `Enter` or `Control+A`.
|
|
428
|
+
* @param target - element to focus first.
|
|
429
|
+
*/
|
|
430
|
+
async press(key, target) {
|
|
431
|
+
if (target !== undefined)
|
|
432
|
+
await this.focus(target);
|
|
433
|
+
const stroke = parseKeyChord(key);
|
|
434
|
+
const base = { key: stroke.key, code: stroke.code, windowsVirtualKeyCode: stroke.keyCode, nativeVirtualKeyCode: stroke.keyCode, modifiers: stroke.modifiers };
|
|
435
|
+
await this.#cdp.send('Input.dispatchKeyEvent', { ...base, type: 'keyDown', ...(stroke.text === undefined ? {} : { text: stroke.text }) }, this.sessionId);
|
|
436
|
+
await this.#cdp.send('Input.dispatchKeyEvent', { ...base, type: 'keyUp' }, this.sessionId);
|
|
437
|
+
await this.#settle();
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Focus an element.
|
|
441
|
+
* @param target - snapshot ref or selector.
|
|
442
|
+
*/
|
|
443
|
+
async focus(target) {
|
|
444
|
+
const { objectId } = await this.#resolveElement(target);
|
|
445
|
+
await this.#callOn(objectId, FOCUS_FOR_TYPING, [false]);
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Choose options in a `<select>`.
|
|
449
|
+
* @param target - snapshot ref or selector naming the select element.
|
|
450
|
+
* @param values - option values or labels.
|
|
451
|
+
* @returns the labels that ended up selected.
|
|
452
|
+
*/
|
|
453
|
+
async select(target, values) {
|
|
454
|
+
const { objectId, label } = await this.#resolveElement(target);
|
|
455
|
+
const result = await this.#callOn(objectId, SELECT_OPTIONS, [values]);
|
|
456
|
+
if (result.ok !== true)
|
|
457
|
+
throw new Error(`cannot select in ${label}: ${result.reason === 'not-a-select' ? 'the element is not a <select>' : (result.reason ?? 'unknown reason')}`);
|
|
458
|
+
await this.#settle();
|
|
459
|
+
return result.selected ?? [];
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Scroll the page with a mouse wheel.
|
|
463
|
+
* @param options - direction, wheel notches, and optionally an element to aim at.
|
|
464
|
+
*/
|
|
465
|
+
async scroll(options = {}) {
|
|
466
|
+
const notches = options.amount ?? 3;
|
|
467
|
+
const delta = (options.up === true ? -1 : 1) * notches * 100;
|
|
468
|
+
let x = Math.round(this.#settings.viewport.width / 2);
|
|
469
|
+
let y = Math.round(this.#settings.viewport.height / 2);
|
|
470
|
+
if (options.target !== undefined) {
|
|
471
|
+
const { objectId } = await this.#resolveElement(options.target);
|
|
472
|
+
const box = await this.#box(objectId);
|
|
473
|
+
if (box.ok === true) {
|
|
474
|
+
x = Math.round(box.x);
|
|
475
|
+
y = Math.round(box.y);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
await this.#cdp.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x, y, deltaX: 0, deltaY: delta }, this.sessionId);
|
|
479
|
+
await delay(250);
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Wait for text or a selector to appear.
|
|
483
|
+
* @param options - condition and budget.
|
|
484
|
+
* @returns what was observed, or throws when the budget expires.
|
|
485
|
+
*/
|
|
486
|
+
async waitFor(options) {
|
|
487
|
+
const timeoutMs = options.timeoutMs ?? 10_000;
|
|
488
|
+
const deadline = Date.now() + timeoutMs;
|
|
489
|
+
const text = options.text;
|
|
490
|
+
const selector = options.selector;
|
|
491
|
+
for (;;) {
|
|
492
|
+
try {
|
|
493
|
+
if (selector !== undefined) {
|
|
494
|
+
const found = await this.evaluate(`Boolean(document.querySelector(${JSON.stringify(selector)}))`, 5_000);
|
|
495
|
+
if (found)
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
else if (text !== undefined) {
|
|
499
|
+
const present = await this.evaluate(`document.body instanceof HTMLElement && document.body.innerText.includes(${JSON.stringify(text)})`, 5_000);
|
|
500
|
+
if (present)
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
else {
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
// The document was being replaced; retry until the budget expires.
|
|
509
|
+
}
|
|
510
|
+
if (Date.now() >= deadline) {
|
|
511
|
+
const what = selector === undefined ? `text ${JSON.stringify(text ?? '')}` : `selector "${selector ?? ''}"`;
|
|
512
|
+
throw new Error(`${what} did not appear in tab "${this.name}" within ${timeoutMs}ms; take a snapshot to see the current page`);
|
|
513
|
+
}
|
|
514
|
+
await delay(150);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Read the page as a numbered accessibility outline.
|
|
519
|
+
* @param options - scope selector and budgets.
|
|
520
|
+
* @returns the outline and its ref table, which replaces the previous one.
|
|
521
|
+
*/
|
|
522
|
+
async snapshot(options = {}) {
|
|
523
|
+
let rootBackendNodeId;
|
|
524
|
+
if (options.selector !== undefined) {
|
|
525
|
+
const { objectId } = await this.#resolveElement({ selector: options.selector });
|
|
526
|
+
const described = await this.#cdp.send('DOM.describeNode', { objectId }, this.sessionId);
|
|
527
|
+
rootBackendNodeId = described.node.backendNodeId;
|
|
528
|
+
}
|
|
529
|
+
const tree = await this.#cdp.send('Accessibility.getFullAXTree', {}, this.sessionId, 60_000);
|
|
530
|
+
const rendered = renderAccessibilityTree(tree.nodes, {
|
|
531
|
+
maxChars: options.maxChars ?? 12_000,
|
|
532
|
+
maxNodes: options.maxNodes ?? 1_500,
|
|
533
|
+
...(rootBackendNodeId === undefined ? {} : { rootBackendNodeId }),
|
|
534
|
+
});
|
|
535
|
+
this.#refs = new Map(rendered.refs);
|
|
536
|
+
return rendered;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Capture a PNG.
|
|
540
|
+
* @param options - viewport, full page, or one element.
|
|
541
|
+
* @returns the image bytes and their pixel size.
|
|
542
|
+
*/
|
|
543
|
+
async screenshot(options = {}) {
|
|
544
|
+
if (options.target !== undefined) {
|
|
545
|
+
const { objectId } = await this.#resolveElement(options.target);
|
|
546
|
+
const box = await this.#callOn(objectId, MEASURE_DOCUMENT_BOX);
|
|
547
|
+
if (box.ok !== true || box.width === undefined || box.height === undefined)
|
|
548
|
+
throw new Error('cannot screenshot that element: it is not an element');
|
|
549
|
+
if (box.width < 1 || box.height < 1)
|
|
550
|
+
throw new Error('cannot screenshot that element: it has zero size');
|
|
551
|
+
const clip = { x: box.x, y: box.y, width: box.width, height: box.height, scale: 1 };
|
|
552
|
+
return this.#capture({ clip, width: clip.width, height: clip.height });
|
|
553
|
+
}
|
|
554
|
+
if (options.fullPage === true) {
|
|
555
|
+
const metrics = await this.#cdp.send('Page.getLayoutMetrics', {}, this.sessionId);
|
|
556
|
+
const size = metrics.cssContentSize ?? metrics.contentSize;
|
|
557
|
+
const height = Math.min(Math.ceil(size.height), 6_000);
|
|
558
|
+
const width = Math.min(Math.ceil(size.width), this.#settings.viewport.width * 3);
|
|
559
|
+
return this.#capture({ clip: { x: 0, y: 0, width, height, scale: 1 }, width, height });
|
|
560
|
+
}
|
|
561
|
+
return this.#capture({ width: this.#settings.viewport.width, height: this.#settings.viewport.height });
|
|
562
|
+
}
|
|
563
|
+
async #capture(options) {
|
|
564
|
+
const response = await this.#cdp.send('Page.captureScreenshot', {
|
|
565
|
+
format: 'png',
|
|
566
|
+
fromSurface: true,
|
|
567
|
+
...(options.clip === undefined ? {} : { clip: options.clip, captureBeyondViewport: true }),
|
|
568
|
+
}, this.sessionId, 60_000);
|
|
569
|
+
return { data: Buffer.from(response.data, 'base64'), width: options.width, height: options.height };
|
|
570
|
+
}
|
|
571
|
+
/** The document generation, which advances whenever the page navigates. */
|
|
572
|
+
get documentGeneration() {
|
|
573
|
+
return this.#documentGeneration;
|
|
574
|
+
}
|
|
575
|
+
async #settle() {
|
|
576
|
+
await delay(120);
|
|
577
|
+
await this.#waitForReady(Math.min(this.#settings.navigateTimeoutMs, 10_000));
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
//# sourceMappingURL=tab.js.map
|
package/dist/tool.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
3
|
+
import type { ConsoleEntry } from './console.js';
|
|
4
|
+
import type { BrowserHost, BrowserSettings, TabListing } from './host.js';
|
|
5
|
+
import type { PageInfo } from './tab.js';
|
|
6
|
+
/** Every action the tool accepts. */
|
|
7
|
+
export declare const BROWSER_ACTIONS: readonly ["open", "snapshot", "click", "type", "press", "hover", "select", "scroll", "wait", "evaluate", "screenshot", "console", "tabs", "close", "back", "forward", "reload"];
|
|
8
|
+
/** One accepted action. */
|
|
9
|
+
export type BrowserAction = (typeof BROWSER_ACTIONS)[number];
|
|
10
|
+
/** Screenshot metadata carried into the output value. */
|
|
11
|
+
export interface ImageValue {
|
|
12
|
+
readonly attachmentId: string;
|
|
13
|
+
readonly mediaType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif';
|
|
14
|
+
readonly bytes: number;
|
|
15
|
+
readonly width: number;
|
|
16
|
+
readonly height: number;
|
|
17
|
+
readonly name?: string;
|
|
18
|
+
}
|
|
19
|
+
/** Canonical output of one call. */
|
|
20
|
+
export interface BrowserValue {
|
|
21
|
+
readonly tab: string;
|
|
22
|
+
readonly url: string;
|
|
23
|
+
readonly title: string;
|
|
24
|
+
readonly body: string;
|
|
25
|
+
readonly image?: ImageValue;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Quote a value for an attribute inside the output envelope.
|
|
29
|
+
* @param value - page-derived text.
|
|
30
|
+
* @returns attribute-safe text.
|
|
31
|
+
*/
|
|
32
|
+
export declare function escapeAttribute(value: string): string;
|
|
33
|
+
/**
|
|
34
|
+
* Wrap page-derived text so the model can tell it from tool prose.
|
|
35
|
+
* @param tabName - tab the text came from.
|
|
36
|
+
* @param info - current page identity.
|
|
37
|
+
* @param text - the snapshot or evaluation result.
|
|
38
|
+
* @returns the enveloped body.
|
|
39
|
+
*/
|
|
40
|
+
export declare function wrapPage(tabName: string, info: PageInfo, text: string): string;
|
|
41
|
+
/**
|
|
42
|
+
* Render a console dump, keeping the newest lines.
|
|
43
|
+
* @param entries - captured lines.
|
|
44
|
+
* @param limit - maximum lines to render.
|
|
45
|
+
* @returns one line per entry.
|
|
46
|
+
*/
|
|
47
|
+
export declare function formatConsole(entries: readonly ConsoleEntry[], limit?: number): string;
|
|
48
|
+
/**
|
|
49
|
+
* Render an evaluation result.
|
|
50
|
+
* @param value - the page value.
|
|
51
|
+
* @param maxChars - output budget.
|
|
52
|
+
* @returns display text.
|
|
53
|
+
*/
|
|
54
|
+
export declare function formatEvaluated(value: unknown, maxChars?: number): string;
|
|
55
|
+
/**
|
|
56
|
+
* Render the open-tab list.
|
|
57
|
+
* @param tabs - tabs with their pages.
|
|
58
|
+
* @param current - the tab the caller is addressing.
|
|
59
|
+
* @returns one line per tab.
|
|
60
|
+
*/
|
|
61
|
+
export declare function formatTabs(tabs: readonly TabListing[], current: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* Register the `browser` tool and its prompt guidance.
|
|
64
|
+
* @param ctx - context whose `tools` and `systemPrompt` registries receive the registrations.
|
|
65
|
+
* @param host - the browser whose tabs the tool drives.
|
|
66
|
+
* @param settings - resolved plugin configuration.
|
|
67
|
+
*/
|
|
68
|
+
export declare function applyBrowserTool(ctx: Context, host: BrowserHost, settings: BrowserSettings): void;
|
|
69
|
+
/** Brand a stored image value back into the reference an image block carries. */
|
|
70
|
+
export declare function imageReference(value: ImageValue): ImageAttachmentRef;
|
|
71
|
+
//# sourceMappingURL=tool.d.ts.map
|