browsing 0.1.3

Lightweight MCP/API for browser automation: navigate, get content (text), screenshot. Parallelism via RwLock.
Documentation
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
//! DOM serializer for LLM representation

use crate::dom::views::{
    DEFAULT_INCLUDE_ATTRIBUTES, DOMInteractedElement, EnhancedDOMTreeNode, NodeType,
    SerializedDOMState,
};
use std::collections::HashMap;

/// Simplified node for serialization
#[derive(Debug, Clone)]
pub struct SimplifiedNode {
    /// Original enhanced DOM tree node
    pub original_node: EnhancedDOMTreeNode,
    /// Child nodes
    pub children: Vec<SimplifiedNode>,
    /// Whether this node should be displayed
    pub should_display: bool,
    /// Whether this node is interactive
    pub is_interactive: bool,
    /// Interactive index if applicable
    pub interactive_index: Option<u32>,
}

impl SimplifiedNode {
    /// Creates a new simplified node from an enhanced DOM tree node
    pub fn new(node: EnhancedDOMTreeNode) -> Self {
        Self {
            original_node: node,
            children: Vec::new(),
            should_display: true,
            is_interactive: false,
            interactive_index: None,
        }
    }
}

/// DOM tree serializer
pub struct DOMTreeSerializer {
    /// Root node of the DOM tree
    root_node: EnhancedDOMTreeNode,
    /// Counter for interactive elements
    interactive_counter: u32,
    /// Map of selectors
    selector_map: HashMap<u32, DOMInteractedElement>,
}

impl DOMTreeSerializer {
    /// Creates a new DOM tree serializer
    pub fn new(root_node: EnhancedDOMTreeNode) -> Self {
        Self {
            root_node,
            interactive_counter: 1,
            selector_map: HashMap::new(),
        }
    }

    /// Serialize accessible elements and build selector map
    pub fn serialize_accessible_elements(mut self) -> (SerializedDOMState, HashMap<String, f64>) {
        // Reset state
        self.interactive_counter = 1;
        self.selector_map.clear();

        // Create simplified tree
        let simplified_tree = self._create_simplified_tree(&self.root_node);

        // Assign interactive indices (need mutable reference)
        let mut simplified_tree_mut = simplified_tree;
        self._assign_interactive_indices(&mut simplified_tree_mut);
        let simplified_tree = simplified_tree_mut;

        // Serialize to string
        let serialized_string =
            Self::serialize_tree(&simplified_tree, DEFAULT_INCLUDE_ATTRIBUTES, 0);

        let serialized_state = SerializedDOMState {
            html: None,
            text: Some(serialized_string.clone()),
            markdown: Some(serialized_string),
            elements: vec![],
            selector_map: self.selector_map,
        };

        (serialized_state, HashMap::new())
    }

    /// Create simplified tree from enhanced DOM tree
    fn _create_simplified_tree(&self, node: &EnhancedDOMTreeNode) -> SimplifiedNode {
        let mut simplified = SimplifiedNode::new(node.clone());

        // Determine if node should be displayed
        simplified.should_display = self._should_display_node(node);

        // Process children
        if let Some(ref children) = node.children_nodes {
            for child in children {
                let child_simplified = self._create_simplified_tree(child);
                simplified.children.push(child_simplified);
            }
        }

        // Process shadow roots
        if let Some(ref shadow_roots) = node.shadow_roots {
            for shadow_root in shadow_roots {
                let shadow_simplified = self._create_simplified_tree(shadow_root);
                simplified.children.push(shadow_simplified);
            }
        }

        // Process content document (iframe)
        if let Some(ref content_doc) = node.content_document {
            let doc_simplified = self._create_simplified_tree(content_doc);
            simplified.children.push(doc_simplified);
        }

        simplified
    }

