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): preserve UTF-16 entry name identity
ldm070ed22516541
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime.rsindex b4f77ab32..c2db64b5f 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime.rs@@ -6,7 +6,7 @@ mod observer;mod registration;use super::performance_runtime::{- PERFORMANCE_ENTRY_NAME_SLOT, PERFORMANCE_ENTRY_START_TIME_SLOT, PERFORMANCE_ENTRY_TYPE_SLOT,+ PERFORMANCE_ENTRY_START_TIME_SLOT, PERFORMANCE_ENTRY_TYPE_SLOT, PerformanceEntryName,performance_entry_slot_number, performance_entry_slot_string, performance_slot_array,};pub(super) use delivery::queue_matching_performance_observers;diff --git a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/entry_list.rs b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/entry_list.rsindex 4fb98bb99..ab3d05bc4 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/entry_list.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/entry_list.rs@@ -12,8 +12,8 @@ struct PerformanceEntryListGetEntriesByTypeArgs {#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "PerformanceObserverEntryList.getEntriesByName")]struct PerformanceEntryListGetEntriesByNameArgs {- #[webidl(required)]- name: String,+ #[webidl(required, converter = "raw")]+ name: PerformanceEntryName,entry_type: Option<String>,}@@ -67,7 +67,7 @@ pub(in crate::context_bootstrap) fn filtered_entry_list_entries<'s>(scope: &mut v8::PinScope<'s, '_>,entries: v8::Local<'s, v8::Array>,expected_type: Option<&str>,- expected_name: Option<&str>,+ expected_name: Option<&PerformanceEntryName>,) -> v8::Local<'s, v8::Array> {let mut filtered_entries: Vec<(u32, f64, v8::Local<'s, v8::Object>)> = Vec::new();for index in 0..entries.length() {@@ -84,8 +84,7 @@ pub(in crate::context_bootstrap) fn filtered_entry_list_entries<'s>(continue;}if expected_name.is_some_and(|expected| {- performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT).as_deref()- != Some(expected)+ PerformanceEntryName::from_entry(scope, entry).as_ref() != Some(expected)}) {continue;}diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rsindex 375c2d354..6e9eaa67f 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs@@ -6,6 +6,8 @@ mod install;mod lazy_subobjects;mod marks_measures;mod memory;+mod name;+pub(in crate::context_bootstrap) use name::PerformanceEntryName;mod resource_buffer;mod window_state;@@ -421,7 +423,7 @@ fn append_resource_performance_entry<'s>(scope,performance,"resource",- &entry.name,+ entry.name.into(),start_time,0.0,None,diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rsindex cf8af2545..7e793fcd3 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs@@ -20,19 +20,19 @@ struct PerformanceGetEntriesByTypeArgs {#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Performance.getEntriesByName")]struct PerformanceGetEntriesByNameArgs {- #[webidl(required)]- name: String,+ #[webidl(required, converter = "raw")]+ name: PerformanceEntryName,entry_type: Option<String>,}#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::PerformanceEntry, scope_lifetime = 'scope)]-struct PerformanceEntryObjectDeclaration<'scope, 'name, 'entry_type> {+struct PerformanceEntryObjectDeclaration<'scope, 'entry_type> {#[webapi(slot = PERFORMANCE_ENTRY_ID_SLOT)]id: f64,#[webapi(slot = PERFORMANCE_ENTRY_NAME_SLOT)]- name: &'name str,+ name: PerformanceEntryName,#[webapi(slot = PERFORMANCE_ENTRY_TYPE_SLOT)]entry_type: &'entry_type str,@@ -54,7 +54,7 @@ struct PerformanceEntryObjectDeclaration<'scope, 'name, 'entry_type> {#[webapi(plain, data_properties, enumerable)]struct PerformanceEntryJsonSnapshotDeclaration {id: f64,- name: String,+ name: PerformanceEntryName,entry_type: String,start_time: f64,duration: f64,@@ -129,7 +129,7 @@ struct PerformanceResourceTimingSlotDeclaration {#[webapi(plain, data_properties, enumerable)]struct PerformanceResourceTimingJsonSnapshotDeclaration {id: f64,- name: String,+ name: PerformanceEntryName,entry_type: String,start_time: f64,duration: f64,@@ -163,7 +163,7 @@ impl PerformanceResourceTimingJsonSnapshotDeclaration {) -> Option<Self> {Some(Self::new(performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_ID_SLOT)?,- performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT)?,+ PerformanceEntryName::from_entry(scope, entry)?,performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_TYPE_SLOT)?,performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_START_TIME_SLOT)?,performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_DURATION_SLOT)?,@@ -497,8 +497,7 @@ fn performance_entry_to_json_callback<'s>(throw_type_error(scope, "Illegal invocation");return;};- let Some(name) = performance_entry_slot_string(scope, receiver, PERFORMANCE_ENTRY_NAME_SLOT)- else {+ let Some(name) = PerformanceEntryName::from_entry(scope, receiver) else {throw_type_error(scope, "Illegal invocation");return;};@@ -754,7 +753,7 @@ pub(super) fn filtered_performance_entries<'s>(scope: &mut v8::PinScope<'s, '_>,performance: v8::Local<'s, v8::Object>,expected_type: Option<&str>,- expected_name: Option<&str>,+ expected_name: Option<&PerformanceEntryName>,) -> v8::Local<'s, v8::Array> {let Some(entries) = performance_slot_array(scope, performance, PERFORMANCE_ENTRIES_SLOT) else {return v8::Array::new(scope, 0);@@ -765,7 +764,7 @@ pub(super) fn filtered_performance_entries<'s>(pub(super) fn find_latest_performance_mark_start<'s>(scope: &mut v8::PinScope<'s, '_>,performance: v8::Local<'s, v8::Object>,- name: &str,+ name: &PerformanceEntryName,) -> Option<f64> {let entries = performance_slot_array(scope, performance, PERFORMANCE_ENTRIES_SLOT)?;let mut found = None;@@ -774,8 +773,7 @@ pub(super) fn find_latest_performance_mark_start<'s>(let entry = v8::Local::<v8::Object>::try_from(entry).ok()?;if performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_TYPE_SLOT).as_deref()== Some("mark")- && performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT).as_deref()- == Some(name)+ && PerformanceEntryName::from_entry(scope, entry).as_ref() == Some(name){found = performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_START_TIME_SLOT);}@@ -787,7 +785,7 @@ pub(super) fn create_performance_entry<'s>(scope: &mut v8::PinScope<'s, '_>,performance: v8::Local<'s, v8::Object>,entry_type: &str,- name: &str,+ name: PerformanceEntryName,start_time: f64,duration: f64,detail: Option<v8::Local<'s, v8::Value>>,@@ -829,7 +827,7 @@ pub(super) fn initialize_performance_entry_slots<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,entry_type: &str,- name: &str,+ name: PerformanceEntryName,start_time: f64,duration: f64,detail: Option<v8::Local<'s, v8::Value>>,diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rsindex a76f3c5da..287e942a3 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs@@ -681,7 +681,15 @@ fn create_navigation_performance_entry<'s>(navigation_type: &str,name: &str,) -> v8::Local<'s, v8::Object> {- let entry = create_performance_entry(scope, performance, "navigation", name, 0.0, 0.0, None);+ let entry = create_performance_entry(+ scope,+ performance,+ "navigation",+ name.into(),+ 0.0,+ 0.0,+ None,+ );super::entries::initialize_resource_timing_slots(scope,entry,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 039d7e761..e89e795a0 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@@ -10,15 +10,15 @@ use crate::webidl;#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Performance.mark")]struct PerformanceMarkArgs {- #[webidl(required)]- name: String,+ #[webidl(required, converter = "raw")]+ name: PerformanceEntryName,}#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "PerformanceMark")]struct PerformanceMarkConstructorArgs {- #[webidl(required)]- name: String,+ #[webidl(required, converter = "raw")]+ name: PerformanceEntryName,}#[derive(Default, webidl::WebIdlDictionary)]@@ -33,20 +33,22 @@ struct PerformanceMarkOptions<'s> {#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Performance.clearMarks")]struct PerformanceClearMarksArgs {- name: Option<String>,+ #[webidl(converter = "raw")]+ name: Option<PerformanceEntryName>,}#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Performance.measure")]struct PerformanceMeasureArgs<'s> {- #[webidl(required)]- name: String,+ #[webidl(required, converter = "raw")]+ name: PerformanceEntryName,#[webidl(converter = "raw",default = MeasureStartOrOptions::Dictionary(PerformanceMeasureOptions::default()))]start_or_options: MeasureStartOrOptions<'s>,- end_mark: Option<String>,+ #[webidl(converter = "raw")]+ end_mark: Option<PerformanceEntryName>,}#[derive(Default, webidl::WebIdlDictionary)]@@ -63,12 +65,12 @@ struct PerformanceMeasureOptions<'s> {}enum MeasureStartOrOptions<'s> {- Mark(String),+ Mark(PerformanceEntryName),Dictionary(PerformanceMeasureOptions<'s>),}enum MeasureBoundary {- Mark(String),+ Mark(PerformanceEntryName),Timestamp(f64),}@@ -85,8 +87,7 @@ impl<'s> webidl::WebIdlConverter<'s> for MeasureStartOrOptions<'s> {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))+ webidl::convert::<PerformanceEntryName>(scope, value, context).map(Self::Mark)}}}@@ -104,8 +105,7 @@ impl<'s> webidl::WebIdlConverter<'s> for MeasureBoundary {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))+ webidl::convert::<PerformanceEntryName>(scope, value, context).map(Self::Mark)}}}@@ -120,7 +120,8 @@ struct ParsedPerformanceMeasure<'s> {#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Performance.clearMeasures")]struct PerformanceClearMeasuresArgs {- name: Option<String>,+ #[webidl(converter = "raw")]+ name: Option<PerformanceEntryName>,}pub(in crate::context_bootstrap) fn performance_mark_callback<'s>(@@ -148,7 +149,7 @@ pub(in crate::context_bootstrap) fn performance_mark_callback<'s>(scope,performance,"mark",- &parsed.name,+ parsed.name,start_time,0.0,detail,@@ -192,7 +193,7 @@ pub(in crate::context_bootstrap) fn performance_mark_constructor_callback<'s>(scope,args.this(),"mark",- &parsed.name,+ parsed.name,start_time,0.0,detail,@@ -226,7 +227,7 @@ fn parse_performance_mark_options<'s>(fn prepare_performance_mark<'s>(scope: &mut v8::PinScope<'s, '_>,performance: v8::Local<'s, v8::Object>,- name: &str,+ name: &PerformanceEntryName,options: PerformanceMarkOptions<'s>,) -> Option<(f64, Option<v8::Local<'s, v8::Value>>)> {let start_time = options@@ -240,7 +241,9 @@ fn prepare_performance_mark<'s>(return None;}if install::is_window_performance(scope, performance)- && install::PERFORMANCE_TIMING_ATTRIBUTE_NAMES.contains(&name)+ && name+ .as_str()+ .is_some_and(|name| install::PERFORMANCE_TIMING_ATTRIBUTE_NAMES.contains(&name)){webidl::throw_dom_exception(scope,@@ -279,10 +282,7 @@ pub(in crate::context_bootstrap) fn performance_clear_marks_callback<'s>(let keep = if !is_mark {true} else {- match (- &parsed.name,- performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT),- ) {+ match (&parsed.name, PerformanceEntryName::from_entry(scope, entry)) {(Some(expected), Some(actual)) => actual != *expected,(Some(_), None) => true,(None, _) => false,@@ -338,7 +338,7 @@ pub(in crate::context_bootstrap) fn performance_measure_callback<'s>(scope,performance,"measure",- &parsed.name,+ parsed.name,start_time,end_time - start_time,detail,@@ -372,10 +372,7 @@ pub(in crate::context_bootstrap) fn performance_clear_measures_callback<'s>(let keep = if !is_measure {true} else {- match (- &parsed.name,- performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT),- ) {+ match (&parsed.name, PerformanceEntryName::from_entry(scope, entry)) {(Some(expected), Some(actual)) => actual != *expected,(Some(_), None) => true,(None, _) => false,@@ -393,7 +390,7 @@ pub(in crate::context_bootstrap) fn performance_clear_measures_callback<'s>(fn prepare_performance_measure<'s>(scope: &mut v8::PinScope<'s, '_>,start_or_options: MeasureStartOrOptions<'s>,- end_mark: Option<String>,+ end_mark: Option<PerformanceEntryName>,) -> Option<ParsedPerformanceMeasure<'s>> {let options = match start_or_options {MeasureStartOrOptions::Dictionary(options) => options,@@ -453,7 +450,7 @@ fn prepare_performance_measure<'s>(fn resolve_measure_boundary<'s>(scope: &mut v8::PinScope<'s, '_>,performance: v8::Local<'s, v8::Object>,- measure_name: &str,+ measure_name: &PerformanceEntryName,boundary: &MeasureBoundary,) -> Result<f64, ()> {match boundary {@@ -472,9 +469,12 @@ fn resolve_measure_boundary<'s>(fn resolve_named_measure_boundary<'s>(scope: &mut v8::PinScope<'s, '_>,performance: v8::Local<'s, v8::Object>,- name: &str,+ name: &PerformanceEntryName,) -> Result<f64, ()> {- if !install::PERFORMANCE_TIMING_ATTRIBUTE_NAMES.contains(&name) {+ let Some(timing_name) = name+ .as_str()+ .filter(|name| install::PERFORMANCE_TIMING_ATTRIBUTE_NAMES.contains(name))+ else {if let Some(start_time) = find_latest_performance_mark_start(scope, performance, name) {return Ok(start_time);}@@ -484,7 +484,7 @@ fn resolve_named_measure_boundary<'s>(&format!("The mark '{name}' does not exist."),);return Err(());- }+ };if !install::is_window_performance(scope, performance) {webidl::throw_type_error(@@ -510,7 +510,7 @@ fn resolve_named_measure_boundary<'s>(return Err(());}};- let Some(key) = v8_string(scope, name) else {+ let Some(key) = v8_string(scope, timing_name) else {return Err(());};let value = timingdiff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/name.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/name.rsnew file mode 100644index 000000000..96fdd13d1--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/name.rs@@ -0,0 +1,69 @@+use super::{PERFORMANCE_ENTRY_NAME_SLOT, performance_entry_slot_value};+use crate::{dom::native::DomStringValue, util, webidl};+use moli_webapi_declare::WebApiValue;+use std::fmt;++/// Entry names are DOMStrings, not Unicode scalar strings or URLs. Keep their+/// original UTF-16 identity through argument conversion, storage and lookup.+#[derive(Clone, PartialEq, Eq)]+pub(in crate::context_bootstrap) struct PerformanceEntryName(DomStringValue);++impl PerformanceEntryName {+ pub(super) fn as_str(&self) -> Option<&str> {+ self.0.as_str()+ }++ pub(in crate::context_bootstrap) fn from_entry<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ entry: v8::Local<'s, v8::Object>,+ ) -> Option<Self> {+ let value = performance_entry_slot_value(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT)?;+ let value = v8::Local::<v8::String>::try_from(value).ok()?;+ Some(Self(DomStringValue::from_utf16(+ util::v8_string_to_u16_string(scope, value).as_slice(),+ )))+ }+}++impl From<&str> for PerformanceEntryName {+ fn from(value: &str) -> Self {+ Self(value.into())+ }+}++impl From<String> for PerformanceEntryName {+ fn from(value: String) -> Self {+ Self(value.into())+ }+}++impl fmt::Display for PerformanceEntryName {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ // The scalar view is only for diagnostic messages, never identity.+ formatter.write_str(self.0.as_str_lossy())+ }+}++impl<'s> webidl::WebIdlConverter<'s> for PerformanceEntryName {+ type Options = webidl::StringOptions;++ fn convert(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: webidl::Context,+ options: &Self::Options,+ ) -> Result<Self, webidl::WebIdlError> {+ webidl::DomString16::convert(scope, value, context, options)+ .map(|value| Self(DomStringValue::from_utf16(&value.0)))+ }+}++impl<'s> WebApiValue<'s> for PerformanceEntryName {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ let value = match self.0.as_str() {+ Some(value) => util::v8_string(scope, value),+ None => util::v8_string_from_utf16_units(scope, &self.0.utf16_units()),+ }?;+ Some(value.into())+ }+}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 35d77cd41..abd2d8a8d 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@@ -45,3 +45,35 @@ fn performance_measure_converts_arguments_and_members_in_webidl_order() {assert_eq!(result["total"], 128);assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");}++#[tokio::test(flavor = "current_thread")]+async fn performance_names_retain_utf16_identity_across_realms_and_observers() {+ let mut vm = new_storage_page_task_executor_test_vm("https://performance-names.test/");+ let source = format!(+ r#"(async () => {{+ const probe = {};+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ try {{+ const checks = [];+ const realms = [globalThis, frame.contentWindow];+ for (const owner of realms) for (const callee of realms)+ checks.push(...await probe(owner, callee));+ globalThis.__performanceNameResult = {{total: checks.length, failures: checks.filter(row => !row.passed)}};+ }} finally {{ frame.remove(); }}+ }})()"#,+ include_str!("../../../tests/fixtures/performance-name-utf16.js"),+ );+ vm.eval(&source).unwrap();+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ vm.advance_timers_until_deadline_for_test(&loader)+ .await+ .unwrap();+ let result: serde_json::Value = serde_json::from_str(+ &vm.eval("JSON.stringify(globalThis.__performanceNameResult)")+ .unwrap(),+ )+ .unwrap();+ assert_eq!(result["total"], 912);+ 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 36f46a54d..286470f69 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@@ -41,3 +41,25 @@ async fn worker_performance_measure_converts_arguments_and_members_in_webidl_ordassert_eq!(result["total"], 32);assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");}++#[tokio::test]+async fn worker_performance_names_retain_utf16_identity_with_observers() {+ ensure_v8();+ let source = format!(+ r#"(async () => {{+ const probe = {};+ const checks = await probe();+ postMessage({{total: checks.length, failures: checks.filter(row => !row.passed)}});+ close();+ }})()"#,+ include_str!("../../../../tests/fixtures/performance-name-utf16.js"),+ );+ let mut worker = spawn_worker(source, "test://performance_names".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"], 228);+ assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");+}diff --git a/moli-renderer-v8/tests/fixtures/performance-name-utf16.js b/moli-renderer-v8/tests/fixtures/performance-name-utf16.jsnew file mode 100644index 000000000..49fa6ed81--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/performance-name-utf16.js@@ -0,0 +1,144 @@+async (owner = globalThis, callee = owner) => {+ const checks = [];+ const test = (name, callback) => {+ try {+ if (!callback()) throw Error('assertion failed');+ checks.push({name, passed: true});+ } catch (error) {+ checks.push({name, passed: false, details: String(error.stack || error)});+ }+ };+ const capture = callback => { try { callback(); } catch (error) { return error; } };+ const performance = owner.performance;+ const method = name => (...args) => Reflect.apply(callee.Performance.prototype[name], performance, args);+ const mark = method('mark');+ const measure = method('measure');+ const byName = method('getEntriesByName');+ const clearMarks = method('clearMarks');+ const clearMeasures = method('clearMeasures');+ const json = entry => Reflect.apply(callee.PerformanceEntry.prototype.toJSON, entry, []);+ const prefix = '__performanceName:';+ const suffixes = ['\ud800', '\ud801', '\udc00', '\udc01', '\ufffd',+ '\ud83d\ude00', '\ud83d', '\ude00', '\0', 'x\0y', '', 'ascii'];+ const names = suffixes.map(value => prefix + value);+ const measureNames = suffixes.map(value => prefix + 'measure/' + value);+ const marks = [];+ const measures = [];+ let resolveDelivery;+ const delivery = new Promise(resolve => { resolveDelivery = resolve; });+ const observer = new owner.PerformanceObserver(list => resolveDelivery(list));+ observer.observe({entryTypes: ['mark', 'measure']});+ try {+ for (let i = 0; i < names.length; i++) {+ const name = names[i];+ const entry = mark(name, {startTime: i + 1});+ marks.push(entry);+ const constructed = new callee.PerformanceMark(name, {startTime: i + 1});+ const measurement = measure(measureNames[i], {start: name, end: 30});+ measures.push(measurement);+ test('mark preserves name ' + i, () => entry.name === name);+ test('constructor preserves name ' + i, () => constructed.name === name);+ test('constructor snapshot preserves name ' + i, () => json(constructed).name === name);+ test('mark snapshot preserves name ' + i, () => json(entry).name === name);+ test('mark typed query preserves identity ' + i, () => {+ const found = byName(name, 'mark');+ return found.length === 1 && found[0] === entry;+ });+ test('untyped query preserves identity ' + i, () => {+ const found = byName(name);+ return found.length === 1 && found[0] === entry;+ });+ test('measure preserves name ' + i, () => measurement.name === measureNames[i]);+ test('measure snapshot preserves name ' + i, () => json(measurement).name === measureNames[i]);+ test('measure typed query preserves identity ' + i, () => {+ const found = byName(measureNames[i], 'measure');+ return found.length === 1 && found[0] === measurement;+ });+ test('options start resolves exact name ' + i, () => measurement.startTime === i + 1);+ test('options end resolves exact name ' + i, () =>+ measure(prefix + 'options-end', {start: 0, end: name}).duration === i + 1);+ test('legacy start resolves exact name ' + i, () =>+ measure(prefix + 'legacy-start', name, names[0]).startTime === i + 1);+ test('legacy end resolves exact name ' + i, () =>+ measure(prefix + 'legacy-end', names[0], name).duration === i);+ }+ test('snapshot reads native name without invoking own getter', () => {+ const entry = marks[0];+ Object.defineProperty(entry, 'name', {get() { throw Error('author name getter'); }});+ return json(entry).name === names[0];+ });+ test('name coercion preserves UTF-16 and runs before mark options', () => {+ const trace = [];+ const entry = mark({toString() { trace.push('name'); return names[0]; }}, {+ get startTime() { trace.push('time'); return 40; },+ });+ return entry.name === names[0] && trace.join() === 'name,time';+ });+ test('latest mark lookup keeps colliding names separate', () =>+ measure(prefix + 'latest', {start: names[0], end: 50}).startTime === 40 &&+ measure(prefix + 'other', {start: names[1], end: 50}).startTime === 2);+ test('boxed boundary strings preserve exact name', () =>+ measure(prefix + 'boxed', {start: new owner.String(names[1]), end: 10}).startTime === 2);+ test('coerced third argument preserves exact name', () =>+ measure(prefix + 'third', {}, {toString() { return names[1]; }}).duration === 2);+ test('missing surrogate name does not resolve replacement character mark', () =>+ capture(() => measure(prefix + 'missing', {start: prefix + '\ud802', end: 50}))+ instanceof callee.DOMException);+ test('symbol name throws callee TypeError before options getters', () => {+ let reads = 0;+ const error = capture(() => mark(Symbol(), {get startTime() { reads++; return 0; }}));+ return error instanceof callee.TypeError && reads === 0;+ });+ test('query name exception precedes entry type conversion', () => {+ const sentinel = {}; let reads = 0;+ return capture(() => byName({toString() { throw sentinel; }},+ {toString() { reads++; return 'mark'; }})) === sentinel && reads === 0;+ });+ for (const clear of [clearMarks, clearMeasures]) {+ test('clear symbol rejects without clearing entries ' + checks.length, () =>+ capture(() => clear(Symbol())) instanceof callee.TypeError &&+ byName(names[1], 'mark').length === 1 && byName(measureNames[1], 'measure').length === 1);+ }+ // Clear while the observer notification is still queued. Its list must+ // retain the original entries and their names independently of the buffer.+ for (let i = 0; i < names.length; i++) {+ clearMarks({toString() { return names[i]; }});+ test('clearMarks removes only exact name ' + i, () => names.every((name, index) =>+ byName(name, 'mark').length === (index <= i ? 0 : 1)));+ test('clearMarks retains measures ' + i, () => byName(measureNames[i], 'measure')[0] === measures[i]);+ }+ for (let i = 0; i < measureNames.length; i++) {+ clearMeasures({toString() { return measureNames[i]; }});+ test('clearMeasures removes only exact name ' + i, () => measureNames.every((name, index) =>+ byName(name, 'measure').length === (index <= i ? 0 : 1)));+ }+ const list = await delivery;+ const listByName = (...args) => Reflect.apply(+ callee.PerformanceObserverEntryList.prototype.getEntriesByName, list, args);+ for (let i = 0; i < names.length; i++) {+ test('observer mark name identity after clear ' + i, () => {+ const found = listByName(names[i], 'mark');+ return found.length === (i === 0 ? 2 : 1) && found[0] === marks[i];+ });+ test('observer measure name identity after clear ' + i, () => {+ const found = listByName(measureNames[i], 'measure');+ return found.length === 1 && found[0] === measures[i];+ });+ }+ test('observer name coercion runs before type conversion', () => {+ const trace = [];+ const found = listByName({toString() { trace.push('name'); return names[1]; }},+ {toString() { trace.push('type'); return 'mark'; }});+ return trace.join() === 'name,type' && found.length === 1 && found[0] === marks[1];+ });+ test('observer symbol name rejects with callee TypeError', () =>+ capture(() => listByName(Symbol())) instanceof callee.TypeError);+ } finally {+ observer.disconnect();+ for (const name of names) clearMarks(name);+ for (const entry of method('getEntriesByType')('measure')) {+ if (entry.name.startsWith(prefix)) clearMeasures(entry.name);+ }+ }+ return checks;+}