Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(cssom): convert adopted stylesheet assignments through WebIDL sequences
ldm0b63c6aacae52
diff --git a/moli-renderer-v8/src/native_bridge/document/css_state/accessors.rs b/moli-renderer-v8/src/native_bridge/document/css_state/accessors.rsindex 46ccbb2c6..9f7c9f691 100644--- a/moli-renderer-v8/src/native_bridge/document/css_state/accessors.rs+++ b/moli-renderer-v8/src/native_bridge/document/css_state/accessors.rs@@ -193,18 +193,28 @@ pub(in crate::native_bridge) fn normalize_adopted_style_sheets_assignment<'s>(owner: AdoptedStyleSheetsArrayOwner,target_document: Option<DomHandle>,) -> Option<v8::Local<'s, v8::Array>> {- let array = if value.is_null_or_undefined() {- v8::Array::new(scope, 0)- } else {- let Ok(array) = v8::Local::<v8::Array>::try_from(value) else {- webidl::throw_type_error(- scope,- "DocumentOrShadowRoot.adoptedStyleSheets must be an array.",- );+ let options = webidl::InterfaceOptions {+ name: crate::web_api_interfaces::CSSStyleSheet::NAME,+ brand_check: crate::web_api_interfaces::CSSStyleSheet::is_instance,+ };+ let sheets = match webidl::convert_with_options::<webidl::Sequence<webidl::InterfaceObject>>(+ scope,+ value,+ webidl::Context::member("DocumentOrShadowRoot", "adoptedStyleSheets"),+ &options,+ ) {+ Ok(sheets) => sheets,+ Err(error) => {+ webidl::throw_error(scope, &error);return None;- };- array+ }};+ let values = sheets+ .0+ .into_iter()+ .map(|sheet| sheet.0.into())+ .collect::<Vec<_>>();+ let array = v8::Array::new_with_elements(scope, &values);if !validate_adopted_style_sheet_array(scope, array, target_document) {return None;}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/adopted_style_sheets.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/adopted_style_sheets.rsnew file mode 100644index 000000000..7a406597f--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/adopted_style_sheets.rs@@ -0,0 +1,22 @@+use super::*;++#[test]+fn adopted_stylesheet_setters_convert_iterables_and_preserve_conversion_exceptions() {+ let mut vm = new_parsed_test_vm(+ "https://adopted-stylesheet-iterables.test/",+ "<!doctype html><iframe id=child></iframe>",+ );+ let result = vm+ .eval(include_str!(+ "../../../../tests/fixtures/adopted-style-sheets-iterables.js"+ ))+ .expect("adopted stylesheet conversion matrix should complete");+ assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "180");+ assert_eq!(+ result,+ "true",+ "{}",+ vm.eval("JSON.stringify(__uiEventResults.rows.filter(row => !row.passed))")+ .unwrap(),+ );+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rsindex 5c354693b..d2fea50bb 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs@@ -3,6 +3,7 @@ use super::*;mod abort_controller_receivers;mod abort_signal_events;mod abort_signal_statics;+mod adopted_style_sheets;mod bar_prop;mod broadcast_channel;mod chrome;diff --git a/moli-renderer-v8/tests/fixtures/adopted-style-sheets-iterables.js b/moli-renderer-v8/tests/fixtures/adopted-style-sheets-iterables.jsnew file mode 100644index 000000000..f1d0ee8d1--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/adopted-style-sheets-iterables.js@@ -0,0 +1,102 @@+(() => {+ const rows = [];+ const realms = [['top', globalThis], ['child', document.querySelector('#child').contentWindow]];+ function check(name, body) {+ try {rows.push({name, passed: body() === true});}+ catch (error) {rows.push({name, passed: false, error: String(error)});}+ }+ function throws(realm, name, body) {+ try {body(); return false;}+ catch (error) {return name === 'TypeError' ? Object.getPrototypeOf(error) === realm.TypeError.prototype :+ Object.getPrototypeOf(error) === realm.DOMException.prototype && error.name === name;}+ }+ for (const [calleeName, callee] of realms) for (const [ownerName, owner] of realms)+ for (const kind of ['Document', 'ShadowRoot']) {+ const doc = owner.document, host = doc.body.appendChild(doc.createElement('div'));+ const receiver = kind === 'Document' ? doc : host.attachShadow({mode: 'open'});+ const descriptor = Object.getOwnPropertyDescriptor(callee[kind].prototype, 'adoptedStyleSheets');+ const get = () => descriptor.get.call(receiver), set = value => descriptor.set.call(receiver, value);+ const a = new owner.CSSStyleSheet(), b = new owner.CSSStyleSheet();+ const label = `${calleeName} setter ${ownerName} ${kind}`;+ try {+ check(`${label} accepts a Set preserving native sheet order`, () => {+ set(new Set([a, b]));return get().length === 2 && get()[0] === a && get()[1] === b;+ });+ check(`${label} accepts a generator`, () => {+ set((function*() {yield b; yield a;})());return get().length === 2 && get()[0] === b && get()[1] === a;+ });+ check(`${label} reads an array's iterator instead of its indexed elements`, () => {+ const input = [a]; let calls = 0;+ Object.defineProperty(input, 0, {get() {throw Error('ignored array index');}});+ input[Symbol.iterator] = function*() {calls++; yield b;};+ set(input);return calls === 1 && get().length === 1 && get()[0] === b;+ });+ check(`${label} owns an array copy without installing methods on the input`, () => {+ const input = new owner.Array(a);set(input);+ input.push(b);+ return get() !== input && get().length === 1 && get()[0] === a &&+ input.push === owner.Array.prototype.push && !Object.hasOwn(input, 'push');+ });+ for (const [name, value] of [['undefined', undefined], ['null', null], ['number', 3],+ ['string', 'x'], ['array-like', {0: a, length: 1}]])+ check(`${label} rejects ${name}`, () => throws(callee, 'TypeError', () => set(value)));+ for (const part of ['iterator getter', 'iterator call', 'next', 'done', 'value'])+ check(`${label} preserves ${part} exception identity and previous state`, () => {+ set([a]); const previous = get(), sentinel = {};let calls = 0;+ const input = {get [Symbol.iterator]() {+ if (part === 'iterator getter') {calls++; throw sentinel;}+ return function() {+ if (part === 'iterator call') {calls++; throw sentinel;}+ return {next() {+ if (part === 'next') {calls++; throw sentinel;}+ return {get done() {if (part === 'done') {calls++; throw sentinel;}return false;},+ get value() {calls++; throw sentinel;}};+ }};+ };+ }};+ try {set(input);return false;}+ catch (error) {return error === sentinel && calls === 1 && get() === previous && get()[0] === a;}+ });+ for (const badKind of ['object', 'prototype', 'inherited', 'proxy', 'revoked'])+ check(`${label} rejects ${badKind} sheet during conversion without traps or IteratorClose`, () => {+ let traps = 0, steps = 0, closes = 0;+ const revoked = Proxy.revocable(a, {});revoked.revoke();+ const bad = badKind === 'object' ? {} : badKind === 'prototype' ? Object.create(owner.CSSStyleSheet.prototype) :+ badKind === 'inherited' ? Object.create(a) : badKind === 'revoked' ? revoked.proxy :+ new Proxy(a, {get() {traps++;throw 1;}, getPrototypeOf() {traps++;throw 1;}});+ const input = {[Symbol.iterator]() {return {next() {steps++;return {value: bad, done: false};},+ return() {closes++;return {};}};}};+ return throws(callee, 'TypeError', () => set(input)) && traps === 0 && steps === 1 && closes === 0;+ });+ check(`${label} rejects a non-constructed sheet`, () => {+ const style = doc.head.appendChild(doc.createElement('style'));+ try {return throws(callee, 'NotAllowedError', () => set([style.sheet]));}+ finally {style.remove();}+ });+ check(`${label} rejects a constructed sheet from another document`, () => {+ const other = owner === globalThis ? realms[1][1] : globalThis;+ return throws(callee, 'NotAllowedError', () => set([new other.CSSStyleSheet()]));+ });+ } finally {set([]);host.remove();}+ }+ // The genuine-receiver conversion cases moved here from the ShadowRoot matrix.+ for (const [calleeName, callee] of realms) for (const [ownerName, owner] of realms)+ for (const flavor of ['live', 'html', 'xml']) {+ const doc = flavor === 'live' ? owner.document : flavor === 'html' ?+ owner.document.implementation.createHTMLDocument('shadow') :+ owner.document.implementation.createDocument(null, 'r');+ const host = doc.createElementNS('http://www.w3.org/1999/xhtml', 'div');+ (doc.body || doc.documentElement).appendChild(host);+ const root = host.attachShadow({mode: 'open'});+ check(`${calleeName} binding ${ownerName} ${flavor} adoptedStyleSheets setter preserves iterator exception identity`, () => {+ const sentinel = {};let conversions = 0;+ try {Object.getOwnPropertyDescriptor(callee.ShadowRoot.prototype, 'adoptedStyleSheets').set.call(root,+ {get [Symbol.iterator]() {conversions++;throw sentinel;}});return false;}+ catch (error) {return error === sentinel && conversions === 1;}+ });+ host.remove();+ }+ globalThis.__uiEventResults = {complete: true, total: rows.length,+ passed: rows.filter(row => row.passed).length, rows};+ return rows.every(row => row.passed);+})()