    /// Check if node should be displayed
    fn _should_display_node(&self, node: &EnhancedDOMTreeNode) -> bool {
        // Skip disabled elements
        if let Some(attrs) = node.attributes.get("disabled") {
            if attrs.as_str() == "true" || attrs.as_str() == "disabled" {
                return false;
            }
        }

        // Skip hidden elements
        if let Some(ref snapshot) = node.snapshot_node {
            if let Some(ref styles) = snapshot.computed_styles {
                if let Some(display) = styles.get("display") {
                    if display == "none" {
                        return false;
                    }
                }
                if let Some(visibility) = styles.get("visibility") {
                    if visibility == "hidden" {
                        return false;
                    }
                }
            }
        }

        // Skip script and style tags
        let tag = node.tag_name();
        if matches!(
            tag.as_str(),
            "script" | "style" | "head" | "meta" | "link" | "title"
        ) {
            return false;
        }

        true
    }

    /// Assign interactive indices to clickable elements
    fn _assign_interactive_indices(&mut self, simplified: &mut SimplifiedNode) {
        if !simplified.should_display {
            // Still process children
            for child in &mut simplified.children {
                self._assign_interactive_indices(child);
            }
            return;
        }

        let node = &simplified.original_node;

        // Check if element is interactive/clickable
        let is_clickable = node
            .snapshot_node
            .as_ref()
            .and_then(|s| s.is_clickable)
            .unwrap_or(false)
            || self._is_interactive_element(node);

        if is_clickable {
            let index = self.interactive_counter;
            self.interactive_counter += 1;

            simplified.is_interactive = true;
            simplified.interactive_index = Some(index);

            // Create interacted element
            let interacted = DOMInteractedElement {
                index,
                backend_node_id: Some(node.backend_node_id as u32),
                tag: node.tag_name(),
                text: self._get_element_text(node),
                attributes: node.attributes.clone(),
                selector: Some(self.generate_xpath_selector(node)),
            };

            self.selector_map.insert(index, interacted);
        }

        // Process children
        for child in &mut simplified.children {
            self._assign_interactive_indices(child);
        }
    }

    /// Check if element is interactive
    fn _is_interactive_element(&self, node: &EnhancedDOMTreeNode) -> bool {
        let tag = node.tag_name();
        matches!(
            tag.as_str(),
            "a" | "button" | "input" | "select" | "textarea" | "label"
        ) || node
            .attributes
            .get("role")
            .map(|r| {
                matches!(
                    r.as_str(),
                    "button" | "link" | "menuitem" | "tab" | "option"
                )
            })
            .unwrap_or(false)
    }

    /// Get element text content
    fn _get_element_text(&self, node: &EnhancedDOMTreeNode) -> Option<String> {
        // Try aria-label first
        if let Some(label) = node.attributes.get("aria-label") {
            if !label.is_empty() {
                return Some(label.clone());
            }
        }

        // Try value attribute
        if let Some(value) = node.attributes.get("value") {
            if !value.is_empty() {
                return Some(value.clone());
            }
        }

        // Try placeholder
        if let Some(placeholder) = node.attributes.get("placeholder") {
            if !placeholder.is_empty() {
                return Some(placeholder.clone());
            }
        }

        // Extract text from children (simplified)
        if node.node_type == NodeType::TextNode && !node.node_value.trim().is_empty() {
            return Some(node.node_value.trim().to_string());
        }

        None
    }

    /// Serialize tree to string representation
    pub fn serialize_tree(
        node: &SimplifiedNode,
        include_attributes: &[&str],
        depth: usize,
    ) -> String {
        if !node.should_display {
            return Self::_serialize_children(node, include_attributes, depth);
        }

        let mut formatted_text = Vec::new();
        let depth_str = "\t".repeat(depth);
        let next_depth = depth + 1;

        match node.original_node.node_type {
            NodeType::ElementNode => {
                let tag = node.original_node.tag_name();
                let mut parts = vec![tag.clone()];

                // Add attributes
                let attrs_str =
                    Self::_build_attributes_string(&node.original_node, include_attributes);
                if !attrs_str.is_empty() {
                    parts.push(attrs_str);
                }

                // Add index if interactive
                if let Some(index) = node.interactive_index {
                    parts.push(format!("[{index}]"));
                }

                formatted_text.push(format!("{}{}", depth_str, parts.join(" ")));

                // Process children
                for child in &node.children {
                    let child_text = Self::serialize_tree(child, include_attributes, next_depth);
                    if !child_text.trim().is_empty() {
                        formatted_text.push(child_text);
                    }
                }
            }
            NodeType::TextNode => {
                let text = node.original_node.node_value.trim();
                if !text.is_empty() && text.len() > 1 {
                    formatted_text.push(format!("{depth_str}{text}"));
                }
            }
            _ => {
                // Process children for other node types
                for child in &node.children {
                    let child_text = Self::serialize_tree(child, include_attributes, next_depth);
                    if !child_text.trim().is_empty() {
                        formatted_text.push(child_text);
                    }
                }
            }
        }

        formatted_text.join("\n")
    }

