Skip to content

The headless browser for AI agents and web scraping

fix(dom): align mutations and observer records with the DOM standard

SGavrla59ea068193b
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rs
index 46ec0431..66b4196e 100644
--- a/crates/obscura-dom/src/tree.rs
+++ b/crates/obscura-dom/src/tree.rs
@@ -756,6 +756,37 @@ impl DomTree {
.or_else(|| inner.shadow_roots.get(&node).map(|root| root.host))
}
+ /// Whether `ancestor` is an inclusive ancestor of `node` through ordinary
+ /// parent links only (a shadow root ends the walk), as MutationObserver
+ /// subtree matching requires. Bounded like the other ancestor walks.
+ pub fn is_inclusive_ancestor(&self, ancestor: NodeId, node: NodeId) -> bool {
+ let inner = self.inner.borrow();
+ let mut current = Some(node);
+ for _ in 0..=inner.nodes.len() {
+ let Some(id) = current else { return false };
+ if id == ancestor {
+ return true;
+ }
+ current = inner
+ .nodes
+ .get(id.index())
+ .and_then(|entry| entry.as_ref())
+ .and_then(|entry| entry.parent);
+ }
+ false
+ }
+
+ /// Whether `ancestor` is a host-including inclusive ancestor of `node`, the
+ /// DOM pre-insertion check that stops a node from being inserted into its
+ /// own subtree. Uses the same bounded walk as the reparenting guards.
+ pub fn is_host_including_inclusive_ancestor(&self, ancestor: NodeId, node: NodeId) -> bool {
+ if ancestor == node {
+ return true;
+ }
+ let inner = self.inner.borrow();
+ Self::would_create_host_including_cycle(&inner, node, ancestor)
+ }
+
/// DOM insertion rejects a node when it is a host-including inclusive
/// ancestor of the destination parent. Ordinary parent links are not enough
/// for this check because a ShadowRoot's parent is intentionally null.
@@ -2241,6 +2272,52 @@ mod tests {
assert_eq!(tree.children(root), vec![shadow_child]);
}
+ #[test]
+ fn host_including_ancestor_query_follows_parents_and_hosts() {
+ let tree = DomTree::new();
+ let document = tree.document();
+ let outer = element(&tree, "div");
+ let host = element(&tree, "x-card");
+ let leaf = element(&tree, "i");
+ tree.append_child(document, outer);
+ tree.append_child(outer, host);
+ let root = tree
+ .attach_shadow_root(host, ShadowRootMode::Open)
+ .unwrap();
+ let shadow_child = element(&tree, "span");
+ tree.append_child(root, shadow_child);
+
+ assert!(tree.is_host_including_inclusive_ancestor(shadow_child, shadow_child));
+ assert!(tree.is_host_including_inclusive_ancestor(outer, host));
+ assert!(tree.is_host_including_inclusive_ancestor(host, shadow_child));
+ assert!(tree.is_host_including_inclusive_ancestor(outer, shadow_child));
+ assert!(tree.is_host_including_inclusive_ancestor(document, shadow_child));
+ assert!(!tree.is_host_including_inclusive_ancestor(shadow_child, outer));
+ assert!(!tree.is_host_including_inclusive_ancestor(leaf, outer));
+ assert!(!tree.is_host_including_inclusive_ancestor(host, outer));
+ }
+
+ #[test]
+ fn inclusive_ancestor_query_stops_at_shadow_roots() {
+ let tree = DomTree::new();
+ let document = tree.document();
+ let outer = element(&tree, "div");
+ let host = element(&tree, "x-card");
+ tree.append_child(document, outer);
+ tree.append_child(outer, host);
+ let root = tree
+ .attach_shadow_root(host, ShadowRootMode::Open)
+ .unwrap();
+ let shadow_child = element(&tree, "span");
+ tree.append_child(root, shadow_child);
+
+ assert!(tree.is_inclusive_ancestor(outer, outer));
+ assert!(tree.is_inclusive_ancestor(document, host));
+ assert!(tree.is_inclusive_ancestor(root, shadow_child));
+ assert!(!tree.is_inclusive_ancestor(host, shadow_child));
+ assert!(!tree.is_inclusive_ancestor(host, outer));
+ }
+
#[test]
fn connectivity_propagates_across_light_and_shadow_subtrees() {
let tree = DomTree::new();
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index c45f1380..7a52ddee 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -76,6 +76,8 @@ const __obscuraCore = globalThis.Deno.core;
'XMLHttpRequestEventTarget', 'HTMLMediaElement', 'HTMLVideoElement',
'HTMLAudioElement', 'WebGL2RenderingContext',
'SVGElement', 'SVGGraphicsElement', 'SVGGeometryElement', 'SVGPathElement',
+ 'MutationRecord', 'CSSConditionRule', 'CSSMediaRule', 'CSSSupportsRule',
+ 'IntersectionObserverEntry', 'XMLDocument',
'SVGSVGElement', 'SVGGElement', 'SVGDefsElement', 'SVGSymbolElement',
'SVGUseElement', 'SVGMarkerElement', 'SVGAElement', 'SVGSwitchElement',
'SVGImageElement', 'SVGForeignObjectElement', 'SVGRectElement',
@@ -2297,6 +2299,38 @@ function __prepareInsertedScript(script) {
}
}
+// Post-connection steps run per inserted node, in tree order, after the whole
+// insertion. While a script among them runs, an iframe later in tree order
+// has not run its steps yet, so it has no content window.
+let _postConnection = null;
+function _runPostConnectionSteps(nodes) {
+ const outer = _postConnection;
+ const state = { roots: nodes, index: 0, cursor: null };
+ _postConnection = state;
+ try {
+ for (let i = 0; i < nodes.length; i++) {
+ state.index = i;
+ state.cursor = null;
+ const n = nodes[i];
+ __prepareInsertedSubtree(n);
+ if (n instanceof Element && n.tagName === 'LINK') _loadLinkedStylesheet(n);
+ }
+ } finally {
+ _postConnection = outer;
+ }
+}
+function _iframeConnectionPending(iframe) {
+ const state = _postConnection;
+ if (!state) return false;
+ for (let j = state.index; j < state.roots.length; j++) {
+ const root = state.roots[j];
+ if (root !== iframe && _dom("is_inclusive_ancestor", root._nid, iframe._nid) !== "true") continue;
+ if (j > state.index) return true;
+ return !!state.cursor && _rngOrder(state.cursor, iframe) < 0;
+ }
+ return false;
+}
+
function __prepareInsertedSubtree(root) {
// HTML's script preparation algorithm leaves a disconnected script
// unstarted. When an ancestor is later connected, insertion steps visit
@@ -2316,7 +2350,10 @@ function __prepareInsertedSubtree(root) {
seen.add(script._nid);
}
}
- for (const script of scripts) __prepareInsertedScript(script);
+ for (const script of scripts) {
+ if (_postConnection) _postConnection.cursor = script;
+ __prepareInsertedScript(script);
+ }
}
function _seedDetachedTreeState(node) {
@@ -2340,6 +2377,389 @@ function _seedUnchangedConnection(node, connected) {
node._treeConnectedEpoch = _treeMutationEpoch;
}
+// Node documents. The main document owns a node unless its tree's root says
+// otherwise: a detached Document (createHTMLDocument, createDocument) is the
+// root of its own tree, and the root of a tree made by another document (its
+// create* methods, DOMParser, an iframe shim document) carries
+// `_nodeDocument`. All nodes of a tree share one node document, so only roots
+// are stamped: insertion clears the stamp (the node is no longer a root) and
+// removal stamps the new root with the document it left.
+let _foreignDocumentCount = 0;
+function _nodeDocumentOf(node) {
+ if (_foreignDocumentCount === 0 || node.isConnected) return globalThis.document;
+ let root = node;
+ for (let parent = root.parentNode; parent; parent = parent.parentNode) root = parent;
+ if (root.nodeType === 9 && root._detached) return root;
+ if (root instanceof ShadowRoot && root.host) return _nodeDocumentOf(root.host);
+ return root._nodeDocument || globalThis.document;
+}
+function _stampNodeDocument(node, doc) {
+ if (node && doc && doc !== globalThis.document) node._nodeDocument = doc;
+ return node;
+}
+function _registerForeignDocument() { _foreignDocumentCount++; }
+// A Document without a browsing context, backed by its own native tree root.
+function _createDetachedDocument(contentType, xml) {
+ const nid = +_dom("create_document_fragment");
+ const DocumentClass = xml ? (globalThis.XMLDocument || Document) : Document;
+ const doc = new DocumentClass(nid);
+ doc._detached = true;
+ doc._contentType = contentType;
+ _seedDetachedTreeState(doc);
+ _cache.set(nid, doc);
+ _registerForeignDocument();
+ return doc;
+}
+function _childNodeOfType(parent, type) {
+ for (let child = parent.firstChild; child; child = child.nextSibling) {
+ if (child.nodeType === type) return child;
+ }
+ return null;
+}
+
+// DOM mutation algorithms (https://dom.spec.whatwg.org/#mutation-algorithms).
+// appendChild, insertBefore, replaceChild, removeChild, the ChildNode and
+// ParentNode methods, textContent and Range all go through these, so they
+// validate in the spec's order and queue the same MutationObserver records.
+
+function _isDomNode(value) {
+ return value instanceof Node
+ || (typeof globalThis.Attr === "function" && value instanceof globalThis.Attr)
+ || (value !== null && typeof value === "object"
+ && (typeof value._nid === "number" || value._documentShim === true));
+}
+
+function _requireNodeArgument(value, method, position, iface = "Node") {
+ if (!_isDomNode(value)) {
+ throw new TypeError(
+ `Failed to execute '${method}' on '${iface}': parameter ${position} is not of type 'Node'.`,
+ );
+ }
+}
+
+// Objects a node's methods create come from that node's relevant global. An
+// iframe document's nodes live in this realm, so their exceptions and node
+// lists take the frame window's constructors explicitly.
+function _frameViewOf(context) {
+ if (!context || !_foreignDocumentCount) return null;
+ const doc = context.nodeType === 9 ? context : _nodeDocumentOf(context);
+ const view = doc && doc !== globalThis.document ? doc.defaultView : null;
+ return view && view !== globalThis ? view : null;
+}
+function _relevantNodeList(context, list) {
+ const view = _frameViewOf(context);
+ const FrameNodeList = view && view.NodeList;
+ if (typeof FrameNodeList === "function" && FrameNodeList.prototype !== NodeList.prototype) {
+ Object.setPrototypeOf(list, FrameNodeList.prototype);
+ }
+ return list;
+}
+function _mutationError(method, message, name, context) {
+ const view = _frameViewOf(context);
+ const Ctor = view && typeof view.DOMException === "function" ? view.DOMException : DOMException;
+ return new Ctor(`Failed to execute '${method}' on 'Node': ${message}`, name);
+}
+
+function _isHostIncludingInclusiveAncestor(node, parent) {
+ if (node === parent) return true;
+ const type = node.nodeType;
+ if (type !== 1 && type !== 9 && type !== 11) return false;
+ // The native walk goes up from parent and through shadow hosts; leaves
+ // that host no shadow root answer without walking.
+ return _dom("is_host_including_inclusive_ancestor", node._nid, parent._nid) === "true";
+}
+
+// "Ensure pre-insertion validity" and the validity checks of "replace"
+// (`replacing` true). Steps run in the spec's order because the order is
+// observable through which exception is thrown.
+function _ensureInsertionValidity(parent, node, child, method, replacing) {
+ const parentType = parent.nodeType;
+ if (parentType !== 1 && parentType !== 9 && parentType !== 11) {
+ throw _mutationError(method, "This node type does not support this method.", "HierarchyRequestError", parent);
+ }
+ // Appending a parentless non-fragment node has no side effect before the
+ // native insert, whose cycle guard rejects the same case with the same
+ // error, so the walk is only needed when ordering or side effects matter.
+ const needsAncestorCheck = child !== null || node.nodeType === 11
+ || node._shadowParent || node.parentNode !== null;
+ if (needsAncestorCheck ? _isHostIncludingInclusiveAncestor(node, parent) : node === parent) {
+ throw _mutationError(method, "The new child element contains the parent.", "HierarchyRequestError", parent);
+ }
+ if (child !== null && child.parentNode !== parent) {
+ throw _mutationError(
+ method,
+ replacing
+ ? "The node to be replaced is not a child of this node."
+ : "The node before which the new node is to be inserted is not a child of this node.",
+ "NotFoundError",
+ parent,
+ );
+ }
+ const nodeType = node.nodeType;
+ if ((nodeType !== 1 && nodeType !== 3 && nodeType !== 4 && nodeType !== 7
+ && nodeType !== 8 && nodeType !== 10 && nodeType !== 11) || node instanceof ShadowRoot) {
+ throw _mutationError(
+ method,
+ `Nodes of type '${node.nodeName}' may not be inserted inside nodes of type '${parent.nodeName}'.`,
+ "HierarchyRequestError",
+ parent,
+ );
+ }
+ if (((nodeType === 3 || nodeType === 4) && parentType === 9)
+ || (nodeType === 10 && parentType !== 9)) {
+ throw _mutationError(
+ method,
+ `Nodes of type '${node.nodeName}' may not be inserted inside nodes of type '${parent.nodeName}'.`,
+ "HierarchyRequestError",
+ parent,
+ );
+ }
+ if (parentType === 9) _ensureDocumentChildValidity(parent, node, nodeType, child, method, replacing);
+}
+
+function _ensureDocumentChildValidity(parent, node, nodeType, child, method, replacing) {
+ const doc = parent;
+ const children = Array.from(doc.childNodes);
+ const childIndex = child === null ? children.length : children.indexOf(child);
+ const hasElementOtherThanChild = children.some(c => c.nodeType === 1 && !(replacing && c === child));
+ const doctypeFollowsChild = child !== null
+ && children.slice(childIndex + (replacing ? 1 : 0)).some(c => c.nodeType === 10);
+ const elementPrecedesChild = children.slice(0, childIndex).some(c => c.nodeType === 1);
+ const oneElement = () => {
+ if (hasElementOtherThanChild || (!replacing && child !== null && child.nodeType === 10) || doctypeFollowsChild) {
+ throw _mutationError(method, "Only one element on document allowed.", "HierarchyRequestError", parent);
+ }
+ };
+ if (nodeType === 11) {
+ let elements = 0;
+ for (const c of Array.from(node.childNodes)) {
+ const t = c.nodeType;
+ if (t === 1) elements++;
+ else if (t === 3 || t === 4) {
+ throw _mutationError(method, "Nodes of type '#text' may not be inserted inside nodes of type '#document'.", "HierarchyRequestError", parent);
+ }
+ }
+ if (elements > 1) throw _mutationError(method, "Only one element on document allowed.", "HierarchyRequestError", parent);
+ if (elements === 1) oneElement();
+ } else if (nodeType === 1) {
+ oneElement();
+ } else if (nodeType === 10) {
+ const hasOtherDoctype = children.some(c => c.nodeType === 10 && !(replacing && c === child));
+ if (hasOtherDoctype) throw _mutationError(method, "Only one doctype on document allowed.", "HierarchyRequestError", parent);
+ if (child !== null ? elementPrecedesChild : children.some(c => c.nodeType === 1)) {
+ throw _mutationError(method, "Can't insert a doctype after the document element.", "HierarchyRequestError", parent);
+ }
+ }
+}
+
+// "Convert nodes into a node": strings become Text nodes; more than one
+// argument is collected into a DocumentFragment so the caller inserts once and
+// observers get a single record.
+function _convertNodesIntoNode(nodes, context) {
+ if (nodes.length === 1 && _isDomNode(nodes[0])) return nodes[0];
+ const owner = _nodeDocumentForInsertion(context);
+ const converted = [];
+ for (let i = 0; i < nodes.length; i++) {
+ const n = nodes[i];
+ converted.push(_isDomNode(n) ? n : owner.createTextNode(String(n)));
+ }
+ if (converted.length === 1) return converted[0];
+ const fragment = owner.createDocumentFragment();
+ for (const n of converted) fragment.appendChild(n);
+ return fragment;
+}
+
+// ParentNode/ChildNode insertion of several nodes. The spec collects them in
+// a DocumentFragment and inserts that; for the common shape (an element or
+// fragment parent and plain nodes that are not already under it, not
+// repeated and not its ancestors) inserting them in order is observably the
+// same, including the one childList record, without the fragment round trip.
+// Anything else takes the fragment path. `reference` is read after conversion.
+function _preInsertConverted(parent, args, context, reference, method) {
+ if (args.length === 1 && _isDomNode(args[0])) return _preInsertNode(parent, args[0], reference(), method);
+ const parentType = parent.nodeType;
+ if (args.length > 1 && (parentType === 1 || parentType === 11) && !(parent instanceof ShadowRoot)) {
+ const nodes = _plainInsertionNodes(parent, args, context);
+ const child = nodes && reference();
+ if (nodes && (child === null || (!nodes.includes(child) && child.parentNode === parent))) {
+ const observed = _hasMutationObservers();
+ const previousSibling = observed
+ ? (child === null ? parent.lastChild : _recordSiblings(child)[0])
+ : null;
+ for (const n of nodes) _insertOneNode(parent, n, child, method, true);
+ if (observed) _queueTreeMutationRecord(parent, nodes, [], previousSibling, child);
+ _runPostConnectionSteps(nodes);
+ return;
+ }
+ }
+ _preInsertNode(parent, _convertNodesIntoNode(args, context), reference(), method);
+}
+function _plainInsertionNodes(parent, args, context) {
+ let owner = null;
+ const nodes = [];
+ const seen = new Set();
+ for (let i = 0; i < args.length; i++) {
+ let n = args[i];
+ if (!_isDomNode(n)) {
+ owner = owner || _nodeDocumentForInsertion(context);
+ n = owner.createTextNode(String(n));
+ } else {
+ const type = n.nodeType;
+ if (type !== 1 && type !== 3 && type !== 4 && type !== 7 && type !== 8) return null;
+ if (seen.has(n) || n.parentNode === parent || n._shadowParent) return null;
+ if (type === 1 && _isHostIncludingInclusiveAncestor(n, parent)) return null;
+ seen.add(n);
+ }
+ nodes.push(n);
+ }
+ return nodes;
+}
+
+function _nodeDocumentForInsertion(node) {
+ if (node.nodeType === 9) return node._detached ? node : globalThis.document;
+ return _nodeDocumentOf(node);
+}
+
+// Previous and next sibling of a node as record values: node ids resolved
+// lazily by MutationRecord, captured in one native call.
+function _recordSiblings(node) {
+ if (node._shadowParent) return [node.previousSibling, node.nextSibling];
+ const pair = _dom("sibling_nids", node._nid) || "-1,-1";
+ const comma = pair.indexOf(",");
+ return [+pair.slice(0, comma), +pair.slice(comma + 1)];
+}
+// Attribute records need the old value only when a registration asked for
+// it; removals still read it, since a removal of a missing attribute is none.
+function _attributeOldValuesWanted() {
+ const observers = globalThis.__mutationObservers;
+ if (!observers || !observers.length) return false;
+ for (const observer of observers) {
+ for (const registration of observer._targets) if (registration.options.attributeOldValue) return true;
+ }
+ return false;
+}
+function _hasMutationObservers() {
+ const observers = globalThis.__mutationObservers;
+ return !!(observers && observers.length);
+}
+
+// "Remove": `suppress` skips the record, as replace/replace-all queue their own.
+function _removeNode(parent, child, suppress, method = "removeChild") {
+ const observed = !suppress && _hasMutationObservers();
+ const [previousSibling, nextSibling] = observed ? _recordSiblings(child) : [null, null];
+ const removedWindowNames = _windowNamedNamesInTree(child);
+ if (child instanceof Element) _releaseLinkedStylesheetsIn(child);
+ const parentConnected = parent.isConnected;
+ const removed = _dom("remove_child", child._nid) === "true";
+ if (!removed) {
+ throw _mutationError(method, "The node to be removed is not a child of this node.", "NotFoundError");
+ }
+ _seedUnchangedConnection(parent, parentConnected);
+ _seedDetachedTreeState(child);
+ if (_foreignDocumentCount) _stampNodeDocument(child, _nodeDocumentForInsertion(parent));
+ _detachStyleSheetsInSubtree(child);
+ _reconcileWindowNamedProperties(removedWindowNames);
+ if (observed) _queueTreeMutationRecord(parent, [], [child], previousSibling, nextSibling);
+}
+
+// Move one node under `parent` before `child` (append when null). A node
+// that still has a parent is removed from it first, which old-parent
+// observers see as a removal (adopt runs "remove" before inserting).
+function _insertOneNode(parent, node, child, method, queueOldParentRecord) {
+ if (node._shadowParent) {
+ node._shadowParent.removeChild(node);
+ } else {
+ const oldParent = node.parentNode;
+ if (oldParent) {
+ if (queueOldParentRecord && _hasMutationObservers()) {
+ const [previousSibling, nextSibling] = _recordSiblings(node);
+ _queueTreeMutationRecord(oldParent, [], [node], previousSibling, nextSibling);
+ }
+ _detachStyleSheetsInSubtree(node);
+ }
+ }
+ const parentConnected = parent.isConnected;
+ const inserted = child === null
+ ? _dom("append_child", parent._nid, node._nid) === "true"
+ : _dom("insert_before", node._nid, child._nid) === "true";
+ if (!inserted) {
+ // The native guard rejects cycles, the case the skipped ancestor walk covers.
+ throw _mutationError(method, "The new child element contains the parent.", "HierarchyRequestError", parent);
+ }
+ _seedUnchangedConnection(parent, parentConnected);
+ _seedInsertedTreeState(node, parent, parentConnected);
+ if (node._nodeDocument !== undefined) node._nodeDocument = undefined;
+ _registerWindowNamedTree(node);
+}
+
+// "Insert": returns the inserted nodes. `suppress` skips parent's record.
+function _insertNode(parent, node, child, suppress, method) {
+ const isFragment = node.nodeType === 11;
+ let nodes;
+ if (isFragment) {
+ nodes = Array.from(node.childNodes);
+ if (nodes.length === 0) return nodes;
+ // The children leave the fragment silently; the fragment's own
+ // observers get one record for all of them.
+ if (_hasMutationObservers()) _queueTreeMutationRecord(node, [], nodes, null, null);
+ } else {
+ nodes = [node];
+ }
+ const observed = !suppress && _hasMutationObservers();
+ const previousSibling = observed
+ ? (child === null ? parent.lastChild : _recordSiblings(child)[0])
+ : null;
+ for (const n of nodes) _insertOneNode(parent, n, child, method, !isFragment);
+ if (observed) _queueTreeMutationRecord(parent, nodes, [], previousSibling, child);
+ _runPostConnectionSteps(nodes);
+ return nodes;
+}
+
+function _preInsertNode(parent, node, child, method) {
+ _ensureInsertionValidity(parent, node, child, method, false);
+ let reference = child;
+ if (reference === node) reference = node.nextSibling;
+ _insertNode(parent, node, reference, false, method);
+ return node;
+}
+
+function _replaceChildNode(parent, node, child, method) {
+ _ensureInsertionValidity(parent, node, child, method, true);
+ let reference = child.nextSibling;
+ if (reference === node) reference = node.nextSibling;
+ let previousSibling = child.previousSibling;
+ if (previousSibling === node) previousSibling = node.previousSibling;
+
+ const observed = _hasMutationObservers();
+ const addedNodes = observed ? (node.nodeType === 11 ? Array.from(node.childNodes) : [node]) : null;
+ // Adopting node removes it from its parent before child is removed, so its
+ // old parent (possibly this one) sees that removal first.
+ if (node.nodeType !== 11) {
+ const oldParent = node._shadowParent || node.parentNode;
+ if (oldParent) oldParent.removeChild(node);
+ }
+ const removedNodes = [];
+ if (child.parentNode === parent) {
+ removedNodes.push(child);
+ _removeNode(parent, child, true, method);
+ }
+ _insertNode(parent, node, reference, true, method);
+ if (observed) _queueTreeMutationRecord(parent, addedNodes, removedNodes, previousSibling, reference);
+ return child;
+}
+
+// "Replace all" (replaceChildren, textContent). `node` may be null.
+function _replaceAllChildren(parent, node, method) {
+ const removedNodes = Array.from(parent.childNodes);
+ const observed = _hasMutationObservers();
+ const addedNodes = node === null ? [] : (node.nodeType === 11 ? Array.from(node.childNodes) : [node]);
+ for (const c of removedNodes) _removeNode(parent, c, true, method);
+ if (node !== null) _insertNode(parent, node, null, true, method);
+ if (observed && (addedNodes.length || removedNodes.length)) {
+ _queueTreeMutationRecord(parent, addedNodes, removedNodes, null, null);
+ }
+}
+
class Node {
static ELEMENT_NODE = 1;
static ATTRIBUTE_NODE = 2;
@@ -2363,30 +2783,44 @@ class Node {
constructor(nid) { this._nid = nid; }
get nodeType() { return +_dom("node_type", this._nid); }
get nodeName() { return _domParse("node_name", this._nid) || ""; }
- get ownerDocument() { return globalThis.document; }
+ get ownerDocument() { return _nodeDocumentOf(this); }
// https://dom.spec.whatwg.org/#dom-node-baseuri
get baseURI() {
try { return _documentBase(); } catch (e) { return ""; }
}
get textContent() { return _domParse("text_content", this._nid) ?? ""; }
set textContent(v) {
+ const type = this.nodeType;
+ if (type === 9 || type === 10) return;
+ const value = v == null ? "" : String(v);
+ if (type !== 1 && type !== 11) {
+ this.data = value;
+ return;
+ }
+ // "String replace all". Removal keeps the old cheap per-child steps; the
+ // record rules are the spec's: one record, and none when nothing changed.
const oldChildren = _domParse("child_nodes", this._nid) || [];
+ const observed = _hasMutationObservers();
+ const removedNodes = observed ? oldChildren.map(_wrap).filter(Boolean) : null;
+ const doc = _foreignDocumentCount ? _nodeDocumentForInsertion(this) : null;
for (const c of oldChildren) {
const child = _wrap(c);
if (child) _detachStyleSheetsInSubtree(child);
_dom("remove_child", c);
+ if (child) {
+ _seedDetachedTreeState(child);
+ _stampNodeDocument(child, doc);
+ }
}
- let added = [];
- if (v != null && v !== "") {
- const tn = +_dom("create_text_node", String(v));
- _dom("append_child", this._nid, tn);
- added = [tn];
+ let addedNodes = [];
+ if (value !== "") {
+ const text = _nodeDocumentForInsertion(this).createTextNode(value);
+ _dom("append_child", this._nid, text._nid);
+ _seedInsertedTreeState(text, this, this.isConnected);
+ addedNodes = [text];
}
- // Real MutationObserver fires childList for the children swap.
- // Without this React 18+ hydration mismatch detection and many polling
- // libs (intersection-driven lazy load, content sync) silently stall.
- if (globalThis.__mutationObservers?.length) {
- globalThis.__notifyMutation('childList', this._nid, added, oldChildren);
+ if (observed && (addedNodes.length || removedNodes.length)) {
+ _queueTreeMutationRecord(this, addedNodes, removedNodes, null, null);
}
}
get nodeValue() {
@@ -2396,7 +2830,9 @@ class Node {
}
set nodeValue(v) {
const t = this.nodeType;
- if (t === 3 || t === 8) _dom("set_text_content", this._nid, String(v ?? ""));
+ if (t !== 3 && t !== 8) return;
+ if (this instanceof CharacterData) this.data = v ?? "";
+ else _dom("set_text_content", this._nid, String(v ?? ""));
}
get parentNode() {
if (this._shadowParent) return this._shadowParent;
@@ -2430,147 +2866,31 @@ class Node {
}
return _wrap(+_dom("prev_sibling", this._nid));
}
- appendChild(c) {
- if (!c) return c;
- if (this instanceof CharacterData) {
- throw new DOMException(
- "Failed to execute 'appendChild' on 'Node': This node type cannot have children.",
- "HierarchyRequestError",
- );
- }
- if (c instanceof DocumentFragment) {
- const children = Array.from(c.childNodes);
- for (const child of children) this.appendChild(child);
- return c;
- }
- if (c._shadowParent) c._shadowParent.removeChild(c);
- else if (c.parentNode) _detachStyleSheetsInSubtree(c);
- const parentConnected = this.isConnected;
- const inserted = _dom("append_child", this._nid, c._nid) === "true";
- if (!inserted) {
- throw new DOMException(
- "Failed to execute 'appendChild' on 'Node': The new child would create an invalid tree.",
- "HierarchyRequestError",
- );
- }
- _seedUnchangedConnection(this, parentConnected);
- _seedInsertedTreeState(c, this, parentConnected);
- _registerWindowNamedTree(c);
- if (globalThis.__mutationObservers?.length) globalThis.__notifyMutation('childList', this._nid, [c._nid], []);
- __prepareInsertedSubtree(c);
- if (c instanceof Element && c.tagName === 'LINK') {
- _loadLinkedStylesheet(c);
- }
- return c;
+ appendChild(node) {
+ _requireNodeArgument(node, "appendChild", 1);
+ return _preInsertNode(this, node, null, "appendChild");
}
- removeChild(c) {
- if (!c || c.parentNode !== this) {
- throw new DOMException(
- "Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.",
- 'NotFoundError'
- );
- }
- const removedWindowNames = _windowNamedNamesInTree(c);
- if (c instanceof Element) _releaseLinkedStylesheetsIn(c);
- const parentConnected = this.isConnected;
- const removed = _dom("remove_child", c._nid) === "true";
- if (!removed) {
- throw new DOMException(
- "Failed to execute 'removeChild' on 'Node': The node is not a child of this node.",
- "NotFoundError",
- );
+ removeChild(child) {
+ _requireNodeArgument(child, "removeChild", 1);
+ if (child.parentNode !== this) {
+ throw _mutationError("removeChild", "The node to be removed is not a child of this node.", "NotFoundError", this);
}
- _seedUnchangedConnection(this, parentConnected);
- _seedDetachedTreeState(c);
- _detachStyleSheetsInSubtree(c);
- _reconcileWindowNamedProperties(removedWindowNames);
- if (globalThis.__mutationObservers?.length) globalThis.__notifyMutation('childList', this._nid, [], [c._nid]);
- return c;
+ _removeNode(this, child, false);
+ return child;
}
- replaceChild(newChild, oldChild) {
- if (!oldChild || !newChild) return oldChild;
- if (oldChild.parentNode !== this) {
- throw new DOMException(
- "Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.",
- "NotFoundError",
- );
- }
- if (newChild === oldChild) return oldChild;
- if (newChild instanceof DocumentFragment) {
- const children = Array.from(newChild.childNodes);
- for (const child of children) this.insertBefore(child, oldChild);
- this.removeChild(oldChild);
- return oldChild;
- }
- if (newChild._shadowParent) newChild._shadowParent.removeChild(newChild);
- else if (newChild.parentNode) _detachStyleSheetsInSubtree(newChild);
- const parentConnected = this.isConnected;
- const removedWindowNames = _windowNamedNamesInTree(oldChild);
- const inserted = _dom("insert_before", newChild._nid, oldChild._nid) === "true";
- if (!inserted) {
- throw new DOMException(
- "Failed to execute 'replaceChild' on 'Node': The new child would create an invalid tree.",
- "HierarchyRequestError",
- );
- }
- const removed = _dom("remove_child", oldChild._nid) === "true";
- if (!removed) throw new DOMException("The node could not be replaced.", "NotFoundError");
- _seedUnchangedConnection(this, parentConnected);
- _seedInsertedTreeState(newChild, this, parentConnected);
- _seedDetachedTreeState(oldChild);
- _detachStyleSheetsInSubtree(oldChild);
- _registerWindowNamedTree(newChild);
- _reconcileWindowNamedProperties(removedWindowNames);
- // As in appendChild and removeChild. A replacement is an insertion and a removal. An
- // observer saw neither so far.
- if (globalThis.__mutationObservers?.length) {
- globalThis.__notifyMutation('childList', this._nid, [newChild._nid], [oldChild._nid]);
- }
- __prepareInsertedSubtree(newChild);
- if (newChild instanceof Element && newChild.tagName === 'LINK') {
- _loadLinkedStylesheet(newChild);
- }
- return oldChild;
+ replaceChild(node, child) {
+ _requireNodeArgument(node, "replaceChild", 1);
+ _requireNodeArgument(child, "replaceChild", 2);
+ return _replaceChildNode(this, node, child, "replaceChild");
}
- insertBefore(n, ref) {
- if (!n) return n;
- if (!ref) { this.appendChild(n); return n; }
- if (ref.parentNode !== this) {
- throw new DOMException(
- "Failed to execute 'insertBefore' on 'Node': The reference node is not a child of this node.",
- "NotFoundError",
- );
+ insertBefore(node, child) {
+ _requireNodeArgument(node, "insertBefore", 1);
+ if (arguments.length < 2) {
+ throw new TypeError("Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present.");
}
- if (n === ref) {
- ref = n.nextSibling;
- if (!ref) return this.appendChild(n);
- }
- if (n instanceof DocumentFragment) {
- const children = Array.from(n.childNodes);
- for (const child of children) this.insertBefore(child, ref);
- return n;
- }
- if (n._shadowParent) n._shadowParent.removeChild(n);
- else if (n.parentNode) _detachStyleSheetsInSubtree(n);
- const parentConnected = this.isConnected;
- const inserted = _dom("insert_before", n._nid, ref._nid) === "true";
- if (!inserted) {
- throw new DOMException(
- "Failed to execute 'insertBefore' on 'Node': The new child would create an invalid tree.",
- "HierarchyRequestError",
- );
- }
- _seedUnchangedConnection(this, parentConnected);
- _seedInsertedTreeState(n, this, parentConnected);
- _registerWindowNamedTree(n);
- // The same steps as in appendChild. Where a node is inserted does not decide whether an
- // observer sees it and whether a <link> loads its stylesheet.
- if (globalThis.__mutationObservers?.length) globalThis.__notifyMutation('childList', this._nid, [n._nid], []);
- __prepareInsertedSubtree(n);
- if (n instanceof Element && n.tagName === 'LINK') {
- _loadLinkedStylesheet(n);
- }
- return n;
+ if (child === undefined) child = null;
+ if (child !== null) _requireNodeArgument(child, "insertBefore", 2);
+ return _preInsertNode(this, node, child, "insertBefore");
}
contains(o) {
if (o === this) return true;
@@ -2645,21 +2965,31 @@ class Node {
return connected;
}
normalize() {
- // Merge adjacent exclusive Text nodes, drop empty ones, recurse. Detached
- // removed nodes keep their own data (read from the backing node by nid).
+ // Spec order: drop an empty Text node; otherwise append the data of the
+ // following contiguous Text nodes (one characterData record), then remove
+ // those nodes one by one (one childList record each). Detached removed
+ // nodes keep their own data (read from the backing node by nid).
let child = this.firstChild;
while (child) {
- const next = child.nextSibling;
if (child.nodeType === 3) {
- let data = child.data, sib = child.nextSibling;
- while (sib && sib.nodeType === 3) { const after = sib.nextSibling; data += sib.data; this.removeChild(sib); sib = after; }
- if (data.length === 0) { this.removeChild(child); child = sib; continue; }
- if (data !== child.data) child.data = data;
- child = sib; continue;
- } else if (child.nodeType === 1 || child.nodeType === 11) {
- child.normalize();
+ if (child.data.length === 0) {
+ const next = child.nextSibling;
+ this.removeChild(child);
+ child = next;
+ continue;
+ }
+ const following = [];
+ let sibling = child.nextSibling;
+ while (sibling && sibling.nodeType === 3) { following.push(sibling); sibling = sibling.nextSibling; }
+ if (following.length) {
+ child.data = child.data + following.map(t => t.data).join("");
+ for (const t of following) this.removeChild(t);
+ }
+ child = sibling;
+ continue;
}
- child = next;
+ if (child.nodeType === 1 || child.nodeType === 11) child.normalize();
+ child = child.nextSibling;
}
}
isEqualNode(other) {
@@ -3864,6 +4194,7 @@ class Element extends Node {
const previousWindowName = (n === "id" || n === "name")
? this.getAttribute(n)
: null;
+ const observedOldValue = _attributeOldValuesWanted() ? this.getAttribute(n) : null;
const value = String(v);
_dom("set_attribute", this._nid, n + "\0" + value);
if (n === "src" && this.localName === "iframe") {
@@ -3888,7 +4219,7 @@ class Element extends Node {
if (this.__inlineHandlerCache) delete this.__inlineHandlerCache.onload;
}
if (popoverPrev !== undefined) this._popoverTypeMaybeChanged(popoverPrev);
- if (globalThis.__mutationObservers?.length) globalThis.__notifyMutation('attributes', this._nid, [], [], n);
+ if (_hasMutationObservers()) _queueAttributeMutationRecord(this, n, null, observedOldValue);
if (this.localName === "source"
&& (n === "srcset" || n === "sizes" || n === "media" || n === "type")) {
const picture = this.parentElement;
@@ -3905,7 +4236,10 @@ class Element extends Node {
n = String(n);
const value = String(v);
_ns_validateQualifiedName(ns, n);
+ const localName = n.includes(":") ? n.slice(n.indexOf(":") + 1) : n;
+ const observedOldValue = _attributeOldValuesWanted() ? this.getAttributeNS(ns, localName) : null;
_dom("set_attribute_ns", this._nid, ns + "\0" + n + "\0" + value);
+ if (_hasMutationObservers()) _queueAttributeMutationRecord(this, localName, ns || null, observedOldValue);
// 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.
@@ -3918,7 +4252,9 @@ class Element extends Node {
const previousWindowName = (n === "id" || n === "name")
? this.getAttribute(n)
: null;
+ const observedOldValue = _hasMutationObservers() ? this.getAttribute(n) : null;
_dom("remove_attribute", this._nid, n);
+ if (observedOldValue !== null) _queueAttributeMutationRecord(this, n, null, observedOldValue);
if (this._nullNamespaceAttrs instanceof Map) {
this._nullNamespaceAttrs.delete(n);
}
@@ -3947,7 +4283,9 @@ class Element extends Node {
removeAttributeNS(ns, n) {
ns = String(ns == null ? "" : ns);
n = String(n);
+ const observedOldValue = _hasMutationObservers() ? this.getAttributeNS(ns, n) : null;
_dom("remove_attribute_ns", this._nid, ns + "\0" + n);
+ if (observedOldValue !== null) _queueAttributeMutationRecord(this, n, ns || null, observedOldValue);
this._nullNamespaceAttrs = null;
if (ns === "" && n === "style") this._style._replaceFromAttribute("");
}
@@ -3962,11 +4300,16 @@ class Element extends Node {
querySelector(s) { return _wrapEl(+_dom("query_selector_scoped", this._nid, s)); }
querySelectorAll(s) {
const ids = _domParse("query_selector_all_scoped", this._nid, s) || [];
- return _nodeList(ids.map(_wrapEl).filter(Boolean));
+ return _relevantNodeList(this, _nodeList(ids.map(_wrapEl).filter(Boolean)));
}
getElementsByTagName(t) { return HTMLCollection._from(this.querySelectorAll(t)); }
getElementsByClassName(c) { return _getElementsByClassName(this, c); }
matches(s) {
+ if (arguments.length === 0) {
+ const view = _frameViewOf(this);
+ throw new ((view && view.TypeError) || TypeError)(
+ "Failed to execute 'matches' on 'Element': 1 argument required, but only 0 present.");
+ }
// :popover-open is a JS-observable popover state, not understood by the
// native selector engine. Handle it here (and strip it from compound
// selectors so the rest can still be matched natively).
@@ -4745,6 +5088,7 @@ class Element extends Node {
}
get contentDocument() {
if (this.localName !== 'iframe') return undefined;
+ if (_postConnection && _iframeConnectionPending(this)) return null;
if (_ensureInitialFrameRealm(this) === false) return null;
const real = _frameObjectsFor(this);
if (real?.document) return real.document;
@@ -4767,6 +5111,7 @@ class Element extends Node {
}
get contentWindow() {
if (this.localName !== 'iframe') return undefined;
+ if (_postConnection && _iframeConnectionPending(this)) return null;
if (_ensureInitialFrameRealm(this) === false) return null;
if (_frameObjectsFor(this)) {
const win = _frameWindowFor(this._frameId);
@@ -5508,18 +5853,17 @@ class Element extends Node {
}
getAnimations() { return _animationsForTarget(this); }
remove() { if (this.parentNode) this.parentNode.removeChild(this); }
- append(...nodes) { for (const n of _convertNodes(nodes)) this.appendChild(n); }
+ append(...nodes) {
+ _preInsertConverted(this, nodes, this, () => null, "append");
+ }
prepend(...nodes) {
- const ref = this.firstChild;
- for (const n of _convertNodes(nodes)) {
- if (ref) this.insertBefore(n, ref); else this.appendChild(n);
- }
+ _preInsertConverted(this, nodes, this, () => this.firstChild, "prepend");
}
replaceChildren(...nodes) {
- const converted = _convertNodes(nodes);
- let c;
- while ((c = this.firstChild)) this.removeChild(c);
- for (const n of converted) this.appendChild(n);
+ const node = _convertNodesIntoNode(nodes, this);
+ const empty = node.nodeType === 11 && !node.firstChild;
+ _ensureInsertionValidity(this, node, null, "replaceChildren", false);
+ _replaceAllChildren(this, empty ? null : node, "replaceChildren");
}
}
@@ -5761,7 +6105,10 @@ class Document extends Node {
return Array.from(_waapiAnimations).filter(animation => animation.playState !== 'idle'
&& (animation.playState !== 'finished' || animation.effect?._timing.fill === 'forwards' || animation.effect?._timing.fill === 'both'));
}
- get documentElement() { return _wrapEl(+_dom("document_element")); }
+ get documentElement() {
+ if (this._detached) return _childNodeOfType(this, 1);
+ return _wrapEl(+_dom("document_element"));
+ }
get children() {
const root = this.documentElement;
return HTMLCollection._from(root ? [root] : []);
@@ -5772,16 +6119,27 @@ class Document extends Node {
get head() { return this.querySelector("head"); }
get body() { return this.querySelector("body"); }
get doctype() {
+ if (this._detached) return _childNodeOfType(this, 10);
if (this._doctype !== undefined) return this._doctype;
const info = _domParse("document_doctype");
if (info && info.name) {
- this._doctype = new DocumentType(info.nodeId, info.name, info.publicId || "", info.systemId || "");
+ const cached = _cache.get(info.nodeId);
+ this._doctype = cached instanceof DocumentType
+ ? cached
+ : new DocumentType(info.nodeId, info.name, info.publicId || "", info.systemId || "");
+ _cache.set(info.nodeId, this._doctype);
} else {
this._doctype = null;
}
return this._doctype;
}
- get title() { return _domParse("document_title") ?? ""; }
+ get title() {
+ if (this._detached) {
+ const title = this.querySelector("title");
+ return title ? title.textContent.replace(/[\t\n\f\r ]+/g, " ").trim() : "";
+ }
+ return _domParse("document_title") ?? "";
+ }
set title(v) {
const value = String(v);
let title = this.querySelector("title");
@@ -5799,6 +6157,7 @@ class Document extends Node {
title.textContent = value;
}
get URL() {
+ if (this._detached) return "about:blank";
const get = _documentRealmMember(this, 'URL');
return get ? Reflect.apply(get, this, []) : (_domParse("document_url") ?? "");
}
@@ -5825,10 +6184,14 @@ class Document extends Node {
// grant cross-document access.
this._effectiveDomain = candidate;
}
- get referrer() { return _domParse("document_referrer") ?? ""; }
- get location() { return globalThis.location; }
- set location(url) { __obscuraCore.ops.op_navigate(_resolveUrl(String(url)), 'GET', ''); }
+ get referrer() { return this._detached ? "" : (_domParse("document_referrer") ?? ""); }
+ get location() { return this._detached ? null : globalThis.location; }
+ set location(url) {
+ if (this._detached) return;
+ __obscuraCore.ops.op_navigate(_resolveUrl(String(url)), 'GET', '');
+ }
get defaultView() {
+ if (this._detached) return null;
const get = _documentRealmMember(this, 'defaultView');
return get ? Reflect.apply(get, this, []) : globalThis;
}
@@ -5844,7 +6207,7 @@ class Document extends Node {
// (HTTP Content-Type -> <meta charset>). characterSet/charset/inputEncoding
// are WHATWG aliases. A node-less document (DOMParser/createDocument) has no
// backing encoding and reports UTF-8.
- get characterSet() { return (this._nid === undefined || this._nid === null) ? "UTF-8" : _docEncoding(); }
+ get characterSet() { return (this._nid === undefined || this._nid === null || this._detached) ? "UTF-8" : _docEncoding(); }
get charset() { return this.characterSet; }
get inputEncoding() { return this.characterSet; }
get contentType() {
@@ -5875,6 +6238,7 @@ class Document extends Node {
return "text/html";
}
get readyState() {
+ if (this._detached) return 'complete';
const get = _documentRealmMember(this, 'readyState');
return get ? Reflect.apply(get, this, []) : (globalThis.__documentReadyState__ || 'complete');
}
@@ -5891,16 +6255,24 @@ class Document extends Node {
const method = _documentRealmMember(this, 'getElementById');
if (method) return Reflect.apply(method, this, [id]);
const needle = String(id);
- return needle === "" ? null : _wrapEl(+_dom("get_element_by_id", needle));
+ if (needle === "") return null;
+ if (this._detached) {
+ return this.querySelector('[id="' + needle.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"]');
+ }
+ return _wrapEl(+_dom("get_element_by_id", needle));
}
querySelector(s) {
const method = _documentRealmMember(this, 'querySelector');
- return method ? Reflect.apply(method, this, [s]) : _wrapEl(+_dom("query_selector", s));
+ if (method) return Reflect.apply(method, this, [s]);
+ if (this._detached) return _wrapEl(+_dom("query_selector_scoped", this._nid, s));
+ return _wrapEl(+_dom("query_selector", s));
}
querySelectorAll(s) {
const method = _documentRealmMember(this, 'querySelectorAll');
if (method) return Reflect.apply(method, this, [s]);
- const ids = _domParse("query_selector_all", s) || [];
+ const ids = (this._detached
+ ? _domParse("query_selector_all_scoped", this._nid, s)
+ : _domParse("query_selector_all", s)) || [];
return _nodeList(ids.map(_wrapEl).filter(Boolean));
}
getElementsByTagName(t) { return HTMLCollection._from(this.querySelectorAll(t)); }
@@ -5926,6 +6298,7 @@ class Document extends Node {
el._nullNamespaceAttrs = new Map();
_seedDetachedTreeState(el);
_cache.set(nid, el);
+ _stampNodeDocument(el, this);
if (el && localName === 'template') {
el._templateContent = this.createDocumentFragment();
el._templateContent._fragmentContext = 'template';
@@ -5959,21 +6332,21 @@ class Document extends Node {
el._nullNamespaceAttrs = new Map();
_seedDetachedTreeState(el);
_cache.set(nid, el);
- return el;
+ return _stampNodeDocument(el, this);
}
createTextNode(t) {
const nid = +_dom("create_text_node", String(t));
const n = new Text(nid);
_seedDetachedTreeState(n);
_cache.set(nid, n);
- return n;
+ return _stampNodeDocument(n, this);
}
createComment(t) {
const nid = +_dom("create_comment_node", String(t ?? ""));
const n = new Comment(nid);
_seedDetachedTreeState(n);
_cache.set(nid, n);
- return n;
+ return _stampNodeDocument(n, this);
}
createCDATASection(data) {
// Spec: throw NotSupportedError on an HTML document, reject data
@@ -5989,7 +6362,7 @@ class Document extends Node {
const n = new CDATASection(nid);
_seedDetachedTreeState(n);
_cache.set(nid, n);
- return n;
+ return _stampNodeDocument(n, this);
}
createProcessingInstruction(target, data) {
// Spec: not gated on document type. Reject targets that are not an XML
@@ -6006,14 +6379,14 @@ class Document extends Node {
const n = new ProcessingInstruction(nid, tgt);
_seedDetachedTreeState(n);
_cache.set(nid, n);
- return n;
+ return _stampNodeDocument(n, this);
}
createDocumentFragment() {
const nid = +_dom("create_document_fragment");
const frag = new DocumentFragment(nid);
_seedDetachedTreeState(frag);
_cache.set(nid, frag);
- return frag;
+ return _stampNodeDocument(frag, this);
}
// Legacy DOM Level 2 event factory. Spec returns an event of the requested
// class with an empty type until init*Event() is called. We previously
@@ -6051,7 +6424,11 @@ class Document extends Node {
}
return new Cls('');
}
- createRange() { return new Range(); }
+ createRange() {
+ const range = new Range();
+ if (this !== globalThis.document) { range._sc = this; range._ec = this; }
+ return range;
+ }
addEventListener(type, fn, opts) {
_eventTargetAdd(this, type, fn, opts);
}
@@ -6260,7 +6637,10 @@ class Document extends Node {
};
}
getSelection() { return this.defaultView ? _selectionFor(this) : null; }
- get activeElement() { return globalThis.__obscura_focused || this.body; }
+ get activeElement() {
+ if (this._detached) return this.body;
+ return globalThis.__obscura_focused || this.body;
+ }
// The element that scrolls the viewport, and where the page offset lives
// (issue #468). Standards mode, so documentElement — quirks mode would be
// body, but we never parse in quirks mode.
@@ -6275,30 +6655,30 @@ class Document extends Node {
// jQuery 3.x with it. Reuse the DOMParser path to build a detached
// document, then optionally set the title.
createHTMLDocument(title) {
- // Build head>title and body explicitly. Parsing a full skeleton string
- // as innerHTML of <html> collapses through the fragment parser (it
- // dropped head/body and kept only <title>), leaving doc.body null.
- const doc = new DOMParser().parseFromString("", "text/html");
- const root = doc.documentElement;
- const head = document.createElement("head");
- const titleEl = document.createElement("title");
- if (title != null) titleEl.textContent = String(title);
- head.appendChild(titleEl);
- const body = document.createElement("body");
- root.appendChild(head);
- root.appendChild(body);
+ const doc = _createDetachedDocument("text/html", false);
+ doc.appendChild(doc.implementation.createDocumentType("html", "", ""));
+ const html = doc.createElement("html");
+ doc.appendChild(html);
+ const head = doc.createElement("head");
+ html.appendChild(head);
+ if (title !== undefined) {
+ const titleEl = doc.createElement("title");
+ titleEl.appendChild(doc.createTextNode(String(title)));
+ head.appendChild(titleEl);
+ }
+ html.appendChild(doc.createElement("body"));
return doc;
},
- // Real spec: createDocument(namespaceURI, qualifiedName, doctype) →
- // an XML document with a root element of the given name. We don't
- // have a separate XML stack, so return a minimal detached document
- // with an element of the requested local name as documentElement.
- createDocument(_ns, qualifiedName, _doctype) {
- const name = (qualifiedName && String(qualifiedName)) || "root";
- const safe = name.replace(/[^a-zA-Z0-9-]/g, "");
- const html = qualifiedName ? `<${safe}></${safe}>` : "";
- const doc = new DOMParser().parseFromString(html, "application/xml");
- if (_doctype) doc._docType = _doctype;
+ createDocument(namespace, qualifiedName, doctype) {
+ const ns = namespace == null ? null : String(namespace);
+ const contentType = ns === "http://www.w3.org/1999/xhtml"
+ ? "application/xhtml+xml"
+ : (ns === "http://www.w3.org/2000/svg" ? "image/svg+xml" : "application/xml");
+ const doc = _createDetachedDocument(contentType, true);
+ const name = qualifiedName == null ? "" : String(qualifiedName);
+ const element = name === "" ? null : doc.createElementNS(ns, name);
+ if (doctype != null) doc.appendChild(doctype);
+ if (element) doc.appendChild(element);
return doc;
},
// createDocumentType(qualifiedName, publicId, systemId): build a detached
@@ -6311,13 +6691,14 @@ class Document extends Node {
throw new DOMException("The qualified name '" + name + "' contains an invalid character", "InvalidCharacterError");
}
const dt = new DocumentType(
- +_dom("create_comment_node", ""),
+ +_dom("create_doctype", name, publicId === undefined ? "" : String(publicId)),
name,
publicId === undefined ? "" : String(publicId),
systemId === undefined ? "" : String(systemId)
);
- dt._ownerDocument = ownerDoc;
- return dt;
+ _seedDetachedTreeState(dt);
+ _cache.set(dt._nid, dt);
+ return _stampNodeDocument(dt, ownerDoc);
},
hasFeature() { return true; },
};
@@ -6331,10 +6712,12 @@ class Document extends Node {
get links() { return this.querySelectorAll("a[href], area[href]"); }
get scripts() { return this.querySelectorAll("script"); }
get cookie() {
+ // A document without a browsing context is cookie-averse.
+ if (this._detached) return "";
return __obscuraCore.ops.op_get_cookies();
}
set cookie(v) {
- if (!v) return;
+ if (!v || this._detached) return;
__obscuraCore.ops.op_set_cookie(v);
}
// Inserts into the document's input stream, which the host keeps alive across calls.
@@ -6407,7 +6790,7 @@ class Document extends Node {
};
setTimeout(finishParsing, 0);
}
- hasFocus() { return true; }
+ hasFocus() { return !this._detached; }
queryCommandSupported(commandId) {
const method = _documentRealmMember(this, 'queryCommandSupported');
if (method) return Reflect.apply(method, this, arguments);
@@ -6488,7 +6871,7 @@ class DocumentFragment extends Node {
querySelector(s) { return _wrapEl(+_dom("query_selector_scoped", this._nid, s)); }
querySelectorAll(s) {
const ids = _domParse("query_selector_all_scoped", this._nid, s) || [];
- return _nodeList(ids.map(_wrapEl).filter(Boolean));
+ return _relevantNodeList(this, _nodeList(ids.map(_wrapEl).filter(Boolean)));
}
get children() {
const ids = _domParse("element_children", this._nid) || [];
@@ -6530,7 +6913,14 @@ class DocumentType extends Node {
get systemId() { return this._systemId; }
get nodeValue() { return null; }
set nodeValue(v) {}
- get ownerDocument() { return this._ownerDocument || globalThis.document; }
+ cloneNode() {
+ const clone = new DocumentType(
+ +_dom("create_doctype", this._name, this._publicId), this._name, this._publicId, this._systemId,
+ );
+ _seedDetachedTreeState(clone);
+ _cache.set(clone._nid, clone);
+ return _stampNodeDocument(clone, this.ownerDocument);
+ }
}
const _cache = new Map();
@@ -7139,6 +7529,9 @@ function _wrap(nid) {
else if (t === 3) n = new Text(nid);
else if (t === 8) n = new Comment(nid);
else if (t === 9) n = new Document(nid);
+ else if (t === 10) {
+ n = new DocumentType(nid, _domParse("doctype_name", nid) ?? "", _domParse("doctype_public_id", nid) ?? "", "");
+ }
else n = new Node(nid);
_cache.set(nid, n);
return n;
@@ -8521,16 +8914,27 @@ if (!Element.prototype.replaceWith) {
Element.prototype.replaceWith = function(...nodes) {
const parent = this.parentNode;
if (!parent) return;
- for (const n of _convertNodes(nodes)) parent.insertBefore(n, this);
- parent.removeChild(this);
+ const next = _viableSibling(this, nodes, "nextSibling");
+ const node = _convertNodesIntoNode(nodes, this);
+ if (this.parentNode === parent) _replaceChildNode(parent, node, this, "replaceWith");
+ else _preInsertNode(parent, node, next, "replaceWith");
};
_markNative(Element.prototype.replaceWith);
}
+// ChildNode before/after/replaceWith anchor on the first sibling that is not
+// itself being inserted.
+function _viableSibling(node, nodes, direction) {
+ let sibling = node[direction];
+ while (sibling && nodes.includes(sibling)) sibling = sibling[direction];
+ return sibling;
+}
if (!Element.prototype.before) {
Element.prototype.before = function(...nodes) {
const parent = this.parentNode;
if (!parent) return;
- for (const n of _convertNodes(nodes)) parent.insertBefore(n, this);
+ const previous = _viableSibling(this, nodes, "previousSibling");
+ _preInsertConverted(parent, nodes, this,
+ () => (previous ? previous.nextSibling : parent.firstChild), "before");
};
_markNative(Element.prototype.before);
}
@@ -8538,8 +8942,8 @@ if (!Element.prototype.after) {
Element.prototype.after = function(...nodes) {
const parent = this.parentNode;
if (!parent) return;
- const ref = this.nextSibling;
- for (const n of _convertNodes(nodes)) parent.insertBefore(n, ref);
+ const next = _viableSibling(this, nodes, "nextSibling");
+ _preInsertConverted(parent, nodes, this, () => next, "after");
};
_markNative(Element.prototype.after);
}
@@ -8549,6 +8953,23 @@ if (!Element.prototype.after) {
// These are the same implementations as Element.prototype — frameworks
// (Svelte 5, Vue, Lit) anchor on Comment/Text nodes and call these methods.
if (!CharacterData.prototype.before) CharacterData.prototype.before = Element.prototype.before;
+// The legacy alias Chromium still ships.
+if (!Element.prototype.webkitMatchesSelector) {
+ Element.prototype.webkitMatchesSelector = function webkitMatchesSelector(selectors) {
+ if (arguments.length === 0) {
+ const view = _frameViewOf(this);
+ throw new ((view && view.TypeError) || TypeError)(
+ "Failed to execute 'webkitMatchesSelector' on 'Element': 1 argument required, but only 0 present.");
+ }
+ return this.matches(selectors);
+ };
+ _markNative(Element.prototype.webkitMatchesSelector);
+}
+for (const name of ["before", "after", "replaceWith", "remove"]) {
+ if (!Object.prototype.hasOwnProperty.call(DocumentType.prototype, name)) {
+ DocumentType.prototype[name] = Element.prototype[name];
+ }
+}
if (!CharacterData.prototype.after) CharacterData.prototype.after = Element.prototype.after;
if (!CharacterData.prototype.replaceWith) CharacterData.prototype.replaceWith = Element.prototype.replaceWith;
if (!CharacterData.prototype.remove) CharacterData.prototype.remove = Element.prototype.remove;
@@ -8856,7 +9277,7 @@ globalThis.ResizeObserver = class ResizeObserver {
return new ResizeObserverEntry(_roConstructionKey, target, measurement);
});
this._active = [];
- try { this._callback(entries, this); } catch (_error) {}
+ try { this._callback.call(this, entries, this); } catch (_error) {}
}
observe(target, options = {}) {
if (!(target instanceof Element)) {
@@ -9305,16 +9726,21 @@ globalThis.getComputedStyle = (el, pseudo = '') => {
};
const target = style;
+ // An element outside any document has no computed style: every property
+ // reads "" and length is 0. Checked per read, as the declaration is live.
+ const detachedLookup = (name) => (_computedStyleHasNoDocument(el) ? '' : lookup(name));
return new Proxy(style, {
get(_, prop) {
if (prop === Symbol.toPrimitive || prop === Symbol.toStringTag) return undefined;
- if (prop === 'getPropertyValue') return (name) => lookup(name);
+ if (prop === 'getPropertyValue') return (name) => detachedLookup(name);
if (prop === 'getPropertyPriority') return () => '';
if (prop === 'item') return (i) => {
+ if (_computedStyleHasNoDocument(el)) return '';
refreshRendered();
return snapshot.names[i | 0] || '';
};
if (prop === 'length') {
+ if (_computedStyleHasNoDocument(el)) return 0;
refreshRendered();
return snapshot.names.length;
}
@@ -9328,14 +9754,25 @@ globalThis.getComputedStyle = (el, pseudo = '') => {
&& (_CSS_PROP_SET.has(prop)
|| _CSS_PROP_SET.has(_cssKebabToCamel(prop))
|| prop.includes('-'))) {
- return lookup(prop);
+ return detachedLookup(prop);
}
if (prop in target) return target[prop];
- if (typeof prop === 'string') return lookup(prop);
+ if (typeof prop === 'string') return detachedLookup(prop);
return undefined;
},
});
};
+// Chrome parity: only elements whose shadow-including root is not a document
+// lose their style. Iframe shim documents count as documents, and shadow
+// content of a connected host keeps its style even when it is not slotted.
+const _iframeDocumentRoots = new WeakSet();
+function _computedStyleHasNoDocument(el) {
+ if (!(el instanceof Node) || el.isConnected) return false;
+ const root = el.getRootNode({ composed: true });
+ if (!root) return true;
+ if (root.nodeType === 9) return root !== globalThis.document && !!root._detached;
+ return !_iframeDocumentRoots.has(root);
+}
// Returns the one Selection instance for a document (cached on the document),
// so window.getSelection() === document.getSelection(). The real Selection
// class is defined below, after Range. _selectionFor is hoisted.
@@ -9348,6 +9785,9 @@ globalThis.getSelection = _markNative(function getSelection() {
return _selectionFor(globalThis.document);
});
+// Rules whose text is derived from their state serialize through this
+// symbol-keyed method, so cssText stays a single CSSRule.prototype accessor.
+const _cssRuleSerializer = Symbol("cssText");
class CSSRule {
static STYLE_RULE = 1;
static CHARSET_RULE = 2;
@@ -9368,9 +9808,9 @@ class CSSRule {
this._parentRule = null;
}
get type() { return this._type; }
- get cssText() { return this._cssText; }
+ get cssText() { return this[_cssRuleSerializer] ? this[_cssRuleSerializer]() : this._cssText; }
set cssText(_value) {}
- get parentStyleSheet() { return this._parentStyleSheet; }
+ get parentStyleSheet() { return this._parentStyleSheet || this._parentRule?.parentStyleSheet || null; }
get parentRule() { return this._parentRule; }
}
for (const name of [
@@ -9404,7 +9844,8 @@ class CSSStyleRule extends CSSRule {
}
set cssText(_value) {}
_changed() {
- if (this._parentStyleSheet) this._parentStyleSheet._ruleChanged();
+ const sheet = this.parentStyleSheet;
+ if (sheet) sheet._ruleChanged();
}
}
@@ -9469,7 +9910,7 @@ function _splitTopLevelCssRules(value) {
function _cssRuleFromText(text) {
const trimmed = String(text || "").trim();
if (!trimmed) return null;
- if (trimmed[0] === "@") return new CSSRule(trimmed, 0);
+ if (trimmed[0] === "@") return _cssConditionRuleFromText(trimmed) || new CSSRule(trimmed, 0);
const open = trimmed.indexOf("{");
if (open <= 0 || !trimmed.endsWith("}")) return null;
const selector = trimmed.slice(0, open).trim();
@@ -9530,18 +9971,81 @@ class CSSGroupingRule extends CSSRule {
if (!parsed.valid || parsed.rules.length !== 1) throw new DOMException("The rule could not be parsed", "SyntaxError");
const child = _cssRuleFromText(parsed.rules[0]);
if (!child) throw new DOMException("The rule could not be parsed", "SyntaxError");
- child._parentStyleSheet = this.parentStyleSheet;
+ child._parentRule = this;
this._rules.splice(idx, 0, child);
- this.parentStyleSheet?._ruleChanged();
+ _groupingRuleChanged(this);
return idx;
}
deleteRule(index) {
const idx = Number(index) >>> 0;
if (idx >= this._rules.length) throw new DOMException("Rule index is out of range", "IndexSizeError");
- this._rules.splice(idx, 1);
- this.parentStyleSheet?._ruleChanged();
+ const [removed] = this._rules.splice(idx, 1);
+ if (removed) removed._parentRule = null;
+ _groupingRuleChanged(this);
}
}
+// A nested rule changes its top-level rule's text: replace that one rule in
+// the sheet, the same incremental path as CSSStyleSheet.insertRule.
+function _groupingRuleChanged(rule) {
+ let top = rule;
+ while (top._parentRule) top = top._parentRule;
+ const sheet = top.parentStyleSheet;
+ if (!sheet) return;
+ const index = sheet._rules.indexOf(top);
+ if (index < 0) sheet._ruleChanged();
+ else sheet._ruleChanged({ index, deleteCount: 1, rules: [top.cssText] });
+}
+
+// @media and @supports expose their nested rules; other at-rules stay opaque.
+class CSSConditionRule extends CSSGroupingRule {
+ constructor() {
+ super("", arguments[1]);
+ this._conditionText = arguments[0];
+ }
+ get conditionText() { return this._conditionText; }
+ [_cssRuleSerializer]() {
+ const keyword = this._type === CSSRule.MEDIA_RULE ? "@media" : "@supports";
+ const body = this._rules.map(rule => "\n " + rule.cssText).join("");
+ return `${keyword} ${this._conditionText} {${body}\n}`;
+ }
+}
+class CSSMediaRule extends CSSConditionRule {
+ get media() {
+ const text = this._conditionText;
+ const items = text ? text.split(",").map(item => item.trim()).filter(Boolean) : [];
+ return {
+ mediaText: text,
+ length: items.length,
+ item(index) { return items[index >>> 0] ?? null; },
+ toString() { return text; },
+ };
+ }
+}
+class CSSSupportsRule extends CSSConditionRule {}
+for (const RuleClass of [CSSRule, CSSStyleRule, CSSGroupingRule, CSSConditionRule, CSSMediaRule, CSSSupportsRule]) {
+ Object.defineProperty(RuleClass.prototype, Symbol.toStringTag, { value: RuleClass.name, configurable: true });
+}
+
+function _cssConditionRuleFromText(text) {
+ const match = /^@(media|supports)\b/i.exec(text);
+ if (!match) return null;
+ const open = text.indexOf("{");
+ if (open < 0 || !text.endsWith("}")) return null;
+ const prelude = text.slice(match[0].length, open).trim().replace(/\s+/g, " ");
+ const parsed = _splitTopLevelCssRules(text.slice(open + 1, -1));
+ if (!parsed.valid) return null;
+ const isMedia = match[1].toLowerCase() === "media";
+ const rule = isMedia
+ ? new CSSMediaRule(prelude, CSSRule.MEDIA_RULE)
+ : new CSSSupportsRule(prelude, CSSRule.SUPPORTS_RULE);
+ for (const childText of parsed.rules) {
+ const child = _cssRuleFromText(childText);
+ if (!child) return null;
+ child._parentRule = rule;
+ rule._rules.push(child);
+ }
+ return rule;
+}
class StyleSheet {
constructor() { this._disabled = false; }
@@ -9659,6 +10163,9 @@ class CSSStyleSheet extends StyleSheet {
}
_serializeText() { return this._rules.map(rule => rule.cssText).join("\n"); }
_ruleChanged(change) {
+ // A rule change restyles like a DOM mutation: computed-style snapshots
+ // taken before it must not be reused.
+ _domMutationEpoch++;
const state = _cssStyleSheetPrivate.get(this);
if (state?.linked && this._ownerNode) {
// ponytail: linked imports retain the existing whole-sheet write path;
@@ -9873,6 +10380,9 @@ Object.defineProperty(Element.prototype, "sheet", {
globalThis.CSSRule = CSSRule;
globalThis.CSSStyleRule = CSSStyleRule;
globalThis.CSSGroupingRule = CSSGroupingRule;
+globalThis.CSSConditionRule = CSSConditionRule;
+globalThis.CSSMediaRule = CSSMediaRule;
+globalThis.CSSSupportsRule = CSSSupportsRule;
globalThis.CSSRuleList = CSSRuleList;
globalThis.StyleSheet = StyleSheet;
globalThis.CSSStyleSheet = CSSStyleSheet;
@@ -9976,92 +10486,207 @@ Object.defineProperty(Document.prototype, 'adoptedStyleSheets', {
});
globalThis.__mutationObservers = [];
+// MutationRecord fields are prototype getters over internal state, as in
+// browsers; records are only built while an observer exists. Node lists and
+// sibling wrappers are materialized on first read.
+const _mutationRecordToken = Symbol("MutationRecord");
+function _recordNode(value) {
+ if (typeof value !== "number") return value || null;
+ return value < 0 ? null : _wrap(value);
+}
+globalThis.MutationRecord = class MutationRecord {
+ #d;
+ constructor() {
+ if (arguments[0] !== _mutationRecordToken) {
+ throw new TypeError("Failed to construct 'MutationRecord': Illegal constructor");
+ }
+ this.#d = arguments[1];
+ }
+ get type() { return this.#d.type; }
+ get target() { return this.#d.target; }
+ get addedNodes() {
+ const d = this.#d;
+ if (!(d.addedNodes instanceof NodeList)) d.addedNodes = _nodeList(d.addedNodes || []);
+ return d.addedNodes;
+ }
+ get removedNodes() {
+ const d = this.#d;
+ if (!(d.removedNodes instanceof NodeList)) d.removedNodes = _nodeList(d.removedNodes || []);
+ return d.removedNodes;
+ }
+ get previousSibling() { return _recordNode(this.#d.previousSibling); }
+ get nextSibling() { return _recordNode(this.#d.nextSibling); }
+ get attributeName() { return this.#d.attributeName ?? null; }
+ get attributeNamespace() { return this.#d.attributeNamespace ?? null; }
+ get oldValue() { return this.#d.oldValue; }
+};
+Object.defineProperty(MutationRecord.prototype, Symbol.toStringTag, { value: "MutationRecord", configurable: true });
+function _makeMutationRecord(type, target, init, includeOldValue) {
+ return new MutationRecord(_mutationRecordToken, {
+ type,
+ target,
+ addedNodes: init.addedNodes,
+ removedNodes: init.removedNodes,
+ previousSibling: init.previousSibling,
+ nextSibling: init.nextSibling,
+ attributeName: init.attributeName,
+ attributeNamespace: init.attributeNamespace,
+ oldValue: includeOldValue ? (init.oldValue ?? null) : null,
+ });
+}
+
+let _mutationObserverMicrotaskQueued = false;
+function _notifyMutationObservers() {
+ _mutationObserverMicrotaskQueued = false;
+ // Observers are notified in creation order; one callback per observer
+ // with every record queued since the last delivery.
+ const observers = _mutationObserverRegistry.slice();
+ for (const observer of observers) {
+ if (observer._records.length === 0) continue;
+ const records = observer._records.splice(0);
+ try { observer._callback.call(observer, records, observer); }
+ catch (e) { _reportMutationObserverError(e); }
+ }
+}
+function _reportMutationObserverError(error) {
+ try {
+ if (typeof globalThis.reportError === "function") globalThis.reportError(error);
+ else console.error(error);
+ } catch (e) { /* reporting must not stop delivery */ }
+}
+// Every observing MutationObserver in creation order, which is delivery order.
+const _mutationObserverRegistry = [];
+
globalThis.MutationObserver = class MutationObserver {
constructor(callback) {
+ if (typeof callback !== "function") {
+ throw new TypeError("Failed to construct 'MutationObserver': parameter 1 is not of type 'Function'.");
+ }
this._callback = callback;
this._targets = [];
this._records = [];
}
- observe(target, options) {
- this._targets.push({ target, options: options || {} });
+ observe(target, options = {}) {
+ if (!_isDomNode(target)) {
+ throw new TypeError("Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.");
+ }
+ const o = options == null ? {} : options;
+ const init = {
+ childList: !!o.childList,
+ subtree: !!o.subtree,
+ attributes: o.attributes === undefined ? undefined : !!o.attributes,
+ characterData: o.characterData === undefined ? undefined : !!o.characterData,
+ attributeOldValue: o.attributeOldValue === undefined ? undefined : !!o.attributeOldValue,
+ characterDataOldValue: o.characterDataOldValue === undefined ? undefined : !!o.characterDataOldValue,
+ attributeFilter: o.attributeFilter === undefined ? undefined : Array.from(o.attributeFilter, String),
+ };
+ if (init.attributes === undefined && (init.attributeOldValue !== undefined || init.attributeFilter !== undefined)) {
+ init.attributes = true;
+ }
+ if (init.characterData === undefined && init.characterDataOldValue !== undefined) init.characterData = true;
+ const fail = (message) => new TypeError("Failed to execute 'observe' on 'MutationObserver': " + message);
+ if (!init.childList && !init.attributes && !init.characterData) {
+ throw fail("The options object must set at least one of 'attributes', 'characterData', or 'childList' to true.");
+ }
+ if (init.attributeOldValue && !init.attributes) {
+ throw fail("The options object may only set 'attributeOldValue' to true when 'attributes' is true or not present.");
+ }
+ if (init.attributeFilter !== undefined && !init.attributes) {
+ throw fail("The options object may only set 'attributeFilter' when 'attributes' is true or not present.");
+ }
+ if (init.characterDataOldValue && !init.characterData) {
+ throw fail("The options object may only set 'characterDataOldValue' to true when 'characterData' is true or not present.");
+ }
+ init.attributes = !!init.attributes;
+ init.characterData = !!init.characterData;
+ const existing = this._targets.find(registration => registration.target === target);
+ if (existing) existing.options = init;
+ else this._targets.push({ target, options: init });
if (!globalThis.__mutationObservers.includes(this)) globalThis.__mutationObservers.push(this);
+ if (!_mutationObserverRegistry.includes(this)) _mutationObserverRegistry.push(this);
}
disconnect() {
this._targets = [];
+ this._records = [];
const idx = globalThis.__mutationObservers.indexOf(this);
if (idx >= 0) globalThis.__mutationObservers.splice(idx, 1);
+ const registered = _mutationObserverRegistry.indexOf(this);
+ if (registered >= 0) _mutationObserverRegistry.splice(registered, 1);
}
takeRecords() {
- const r = this._records.slice();
- this._records = [];
- return r;
- }
- _notify(records) {
- this._records.push(...records);
- Promise.resolve().then(() => {
- if (this._records.length > 0) {
- const batch = this._records.splice(0);
- try { this._callback(batch, this); } catch(e) { /* observer errors shouldn't propagate */ }
- }
- });
+ return this._records.splice(0);
+ }
+ _enqueue(record) {
+ this._records.push(record);
+ if (!_mutationObserverMicrotaskQueued) {
+ _mutationObserverMicrotaskQueued = true;
+ queueMicrotask(_notifyMutationObservers);
+ }
}
};
-globalThis.__notifyMutation = function(type, target_nid, addedNodes, removedNodes, attributeName, oldValue) {
+
+// "Queue a mutation record": find every observer registered on the target or,
+// with subtree, on one of its inclusive ancestors, and apply its filters.
+function _queueMutationRecord(type, target, init) {
+ const observers = globalThis.__mutationObservers;
+ if (!observers.length || !target) return;
+ for (const observer of observers) {
+ let matched = false;
+ let wantsOldValue = false;
+ for (const registration of observer._targets) {
+ const root = registration.target;
+ const options = registration.options;
+ if (!root) continue;
+ // Filter by record type first: the ancestry check is the costly part.
+ let oldValue = false;
+ if (type === "attributes") {
+ if (!options.attributes) continue;
+ if (options.attributeFilter
+ && (init.attributeNamespace != null || !options.attributeFilter.includes(init.attributeName))) continue;
+ oldValue = !!options.attributeOldValue;
+ } else if (type === "characterData") {
+ if (!options.characterData) continue;
+ oldValue = !!options.characterDataOldValue;
+ } else if (!options.childList) {
+ continue;
+ }
+ if (root !== target && root._nid !== target._nid) {
+ if (!options.subtree || !_isObservedAncestor(root, target)) continue;
+ }
+ if (oldValue) wantsOldValue = true;
+ matched = true;
+ }
+ if (matched) observer._enqueue(_makeMutationRecord(type, target, init, wantsOldValue));
+ }
+}
+// Subtree registrations match inclusive ancestors. One native bounded walk
+// replaces a JS parentNode walk per mutation; JS-only shadow parents keep it.
+function _isObservedAncestor(root, target) {
+ if (target._shadowParent || root._shadowParent) {
+ for (let cur = target.parentNode; cur; cur = cur.parentNode) if (cur === root) return true;
+ return false;
+ }
+ return _dom("is_inclusive_ancestor", root._nid, target._nid) === "true";
+}
+function _queueAttributeMutationRecord(target, localName, namespace, oldValue) {
+ _queueMutationRecord("attributes", target, { attributeName: localName, attributeNamespace: namespace, oldValue });
+}
+function _queueTreeMutationRecord(target, addedNodes, removedNodes, previousSibling, nextSibling) {
+ _queueMutationRecord("childList", target, { addedNodes, removedNodes, previousSibling, nextSibling });
+}
+// Node-id entry point kept for the native-backed callers (innerHTML,
+// attributes, character data).
+globalThis.__notifyMutation = function(type, target_nid, addedNodes, removedNodes, attributeName, oldValue, attributeNamespace) {
if (!globalThis.__mutationObservers.length) return;
- // Use `_wrap` (the canonical node-id → wrapper resolver) instead of a
- // direct cache poke. The previous code referenced `globalThis._cache`,
- // but `_cache` is a module-local Map — the lookup always returned
- // undefined, so the function silently bailed every time. Result: no
- // MutationObserver fired in obscura, ever, despite the call sites being
- // wired up at appendChild / setAttribute. _wrap also lazily creates a
- // wrapper for nodes that didn't have one yet (e.g. children parsed from
- // `set innerHTML`), which we need for record.target/added/removed.
const target = _wrap(target_nid);
if (!target) return;
- const record = {
- type: type, // 'childList', 'attributes', 'characterData'
- target: target,
+ _queueMutationRecord(type, target, {
addedNodes: (addedNodes || []).map(nid => _wrap(nid)).filter(Boolean),
removedNodes: (removedNodes || []).map(nid => _wrap(nid)).filter(Boolean),
- attributeName: attributeName || null,
+ attributeName: attributeName ?? null,
+ attributeNamespace: attributeNamespace ?? null,
oldValue: oldValue ?? null,
- previousSibling: null,
- nextSibling: null,
- };
- // Walk target → ancestors so a subtree-mode observer rooted at any
- // ancestor matches. The previous implementation just checked that
- // `target.contains` and `target.closest` were defined (always true on
- // any Element), so subtree=true silently behaved like subtree=false and
- // every nested mutation missed its subscriber.
- for (const obs of globalThis.__mutationObservers) {
- let matched = false;
- for (const t of obs._targets) {
- const root = t.target;
- if (!root) continue;
- // Filter by type per the observer options. Default behaviour matches
- // real MutationObserver: attribute mutations need options.attributes,
- // characterData mutations need options.characterData, childList
- // needs options.childList.
- const wantsType =
- (type === 'attributes' && t.options.attributes) ||
- (type === 'characterData' && t.options.characterData) ||
- (type === 'childList' && t.options.childList);
- if (!wantsType) continue;
- if (type === 'attributes' && t.options.attributeFilter !== undefined
- && !t.options.attributeFilter.includes(attributeName)) continue;
- if (root._nid === target_nid) { matched = true; break; }
- if (t.options.subtree) {
- // Walk parents until we hit the observed root or run off the tree.
- let cur = target.parentNode;
- while (cur) {
- if (cur._nid === root._nid) { matched = true; break; }
- cur = cur.parentNode;
- }
- if (matched) break;
- }
- }
- if (matched) obs._notify([record]);
- }
+ });
};
globalThis.ShadowRoot = class ShadowRoot extends DocumentFragment {
@@ -10092,37 +10717,17 @@ globalThis.ShadowRoot = class ShadowRoot extends DocumentFragment {
}
}
appendChild(child) {
+ _requireNodeArgument(child, "appendChild", 1);
this._assertInsertable(child, 'appendChild');
return super.appendChild(child);
}
insertBefore(node, reference) {
- if (reference && reference.parentNode !== this) {
- throw new DOMException(
- "Failed to execute 'insertBefore' on 'Node': The reference node is not a child of this node.",
- 'NotFoundError'
- );
- }
- if (node === reference) return node;
+ _requireNodeArgument(node, "insertBefore", 1);
this._assertInsertable(node, 'insertBefore');
- return super.insertBefore(node, reference);
- }
- removeChild(child) {
- if (!child || child.parentNode !== this) {
- throw new DOMException(
- "Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.",
- 'NotFoundError'
- );
- }
- return super.removeChild(child);
+ return super.insertBefore(...arguments);
}
replaceChild(node, oldChild) {
- if (!oldChild || oldChild.parentNode !== this) {
- throw new DOMException(
- "Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.",
- 'NotFoundError'
- );
- }
- if (node === oldChild) return oldChild;
+ _requireNodeArgument(node, "replaceChild", 1);
this._assertInsertable(node, 'replaceChild');
return super.replaceChild(node, oldChild);
}
@@ -10319,7 +10924,7 @@ function _scheduleIntersectionObserverDelivery(observer) {
for (const current of pending) {
if (!current._connected || !current._records.length) continue;
const records = current.takeRecords();
- try { current._callback(records, current); } catch (e) {}
+ try { current._callback.call(current, records, current); } catch (e) {}
}
}, _schedulerPriorityRank["user-visible"] * 2, documentGeneration, () => {
_intersectionDeliveryTaskPending = false;
@@ -10450,6 +11055,26 @@ function _ioElementPaddingBox(element, style, measurements) {
: element.clientHeight;
return _ioRect(rect.left + borderLeft, rect.top + borderTop, width, height);
}
+// Entry fields are prototype getters over internal state, as in browsers.
+const _ioEntryToken = Symbol("IntersectionObserverEntry");
+globalThis.IntersectionObserverEntry = class IntersectionObserverEntry {
+ #d;
+ constructor() {
+ if (arguments[0] !== _ioEntryToken) {
+ throw new TypeError("Failed to construct 'IntersectionObserverEntry': Illegal constructor");
+ }
+ this.#d = arguments[1];
+ }
+ get time() { return this.#d.time; }
+ get rootBounds() { return this.#d.rootBounds ?? null; }
+ get boundingClientRect() { return this.#d.boundingClientRect; }
+ get intersectionRect() { return this.#d.intersectionRect; }
+ get isIntersecting() { return !!this.#d.isIntersecting; }
+ get isVisible() { return !!this.#d.isVisible; }
+ get intersectionRatio() { return this.#d.intersectionRatio; }
+ get target() { return this.#d.target; }
+};
+Object.defineProperty(IntersectionObserverEntry.prototype, Symbol.toStringTag, { value: "IntersectionObserverEntry", configurable: true });
globalThis.IntersectionObserver = class IntersectionObserver {
constructor(callback, options) {
if (typeof callback !== "function") {
@@ -10558,17 +11183,21 @@ globalThis.IntersectionObserver = class IntersectionObserver {
const width = Math.max(0, right - left);
const height = Math.max(0, bottom - top);
const targetArea = Math.max(0, rect.width) * Math.max(0, rect.height);
- const isIntersecting = edgesTouch;
- const area = isIntersecting ? width * height : 0;
- return {
+ const area = edgesTouch ? width * height : 0;
+ const intersectionRatio = targetArea > 0 ? area / targetArea : (edgesTouch ? 1 : 0);
+ // As in Chromium, an entry below the first threshold is reported as not
+ // intersecting even when the boxes overlap.
+ const isIntersecting = edgesTouch && this._thresholdIndex(intersectionRatio) > 0;
+ return new IntersectionObserverEntry(_ioEntryToken, {
target,
isIntersecting,
- intersectionRatio: targetArea > 0 ? area / targetArea : (isIntersecting ? 1 : 0),
+ intersectionRatio,
boundingClientRect: _ioRect(rect.x, rect.y, rect.width, rect.height),
- intersectionRect: isIntersecting ? _ioRect(left, top, width, height) : _ioRect(0, 0, 0, 0),
- rootBounds: root,
+ intersectionRect: edgesTouch ? _ioRect(left, top, width, height) : _ioRect(0, 0, 0, 0),
+ // A target outside the root's tree is not measured against the root.
+ rootBounds: inRootTree ? root : _ioRect(0, 0, 0, 0),
time: performance.now(),
- };
+ });
}
_thresholdIndex(ratio) {
let index = 0;
@@ -10645,26 +11274,11 @@ globalThis.IntersectionObserver = class IntersectionObserver {
// rendering update and schedules both observer families.
globalThis.__obscura_recompute_intersections = _scheduleIntersectionRenderCheckpoint;
globalThis.addEventListener("resize", renderingUpdate);
- const wireUp = () => {
- if (!globalThis.document) return;
- // DOM writes synchronously mark ResizeObserver dirty through `_dom`; this
- // MutationObserver is only needed for intersection geometry. Scheduling RO
- // again here would escape its depth-bounded delivery cycle and allow a
- // self-resizing callback to create an infinite chain of zero-delay tasks.
- const observer = new MutationObserver(_scheduleIntersectionRenderCheckpoint);
- try {
- observer.observe(globalThis.document, {
- childList: true,
- subtree: true,
- attributes: true,
- characterData: true,
- });
- } catch {}
- };
- if (globalThis.document) wireUp();
- else Promise.resolve().then(wireUp);
+ // DOM mutations need no MutationObserver here: every mutating `_dom`
+ // command already schedules the intersection checkpoint synchronously. A
+ // document-wide observer would make every page build spec mutation records
+ // (siblings, old values) for every DOM write without reading them.
})();
-globalThis.IntersectionObserverEntry = class IntersectionObserverEntry {};
globalThis.DOMException = (function () {
const NAME_TO_CODE = {
@@ -11677,24 +12291,24 @@ globalThis.DOMParser = class DOMParser {
getElementsByName(n) {
return root.querySelectorAll(`[name="${n}"]`);
},
- createElement: (t) => document.createElement(t),
- createElementNS: (ns, t) => document.createElement(t),
- createTextNode: (t) => document.createTextNode(t),
- createComment: (t) => document.createComment(t),
- createDocumentFragment: () => document.createDocumentFragment(),
+ createElement: (t) => _stampNodeDocument(document.createElement(t), docNode),
+ createElementNS: (ns, t) => _stampNodeDocument(document.createElement(t), docNode),
+ createTextNode: (t) => _stampNodeDocument(document.createTextNode(t), docNode),
+ createComment: (t) => _stampNodeDocument(document.createComment(t), docNode),
+ createDocumentFragment: () => _stampNodeDocument(document.createDocumentFragment(), docNode),
createRange: () => new Range(),
createEvent: (type) => document.createEvent(type),
createCDATASection: (data) => {
if (mimeType === "text/html") throw new DOMException("createCDATASection is not supported in HTML documents", "NotSupportedError");
const s = String(data);
if (s.indexOf("]]>") !== -1) throw new DOMException("CDATA section data must not contain ']]>'", "InvalidCharacterError");
- return new CDATASection(+_dom("create_text_node", s));
+ return _stampNodeDocument(new CDATASection(+_dom("create_text_node", s)), docNode);
},
createProcessingInstruction: (target, data) => {
const t = String(target), s = String(data);
if (!_isValidPITarget(t)) throw new DOMException("Invalid processing instruction target", "InvalidCharacterError");
if (s.indexOf("?>") !== -1) throw new DOMException("Processing instruction data must not contain '?>'", "InvalidCharacterError");
- return new ProcessingInstruction(+_dom("create_text_node", s), t);
+ return _stampNodeDocument(new ProcessingInstruction(+_dom("create_text_node", s), t), docNode);
},
adoptNode: (n) => n,
importNode: (n) => n,
@@ -11705,6 +12319,7 @@ globalThis.DOMParser = class DOMParser {
removeChild: function (n) { try { root.removeChild(n); } catch (e) {} return n; },
insertBefore: function (n, ref) { try { root.insertBefore(n, ref); } catch (e) {} return n; },
_docType: null,
+ _documentShim: true,
get doctype() { return this._docType; },
cloneNode: function (deep) {
return new DOMParser().parseFromString(root.outerHTML, mimeType);
@@ -11712,6 +12327,9 @@ globalThis.DOMParser = class DOMParser {
contains(n) { return root.contains ? root.contains(n) : false; },
addEventListener() {}, removeEventListener() {}, dispatchEvent() { return true; },
};
+ // The parsed tree belongs to this document, not the main one.
+ _registerForeignDocument();
+ _stampNodeDocument(root, docNode);
_documentInstances.add(docNode);
return docNode;
}
@@ -13841,7 +14459,7 @@ function _rngOrder(a, b) {
function _rngCmp(nA, oA, nB, oB) {
if (_rngSame(nA, nB)) return oA < oB ? -1 : (oA > oB ? 1 : 0);
if (_rngOrder(nA, nB) > 0) return -_rngCmp(nB, oB, nA, oA);
- if (nA.contains && nA.contains(nB)) { // nA is a strict ancestor of nB
+ if (_dom("is_inclusive_ancestor", nA._nid, nB._nid) === "true") { // nA is a strict ancestor of nB
let child = nB;
while (child && child.parentNode && child.parentNode._nid !== nA._nid) child = child.parentNode;
if (child && child.parentNode && child.parentNode._nid === nA._nid && _rngNodeIndex(child) < oA) return 1;
@@ -13849,6 +14467,79 @@ function _rngCmp(nA, oA, nB, oB) {
}
return -1;
}
+function _rngIsCharacterData(n) {
+ const t = n.nodeType;
+ return t === 3 || t === 4 || t === 7 || t === 8;
+}
+// One native walk up from n; Node.contains enumerates a's whole subtree.
+function _rngIsInclusiveAncestor(a, n) {
+ return _rngSame(a, n) || _dom("is_inclusive_ancestor", a._nid, n._nid) === "true";
+}
+// A node is contained when all of it lies between the boundary points, and
+// partially contained when it is an inclusive ancestor of just one of them.
+function _rngContains(range, node) {
+ return _rngCmp(node, 0, range._sc, range._so) > 0
+ && _rngCmp(node, _rngNodeLength(node), range._ec, range._eo) < 0;
+}
+function _rngPartiallyContains(range, node) {
+ return _rngIsInclusiveAncestor(node, range._sc) !== _rngIsInclusiveAncestor(node, range._ec);
+}
+// Where extract/delete collapse the range: the start, or just after the
+// start's highest ancestor that does not contain the end.
+function _rngCollapsePoint(sc, so, ec) {
+ if (_rngIsInclusiveAncestor(sc, ec)) return [sc, so];
+ let reference = sc;
+ while (reference.parentNode && !_rngIsInclusiveAncestor(reference.parentNode, ec)) reference = reference.parentNode;
+ return [reference.parentNode, _rngNodeIndex(reference) + 1];
+}
+// The shared body of cloneContents (extract false) and extractContents.
+function _rngCopyContents(range, extract) {
+ const sc = range._sc, so = range._so, ec = range._ec, eo = range._eo;
+ const doc = sc.nodeType === 9 ? sc : (sc.ownerDocument || globalThis.document);
+ const fragment = doc.createDocumentFragment();
+ if (range.collapsed) return fragment;
+ if (_rngSame(sc, ec) && _rngIsCharacterData(sc)) {
+ const clone = sc.cloneNode(false);
+ clone.data = sc.data.substring(so, eo);
+ fragment.appendChild(clone);
+ if (extract) sc.replaceData(so, eo - so, "");
+ return fragment;
+ }
+ let common = sc;
+ while (!_rngIsInclusiveAncestor(common, ec)) common = common.parentNode;
+ const children = Array.from(common.childNodes);
+ const firstPartial = _rngIsInclusiveAncestor(sc, ec)
+ ? null : (children.find(c => _rngPartiallyContains(range, c)) || null);
+ const lastPartial = _rngIsInclusiveAncestor(ec, sc)
+ ? null : ([...children].reverse().find(c => _rngPartiallyContains(range, c)) || null);
+ const contained = children.filter(c => _rngContains(range, c));
+ if (contained.some(c => c.nodeType === 10)) {
+ throw new DOMException("The Range contains a DocumentType node.", "HierarchyRequestError");
+ }
+ const [newNode, newOffset] = extract ? _rngCollapsePoint(sc, so, ec) : [null, 0];
+ const copyPartial = (child, start, end) => {
+ if (_rngIsCharacterData(child)) {
+ const clone = child.cloneNode(false);
+ const from = start ? so : 0;
+ const to = start ? _rngNodeLength(child) : eo;
+ clone.data = child.data.substring(from, to);
+ fragment.appendChild(clone);
+ if (extract) child.replaceData(from, to - from, "");
+ return;
+ }
+ const clone = child.cloneNode(false);
+ fragment.appendChild(clone);
+ const sub = new Range();
+ if (start) { sub._sc = sc; sub._so = so; sub._ec = child; sub._eo = _rngNodeLength(child); }
+ else { sub._sc = child; sub._so = 0; sub._ec = ec; sub._eo = eo; }
+ clone.appendChild(_rngCopyContents(sub, extract));
+ };
+ if (firstPartial) copyPartial(firstPartial, true);
+ for (const child of contained) fragment.appendChild(extract ? child : child.cloneNode(true));
+ if (lastPartial) copyPartial(lastPartial, false);
+ if (extract) { range._sc = newNode; range._so = newOffset; range._ec = newNode; range._eo = newOffset; }
+ return fragment;
+}
function _rngCheckOffset(n, o) {
if (n && n.nodeType === 10) throw new DOMException("Range boundary cannot be a DocumentType", "InvalidNodeTypeError");
if (o < 0 || o > _rngNodeLength(n)) throw new DOMException("Range offset out of bounds", "IndexSizeError");
@@ -13963,11 +14654,93 @@ globalThis.Range = class Range {
if (!_rngSame(sc, ec) && (ec.nodeType === 3 || ec.nodeType === 4)) s += (ec.data || "").slice(0, this._eo);
return s;
}
- cloneContents() { return (globalThis.document || document).createDocumentFragment(); }
- extractContents() { return (globalThis.document || document).createDocumentFragment(); }
- deleteContents() {}
- insertNode(node) { if (node && this._sc && this._sc.insertBefore) { const kids = this._sc.childNodes; this._sc.insertBefore(node, kids[this._so] || null); } }
- surroundContents(node) { this.insertNode(node); }
+ cloneContents() { return _rngCopyContents(this, false); }
+ extractContents() { return _rngCopyContents(this, true); }
+ deleteContents() {
+ if (this.collapsed) return;
+ const sc = this._sc, so = this._so, ec = this._ec, eo = this._eo;
+ if (_rngSame(sc, ec) && _rngIsCharacterData(sc)) {
+ sc.replaceData(so, eo - so, "");
+ return;
+ }
+ // The contained nodes whose parent is not contained, in tree order, read
+ // off the two boundary paths instead of testing every node in the range.
+ const common = this.commonAncestorContainer;
+ const toRemove = [];
+ const childrenOf = (node) => Array.from(node.childNodes);
+ let startIndex = so;
+ if (!_rngSame(sc, common)) {
+ if (!_rngIsCharacterData(sc)) toRemove.push(...childrenOf(sc).slice(so));
+ let node = sc;
+ while (!_rngSame(node.parentNode, common)) {
+ for (let sibling = node.nextSibling; sibling; sibling = sibling.nextSibling) toRemove.push(sibling);
+ node = node.parentNode;
+ }
+ startIndex = _rngNodeIndex(node) + 1;
+ }
+ const endSide = [];
+ let endIndex = eo;
+ if (!_rngSame(ec, common)) {
+ if (!_rngIsCharacterData(ec)) endSide.push(childrenOf(ec).slice(0, eo));
+ let node = ec;
+ while (!_rngSame(node.parentNode, common)) {
+ const preceding = [];
+ for (let sibling = node.previousSibling; sibling; sibling = sibling.previousSibling) preceding.unshift(sibling);
+ endSide.push(preceding);
+ node = node.parentNode;
+ }
+ endIndex = _rngNodeIndex(node);
+ }
+ toRemove.push(...childrenOf(common).slice(startIndex, Math.max(startIndex, endIndex)));
+ for (let i = endSide.length - 1; i >= 0; i--) toRemove.push(...endSide[i]);
+ const [newNode, newOffset] = _rngCollapsePoint(sc, so, ec);
+ if (_rngIsCharacterData(sc)) sc.replaceData(so, _rngNodeLength(sc) - so, "");
+ for (const node of toRemove) {
+ const parent = node.parentNode;
+ if (parent) parent.removeChild(node);
+ }
+ if (_rngIsCharacterData(ec)) ec.replaceData(0, eo, "");
+ this._sc = newNode; this._so = newOffset; this._ec = newNode; this._eo = newOffset;
+ }
+ insertNode(node) {
+ _requireNodeArgument(node, "insertNode", 1, "Range");
+ const sc = this._sc;
+ const st = sc.nodeType;
+ if (st === 7 || st === 8 || ((st === 3 || st === 4) && !sc.parentNode) || _rngSame(sc, node)) {
+ throw new DOMException("Failed to execute 'insertNode' on 'Range': The node provided cannot be inserted here.", "HierarchyRequestError");
+ }
+ const startIsText = st === 3 || st === 4;
+ let reference = startIsText ? sc : (sc.childNodes[this._so] || null);
+ const parent = reference === null ? sc : reference.parentNode;
+ _ensureInsertionValidity(parent, node, reference, "insertNode", false);
+ if (startIsText) reference = sc.splitText(this._so);
+ if (reference === node) reference = node.nextSibling;
+ if (node.parentNode) node.parentNode.removeChild(node);
+ let newOffset = reference === null ? _rngNodeLength(parent) : _rngNodeIndex(reference);
+ newOffset += node.nodeType === 11 ? node.childNodes.length : 1;
+ const wasCollapsed = this.collapsed;
+ _preInsertNode(parent, node, reference, "insertNode");
+ if (wasCollapsed) { this._ec = parent; this._eo = newOffset; }
+ }
+ surroundContents(newParent) {
+ _requireNodeArgument(newParent, "surroundContents", 1, "Range");
+ const partial = (node) => node.nodeType !== 3 && _rngPartiallyContains(this, node);
+ for (let n = this._sc; n; n = n.parentNode) {
+ if (partial(n)) throw new DOMException("Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.", "InvalidStateError");
+ }
+ for (let n = this._ec; n; n = n.parentNode) {
+ if (partial(n)) throw new DOMException("Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.", "InvalidStateError");
+ }
+ const t = newParent.nodeType;
+ if (t === 9 || t === 10 || t === 11) {
+ throw new DOMException("Failed to execute 'surroundContents' on 'Range': The node provided is of an invalid type.", "InvalidNodeTypeError");
+ }
+ const fragment = this.extractContents();
+ if (newParent.firstChild) _replaceAllChildren(newParent, null, "surroundContents");
+ this.insertNode(newParent);
+ newParent.appendChild(fragment);
+ this.selectNode(newParent);
+ }
detach() {}
getBoundingClientRect() {
if (this.collapsed) return new DOMRect();
@@ -14090,11 +14863,12 @@ _markNative(globalThis.Selection);
Storage.prototype.removeItem, Storage.prototype.clear, Storage.prototype.key,
Notification, Notification.requestPermission,
window.chrome?.csi, window.chrome?.loadTimes,
- MutationObserver, ResizeObserver, IntersectionObserver, PerformanceObserver,
+ MutationObserver, MutationRecord, ResizeObserver, IntersectionObserver, PerformanceObserver,
XMLSerializer, XMLSerializer.prototype.serializeToString,
].forEach(fn => { if (typeof fn === 'function') _markNative(fn); });
class _IframeDocument {
+ get _documentShim() { return true; }
constructor(html, url, iframeEl) {
this._url = url;
this._iframeEl = iframeEl;
@@ -14109,6 +14883,9 @@ class _IframeDocument {
this._root = document.createElement('html');
this._head = document.createElement('head');
this._body = document.createElement('body');
+ _iframeDocumentRoots.add(this._root);
+ _registerForeignDocument();
+ _stampNodeDocument(this._root, this);
this._root.appendChild(this._head);
this._root.appendChild(this._body);
var bodyContent = html
@@ -14156,11 +14933,11 @@ class _IframeDocument {
getElementsByClassName(cls) {
return _getElementsByClassName(this._root, cls);
}
- createElement(tag) { return document.createElement(tag); }
- createElementNS(ns, tag) { return document.createElementNS(ns, tag); }
- createTextNode(text) { return document.createTextNode(text); }
- createComment(text) { return document.createComment(text); }
- createDocumentFragment() { return document.createDocumentFragment(); }
+ createElement(tag) { return _stampNodeDocument(document.createElement(tag), this); }
+ createElementNS(ns, tag) { return _stampNodeDocument(document.createElementNS(ns, tag), this); }
+ createTextNode(text) { return _stampNodeDocument(document.createTextNode(text), this); }
+ createComment(text) { return _stampNodeDocument(document.createComment(text), this); }
+ createDocumentFragment() { return _stampNodeDocument(document.createDocumentFragment(), this); }
createEvent(type) { return document.createEvent(type); }
createRange() { return new Range(); }
hasFocus() { return false; }
@@ -17017,7 +17794,15 @@ if (typeof URLPattern === 'undefined') {
}
if (typeof Document !== 'undefined' && !Document.prototype.importNode) {
- Document.prototype.importNode = function(node, deep) { return node?.cloneNode(!!deep) || null; };
+ Document.prototype.importNode = function(node) {
+ const deep = arguments[1];
+ _requireNodeArgument(node, "importNode", 1, "Document");
+ if (node.nodeType === 9 || node instanceof ShadowRoot) {
+ throw new DOMException("Failed to execute 'importNode' on 'Document': The node provided is a document, which may not be imported.", "NotSupportedError");
+ }
+ const clone = node.cloneNode(!!deep);
+ return _stampNodeDocument(clone, this);
+ };
}
// Document.adoptNode: standard DOM (HTML living spec). Frameworks that move
@@ -17026,7 +17811,19 @@ if (typeof Document !== 'undefined' && !Document.prototype.importNode) {
// transfer ownership from, the node is already ours, so return it as-is,
// matching the observable effect of adoption into this document.
if (typeof Document !== 'undefined' && !Document.prototype.adoptNode) {
- Document.prototype.adoptNode = function(node) { return node || null; };
+ Document.prototype.adoptNode = function(node) {
+ _requireNodeArgument(node, "adoptNode", 1, "Document");
+ if (node.nodeType === 9) {
+ throw new DOMException("Failed to execute 'adoptNode' on 'Document': The node provided is a document, which may not be adopted.", "NotSupportedError");
+ }
+ if (node instanceof ShadowRoot) {
+ throw new DOMException("Failed to execute 'adoptNode' on 'Document': The node provided is a shadow root, which may not be adopted.", "HierarchyRequestError");
+ }
+ const parent = node.parentNode;
+ if (parent) parent.removeChild(node);
+ if (node._nodeDocument !== undefined) node._nodeDocument = undefined;
+ return _stampNodeDocument(node, this);
+ };
}
// Element.toggleAttribute: standard DOM. Lit/Stencil and several ad SDKs call
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index a64a7726..e6f9e22c 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -3093,6 +3093,35 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
.contains(&NodeId::new(other))
.to_string()
}
+ // arg1 is an inclusive ancestor of arg2 through ordinary parents.
+ "is_inclusive_ancestor" => {
+ let (Ok(ancestor), Ok(node)) = (arg1.parse::<u32>(), arg2.parse::<u32>()) else {
+ return "false".into();
+ };
+ dom.is_inclusive_ancestor(NodeId::new(ancestor), NodeId::new(node))
+ .to_string()
+ }
+ // "previous,next" sibling ids of arg1, -1 for none: one crossing for
+ // the pair a mutation record captures.
+ "sibling_nids" => {
+ let Ok(nid) = arg1.parse::<u32>() else {
+ return "-1,-1".into();
+ };
+ let (prev, next) = dom
+ .with_node(NodeId::new(nid), |node| (node.prev_sibling, node.next_sibling))
+ .unwrap_or((None, None));
+ let id = |value: Option<NodeId>| value.map_or(-1, |id| id.index() as i64);
+ format!("{},{}", id(prev), id(next))
+ }
+ // arg1 is a host-including inclusive ancestor of arg2. Walks up from
+ // arg2 instead of enumerating arg1's descendants.
+ "is_host_including_inclusive_ancestor" => {
+ let (Ok(ancestor), Ok(node)) = (arg1.parse::<u32>(), arg2.parse::<u32>()) else {
+ return "false".into();
+ };
+ dom.is_host_including_inclusive_ancestor(NodeId::new(ancestor), NodeId::new(node))
+ .to_string()
+ }
// Connectivity is maintained incrementally by DomTree. Exposing the
// cached bit avoids an ancestor op crossing for every level when JS
// builds a deep detached subtree.
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 2c353943..11627f34 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -7642,6 +7642,523 @@ mod tests {
);
}
+ #[test]
+ fn replacement_script_runs_after_the_old_child_is_removed_without_observers() {
+ let mut rt = setup_runtime("<!doctype html><body><span id=old>old</span></body>");
+ let result = rt.evaluate(r#"(() => {
+ const old = document.getElementById('old');
+ const script = document.createElement('script');
+ script.textContent = "globalThis.oldPresentDuringReplacement = document.getElementById('old') !== null";
+ const removed = document.body.replaceChild(script, old);
+ return [oldPresentDuringReplacement, removed === old, old.parentNode === null];
+ })()"#).unwrap();
+ assert_eq!(result, serde_json::json!([false, true, true]));
+ }
+
+ #[test]
+ fn pre_insertion_validity_checks_arguments_and_order() {
+ let mut rt = setup_runtime("<!DOCTYPE html><html><body><p id='log'></p></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const name = (fn) => {
+ try { fn(); return "none"; }
+ catch (error) { return error instanceof TypeError ? "TypeError" : error.name; }
+ };
+ const body = document.body;
+ const text = document.createTextNode("t");
+ const a = document.createElement("a");
+ const b = document.createElement("b");
+ const c = document.createElement("i");
+ a.appendChild(b);
+ const doc = document.implementation.createHTMLDocument("title");
+ const doctype = document.implementation.createDocumentType("html", "", "");
+ return [
+ name(() => body.insertBefore(null, null)),
+ name(() => body.insertBefore(text)),
+ name(() => body.insertBefore(text, {})),
+ name(() => body.appendChild({})),
+ name(() => body.removeChild(null)),
+ name(() => body.replaceChild(text, null)),
+ name(() => text.insertBefore(document.createTextNode("x"), null)),
+ name(() => text.appendChild(text)),
+ name(() => b.insertBefore(a, c)),
+ name(() => b.insertBefore(text, c)),
+ name(() => a.insertBefore(doc, null)),
+ name(() => a.insertBefore(doctype, null)),
+ name(() => doc.insertBefore(doc.createTextNode("x"), doc.documentElement)),
+ name(() => doc.appendChild(doc.createElement("x"))),
+ name(() => doc.insertBefore(doctype, null)),
+ Array.from(doc.childNodes, n => n.nodeType),
+ doc.doctype === doc.firstChild,
+ body.insertBefore(text, undefined) === text,
+ body.lastChild === text,
+ document.doctype === document.firstChild,
+ Node.prototype.insertBefore.length,
+ Node.prototype.appendChild.length
+ ];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ "TypeError", "TypeError", "TypeError", "TypeError", "TypeError", "TypeError",
+ "HierarchyRequestError", "HierarchyRequestError", "HierarchyRequestError",
+ "NotFoundError", "HierarchyRequestError", "HierarchyRequestError",
+ "HierarchyRequestError", "HierarchyRequestError", "HierarchyRequestError",
+ [10, 1], true, true, true, true, 2, 1
+ ])
+ );
+ }
+
+ #[test]
+ fn document_child_constraints_follow_dom_order() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const name = (fn) => { try { fn(); return "none"; } catch (error) { return error.name; } };
+ const doc = document.implementation.createHTMLDocument("t");
+ const comment = doc.insertBefore(doc.createComment("c"), doc.firstChild);
+ const root = doc.documentElement;
+ doc.removeChild(root);
+ const afterRemove = Array.from(doc.childNodes, n => n.nodeType);
+ const fragment = doc.createDocumentFragment();
+ fragment.appendChild(doc.createElement("a"));
+ const beforeDoctype = name(() => doc.insertBefore(fragment, doc.doctype));
+ const beforeComment = name(() => doc.insertBefore(fragment, comment));
+ const appended = name(() => doc.appendChild(fragment));
+ const two = doc.createDocumentFragment();
+ two.append(doc.createElement("x"), doc.createElement("y"));
+ const replacedDoctype = name(() => doc.replaceChild(doc.createElement("z"), doc.doctype));
+ return [
+ afterRemove, beforeDoctype, beforeComment, appended,
+ doc.documentElement.localName, name(() => doc.appendChild(two)),
+ replacedDoctype
+ ];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ [8, 10], "HierarchyRequestError", "HierarchyRequestError", "none", "a",
+ "HierarchyRequestError", "HierarchyRequestError"
+ ])
+ );
+ }
+
+ #[test]
+ fn child_list_records_match_the_dom_mutation_algorithms() {
+ let mut rt = setup_runtime("<html><body><div id='p'><a></a><b></b><i></i></div><div id='q'><u></u></div></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const p = document.getElementById("p");
+ const q = document.getElementById("q");
+ const [a, b, i] = Array.from(p.childNodes);
+ const u = q.firstChild;
+ const observer = new MutationObserver(() => {});
+ observer.observe(p, { childList: true, attributes: true, characterData: true, subtree: true });
+ const describe = (records) => records.map(r => [
+ r.type,
+ r.target.id || r.target.nodeName,
+ Array.from(r.addedNodes, n => n.nodeName),
+ Array.from(r.removedNodes, n => n.nodeName),
+ r.previousSibling && r.previousSibling.nodeName,
+ r.nextSibling && r.nextSibling.nodeName,
+ r.attributeName,
+ r.attributeNamespace,
+ r.oldValue
+ ]);
+ const out = {};
+ p.insertBefore(b, a);
+ out.moveWithin = describe(observer.takeRecords());
+ const fragment = document.createDocumentFragment();
+ fragment.append(document.createElement("x"), document.createElement("y"));
+ p.appendChild(fragment);
+ out.fragment = describe(observer.takeRecords());
+ p.replaceChild(u, i);
+ out.replaceFromOtherParent = describe(observer.takeRecords());
+ p.replaceChild(a, a);
+ out.replaceSelf = describe(observer.takeRecords());
+ const e = document.createElement("em");
+ e.textContent = "";
+ p.appendChild(e);
+ observer.takeRecords();
+ e.textContent = "";
+ out.emptyTextContent = describe(observer.takeRecords());
+ e.append("one", "two");
+ out.appendTwo = describe(observer.takeRecords());
+ e.normalize();
+ out.normalize = describe(observer.takeRecords());
+ e.setAttribute("title", "x");
+ e.setAttribute("title", "y");
+ e.removeAttribute("title");
+ out.attributes = describe(observer.takeRecords());
+ out.recordType = [
+ typeof MutationRecord,
+ (() => { p.appendChild(document.createElement("s")); return observer.takeRecords()[0] instanceof MutationRecord; })(),
+ Object.keys((() => { p.appendChild(document.createElement("s")); return observer.takeRecords()[0]; })()).length
+ ];
+ out.options = [
+ (() => { try { observer.observe(p, {}); return "none"; } catch (error) { return error.constructor.name; } })(),
+ (() => { try { observer.observe(p, { attributeOldValue: true, attributes: false }); return "none"; } catch (error) { return error.constructor.name; } })()
+ ];
+ return out;
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "moveWithin": [
+ ["childList", "p", [], ["B"], "A", "I", null, null, null],
+ ["childList", "p", ["B"], [], null, "A", null, null, null]
+ ],
+ "fragment": [["childList", "p", ["X", "Y"], [], "I", null, null, null, null]],
+ "replaceFromOtherParent": [["childList", "p", ["U"], ["I"], "A", "X", null, null, null]],
+ "replaceSelf": [
+ ["childList", "p", [], ["A"], "B", "U", null, null, null],
+ ["childList", "p", ["A"], [], "B", "U", null, null, null]
+ ],
+ "emptyTextContent": [],
+ "appendTwo": [["childList", "EM", ["#text", "#text"], [], null, null, null, null, null]],
+ "normalize": [
+ ["characterData", "#text", [], [], null, null, null, null, null],
+ ["childList", "EM", [], ["#text"], "#text", null, null, null, null]
+ ],
+ "attributes": [
+ ["attributes", "EM", [], [], null, null, "title", null, null],
+ ["attributes", "EM", [], [], null, null, "title", null, null],
+ ["attributes", "EM", [], [], null, null, "title", null, null]
+ ],
+ "recordType": ["function", true, 0],
+ "options": ["TypeError", "TypeError"]
+ })
+ );
+ }
+
+ #[test]
+ fn parent_node_insertion_of_several_nodes_is_one_mutation() {
+ let mut rt = setup_runtime("<html><body><div id='p'><i id='first'></i></div><div id='q'><u></u></div></body></html>");
+ let result = rt
+ .evaluate(
+ r#"(() => {
+ const p = document.getElementById("p");
+ const q = document.getElementById("q");
+ const first = document.getElementById("first");
+ const observer = new MutationObserver(() => {});
+ observer.observe(document.body, { childList: true, subtree: true });
+ const describe = (records) => records.map(r => [
+ r.target.id, Array.from(r.addedNodes, n => n.nodeName), Array.from(r.removedNodes, n => n.nodeName),
+ r.previousSibling && r.previousSibling.nodeName, r.nextSibling && r.nextSibling.nodeName
+ ]);
+ const a = document.createElement("a");
+ p.append(a, "t", q.firstChild);
+ const appended = describe(observer.takeRecords());
+ const b = document.createElement("b");
+ p.prepend(b, "s");
+ const prepended = describe(observer.takeRecords());
+ first.after(first, "x");
+ const withSelf = describe(observer.takeRecords());
+ const errors = [];
+ try { p.append(document.createElement("em"), document.body); } catch (e) { errors.push(e.name); }
+ return [appended, prepended, withSelf, errors, Array.from(p.childNodes, n => n.nodeName)];
+ })()"#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ [["q", [], ["U"], null, null], ["p", ["A", "#text", "U"], [], "I", null]],
+ [["p", ["B", "#text"], [], null, "I"]],
+ [["p", [], ["I"], "#text", "A"], ["p", ["I", "#text"], [], "#text", "A"]],
+ ["HierarchyRequestError"],
+ ["B", "#text", "I", "#text", "A", "#text", "U"]
+ ])
+ );
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn mutation_observer_old_values_and_callback_this() {
+ let mut rt = setup_runtime("<html><body><p id='p' title='a'>text</p></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const p = document.getElementById("p");
+ const observer = new MutationObserver(() => {});
+ observer.observe(p, { attributeOldValue: true, characterDataOldValue: true, subtree: true, attributeFilter: ["title"] });
+ p.setAttribute("title", "b");
+ p.setAttribute("lang", "en");
+ p.firstChild.data = "changed";
+ const records = observer.takeRecords().map(r => [r.type, r.attributeName, r.oldValue]);
+ let seenThis = null;
+ const callbackObserver = new MutationObserver(function (list, obs) {
+ seenThis = [this === callbackObserver, obs === callbackObserver, arguments.length, Array.isArray(list)];
+ });
+ callbackObserver.observe(p, { childList: true });
+ p.appendChild(document.createElement("span"));
+ globalThis.__callbackThis = () => seenThis;
+ return records;
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([["attributes", "title", "a"], ["characterData", null, "text"]])
+ );
+ rt.run_event_loop_bounded(100).await.unwrap();
+ assert_eq!(
+ rt.evaluate("__callbackThis()").unwrap(),
+ serde_json::json!([true, true, 2, true])
+ );
+ }
+
+ #[test]
+ fn range_mutations_move_nodes_and_queue_records() {
+ let mut rt = setup_runtime("<html><body><div id='d'><b>bold</b><i>ital</i><u>under</u></div></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const d = document.getElementById("d");
+ const [b, i, u] = Array.from(d.children);
+ const observer = new MutationObserver(() => {});
+ observer.observe(d, { childList: true, characterData: true, subtree: true });
+ const range = document.createRange();
+ range.setStart(b.firstChild, 2);
+ range.setEnd(u.firstChild, 3);
+ const cloned = range.cloneContents();
+ const clonedText = Array.from(cloned.childNodes, n => n.textContent);
+ const unchanged = d.textContent;
+ observer.takeRecords();
+ const extracted = range.extractContents();
+ const extractedText = Array.from(extracted.childNodes, n => [n.nodeName, n.textContent]);
+ const afterExtract = [d.innerHTML, range.startContainer === d, range.startOffset, range.collapsed];
+ const extractRecords = observer.takeRecords().map(r => [r.type, Array.from(r.removedNodes, n => n.nodeName)]);
+ const insertRange = document.createRange();
+ insertRange.setStart(d, 1);
+ insertRange.collapse(true);
+ const marker = document.createElement("mark");
+ insertRange.insertNode(marker);
+ const afterInsert = [d.innerHTML, insertRange.endContainer === d, insertRange.endOffset];
+ const surround = document.createRange();
+ surround.selectNode(marker);
+ const wrapper = document.createElement("span");
+ surround.surroundContents(wrapper);
+ const deleteRange = document.createRange();
+ deleteRange.selectNodeContents(d);
+ deleteRange.deleteContents();
+ return [clonedText, unchanged, extractedText, afterExtract, extractRecords, afterInsert, marker.parentNode === wrapper, d.childNodes.length];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ ["ld", "ital", "und"],
+ "bolditalunder",
+ [["B", "ld"], ["I", "ital"], ["U", "und"]],
+ ["<b>bo</b><u>er</u>", true, 1, true],
+ [["characterData", []], ["childList", ["I"]], ["characterData", []]],
+ ["<b>bo</b><mark></mark><u>er</u>", true, 2],
+ true,
+ 0
+ ])
+ );
+ }
+
+ #[test]
+ fn node_document_follows_the_creating_document_and_adoption() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const doc = document.implementation.createHTMLDocument();
+ const el = doc.createElement("p");
+ const text = doc.createTextNode("t");
+ const created = [el.ownerDocument === doc, text.ownerDocument === doc, doc.ownerDocument, doc.title, !!doc.body, doc.defaultView];
+ doc.body.appendChild(el);
+ el.innerHTML = "<span>parsed</span>";
+ const parsed = el.firstChild;
+ const inTree = [el.ownerDocument === doc, parsed.ownerDocument === doc, doc.querySelector("span") === parsed, document.querySelector("span")];
+ doc.body.removeChild(el);
+ const removed = [el.ownerDocument === doc, parsed.ownerDocument === doc];
+ document.body.appendChild(el);
+ const adopted = [el.ownerDocument === document, parsed.ownerDocument === document, el.isConnected];
+ document.body.removeChild(el);
+ const leftMain = el.ownerDocument === document;
+ const imported = doc.importNode(document.createElement("q"), true);
+ const adoptedNode = doc.adoptNode(el);
+ const xml = document.implementation.createDocument(null, "root", null);
+ const parser = new DOMParser().parseFromString("<p>x</p>", "text/html");
+ return [
+ created, inTree, removed, adopted, leftMain,
+ imported.ownerDocument === doc, adoptedNode.ownerDocument === doc,
+ xml instanceof XMLDocument, xml.documentElement.localName, xml.contentType,
+ xml.documentElement.ownerDocument === xml,
+ parser.querySelector("p").ownerDocument === parser,
+ document.createElement("div").ownerDocument === document,
+ document.documentElement.ownerDocument === document
+ ];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ [true, true, null, "", true, null],
+ [true, true, true, null],
+ [true, true],
+ [true, true, true],
+ true,
+ true, true,
+ true, "root", "application/xml",
+ true, true, true, true
+ ])
+ );
+ }
+
+ #[test]
+ fn mutation_errors_use_the_dom_exception_of_the_node_frame() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"(() => {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ const doc = child.document;
+ const caught = (fn) => { try { fn(); return null; } catch (error) { return error; } };
+ const out = [];
+ for (const make of [
+ () => doc.createElement("a"),
+ () => doc.createTextNode("t"),
+ () => doc.createComment("c"),
+ ]) {
+ const node = make();
+ doc.body.appendChild(node);
+ const error = caught(() => node.removeChild(doc));
+ out.push([
+ node.ownerDocument === doc,
+ error && error.name,
+ error && error.constructor === child.DOMException,
+ error && error.constructor === DOMException,
+ ]);
+ }
+ const local = caught(() => document.body.removeChild(document.createElement("p")));
+ out.push([local.name, local.constructor === DOMException, local.constructor === child.DOMException]);
+ return [child.DOMException !== DOMException, out];
+ })()"#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ true,
+ [
+ [true, "NotFoundError", true, false],
+ [true, "NotFoundError", true, false],
+ [true, "NotFoundError", true, false],
+ ["NotFoundError", true, false]
+ ]
+ ])
+ );
+ }
+
+ #[test]
+ fn media_rules_expose_nested_rules_and_accept_insert_rule() {
+ let mut rt = setup_runtime("<html><head><style id='s'>#t { color: black; } @media all { #t { color: blue; } }</style></head><body><div id='t'></div></body></html>");
+ let result = rt
+ .evaluate(
+ r##"
+ const sheet = document.getElementById("s").sheet;
+ const media = sheet.cssRules[1];
+ const before = [media instanceof CSSMediaRule, media instanceof CSSGroupingRule, media.type, media.conditionText, media.cssRules.length];
+ const index = media.insertRule("#t { color: red; }", 1);
+ const inserted = [index, media.cssRules.length, media.cssRules[1].parentRule === media, media.cssRules[1].parentStyleSheet === sheet];
+ media.deleteRule(1);
+ return [before, inserted, media.cssRules.length, typeof CSSSupportsRule];
+ "##,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([[true, true, 4, "all", 1], [1, 2, true, true], 1, "function"])
+ );
+ }
+
+ #[test]
+ fn new_dom_interfaces_have_browser_shapes() {
+ let mut rt = setup_runtime("<html><head><style id='s'>@media all { p { color: red } }</style></head><body></body></html>");
+ let result = rt
+ .evaluate(
+ r##"(() => {
+ const caught = (fn) => { try { fn(); return "none"; } catch (e) { return e.message; } };
+ const observer = new MutationObserver(() => {});
+ const div = document.createElement("div");
+ observer.observe(div, { childList: true });
+ div.appendChild(document.createElement("i"));
+ const record = observer.takeRecords()[0];
+ const media = document.getElementById("s").sheet.cssRules[0];
+ return [
+ Object.prototype.toString.call(record),
+ Object.prototype.toString.call(media),
+ caught(() => new MutationRecord()),
+ caught(() => new IntersectionObserverEntry({})),
+ [MutationRecord.length, IntersectionObserverEntry.length, CSSConditionRule.length, CSSMediaRule.length],
+ ["MutationRecord", "IntersectionObserverEntry", "CSSMediaRule", "XMLDocument"]
+ .map(name => Object.getOwnPropertyDescriptor(globalThis, name).enumerable),
+ Object.getOwnPropertyNames(CSSConditionRule.prototype).sort(),
+ media.cssText,
+ Document.prototype.importNode.length
+ ];
+ })()"##,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ "[object MutationRecord]",
+ "[object CSSMediaRule]",
+ "Failed to construct 'MutationRecord': Illegal constructor",
+ "Failed to construct 'IntersectionObserverEntry': Illegal constructor",
+ [0, 0, 0, 0],
+ [false, false, false, false],
+ ["conditionText", "constructor"],
+ "@media all {\n p { color: red; }\n}",
+ 1
+ ])
+ );
+ }
+
+ #[test]
+ fn computed_style_is_empty_outside_a_document() {
+ let mut rt = setup_runtime("<html><body><div id='c' style='color: red'></div></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const detached = document.createElement("div");
+ detached.style.color = "red";
+ const style = getComputedStyle(detached);
+ const empty = [style.length, style.color, style.getPropertyValue("color"), style.display];
+ document.body.appendChild(detached);
+ const live = style.color !== "";
+ const host = document.createElement("div");
+ const shadow = host.attachShadow({ mode: "open" });
+ shadow.innerHTML = "<p id='in'></p>";
+ const inDetachedShadow = getComputedStyle(shadow.getElementById("in")).display;
+ return [empty, live, inDetachedShadow, typeof getComputedStyle(document.getElementById("c")).color];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([[0, "", "", ""], true, "", "string"])
+ );
+ }
+
#[test]
fn shadow_root_identity_and_children_are_native_tree_backed() {
let mut rt = setup_runtime("<html><body></body></html>");
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rs
index 66665224..7f0f21c5 100644
--- a/crates/obscura-render/src/dom.rs
+++ b/crates/obscura-render/src/dom.rs
@@ -13333,7 +13333,12 @@ fn build(
// the CSS tie-break. Taffy has no CSS `order` style field, so feeding
// it the correctly ordered item sequence is the missing translation.
dom_children.sort_by_key(|cid| styles.get(cid).map(|style| style.order).unwrap_or(0));
- } else if style.display == crate::Display::Block {
+ } else if style.display == crate::Display::Block
+ || (style.display == crate::Display::Inline && style.is_inline_block && !has_inline_ish_content)
+ {
+ // An inline-block's inner display is flow-root, so the same applies
+ // to formatting whitespace around its block children.
+ //
// Formatting whitespace between block lines does not generate an
// inline line box. Keeping a zero-height taffy leaf here still breaks
// sibling margin adjacency, turning `margin-bottom:30px` followed by
@@ -13472,6 +13477,21 @@ fn build(
taffy_style.align_items = Some(taffy::AlignItems::FLEX_START);
}
+ // An inline-block is a flow-root inside. With only block-level in-flow
+ // children there is no inline formatting context to emulate, so its
+ // children stack and stretch as in a block instead of sharing a row.
+ if style.display == crate::Display::Inline
+ && style.is_inline_block
+ && !has_inline_ish_content
+ && !native_float_band
+ && !has_float_child
+ && dom_children
+ .iter()
+ .any(|cid| styles.get(cid).is_some_and(is_in_flow_block_level))
+ {
+ taffy_style.display = taffy::style::Display::Block;
+ }
+
if native_float_band {
// Native float placement is only selected for the guarded flat-band
// shape. It requires a real block formatting context on the parent.
diff --git a/crates/obscura-render/tests/layout_test.rs b/crates/obscura-render/tests/layout_test.rs
index 8c6b962d..d013b833 100644
--- a/crates/obscura-render/tests/layout_test.rs
+++ b/crates/obscura-render/tests/layout_test.rs
@@ -2006,6 +2006,28 @@ fn inline_block_flex_items_keep_block_inner_flow() {
);
}
+#[test]
+fn inline_block_block_children_stack_and_shrink_to_the_widest_child() {
+ let tree = parse_html(include_str!("../../../render-repros/inline-block-block-children.html"));
+ let layout = layout_dom(&tree, (300.0, 200.0));
+ let rect = |id| layout.rects[&tree.get_element_by_id(id).unwrap()];
+ for (id, expected) in [
+ ("plain", (0.0, 0.0, 144.0, 74.0)),
+ ("plain-one", (12.0, 12.0, 80.0, 20.0)),
+ ("plain-two", (12.0, 32.0, 120.0, 30.0)),
+ ("margins", (0.0, 74.0, 144.0, 89.0)),
+ ("margin-one", (12.0, 86.0, 80.0, 20.0)),
+ ("margin-two", (12.0, 121.0, 120.0, 30.0)),
+ ] {
+ let actual = rect(id);
+ assert!((actual.x - expected.0).abs() < 0.01
+ && (actual.y - expected.1).abs() < 0.01
+ && (actual.width - expected.2).abs() < 0.01
+ && (actual.height - expected.3).abs() < 0.01,
+ "{id}: {actual:?}, expected {expected:?}");
+ }
+}
+
#[test]
fn percentage_height_under_indefinite_parent_uses_content_height() {
let tree = parse_html(include_str!(
diff --git a/render-repros/checks.json b/render-repros/checks.json
index befb9190..f9d0f93e 100644
--- a/render-repros/checks.json
+++ b/render-repros/checks.json
@@ -1,4 +1,10 @@
{
+ "inline-block-block-children": [
+ {"name": "first block keeps its authored width", "color": "#d02020", "x": 12, "y": 12, "width": 80, "height": 20},
+ {"name": "second block stacks without formatting whitespace", "color": "#2050d0", "x": 12, "y": 32, "width": 120, "height": 30},
+ {"name": "inline-block starts the next outer line", "color": "#087f5b", "x": 12, "y": 86, "width": 80, "height": 20},
+ {"name": "sibling block margins collapse within the flow root", "color": "#7048e8", "x": 12, "y": 121, "width": 120, "height": 30}
+ ],
"emulated-color-scheme": [
{"name": "default light preference keeps the green block", "color": "#00aa00", "x": 0, "y": 0, "width": 240, "height": 100}
],
diff --git a/render-repros/inline-block-block-children.html b/render-repros/inline-block-block-children.html
new file mode 100644
index 00000000..f05dad5c
--- /dev/null
+++ b/render-repros/inline-block-block-children.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<meta charset="utf-8">
+<style>
+body { margin:0 }
+.row { line-height:0 }
+.panel { display:inline-block; padding:10px; border:2px solid #000; vertical-align:top }
+.one { width:80px; height:20px; background:#d02020 }
+.two { width:120px; height:30px; background:#2050d0 }
+#margins .one { margin-bottom:10px; background:#087f5b }
+#margins .two { margin-top:15px; background:#7048e8 }
+</style>
+<div class=row><span class=panel id=plain>
+ <div class=one id=plain-one></div>
+ <div class=two id=plain-two></div>
+</span></div>
+<div class=row><span class=panel id=margins>
+ <div class=one id=margin-one></div>
+ <div class=two id=margin-two></div>
+</span></div>