The headless browser for AI agents and web scraping
Implement native select option ownership and legacy APIs
SGavrl25700b93598f
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rsindex 39ede23d..a3091879 100644--- a/crates/obscura-dom/src/tree.rs+++ b/crates/obscura-dom/src/tree.rs@@ -1280,11 +1280,7 @@ impl DomTree {/// 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();+ let html_tag = |id| self.html_element_local_name(id);if html_tag(table).as_ref().map(|tag| tag.as_ref()) != Some("table") {return None;}@@ -1309,6 +1305,60 @@ impl DomTree {Some(head)}+ fn html_element_local_name(&self, id: NodeId) -> Option<LocalName> {+ 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()+ }++ /// Options owned by this select, excluding nested select, datalist and+ /// option subtrees rather than treating every descendant as an option.+ pub fn select_options(&self, select: NodeId) -> Option<Vec<NodeId>> {+ if self.html_element_local_name(select).as_ref().map(|name| name.as_ref()) != Some("select") {+ return None;+ }+ let mut options = Vec::new();+ let mut pending: Vec<_> = self.children(select).into_iter().rev().collect();+ let mut remaining = self.node_slot_count();+ while let Some(node) = pending.pop() {+ if remaining == 0 {+ eprintln!("obscura: select-options traversal cap hit - tree has a cycle");+ return None;+ }+ remaining -= 1;+ match self.html_element_local_name(node).as_ref().map(|name| name.as_ref()) {+ Some("option") => options.push(node),+ Some("select" | "datalist") => {},+ _ => pending.extend(self.children(node).into_iter().rev()),+ }+ }+ Some(options)+ }++ pub fn option_index(&self, option: NodeId) -> Option<usize> {+ if self.html_element_local_name(option).as_ref().map(|name| name.as_ref()) != Some("option") {+ return None;+ }+ let mut parent = self.with_node(option, |node| node.parent).flatten();+ let mut remaining = self.node_slot_count();+ while let Some(node) = parent {+ if remaining == 0 {+ eprintln!("obscura: option-index traversal cap hit - tree has a cycle");+ return None;+ }+ remaining -= 1;+ match self.html_element_local_name(node).as_ref().map(|name| name.as_ref()) {+ Some("select") => return self.select_options(node)+ .map(|options| options.iter().position(|id| *id == option).unwrap_or(0)),+ Some("datalist" | "option") => return Some(0),+ _ => parent = self.with_node(node, |node| node.parent).flatten(),+ }+ }+ Some(0)+ }+/// 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>> {@@ -2110,6 +2160,63 @@ mod tests {assert_eq!(tree.table_rows(NodeId::new(u32::MAX)), None);}+ #[test]+ fn select_options_follow_native_ownership_boundaries() {+ let tree = DomTree::new();+ let select = element(&tree, "select");+ let first = element(&tree, "option");+ tree.append_child(select, first);+ let mut included = vec![first];+ for tag in ["div", "optgroup", "select", "datalist", "option"] {+ let parent = element(&tree, tag);+ let option = element(&tree, "option");+ tree.append_child(select, parent);+ tree.append_child(parent, option);+ match tag {+ "div" | "optgroup" => included.push(option),+ "option" => included.push(parent),+ _ => {},+ }+ let expected = if tag == "div" { 1 } else if tag == "optgroup" { 2 } else { 0 };+ assert_eq!(tree.option_index(option), Some(expected));+ if tag == "select" { assert_eq!(tree.select_options(parent), Some(vec![option])); }+ }+ let foreign = tree.new_node(NodeData::Element {+ name: QualName::new(None, Namespace::from("urn:foreign"), LocalName::from("select")),+ attrs: vec![], template_contents: None,+ mathml_annotation_xml_integration_point: false,+ });+ let foreign_child = element(&tree, "option");+ tree.append_child(select, foreign);+ tree.append_child(foreign, foreign_child);+ included.push(foreign_child);+ assert_eq!(tree.select_options(select), Some(included.clone()));+ assert_eq!(tree.option_index(foreign_child), Some(4));+ tree.detach(first);+ included.remove(0);+ assert_eq!(tree.select_options(select), Some(included));+ assert_eq!(tree.option_index(first), Some(0));+ assert_eq!(tree.option_index(foreign_child), Some(3));+ assert_eq!(tree.select_options(foreign), None);+ assert_eq!(tree.option_index(select), None);+ assert_eq!(tree.select_options(NodeId::new(u32::MAX)), None);+ assert_eq!(tree.option_index(NodeId::new(u32::MAX)), None);+ }++ #[test]+ fn select_options_and_indexes_bound_broken_cycles() {+ let tree = DomTree::new();+ let select = element(&tree, "select");+ let container = element(&tree, "div");+ let option = element(&tree, "option");+ tree.append_child(select, container);+ tree.append_child(container, option);+ tree.with_node_mut(container, |node| node.first_child = Some(container));+ assert_eq!(tree.select_options(select), None);+ tree.with_node_mut(container, |node| node.parent = Some(container));+ assert_eq!(tree.option_index(option), 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 0f13da45..06e8eddb 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -4985,7 +4985,8 @@ class Element extends Node {const tag = this.localName;if (tag === 'select') {// Selected option wins; otherwise first option (HTML default).- const opts = this.querySelectorAll('option');+ const opts = this.namespaceURI === 'http://www.w3.org/1999/xhtml'+ ? _selectOptions(this) : this.querySelectorAll('option');for (let i = 0; i < opts.length; i++) {if (opts[i].selected) {return opts[i].getAttribute('value') !== null ? opts[i].getAttribute('value') : opts[i].textContent;@@ -5038,7 +5039,8 @@ class Element extends Node {// itself. Dispatching here fed pages that assign inside a change// handler back into that handler in an infinite loop.const wanted = String(v);- const opts = this.querySelectorAll('option');+ const opts = this.namespaceURI === 'http://www.w3.org/1999/xhtml'+ ? _selectOptions(this) : this.querySelectorAll('option');for (let i = 0; i < opts.length; i++) {const attrV = opts[i].getAttribute('value');const optVal = attrV !== null ? attrV : opts[i].textContent;@@ -5506,24 +5508,27 @@ class Element extends Node {}get options() {if (this.localName !== 'select') return [];- return HTMLCollection._from(this.querySelectorAll('option'));+ return HTMLCollection._from(this.namespaceURI === 'http://www.w3.org/1999/xhtml'+ ? _selectOptions(this) : this.querySelectorAll('option'));}add(item, before = null) {- if (this.localName !== 'select') {- throw new TypeError("Illegal invocation");- }- if (!item || item.nodeType !== 1+ _selectApply(_validateSelect, this, []);+ if (!_isDomNode(item) || item.nodeType !== 1+ || item.namespaceURI !== 'http://www.w3.org/1999/xhtml'|| (item.localName !== 'option' && item.localName !== 'optgroup')) {throw new TypeError("Failed to execute 'add' on 'HTMLSelectElement': parameter 1 is not of type 'HTMLOptionElement' or 'HTMLOptGroupElement'.");}- if (typeof before === 'number') {- const reference = this.options[before] || null;- this.insertBefore(item, reference);- } else if (before == null) {- this.appendChild(item);- } else {- this.insertBefore(item, before);+ let reference = before;+ if (before !== null && !(_isDomNode(before) && before.nodeType === 1+ && before.namespaceURI === 'http://www.w3.org/1999/xhtml')) {+ const index = +before | 0;+ reference = _selectOptions(this)[index] || null;+ }+ if (reference && (reference === this || !this.contains(reference))) {+ throw new DOMException("The reference node is not a descendant of this select.", "NotFoundError");}+ const parent = reference ? reference.parentNode : this;+ parent.insertBefore(item, reference);}get selectedIndex() {const opts = this.options;@@ -14446,7 +14451,6 @@ globalThis.HTMLFormElement = class HTMLFormElement extends Element {}}};-globalThis.HTMLSelectElement = Element;globalThis.HTMLTextAreaElement = class HTMLTextAreaElement extends Element {get readOnly() { return this.hasAttribute('readonly'); }set readOnly(v) { if (v) this.setAttribute('readonly', ''); else this.removeAttribute('readonly'); }@@ -14546,7 +14550,6 @@ globalThis.HTMLSlotElement = class HTMLSlotElement extends Element {assignedNodes(options) { return _slotAssignedNodes(this, !!(options && options.flatten)); }assignedElements(options) { return this.assignedNodes(options).filter(n => n.nodeType === 1); }};-globalThis.HTMLOptionElement = Element;globalThis.HTMLDataListElement = Element;globalThis.HTMLFieldSetElement = Element;globalThis.HTMLLegendElement = Element;@@ -14563,6 +14566,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'],+ HTMLSelectElement: ['select'], HTMLOptionElement: ['option'],HTMLTableElement: ['table'], HTMLTableCaptionElement: ['caption'], HTMLTableCellElement: ['td', 'th'],HTMLTableColElement: ['col', 'colgroup'], HTMLTableRowElement: ['tr'],HTMLTableSectionElement: ['tbody', 'thead', 'tfoot'], HTMLTimeElement: ['time'], HTMLTitleElement: ['title'],@@ -14586,6 +14590,134 @@ for (const [name, tags] of Object.entries({}}+const _selectApply = Reflect.apply;+const _selectElementRemove = Element.prototype.remove;+function _selectTagIsValid(nid) {+ const info = _domParse('tag_name', nid, 'interface');+ return typeof info === 'string' ? info === 'SELECT'+ : !!info && info[1] === 'http://www.w3.org/1999/xhtml' && info[2] === 'select';+}+function _validateSelectMember() {+ const nid = this && this._nid;+ return !!this && _nodeCacheGet(nid) === this && _selectTagIsValid(nid);+}+function _validateSelect() {+ const nid = this && this._nid;+ if (!this || _nodeCacheGet(nid) !== this) {+ const member = this && _documentRealmMember(this, 'validateSelect');+ if (member && member !== _validateSelectMember && _selectApply(member, this, [])) return;+ throw new TypeError('Illegal invocation');+ }+ if (!_selectTagIsValid(nid)) throw new TypeError('Illegal invocation');+}+function _selectOptionsMember() {+ const nid = this && this._nid;+ if (!this || _nodeCacheGet(nid) !== this) return null;+ const ids = _domParse('select_options', nid);+ return ids === null ? null : ids.map(_wrapEl);+}+function _selectOptions(select) {+ const nid = select && select._nid;+ if (!select || _nodeCacheGet(nid) !== select) {+ const member = select && _documentRealmMember(select, 'selectOptions');+ if (member && member !== _selectOptionsMember) {+ const options = _selectApply(member, select, []);+ if (options !== null) return options;+ }+ throw new TypeError('Illegal invocation');+ }+ const ids = _domParse('select_options', nid);+ if (ids === null) throw new TypeError('Illegal invocation');+ return ids.map(_wrapEl);+}+function _optionIndexMember() {+ const nid = this && this._nid;+ return this && _nodeCacheGet(nid) === this ? _domParse('option_index', nid) : null;+}+function _optionIndexGetter() {+ const nid = this && this._nid;+ if (!this || _nodeCacheGet(nid) !== this) {+ const member = this && _documentRealmMember(this, 'optionIndex');+ if (member && member !== _optionIndexMember) {+ const index = _selectApply(member, this, []);+ if (index !== null) return index;+ }+ throw new TypeError('Illegal invocation');+ }+ const index = _domParse('option_index', nid);+ if (index === null) throw new TypeError('Illegal invocation');+ return index;+}+Object.defineProperties(HTMLSelectElement.prototype, {+ length: {+ get() { return _selectOptions(this).length; },+ set(value) {+ _selectApply(_validateSelect, this, []);+ const length = +value >>> 0;+ if (length > 100000) {+ console.warn("Failed to set the 'length' property on 'HTMLSelectElement': maximum supported length is 100000.");+ return;+ }+ const options = _selectOptions(this);+ for (let i = options.length - 1; i >= length; i--) {+ _selectApply(_selectElementRemove, options[i], []);+ }+ for (let i = options.length; i < length; i++) {+ this.appendChild(this.ownerDocument.createElement('option'));+ }+ },+ configurable: true, enumerable: true,+ },+ item: {+ value: function item(index) {+ _selectApply(_validateSelect, this, []);+ if (!arguments.length) throw new TypeError("Failed to execute 'item' on 'HTMLSelectElement': 1 argument required.");+ index = +index >>> 0;+ return _selectOptions(this)[index] || null;+ },+ writable: true, configurable: true, enumerable: true,+ },+ namedItem: {+ value: function namedItem(name) {+ _selectApply(_validateSelect, this, []);+ if (!arguments.length) throw new TypeError("Failed to execute 'namedItem' on 'HTMLSelectElement': 1 argument required.");+ if (typeof name === 'symbol') throw new TypeError('Cannot convert a Symbol value to a string');+ name = String(name);+ if (!name) return null;+ for (const option of _selectOptions(this)) {+ if (option.id === name || option.getAttribute('name') === name) return option;+ }+ return null;+ },+ writable: true, configurable: true, enumerable: true,+ },+ remove: {+ value: function remove(index = undefined) {+ _selectApply(_validateSelect, this, []);+ if (!arguments.length) {+ return _selectApply(_selectElementRemove, this, []);+ }+ index = +index | 0;+ const option = _selectOptions(this)[index];+ if (option) _selectApply(_selectElementRemove, option, []);+ },+ writable: true, configurable: true, enumerable: true,+ },+});+Object.defineProperty(HTMLSelectElement, 'length', {value: 0, configurable: true});+Object.defineProperty(HTMLOptionElement, 'length', {value: 0, configurable: true});+Object.defineProperty(_optionIndexGetter, 'name', {value: 'get index', configurable: true});+Object.defineProperty(HTMLOptionElement.prototype, 'index', {+ get: _optionIndexGetter, configurable: true, enumerable: true,+});+for (const name of ['length', 'item', 'namedItem', 'remove']) {+ const descriptor = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, name);+ for (const method of [descriptor.get, descriptor.set, descriptor.value]) {+ if (method) _markNative(method);+ }+}+_markNative(_optionIndexGetter);+// SVGAnimatedString backs the className and href reflections on SVG elements.// baseVal and animVal both read the live attribute (no SMIL animation), and// baseVal is writable. Used by the SVG-aware get className()/get href() above.@@ -18924,6 +19056,9 @@ const _documentMembers = Object.freeze(Object.fromEntries([}],['checkVisibility', Element.prototype.checkVisibility],['elementStyle', function() { return _elementStyle(this); }],+ ['selectOptions', _selectOptionsMember],+ ['validateSelect', _validateSelectMember],+ ['optionIndex', _optionIndexMember],['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/frame.rs b/crates/obscura-js/src/frame.rsindex 41809ed8..c7e8780c 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -550,6 +550,39 @@ mod tests {serde_json::json!(true));}+ #[test]+ fn borrowed_select_and_option_methods_keep_the_owning_dom() {+ let mut parent = page("https://parent.example/",+ "<html><body><select id='parent'><option>Parent</option></select></body></html>");+ let _frame = FrameRealm::new(&mut parent, 1, 0, "https://parent.example/frame",+ "<html><body><select><option id='a'>A</option><optgroup><option id='b'>B</option></optgroup></select></body></html>").unwrap();+ assert_eq!(parent.evaluate(r#"(() => {+ const select = globalThis.__obscura_frameObjects[1].document.querySelector('select');+ const length = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'length');+ const index = Object.getOwnPropertyDescriptor(HTMLOptionElement.prototype, 'index').get;+ const item = HTMLSelectElement.prototype.item.call(select, 1);+ const named = HTMLSelectElement.prototype.namedItem.call(select, 'b');+ const initial = [length.get.call(select), item.id, named === item, index.call(item)];+ length.set.call(select, 3);+ HTMLSelectElement.prototype.remove.call(select, 0);+ const changed = [select.length, select.item(0).id, index.call(item)];+ const div = select.ownerDocument.createElement('div');+ const rejected = [() => length.get.call(div), () => length.set.call(div, 1),+ () => HTMLSelectElement.prototype.item.call(div, 0),+ () => HTMLSelectElement.prototype.namedItem.call(div, ''),+ () => HTMLSelectElement.prototype.remove.call(div), () => index.call(div)].map(call => {+ try { call(); return false; } catch (error) { return error instanceof TypeError; }+ });+ HTMLSelectElement.prototype.remove.call(select);+ return {initial, changed, rejected, childConnected:select.isConnected,+ parent:[document.getElementById('parent').length, document.querySelector('option').textContent]};+ })()"#).unwrap(), serde_json::json!({+ "initial":[2,"b",true,1], "changed":[2,"b",0], "rejected":[true,true,true,true,true,true],+ "childConnected":false,+ "parent":[1,"Parent"],+ }));+ }+#[test]fn borrowed_style_getter_keeps_the_elements_declaration() {let mut parent = page("https://parent.example/", "<html><body></body></html>");diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 341307ae..d1ef90e6 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -2714,6 +2714,16 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->rows.into_iter().map(|row| row.index()).collect::<Vec<_>>()})).to_string()}+ "select_options" => {+ let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));+ serde_json::json!(dom.select_options(nid).map(|options| {+ options.into_iter().map(|option| option.index()).collect::<Vec<_>>()+ })).to_string()+ }+ "option_index" => {+ let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));+ serde_json::json!(dom.option_index(nid)).to_string()+ }"tag_name" => {let nid = arg1.parse::<u32>().unwrap_or(0);domdiff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 0df100cb..b263b7df 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -4693,6 +4693,196 @@ mod tests {}));}+ #[test]+ fn select_options_use_native_ownership_and_live_option_indexes() {+ let mut rt = setup_runtime("<html><body></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const select = document.createElement('select');+ document.body.append(select);+ const add = (parent, id) => {+ const option = new Option(id, id);+ option.id = id;+ parent.append(option);+ return option;+ };+ const first = add(select, 'first');+ const div = document.createElement('div');+ select.append(div);+ const second = add(div, 'second');+ const group = document.createElement('optgroup');+ select.append(group);+ const third = add(group, 'third');+ const nested = document.createElement('select');+ select.append(nested);+ const hidden = add(nested, 'nested');+ hidden.selected = true;+ const datalist = document.createElement('datalist');+ select.append(datalist);+ const suggested = add(datalist, 'suggested');+ const outer = add(select, 'outer');+ const inner = add(outer, 'inner');+ const initial = [select.length, Array.from(select.options, o => o.id),+ [first.index, second.index, third.index, hidden.index, suggested.index, outer.index, inner.index],+ select.value, select.selectedIndex, select.item(2) === third,+ select.namedItem('second') === second];+ select.value = 'third';+ const chosen = [third.selected, hidden.selected, select.value, select.selectedIndex];+ second.remove();+ return {initial, chosen, moved: [third.index, select.length], liveRows:+ typeof Object.getOwnPropertyDescriptor(HTMLTableElement.prototype, 'rows').get};+ })()"#).unwrap(), serde_json::json!({+ "initial":[4,["first","second","third","outer"],[0,1,2,0,0,3,0],"first",0,true,true],+ "chosen":[true,true,"third",2], "moved":[1,3], "liveRows":"function",+ }));+ }++ #[test]+ fn select_add_respects_group_parents_and_union_conversions() {+ let mut rt = setup_runtime("<html><body></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const result = [];+ for (const kind of ['number','string','bigint','symbol','object','group','self','foreign']) {+ const select = document.createElement('select');+ select.innerHTML = '<option id="a">A</option><optgroup><option id="b">B</option></optgroup>';+ const option = new Option('X');+ const before = {number:1, string:'1', bigint:1n, symbol:Symbol(),+ object:{valueOf() { return 1; }}, group:select.querySelector('optgroup'),+ self:select, foreign:document.createElementNS('urn:foreign','option')}[kind];+ try {+ select.add(option, before);+ result.push([kind, option.parentNode.localName, Array.from(select.options, o => o.text)]);+ } catch (error) { result.push([kind, error.name]); }+ }+ return result;+ })()"#).unwrap(), serde_json::json!([+ ["number","optgroup",["A","X","B"]], ["string","optgroup",["A","X","B"]],+ ["bigint","TypeError"], ["symbol","TypeError"], ["object","optgroup",["A","X","B"]],+ ["group","select",["A","X","B"]], ["self","NotFoundError"], ["foreign","select",["X","A","B"]],+ ]));+ }++ #[test]+ fn select_length_and_remove_overloads_modify_owned_options_only() {+ let mut rt = setup_runtime("<html><body><select><option id='a'>A</option><optgroup><option id='b'>B</option><option id='c'>C</option></optgroup></select></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const select = document.querySelector('select');+ const group = select.querySelector('optgroup');+ select.length = 5;+ const grown = [select.length, select.item(4).text, select.item(4) instanceof HTMLOptionElement];+ select.length = 2;+ const shrunk = [select.length, group.children.length, select.item(1).id];+ select.remove(-1);+ select.remove(99);+ const untouched = [select.length, select.isConnected];+ select.remove(null);+ const removedFirst = [select.length, select.item(0).id, select.isConnected];+ select.length = 0;+ select.length = 1;+ const cleared = [select.length, group.children.length, select.item(0).index];+ select.remove();+ return {grown, shrunk, untouched, removedFirst, cleared, connected:select.isConnected};+ })()"#).unwrap(), serde_json::json!({+ "grown":[5,"",true], "shrunk":[2,1,"b"], "untouched":[2,true],+ "removedFirst":[1,"b",true], "cleared":[1,0,0], "connected":false,+ }));+ }++ #[test]+ fn select_legacy_methods_enforce_webidl_conversions_and_bounded_lengths() {+ let mut rt = setup_runtime("<html><body><select><option id='first' name='alias'>A</option><option>B</option></select></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const select = document.querySelector('select');+ const throws = f => { try { f(); return false; } catch (e) { return e instanceof TypeError; } };+ const errors = [throws(() => select.item()), throws(() => select.namedItem()),+ throws(() => select.item(0n)), throws(() => select.length = 2n),+ throws(() => select.namedItem(Symbol())), throws(() => select.remove(Symbol())),+ throws(() => select.length = Symbol())];+ const reads = [select.item('0').id, select.item(-1), select.item(undefined).id,+ select.namedItem('alias').id, select.namedItem(''), select.namedItem('missing')];+ const warnings = [];+ console.warn = value => warnings.push(value);+ select.length = 100001;+ select.length = -1;+ const bounded = [select.length, warnings.length,+ warnings.every(value => value.includes('100000'))];+ select.length = '3';+ return {errors, reads, bounded, converted:select.length};+ })()"#).unwrap(), serde_json::json!({+ "errors":[true,true,true,true,true,true,true], "reads":["first",null,"first","first",null,null],+ "bounded":[2,2,true], "converted":3,+ }));+ }++ #[test]+ fn select_legacy_methods_read_options_after_argument_coercion() {+ let mut rt = setup_runtime("<html><body><select><option id='first'>A</option></select></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const select = document.querySelector('select');+ const change = id => { select.innerHTML = '<option id="'+id+'">X</option>'; };+ const item = select.item({valueOf() { change('item'); return 0; }}).id;+ const named = select.namedItem({toString() { change('named'); return 'named'; }}).id;+ select.remove({valueOf() { change('removed'); return 0; }});+ const removed = select.length;+ select.length = {valueOf() { change('length'); return 0; }};+ return [item, named, removed, select.length];+ })()"#).unwrap(), serde_json::json!(["item","named",0,0]));+ }++ #[test]+ fn select_and_option_interfaces_preserve_factories_and_validate_receivers() {+ let mut rt = setup_runtime("<html><body><select><option>A</option></select><div></div></body></html>");+ assert_eq!(rt.evaluate(r#"(() => {+ const select = document.querySelector('select');+ const option = select.item(0);+ const length = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'length');+ const index = Object.getOwnPropertyDescriptor(HTMLOptionElement.prototype, 'index').get;+ const errors = [];+ for (const value of [document.querySelector('div'), {}, Object.create(HTMLSelectElement.prototype),+ document.createElementNS('urn:foreign', 'select'), document.createElementNS('http://www.w3.org/1999/xhtml', 'SELECT')]) {+ for (const method of [() => length.get.call(value), () => length.set.call(value, 2),+ () => HTMLSelectElement.prototype.item.call(value, 0),+ () => HTMLSelectElement.prototype.namedItem.call(value, ''),+ () => HTMLSelectElement.prototype.remove.call(value)]) {+ try { method(); errors.push(false); } catch (e) { errors.push(e instanceof TypeError); }+ }+ }+ for (const value of [select, {}, document.createElementNS('urn:foreign', 'option')]) {+ try { index.call(value); errors.push(false); } catch (e) { errors.push(e instanceof TypeError); }+ }+ const constructors = [HTMLSelectElement, HTMLOptionElement].map(C => {+ try { new C(); return false; } catch (e) { return e instanceof TypeError; }+ });+ return {brands:[select instanceof HTMLSelectElement, option instanceof HTMLOptionElement,+ select.cloneNode(true) instanceof HTMLSelectElement,+ option.cloneNode() instanceof HTMLOptionElement, new Option() instanceof HTMLOptionElement,+ document.createElement('div') instanceof HTMLSelectElement],+ noGenericLength:!('length' in document.createElement('div')),+ errors:errors.every(Boolean), constructors, detached:new Option().index,+ signatures:[HTMLSelectElement.length, HTMLOptionElement.length, index.name,+ index.toString(), HTMLSelectElement.prototype.item.length,+ HTMLSelectElement.prototype.namedItem.length, HTMLSelectElement.prototype.remove.length]};+ })()"#).unwrap(), serde_json::json!({+ "brands":[true,true,true,true,true,false], "noGenericLength":true,+ "errors":true, "constructors":[true,true], "detached":0,+ "signatures":[0,0,"get index","function get index() { [native code] }",1,1,0],+ }));+ }++ #[test]+ fn select_legacy_methods_work_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><select><option id='a'>A</option><optgroup><option id='b'>B</option></optgroup></select></body></html>").unwrap();+ assert_eq!(frame.evaluate(&mut rt, r#"(() => {+ const select = document.querySelector('select');+ const branded = select instanceof HTMLSelectElement && select.item(1) instanceof HTMLOptionElement;+ const index = select.namedItem('b').index;+ select.remove(0);+ select.length = 3;+ return [branded, index, select.item(0).id, select.item(2).index, select.length];+ })()"#).unwrap(), serde_json::json!([true,1,"b",2,3]));+ }+#[test]fn table_rows_are_live_ordered_readonly_collections() {let mut rt = setup_runtime("<html><body></body></html>");diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.mdindex 20821b86..5229bf65 100644--- a/docs/Architecture-overview.md+++ b/docs/Architecture-overview.md@@ -168,6 +168,16 @@ read; prefixed or foreign names include namespace/local-name metadata in thatsame read. Table construction and parser/wrapper workloads are covered by thepublic performance smoke gate.+Select and option wrappers have distinct HTML interfaces. Select `length`,+`item`, `namedItem`, `remove`, `add`, value lookup, and option `index` use native+option ownership: nested HTML selects, datalists, and option subtrees do not+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.+`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.