    /// Serialize children only
    fn _serialize_children(
        node: &SimplifiedNode,
        include_attributes: &[&str],
        depth: usize,
    ) -> String {
        let mut parts = Vec::new();
        for child in &node.children {
            let child_text = Self::serialize_tree(child, include_attributes, depth);
            if !child_text.trim().is_empty() {
                parts.push(child_text);
            }
        }
        parts.join("\n")
    }

    /// Build attributes string
    fn _build_attributes_string(node: &EnhancedDOMTreeNode, include_attributes: &[&str]) -> String {
        let mut attrs = Vec::new();

        for attr_name in include_attributes {
            if let Some(value) = node.attributes.get(*attr_name) {
                if !value.is_empty() {
                    attrs.push(format!("{attr_name}=\"{value}\""));
                }
            }
        }

        attrs.join(" ")
    }

    /// Find interacted element for a node (helper)
    fn _find_interacted_element(
        &self,
        node: &EnhancedDOMTreeNode,
    ) -> Option<&DOMInteractedElement> {
        // Look up by backend_node_id in selector_map
        self.selector_map
            .values()
            .find(|elem| elem.backend_node_id == Some(node.backend_node_id as u32))
    }

    /// Generate XPath selector for a DOM node (public for testing)
    pub fn generate_xpath_selector(&self, node: &EnhancedDOMTreeNode) -> String {
        let tag_name = node.tag_name();

        // Strategy 1: Use id attribute if available (most specific)
        if let Some(id) = node.attributes.get("id") {
            if !id.is_empty() {
                return format!("//*[@id={}]", Self::_escape_xpath_string(id));
            }
        }

        // Strategy 2: Use name attribute for form elements
        if tag_name == "input" || tag_name == "select" || tag_name == "textarea" {
            if let Some(name) = node.attributes.get("name") {
                if !name.is_empty() {
                    return format!("//{}[@name={}]", tag_name, Self::_escape_xpath_string(name));
                }
            }
        }

        // Strategy 3: Use unique data attributes (data-testid, data-cy, etc.)
        for attr in &["data-testid", "data-cy", "data-test", "data-qa"] {
            if let Some(value) = node.attributes.get(*attr) {
                if !value.is_empty() {
                    return format!("//*[@{}={}]", attr, Self::_escape_xpath_string(value));
                }
            }
        }

        // Strategy 4: Use tag name with position (least specific but always works)
        if let Some(position) = self._get_node_position(node) {
            format!("//{}[{}]", tag_name, position)
        } else {
            format!("//{}", tag_name)
        }
    }

    /// Get the position of a node among its siblings (1-indexed)
    fn _get_node_position(&self, node: &EnhancedDOMTreeNode) -> Option<usize> {
        if let Some(parent) = &node.parent_node {
            if let Some(children) = &parent.children_nodes {
                let tag_name = node.tag_name();
                let position = children
                    .iter()
                    .enumerate()
                    .filter(|(_, sibling)| sibling.tag_name() == tag_name)
                    .position(|(_, sibling)| sibling.backend_node_id == node.backend_node_id);
                return position.map(|p| p + 1);
            }
        }
        None
    }

    /// Escape string for use in XPath expressions
    fn _escape_xpath_string(s: &str) -> String {
        if s.contains("'") {
            if s.contains("\"") {
                let parts: Vec<String> = s.split('\'').map(|part| format!("'{}'", part)).collect();
                format!("concat({})", parts.join(", \",\", "))
            } else {
                format!("\"{}\"", s)
            }
        } else {
            format!("'{}'", s)
        }
    }
}