Skip to content

The headless browser for AI agents and web scraping

Restore native select indexing and legacy table APIs

SGavrl59276a3620ae
diff --git a/crates/obscura-cdp/tests/integration.rs b/crates/obscura-cdp/tests/integration.rs
index fb06981d..e82a26f9 100644
--- a/crates/obscura-cdp/tests/integration.rs
+++ b/crates/obscura-cdp/tests/integration.rs
@@ -51,6 +51,7 @@ integration_tests!(
input_mouse_event_parity,
input_mouse_label_activation,
js_fetch_emits_network_events,
+ legacy_table_apis,
lifecycle_replay,
max_connections_cap,
module_network_events,
diff --git a/crates/obscura-cdp/tests/legacy_table_apis.rs b/crates/obscura-cdp/tests/legacy_table_apis.rs
new file mode 100644
index 00000000..6fde1f3f
--- /dev/null
+++ b/crates/obscura-cdp/tests/legacy_table_apis.rs
@@ -0,0 +1,234 @@
+use obscura_cdp::dispatch::{dispatch, CdpContext};
+use obscura_cdp::types::CdpRequest;
+use serde_json::{json, Value};
+
+const PAGE: &str = r#"<select id="s"><option value="a">A</option><option value="b" selected>B</option></select><table id="t"><tfoot><tr><td>f</td></tr></tfoot><thead><tr><th>h</th></tr></thead><tbody><tr id="body"><td id="first">1</td><td>2</td></tr></tbody><tr><td>direct</td></tr></table>"#;
+
+async fn evaluate(expression: &str) -> Value {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session_id = "legacy-table";
+ ctx.sessions.insert(session_id.to_string(), page_id);
+ let nav = dispatch(&CdpRequest {
+ id: 1, method: "Page.navigate".to_string(),
+ params: json!({"url": format!("data:text/html,{PAGE}"), "waitUntil": "load"}),
+ session_id: Some(session_id.to_string()),
+ }, &mut ctx).await;
+ assert!(nav.error.is_none(), "{:?}", nav.error);
+ assert!(nav.result.as_ref().unwrap().get("errorText").is_none(), "{:?}", nav.result);
+ let resp = dispatch(&CdpRequest {
+ id: 2, method: "Runtime.evaluate".to_string(),
+ params: json!({"expression": expression, "returnByValue": true}),
+ session_id: Some(session_id.to_string()),
+ }, &mut ctx).await;
+ assert!(resp.error.is_none(), "{:?}", resp.error);
+ let result = resp.result.unwrap();
+ assert!(result.get("exceptionDetails").is_none(), "{result}");
+ result["result"]["value"].clone()
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn issue_repro_preserves_landed_select_and_table_rows_apis() {
+ assert_eq!(evaluate(r#"(() => {
+ const s = document.getElementById('s'), t = document.createElement('table');
+ t.innerHTML = '<tbody><tr><td>1</td><td>2</td></tr></tbody>';
+ return [s.length, s[s.selectedIndex].value, t.rows.length, t.rows[0].cells.length].join(',');
+ })()"#).await, json!("2,b,1,2"));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn select_indexed_access_is_live_and_uses_platform_setter_reflection() {
+ assert_eq!(evaluate(r#"(() => {
+ const s = document.getElementById('s');
+ const initial = [s[0] === s.item(0), s[1] === s.item(1), s[2] === undefined,
+ '0' in s, '2' in s, s instanceof HTMLSelectElement];
+ const inserted = new Option('New', 'n');
+ s[0] = inserted;
+ const replaced = [s[0] === inserted, s.length, inserted.index, s[1].value];
+ s[0] = null;
+ const removed = [s.length, s[0].value, s[1] === undefined];
+ s[3] = new Option('Last', 'last');
+ const filled = Array.from(s.options, option => option.value);
+ const defined = Reflect.defineProperty(s, '0', {value:new Option('Defined','d'),configurable:false});
+ const descriptor = Object.getOwnPropertyDescriptor(s, '0');
+ const reflection = [defined, s[0].value, descriptor.writable, descriptor.enumerable,
+ descriptor.configurable, Reflect.deleteProperty(s, '0'), Reflect.deleteProperty(s, '99')];
+ const accessor = Reflect.defineProperty(s, '0', {get(){return null;}});
+ const kept = s[0].value;
+ Reflect.defineProperty(s, '0', {configurable:false});
+ let invalid = false;
+ try { s[0] = 'bad'; } catch(e) { invalid = e instanceof TypeError; }
+ s.innerHTML = '<option value="fresh">Fresh</option>';
+ return {initial,replaced,removed,filled,reflection,accessor,kept,invalid,
+ fresh:[s[0].value,s[1] === undefined,s.length]};
+ })()"#).await, json!({
+ "initial":[true,true,true,true,false,true],
+ "replaced":[true,2,0,"b"],"removed":[1,"b",true],
+ "filled":["b","","","last"],"reflection":[true,"d",true,true,true,false,true],
+ "accessor":true,"kept":"d","invalid":true,"fresh":["fresh",true,1],
+ }));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn native_indices_follow_actual_table_section_and_cell_ownership() {
+ assert_eq!(evaluate(r#"(() => {
+ const t = document.getElementById('t'), direct = t.appendChild(document.createElement('tr'));
+ direct.insertCell().textContent = 'dom';
+ const body = t.tBodies[0].rows[0];
+ body.cells[0].innerHTML = '1<table><tr><td>nested</td></tr></table>';
+ body.append(document.createElementNS('urn:foreign', 'td'));
+ t.tBodies[0].append(document.createElementNS('urn:foreign', 'tr'));
+ const section = document.createElement('tbody'), detached = section.insertRow();
+ return [Array.from(t.rows, r => r.cells[0].textContent).join(','),
+ t.tHead.rows.length, t.tFoot.localName, t.tBodies.length, body.cells.length,
+ body.rowIndex, body.sectionRowIndex, t.rows[2].sectionRowIndex,
+ direct.rowIndex, direct.sectionRowIndex, body.cells[1].cellIndex,
+ detached.rowIndex, detached.sectionRowIndex,
+ document.createElement('tr').rowIndex, document.createElement('td').cellIndex];
+ })()"#).await, json!(["h,1nested,direct,dom,f",1,"tfoot",2,2,1,0,0,3,3,1,-1,0,-1,-1]));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn all_table_child_collections_are_live_cached_readonly_and_named() {
+ assert_eq!(evaluate(r#"(() => {
+ const t = document.getElementById('t'), bodies = t.tBodies, section = bodies[0];
+ const rows = section.rows, row = rows[0], cells = row.cells;
+ const descriptor = Object.getOwnPropertyDescriptor(cells, '0');
+ const initial = [bodies === t.tBodies, rows === section.rows, cells === row.cells,
+ bodies instanceof HTMLCollection, rows instanceof HTMLCollection, cells instanceof HTMLCollection,
+ Array.isArray(cells), Object.prototype.toString.call(cells),
+ rows.body === row, cells.first === cells[0], cells.item(9), cells.namedItem('missing'),
+ Object.keys(cells), [descriptor.value === cells[0], descriptor.writable,
+ descriptor.enumerable, descriptor.configurable]];
+ const writes = [Reflect.set(cells, '0', null), Reflect.set(cells, 'length', 0),
+ Reflect.defineProperty(cells, '0', {value:null}), Reflect.deleteProperty(cells, '0')];
+ cells[0].id = 'renamed'; cells[0].setAttribute('name', 'alias');
+ const renamed = [cells.first === undefined, cells.renamed === cells[0], cells.alias === cells[0]];
+ row.insertCell(0).id = 'new'; row.deleteCell(-1);
+ const changed = [cells.length, cells[0].id, cells[1].id, cells[1].cellIndex];
+ section.deleteRow(0); t.createTBody();
+ return {initial, writes, renamed, changed, empty:rows.length, bodies:bodies.length,
+ retained:cells.length, detached:row.rowIndex, detachedSection:row.sectionRowIndex};
+ })()"#).await, json!({
+ "initial":[true,true,true,true,true,true,false,"[object HTMLCollection]",true,true,null,null,
+ ["0","1"],[true,false,true,true]],
+ "writes":[false,false,false,false],"renamed":[true,true,true],
+ "changed":[2,"new","renamed",1],"empty":0,"bodies":3,"retained":2,
+ "detached":-1,"detachedSection":-1,
+ }));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn table_and_section_mutations_keep_correct_parent_and_row_order() {
+ assert_eq!(evaluate(r#"(() => {
+ const t = document.getElementById('t'), row = t.insertRow(2);
+ row.insertCell(0).textContent = 'x'; row.insertCell(0).textContent = 'y';
+ const out = [row.parentNode.localName, Array.from(row.cells, c => c.textContent).join('')];
+ row.deleteCell(-1); out.push(row.cells.length);
+ t.deleteRow(0); out.push(t.rows[0].cells[0].textContent);
+ const empty = document.createElement('table');
+ empty.append(document.createElement('thead'), document.createElement('tbody'),
+ document.createElement('tfoot'), document.createElement('tbody'));
+ const inserted = empty.insertRow();
+ out.push(inserted.parentNode === empty.lastElementChild);
+ const body = t.createTBody(); out.push(body.previousElementSibling.localName);
+ body.insertRow().insertCell().textContent = 'section';
+ body.insertRow(0); body.deleteRow(-1); out.push(body.rows.length);
+ const trulyEmpty = document.createElement('table'); trulyEmpty.insertRow();
+ out.push(trulyEmpty.firstElementChild.localName, trulyEmpty.rows[0].localName);
+ return out;
+ })()"#).await, json!(["tbody","yx",1,"1",true,"tbody",1,"tbody","tr"]));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn table_index_conversion_required_arguments_and_empty_deletion_match_webidl() {
+ assert_eq!(evaluate(r#"(() => {
+ const t = document.createElement('table'), section = document.createElement('tbody');
+ const row = document.createElement('tr');
+ const error = fn => { try { fn(); return 'ok'; } catch (e) { return e.name; } };
+ const out = [error(() => t.deleteRow(-1)), error(() => row.deleteCell(-1)),
+ error(() => section.deleteRow(-1)), error(() => t.deleteRow()),
+ error(() => section.deleteRow()), error(() => row.deleteCell()),
+ error(() => t.insertRow(1)), error(() => row.insertCell(-2)),
+ error(() => t.insertRow(1n)), error(() => row.insertCell(Symbol()))];
+ let calls = 0;
+ t.insertRow({valueOf(){ calls++; return 0.8; }}).insertCell();
+ out.push(calls, t.rows.length, error(() => t.deleteRow(undefined)), t.rows.length);
+ t.insertRow(4294967296);
+ out.push(t.rows.length, t.insertRow.length, t.deleteRow.length,
+ row.insertCell.length, row.deleteCell.length, t.createTBody.length);
+ return out;
+ })()"#).await, json!(["ok","ok","ok","TypeError","TypeError","TypeError",
+ "IndexSizeError","IndexSizeError","TypeError","TypeError",1,1,"ok",0,1,0,1,0,1,0]));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn index_coercion_mutations_precede_collection_range_validation() {
+ assert_eq!(evaluate(r#"(() => {
+ const error = fn => { try { fn(); return 'ok'; } catch (e) { return e.name; } };
+ const section = document.createElement('tbody'); section.insertRow();
+ const row = document.createElement('tr'); row.insertCell();
+ const out = [
+ error(() => section.insertRow({valueOf(){section.deleteRow(-1);return 1;}})),
+ section.rows.length,
+ error(() => row.insertCell({valueOf(){row.deleteCell(-1);return 1;}})),
+ row.cells.length];
+ section.insertRow();
+ row.insertCell();
+ out.push(error(() => section.deleteRow({valueOf(){section.deleteRow(-1);return 0;}})),
+ section.rows.length,
+ error(() => row.deleteCell({valueOf(){row.deleteCell(-1);return 0;}})),
+ row.cells.length);
+ const table = document.createElement('table'); table.insertRow();
+ out.push(error(() => table.insertRow({valueOf(){table.deleteRow(-1);return 1;}})),
+ table.rows.length);
+ return out;
+ })()"#).await, json!(["IndexSizeError",0,"IndexSizeError",0,
+ "IndexSizeError",0,"IndexSizeError",0,"IndexSizeError",0]));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn table_members_reject_wrong_receivers_and_preserve_native_reflection() {
+ assert_eq!(evaluate(r#"(() => {
+ const interfaces = [[HTMLTableElement,'tBodies'],[HTMLTableSectionElement,'rows'],
+ [HTMLTableRowElement,'cells'],[HTMLTableRowElement,'rowIndex'],
+ [HTMLTableCellElement,'cellIndex']];
+ const invalid = interfaces.map(([C, key]) => {
+ const get = Object.getOwnPropertyDescriptor(C.prototype, key).get;
+ return [document.createElement('div'), {}, Object.create(C.prototype),
+ document.createElementNS('urn:foreign','tr')].every(value => {
+ try { get.call(value); return false; } catch (e) { return e instanceof TypeError; }
+ });
+ });
+ const method = HTMLTableRowElement.prototype.insertCell;
+ let bad = false;
+ try { method.call(document.createElement('div')); } catch(e) { bad = e instanceof TypeError; }
+ const descriptor = Object.getOwnPropertyDescriptor(HTMLTableRowElement.prototype, 'cells');
+ return [invalid, bad, descriptor.enumerable, descriptor.configurable,
+ descriptor.get.name, descriptor.get.toString(), method.toString(),
+ ['rows','cells','tBodies','rowIndex','cellIndex'].some(key => key in document.createElement('div'))];
+ })()"#).await, json!([[true,true,true,true,true],true,true,true,"get cells",
+ "function get cells() { [native code] }","function insertCell() { [native code] }",false]));
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn section_setters_keep_standard_placement_and_reject_invalid_values() {
+ assert_eq!(evaluate(r#"(() => {
+ const t = document.createElement('table');
+ t.innerHTML = '<caption></caption><colgroup></colgroup><tbody></tbody><tfoot></tfoot>';
+ const bodies = t.tBodies, head = document.createElement('thead'), foot = document.createElement('tfoot');
+ t.tHead = head; t.tFoot = foot;
+ const order = Array.from(t.children, c => c.localName);
+ const error = fn => { try { fn(); return 'ok'; } catch (e) { return e.name; } };
+ const invalid = [error(() => t.tHead = document.createElement('tbody')),
+ error(() => t.tHead = document.createElementNS('urn:foreign','thead')),
+ error(() => t.tFoot = {nodeType:1, localName:'tfoot', namespaceURI:'http://www.w3.org/1999/xhtml'}),
+ error(() => t.tHead = {nodeType:1, localName:'div'}),
+ error(() => {const body=document.createElement('tbody');
+ Object.defineProperty(body,'localName',{value:'thead'});t.tHead=body;})];
+ const retained = [t.tHead === head, t.tFoot === foot, bodies.length];
+ t.tHead = null; t.tFoot = undefined;
+ return [order, invalid, retained, t.tHead, t.tFoot];
+ })()"#).await, json!([["caption","colgroup","thead","tbody","tfoot"],
+ ["HierarchyRequestError","TypeError","TypeError","TypeError","HierarchyRequestError"],[true,true,1],null,null]));
+}
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rs
index bf76d261..e981afb8 100644
--- a/crates/obscura-dom/src/tree.rs
+++ b/crates/obscura-dom/src/tree.rs
@@ -1375,6 +1375,61 @@ impl DomTree {
Some(head)
}
+ fn html_named_children(&self, parent: NodeId, parents: &[&str], children: &[&str]) -> Option<Vec<NodeId>> {
+ let tag = self.html_element_local_name(parent)?;
+ if !parents.contains(&tag.as_ref()) { return None; }
+ Some(self.children(parent).into_iter().filter(|child| {
+ self.html_element_local_name(*child).is_some_and(|tag| children.contains(&tag.as_ref()))
+ }).collect())
+ }
+
+ pub fn table_interface(&self, node: NodeId) -> Option<&'static str> {
+ match self.html_element_local_name(node)?.as_ref() {
+ "table" => Some("HTMLTableElement"),
+ "thead" | "tbody" | "tfoot" => Some("HTMLTableSectionElement"),
+ "tr" => Some("HTMLTableRowElement"),
+ "td" | "th" => Some("HTMLTableCellElement"),
+ _ => None,
+ }
+ }
+
+ pub fn table_sections(&self, table: NodeId, section: &str) -> Option<Vec<NodeId>> {
+ if !["thead", "tbody", "tfoot"].contains(&section) { return None; }
+ self.html_named_children(table, &["table"], &[section])
+ }
+
+ pub fn table_section_rows(&self, section: NodeId) -> Option<Vec<NodeId>> {
+ self.html_named_children(section, &["thead", "tbody", "tfoot"], &["tr"])
+ }
+
+ pub fn table_row_cells(&self, row: NodeId) -> Option<Vec<NodeId>> {
+ self.html_named_children(row, &["tr"], &["td", "th"])
+ }
+
+ pub fn table_row_index(&self, row: NodeId, section_only: bool) -> Option<isize> {
+ if self.html_element_local_name(row)?.as_ref() != "tr" { return None; }
+ let Some(parent) = self.with_node(row, |node| node.parent).flatten() else { return Some(-1) };
+ let rows = match self.html_element_local_name(parent).as_ref().map(|tag| tag.as_ref()) {
+ Some("table") => self.table_rows(parent),
+ Some("thead" | "tbody" | "tfoot") if section_only => self.table_section_rows(parent),
+ Some("thead" | "tbody" | "tfoot") => {
+ self.with_node(parent, |node| node.parent).flatten().and_then(|table| self.table_rows(table))
+ }
+ _ => None,
+ };
+ Some(rows.and_then(|rows| rows.iter().position(|candidate| *candidate == row))
+ .map(|index| index as isize).unwrap_or(-1))
+ }
+
+ pub fn table_cell_index(&self, cell: NodeId) -> Option<isize> {
+ let tag = self.html_element_local_name(cell)?;
+ if !["td", "th"].contains(&tag.as_ref()) { return None; }
+ let cells = self.with_node(cell, |node| node.parent).flatten()
+ .and_then(|row| self.table_row_cells(row));
+ Some(cells.and_then(|cells| cells.iter().position(|candidate| *candidate == cell))
+ .map(|index| index as isize).unwrap_or(-1))
+ }
+
fn html_element_local_name(&self, id: NodeId) -> Option<LocalName> {
self.with_node(id, |node| {
node.as_element().filter(|name| {
@@ -2479,6 +2534,51 @@ mod tests {
assert_eq!(tree.table_rows(NodeId::new(u32::MAX)), None);
}
+ #[test]
+ fn table_child_collections_and_indices_follow_native_ownership() {
+ let tree = DomTree::new();
+ let table = element(&tree, "table");
+ let mut sections = Vec::new();
+ let mut rows = Vec::new();
+ for tag in ["tfoot", "tbody", "thead"] {
+ let section = element(&tree, tag);
+ let row = element(&tree, "tr");
+ tree.append_child(table, section);
+ tree.append_child(section, row);
+ sections.push(section);
+ rows.push(row);
+ }
+ let first = element(&tree, "th");
+ let second = element(&tree, "td");
+ tree.append_child(rows[1], first);
+ tree.append_child(rows[1], second);
+ let foreign = tree.new_node(NodeData::Element {
+ name: QualName::new(None, Namespace::from("urn:foreign"), LocalName::from("td")),
+ attrs: vec![], template_contents: None,
+ mathml_annotation_xml_integration_point: false,
+ });
+ tree.append_child(rows[1], foreign);
+ assert_eq!(tree.table_sections(table, "tbody"), Some(vec![sections[1]]));
+ assert_eq!(tree.table_section_rows(sections[1]), Some(vec![rows[1]]));
+ assert_eq!(tree.table_row_cells(rows[1]), Some(vec![first, second]));
+ assert_eq!(tree.table_interface(first), Some("HTMLTableCellElement"));
+ assert_eq!(tree.table_interface(foreign), None);
+ assert_eq!(tree.table_row_index(rows[0], false), Some(2));
+ assert_eq!(tree.table_row_index(rows[1], false), Some(1));
+ assert_eq!(tree.table_row_index(rows[1], true), Some(0));
+ assert_eq!(tree.table_cell_index(second), Some(1));
+ assert_eq!(tree.table_cell_index(foreign), None);
+ assert_eq!(tree.table_row_cells(table), None);
+ assert_eq!(tree.table_section_rows(NodeId::new(u32::MAX)), None);
+ tree.append_child(sections[2], rows[1]);
+ assert_eq!(tree.table_row_index(rows[1], false), Some(1));
+ assert_eq!(tree.table_row_index(rows[1], true), Some(1));
+ tree.remove_child(rows[1]);
+ assert_eq!(tree.table_row_index(rows[1], false), Some(-1));
+ assert_eq!(tree.table_row_index(rows[1], true), Some(-1));
+ assert_eq!(tree.table_cell_index(second), Some(1));
+ }
+
#[test]
fn select_options_follow_native_ownership_boundaries() {
let tree = DomTree::new();
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 341d2384..2bc2dda5 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -14601,15 +14601,45 @@ for (const [name, tags] of Object.entries({
HTMLTableSectionElement: ['tbody', 'thead', 'tfoot'], HTMLTimeElement: ['time'], HTMLTitleElement: ['title'],
})) {
if (globalThis[name] !== undefined && globalThis[name] !== Element) continue;
- const Interface = class extends Element {
- constructor(nid, token) {
- if (token !== _htmlInterfaceToken) {
+ let Interface;
+ if (name === 'HTMLSelectElement') {
+ let nativeSelectConstructor = null;
+ Interface = class extends Element {
+ constructor(nid, token) {
+ if (token === _htmlInterfaceToken) {
+ if (!nativeSelectConstructor) {
+ const allocate = __obscuraCore.ops.op_create_select_allocator(new.target.prototype,
+ _selectIndexedSnapshot, _selectIndexedSet);
+ nativeSelectConstructor = class extends Element {
+ constructor(nid) {
+ if (typeof nid !== 'number' || (nid >>> 0) !== nid) throw new TypeError('Could not initialize native select');
+ const select = new allocate();
+ select._nid = nid;
+ return select;
+ }
+ };
+ // Keep the public interface for upgrades, but wrap ordinary selects directly.
+ _additionalHtmlElementClasses.select = nativeSelectConstructor;
+ _additionalHtmlElementClasses.SELECT = nativeSelectConstructor;
+ }
+ return new nativeSelectConstructor(nid);
+ }
const entry = _customElementConstructionStack[_customElementConstructionStack.length - 1];
if (!entry || new.target !== entry.constructor || entry.constructed) throw new TypeError('Illegal constructor');
+ super(nid);
}
- super(nid);
- }
- };
+ };
+ } else {
+ Interface = class extends Element {
+ constructor(nid, token) {
+ if (token !== _htmlInterfaceToken) {
+ const entry = _customElementConstructionStack[_customElementConstructionStack.length - 1];
+ if (!entry || new.target !== entry.constructor || entry.constructed) throw new TypeError('Illegal constructor');
+ }
+ super(nid);
+ }
+ };
+ }
Object.defineProperty(Interface, 'name', {value: name, configurable: true});
Object.defineProperty(Interface, 'length', {value: 0, configurable: true});
Object.defineProperty(Interface.prototype, Symbol.toStringTag, {value: name, configurable: true});
@@ -14775,6 +14805,36 @@ function _selectOptions(select) {
if (ids === null) throw new TypeError('Illegal invocation');
return ids.map(_wrapEl);
}
+const _selectIndexedSnapshots = new WeakMap();
+function _selectIndexedSnapshot() {
+ if (_nodeCacheGet(this._nid) !== this) throw new TypeError('Illegal invocation');
+ const epoch = _formEpoch();
+ let snapshot = _selectIndexedSnapshots.get(this);
+ if (!snapshot || snapshot.low !== epoch[0] || snapshot.high !== epoch[1]) {
+ snapshot = {low:epoch[0], high:epoch[1], options:_selectOptions(this)};
+ _selectIndexedSnapshots.set(this, snapshot);
+ }
+ return snapshot.options;
+}
+function _selectIndexedSet(index, value) {
+ if (_nodeCacheGet(this._nid) !== this) throw new TypeError('Illegal invocation');
+ if (value != null) {
+ Reflect.apply(_optionIndexGetter, value, []);
+ if (index >= 100000) throw new RangeError('Maximum supported select length is 100000');
+ }
+ const options = _selectOptions(this);
+ const current = options[index];
+ if (value == null) {
+ if (current) Reflect.apply(_selectElementRemove, current, []);
+ } else if (current !== value) {
+ if (index >= options.length) {
+ if (index > options.length) this.length = index;
+ this.appendChild(value);
+ } else {
+ current.parentNode.replaceChild(value, current);
+ }
+ }
+}
function _optionIndexMember() {
const nid = this && this._nid;
return this && _nodeCacheGet(nid) === this ? _domParse('option_index', nid) : null;
@@ -15181,22 +15241,22 @@ const _htmlCollectionProxy = {
},
};
const _tableRowCollections = new WeakMap();
+const _tableRealmMembers = Object.create(null);
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');
+ return _tableMemberReceiver(this, 'HTMLTableElement', 'rows', 'get').call(this);
}
if (_tableRowCollections.has(this)) return _tableRowCollections.get(this);
- const table = this;
+ const collection = _createTableCollection(this, 'table_rows');
+ _tableRowCollections.set(this, collection);
+ return collection;
+}
+function _createTableCollection(table, op) {
let epoch = -1;
let elements = [];
function refresh() {
if (epoch !== _domMutationEpoch) {
- const ids = _domParse('table_rows', table._nid);
+ const ids = _domParse(op, table._nid);
if (ids === null) throw new TypeError('Illegal invocation');
elements = ids.map(_wrapEl);
epoch = _domMutationEpoch;
@@ -15264,7 +15324,6 @@ function _tableRowsGetter() {
preventExtensions() { return false; },
});
refresh();
- _tableRowCollections.set(table, collection);
return collection;
}
Object.defineProperty(HTMLTableElement, 'length', {value: 0, configurable: true});
@@ -15273,6 +15332,182 @@ Object.defineProperty(HTMLTableElement.prototype, 'rows', {
get: _tableRowsGetter, enumerable: true, configurable: true,
});
_markNative(_tableRowsGetter);
+_tableRealmMembers['HTMLTableElement.rows.get'] = _tableRowsGetter;
+function _tableRealmDispatch(iface, member, accessor, args) {
+ if (!this || _nodeCacheGet(this._nid) !== this) throw new TypeError('Illegal invocation');
+ const implementation = _tableRealmMembers[iface + '.' + member + '.' + (accessor || 'value')];
+ if (!implementation) throw new TypeError('Illegal invocation');
+ return Reflect.apply(implementation, this, args);
+}
+function _tableMemberReceiver(receiver, iface, member, accessor) {
+ if (receiver && _cache.get(receiver._nid) === receiver) return null;
+ const dispatch = receiver && _documentRealmMember(receiver, 'tableMember');
+ if (dispatch && dispatch !== _tableRealmDispatch) {
+ return (...args) => Reflect.apply(dispatch, receiver, [iface, member, accessor, args]);
+ }
+ throw new TypeError('Illegal invocation');
+}
+function _tableMemberValue(receiver, op) {
+ const value = _domParse(op, receiver._nid);
+ if (value === null) throw new TypeError('Illegal invocation');
+ return value;
+}
+function _tableElementTagMember() {
+ if (!this || _nodeCacheGet(this._nid) !== this) throw new TypeError('Expected an HTMLElement');
+ const info = _domParse('tag_name', this._nid, 'interface');
+ if (typeof info === 'string' && info) return info.toLowerCase();
+ if (info && info[1] === 'http://www.w3.org/1999/xhtml') return info[2];
+ throw new TypeError('Expected an HTMLElement');
+}
+function _tableElementTag(value) {
+ if (value && _nodeCacheGet(value._nid) === value) {
+ return Reflect.apply(_tableElementTagMember, value, []);
+ }
+ const member = value && _documentRealmMember(value, 'tableElementTag');
+ if (member && member !== _tableElementTagMember) return Reflect.apply(member, value, []);
+ throw new TypeError('Expected an HTMLElement');
+}
+function _defineTableGetter(iface, member, op, collection = false, element = false) {
+ const cache = collection ? new WeakMap() : null;
+ const getter = function () {
+ const foreign = _tableMemberReceiver(this, iface, member, 'get');
+ if (foreign) return foreign.call(this);
+ if (cache) {
+ if (cache.has(this)) return cache.get(this);
+ const value = _createTableCollection(this, op);
+ cache.set(this, value);
+ return value;
+ }
+ const value = _tableMemberValue(this, op);
+ return element ? (value.length ? _wrapEl(value[0]) : null) : value;
+ };
+ Object.defineProperty(getter, 'name', {value: 'get ' + member, configurable: true});
+ Object.defineProperty(globalThis[iface].prototype, member, {
+ get: getter, enumerable: true, configurable: true,
+ });
+ _markNative(getter);
+ _tableRealmMembers[iface + '.' + member + '.get'] = getter;
+}
+_defineTableGetter('HTMLTableElement', 'tBodies', 'table_bodies', true);
+_defineTableGetter('HTMLTableElement', 'tHead', 'table_head', false, true);
+_defineTableGetter('HTMLTableElement', 'tFoot', 'table_foot', false, true);
+_defineTableGetter('HTMLTableSectionElement', 'rows', 'table_section_rows', true);
+_defineTableGetter('HTMLTableRowElement', 'cells', 'table_row_cells', true);
+_defineTableGetter('HTMLTableRowElement', 'rowIndex', 'table_row_index');
+_defineTableGetter('HTMLTableRowElement', 'sectionRowIndex', 'table_section_row_index');
+_defineTableGetter('HTMLTableCellElement', 'cellIndex', 'table_cell_index');
+function _defineTableMethod(iface, member, implementation) {
+ const method = function (...args) {
+ const foreign = _tableMemberReceiver(this, iface, member);
+ if (foreign) return foreign.apply(this, args);
+ if (_tableMemberValue(this, 'table_interface') !== iface) throw new TypeError('Illegal invocation');
+ return implementation.apply(this, args);
+ };
+ Object.defineProperty(method, 'name', {value: member, configurable: true});
+ Object.defineProperty(method, 'length', {
+ value: member.startsWith('delete') ? 1 : 0, configurable: true,
+ });
+ Object.defineProperty(globalThis[iface].prototype, member, {
+ value: method, writable: true, enumerable: true, configurable: true,
+ });
+ _markNative(method);
+ _tableRealmMembers[iface + '.' + member + '.value'] = method;
+}
+function _tableIndex(index, length, method, iface, inserting) {
+ index = +index | 0;
+ if (index < -1 || index > length - (inserting ? 0 : 1)) {
+ throw new DOMException("Failed to execute '" + method + "' on '" + iface
+ + "': The index is outside the allowed range.", 'IndexSizeError');
+ }
+ return index;
+}
+function _insertTableRow(rows, container, index, iface) {
+ index = _tableIndex(index, rows.length, 'insertRow', iface, true);
+ const row = container.ownerDocument.createElement('tr');
+ if (index === -1 || index === rows.length) {
+ (rows.length ? rows[rows.length - 1].parentNode : container).appendChild(row);
+ } else {
+ rows[index].parentNode.insertBefore(row, rows[index]);
+ }
+ return row;
+}
+function _deleteTableMember(rows, index, method, iface) {
+ index = _tableIndex(index, rows.length, method, iface, false);
+ if (index === -1) {
+ if (rows.length) rows[rows.length - 1].remove();
+ } else {
+ rows[index].remove();
+ }
+}
+_defineTableMethod('HTMLTableElement', 'createTBody', function () {
+ const body = this.ownerDocument.createElement('tbody');
+ const bodies = this.tBodies;
+ const last = bodies[bodies.length - 1];
+ this.insertBefore(body, last ? last.nextSibling : null);
+ return body;
+});
+_defineTableMethod('HTMLTableElement', 'insertRow', function (index = -1) {
+ index = +index | 0;
+ const rows = this.rows;
+ index = _tableIndex(index, rows.length, 'insertRow', 'HTMLTableElement', true);
+ if (rows.length) return _insertTableRow(rows, this, index, 'HTMLTableElement');
+ const bodies = this.tBodies;
+ const body = bodies.length ? bodies[bodies.length - 1] : this.createTBody();
+ return _insertTableRow(rows, body, index, 'HTMLTableElement');
+});
+_defineTableMethod('HTMLTableElement', 'deleteRow', function (index) {
+ if (!arguments.length) throw new TypeError("Failed to execute 'deleteRow': 1 argument required.");
+ index = +index | 0;
+ _deleteTableMember(this.rows, index, 'deleteRow', 'HTMLTableElement');
+});
+_defineTableMethod('HTMLTableSectionElement', 'insertRow', function (index = -1) {
+ index = +index | 0;
+ return _insertTableRow(this.rows, this, index, 'HTMLTableSectionElement');
+});
+_defineTableMethod('HTMLTableSectionElement', 'deleteRow', function (index) {
+ if (!arguments.length) throw new TypeError("Failed to execute 'deleteRow': 1 argument required.");
+ index = +index | 0;
+ _deleteTableMember(this.rows, index, 'deleteRow', 'HTMLTableSectionElement');
+});
+_defineTableMethod('HTMLTableRowElement', 'insertCell', function (index = -1) {
+ index = +index | 0;
+ const cells = this.cells;
+ index = _tableIndex(index, cells.length, 'insertCell', 'HTMLTableRowElement', true);
+ const cell = this.ownerDocument.createElement('td');
+ this.insertBefore(cell, index === -1 || index === cells.length ? null : cells[index]);
+ return cell;
+});
+_defineTableMethod('HTMLTableRowElement', 'deleteCell', function (index) {
+ if (!arguments.length) throw new TypeError("Failed to execute 'deleteCell': 1 argument required.");
+ index = +index | 0;
+ _deleteTableMember(this.cells, index, 'deleteCell', 'HTMLTableRowElement');
+});
+for (const [member, tag, op] of [['tHead', 'thead', 'table_head'], ['tFoot', 'tfoot', 'table_foot']]) {
+ const setter = function (value) {
+ const foreign = _tableMemberReceiver(this, 'HTMLTableElement', member, 'set');
+ if (foreign) return foreign.call(this, value);
+ _tableMemberValue(this, op);
+ if (value != null) {
+ if (_tableElementTag(value) !== tag) throw new DOMException('Invalid table section', 'HierarchyRequestError');
+ }
+ const current = this[member];
+ if (current) current.remove();
+ if (value == null) return;
+ if (tag === 'tfoot') this.appendChild(value);
+ else {
+ let before = this.firstChild;
+ while (before && _isHTMLEl(before) && ['caption', 'colgroup'].includes(before.localName)) {
+ before = before.nextSibling;
+ }
+ this.insertBefore(value, before);
+ }
+ };
+ Object.defineProperty(setter, 'name', {value: 'set ' + member, configurable: true});
+ Object.defineProperty(HTMLTableElement.prototype, member, {set: setter});
+ _markNative(setter);
+ _tableRealmMembers['HTMLTableElement.' + member + '.set'] = setter;
+}
+Object.freeze(_tableRealmMembers);
// True for elements in the HTML namespace (the only ones whose name attribute
// contributes to an HTMLCollection's supported property names).
function _isHTMLEl(el) {
@@ -19206,6 +19441,8 @@ const _documentMembers = Object.freeze(Object.fromEntries([
['formControls', _formControlsMember],
['validateSelect', _validateSelectMember],
['optionIndex', _optionIndexMember],
+ ['tableMember', _tableRealmDispatch],
+ ['tableElementTag', _tableElementTagMember],
['domNodeReference', function() {
const nid = this._nid;
if (_nodeCacheGet(nid) !== this) throw new TypeError('Not a current DOM node');
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 8445373e..df379b50 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -2843,6 +2843,32 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
rows.into_iter().map(|row| row.index()).collect::<Vec<_>>()
})).to_string()
}
+ "table_interface" => {
+ let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));
+ serde_json::json!(dom.table_interface(nid)).to_string()
+ }
+ "table_head" | "table_foot" | "table_bodies" | "table_section_rows" | "table_row_cells" => {
+ let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));
+ let elements = match cmd.as_str() {
+ "table_head" => dom.table_sections(nid, "thead"),
+ "table_foot" => dom.table_sections(nid, "tfoot"),
+ "table_bodies" => dom.table_sections(nid, "tbody"),
+ "table_section_rows" => dom.table_section_rows(nid),
+ _ => dom.table_row_cells(nid),
+ };
+ serde_json::json!(elements.map(|elements| {
+ elements.into_iter().map(|element| element.index()).collect::<Vec<_>>()
+ })).to_string()
+ }
+ "table_row_index" | "table_section_row_index" | "table_cell_index" => {
+ let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));
+ let index = match cmd.as_str() {
+ "table_row_index" => dom.table_row_index(nid, false),
+ "table_section_row_index" => dom.table_row_index(nid, true),
+ _ => dom.table_cell_index(nid),
+ };
+ serde_json::json!(index).to_string()
+ }
"select_options" => {
let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));
serde_json::json!(dom.select_options(nid).map(|options| {
@@ -7041,6 +7067,139 @@ pub(crate) fn document_realm<'s, 'i>(
Some((owner, members))
}
+fn select_index_callback<'s, 'i>(
+ scope: &mut v8::PinScope<'s, 'i>,
+ object: v8::Local<'_, v8::Object>,
+ data: v8::Local<'_, v8::Value>,
+ field: u32,
+ args: &[v8::Local<'s, v8::Value>],
+) -> Option<v8::Local<'s, v8::Value>> {
+ let data = v8::Local::new(scope, data);
+ let callback = v8::Local::<v8::Array>::try_from(data).ok()
+ .and_then(|values| values.get_index(scope, field))
+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok());
+ let Some(callback) = callback else {
+ if let Some(message) = v8::String::new(scope, "Invalid native select") {
+ let error = v8::Exception::type_error(scope, message);
+ scope.throw_exception(error);
+ }
+ return None;
+ };
+ callback.call(scope, object.into(), args)
+}
+
+fn select_index_values<'s, 'i>(
+ scope: &mut v8::PinScope<'s, 'i>,
+ object: v8::Local<'_, v8::Object>,
+ data: v8::Local<'_, v8::Value>,
+) -> Option<v8::Local<'s, v8::Array>> {
+ let value = select_index_callback(scope, object, data, 0, &[])?;
+ if let Ok(values) = v8::Local::<v8::Array>::try_from(value) { return Some(values); }
+ if let Some(message) = v8::String::new(scope, "Invalid native select options") {
+ let error = v8::Exception::type_error(scope, message);
+ scope.throw_exception(error);
+ }
+ None
+}
+
+fn select_allocator(
+ scope: &mut v8::PinScope,
+ args: v8::FunctionCallbackArguments,
+ _rv: v8::ReturnValue,
+) {
+ if args.is_construct_call() { return; }
+ if let Some(message) = v8::String::new(scope, "Illegal constructor") {
+ let error = v8::Exception::type_error(scope, message);
+ scope.throw_exception(error);
+ }
+}
+
+#[op2(reentrant)]
+fn op_create_select_allocator<'s, 'i>(
+ scope: &mut v8::PinScope<'s, 'i>,
+ prototype: v8::Local<'s, v8::Object>,
+ refresh: v8::Local<'s, v8::Function>,
+ setter: v8::Local<'s, v8::Function>,
+) -> Result<v8::Local<'s, v8::Function>, deno_error::JsErrorBox> {
+ let context = prototype.get_creation_context(scope)
+ .ok_or_else(|| deno_error::JsErrorBox::type_error("Invalid select creation realm"))?;
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let key = v8::String::new(scope, "_nid")
+ .ok_or_else(|| deno_error::JsErrorBox::generic("Could not create select node key"))?;
+ let data = v8::Array::new_with_elements(scope, &[refresh.into(), setter.into()]);
+ let constructor = v8::FunctionTemplate::builder(select_allocator).build(scope);
+ let template = constructor.instance_template(scope);
+ let empty_nid = v8::Integer::new(scope, 0);
+ template.set(key.into(), empty_nid.into());
+ template.set_indexed_property_handler(v8::IndexedPropertyHandlerConfiguration::new().data(data.into())
+ .getter(|scope: &mut v8::PinScope, index: u32,
+ args: v8::PropertyCallbackArguments, mut rv: v8::ReturnValue<v8::Value>| {
+ let Some(values) = select_index_values(scope, args.holder(), args.data()) else { return v8::Intercepted::kYes };
+ if index >= values.length() { return v8::Intercepted::kNo; }
+ if let Some(value) = values.get_index(scope, index) { rv.set(value); }
+ v8::Intercepted::kYes
+ })
+ .setter(|scope: &mut v8::PinScope, index: u32, value: v8::Local<v8::Value>,
+ args: v8::PropertyCallbackArguments, mut rv: v8::ReturnValue<()>| {
+ let value = v8::Local::new(scope, value);
+ let index = v8::Integer::new_from_unsigned(scope, index);
+ if select_index_callback(scope, args.holder(), args.data(), 1, &[index.into(), value]).is_some() {
+ rv.set_bool(true);
+ }
+ v8::Intercepted::kYes
+ })
+ .query(|scope: &mut v8::PinScope, index: u32,
+ args: v8::PropertyCallbackArguments, mut rv: v8::ReturnValue<v8::Integer>| {
+ let Some(values) = select_index_values(scope, args.holder(), args.data()) else { return v8::Intercepted::kYes };
+ if index >= values.length() { return v8::Intercepted::kNo; }
+ rv.set_int32(0);
+ v8::Intercepted::kYes
+ })
+ .definer(|scope: &mut v8::PinScope, index: u32, descriptor: &v8::PropertyDescriptor,
+ args: v8::PropertyCallbackArguments, mut rv: v8::ReturnValue<()>| {
+ if descriptor.has_get() || descriptor.has_set() {
+ rv.set_bool(true);
+ return v8::Intercepted::kYes;
+ }
+ let value = if descriptor.has_value() { descriptor.value() } else { v8::undefined(scope).into() };
+ let value = v8::Local::new(scope, value);
+ let index = v8::Integer::new_from_unsigned(scope, index);
+ if select_index_callback(scope, args.holder(), args.data(), 1, &[index.into(), value]).is_some() {
+ rv.set_bool(true);
+ }
+ v8::Intercepted::kYes
+ })
+ .deleter(|scope: &mut v8::PinScope, index: u32,
+ args: v8::PropertyCallbackArguments, mut rv: v8::ReturnValue<v8::Boolean>| {
+ let Some(values) = select_index_values(scope, args.holder(), args.data()) else { return v8::Intercepted::kYes };
+ let allowed = index >= values.length();
+ if !allowed && args.should_throw_on_error() {
+ if let Some(message) = v8::String::new(scope, "Cannot delete a supported select index") {
+ let error = v8::Exception::type_error(scope, message);
+ scope.throw_exception(error);
+ }
+ }
+ rv.set_bool(allowed);
+ v8::Intercepted::kYes
+ })
+ .enumerator(|scope: &mut v8::PinScope,
+ args: v8::PropertyCallbackArguments, mut rv: v8::ReturnValue<v8::Array>| {
+ if let Some(values) = select_index_values(scope, args.holder(), args.data()) {
+ let keys: Vec<v8::Local<v8::Value>> = (0..values.length())
+ .map(|index| v8::Integer::new_from_unsigned(scope, index).into()).collect();
+ rv.set(v8::Array::new_with_elements(scope, &keys));
+ }
+ }));
+ let constructor = constructor.get_function(scope)
+ .ok_or_else(|| deno_error::JsErrorBox::generic("Could not create native select constructor"))?;
+ let key = v8::String::new(scope, "prototype")
+ .ok_or_else(|| deno_error::JsErrorBox::generic("Could not create select prototype key"))?;
+ if constructor.set(scope, key.into(), prototype.into()) != Some(true) {
+ return Err(deno_error::JsErrorBox::generic("Could not initialize native select prototype"));
+ }
+ Ok(constructor)
+}
+
#[op2]
fn op_document_realm_member<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
@@ -8257,6 +8416,7 @@ pub fn build_extension() -> Extension {
op_dom(),
op_form_owner(),
op_form_cache_buffer(),
+ op_create_select_allocator(),
op_script_mark_started(),
op_script_try_start(),
op_shadow_attach(),
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 4562edc9..f8ac218d 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -5238,6 +5238,68 @@ mod tests {
})()"#).unwrap(), serde_json::json!([true,2,2]));
}
+ #[test]
+ fn table_members_preserve_child_realm_collections_and_borrowed_methods() {
+ let mut rt = setup_runtime("<html><body><table><tr><td>Parent</td></tr></table></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!(rt.evaluate(r#"(() => {
+ const child = globalThis.__obscura_frameObjects[1].document;
+ const table = child.querySelector('table'), body = table.tBodies[0], row = body.rows[0];
+ const cells = row.cells;
+ const outerGetter = Object.getOwnPropertyDescriptor(HTMLTableRowElement.prototype, 'cells').get;
+ const outerMethod = HTMLTableRowElement.prototype.insertCell;
+ const cell = outerMethod.call(row);
+ const branded = cells instanceof child.defaultView.HTMLCollection
+ && cell instanceof child.defaultView.HTMLTableCellElement;
+ const borrowed = outerGetter !== Object.getOwnPropertyDescriptor(child.defaultView.HTMLTableRowElement.prototype, 'cells').get
+ && outerGetter.call(row) === cells;
+ table.insertRow(0).insertCell();
+ const indices = [row.rowIndex, row.sectionRowIndex, cell.cellIndex];
+ row.deleteCell(0);
+ return [branded, borrowed, cells.length, indices, cell.cellIndex,
+ table.cloneNode(true).rows[1].cells.length, document.querySelector('td').textContent];
+ })()"#).unwrap(), serde_json::json!([true,true,1,[1,1,1],0,1,"Parent"]));
+ }
+
+ #[test]
+ fn native_select_factory_preserves_child_clones_and_custom_upgrade_identity() {
+ let mut rt = setup_runtime("<html><body><select id='custom' is='native-select'><option value='a'>A</option></select></body></html>");
+ let _frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://example.com/child", "<html><body><select><option value='a'>A</option><option value='b'>B</option></select></body></html>").unwrap();
+ assert_eq!(rt.evaluate(r#"(() => {
+ const child = globalThis.__obscura_frameObjects[1].document;
+ const select = child.querySelector('select'), option = child.createElement('option');
+ option.value = 'n'; select[0] = option;
+ const clone = select.cloneNode(true);
+ const childChecks = [select[0] === option,
+ select instanceof child.defaultView.HTMLSelectElement,
+ clone[0].value, clone[0] instanceof child.defaultView.HTMLOptionElement,
+ Object.getOwnPropertyDescriptor(select, '0').value === option,
+ Reflect.deleteProperty(select, '0')];
+ Reflect.defineProperty(select, '1', {value:null});
+ let strictDelete = false;
+ try { (function(){'use strict';delete select[0];})(); }
+ catch(e) { strictDelete = e instanceof TypeError; }
+ const retained = document.getElementById('custom');
+ retained.marker = 'retained';
+ class NativeSelect extends HTMLSelectElement {
+ constructor() { super(); this.upgraded = true; this[0].value = 'upgraded'; }
+ }
+ customElements.define('native-select', NativeSelect, {extends:'select'});
+ // Customized-built-in matching is separate from the existing upgrade mechanism.
+ customElements._upgradeElement(retained, NativeSelect);
+ const created = document.createElement('select');
+ created.appendChild(document.createElement('option'));
+ const foreign = document.createElementNS('urn:foreign', 'select');
+ return [childChecks, select.length, select[1] === undefined, strictDelete,
+ retained === document.getElementById('custom'), retained.marker,
+ retained.upgraded, retained instanceof NativeSelect, retained[0].value,
+ created[0] === created.item(0), '0' in foreign];
+ })()"#).unwrap(), serde_json::json!([[true,true,"n",true,true,false],
+ 1,true,true,true,"retained",true,true,"upgraded",true,false]));
+ }
+
#[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.md
index 20e937b7..afd4d309 100644
--- a/docs/Architecture-overview.md
+++ b/docs/Architecture-overview.md
@@ -161,8 +161,16 @@ 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.
+mutation invalidates its row snapshot. Section `rows`, row `cells`, and table
+`tBodies` share this cached, owning-realm collection implementation. Native
+indices exclude nested tables and foreign namespaces. Table section access,
+row/cell insertion and deletion, and `createTBody` preserve their actual DOM
+parents and invalidate retained collections through ordinary DOM mutations.
+This also supports Playwright's implicit table-header role calculation.
+These collections retain the existing `rows` write-rejection behavior: indexed
+and supported named assignments/redefinitions are rejected without changing
+the collection. Chromium instead reports success for ignored writes, including
+ignored nonconfigurable redefinitions; that reflection difference remains.
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
@@ -175,8 +183,19 @@ contribute options to the outer select. Numeric insertion targets retain their
actual optgroup parent. Length assignments above 100,000 are rejected with a
warning rather than attempting unbounded allocation. These APIs also support
borrowed methods on child-realm nodes. Select collections still use the existing
-snapshot HTMLCollection implementation; indexed properties on the select itself
-and the remaining table construction APIs are separate work.
+snapshot HTMLCollection implementation. Numeric select access uses V8 indexed
+handlers, not a Proxy around ordinary DOM properties. Fresh selects allocate the
+native wrapper directly; custom-element upgrades retain that same wrapper.
+Select-only constructor state is isolated from ordinary HTML interface constructors.
+The private derived constructor initializes the predeclared node slot in JavaScript
+without allocating a discarded JavaScript element or setting each node through V8's C API.
+Indexed reads reuse option
+snapshots keyed by the native form mutation generation. Assignments replace or
+remove the actual option and fill gaps with blank options. Non-null assignments
+past the same 100,000 option limit throw RangeError. Supported indices remain
+configurable and writable in reflection, while deletion is rejected and
+redefinition uses the platform indexed setter. Named getters and existing select
+methods retain their ordinary lookup paths.
CDP `DOM.querySelector` and `DOM.querySelectorAll` search descendants of the
requested node, including explicit shadow roots, without crossing into sibling
diff --git a/render-repros/legacy-table-apis.html b/render-repros/legacy-table-apis.html
new file mode 100644
index 00000000..682ddb37
--- /dev/null
+++ b/render-repros/legacy-table-apis.html
@@ -0,0 +1,36 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Legacy table APIs</title>
+<style>
+body { margin: 24px; font: 16px Arial, sans-serif; }
+table { width: 360px; border-collapse: collapse; }
+th, td { padding: 8px; border: 1px solid #456; text-align: left; }
+thead { background: #dceaff; }
+tfoot { background: #eee; }
+#result { margin-top: 16px; }
+</style>
+<select id="s"><option value="a">A</option><option value="b" selected>B</option></select>
+<table id="t">
+ <tfoot><tr><td>Footer</td><td>Last</td></tr></tfoot>
+ <thead><tr><th>Header</th><th>Value</th></tr></thead>
+ <tbody><tr><td>First</td><td>1</td></tr></tbody>
+</table>
+<p id="result">RUNNING</p>
+<script>
+const table = document.getElementById('t');
+const select = document.getElementById('s');
+const cells = table.tBodies[0].rows[0].cells;
+const row = table.insertRow(2);
+row.insertCell().textContent = 'Inserted';
+row.insertCell().textContent = '2';
+row.insertCell().textContent = 'Remove';
+row.deleteCell(-1);
+const body = table.createTBody();
+body.insertRow().insertCell().textContent = 'Remove';
+body.deleteRow(-1);
+const values = [select.length, select[select.selectedIndex].value,
+ table.rows.length, cells.length, row.rowIndex, row.sectionRowIndex,
+ row.cells[1].cellIndex, table.tBodies.length, body.rows.length];
+document.getElementById('result').textContent = 'Result: ' + values.join(',');
+document.documentElement.dataset.legacyTableResult = JSON.stringify(values);
+</script>
diff --git a/scripts/ci/perf_smoke.py b/scripts/ci/perf_smoke.py
index e16b96ae..75f55261 100755
--- a/scripts/ci/perf_smoke.py
+++ b/scripts/ci/perf_smoke.py
@@ -1,5 +1,8 @@
#!/usr/bin/env python3
-"""Interleaved latency, CPU, peak-RSS, and result-correctness comparison."""
+"""Interleaved latency, CPU, peak-RSS, and result-correctness comparison.
+
+Linux wait4 supplies precise CPU and peak RSS for the timeout-guarded process tree.
+"""
from __future__ import annotations
@@ -55,6 +58,30 @@ SCENARIOS = {
"(() => {document.body.innerHTML='<table><tr><td>row</td></tr></table>'.repeat(5000);return document.querySelectorAll('table').length})()",
5000,
),
+ "table-rows-hot": (
+ "(() => {document.body.innerHTML='<table><thead><tr><th>head</th></tr></thead><tbody>'+'<tr><td>body</td></tr>'.repeat(100)+'</tbody></table>';const t=document.querySelector('table'),first=t.rows[0];let n=0;for(let i=0;i<1000000;i++){const rows=t.rows;if(rows[0]===first)n+=rows.length;}return n})()",
+ 101000000,
+ ),
+ "table-cells-hot": (
+ "(() => {document.body.innerHTML='<table><tbody>'+'<tr><td>A</td><td>B</td><td>C</td></tr>'.repeat(100)+'</tbody></table>';const row=document.querySelector('tr');let n=0;for(let i=0;i<100000;i++){const cells=row.cells||row.children;n+=cells.length;if(cells[0].textContent==='A')n++;}return n})()",
+ 400000,
+ ),
+ "select-create-wrap": (
+ "(() => {document.body.innerHTML='<select><option>A</option><option>B</option></select>'.repeat(5000);return document.querySelectorAll('select').length})()",
+ 5000,
+ ),
+ "select-create-wrap-50k": (
+ "(() => {document.body.innerHTML='<select><option>A</option><option>B</option></select>'.repeat(50000);return document.querySelectorAll('select').length})()",
+ 50000,
+ ),
+ "select-item-or-index-hot": (
+ "(() => {document.body.innerHTML='<select><option>A</option><option>B</option></select>';const s=document.querySelector('select'),first=s.item(0),indexed='0' in s;let n=0;for(let i=0;i<1000000;i++)if((indexed?s[0]:s.item(0))===first)n++;return n})()",
+ 1000000,
+ ),
+ "select-existing-getters-hot": (
+ "(() => {document.body.innerHTML='<select><option>A</option><option>B</option></select>';const s=document.querySelector('select');let n=0;for(let i=0;i<1000000;i++)n+=s.length;return n})()",
+ 2000000,
+ ),
"form-elements-owned": (
"(() => {document.body.innerHTML='<form id=f>'+'<input name=inside>'.repeat(1000)+'</form>';const f=document.getElementById('f');let n=0;for(let i=0;i<200;i++)n+=f.elements.length;return n})()",
200000,
@@ -102,8 +129,6 @@ class Handler(BaseHTTPRequestHandler):
def run_once(binary: Path, url: str, expression: str, expected: int) -> tuple[float, int, float]:
- with tempfile.NamedTemporaryFile(prefix="obscura-rss-", delete=False) as rss_file:
- rss_path = Path(rss_file.name)
with tempfile.NamedTemporaryFile(prefix="obscura-stdout-", delete=False) as stdout_file:
stdout_path = Path(stdout_file.name)
with tempfile.NamedTemporaryFile(prefix="obscura-stderr-", delete=False) as stderr_file:
@@ -117,11 +142,6 @@ def run_once(binary: Path, url: str, expression: str, expected: int) -> tuple[fl
"--fsize=2097152",
"--nofile=256",
"--",
- "/usr/bin/time",
- "-f",
- "%U %S %M",
- "-o",
- str(rss_path),
str(binary),
"fetch",
url,
@@ -144,8 +164,9 @@ def run_once(binary: Path, url: str, expression: str, expected: int) -> tuple[fl
start_new_session=True,
)
try:
- # A Python timeout wait polls exits in steps up to 50 ms.
- process.wait()
+ # Linux wait4 keeps precise CPU counters for the guarded process tree.
+ _, status, usage = os.wait4(process.pid, 0)
+ process.returncode = os.waitstatus_to_exitcode(status)
finally:
# Remove background descendants left by an untrusted candidate binary.
try:
@@ -156,9 +177,9 @@ def run_once(binary: Path, url: str, expression: str, expected: int) -> tuple[fl
elapsed_ms = (time.perf_counter() - started) * 1000
if process.returncode != 0:
raise RuntimeError(f"{binary} exited with status {process.returncode}")
- user, system, peak = rss_path.read_text(encoding="ascii").split()
- cpu_seconds, rss_kib = float(user) + float(system), int(peak)
- if not math.isfinite(cpu_seconds) or float(user) < 0 or float(system) < 0 or rss_kib <= 0:
+ cpu_seconds = usage.ru_utime + usage.ru_stime
+ rss_kib = usage.ru_maxrss
+ if not math.isfinite(cpu_seconds) or usage.ru_utime < 0 or usage.ru_stime < 0 or rss_kib <= 0:
raise RuntimeError(f"{binary} produced an invalid CPU/RSS measurement")
try:
result = json.loads(stdout_path.read_text(encoding="utf-8"))
@@ -170,7 +191,6 @@ def run_once(binary: Path, url: str, expression: str, expected: int) -> tuple[fl
)
return elapsed_ms, rss_kib, cpu_seconds
finally:
- rss_path.unlink(missing_ok=True)
stdout_path.unlink(missing_ok=True)
stderr_path.unlink(missing_ok=True)
@@ -254,7 +274,7 @@ def main() -> None:
}
lines.append(
f"| {scenario} | {base_latency:.1f} ms | {pr_latency:.1f} ms | "
- f"{(latency_ratio - 1) * 100:+.1f}% | {base_cpu:.2f} s | {pr_cpu:.2f} s | {base_rss / 1024:.1f} MiB | "
+ f"{(latency_ratio - 1) * 100:+.1f}% | {base_cpu:.4f} s | {pr_cpu:.4f} s | {base_rss / 1024:.1f} MiB | "
f"{pr_rss / 1024:.1f} MiB | {(rss_ratio - 1) * 100:+.1f}% |\n"
)
latency_delta = pr_latency - base_latency
@@ -265,7 +285,7 @@ def main() -> None:
):
failures.append(f"{scenario} latency is {latency_ratio:.2f}x the base")
if pr_cpu > base_cpu * CPU_FAILURE_RATIO and pr_cpu - base_cpu > CPU_FAILURE_DELTA_SECONDS + 1e-9:
- failures.append(f"{scenario} CPU increased from {base_cpu:.2f} s to {pr_cpu:.2f} s")
+ failures.append(f"{scenario} CPU increased from {base_cpu:.4f} s to {pr_cpu:.4f} s")
if rss_ratio > RSS_FAILURE_RATIO and rss_delta > RSS_FAILURE_DELTA_KIB:
failures.append(f"{scenario} RSS is {rss_ratio:.2f}x the base")
diff --git a/scripts/ci/test_perf_smoke.py b/scripts/ci/test_perf_smoke.py
index 9e0461f2..3dd7889b 100644
--- a/scripts/ci/test_perf_smoke.py
+++ b/scripts/ci/test_perf_smoke.py
@@ -22,17 +22,21 @@ class ProcessMeasurementTests(unittest.TestCase):
commands.append(command)
kwargs["stdout"].write(b"5000\n")
kwargs["stdout"].flush()
- Path(command[command.index("-o") + 1]).write_text("0.12 0.03 1024\n")
self.assertTrue(kwargs["start_new_session"])
return process
with patch.object(perf_smoke.subprocess, "Popen", side_effect=start), \
+ patch.object(perf_smoke.os, "wait4", return_value=(
+ process.pid, 0, Mock(ru_utime=0.123456, ru_stime=0.027778, ru_maxrss=1024),
+ )) as wait, \
patch.object(perf_smoke.os, "killpg") as cleanup:
_, rss, cpu = perf_smoke.run_once(Path("/fake/engine"), "http://localhost/", "5000", 5000)
self.assertEqual(rss, 1024)
- self.assertAlmostEqual(cpu, 0.15)
- process.wait.assert_called_once_with()
+ self.assertAlmostEqual(cpu, 0.151234)
+ wait.assert_called_once_with(process.pid, 0)
+ process.wait.assert_not_called()
self.assertEqual(commands[0][:4], ["timeout", "--signal=KILL", "45", "prlimit"])
+ self.assertNotIn("/usr/bin/time", commands[0])
self.assertIn("--fsize=2097152", commands[0])
self.assertIn("--nofile=256", commands[0])
cleanup.assert_called_once_with(process.pid, signal.SIGKILL)
@@ -57,24 +61,27 @@ class RegressionGateTests(unittest.TestCase):
baseline.touch()
candidate.touch()
clock = [0.0]
+ measured_cpu = [0.0]
def start(command, **kwargs):
changed = str(candidate) in command
clock[0] += (candidate_latency if changed else base_latency) / 1000
- cpu = candidate_cpu if changed else base_cpu
- metrics = f"{cpu:.2f} 0.00 40960\n" if command[command.index("-f") + 1] != "%M" else "40960\n"
- Path(command[command.index("-o") + 1]).write_text(metrics)
+ measured_cpu[0] = candidate_cpu if changed else base_cpu
kwargs["stdout"].write(b"5\n")
kwargs["stdout"].flush()
process = Mock(pid=12345, returncode=0)
process.wait.return_value = 0
return process
+ def wait(pid, _flags):
+ return pid, 0, Mock(ru_utime=measured_cpu[0], ru_stime=0.0, ru_maxrss=40960)
+
logs = io.StringIO()
error = None
with patch.object(sys, "argv", ["perf_smoke.py", "--base", str(baseline), "--candidate", str(candidate), "--output", str(output)]), \
patch.object(perf_smoke, "SCENARIOS", {"probe": ("5", 5)}), \
patch.object(perf_smoke.subprocess, "Popen", side_effect=start), \
+ patch.object(perf_smoke.os, "wait4", side_effect=wait), \
patch.object(perf_smoke.time, "perf_counter", side_effect=lambda: clock[0]), \
patch.object(perf_smoke.os, "killpg"), \
patch.dict(perf_smoke.os.environ, {"GITHUB_STEP_SUMMARY": ""}), \
@@ -100,6 +107,17 @@ class RegressionGateTests(unittest.TestCase):
error, _, _ = self.compare(50, 55, 0.02, 0.04)
self.assertIsNone(error)
+ def test_precise_cpu_is_not_rounded_into_a_false_regression(self):
+ error, report, _ = self.compare(300, 310, 0.2591, 0.2799)
+ self.assertIsNone(error)
+ self.assertEqual(report["scenarios"]["probe"]["base_cpu_seconds"], 0.2591)
+ self.assertEqual(report["scenarios"]["probe"]["candidate_cpu_seconds"], 0.2799)
+
+ def test_small_cpu_regression_still_exceeds_unchanged_relative_and_absolute_gates(self):
+ error, _, logs = self.compare(300, 300, 0.25, 0.276)
+ self.assertIsNotNone(error)
+ self.assertIn("::error::probe CPU", logs)
+
def test_nonfinite_cpu_measurement_is_rejected(self):
with self.assertRaisesRegex(RuntimeError, "invalid CPU"):
self.compare(100, 100, float("nan"), 0.12)