@howaboua/pi-browser 0.0.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/CHANGELOG.md +9 -0
- package/LICENSE +22 -0
- package/README.md +47 -0
- package/biome.json +31 -0
- package/changelog.ts +337 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +82 -0
- package/dist/remote-worker.d.ts +2 -0
- package/dist/remote-worker.js +3005 -0
- package/dist/src/browser/artifacts.d.ts +13 -0
- package/dist/src/browser/artifacts.js +133 -0
- package/dist/src/browser/bounds.d.ts +4 -0
- package/dist/src/browser/bounds.js +129 -0
- package/dist/src/browser/config.d.ts +11 -0
- package/dist/src/browser/config.js +106 -0
- package/dist/src/browser/help.d.ts +1 -0
- package/dist/src/browser/help.js +27 -0
- package/dist/src/browser/launcher.d.ts +8 -0
- package/dist/src/browser/launcher.js +169 -0
- package/dist/src/browser/operation-executor.d.ts +9 -0
- package/dist/src/browser/operation-executor.js +112 -0
- package/dist/src/browser/operation.d.ts +92 -0
- package/dist/src/browser/operation.js +20 -0
- package/dist/src/browser/parse-operation.d.ts +6 -0
- package/dist/src/browser/parse-operation.js +248 -0
- package/dist/src/browser/remote-helper.d.ts +3 -0
- package/dist/src/browser/remote-helper.js +114 -0
- package/dist/src/browser/remote-process.d.ts +7 -0
- package/dist/src/browser/remote-process.js +78 -0
- package/dist/src/browser/remote.d.ts +4 -0
- package/dist/src/browser/remote.js +73 -0
- package/dist/src/browser/request.d.ts +8 -0
- package/dist/src/browser/request.js +80 -0
- package/dist/src/browser/routes.d.ts +16 -0
- package/dist/src/browser/routes.js +40 -0
- package/dist/src/browser/runtime.d.ts +17 -0
- package/dist/src/browser/runtime.js +61 -0
- package/dist/src/browser/settings.d.ts +2 -0
- package/dist/src/browser/settings.js +164 -0
- package/dist/src/browser/worker-server.d.ts +2 -0
- package/dist/src/browser/worker-server.js +241 -0
- package/dist/src/browser-parameters.d.ts +42 -0
- package/dist/src/browser-parameters.js +113 -0
- package/dist/src/browser-tool.d.ts +48 -0
- package/dist/src/browser-tool.js +71 -0
- package/dist/src/cdp/actions/click.d.ts +4 -0
- package/dist/src/cdp/actions/click.js +56 -0
- package/dist/src/cdp/actions/element.d.ts +22 -0
- package/dist/src/cdp/actions/element.js +126 -0
- package/dist/src/cdp/actions/page.d.ts +7 -0
- package/dist/src/cdp/actions/page.js +127 -0
- package/dist/src/cdp/actions/screenshot.d.ts +10 -0
- package/dist/src/cdp/actions/screenshot.js +96 -0
- package/dist/src/cdp/actions/selector.d.ts +2 -0
- package/dist/src/cdp/actions/selector.js +41 -0
- package/dist/src/cdp/actions/type.d.ts +3 -0
- package/dist/src/cdp/actions/type.js +138 -0
- package/dist/src/cdp/client.d.ts +20 -0
- package/dist/src/cdp/client.js +248 -0
- package/dist/src/cdp/discovery.d.ts +7 -0
- package/dist/src/cdp/discovery.js +153 -0
- package/dist/src/cdp/evaluate.d.ts +3 -0
- package/dist/src/cdp/evaluate.js +31 -0
- package/dist/src/cdp/pages.d.ts +3 -0
- package/dist/src/cdp/pages.js +40 -0
- package/dist/src/cdp/serial.d.ts +1 -0
- package/dist/src/cdp/serial.js +18 -0
- package/dist/src/cdp/session.d.ts +25 -0
- package/dist/src/cdp/session.js +246 -0
- package/dist/src/cdp/snapshot-contract.d.ts +32 -0
- package/dist/src/cdp/snapshot-contract.js +23 -0
- package/dist/src/cdp/snapshot.d.ts +3 -0
- package/dist/src/cdp/snapshot.js +205 -0
- package/dist/src/cdp/types.d.ts +20 -0
- package/dist/src/cdp/types.js +14 -0
- package/dist/src/cdp/url.d.ts +1 -0
- package/dist/src/cdp/url.js +12 -0
- package/index.ts +115 -0
- package/package.json +93 -0
- package/remote-worker.ts +58 -0
- package/src/browser/artifacts.ts +178 -0
- package/src/browser/bounds.ts +159 -0
- package/src/browser/config.ts +162 -0
- package/src/browser/help.ts +30 -0
- package/src/browser/launcher.ts +208 -0
- package/src/browser/operation-executor.ts +251 -0
- package/src/browser/operation.ts +105 -0
- package/src/browser/parse-operation.ts +272 -0
- package/src/browser/remote-helper.ts +137 -0
- package/src/browser/remote-process.ts +85 -0
- package/src/browser/remote.ts +120 -0
- package/src/browser/request.ts +95 -0
- package/src/browser/routes.ts +69 -0
- package/src/browser/runtime.ts +84 -0
- package/src/browser/settings.ts +219 -0
- package/src/browser/worker-server.ts +274 -0
- package/src/browser-parameters.ts +118 -0
- package/src/browser-tool.ts +88 -0
- package/src/cdp/actions/click.ts +126 -0
- package/src/cdp/actions/element.ts +234 -0
- package/src/cdp/actions/page.ts +219 -0
- package/src/cdp/actions/screenshot.ts +176 -0
- package/src/cdp/actions/selector.ts +63 -0
- package/src/cdp/actions/type.ts +224 -0
- package/src/cdp/client.ts +286 -0
- package/src/cdp/discovery.ts +198 -0
- package/src/cdp/evaluate.ts +55 -0
- package/src/cdp/pages.ts +60 -0
- package/src/cdp/serial.ts +23 -0
- package/src/cdp/session.ts +345 -0
- package/src/cdp/snapshot-contract.ts +63 -0
- package/src/cdp/snapshot.ts +273 -0
- package/src/cdp/types.ts +49 -0
- package/src/cdp/url.ts +11 -0
- package/tsconfig.json +7 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import { CdpClient } from "./client.js";
|
|
2
|
+
import {
|
|
3
|
+
getDisplayPrefixLength,
|
|
4
|
+
getWebSocketUrl,
|
|
5
|
+
resolvePrefix,
|
|
6
|
+
} from "./discovery.js";
|
|
7
|
+
import { getPages, waitForOpenedTarget } from "./pages.js";
|
|
8
|
+
import { waitForTurn } from "./serial.js";
|
|
9
|
+
import type { ElementRefs, PageInfo } from "./types.js";
|
|
10
|
+
import { asRecord } from "./types.js";
|
|
11
|
+
import { assertHttpUrl } from "./url.js";
|
|
12
|
+
|
|
13
|
+
const TAB_IDLE_MS = 20 * 60 * 1_000;
|
|
14
|
+
|
|
15
|
+
export interface ActiveTab {
|
|
16
|
+
cdp: CdpClient;
|
|
17
|
+
sessionId: string;
|
|
18
|
+
elementRefs: ElementRefs;
|
|
19
|
+
refId: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface PendingConnection<T> {
|
|
23
|
+
controller: AbortController;
|
|
24
|
+
promise: Promise<T>;
|
|
25
|
+
value?: T;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
class TabBridge {
|
|
29
|
+
readonly elementRefs: ElementRefs = new Map();
|
|
30
|
+
readonly targetId: string;
|
|
31
|
+
readonly cdp: CdpClient;
|
|
32
|
+
readonly sessionId: string;
|
|
33
|
+
private tail = Promise.resolve();
|
|
34
|
+
private idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
35
|
+
private closed = false;
|
|
36
|
+
private readonly onClose: () => void;
|
|
37
|
+
|
|
38
|
+
private constructor(
|
|
39
|
+
targetId: string,
|
|
40
|
+
cdp: CdpClient,
|
|
41
|
+
sessionId: string,
|
|
42
|
+
onClose: () => void,
|
|
43
|
+
) {
|
|
44
|
+
this.targetId = targetId;
|
|
45
|
+
this.cdp = cdp;
|
|
46
|
+
this.sessionId = sessionId;
|
|
47
|
+
this.onClose = onClose;
|
|
48
|
+
this.resetIdle();
|
|
49
|
+
cdp.onEvent("Target.targetDestroyed", (value) => {
|
|
50
|
+
const event = asRecord(value, "target destroyed event");
|
|
51
|
+
if (event["targetId"] === targetId) this.close(false);
|
|
52
|
+
});
|
|
53
|
+
cdp.onEvent("Target.detachedFromTarget", (value) => {
|
|
54
|
+
const event = asRecord(value, "target detached event");
|
|
55
|
+
if (event["sessionId"] === sessionId) this.close(false);
|
|
56
|
+
});
|
|
57
|
+
cdp.onClose(() => this.close(false));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
static async connect(
|
|
61
|
+
targetId: string,
|
|
62
|
+
onClose: () => void,
|
|
63
|
+
signal?: AbortSignal,
|
|
64
|
+
): Promise<TabBridge> {
|
|
65
|
+
const cdp = new CdpClient();
|
|
66
|
+
try {
|
|
67
|
+
await cdp.connect(await getWebSocketUrl(), signal);
|
|
68
|
+
const response = asRecord(
|
|
69
|
+
await cdp.send(
|
|
70
|
+
"Target.attachToTarget",
|
|
71
|
+
{ targetId, flatten: true },
|
|
72
|
+
undefined,
|
|
73
|
+
signal,
|
|
74
|
+
),
|
|
75
|
+
"Target.attachToTarget response",
|
|
76
|
+
);
|
|
77
|
+
if (typeof response["sessionId"] !== "string") {
|
|
78
|
+
throw new Error("Chrome did not return a tab session");
|
|
79
|
+
}
|
|
80
|
+
return new TabBridge(targetId, cdp, response["sessionId"], onClose);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
cdp.close();
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async run<T>(
|
|
88
|
+
refId: string,
|
|
89
|
+
signal: AbortSignal | undefined,
|
|
90
|
+
action: (tab: ActiveTab) => Promise<T>,
|
|
91
|
+
): Promise<T> {
|
|
92
|
+
if (this.closed) throw new Error("Tab bridge is closed");
|
|
93
|
+
let release!: () => void;
|
|
94
|
+
const turn = new Promise<void>((resolveValue) => {
|
|
95
|
+
release = resolveValue;
|
|
96
|
+
});
|
|
97
|
+
const previous = this.tail;
|
|
98
|
+
this.tail = previous.then(
|
|
99
|
+
() => turn,
|
|
100
|
+
() => turn,
|
|
101
|
+
);
|
|
102
|
+
try {
|
|
103
|
+
await waitForTurn(previous, signal);
|
|
104
|
+
if (this.closed) throw new Error("Tab bridge is closed");
|
|
105
|
+
this.resetIdle();
|
|
106
|
+
return await action({
|
|
107
|
+
cdp: this.cdp,
|
|
108
|
+
sessionId: this.sessionId,
|
|
109
|
+
elementRefs: this.elementRefs,
|
|
110
|
+
refId,
|
|
111
|
+
});
|
|
112
|
+
} finally {
|
|
113
|
+
release();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
close(detach = true): void {
|
|
118
|
+
if (this.closed) return;
|
|
119
|
+
this.closed = true;
|
|
120
|
+
if (this.idleTimer) clearTimeout(this.idleTimer);
|
|
121
|
+
this.elementRefs.clear();
|
|
122
|
+
if (detach) {
|
|
123
|
+
void this.cdp
|
|
124
|
+
.send(
|
|
125
|
+
"Target.detachFromTarget",
|
|
126
|
+
{ sessionId: this.sessionId },
|
|
127
|
+
undefined,
|
|
128
|
+
undefined,
|
|
129
|
+
)
|
|
130
|
+
.catch(() => undefined)
|
|
131
|
+
.finally(() => this.cdp.close());
|
|
132
|
+
} else {
|
|
133
|
+
this.cdp.close();
|
|
134
|
+
}
|
|
135
|
+
this.onClose();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private resetIdle(): void {
|
|
139
|
+
if (this.idleTimer) clearTimeout(this.idleTimer);
|
|
140
|
+
this.idleTimer = setTimeout(() => this.close(), TAB_IDLE_MS);
|
|
141
|
+
this.idleTimer.unref?.();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export class BrowserCdpSession {
|
|
146
|
+
private root: CdpClient | undefined;
|
|
147
|
+
private rootPending: PendingConnection<CdpClient> | undefined;
|
|
148
|
+
private readonly tabs = new Map<string, TabBridge>();
|
|
149
|
+
private readonly tabPromises = new Map<
|
|
150
|
+
string,
|
|
151
|
+
PendingConnection<TabBridge>
|
|
152
|
+
>();
|
|
153
|
+
|
|
154
|
+
async pages(signal?: AbortSignal): Promise<PageInfo[]> {
|
|
155
|
+
return getPages(await this.rootConnection(signal), signal);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async open(
|
|
159
|
+
url: string,
|
|
160
|
+
signal?: AbortSignal,
|
|
161
|
+
): Promise<{
|
|
162
|
+
refId: string;
|
|
163
|
+
}> {
|
|
164
|
+
assertHttpUrl(url);
|
|
165
|
+
const root = await this.rootConnection(signal);
|
|
166
|
+
const response = asRecord(
|
|
167
|
+
await root.send("Target.createTarget", { url }, undefined, signal),
|
|
168
|
+
"Target.createTarget response",
|
|
169
|
+
);
|
|
170
|
+
if (typeof response["targetId"] !== "string") {
|
|
171
|
+
throw new Error("Chrome did not return a new tab target");
|
|
172
|
+
}
|
|
173
|
+
const page = await waitForOpenedTarget(
|
|
174
|
+
root,
|
|
175
|
+
response["targetId"],
|
|
176
|
+
url,
|
|
177
|
+
5_000,
|
|
178
|
+
signal,
|
|
179
|
+
);
|
|
180
|
+
const pages = await getPages(root, signal);
|
|
181
|
+
if (!pages.some((candidate) => candidate.targetId === page.targetId)) {
|
|
182
|
+
pages.push(page);
|
|
183
|
+
}
|
|
184
|
+
const prefixLength = getDisplayPrefixLength(
|
|
185
|
+
pages.map((candidate) => candidate.targetId),
|
|
186
|
+
);
|
|
187
|
+
return {
|
|
188
|
+
refId: page.targetId.slice(0, prefixLength),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async withTab<T>(
|
|
193
|
+
refId: string,
|
|
194
|
+
signal: AbortSignal | undefined,
|
|
195
|
+
action: (tab: ActiveTab) => Promise<T>,
|
|
196
|
+
): Promise<T> {
|
|
197
|
+
const pages = await this.pages(signal);
|
|
198
|
+
const targetId = resolvePrefix(
|
|
199
|
+
refId,
|
|
200
|
+
pages.map((page) => page.targetId),
|
|
201
|
+
"target",
|
|
202
|
+
"Run tabs.",
|
|
203
|
+
);
|
|
204
|
+
let bridge = this.tabs.get(targetId);
|
|
205
|
+
if (!bridge) {
|
|
206
|
+
let pending = this.tabPromises.get(targetId);
|
|
207
|
+
if (!pending) {
|
|
208
|
+
const controller = new AbortController();
|
|
209
|
+
const promise = this.connectTab(targetId, controller.signal);
|
|
210
|
+
pending = { controller, promise };
|
|
211
|
+
this.tabPromises.set(targetId, pending);
|
|
212
|
+
void promise.then(
|
|
213
|
+
(value) => {
|
|
214
|
+
pending!.value = value;
|
|
215
|
+
},
|
|
216
|
+
() => {
|
|
217
|
+
if (this.tabPromises.get(targetId) === pending) {
|
|
218
|
+
this.tabPromises.delete(targetId);
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
const connected = await waitForTurn(pending.promise, signal);
|
|
224
|
+
bridge = this.tabs.get(targetId);
|
|
225
|
+
if (!bridge) {
|
|
226
|
+
if (this.tabPromises.get(targetId) !== pending) {
|
|
227
|
+
connected.close();
|
|
228
|
+
throw new Error("Tab bridge was stopped while connecting");
|
|
229
|
+
}
|
|
230
|
+
this.tabPromises.delete(targetId);
|
|
231
|
+
this.tabs.set(targetId, connected);
|
|
232
|
+
bridge = connected;
|
|
233
|
+
} else if (bridge !== connected) {
|
|
234
|
+
connected.close();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const prefixLength = getDisplayPrefixLength(
|
|
238
|
+
pages.map((page) => page.targetId),
|
|
239
|
+
);
|
|
240
|
+
return bridge.run(targetId.slice(0, prefixLength), signal, action);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async stop(refId?: string): Promise<void> {
|
|
244
|
+
if (!refId) {
|
|
245
|
+
for (const targetId of this.tabPromises.keys()) {
|
|
246
|
+
this.stopPendingTab(targetId, "All tab bridges were stopped");
|
|
247
|
+
}
|
|
248
|
+
for (const bridge of this.tabs.values()) bridge.close();
|
|
249
|
+
this.tabs.clear();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const pages = await this.pages();
|
|
253
|
+
const targetId = resolvePrefix(
|
|
254
|
+
refId,
|
|
255
|
+
pages.map((page) => page.targetId),
|
|
256
|
+
"target",
|
|
257
|
+
);
|
|
258
|
+
this.stopPendingTab(targetId, "Tab bridge " + refId + " was stopped");
|
|
259
|
+
this.tabs.get(targetId)?.close();
|
|
260
|
+
this.tabs.delete(targetId);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
close(): void {
|
|
264
|
+
for (const targetId of this.tabPromises.keys()) {
|
|
265
|
+
this.stopPendingTab(targetId, "Browser session closed");
|
|
266
|
+
}
|
|
267
|
+
for (const bridge of this.tabs.values()) bridge.close();
|
|
268
|
+
this.tabs.clear();
|
|
269
|
+
const rootPending = this.rootPending;
|
|
270
|
+
this.rootPending = undefined;
|
|
271
|
+
if (rootPending) {
|
|
272
|
+
rootPending.controller.abort(new Error("Browser session closed"));
|
|
273
|
+
void rootPending.promise.then(
|
|
274
|
+
(client) => client.close(),
|
|
275
|
+
() => undefined,
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
this.root?.close();
|
|
279
|
+
this.root = undefined;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private async rootConnection(signal?: AbortSignal): Promise<CdpClient> {
|
|
283
|
+
if (this.root) return this.root;
|
|
284
|
+
let pending = this.rootPending;
|
|
285
|
+
if (!pending) {
|
|
286
|
+
const controller = new AbortController();
|
|
287
|
+
const promise = this.connectRoot(controller.signal);
|
|
288
|
+
pending = { controller, promise };
|
|
289
|
+
this.rootPending = pending;
|
|
290
|
+
void promise.then(
|
|
291
|
+
(value) => {
|
|
292
|
+
pending!.value = value;
|
|
293
|
+
if (this.rootPending === pending) this.rootPending = undefined;
|
|
294
|
+
},
|
|
295
|
+
() => {
|
|
296
|
+
if (this.rootPending === pending) this.rootPending = undefined;
|
|
297
|
+
},
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
return waitForTurn(pending.promise, signal);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private async connectTab(
|
|
304
|
+
targetId: string,
|
|
305
|
+
signal?: AbortSignal,
|
|
306
|
+
): Promise<TabBridge> {
|
|
307
|
+
let bridge: TabBridge | undefined;
|
|
308
|
+
bridge = await TabBridge.connect(
|
|
309
|
+
targetId,
|
|
310
|
+
() => {
|
|
311
|
+
if (bridge && this.tabs.get(targetId) === bridge) {
|
|
312
|
+
this.tabs.delete(targetId);
|
|
313
|
+
}
|
|
314
|
+
const pending = this.tabPromises.get(targetId);
|
|
315
|
+
if (bridge && pending?.value === bridge) {
|
|
316
|
+
this.tabPromises.delete(targetId);
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
signal,
|
|
320
|
+
);
|
|
321
|
+
return bridge;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private stopPendingTab(targetId: string, message: string): void {
|
|
325
|
+
const pending = this.tabPromises.get(targetId);
|
|
326
|
+
if (!pending) return;
|
|
327
|
+
this.tabPromises.delete(targetId);
|
|
328
|
+
pending.controller.abort(new Error(message));
|
|
329
|
+
void pending.promise.then(
|
|
330
|
+
(bridge) => bridge.close(),
|
|
331
|
+
() => undefined,
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private async connectRoot(signal: AbortSignal): Promise<CdpClient> {
|
|
336
|
+
const client = new CdpClient();
|
|
337
|
+
await client.connect(await getWebSocketUrl(), signal);
|
|
338
|
+
this.root = client;
|
|
339
|
+
client.onClose(() => {
|
|
340
|
+
if (this.root !== client) return;
|
|
341
|
+
this.root = undefined;
|
|
342
|
+
});
|
|
343
|
+
return client;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export type SnapshotResponseLength = "short" | "medium" | "long";
|
|
2
|
+
|
|
3
|
+
export const SNAPSHOT_LIMITS: Record<SnapshotResponseLength, number> = {
|
|
4
|
+
short: 60,
|
|
5
|
+
medium: 140,
|
|
6
|
+
long: 300,
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export interface SnapshotLine {
|
|
10
|
+
line: number;
|
|
11
|
+
text: string;
|
|
12
|
+
element_id?: number | undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface SnapshotElement {
|
|
16
|
+
id: number;
|
|
17
|
+
role: string;
|
|
18
|
+
name?: string | undefined;
|
|
19
|
+
value?: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface SnapshotResult {
|
|
23
|
+
ref_id?: string | undefined;
|
|
24
|
+
title: string;
|
|
25
|
+
url: string;
|
|
26
|
+
lineno: number;
|
|
27
|
+
content: SnapshotLine[];
|
|
28
|
+
elements: SnapshotElement[];
|
|
29
|
+
pattern?: string | undefined;
|
|
30
|
+
next_lineno?: number | undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface SnapshotOptions {
|
|
34
|
+
refId?: string | undefined;
|
|
35
|
+
pattern?: string | undefined;
|
|
36
|
+
lineno?: number | string | undefined;
|
|
37
|
+
responseLength?: SnapshotResponseLength | string | undefined;
|
|
38
|
+
signal?: AbortSignal | undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function positiveInteger(value: number | string, label: string): number {
|
|
42
|
+
const source = String(value);
|
|
43
|
+
if (!/^[1-9]\d*$/.test(source)) {
|
|
44
|
+
throw new Error(`${label} must be a positive integer`);
|
|
45
|
+
}
|
|
46
|
+
const parsed = Number(source);
|
|
47
|
+
if (!Number.isSafeInteger(parsed)) {
|
|
48
|
+
throw new Error(`${label} must be a safe positive integer`);
|
|
49
|
+
}
|
|
50
|
+
return parsed;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function snapshotResponseLength(
|
|
54
|
+
value: string | undefined,
|
|
55
|
+
): SnapshotResponseLength {
|
|
56
|
+
const resolved = value ?? "medium";
|
|
57
|
+
if (resolved !== "short" && resolved !== "medium" && resolved !== "long") {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`response length must be one of: ${Object.keys(SNAPSHOT_LIMITS).join(", ")}`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return resolved;
|
|
63
|
+
}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { evaluate } from "./evaluate.js";
|
|
2
|
+
import {
|
|
3
|
+
positiveInteger,
|
|
4
|
+
SNAPSHOT_LIMITS,
|
|
5
|
+
type SnapshotElement,
|
|
6
|
+
type SnapshotLine,
|
|
7
|
+
type SnapshotOptions,
|
|
8
|
+
type SnapshotResult,
|
|
9
|
+
snapshotResponseLength,
|
|
10
|
+
} from "./snapshot-contract.js";
|
|
11
|
+
import type { CdpConnection, ElementRefs } from "./types.js";
|
|
12
|
+
import { asRecord } from "./types.js";
|
|
13
|
+
|
|
14
|
+
interface AxValue {
|
|
15
|
+
value?: unknown;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface AxNode {
|
|
19
|
+
nodeId: string;
|
|
20
|
+
parentId?: string | undefined;
|
|
21
|
+
childIds?: string[] | undefined;
|
|
22
|
+
backendDOMNodeId?: number | undefined;
|
|
23
|
+
ignored?: boolean | undefined;
|
|
24
|
+
role?: AxValue | undefined;
|
|
25
|
+
name?: AxValue | undefined;
|
|
26
|
+
value?: AxValue | undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const INTERACTIVE_ROLES = new Set([
|
|
30
|
+
"button",
|
|
31
|
+
"checkbox",
|
|
32
|
+
"combobox",
|
|
33
|
+
"link",
|
|
34
|
+
"listbox",
|
|
35
|
+
"menuitem",
|
|
36
|
+
"option",
|
|
37
|
+
"menuitemcheckbox",
|
|
38
|
+
"menuitemradio",
|
|
39
|
+
"radio",
|
|
40
|
+
"searchbox",
|
|
41
|
+
"slider",
|
|
42
|
+
"spinbutton",
|
|
43
|
+
"switch",
|
|
44
|
+
"tab",
|
|
45
|
+
"textbox",
|
|
46
|
+
"treeitem",
|
|
47
|
+
]);
|
|
48
|
+
const NEXT_ELEMENT_IDS = new WeakMap<ElementRefs, number>();
|
|
49
|
+
|
|
50
|
+
function axNode(value: unknown): AxNode {
|
|
51
|
+
const record = asRecord(value, "accessibility node");
|
|
52
|
+
if (typeof record["nodeId"] !== "string") {
|
|
53
|
+
throw new Error("Accessibility node has no nodeId");
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
nodeId: record["nodeId"],
|
|
57
|
+
...(typeof record["parentId"] === "string"
|
|
58
|
+
? { parentId: record["parentId"] }
|
|
59
|
+
: {}),
|
|
60
|
+
...(Array.isArray(record["childIds"])
|
|
61
|
+
? {
|
|
62
|
+
childIds: record["childIds"].filter(
|
|
63
|
+
(id): id is string => typeof id === "string",
|
|
64
|
+
),
|
|
65
|
+
}
|
|
66
|
+
: {}),
|
|
67
|
+
...(typeof record["backendDOMNodeId"] === "number"
|
|
68
|
+
? { backendDOMNodeId: record["backendDOMNodeId"] }
|
|
69
|
+
: {}),
|
|
70
|
+
...(typeof record["ignored"] === "boolean"
|
|
71
|
+
? { ignored: record["ignored"] }
|
|
72
|
+
: {}),
|
|
73
|
+
...(record["role"] ? { role: asRecord(record["role"]) } : {}),
|
|
74
|
+
...(record["name"] ? { name: asRecord(record["name"]) } : {}),
|
|
75
|
+
...(record["value"] ? { value: asRecord(record["value"]) } : {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function shouldShow(node: AxNode): boolean {
|
|
80
|
+
const role = String(node.role?.value ?? "");
|
|
81
|
+
const name = node.name?.value ?? "";
|
|
82
|
+
const value = node.value?.value;
|
|
83
|
+
if (role === "InlineTextBox") return false;
|
|
84
|
+
return (
|
|
85
|
+
role !== "none" &&
|
|
86
|
+
role !== "generic" &&
|
|
87
|
+
!(name === "" && (value === "" || value == null))
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function orderedChildren(
|
|
92
|
+
node: AxNode,
|
|
93
|
+
nodesById: Map<string, AxNode>,
|
|
94
|
+
childrenByParent: Map<string, AxNode[]>,
|
|
95
|
+
): AxNode[] {
|
|
96
|
+
const children: AxNode[] = [];
|
|
97
|
+
const seen = new Set<string>();
|
|
98
|
+
for (const childId of node.childIds ?? []) {
|
|
99
|
+
const child = nodesById.get(childId);
|
|
100
|
+
if (child && !seen.has(child.nodeId)) {
|
|
101
|
+
seen.add(child.nodeId);
|
|
102
|
+
children.push(child);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const child of childrenByParent.get(node.nodeId) ?? []) {
|
|
106
|
+
if (!seen.has(child.nodeId)) {
|
|
107
|
+
seen.add(child.nodeId);
|
|
108
|
+
children.push(child);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return children;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function normalizeText(value: unknown): string {
|
|
115
|
+
return String(value ?? "")
|
|
116
|
+
.replace(/\s+/g, " ")
|
|
117
|
+
.trim();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function splitText(value: unknown, max = 700): string[] {
|
|
121
|
+
const text = normalizeText(value);
|
|
122
|
+
if (!text) return [];
|
|
123
|
+
const parts: string[] = [];
|
|
124
|
+
for (let start = 0; start < text.length; start += max) {
|
|
125
|
+
parts.push(text.slice(start, start + max));
|
|
126
|
+
}
|
|
127
|
+
return parts;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export async function snapshotData(
|
|
131
|
+
cdp: CdpConnection,
|
|
132
|
+
sessionId: string,
|
|
133
|
+
elementRefs: ElementRefs,
|
|
134
|
+
options: SnapshotOptions = {},
|
|
135
|
+
): Promise<SnapshotResult> {
|
|
136
|
+
const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
|
|
137
|
+
const responseLength = snapshotResponseLength(options.responseLength);
|
|
138
|
+
const response = asRecord(
|
|
139
|
+
await cdp.send(
|
|
140
|
+
"Accessibility.getFullAXTree",
|
|
141
|
+
{},
|
|
142
|
+
sessionId,
|
|
143
|
+
options.signal,
|
|
144
|
+
),
|
|
145
|
+
"Accessibility response",
|
|
146
|
+
);
|
|
147
|
+
if (!Array.isArray(response["nodes"])) {
|
|
148
|
+
throw new Error("Accessibility response has no nodes");
|
|
149
|
+
}
|
|
150
|
+
const nodes = response["nodes"].map(axNode);
|
|
151
|
+
const nodesById = new Map(nodes.map((node) => [node.nodeId, node]));
|
|
152
|
+
const childrenByParent = new Map<string, AxNode[]>();
|
|
153
|
+
for (const node of nodes) {
|
|
154
|
+
if (!node.parentId) continue;
|
|
155
|
+
const children = childrenByParent.get(node.parentId) ?? [];
|
|
156
|
+
children.push(node);
|
|
157
|
+
childrenByParent.set(node.parentId, children);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
elementRefs.clear();
|
|
161
|
+
type InternalLine = SnapshotLine & { kind: string };
|
|
162
|
+
const lines: InternalLine[] = [];
|
|
163
|
+
const elements: SnapshotElement[] = [];
|
|
164
|
+
const visited = new Set<string>();
|
|
165
|
+
const nextElementId = () => {
|
|
166
|
+
const id = NEXT_ELEMENT_IDS.get(elementRefs) ?? 1;
|
|
167
|
+
if (!Number.isSafeInteger(id)) {
|
|
168
|
+
throw new Error("Element id limit reached; restart the tab bridge");
|
|
169
|
+
}
|
|
170
|
+
NEXT_ELEMENT_IDS.set(elementRefs, id + 1);
|
|
171
|
+
return id;
|
|
172
|
+
};
|
|
173
|
+
const addLine = (text: string, element?: SnapshotElement, kind = "text") => {
|
|
174
|
+
for (const part of splitText(text)) {
|
|
175
|
+
lines.push({
|
|
176
|
+
line: lines.length + 1,
|
|
177
|
+
text: part,
|
|
178
|
+
kind,
|
|
179
|
+
...(element ? { element_id: element.id } : {}),
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const addStaticText = (text: string) => {
|
|
184
|
+
const normalized = normalizeText(text);
|
|
185
|
+
if (!normalized) return;
|
|
186
|
+
const previous = lines.at(-1);
|
|
187
|
+
if (
|
|
188
|
+
previous?.kind === "text" &&
|
|
189
|
+
previous.text.length + normalized.length + 1 <= 700
|
|
190
|
+
) {
|
|
191
|
+
previous.text += ` ${normalized}`;
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
addLine(normalized);
|
|
195
|
+
};
|
|
196
|
+
const visit = (node: AxNode | undefined, parentName = ""): void => {
|
|
197
|
+
if (!node || visited.has(node.nodeId)) return;
|
|
198
|
+
visited.add(node.nodeId);
|
|
199
|
+
const role = String(node.role?.value ?? "");
|
|
200
|
+
const name = normalizeText(node.name?.value ?? "");
|
|
201
|
+
const value = node.value?.value;
|
|
202
|
+
let renderedName = parentName;
|
|
203
|
+
if (!node.ignored && shouldShow(node)) {
|
|
204
|
+
if (INTERACTIVE_ROLES.has(role) && node.backendDOMNodeId) {
|
|
205
|
+
const element: SnapshotElement = {
|
|
206
|
+
id: nextElementId(),
|
|
207
|
+
role,
|
|
208
|
+
...(name ? { name } : {}),
|
|
209
|
+
...(value === "" || value == null ? {} : { value }),
|
|
210
|
+
};
|
|
211
|
+
elementRefs.set(element.id, node.backendDOMNodeId);
|
|
212
|
+
elements.push(element);
|
|
213
|
+
addLine(
|
|
214
|
+
`[${element.id}] ${role}${name ? ` ${name}` : ""}${
|
|
215
|
+
value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`
|
|
216
|
+
}`,
|
|
217
|
+
element,
|
|
218
|
+
"interactive",
|
|
219
|
+
);
|
|
220
|
+
renderedName = name;
|
|
221
|
+
} else if (role === "StaticText") {
|
|
222
|
+
if (name && name !== parentName) addStaticText(name);
|
|
223
|
+
} else if (role === "heading" || role === "image") {
|
|
224
|
+
if (name) addLine(`${role}: ${name}`, undefined, role);
|
|
225
|
+
renderedName = name || parentName;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
for (const child of orderedChildren(node, nodesById, childrenByParent)) {
|
|
229
|
+
visit(child, renderedName);
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
for (const root of nodes.filter(
|
|
234
|
+
(node) => !node.parentId || !nodesById.has(node.parentId),
|
|
235
|
+
)) {
|
|
236
|
+
visit(root);
|
|
237
|
+
}
|
|
238
|
+
for (const node of nodes) visit(node);
|
|
239
|
+
|
|
240
|
+
const metadata = asRecord(
|
|
241
|
+
await evaluate(
|
|
242
|
+
cdp,
|
|
243
|
+
sessionId,
|
|
244
|
+
"({title: document.title, url: location.href})",
|
|
245
|
+
options.signal,
|
|
246
|
+
),
|
|
247
|
+
"page metadata",
|
|
248
|
+
);
|
|
249
|
+
const pattern = options.pattern?.toLowerCase();
|
|
250
|
+
const matching = pattern
|
|
251
|
+
? lines.filter((line) => line.text.toLowerCase().includes(pattern))
|
|
252
|
+
: lines;
|
|
253
|
+
const start = lineno - 1;
|
|
254
|
+
const content = matching
|
|
255
|
+
.slice(start, start + SNAPSHOT_LIMITS[responseLength])
|
|
256
|
+
.map(({ kind: _kind, ...line }) => line);
|
|
257
|
+
const visibleIds = new Set(
|
|
258
|
+
content.flatMap((line) =>
|
|
259
|
+
line.element_id === undefined ? [] : [line.element_id],
|
|
260
|
+
),
|
|
261
|
+
);
|
|
262
|
+
const hasMore = start + content.length < matching.length;
|
|
263
|
+
return {
|
|
264
|
+
...(options.refId ? { ref_id: options.refId } : {}),
|
|
265
|
+
title: typeof metadata["title"] === "string" ? metadata["title"] : "",
|
|
266
|
+
url: typeof metadata["url"] === "string" ? metadata["url"] : "",
|
|
267
|
+
lineno: start + 1,
|
|
268
|
+
content,
|
|
269
|
+
elements: elements.filter((element) => visibleIds.has(element.id)),
|
|
270
|
+
...(options.pattern ? { pattern: options.pattern } : {}),
|
|
271
|
+
...(hasMore ? { next_lineno: start + content.length + 1 } : {}),
|
|
272
|
+
};
|
|
273
|
+
}
|