The headless browser for AI agents and web scraping
Reuse DOM metadata during hydration
SGavrl4171445e552d
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex f4e3f3bd..bf5745d7 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -2789,7 +2789,15 @@ class Element extends Node {// Element for element nodes, and node ids are never freed-and-reused), so this// is constant. Overrides Node's dynamic getter to drop one op per nodeType read.get nodeType() { return 1; }- get tagName() { return _domParse("tag_name", this._nid) || ""; }+ get tagName() {+ // An element's qualified name is immutable for its lifetime. React reads+ // nodeName/tagName repeatedly while hydrating; crossing the native bridge+ // for every comparison adds thousands of calls on modern component trees.+ if (this._tagName !== undefined) return this._tagName;+ this._tagName = _domParse("tag_name", this._nid) || "";+ return this._tagName;+ }+ get nodeName() { return this.tagName; }get localName() {// tagName is an op call and the tag never changes, so cache the lowercased// localName. This keeps the new <a>/<area> href getters (which read@@ -2956,12 +2964,16 @@ class Element extends Node {get style() { return this._style; }set style(v) { if (typeof v === "string") this._style.cssText = v; }getAttribute(n) {- // Fast path: HTML attributes are stored lowercase, so a direct hit needs no- // case folding. Only on a miss do we lowercase (gated) and retry, so the hot- // case (reading an existing lowercase attribute) pays zero scan.- let v = _domParse("get_attribute", this._nid, n);- if (v === null) { const ln = _htmlAttrName(this, n); if (ln !== n) v = _domParse("get_attribute", this._nid, ln); }- return v;+ n = _htmlAttrName(this, n);+ // Script-created elements start with a provably empty attribute set. Keep+ // that small null-namespace map coherent through the ordinary mutation+ // APIs so React's write-then-read reflection does not cross the bridge.+ if (this._nullNamespaceAttrs instanceof Map) {+ return this._nullNamespaceAttrs.has(n)+ ? this._nullNamespaceAttrs.get(n)+ : null;+ }+ return _domParse("get_attribute", this._nid, n);}setAttribute(n, v) {n = _htmlAttrName(this, n);@@ -2971,6 +2983,9 @@ class Element extends Node {: null;const value = String(v);_dom("set_attribute", this._nid, n + "\0" + value);+ if (this._nullNamespaceAttrs instanceof Map) {+ this._nullNamespaceAttrs.set(n, value);+ }if (n === "id" || (n === "name" && _windowNameEligibleElement(this))) {if (this.getRootNode() === globalThis.document) {_ensureWindowNamedProperty(value);@@ -2999,6 +3014,10 @@ class Element extends Node {const value = String(v);_ns_validateQualifiedName(ns, n);_dom("set_attribute_ns", this._nid, ns + "\0" + n + "\0" + value);+ // Namespace-aware writes can replace an attribute by namespace/local name+ // while changing its qualified name. Fall back to native reads afterwards+ // instead of maintaining a second, subtly different key space here.+ this._nullNamespaceAttrs = null;if (ns === "" && n === "style") this._style._replaceFromAttribute(value);}removeAttribute(n) {@@ -3008,6 +3027,9 @@ class Element extends Node {? this.getAttribute(n): null;_dom("remove_attribute", this._nid, n);+ if (this._nullNamespaceAttrs instanceof Map) {+ this._nullNamespaceAttrs.delete(n);+ }if (previousWindowName&& (n === "id" || (n === "name" && _windowNameEligibleElement(this)))) {_reconcileWindowNamedProperty(previousWindowName);@@ -3029,6 +3051,7 @@ class Element extends Node {ns = String(ns == null ? "" : ns);n = String(n);_dom("remove_attribute_ns", this._nid, ns + "\0" + n);+ this._nullNamespaceAttrs = null;if (ns === "" && n === "style") this._style._replaceFromAttribute("");}hasAttribute(n) { return this.getAttribute(n) !== null; }@@ -4638,7 +4661,20 @@ class Document extends Node {}createElement(t) {const localName = String(t).toLowerCase();- const el = _wrapEl(+_dom("create_element", localName));+ const nid = +_dom("create_element", localName);+ const C = _elementClassForKnownName(+ "http://www.w3.org/1999/xhtml",+ localName,+ );+ const el = new C(nid);+ // 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.+ el._tagName = localName.toUpperCase();+ el._lname = localName;+ el._ns = "http://www.w3.org/1999/xhtml";+ el._nullNamespaceAttrs = new Map();+ _cache.set(nid, el);if (el && localName === 'template') {el._templateContent = this.createDocumentFragment();el._templateContent._fragmentContext = 'template';@@ -4649,16 +4685,36 @@ class Document extends Node {}createElementNS(ns, t) {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") {- const el = this.createElement(t);+ const el = this.createElement(qualified);if (el) el._ns = namespace;return el;}- const el = _wrapEl(+_dom("create_element", String(t).toLowerCase()));- if (el) el._ns = ns;+ const nid = +_dom(+ "create_element_ns",+ (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;+ el._lname = localName;+ el._ns = effectiveNamespace;+ el._nullNamespaceAttrs = new Map();+ _cache.set(nid, el);return el;}- createTextNode(t) { return _wrap(+_dom("create_text_node", String(t))); }+ createTextNode(t) {+ const nid = +_dom("create_text_node", String(t));+ const n = new Text(nid);+ _cache.set(nid, n);+ return n;+ }createComment(t) {const nid = +_dom("create_comment_node", String(t ?? ""));const n = new Comment(nid);@@ -5668,6 +5724,26 @@ function _elementClassFor(nid) {if (tag === "TRACK") return HTMLTrackElement;return Element;}+function _elementClassForKnownName(namespace, qualifiedName) {+ const localName = qualifiedName.includes(":")+ ? qualifiedName.slice(qualifiedName.indexOf(":") + 1)+ : qualifiedName;+ if (namespace === "http://www.w3.org/2000/svg") {+ if (localName === "path" && globalThis.SVGPathElement) return globalThis.SVGPathElement;+ if (localName === "svg" && globalThis.SVGSVGElement) return globalThis.SVGSVGElement;+ if (globalThis.SVGElement) return globalThis.SVGElement;+ }+ if (namespace === "http://www.w3.org/1999/xhtml") {+ const tag = localName.toUpperCase();+ if (tag === "FORM" && globalThis.HTMLFormElement) return globalThis.HTMLFormElement;+ if (tag === "IMG") return HTMLImageElement;+ if (tag === "CANVAS" && globalThis.HTMLCanvasElement) return globalThis.HTMLCanvasElement;+ if (tag === "AUDIO") return HTMLAudioElement;+ if (tag === "VIDEO") return HTMLVideoElement;+ if (tag === "TRACK") return HTMLTrackElement;+ }+ return Element;+}function _wrap(nid) {if (nid < 0 || nid === null || nid === undefined || isNaN(nid)) return null;if (_cache.has(nid)) return _cache.get(nid);diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 040110bd..66c7965a 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -3909,164 +3909,6 @@ mod tests {);}- #[test]- fn clone_node_deep_preserves_context_sensitive_elements() {- // A <tr> is not a valid child of <div>, so cloning through a throwaway- // <div>.innerHTML dropped it and returned null. A structural clone keeps it.- let mut rt = setup_runtime("<html><body></body></html>");- let tag = rt- .evaluate("(document.createElement('tr').cloneNode(true) || {}).tagName || 'NULL'")- .unwrap();- assert_eq!(tag, serde_json::json!("TR"));- let td = rt- .evaluate("(document.createElement('td').cloneNode(true) || {}).tagName || 'NULL'")- .unwrap();- assert_eq!(td, serde_json::json!("TD"));- }-- #[test]- fn clone_node_deep_copies_children_and_attributes() {- let mut rt = setup_runtime(r#"<html><body><ul id="l"><li class="a">one</li><li class="b">two</li></ul></body></html>"#);- let out = rt- .evaluate(- "(function(){var c=document.getElementById('l').cloneNode(true); return c.children.length + '|' + c.children[0].className + '|' + c.children[1].textContent;})()",- )- .unwrap();- assert_eq!(out, serde_json::json!("2|a|two"));- }-- #[test]- fn test_clone_node_deep() {- let mut rt = setup_runtime(r#"<div id="src"><p>A</p><p>B</p></div>"#);- rt.execute_script(- "test",- r#"- var src = document.getElementById('src');- var clone = src.cloneNode(true);- document.body.appendChild(clone);- "#,- )- .unwrap();- let count = rt.evaluate("document.querySelectorAll('p').length").unwrap();- assert!(- count.as_f64().unwrap() as i64 >= 4,- "Deep clone should duplicate <p> children, got: {}",- count- );- }-- #[test]- fn clone_node_deep_preserves_table_rows() {- let mut rt = setup_runtime(- r#"<html><body><table id="t"><tbody><tr><td>1</td><td>2</td></tr></tbody></table></body></html>"#,- );- // Navigate the detached clone directly (querySelector does not traverse- // detached subtrees). tbody > tr > (td, td).- let out = rt- .evaluate(- "(function(){var tb=document.querySelector('#t tbody').cloneNode(true); var tr=tb.children[0]; return tr.tagName + '|' + tr.children.length + '|' + tr.children[1].textContent;})()",- )- .unwrap();- assert_eq!(out, serde_json::json!("TR|2|2"));- }-- #[test]- fn clone_node_shallow_copies_attributes_without_children() {- let mut rt = setup_runtime(r#"<html><body><div id="d" data-x="7"><span>kid</span></div></body></html>"#);- let out = rt- .evaluate(- "(function(){var c=document.getElementById('d').cloneNode(false); return c.getAttribute('data-x') + '|' + c.childNodes.length;})()",- )- .unwrap();- assert_eq!(out, serde_json::json!("7|0"));- }-- #[test]- fn clone_node_copies_js_assigned_inline_styles() {- let mut rt = setup_runtime("<html><body><div id='d'></div></body></html>");- let out = rt- .evaluate(- "(function(){var d=document.getElementById('d');d.style.color='red';d.style.fontSize='12px';var c=d.cloneNode(false);return c.style.color+'|'+c.style.fontSize+'|'+c.style.cssText;})()",- )- .unwrap();- assert_eq!(out, serde_json::json!("red|12px|color: red; font-size: 12px;"));- }-- #[test]- fn clone_node_deep_copies_template_content() {- let mut rt = setup_runtime("<html><body></body></html>");- let out = rt- .evaluate(- "(function(){var t=document.createElement('template');t.content.appendChild(document.createElement('option')).textContent='choice';var c=t.cloneNode(true);return c.content.childNodes.length+'|'+c.content.firstChild.tagName+'|'+c.content.firstChild.textContent;})()",- )- .unwrap();- assert_eq!(out, serde_json::json!("1|OPTION|choice"));- }-- #[test]- fn insert_adjacent_html_parses_table_fragments() {- let mut rt = setup_runtime(- r#"<html><body><table id="t"><tbody id="tb"></tbody></table></body></html>"#,- );- let out = rt- .evaluate("(function(){var tb=document.getElementById('tb'); tb.insertAdjacentHTML('beforeend','<tr><td>1</td><td>2</td></tr>'); var tr=tb.firstElementChild; return tr ? (tr.tagName+':'+tr.children.length) : 'NULL';})()")- .unwrap();- assert_eq!(out, serde_json::json!("TR:2"));- }-- #[test]- fn insert_adjacent_html_position_is_case_insensitive() {- let mut rt = setup_runtime(r#"<html><body><div id="host"><span>base</span></div></body></html>"#);- let out = rt- .evaluate("(function(){var h=document.getElementById('host'); h.insertAdjacentHTML('BeforeEnd','<b>x</b>'); return h.lastElementChild ? h.lastElementChild.tagName : 'NULL';})()")- .unwrap();- assert_eq!(out, serde_json::json!("B"));- }-- #[test]- fn insert_adjacent_html_rejects_invalid_position() {- let mut rt = setup_runtime(r#"<html><body><div id="host"></div></body></html>"#);- let out = rt- .evaluate("(function(){var h=document.getElementById('host'); try { h.insertAdjacentHTML('nope','<b>x</b>'); return 'no-throw'; } catch(e){ return e.name; }})()")- .unwrap();- assert_eq!(out, serde_json::json!("SyntaxError"));- }-- #[test]- fn insert_adjacent_html_keeps_leading_comments_in_table_contexts() {- let mut rt = setup_runtime(- r#"<html><body><table><tbody id="tb"><tr id="row"></tr></tbody></table></body></html>"#,- );- let out = rt- .evaluate(- "(function(){var tb=document.getElementById('tb');tb.insertAdjacentHTML('beforeend','<!--m--><tr><td>v</td></tr>');var row=document.getElementById('row');row.insertAdjacentHTML('beforeend','<!--n--><td>x</td>');return Array.from(tb.childNodes).map(function(n){return n.nodeName}).join('|')+';'+Array.from(row.childNodes).map(function(n){return n.nodeName}).join('|');})()",- )- .unwrap();- assert_eq!(out, serde_json::json!("TR|#comment|TR;#comment|TD"));- }-- #[test]- fn insert_adjacent_html_uses_the_insertion_element_as_context() {- let mut rt = setup_runtime(- r#"<html><body><div id="d"></div><table id="table"><tbody id="tb"></tbody></table></body></html>"#,- );- let out = rt- .evaluate(- "(function(){var d=document.getElementById('d');d.insertAdjacentHTML('beforeend','<tr><td>v</td></tr>');var table=document.getElementById('table');table.insertAdjacentHTML('beforeend','<tr><td>x</td></tr>');var tb=document.getElementById('tb');tb.insertAdjacentHTML('beforeend','<tr><td>y</td></tr>tail');return d.firstChild.nodeName+':'+d.textContent+';'+table.lastElementChild.tagName+';'+Array.from(tb.childNodes).map(function(n){return n.nodeName+(n.data?':'+n.data:'')}).join('|');})()",- )- .unwrap();- assert_eq!(out, serde_json::json!("#text:v;TBODY;TR|#text:tail"));- }-- #[test]- fn set_attribute_ns_is_retrievable_by_namespace_and_local_name() {- let mut rt = setup_runtime("<html><body></body></html>");- let v = rt- .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg'); s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g'); return s.getAttributeNS('http://www.w3.org/1999/xlink','href');})()")- .unwrap();- assert_eq!(v, serde_json::json!("#g"));- }-#[test]fn created_foreign_element_keeps_native_qualified_name_through_clone() {let mut rt = setup_runtime("<html><body></body></html>");@@ -4151,59 +3993,6 @@ mod tests {);}- #[test]- fn remove_attribute_ns_removes_by_namespace() {- let mut rt = setup_runtime("<html><body></body></html>");- let v = rt- .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg'); s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g'); s.removeAttributeNS('http://www.w3.org/1999/xlink','href'); return s.getAttributeNS('http://www.w3.org/1999/xlink','href');})()")- .unwrap();- assert_eq!(v, serde_json::json!(null));- }-- #[test]- fn get_attribute_ns_reads_plain_attributes_with_null_namespace() {- // Backward-compat: getAttributeNS(null, name) still reads a plain attr.- let mut rt = setup_runtime(r#"<html><body><div id="d" title="hi"></div></body></html>"#);- let v = rt- .evaluate("document.getElementById('d').getAttributeNS(null,'title')")- .unwrap();- assert_eq!(v, serde_json::json!("hi"));- }-- #[test]- fn namespaced_attribute_keeps_its_qualified_name() {- let mut rt = setup_runtime("<html><body></body></html>");- let v = rt- .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g');return s.getAttribute('xlink:href')+'|'+s.getAttributeNames()[0]+'|'+s.outerHTML;})()")- .unwrap();- assert_eq!(v, serde_json::json!("#g|xlink:href|<svg xlink:href=\"#g\"></svg>"));- }-- #[test]- fn parsed_xlink_attribute_is_available_through_both_apis() {- let mut rt = setup_runtime(- r##"<html><body><svg><use id="u" xlink:href="#icon"></use></svg></body></html>"##,- );- let v = rt- .evaluate("(function(){var u=document.getElementById('u');return u.getAttribute('xlink:href')+'|'+u.getAttributeNS('http://www.w3.org/1999/xlink','href')+'|'+u.getAttributeNames().join(',');})()")- .unwrap();- assert_eq!(v, serde_json::json!("#icon|#icon|id,xlink:href"));- }-- #[test]- fn set_attribute_ns_validates_namespace_constraints() {- let mut rt = setup_runtime("<html><body></body></html>");- let v = rt- .evaluate("(function(){var e=document.createElement('div'),out=[];for(const args of [[null,'x:y'],['urn:test','a:b:c'],['urn:test','xml:lang'],['urn:test','xmlns:x']]){try{e.setAttributeNS(args[0],args[1],'v');out.push('none')}catch(err){out.push(err.name)}}return out.join('|');})()")- .unwrap();- assert_eq!(- v,- serde_json::json!(- "NamespaceError|InvalidCharacterError|NamespaceError|NamespaceError"- )- );- }-#[test]fn throwing_custom_element_constructor_marks_upgrade_failed_without_connecting() {let mut rt = setup_runtime(@@ -5912,6 +5701,40 @@ mod tests {);}+ #[test]+ fn script_created_attribute_reads_stay_coherent_across_mutation_apis() {+ let mut rt = setup_runtime(r#"<html><body></body></html>"#);+ let result = rt+ .evaluate(+ r#"+ (() => {+ const element = document.createElement("DIV");+ const initial = element.getAttribute("data-state");+ element.setAttribute("DATA-STATE", "ready");+ const ordinary = [+ element.getAttribute("data-state"),+ element.getAttribute("DATA-STATE"),+ ];+ element.setAttributeNS(null, "data-state", "namespaced");+ const namespaced = element.getAttribute("data-state");+ element.removeAttributeNS(null, "data-state");+ const removed = element.getAttribute("data-state");+ return { initial, ordinary, namespaced, removed };+ })()+ "#,+ )+ .unwrap();+ assert_eq!(+ result,+ serde_json::json!({+ "initial": null,+ "ordinary": ["ready", "ready"],+ "namespaced": "namespaced",+ "removed": null,+ })+ );+ }+#[test]fn element_scroll_methods_update_scroll_offsets() {let mut rt = setup_runtime(