The headless browser for AI agents and web scraping
Add live table rows without extra wrapper bridge reads
SGavrld8f146726c87
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rsindex 66ab2b79..39ede23d 100644--- a/crates/obscura-dom/src/tree.rs+++ b/crates/obscura-dom/src/tree.rs@@ -1277,6 +1277,38 @@ impl DomTree {result}+ /// HTML table rows: header sections first, body/direct rows in tree order,+ /// and footer sections last. Nested tables do not contribute rows.+ pub fn table_rows(&self, table: NodeId) -> Option<Vec<NodeId>> {+ let html_tag = |id| self.with_node(id, |node| {+ node.as_element().filter(|name| {+ name.ns.as_ref() == "http://www.w3.org/1999/xhtml"+ }).map(|name| name.local.clone())+ }).flatten();+ if html_tag(table).as_ref().map(|tag| tag.as_ref()) != Some("table") {+ return None;+ }+ let mut head = Vec::new();+ let mut body = Vec::new();+ let mut foot = Vec::new();+ for child in self.children(table) {+ let Some(tag) = html_tag(child) else { continue };+ let rows = match tag.as_ref() {+ "tr" => { body.push(child); continue; }+ "thead" => &mut head,+ "tbody" => &mut body,+ "tfoot" => &mut foot,+ _ => continue,+ };+ rows.extend(self.children(child).into_iter().filter(|row| {+ html_tag(*row).as_ref().map(|tag| tag.as_ref()) == Some("tr")+ }));+ }+ head.extend(body);+ head.extend(foot);+ Some(head)+ }+/// Snapshot the direct children of `host`'s shadow root. Ordinary/// `children(host)` continues to return only light children.pub fn shadow_children(&self, host: NodeId) -> Option<Vec<NodeId>> {@@ -2046,6 +2078,38 @@ mod tests {})}+ #[test]+ fn table_rows_order_sections_and_exclude_nested_or_foreign_rows() {+ let tree = DomTree::new();+ let table = element(&tree, "table");+ let mut expected = Vec::new();+ for tag in ["tfoot", "tbody", "thead"] {+ let section = element(&tree, tag);+ tree.append_child(table, section);+ let row = element(&tree, "tr");+ tree.append_child(section, row);+ expected.push(row);+ }+ let direct = element(&tree, "tr");+ tree.append_child(table, direct);+ let nested = element(&tree, "table");+ tree.append_child(expected[1], nested);+ let nested_row = element(&tree, "tr");+ tree.append_child(nested, nested_row);+ let foreign = tree.new_node(NodeData::Element {+ name: QualName::new(None, Namespace::from("urn:foreign"), LocalName::from("tr")),+ attrs: vec![], template_contents: None,+ mathml_annotation_xml_integration_point: false,+ });+ tree.append_child(table, foreign);+ assert_eq!(tree.table_rows(table), Some(vec![expected[2], expected[1], direct, expected[0]]));+ assert_eq!(tree.table_rows(nested), Some(vec![nested_row]));+ tree.append_child(table, expected[2]);+ assert_eq!(tree.table_rows(table), Some(vec![expected[1], direct, expected[2], expected[0]]));+ assert_eq!(tree.table_rows(foreign), None);+ assert_eq!(tree.table_rows(NodeId::new(u32::MAX)), None);+ }+#[test]fn test_new_tree_has_document() {let tree = DomTree::new();diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 77f28615..18f542cb 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -7869,41 +7869,47 @@ globalThis.VTTCue = VTTCue;const _htmlInterfaceToken = {};const _additionalHtmlElementClasses = Object.create(null);const _elementClassFor = (function _elementClassFor(nid) {- const tag = _domParse("tag_name", nid);- if (tag.includes(":") && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml") {- return _elementClassForKnownName("http://www.w3.org/1999/xhtml", _domParse("local_name", nid));+ // Canonical HTML names keep the scalar fast path. Other names carry their+ // namespace/local name in the same native read rather than two more ops.+ const info = _domParse("tag_name", nid, "interface");+ const canonicalHTML = typeof info === 'string';+ const tag = canonicalHTML ? info : info[0];+ const namespace = canonicalHTML ? "http://www.w3.org/1999/xhtml" : info[1];+ const localName = canonicalHTML ? null : info[2];+ if (!canonicalHTML && tag.includes(":") && namespace === "http://www.w3.org/1999/xhtml") {+ return _elementClassForKnownName(namespace, localName);}// HTML tagName values are ASCII-uppercase. Foreign SVG names retain their// case, so keep the common HTML path fast and only inspect the native// namespace for possible SVG wrappers.- if (tag && tag !== tag.toUpperCase()- && _domParse("namespace_uri", nid) === "http://www.w3.org/2000/svg") {+ if (!canonicalHTML && tag && tag !== tag.toUpperCase()+ && namespace === "http://www.w3.org/2000/svg") {const svgClass = _svgElementClasses[tag];if (svgClass) return svgClass;if (globalThis.SVGElement) return globalThis.SVGElement;}if (tag === "FORM" && globalThis.HTMLFormElement) return globalThis.HTMLFormElement;if (tag === "INPUT" && globalThis.HTMLInputElement- && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml"- && _domParse("local_name", nid) === "input") return globalThis.HTMLInputElement;+ && (canonicalHTML || namespace === "http://www.w3.org/1999/xhtml"+ && localName === "input")) return globalThis.HTMLInputElement;if (tag === "TEXTAREA" && globalThis.HTMLTextAreaElement) return globalThis.HTMLTextAreaElement;if (tag === "META" && globalThis.HTMLMetaElement- && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml"- && _domParse("local_name", nid) === "meta") return globalThis.HTMLMetaElement;+ && (canonicalHTML || namespace === "http://www.w3.org/1999/xhtml"+ && localName === "meta")) return globalThis.HTMLMetaElement;if ((tag === "OL" || tag === "LI")- && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml") {- const localName = _domParse("local_name", nid);- if (localName === "ol") return HTMLOListElement;- if (localName === "li") return HTMLLIElement;+ && namespace === "http://www.w3.org/1999/xhtml") {+ const local = canonicalHTML ? tag.toLowerCase() : localName;+ if (local === "ol") return HTMLOListElement;+ if (local === "li") return HTMLLIElement;}// Only HTML slots take part in slot assignment; a foreign-namespace "SLOT"// (createElementNS + cloneNode lands here) stays a plain Element.if (tag === "SLOT" && globalThis.HTMLSlotElement- && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml") {+ && namespace === "http://www.w3.org/1999/xhtml") {return globalThis.HTMLSlotElement;}if (tag === "IFRAME" && globalThis.HTMLIFrameElement- && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml") {+ && namespace === "http://www.w3.org/1999/xhtml") {return globalThis.HTMLIFrameElement;}if (tag === "IMG") return HTMLImageElement;@@ -7912,8 +7918,8 @@ const _elementClassFor = (function _elementClassFor(nid) {if (tag === "VIDEO") return HTMLVideoElement;if (tag === "TRACK") return HTMLTrackElement;const additional = _additionalHtmlElementClasses[tag];- if (additional && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml"- && _domParse("local_name", nid) === tag.toLowerCase()) return additional;+ if (additional && (canonicalHTML || namespace === "http://www.w3.org/1999/xhtml"+ && localName === tag.toLowerCase())) return additional;return Element;});const _elementClassForKnownName = (function _elementClassForKnownName(namespace, localName) {@@ -14461,7 +14467,6 @@ globalThis.HTMLLabelElement = Element;for (const proto of [HTMLInputElement.prototype, HTMLTextAreaElement.prototype]) {Object.defineProperty(proto, 'readOnly', { enumerable: true });}-globalThis.HTMLTableElement = Element;// <iframe> needs its own brand: with `HTMLIFrameElement = Element` every// element passed `instanceof HTMLIFrameElement`, so style-loader's// "insert target is an iframe" branch took `contentDocument.head` of <head>@@ -14555,7 +14560,7 @@ for (const [name, tags] of Object.entries({HTMLMeterElement: ['meter'], HTMLModElement: ['del', 'ins'], HTMLObjectElement: ['object'],HTMLOptGroupElement: ['optgroup'], HTMLOutputElement: ['output'], HTMLParamElement: ['param'],HTMLPictureElement: ['picture'], HTMLQuoteElement: ['blockquote', 'q'], HTMLSourceElement: ['source'],- HTMLTableCaptionElement: ['caption'], HTMLTableCellElement: ['td', 'th'],+ HTMLTableElement: ['table'], HTMLTableCaptionElement: ['caption'], HTMLTableCellElement: ['td', 'th'],HTMLTableColElement: ['col', 'colgroup'], HTMLTableRowElement: ['tr'],HTMLTableSectionElement: ['tbody', 'thead', 'tfoot'], HTMLTimeElement: ['time'], HTMLTitleElement: ['title'],})) {@@ -14895,6 +14900,99 @@ const _htmlCollectionProxy = {return typeof k === "string" && !!(t.namedItem && t.namedItem(k));},};+const _tableRowCollections = new WeakMap();+function _tableRowsGetter() {+ if (!this || _cache.get(this._nid) !== this) {+ const owner = this && this.ownerDocument && this.ownerDocument.defaultView;+ if (owner && owner !== globalThis) {+ const getter = Object.getOwnPropertyDescriptor(owner.HTMLTableElement.prototype, 'rows').get;+ return getter.call(this);+ }+ throw new TypeError('Illegal invocation');+ }+ if (_tableRowCollections.has(this)) return _tableRowCollections.get(this);+ const table = this;+ let epoch = -1;+ let elements = [];+ function refresh() {+ if (epoch !== _domMutationEpoch) {+ const ids = _domParse('table_rows', table._nid);+ if (ids === null) throw new TypeError('Illegal invocation');+ elements = ids.map(_wrapEl);+ epoch = _domMutationEpoch;+ }+ return elements;+ }+ const index = key => typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)+ && Number(key) < 4294967295;+ const target = Object.create(HTMLCollection.prototype);+ const collection = new Proxy(target, {+ get(t, key, receiver) {+ const rows = refresh();+ if (key === 'length') return rows.length;+ if (key === Symbol.toStringTag && !Reflect.has(t, key)) return 'HTMLCollection';+ if (index(key)) return rows[Number(key)];+ const value = Reflect.get(t, key, receiver);+ if (value !== undefined || typeof key !== 'string') return value;+ return HTMLCollection.prototype.namedItem.call(receiver, key) || undefined;+ },+ has(t, key) {+ if (index(key)) return Number(key) < refresh().length;+ return Reflect.has(t, key) || (typeof key === 'string'+ && !!HTMLCollection.prototype.namedItem.call(collection, key));+ },+ ownKeys(t) {+ const rows = refresh();+ const keys = new Set();+ for (let i = 0; i < rows.length; i++) keys.add(String(i));+ rows.forEach(row => {+ for (const name of [row.id, row.getAttribute('name')]) {+ if (name && !Reflect.has(t, name)) keys.add(name);+ }+ });+ for (const key of Reflect.ownKeys(t)) keys.add(key);+ return [...keys];+ },+ getOwnPropertyDescriptor(t, key) {+ if (index(key)) {+ const row = refresh()[Number(key)];+ return row ? {value: row, writable: false, enumerable: true, configurable: true} : undefined;+ }+ const descriptor = Reflect.getOwnPropertyDescriptor(t, key);+ if (descriptor || typeof key !== 'string' || Reflect.has(t, key)) return descriptor;+ const row = HTMLCollection.prototype.namedItem.call(collection, key);+ return row ? {value: row, writable: false, enumerable: false, configurable: true} : undefined;+ },+ set(t, key, value, receiver) {+ if (key === 'length' || index(key)+ || (typeof key === 'string' && !Reflect.has(t, key)+ && HTMLCollection.prototype.namedItem.call(collection, key))) return false;+ return Reflect.set(t, key, value, receiver);+ },+ defineProperty(t, key, descriptor) {+ if (key === 'length' || index(key)+ || (typeof key === 'string' && !Reflect.has(t, key)+ && HTMLCollection.prototype.namedItem.call(collection, key))) return false;+ return Reflect.defineProperty(t, key, descriptor);+ },+ deleteProperty(t, key) {+ if (index(key)) return Number(key) >= refresh().length;+ if (typeof key === 'string' && !Reflect.has(t, key)+ && HTMLCollection.prototype.namedItem.call(collection, key)) return false;+ return Reflect.deleteProperty(t, key);+ },+ preventExtensions() { return false; },+ });+ refresh();+ _tableRowCollections.set(table, collection);+ return collection;+}+Object.defineProperty(HTMLTableElement, 'length', {value: 0, configurable: true});+Object.defineProperty(_tableRowsGetter, 'name', {value: 'get rows', configurable: true});+Object.defineProperty(HTMLTableElement.prototype, 'rows', {+ get: _tableRowsGetter, enumerable: true, configurable: true,+});+_markNative(_tableRowsGetter);// True for elements in the HTML namespace (the only ones whose name attribute// contributes to an HTMLCollection's supported property names).function _isHTMLEl(el) {diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 7536e7dc..8415cb46 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -2655,12 +2655,19 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->None => "null".into(),}}+ "table_rows" => {+ let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));+ serde_json::json!(dom.table_rows(nid).map(|rows| {+ rows.into_iter().map(|row| row.index()).collect::<Vec<_>>()+ })).to_string()+ }"tag_name" => {let nid = arg1.parse::<u32>().unwrap_or(0);- let name = dom+ dom.with_node(NodeId::new(nid), |n| {n.as_element().map(|name| {- if name.ns == html5ever::ns!(html) {+ let html = name.ns == html5ever::ns!(html);+ let tag = if html {match &name.prefix {Some(prefix) => {let mut qualified = format!("{}:{}", prefix, name.local);@@ -2674,12 +2681,17 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->Some(prefix) => format!("{}:{}", prefix, name.local),None => name.local.to_string(),}+ };+ if arg2 == "interface" && (!html || name.prefix.is_some()+ || name.local.as_ref().bytes().any(|byte| byte.is_ascii_uppercase())) {+ serde_json::json!([tag, name.ns.as_ref(), name.local.as_ref()]).to_string()+ } else {+ serde_json::Value::String(tag).to_string()}})}).flatten()- .unwrap_or_default();- serde_json::to_string(&name).unwrap_or("\"\"".into())+ .unwrap_or_else(|| "\"\"".into())}"prefix" => {let nid = arg1.parse::<u32>().unwrap_or(0);diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex e9876971..6d108e9c 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -4606,6 +4606,93 @@ impl Default for ObscuraJsRuntime {#[cfg(test)]mod tests {+ #[test]+ fn table_rows_are_live_ordered_readonly_collections() {+ let mut rt = setup_runtime("<html><body></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const table = document.createElement('table');+ document.body.append(table);+ for (const [section, id] of [['tfoot','foot'],['tbody','body'],['thead','head']]) {+ const group = document.createElement(section);+ group.innerHTML = '<tr id="'+id+'"><td></td></tr>';+ table.append(group);+ }+ const direct = document.createElement('tr');+ direct.id = 'direct';+ table.append(direct);+ table.querySelector('td').innerHTML = '<table><tr id="nested"><td></td></tr></table>';+ table.querySelector('thead').append(document.createElementNS('urn:foreign', 'tr'));+ const rows = table.rows;+ const initial = Array.from(rows, row => row.id);+ const collection = [rows === table.rows, rows instanceof HTMLCollection,+ Array.isArray(rows), Object.prototype.toString.call(rows),+ rows.item(1).id, rows.namedItem('head').id, rows.head.id,+ Object.keys(rows), 'head' in rows, rows.item(99)];+ const writes = [Reflect.set(rows, '0', null), Reflect.set(rows, 'length', 0),+ Reflect.defineProperty(rows, '1', {value:null}), Reflect.deleteProperty(rows, '0')];+ rows.custom = 'expando';+ const reflection = [Object.keys(rows), Object.getOwnPropertyNames(rows),+ Reflect.deleteProperty(rows, '99')];+ Object.defineProperty(rows, Symbol.toStringTag, {value:'CustomCollection', configurable:false});+ reflection.push(Object.prototype.toString.call(rows));+ table.querySelector('thead').textContent = '';+ direct.id = 'renamed';+ direct.setAttribute('name', 'alias');+ const changed = [rows.length, rows[0].id, rows.renamed === direct,+ rows.alias === direct, 'head' in rows, rows.head === undefined];+ direct.id = '99';+ const numericName = [Object.getOwnPropertyNames(rows).includes('99'),+ rows[99] === undefined, rows.namedItem('99') === direct,+ Reflect.deleteProperty(rows, '99')];+ table.textContent = '';+ return {initial, collection, writes, reflection, changed, numericName, empty:rows.length};+ })()"#).unwrap(), serde_json::json!({+ "initial":["head","body","direct","foot"],+ "collection":[true,true,false,"[object HTMLCollection]","body","head","head",+ ["0","1","2","3"],true,null],+ "writes":[false,false,false,false],+ "reflection":[["0","1","2","3","custom"],+ ["0","1","2","3","head","body","direct","foot","custom"],true,"[object CustomCollection]"],+ "changed":[3,"body",true,true,false,true], "numericName":[true,true,true,true], "empty":0,+ }));+ }++ #[test]+ fn table_rows_preserve_factory_brands_and_reject_non_table_receivers() {+ let mut rt = setup_runtime("<html><body><table><tr><th>Header</th></tr></table><h1>Heading</h1></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const parsed = document.querySelector('table');+ const created = document.createElement('table');+ const cloned = parsed.cloneNode(true);+ const getter = Object.getOwnPropertyDescriptor(HTMLTableElement.prototype, 'rows').get;+ const invalid = [document.createElement('div'), {},+ document.createElementNS('urn:foreign', 'table')].map(value => {+ try { getter.call(value); return false; } catch (error) { return error instanceof TypeError; }+ });+ let illegalConstructor = false;+ try { new HTMLTableElement(); } catch (error) { illegalConstructor = error instanceof TypeError; }+ return [parsed instanceof HTMLTableElement, created instanceof HTMLTableElement,+ cloned instanceof HTMLTableElement, cloned.rows.length, parsed.rows.length,+ document.querySelector('h1') instanceof HTMLTableElement, invalid, illegalConstructor,+ HTMLTableElement.length, getter.name, getter.toString()];+ })()"#).unwrap(), serde_json::json!([true,true,true,1,1,false,[true,true,true],true,+ 0,"get rows","function get rows() { [native code] }"]));+ }++ #[test]+ fn table_rows_are_live_in_child_realms() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,+ "http://example.com/child", "<html><body><table><tr><th>Header</th></tr></table></body></html>").unwrap();+ assert_eq!(frame.evaluate(&mut rt, r#"(() => {+ const table = document.querySelector('table');+ const rows = table.rows;+ const branded = table instanceof HTMLTableElement && rows instanceof HTMLCollection;+ table.querySelector('tbody').append(document.createElement('tr'));+ return [branded, rows.length, table.cloneNode(true).rows.length];+ })()"#).unwrap(), serde_json::json!([true,2,2]));+ }+#[test]fn noninteractive_dialogs_do_not_accept_destructive_confirmation() {let mut rt = setup_runtime("<html><body></body></html>");diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.mdindex 9f863688..ea46e47a 100644--- a/docs/Architecture-overview.md+++ b/docs/Architecture-overview.md@@ -137,6 +137,16 @@ The noninteractive dialog defaults dismiss `confirm()` (`false`), canceldo not emit client-controlled CDP dialogs. `Page.handleJavaScriptDialog`continues to resolve the separate beforeunload confirmation from `Page.close`.+`HTMLTableElement.rows` is a live, read-only HTMLCollection. Native traversal+orders header rows first, body/direct rows next, and footer rows last, excluding+nested tables and foreign namespaces. Reads reuse the collection until a DOM+mutation invalidates its row snapshot. This also supports Playwright's implicit+table-header role calculation; it does not add the other missing table APIs.+Wrapper classification keeps canonical HTML names on a single scalar native+read; prefixed or foreign names include namespace/local-name metadata in that+same read. Table construction and parser/wrapper workloads are covered by the+public performance smoke gate.+`window.origin` (including the bare `origin` identifier) reports the owningdocument's origin, including inherited blank-frame origins. Page assignmentreplaces this property without changing the document's actual origin.diff --git a/scripts/ci/perf_smoke.py b/scripts/ci/perf_smoke.pyindex 513b9a92..f3c83302 100755--- a/scripts/ci/perf_smoke.py+++ b/scripts/ci/perf_smoke.py@@ -47,6 +47,14 @@ SCENARIOS = {"(() => {let h=document.createElement('div');document.body.append(h);let r=h.attachShadow({mode:'open'});let n=0;for(let i=0;i<200000;i++)if(h.shadowRoot===r)n++;return n;})()",200000,),+ "table-create": (+ "(() => {for(let i=0;i<5000;i++)document.body.append(document.createElement('table'));return document.querySelectorAll('table').length})()",+ 5000,+ ),+ "table-parse-wrap": (+ "(() => {document.body.innerHTML='<table><tr><td>row</td></tr></table>'.repeat(5000);return document.querySelectorAll('table').length})()",+ 5000,+ ),}SCENARIOS.update({f"html-parse-depth-{depth}": (