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(performance): convert measure arguments in Web IDL order
ldm00f0bedce8672
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rsindex 1e676e8de..039d7e761 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs@@ -38,9 +38,15 @@ struct PerformanceClearMarksArgs {#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Performance.measure")]-struct PerformanceMeasureArgs {+struct PerformanceMeasureArgs<'s> {#[webidl(required)]name: String,+ #[webidl(+ converter = "raw",+ default = MeasureStartOrOptions::Dictionary(PerformanceMeasureOptions::default())+ )]+ start_or_options: MeasureStartOrOptions<'s>,+ end_mark: Option<String>,}#[derive(Default, webidl::WebIdlDictionary)]@@ -51,9 +57,14 @@ struct PerformanceMeasureOptions<'s> {#[webidl(converter = "double")]duration: Option<f64>,#[webidl(converter = "raw")]- end: Option<v8::Local<'s, v8::Value>>,+ end: Option<MeasureBoundary>,#[webidl(converter = "raw")]- start: Option<v8::Local<'s, v8::Value>>,+ start: Option<MeasureBoundary>,+}++enum MeasureStartOrOptions<'s> {+ Mark(String),+ Dictionary(PerformanceMeasureOptions<'s>),}enum MeasureBoundary {@@ -61,6 +72,44 @@ enum MeasureBoundary {Timestamp(f64),}+impl<'s> webidl::WebIdlConverter<'s> for MeasureStartOrOptions<'s> {+ type Options = ();++ fn convert(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: webidl::Context,+ _options: &Self::Options,+ ) -> Result<Self, webidl::WebIdlError> {+ if value.is_object() || value.is_null_or_undefined() {+ webidl::parse_dictionary::<PerformanceMeasureOptions>(scope, value, context)+ .map(|options| Self::Dictionary(options.unwrap_or_default()))+ } else {+ webidl::convert::<webidl::DomString>(scope, value, context)+ .map(|name| Self::Mark(name.0))+ }+ }+}++impl<'s> webidl::WebIdlConverter<'s> for MeasureBoundary {+ type Options = ();++ fn convert(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: webidl::Context,+ _options: &Self::Options,+ ) -> Result<Self, webidl::WebIdlError> {+ if value.is_number() {+ webidl::convert::<webidl::Double>(scope, value, context)+ .map(|time| Self::Timestamp(time.0))+ } else {+ webidl::convert::<webidl::DomString>(scope, value, context)+ .map(|name| Self::Mark(name.0))+ }+ }+}+struct ParsedPerformanceMeasure<'s> {start: Option<MeasureBoundary>,duration: Option<f64>,@@ -257,7 +306,9 @@ pub(in crate::context_bootstrap) fn performance_measure_callback<'s>(let Some(parsed) = webidl::parse_args::<PerformanceMeasureArgs>(scope, &args) else {return;};- let Some(parsed_measure) = parse_performance_measure_arguments(scope, &args) else {+ let Some(parsed_measure) =+ prepare_performance_measure(scope, parsed.start_or_options, parsed.end_mark)+ else {return;};let start = match parsed_measure.start.as_ref() {@@ -339,157 +390,66 @@ pub(in crate::context_bootstrap) fn performance_clear_measures_callback<'s>(rv.set_undefined();}-fn parse_performance_measure_arguments<'s>(+fn prepare_performance_measure<'s>(scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,+ start_or_options: MeasureStartOrOptions<'s>,+ end_mark: Option<String>,) -> Option<ParsedPerformanceMeasure<'s>> {- let second = (args.length() > 1).then(|| args.get(1));- let options = second- .filter(|value| !webidl::is_nullish(*value) && value.is_object())- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok());-- if let Some(options) = options {- let options =- match webidl::parse_dictionary_object::<PerformanceMeasureOptions>(scope, options) {- Ok(options) => options,- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- };- let end = match options.end {- Some(end) => match parse_measure_boundary_value(- scope,- end,- webidl::Context::member("PerformanceMeasureOptions", "end"),- ) {- Ok(end) => Some(end),- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- },- None => None,- };- let start = match options.start {- Some(start) => match parse_measure_boundary_value(- scope,- start,- webidl::Context::member("PerformanceMeasureOptions", "start"),- ) {- Ok(start) => Some(start),- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- },- None => None,- };- let legacy_end = parse_optional_legacy_end(scope, args)?;- let non_empty = options.detail.is_some()- || options.duration.is_some()- || start.is_some()- || end.is_some();- if !non_empty {+ let options = match start_or_options {+ MeasureStartOrOptions::Dictionary(options) => options,+ MeasureStartOrOptions::Mark(start) => {return Some(ParsedPerformanceMeasure {- start: None,+ start: Some(MeasureBoundary::Mark(start)),duration: None,- end: legacy_end.map(MeasureBoundary::Mark),+ end: end_mark.map(MeasureBoundary::Mark),detail: None,});}- if legacy_end.is_some() {- webidl::throw_type_error(- scope,- "If a non-empty PerformanceMeasureOptions object was passed, endMark must not be passed.",- );- return None;- }- if start.is_none() && end.is_none() {- webidl::throw_type_error(- scope,- "A non-empty PerformanceMeasureOptions object must contain start or end.",- );- return None;- }- if start.is_some() && options.duration.is_some() && end.is_some() {- webidl::throw_type_error(- scope,- "PerformanceMeasureOptions must not define start, duration, and end together.",- );- return None;- }+ };+ let PerformanceMeasureOptions {+ detail,+ duration,+ end,+ start,+ } = options;+ let non_empty = detail.is_some() || duration.is_some() || start.is_some() || end.is_some();+ if !non_empty {return Some(ParsedPerformanceMeasure {- start,- duration: options.duration,- end,- detail: options.detail,+ start: None,+ duration: None,+ end: end_mark.map(MeasureBoundary::Mark),+ detail: None,});}-- let start = match second.filter(|value| !webidl::is_nullish(*value)) {- Some(start) => match parse_dom_string(+ if end_mark.is_some() {+ webidl::throw_type_error(scope,- start,- webidl::Context::argument("Performance.measure", 2),- ) {- Ok(start) => Some(MeasureBoundary::Mark(start)),- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- },- None => None,- };- let end = parse_optional_legacy_end(scope, args)?.map(MeasureBoundary::Mark);+ "If a non-empty PerformanceMeasureOptions object was passed, endMark must not be passed.",+ );+ return None;+ }+ if start.is_none() && end.is_none() {+ webidl::throw_type_error(+ scope,+ "A non-empty PerformanceMeasureOptions object must contain start or end.",+ );+ return None;+ }+ if start.is_some() && duration.is_some() && end.is_some() {+ webidl::throw_type_error(+ scope,+ "PerformanceMeasureOptions must not define start, duration, and end together.",+ );+ return None;+ }Some(ParsedPerformanceMeasure {start,- duration: None,+ duration,end,- detail: None,+ detail,})}-fn parse_optional_legacy_end<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,-) -> Option<Option<String>> {- if args.length() <= 2 || webidl::is_nullish(args.get(2)) {- return Some(None);- }- match parse_dom_string(- scope,- args.get(2),- webidl::Context::argument("Performance.measure", 3),- ) {- Ok(end) => Some(Some(end)),- Err(error) => {- webidl::throw_error(scope, &error);- None- }- }-}--fn parse_dom_string<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,- context: webidl::Context,-) -> Result<String, webidl::WebIdlError> {- webidl::convert::<webidl::DomString>(scope, value, context).map(Into::into)-}--fn parse_measure_boundary_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,- context: webidl::Context,-) -> Result<MeasureBoundary, webidl::WebIdlError> {- if value.is_number() {- return webidl::convert::<webidl::Double>(scope, value, context)- .map(|value| MeasureBoundary::Timestamp(value.0));- }- parse_dom_string(scope, value, context).map(MeasureBoundary::Mark)-}-fn resolve_measure_boundary<'s>(scope: &mut v8::PinScope<'s, '_>,performance: v8::Local<'s, v8::Object>,diff --git a/moli-renderer-v8/src/script_vm/tests/performance_user_timing.rs b/moli-renderer-v8/src/script_vm/tests/performance_user_timing.rsindex c12aaf076..35d77cd41 100644--- a/moli-renderer-v8/src/script_vm/tests/performance_user_timing.rs+++ b/moli-renderer-v8/src/script_vm/tests/performance_user_timing.rs@@ -22,3 +22,26 @@ fn user_timing_implicit_timestamps_share_the_performance_now_clock() {assert_eq!(result["total"], 400);assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");}++#[test]+fn performance_measure_converts_arguments_and_members_in_webidl_order() {+ let mut vm = new_storage_page_task_executor_test_vm("https://measure-conversion.test/");+ let source = format!(+ r#"(() => {{+ const probe = {};+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ try {{+ const realms = [globalThis, frame.contentWindow];+ const checks = [];+ for (const owner of realms) for (const callee of realms)+ checks.push(...probe(owner, callee));+ return JSON.stringify({{total: checks.length, failures: checks.filter(row => !row.passed)}});+ }} finally {{ frame.remove(); }}+ }})()"#,+ include_str!("../../../tests/fixtures/user-timing-measure-conversion.js"),+ );+ let result: serde_json::Value = serde_json::from_str(&vm.eval(&source).unwrap()).unwrap();+ assert_eq!(result["total"], 128);+ assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");+}diff --git a/moli-renderer-v8/src/worker/thread/tests/performance_user_timing.rs b/moli-renderer-v8/src/worker/thread/tests/performance_user_timing.rsindex 8f14da8e5..36f46a54d 100644--- a/moli-renderer-v8/src/worker/thread/tests/performance_user_timing.rs+++ b/moli-renderer-v8/src/worker/thread/tests/performance_user_timing.rs@@ -21,3 +21,23 @@ async fn worker_user_timing_implicit_timestamps_share_the_performance_now_clock(assert_eq!(result["total"], 200);assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");}++#[tokio::test]+async fn worker_performance_measure_converts_arguments_and_members_in_webidl_order() {+ ensure_v8();+ let source = format!(+ r#"const probe = {};+ const checks = probe();+ postMessage({{total: checks.length, failures: checks.filter(row => !row.passed)}});+ close();"#,+ include_str!("../../../../tests/fixtures/user-timing-measure-conversion.js"),+ );+ let mut worker = spawn_worker(source, "test://measure_conversion_order".into());+ let message = timeout(TIMEOUT, worker.recv())+ .await+ .expect("timed out")+ .expect("channel closed");+ let result: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();+ assert_eq!(result["total"], 32);+ assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");+}diff --git a/moli-renderer-v8/tests/fixtures/user-timing-measure-conversion.js b/moli-renderer-v8/tests/fixtures/user-timing-measure-conversion.jsnew file mode 100644index 000000000..4e86bfb5e--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/user-timing-measure-conversion.js@@ -0,0 +1,193 @@+(owner = globalThis, callee = owner) => {+ const checks = [];+ const performance = owner.performance;+ const method = callee.Performance.prototype.measure;+ const mark = owner.Performance.prototype.mark.bind(performance);+ const entries = owner.Performance.prototype.getEntriesByType.bind(performance);+ const prefix = '__measureConversion:';+ const names = new Set();+ let next = 0;+ const measure = (...args) => {+ if (typeof args[0] === 'string') names.add(args[0]);+ return Reflect.apply(method, performance, args);+ };+ const name = () => prefix + next++;+ const assert = (passed, message) => { if (!passed) throw Error(message); };+ const equal = (actual, expected) => assert(JSON.stringify(actual) === JSON.stringify(expected),+ JSON.stringify({actual, expected}));+ const capture = callback => { try { callback(); } catch (error) { return error; } };+ const test = (label, callback) => {+ try { callback(); checks.push({name: label, passed: true}); }+ catch (error) { checks.push({name: label, passed: false, details: String(error.stack || error)}); }+ };+ const options = (trace, overrides = {}) => Object.defineProperties({}, {+ detail: {configurable: true, get() { trace.push('detail'); return undefined; }},+ duration: {configurable: true, get() { trace.push('duration'); return undefined; }},+ end: {configurable: true, get() { trace.push('end'); return overrides.end; }},+ start: {configurable: true, get() { trace.push('start'); return overrides.start; }},+ });+ const startName = prefix + 'start';+ const endName = prefix + 'end';+ const markNames = [startName, endName, 'null', 'true', '5', '0'];+ for (const [value, time] of [[startName, 2], [endName, 9], ['null', 777.125],+ ['true', 161], ['5', 162], ['0', 163]]) mark(value, {startTime: time});+ try {+ test('required name uses callee TypeError', () => {+ assert(capture(() => Reflect.apply(method, performance, [])) instanceof callee.TypeError, 'arity');+ });+ test('receiver validation precedes argument conversion', () => {+ let reads = 0;+ const error = capture(() => Reflect.apply(method, {}, [{toString() { reads++; return name(); }}]));+ assert(error instanceof callee.TypeError && reads === 0, 'receiver conversion order');+ });+ test('name conversion precedes dictionary reads', () => {+ const trace = []; const sentinel = {};+ const error = capture(() => measure({toString() { trace.push('name'); throw sentinel; }},+ options(trace)));+ assert(error === sentinel, 'name exception identity'); equal(trace, ['name']);+ });+ test('dictionary converts each member before reading the next', () => {+ const trace = [];+ const result = measure(name(), options(trace, {+ end: {[Symbol.toPrimitive](hint) { trace.push('convert-end:' + hint); return endName; }},+ start: {[Symbol.toPrimitive](hint) { trace.push('convert-start:' + hint); return startName; }},+ }));+ equal(trace, ['detail', 'duration', 'end', 'convert-end:string', 'start', 'convert-start:string']);+ assert(result.startTime === 2 && result.duration === 7, 'measure values');+ });+ test('end conversion exception precedes start getter and third argument', () => {+ const trace = []; const endError = {}; const startError = {};+ const value = options(trace, {end: {toString() { trace.push('convert-end'); throw endError; }}});+ Object.defineProperty(value, 'start', {get() { trace.push('start'); throw startError; }});+ const error = capture(() => measure(name(), value, {toString() { trace.push('third'); return endName; }}));+ assert(error === endError, 'end exception identity');+ equal(trace, ['detail', 'duration', 'end', 'convert-end']);+ });+ for (const [label, end] of [['infinity', Infinity], ['NaN', NaN], ['symbol', Symbol()]]) {+ test(label + ' end conversion stops later getters in callee realm', () => {+ const trace = []; const sentinel = {};+ const value = options(trace, {end});+ Object.defineProperty(value, 'start', {get() { trace.push('start'); throw sentinel; }});+ const error = capture(() => measure(name(), value));+ assert(error instanceof callee.TypeError, 'callee TypeError');+ equal(trace, ['detail', 'duration', 'end']);+ });+ }+ test('duration conversion precedes end getter', () => {+ const trace = []; const sentinel = {};+ const value = options(trace);+ Object.defineProperty(value, 'duration', {get() {+ trace.push('duration'); return {valueOf() { trace.push('convert-duration'); throw sentinel; }};+ }});+ assert(capture(() => measure(name(), value)) === sentinel, 'duration identity');+ equal(trace, ['detail', 'duration', 'convert-duration']);+ });+ test('nonfinite duration stops end getter', () => {+ const trace = []; const value = options(trace);+ Object.defineProperty(value, 'duration', {get() { trace.push('duration'); return Infinity; }});+ assert(capture(() => measure(name(), value)) instanceof callee.TypeError, 'duration type');+ equal(trace, ['detail', 'duration']);+ });+ test('start conversion exception precedes legacy argument', () => {+ const trace = []; const sentinel = {};+ const value = options(trace, {end: 9, start: {toString() { trace.push('convert-start'); throw sentinel; }}});+ assert(capture(() => measure(name(), value, {toString() { trace.push('third'); return endName; }})) === sentinel, 'start identity');+ equal(trace, ['detail', 'duration', 'end', 'start', 'convert-start']);+ });+ test('end conversion can update the later start member', () => {+ const value = {start: 2, end: {toString() { value.start = 4; return endName; }}};+ const result = measure(name(), value);+ assert(result.startTime === 4 && result.duration === 5, 'updated start');+ });+ test('end conversion can remove the later start member', () => {+ const value = {start: 2, end: {toString() { delete value.start; return endName; }}};+ const result = measure(name(), value);+ assert(result.startTime === 0 && result.duration === 9, 'removed start');+ });+ test('end conversion cannot change an already converted duration', () => {+ let conversions = 0;+ const value = {duration: {valueOf() { conversions++; return 1; }},+ end: {toString() { value.duration = 3; return endName; }}};+ const result = measure(name(), value);+ assert(result.startTime === 8 && result.duration === 1 && conversions === 1, 'stored duration');+ });+ test('third argument conversion follows the dictionary conversions', () => {+ const trace = [];+ const value = options(trace, {+ end: {toString() { trace.push('convert-end'); return endName; }},+ start: {toString() { trace.push('convert-start'); return startName; }},+ });+ const error = capture(() => measure(name(), value, {toString() { trace.push('third'); return endName; }}));+ assert(error instanceof callee.TypeError, 'nonempty options and third argument');+ equal(trace, ['detail', 'duration', 'end', 'convert-end', 'start', 'convert-start', 'third']);+ });+ for (const [label, second] of [['empty', {}], ['null', null], ['undefined', undefined]]) {+ test(label + ' second argument preserves a null legacy end mark', () => {+ const result = measure(name(), second, null);+ assert(result.startTime === 0 && result.duration === 777.125, 'null is a DOMString mark');+ });+ }+ test('null legacy end counts as given with nonempty options', () => {+ assert(capture(() => measure(name(), {start: 0}, null)) instanceof callee.TypeError, 'third argument present');+ });+ test('third argument exception precedes semantic validation', () => {+ const sentinel = {};+ assert(capture(() => measure(name(), {detail: {}}, {toString() { throw sentinel; }})) === sentinel, 'third exception');+ });+ test('third argument exception precedes detail serialization', () => {+ const sentinel = {};+ assert(capture(() => measure(name(), {start: 0, detail: () => {}}, {toString() { throw sentinel; }})) === sentinel, 'third before clone');+ });+ test('object numeric primitive is converted to a mark string', () => {+ const trace = [];+ const result = measure(name(), {start: 0, end: {[Symbol.toPrimitive](hint) { trace.push(hint); return 5; }}});+ assert(result.duration === 162, 'object selects DOMString'); equal(trace, ['string']);+ });+ test('boxed Number is converted as a string rather than a timestamp', () => {+ const value = new Number(5); let valueOfCalls = 0;+ value.valueOf = () => { valueOfCalls++; throw Error('number hint'); };+ const result = measure(name(), {start: 0, end: value});+ assert(result.duration === 162 && valueOfCalls === 0, 'boxed number');+ });+ for (const [label, end, expected] of [['boolean', true, 161], ['bigint', 5n, 162], ['null', null, 777.125], ['number', 5, 5]]) {+ test(label + ' end preserves union selection', () => {+ assert(measure(name(), {start: 0, end}).duration === expected, 'union result');+ });+ }+ test('undefined end stays omitted', () => {+ const result = measure(name(), {start: 2, duration: 1, end: undefined});+ assert(result.startTime === 2 && result.duration === 1, 'undefined end');+ });+ test('invalid primitive result throws before start getter', () => {+ const trace = []; const value = options(trace, {end: {[Symbol.toPrimitive]() { trace.push('convert-end'); return {}; }}});+ Object.defineProperty(value, 'start', {get() { trace.push('start'); throw {}; }});+ assert(capture(() => measure(name(), value)) instanceof callee.TypeError, 'primitive result error');+ equal(trace, ['detail', 'duration', 'end', 'convert-end']);+ });+ test('inherited dictionary members retain conversion order', () => {+ const trace = [];+ const prototype = options(trace, {end: {toString() { trace.push('convert-end'); return endName; }}, start: 2});+ const result = measure(name(), Object.create(prototype));+ assert(result.startTime === 2 && result.duration === 7, 'inherited values');+ equal(trace, ['detail', 'duration', 'end', 'convert-end', 'start']);+ });+ test('proxy dictionary reads preserve conversion boundaries', () => {+ const trace = [];+ const target = {end: {toString() { trace.push('convert-end'); return endName; }}, start: 2};+ const result = measure(name(), new Proxy(target, {get(object, key, receiver) {+ trace.push(key); return Reflect.get(object, key, receiver);+ }}));+ assert(result.startTime === 2 && result.duration === 7, 'proxy values');+ equal(trace, ['detail', 'duration', 'end', 'convert-end', 'start']);+ });+ test('conversion failure does not enqueue a measure', () => {+ const before = entries('measure').length;+ capture(() => measure(name(), {end: Symbol()}));+ assert(entries('measure').length === before, 'failed measure queued');+ });+ } finally {+ for (const value of names) owner.Performance.prototype.clearMeasures.call(performance, value);+ for (const value of markNames) owner.Performance.prototype.clearMarks.call(performance, value);+ }+ return checks;+}