The headless browser for AI agents and web scraping
Give missing HTML element interfaces distinct brands
SGavrl831cb299c939
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 1a66d14b..12a4c06b 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -4156,6 +4156,10 @@ class Element extends Node {return this._tagName;}get nodeName() { return this.tagName; }+ get prefix() {+ if (this._prefix === undefined) this._prefix = _domParse("prefix", this._nid);+ return this._prefix;+ }get localName() {// The native tree owns the namespace-aware QualName. Reading its local// component directly preserves case-sensitive SVG/MathML names such as@@ -6624,7 +6628,7 @@ class Document extends Node {"http://www.w3.org/1999/xhtml",localName,);- const el = new C(nid);+ const el = new C(nid, _htmlInterfaceToken);// This node was just created from values already known to JS. Seed its// immutable metadata instead of rediscovering it through native calls in// hydration's tag/local-name checks.@@ -6647,7 +6651,7 @@ class Document extends Node {const namespace = ns == null ? null : String(ns);const qualified = String(t);_ns_validateQualifiedName(namespace == null ? "" : namespace, qualified);- if (namespace === "http://www.w3.org/1999/xhtml") {+ if (namespace === "http://www.w3.org/1999/xhtml" && qualified === qualified.toLowerCase() && !qualified.includes(':')) {const el = this.createElement(qualified);if (el) el._ns = namespace;return el;@@ -6657,12 +6661,12 @@ class Document extends Node {(namespace == null ? "" : namespace) + "\0" + qualified,);const effectiveNamespace = namespace == null ? "" : namespace;- const C = _elementClassForKnownName(effectiveNamespace, qualified);- const el = new C(nid);const localName = qualified.includes(":")? qualified.slice(qualified.indexOf(":") + 1): qualified;- el._tagName = qualified;+ const C = _elementClassForKnownName(effectiveNamespace, localName);+ const el = new C(nid, _htmlInterfaceToken);+ el._tagName = effectiveNamespace === "http://www.w3.org/1999/xhtml" ? qualified.toUpperCase() : qualified;el._lname = localName;el._ns = effectiveNamespace;el._nullNamespaceAttrs = new Map();@@ -7744,8 +7748,13 @@ globalThis.TextTrackCue = TextTrackCue;globalThis.TextTrackCueList = TextTrackCueList;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));+ }// 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.@@ -7784,12 +7793,12 @@ const _elementClassFor = (function _elementClassFor(nid) {if (tag === "AUDIO") return HTMLAudioElement;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;return Element;});-const _elementClassForKnownName = (function _elementClassForKnownName(namespace, qualifiedName) {- const localName = qualifiedName.includes(":")- ? qualifiedName.slice(qualifiedName.indexOf(":") + 1)- : qualifiedName;+const _elementClassForKnownName = (function _elementClassForKnownName(namespace, localName) {if (namespace === "http://www.w3.org/2000/svg") {const svgClass = _svgElementClasses[localName];if (svgClass) return svgClass;@@ -7810,15 +7819,18 @@ const _elementClassForKnownName = (function _elementClassForKnownName(namespace,if (tag === "AUDIO") return HTMLAudioElement;if (tag === "VIDEO") return HTMLVideoElement;if (tag === "TRACK") return HTMLTrackElement;+ const additional = _additionalHtmlElementClasses[localName];+ if (additional && localName === localName.toLowerCase()) return additional;}return Element;});const _wrap = (function _wrap(nid) {if (nid < 0 || nid === null || nid === undefined || isNaN(nid)) return null;- if (_cache.has(nid)) return _cache.get(nid);+ const cached = _cache.get(nid);+ if (cached !== undefined) return cached;const t = +_dom("node_type", nid);let n;- if (t === 1) { const C = _elementClassFor(nid); n = new C(nid); }+ if (t === 1) { const C = _elementClassFor(nid); n = new C(nid, _htmlInterfaceToken); }else if (t === 3) n = new Text(nid);else if (t === 8) n = new Comment(nid);else if (t === 9) n = new Document(nid);@@ -7829,11 +7841,13 @@ const _wrap = (function _wrap(nid) {_cache.set(nid, n);return n;});+// Keep the common cached-node path small enough for V8 to inline.const _wrapEl = (function _wrapEl(nid) {if (nid < 0 || nid === null || nid === undefined || isNaN(nid)) return null;- if (_cache.has(nid)) return _cache.get(nid);+ const cached = _cache.get(nid);+ if (cached !== undefined) return cached;const C = _elementClassFor(nid);- const n = new C(nid);+ const n = new C(nid, _htmlInterfaceToken);_cache.set(nid, n);return n;});@@ -14329,6 +14343,39 @@ globalThis.HTMLLegendElement = Element;globalThis.HTMLProgressElement = Element;globalThis.HTMLDetailsElement = Element;globalThis.HTMLDialogElement = Element;+// Identity-only interfaces still need distinct prototypes. Inheriting Element+// preserves implemented DOM behavior without making unrelated tags pass brand checks.+for (const [name, tags] of Object.entries({+ HTMLAreaElement: ['area'], HTMLBaseElement: ['base'], HTMLDListElement: ['dl'],+ HTMLDataElement: ['data'], HTMLDirectoryElement: ['dir'], HTMLEmbedElement: ['embed'],+ HTMLFontElement: ['font'], HTMLFrameElement: ['frame'], HTMLFrameSetElement: ['frameset'],+ HTMLMapElement: ['map'], HTMLMarqueeElement: ['marquee'], HTMLMenuElement: ['menu'],+ 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'],+ HTMLTableColElement: ['col', 'colgroup'], HTMLTableRowElement: ['tr'],+ HTMLTableSectionElement: ['tbody', 'thead', 'tfoot'], HTMLTimeElement: ['time'], HTMLTitleElement: ['title'],+})) {+ if (globalThis[name] !== undefined) continue;+ const 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.prototype, Symbol.toStringTag, {value: name, configurable: true});+ Object.defineProperty(globalThis, name, {value: Interface, writable: true, configurable: true});+ for (const tag of tags) {+ _additionalHtmlElementClasses[tag] = Interface;+ _additionalHtmlElementClasses[tag.toUpperCase()] = Interface;+ }+}+// 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.diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 76a3ac76..31f58899 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -2651,7 +2651,14 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->.with_node(NodeId::new(nid), |n| {n.as_element().map(|name| {if name.ns == html5ever::ns!(html) {- name.local.as_ref().to_ascii_uppercase()+ match &name.prefix {+ Some(prefix) => {+ let mut qualified = format!("{}:{}", prefix, name.local);+ qualified.make_ascii_uppercase();+ qualified+ }+ None => name.local.as_ref().to_ascii_uppercase(),+ }} else {match &name.prefix {Some(prefix) => format!("{}:{}", prefix, name.local),@@ -2664,6 +2671,13 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->.unwrap_or_default();serde_json::to_string(&name).unwrap_or("\"\"".into())}+ "prefix" => {+ let nid = arg1.parse::<u32>().unwrap_or(0);+ let prefix = dom.with_node(NodeId::new(nid), |n| {+ n.as_element().and_then(|name| name.prefix.as_ref().map(|prefix| prefix.to_string()))+ }).flatten();+ serde_json::to_string(&prefix).unwrap_or("null".into())+ }"local_name" => {let nid = arg1.parse::<u32>().unwrap_or(0);let name = domdiff --git a/crates/obscura-js/tests/html_interface_brands.rs b/crates/obscura-js/tests/html_interface_brands.rsnew file mode 100644index 00000000..1960d5f6--- /dev/null+++ b/crates/obscura-js/tests/html_interface_brands.rs@@ -0,0 +1,42 @@+use obscura_js::runtime::ObscuraJsRuntime;+use serde_json::json;++#[test]+fn html_interface_brands_follow_tag_namespace_and_real_prototypes() {+ let mut runtime = ObscuraJsRuntime::new();+ runtime.set_dom(obscura_dom::parse_html("<!doctype html><head><base href=/></head><body><table><tbody><tr><td>cell</td></tr></tbody></table></body>"));+ runtime.run_page_init();+ let result = runtime.evaluate(r#"(() => {+ const pairs = [['base','HTMLBaseElement'],['td','HTMLTableCellElement'],['th','HTMLTableCellElement'],+ ['tbody','HTMLTableSectionElement'],['thead','HTMLTableSectionElement'],['tfoot','HTMLTableSectionElement'],+ ['tr','HTMLTableRowElement'],['col','HTMLTableColElement'],['colgroup','HTMLTableColElement'],+ ['picture','HTMLPictureElement'],['source','HTMLSourceElement'],['title','HTMLTitleElement'],['time','HTMLTimeElement']];+ const failures=[];+ for (const [tag,name] of pairs) {+ const C=globalThis[name],element=document.createElement(tag),unrelated=document.createElement(tag==='div'?'span':'div');+ if(typeof C!=='function'||!(element instanceof C)||unrelated instanceof C||Object.getPrototypeOf(element)!==C.prototype+ ||Object.getPrototypeOf(C.prototype)!==HTMLElement.prototype||Object.prototype.toString.call(element)!=='[object '+name+']') failures.push(name);+ if(!(element.cloneNode() instanceof C)) failures.push('clone '+name);+ if(document.createElementNS('urn:other',tag) instanceof C) failures.push('namespace '+name);+ const prefixed=document.createElementNS('http://www.w3.org/1999/xhtml','x:'+tag);+ for(const node of [prefixed,prefixed.cloneNode()]) {+ if(!(node instanceof C)||node.localName!==tag||node.prefix!=='x'||node.tagName!==('x:'+tag).toUpperCase()) failures.push('prefix '+name);+ }+ const literal=document.createElement('x:'+tag);+ for(const node of [literal,literal.cloneNode()]) {+ if(node instanceof C||node.localName!=='x:'+tag||node.prefix!==null||node.tagName!==('x:'+tag).toUpperCase()) failures.push('literal colon '+name);+ }+ const upper=document.createElementNS('http://www.w3.org/1999/xhtml',tag.toUpperCase());+ if(upper instanceof C || upper.localName!==tag.toUpperCase() || upper.cloneNode() instanceof C) failures.push('case '+name);+ let illegal=false;try{new C();}catch(e){illegal=e instanceof TypeError;}if(!illegal)failures.push('constructor '+name);+ if(Object.getOwnPropertyDescriptor(globalThis,name).enumerable)failures.push('enumerable '+name);+ }+ const cell=document.querySelector('td');cell.id='brand-cache-cell';cell.marker='retained';+ const sameWrapper=document.getElementById('brand-cache-cell')===cell+ &&cell.parentNode.childNodes[0]===cell&&document.querySelector('td').marker==='retained';+ return [failures,sameWrapper,document.querySelector('base') instanceof HTMLBaseElement,+ document.querySelector('td') instanceof HTMLTableCellElement,HTMLBaseElement!==HTMLTableCellElement,+ HTMLBaseElement.prototype!==HTMLTableCellElement.prototype];+ })()"#).unwrap();+ assert_eq!(result,json!([[],true,true,true,true,true]));+}