-
Notifications
You must be signed in to change notification settings - Fork 616
/
Copy pathutils.ts
764 lines (703 loc) · 21.2 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
import { AccessibilityNode, TreeResult, AXNode } from "../../types/context";
import { StagehandPage } from "../StagehandPage";
import { LogLine } from "../../types/log";
import { CDPSession, Page, Locator } from "playwright";
import {
PlaywrightCommandMethodNotSupportedException,
PlaywrightCommandException,
} from "@/types/playwright";
// Parser function for str output
export function formatSimplifiedTree(
node: AccessibilityNode,
level = 0,
): string {
const indent = " ".repeat(level);
let result = `${indent}[${node.nodeId}] ${node.role}${
node.name ? `: ${node.name}` : ""
}\n`;
if (node.children?.length) {
result += node.children
.map((child) => formatSimplifiedTree(child, level + 1))
.join("");
}
return result;
}
/**
* Helper function to remove or collapse unnecessary structural nodes
* Handles three cases:
* 1. Removes generic/none nodes with no children
* 2. Collapses generic/none nodes with single child
* 3. Keeps generic/none nodes with multiple children but cleans their subtrees
* and attempts to resolve their role to a DOM tag name
*/
async function cleanStructuralNodes(
node: AccessibilityNode,
page?: StagehandPage,
logger?: (logLine: LogLine) => void,
): Promise<AccessibilityNode | null> {
// 1) Filter out nodes with negative IDs
if (node.nodeId && parseInt(node.nodeId) < 0) {
return null;
}
// 2) Base case: if no children exist, this is effectively a leaf.
// If it's "generic" or "none", we remove it; otherwise, keep it.
if (!node.children || node.children.length === 0) {
return node.role === "generic" || node.role === "none" ? null : node;
}
// 3) Recursively clean children
const cleanedChildrenPromises = node.children.map((child) =>
cleanStructuralNodes(child, page, logger),
);
const resolvedChildren = await Promise.all(cleanedChildrenPromises);
const cleanedChildren = resolvedChildren.filter(
(child): child is AccessibilityNode => child !== null,
);
// 4) **Prune** "generic" or "none" nodes first,
// before resolving them to their tag names.
if (node.role === "generic" || node.role === "none") {
if (cleanedChildren.length === 1) {
// Collapse single-child structural node
return cleanedChildren[0];
} else if (cleanedChildren.length === 0) {
// Remove empty structural node
return null;
}
// If we have multiple children, we keep this node as a container.
// We'll update role below if needed.
}
// 5) If we still have a "generic"/"none" node after pruning
// (i.e., because it had multiple children), now we try
// to resolve and replace its role with the DOM tag name.
if (
page &&
logger &&
node.backendDOMNodeId !== undefined &&
(node.role === "generic" || node.role === "none")
) {
try {
const { object } = await page.sendCDP<{
object: { objectId?: string };
}>("DOM.resolveNode", {
backendNodeId: node.backendDOMNodeId,
});
if (object && object.objectId) {
try {
// Get the tagName for the node
const { result } = await page.sendCDP<{
result: { type: string; value?: string };
}>("Runtime.callFunctionOn", {
objectId: object.objectId,
functionDeclaration: `
function() {
return this.tagName ? this.tagName.toLowerCase() : "";
}
`,
returnByValue: true,
});
// If we got a tagName, update the node's role
if (result?.value) {
node.role = result.value;
}
} catch (tagNameError) {
logger({
category: "observation",
message: `Could not fetch tagName for node ${node.backendDOMNodeId}`,
level: 2,
auxiliary: {
error: {
value: tagNameError.message,
type: "string",
},
},
});
}
}
} catch (resolveError) {
logger({
category: "observation",
message: `Could not resolve DOM node ID ${node.backendDOMNodeId}`,
level: 2,
auxiliary: {
error: {
value: resolveError.message,
type: "string",
},
},
});
}
}
// 6) Return the updated node.
// If it has children, update them; otherwise keep it as-is.
return cleanedChildren.length > 0
? { ...node, children: cleanedChildren }
: node;
}
/**
* Builds a hierarchical tree structure from a flat array of accessibility nodes.
* The function processes nodes in multiple passes to create a clean, meaningful tree.
* @param nodes - Flat array of accessibility nodes from the CDP
* @returns Object containing both the tree structure and a simplified string representation
*/
export async function buildHierarchicalTree(
nodes: AccessibilityNode[],
page?: StagehandPage,
logger?: (logLine: LogLine) => void,
): Promise<TreeResult> {
// Map to store processed nodes for quick lookup
const nodeMap = new Map<string, AccessibilityNode>();
const iframe_list: AccessibilityNode[] = [];
// First pass: Create nodes that are meaningful
// We only keep nodes that either have a name or children to avoid cluttering the tree
nodes.forEach((node) => {
// Skip node if its ID is negative (e.g., "-1000002014")
const nodeIdValue = parseInt(node.nodeId, 10);
if (nodeIdValue < 0) {
return;
}
const hasChildren = node.childIds && node.childIds.length > 0;
const hasValidName = node.name && node.name.trim() !== "";
const isInteractive =
node.role !== "none" &&
node.role !== "generic" &&
node.role !== "InlineTextBox"; //add other interactive roles here
// Include nodes that are either named, have children, or are interactive
if (!hasValidName && !hasChildren && !isInteractive) {
return;
}
// Create a clean node object with only relevant properties
nodeMap.set(node.nodeId, {
role: node.role,
nodeId: node.nodeId,
...(hasValidName && { name: node.name }), // Only include name if it exists and isn't empty
...(node.description && { description: node.description }),
...(node.value && { value: node.value }),
...(node.backendDOMNodeId !== undefined && {
backendDOMNodeId: node.backendDOMNodeId,
}),
});
});
// Second pass: Establish parent-child relationships
// This creates the actual tree structure by connecting nodes based on parentId
nodes.forEach((node) => {
// Add iframes to a list and include in the return object
const isIframe = node.role === "Iframe";
if (isIframe) {
const iframeNode = {
role: node.role,
nodeId: node.nodeId,
};
iframe_list.push(iframeNode);
}
if (node.parentId && nodeMap.has(node.nodeId)) {
const parentNode = nodeMap.get(node.parentId);
const currentNode = nodeMap.get(node.nodeId);
if (parentNode && currentNode) {
if (!parentNode.children) {
parentNode.children = [];
}
parentNode.children.push(currentNode);
}
}
});
// Final pass: Build the root-level tree and clean up structural nodes
const rootNodes = nodes
.filter((node) => !node.parentId && nodeMap.has(node.nodeId)) // Get root nodes
.map((node) => nodeMap.get(node.nodeId))
.filter(Boolean) as AccessibilityNode[];
const cleanedTreePromises = rootNodes.map((node) =>
cleanStructuralNodes(node, page, logger),
);
const finalTree = (await Promise.all(cleanedTreePromises)).filter(
Boolean,
) as AccessibilityNode[];
// Generate a simplified string representation of the tree
const simplifiedFormat = finalTree
.map((node) => formatSimplifiedTree(node))
.join("\n");
return {
tree: finalTree,
simplified: simplifiedFormat,
iframes: iframe_list,
};
}
/**
* Retrieves the full accessibility tree via CDP and transforms it into a hierarchical structure.
*
* DO NOT USE THIS FUNCTION DIRECTLY.
* Instead, use `StagehandPage.getAccessibilityTree()`
*/
export async function getAccessibilityTree(
page: StagehandPage,
logger: (logLine: LogLine) => void,
): Promise<TreeResult> {
await page.enableCDP("Accessibility");
try {
// Identify which elements are scrollable and get their backendNodeIds
const scrollableBackendIds = await findScrollableElementIds(page);
// Fetch the full accessibility tree from Chrome DevTools Protocol
const { nodes } = await page.sendCDP<{ nodes: AXNode[] }>(
"Accessibility.getFullAXTree",
);
const startTime = Date.now();
// Transform into hierarchical structure
const hierarchicalTree = await buildHierarchicalTree(
nodes.map((node) => {
let roleValue = node.role?.value || "";
if (scrollableBackendIds.has(node.backendDOMNodeId)) {
if (roleValue === "generic" || roleValue === "none") {
roleValue = "scrollable";
} else {
roleValue = roleValue ? `scrollable, ${roleValue}` : "scrollable";
}
}
return {
role: roleValue,
name: node.name?.value,
description: node.description?.value,
value: node.value?.value,
nodeId: node.nodeId,
backendDOMNodeId: node.backendDOMNodeId,
parentId: node.parentId,
childIds: node.childIds,
};
}),
page,
logger,
);
logger({
category: "observation",
message: `got accessibility tree in ${Date.now() - startTime}ms`,
level: 1,
});
return hierarchicalTree;
} catch (error) {
logger({
category: "observation",
message: "Error getting accessibility tree",
level: 1,
auxiliary: {
error: {
value: error.message,
type: "string",
},
trace: {
value: error.stack,
type: "string",
},
},
});
throw error;
} finally {
await page.disableCDP("Accessibility");
}
}
// This function is wrapped into a string and sent as a CDP command
// It is not meant to be actually executed here
const functionString = `
function getNodePath(el) {
if (!el || (el.nodeType !== Node.ELEMENT_NODE && el.nodeType !== Node.TEXT_NODE)) {
console.log("el is not a valid node type");
return "";
}
const parts = [];
let current = el;
while (current && (current.nodeType === Node.ELEMENT_NODE || current.nodeType === Node.TEXT_NODE)) {
let index = 0;
let hasSameTypeSiblings = false;
const siblings = current.parentElement
? Array.from(current.parentElement.childNodes)
: [];
for (let i = 0; i < siblings.length; i++) {
const sibling = siblings[i];
if (
sibling.nodeType === current.nodeType &&
sibling.nodeName === current.nodeName
) {
index = index + 1;
hasSameTypeSiblings = true;
if (sibling.isSameNode(current)) {
break;
}
}
}
if (!current || !current.parentNode) break;
if (current.nodeName.toLowerCase() === "html"){
parts.unshift("html");
break;
}
// text nodes are handled differently in XPath
if (current.nodeName !== "#text") {
const tagName = current.nodeName.toLowerCase();
const pathIndex = hasSameTypeSiblings ? \`[\${index}]\` : "";
parts.unshift(\`\${tagName}\${pathIndex}\`);
}
current = current.parentElement;
}
return parts.length ? \`/\${parts.join("/")}\` : "";
}`;
export async function getXPathByResolvedObjectId(
cdpClient: CDPSession,
resolvedObjectId: string,
): Promise<string> {
const { result } = await cdpClient.send("Runtime.callFunctionOn", {
objectId: resolvedObjectId,
functionDeclaration: `function() {
${functionString}
return getNodePath(this);
}`,
returnByValue: true,
});
return result.value || "";
}
/**
* `findScrollableElementIds` is a function that identifies elements in
* the browser that are deemed "scrollable". At a high level, it does the
* following:
* - Calls the browser-side `window.getScrollableElementXpaths()` function,
* which returns a list of XPaths for scrollable containers.
* - Iterates over the returned list of XPaths, locating each element in the DOM
* using `stagehandPage.sendCDP(...)`
* - During each iteration, we call `Runtime.evaluate` to run `document.evaluate(...)`
* with each XPath, obtaining a `RemoteObject` reference if it exists.
* - Then, for each valid object reference, we call `DOM.describeNode` to retrieve
* the element’s `backendNodeId`.
* - Collects all resulting `backendNodeId`s in a Set and returns them.
*
* @param stagehandPage - A StagehandPage instance with built-in CDP helpers.
* @returns A Promise that resolves to a Set of unique `backendNodeId`s corresponding
* to scrollable elements in the DOM.
*/
export async function findScrollableElementIds(
stagehandPage: StagehandPage,
): Promise<Set<number>> {
// get the xpaths of the scrollable elements
const xpaths = await stagehandPage.page.evaluate(() => {
return window.getScrollableElementXpaths();
});
const scrollableBackendIds = new Set<number>();
for (const xpath of xpaths) {
if (!xpath) continue;
// evaluate the XPath in the stagehandPage
const { result } = await stagehandPage.sendCDP<{
result?: { objectId?: string };
}>("Runtime.evaluate", {
expression: `
(function() {
const res = document.evaluate(${JSON.stringify(
xpath,
)}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return res.singleNodeValue;
})();
`,
returnByValue: false,
});
// if we have an objectId, call DOM.describeNode to get backendNodeId
if (result?.objectId) {
const { node } = await stagehandPage.sendCDP<{
node?: { backendNodeId?: number };
}>("DOM.describeNode", {
objectId: result.objectId,
});
if (node?.backendNodeId) {
scrollableBackendIds.add(node.backendNodeId);
}
}
}
return scrollableBackendIds;
}
export async function performPlaywrightMethod(
stagehandPage: Page,
logger: (logLine: LogLine) => void,
method: string,
args: unknown[],
xpath: string,
) {
const locator = stagehandPage.locator(`xpath=${xpath}`).first();
const initialUrl = stagehandPage.url();
logger({
category: "action",
message: "performing playwright method",
level: 2,
auxiliary: {
xpath: {
value: xpath,
type: "string",
},
method: {
value: method,
type: "string",
},
},
});
if (method === "scrollIntoView") {
logger({
category: "action",
message: "scrolling element into view",
level: 2,
auxiliary: {
xpath: {
value: xpath,
type: "string",
},
},
});
try {
await locator
.evaluate((element: HTMLElement) => {
element.scrollIntoView({ behavior: "smooth", block: "center" });
})
.catch((e: Error) => {
logger({
category: "action",
message: "error scrolling element into view",
level: 1,
auxiliary: {
error: {
value: e.message,
type: "string",
},
trace: {
value: e.stack,
type: "string",
},
xpath: {
value: xpath,
type: "string",
},
},
});
});
} catch (e) {
logger({
category: "action",
message: "error scrolling element into view",
level: 1,
auxiliary: {
error: {
value: e.message,
type: "string",
},
trace: {
value: e.stack,
type: "string",
},
xpath: {
value: xpath,
type: "string",
},
},
});
throw new PlaywrightCommandException(e.message);
}
} else if (method === "fill" || method === "type") {
try {
await locator.fill("");
await locator.click();
const text = args[0]?.toString();
for (const char of text) {
await stagehandPage.keyboard.type(char, {
delay: Math.random() * 50 + 25,
});
}
} catch (e) {
logger({
category: "action",
message: "error filling element",
level: 1,
auxiliary: {
error: {
value: e.message,
type: "string",
},
trace: {
value: e.stack,
type: "string",
},
xpath: {
value: xpath,
type: "string",
},
},
});
throw new PlaywrightCommandException(e.message);
}
} else if (method === "press") {
try {
const key = args[0]?.toString();
await stagehandPage.keyboard.press(key);
} catch (e) {
logger({
category: "action",
message: "error pressing key",
level: 1,
auxiliary: {
error: {
value: e.message,
type: "string",
},
trace: {
value: e.stack,
type: "string",
},
key: {
value: args[0]?.toString() ?? "unknown",
type: "string",
},
},
});
throw new PlaywrightCommandException(e.message);
}
} else if (typeof locator[method as keyof typeof locator] === "function") {
// Log current URL before action
logger({
category: "action",
message: "page URL before action",
level: 2,
auxiliary: {
url: {
value: stagehandPage.url(),
type: "string",
},
},
});
// Perform the action
try {
await (
locator[method as keyof Locator] as unknown as (
...args: string[]
) => Promise<void>
)(...args.map((arg) => arg?.toString() || ""));
} catch (e) {
logger({
category: "action",
message: "error performing method",
level: 1,
auxiliary: {
error: {
value: e.message,
type: "string",
},
trace: {
value: e.stack,
type: "string",
},
xpath: {
value: xpath,
type: "string",
},
method: {
value: method,
type: "string",
},
args: {
value: JSON.stringify(args),
type: "object",
},
},
});
throw new PlaywrightCommandException(e.message);
}
// Handle navigation if a new page is opened
if (method === "click") {
logger({
category: "action",
message: "clicking element, checking for page navigation",
level: 1,
auxiliary: {
xpath: {
value: xpath,
type: "string",
},
},
});
const newOpenedTab = await Promise.race([
new Promise<Page | null>((resolve) => {
Promise.resolve(stagehandPage.context()).then((context) => {
context.once("page", (page: Page) => resolve(page));
setTimeout(() => resolve(null), 1_500);
});
}),
]);
logger({
category: "action",
message: "clicked element",
level: 1,
auxiliary: {
newOpenedTab: {
value: newOpenedTab ? "opened a new tab" : "no new tabs opened",
type: "string",
},
},
});
if (newOpenedTab) {
logger({
category: "action",
message: "new page detected (new tab) with URL",
level: 1,
auxiliary: {
url: {
value: newOpenedTab.url(),
type: "string",
},
},
});
await newOpenedTab.close();
await stagehandPage.goto(newOpenedTab.url());
await stagehandPage.waitForLoadState("domcontentloaded");
}
await Promise.race([
stagehandPage.waitForLoadState("networkidle"),
new Promise((resolve) => setTimeout(resolve, 5_000)),
]).catch((e) => {
logger({
category: "action",
message: "network idle timeout hit",
level: 1,
auxiliary: {
trace: {
value: e.stack,
type: "string",
},
message: {
value: e.message,
type: "string",
},
},
});
});
logger({
category: "action",
message: "finished waiting for (possible) page navigation",
level: 1,
});
if (stagehandPage.url() !== initialUrl) {
logger({
category: "action",
message: "new page detected with URL",
level: 1,
auxiliary: {
url: {
value: stagehandPage.url(),
type: "string",
},
},
});
}
}
} else {
logger({
category: "action",
message: "chosen method is invalid",
level: 1,
auxiliary: {
method: {
value: method,
type: "string",
},
},
});
throw new PlaywrightCommandMethodNotSupportedException(
`Method ${method} not supported`,
);
}
}