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(emulation): preserve Date coercion and locale fallback semantics
ldm0007519d6165e
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/locale_timezone_inputs.py b/moli-cdp-smoke/moli_cdp_smoke/groups/locale_timezone_inputs.pyindex 09089225e..32dc0b20a 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/locale_timezone_inputs.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/locale_timezone_inputs.py@@ -13,6 +13,9 @@ EXPLICIT_DATE_INPUTS = ["Mon Jan 01 2024 00:00:00 -04:00","Mon Jan 01 2024 00:00:00 PST (Pacific Standard Time)","Mon Jan 01 2024 00:00:00 pSt\u00a0",+ "00:00:00-0100 Jan-01-2024",+ "00:00-01:00 01-01-2024",+ "00:00:00.000-0100 Jan-01-2024","2024-01-01T00:00:00Z","2024-01-01T00:00:00+02:00","2024", "2024-01", "2024-01-01", "+002024-01-01",@@ -43,6 +46,69 @@ OPTION_READS = """() => {});}"""+OBJECT_DATES = """() => {+ const input = '2024-01-01T00:00:00';+ const calls = [];+ const values = [new String(input), [input],+ {[Symbol.toPrimitive](hint) {calls.push(hint); return input;}},+ {valueOf() {calls.push('valueOf'); return {};},+ toString() {calls.push('toString'); return input;}}];+ const correct = values.map(value => +new Date(value) === +new Date(2024, 0, 1));+ const original = new Date(1234);+ Object.defineProperty(original, Symbol.toPrimitive, {get() {throw new Error('unexpected Date coercion');}});+ return [correct, calls, +new Date(original),+ +new Date({[Symbol.toPrimitive]() {return 1234;}})];+}"""++PRIMITIVE_OPTIONS = """zone => {+ const date = new Date('2024-01-01T00:00:00Z');+ return [42, true, '', Symbol(), 1n].map(options => [+ new Intl.DateTimeFormat('en-US', options).resolvedOptions().timeZone === zone,+ ...['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method =>+ date[method]('en-US', options) === date[method]('en-US', {timeZone: zone}))+ ]);+}"""++LOCALE_FALLBACK = """() => {+ const date = new Date('2024-01-01T00:00:00Z');+ const names = ['Collator', 'DateTimeFormat', 'DisplayNames', 'DurationFormat',+ 'ListFormat', 'NumberFormat', 'PluralRules', 'RelativeTimeFormat', 'Segmenter'];+ return [[], {}, ['zz-ZZ']].map(locales => [+ ...names.filter(name => typeof Intl[name] === 'function').map(name =>+ ['lookup', 'best fit'].every(localeMatcher => {+ const options = {localeMatcher, type: name === 'DisplayNames' ? 'language' : undefined};+ return new Intl[name](locales, options).resolvedOptions().locale ===+ new Intl[name](undefined, options).resolvedOptions().locale;+ })),+ new Intl.NumberFormat(locales).format(1234.5) === new Intl.NumberFormat().format(1234.5),+ ...['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method =>+ date[method](locales) === date[method]())+ ]);+}"""++LOCALE_READS = """() => {+ const date = new Date(0);+ return ['Collator', 'DateTimeFormat', 'NumberFormat', 'PluralRules',+ 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(name => {+ const trace = [];+ const locales = new Proxy({length: 1, 0: {toString() {trace.push('locale:string'); return 'zz-ZZ';}}}, {+ get(target, key, receiver) {trace.push(`locales:get:${String(key)}`); return Reflect.get(target, key, receiver);},+ has(target, key) {trace.push(`locales:has:${String(key)}`); return Reflect.has(target, key);}+ });+ const options = new Proxy({localeMatcher: {toString() {trace.push('matcher:string'); return 'lookup';}}}, {+ get(target, key, receiver) {trace.push(`options:get:${String(key)}`); return Reflect.get(target, key, receiver);}+ });+ if (name.startsWith('toLocale')) date[name](locales, options);+ else {+ const newTarget = new Proxy(function() {}, {get(target, key, receiver) {+ trace.push(`newTarget:get:${String(key)}`); return Reflect.get(target, key, receiver);+ }});+ Reflect.construct(Intl[name], [locales, options], newTarget);+ }+ return trace;+ });+}"""+async def run_locale_timezone_inputs_group(browser: Any, _fixture: str, results: list[dict[str, Any]]@@ -66,6 +132,7 @@ async def run_locale_timezone_inputs_group(True, "explicit-zone reference inputs must be valid native dates",)baseline_reads = await page.evaluate(OPTION_READS)+ baseline_locale_reads = await page.evaluate(LOCALE_READS)baseline_defaults = await page.evaluate("""() => [new Intl.NumberFormat().resolvedOptions().locale,new Intl.DateTimeFormat().resolvedOptions().timeZone,@@ -83,6 +150,14 @@ async def run_locale_timezone_inputs_group(assert_equal(dates, baseline_dates, f"explicit date zones survive {zone}")record(results, "timezone_explicit_dates", {"timezone": zone, "inputs": len(dates)})+ assert_equal(await page.evaluate(OBJECT_DATES),+ [[True] * 4, ['default', 'valueOf', 'toString'], 1234, 1234],+ f"single Date argument coercion under {zone}")+ record(results, "timezone_date_object_coercion", {"timezone": zone})+ assert_equal(await page.evaluate(PRIMITIVE_OPTIONS, zone), [[True] * 4] * 5,+ f"primitive Intl/Date options under {zone}")+ record(results, "timezone_primitive_options", {"timezone": zone, "inputs": 5})+local_dates = await page.evaluate(r"""() => [['Tue Jan 02 2024 00:00:00', 2],['Thu Jan 04 2024 00:00:00', 4],@@ -92,14 +167,18 @@ async def run_locale_timezone_inputs_group([' 2024-01-02 ', 2],['2024-01-02T00:00:00', 2],['2024-01-02t00:00:00', 2],+ ['00:00:00 Jan-02-2024', 2],+ ['00:00:00 01-02-2024', 2],+ ['00:00 Jan-02-2024', 2],+ ['00:00:00.000 January-02-2024 (PST)', 2],['Jan 02 2024\0PST', 2],['2024-01-02T00:00:00\0Z', 2]].map(([input, day]) => [Date.parse(input) === +new Date(2024, 0, day),+new Date(input) === +new Date(2024, 0, day)])""")- assert_equal(local_dates, [[True, True]] * 10, f"local ISO/legacy fields under {zone}")- record(results, "timezone_local_date_grammars", {"timezone": zone, "inputs": 10})+ assert_equal(local_dates, [[True, True]] * 14, f"local ISO/legacy fields under {zone}")+ record(results, "timezone_local_date_grammars", {"timezone": zone, "inputs": 14})frozen = await page.evaluate("""zone => {const date = new Date('2024-01-01T00:00:00Z');@@ -145,6 +224,19 @@ async def run_locale_timezone_inputs_group(assert_equal(result, [True] * 9, f"ICU locale {locale} matches explicit {tag}")record(results, "icu_locale_default_conversion", {"locale": locale, "language_tag": tag})+ # A supported plain default makes fallback identity independent of+ # service-specific support for Unicode locale extensions above.+ await cdp.send("Emulation.setLocaleOverride", {"locale": "fr_FR"})+ fallback = await page.evaluate(LOCALE_FALLBACK)+ assert_equal(len(fallback), 3, "all empty/unsupported locale list variants exercised")+ for index, row in enumerate(fallback):+ assert_equal(len(row) >= 12, True, "Intl services and Date locale methods exercised")+ assert_equal(row, [True] * len(row), f"default locale fallback variant {index}")+ record(results, "locale_empty_and_unsupported_lists", {"locale": "fr_FR", "inputs": 3})+ assert_equal(await page.evaluate(LOCALE_READS), baseline_locale_reads,+ "locale fallback preserves native newTarget, locale and option observation order")+ record(results, "locale_fallback_getter_order", {"locale": "fr_FR", "surfaces": 7})+await cdp.send("Emulation.setLocaleOverride", {"locale": ""})await cdp.send("Emulation.setTimezoneOverride", {"timezoneId": ""})restored = await page.evaluate("""() => [diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rsindex d302b710a..d4e97bfb8 100644--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rs+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rs@@ -1,5 +1,5 @@use super::{DateIntrinsic, original_date_method};-use crate::util::{call_script_visible_function, v8_string, v8str};+use crate::util::{call_script_visible_function, throw_type_error, v8_string, v8str};use crate::webidl;use anyhow::{Result, anyhow};use moli_webapi_declare::WebApiObject;@@ -202,9 +202,18 @@ fn date_constructor_timezone_arguments<'s>(.ok_or(())?} else if arguments.length() == 1 {let input = arguments.get_index(scope, 0).ok_or(())?;- if !input.is_string() {+ // Date copies another Date's [[DateValue]] without invoking even an+ // own @@toPrimitive getter. Every other object is converted with the+ // default hint, then strings are parsed and other primitives become+ // numeric epochs. Forward the primitive, never the original object,+ // so V8 cannot run the page's conversion hooks a second time.+ if input.is_date() {return Ok(None);}+ let input = date_constructor_primitive(scope, input).ok_or(())?;+ if !input.is_string() {+ return Ok(Some(v8::Array::new_with_elements(scope, &[input])));+ }let input = v8::Local::<v8::String>::try_from(input).map_err(|_| ())?;let epoch = parse_date_string(scope, date_parse, input, Some(timezone)).ok_or(())?;return Ok(Some(v8::Array::new_with_elements(scope, &[epoch])));@@ -218,6 +227,57 @@ fn date_constructor_timezone_arguments<'s>()))}+/// ECMA-262 ToPrimitive with no preferred type (Date constructor step 3.b.i).+/// rusty_v8 does not expose this abstract operation. Keep the small conversion+/// boundary here rather than using ToString/ToNumber, which change both the+/// hint and which branch the native Date constructor must take.+fn date_constructor_primitive<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ input: v8::Local<'s, v8::Value>,+) -> Option<v8::Local<'s, v8::Value>> {+ if !input.is_object() {+ return Some(input);+ }+ let object = v8::Local::<v8::Object>::try_from(input).ok()?;+ let key = v8::Symbol::get_to_primitive(scope);+ let exotic = object.get(scope, key.into())?;+ if !exotic.is_null_or_undefined() {+ let Ok(method) = v8::Local::<v8::Function>::try_from(exotic) else {+ throw_type_error(scope, "Symbol.toPrimitive is not callable");+ return None;+ };+ let hint = v8str(scope, "default");+ let result = call_script_visible_function(+ scope,+ method,+ input,+ &[hint.into()],+ "Date constructor ToPrimitive",+ )?;+ if !result.is_object() {+ return Some(result);+ }+ } else {+ for key in ["valueOf", "toString"] {+ let method = object.get(scope, v8str(scope, key).into())?;+ if let Ok(method) = v8::Local::<v8::Function>::try_from(method) {+ let result = call_script_visible_function(+ scope,+ method,+ input,+ &[],+ "Date constructor OrdinaryToPrimitive",+ )?;+ if !result.is_object() {+ return Some(result);+ }+ }+ }+ }+ throw_type_error(scope, "Cannot convert object to primitive value");+ None+}+fn single_date_epoch_argument<'s>(scope: &mut v8::PinScope<'s, '_>,wall_clock_utc_ms: Option<f64>,diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rsindex 5fdfc9349..eed4097a1 100644--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rs+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rs@@ -61,10 +61,13 @@ fn legacy_timezone(input: &str) -> (bool, usize) {const ZONES: &[&str] = &["ut", "utc", "gmt", "z", "est", "edt", "cst", "cdt", "mst", "mdt", "pst", "pdt",];+ const MONTHS: &[&str] = &[+ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",+ ];let mut chars = input.char_indices().peekable();let mut comments = 0;let mut number_seen = false;- let mut time_seen = false;+ let mut time_fields = 0;while let Some((start, ch)) = chars.next() {if ch == '(' {comments += 1;@@ -74,9 +77,35 @@ fn legacy_timezone(input: &str) -> (bool, usize) {}} else if ch.is_ascii_digit() {number_seen = true;- } else if ch == ':' {- time_seen = true;- } else if matches!(ch, '+' | '-') && time_seen {+ let mut number = ch.to_digit(10).unwrap();+ while let Some((_, digit)) = chars.next_if(|(_, ch)| ch.is_ascii_digit()) {+ number = number+ .saturating_mul(10)+ .saturating_add(digit.to_digit(10).unwrap());+ }+ // Mirror DateParser's token consumption, not a full date parser:+ // day numbers and month names consume their following '-' before+ // the timezone branch sees it. A completed time does NOT consume+ // that sign (00:00:00-0100 is an offset). The original native parse+ // above still decides validity, ranges and calendar composition.+ if chars.next_if(|(_, ch)| *ch == ':').is_some() {+ time_fields += 1;+ if chars.next_if(|(_, ch)| *ch == ':').is_some() {+ time_fields += 1;+ } else {+ let _ = chars.next_if(|(_, ch)| *ch == '.');+ }+ } else if ((time_fields == 1 || time_fields == 2) && number <= 59)+ || (time_fields == 3 && number <= 999)+ {+ time_fields = 4;+ if chars.next_if(|(_, ch)| *ch == '.').is_some() {+ while chars.next_if(|(_, ch)| ch.is_ascii_digit()).is_some() {}+ }+ } else {+ let _ = chars.next_if(|(_, ch)| *ch == '-');+ }+ } else if matches!(ch, '+' | '-') && time_fields > 0 {return (true, comments);} else if is_legacy_word_char(ch) {while chars.peek().is_some_and(|(_, ch)| is_legacy_word_char(*ch)) {@@ -88,6 +117,13 @@ fn legacy_timezone(input: &str) -> (bool, usize) {if number_seen && ZONES.iter().any(|zone| word.eq_ignore_ascii_case(zone)) {return (true, comments);}+ if word.as_bytes().get(..3).is_some_and(|prefix| {+ MONTHS+ .iter()+ .any(|month| prefix.eq_ignore_ascii_case(month.as_bytes()))+ }) {+ let _ = chars.next_if(|(_, ch)| *ch == '-');+ }}}(false, comments)@@ -125,6 +161,9 @@ mod tests {"Jan 1 2024 00:00:00 PST","Jan 1 2024 00:00:00 eSt\u{a0}","Jan 1 2024 00:00:00 +0530",+ "00:00:00-0100 Jan-01-2024",+ "00:00-01:00 01-01-2024",+ "00:00:00.000-0100 Jan-01-2024",] {assert_eq!(local_date_parse_input_as_utc(input), None, "{input}");}@@ -133,6 +172,10 @@ mod tests {"Thu Jan 04 2024 00:00:00","Jan 1 2024 (PST)"," 2024-01-01 ",+ "00:00:00 Jan-01-2024",+ "00:00:00 01-01-2024",+ "00:00 January-01-2024",+ "00:00:00.000 Jan-01-2024",] {assert_eq!(local_date_parse_input_as_utc(input),diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rsindex dd8391731..0d4fb1f72 100644--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rs+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rs@@ -2,7 +2,8 @@ use super::*;use crate::util::call_script_visible_function;use super::super::{- intl::intl_datetime_options_with_default_timezone, overrides::current_date_locale_overrides,+ intl::{intl_date_locales_with_default, intl_datetime_options_with_default_timezone},+ overrides::current_date_locale_overrides,};const DATE_LOCAL_FIELD_INTRINSICS: &[DateIntrinsic] = &[@@ -87,13 +88,12 @@ fn set_date_locale_method_result<'s>(.map(|index| args.get(index)).collect::<Vec<_>>();if let Some(locale) = locale_override.as_deref()- && forwarded.first().is_none_or(|value| value.is_undefined())- && let Some(locale) = v8_string(scope, locale)+ && let Some(locale) = intl_date_locales_with_default(scope, args.get(0), locale){if forwarded.is_empty() {- forwarded.push(locale.into());+ forwarded.push(locale);} else {- forwarded[0] = locale.into();+ forwarded[0] = locale;}}if let Some(timezone) = timezone_override.as_deref()diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rsindex 7396d8427..992d9801c 100644--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs@@ -1,5 +1,6 @@use crate::util::{- call_script_visible_function, get_private_value, set_private_value, v8_string, v8str,+ call_script_visible_function, define_v8_array_data_property, get_private_value,+ set_private_value, v8_string, v8str,};use crate::webidl;use anyhow::{Result, anyhow};@@ -10,6 +11,9 @@ use super::bindings::{};use super::overrides::current_date_locale_overrides;+mod locales;+use locales::LocaleIntrinsics;+const INTL_DEFAULT_LOCALE_SLOT: &str = "__moliIntlDefaultLocale";const INTL_CONSTRUCTORS: &[&str] = &[@@ -31,6 +35,10 @@ struct IntlConstructorData<'s> {reflect: v8::Local<'s, v8::Function>,#[webidl(required)]uses_timezone: bool,+ #[webidl(required)]+ canonicalize_locales: v8::Local<'s, v8::Function>,+ #[webidl(required)]+ supported_locales: v8::Local<'s, v8::Function>,}#[derive(WebApiObject)]@@ -82,8 +90,9 @@ pub(super) fn install_intl_default_override_constructors<'s>(// Chromium changes ICU's process-wide default and notifies every isolate.// Moli can host independently configured targets in one renderer process,// so a process-global ICU mutation would leak one target's emulation into- // another. Keep the override context-local by injecting only omitted- // constructor defaults; explicit page-provided locale/timeZone values win.+ // another. Keep the override context-local; native locale matching tries+ // the page's canonical requests before our fallback, and explicit timeZone+ // values win. The locale adapter is lazy to preserve native getter order.let Some(intl_value) = global.get(scope, v8str(scope, "Intl").into()) else {return Ok(());};@@ -93,6 +102,10 @@ pub(super) fn install_intl_default_override_constructors<'s>(let Some(reflect) = ReflectIntrinsics::from_global(scope, global) else {return Ok(());};+ let canonicalize = intl+ .get(scope, v8str(scope, "getCanonicalLocales").into())+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ .ok_or_else(|| anyhow!("missing native Intl.getCanonicalLocales"))?;for &name in INTL_CONSTRUCTORS {let key = v8str(scope, name);let Some(original_value) = intl.get(scope, key.into()) else {@@ -108,9 +121,20 @@ pub(super) fn install_intl_default_override_constructors<'s>(install_intl_resolved_options_override(scope, prototype)?;}let uses_timezone = name == "DateTimeFormat";+ let supported = original+ .get(scope, v8str(scope, "supportedLocalesOf").into())+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ .ok_or_else(|| anyhow!("missing native Intl.{name}.supportedLocalesOf"))?;+ if uses_timezone {+ locales::retain_date_locale_intrinsics(+ scope,+ global,+ LocaleIntrinsics::new(canonicalize, supported),+ )?;+ }let handler = IntlConstructorHandler::new(- IntlConstructorData::new(reflect.apply, uses_timezone),- IntlConstructorData::new(reflect.construct, uses_timezone),+ IntlConstructorData::new(reflect.apply, uses_timezone, canonicalize, supported),+ IntlConstructorData::new(reflect.construct, uses_timezone, canonicalize, supported),).bind(scope)?;let Some(proxy) = v8::Proxy::new(scope, original.into(), handler) else {@@ -153,7 +177,7 @@ fn intl_constructor_proxy_apply_callback<'s>(let Some(args) = webidl::parse_args::<ConstructorApplyArgs>(scope, &args) else {return;};- let applied_locale = apply_intl_constructor_defaults(scope, args.arguments, data.uses_timezone);+ let locale_list = apply_intl_constructor_defaults(scope, args.arguments, data);let invoke_args = [args.target, args.receiver, args.arguments.into()];let receiver = v8::undefined(scope);if let Some(result) = call_script_visible_function(@@ -163,7 +187,7 @@ fn intl_constructor_proxy_apply_callback<'s>(&invoke_args,"invoke Intl constructor through Reflect.apply",) {- tag_intl_default_locale(scope, result, applied_locale.as_deref());+ tag_intl_default_locale(scope, result, locale_list);rv.set(result);}}@@ -179,7 +203,7 @@ fn intl_constructor_proxy_construct_callback<'s>(let Some(args) = webidl::parse_args::<ConstructorConstructArgs>(scope, &args) else {return;};- let applied_locale = apply_intl_constructor_defaults(scope, args.arguments, data.uses_timezone);+ let locale_list = apply_intl_constructor_defaults(scope, args.arguments, data);let invoke_args = [args.target, args.arguments.into(), args.new_target];let receiver = v8::undefined(scope);if let Some(result) = call_script_visible_function(@@ -189,7 +213,7 @@ fn intl_constructor_proxy_construct_callback<'s>(&invoke_args,"invoke Intl constructor through Reflect.construct",) {- tag_intl_default_locale(scope, result, applied_locale.as_deref());+ tag_intl_default_locale(scope, result, locale_list);rv.set(result);}}@@ -197,48 +221,66 @@ fn intl_constructor_proxy_construct_callback<'s>(fn apply_intl_constructor_defaults<'s>(scope: &mut v8::PinScope<'s, '_>,arguments: v8::Local<'s, v8::Array>,- uses_timezone: bool,-) -> Option<String> {+ data: IntlConstructorData<'s>,+) -> Option<v8::Local<'s, v8::Object>> {let (locale_override, timezone_override) = current_date_locale_overrides(scope);- let mut applied_locale = None;- let locale_argument = arguments.get_index(scope, 0);- if let Some(locale) = locale_override.as_deref()- && locale_argument.is_none_or(|value| value.is_undefined())- && let Some(value) = v8_string(scope, locale)- {- let _ = arguments.set_index(scope, 0, value.into());- applied_locale = locale_override;- }- if uses_timezone+ let locale_list = locale_override.as_deref().and_then(|locale| {+ // The Proxy trap array is internal and dense. Reading beyond its+ // length would incorrectly consult the page's Array.prototype.+ let original = if arguments.length() == 0 {+ v8::undefined(scope).into()+ } else {+ arguments.get_index(scope, 0)?+ };+ let list = locales::defer_locale_list(+ scope,+ original,+ locale,+ LocaleIntrinsics::new(data.canonicalize_locales, data.supported_locales),+ )?;+ define_v8_array_data_property(scope, arguments, 0, list.into())?;+ Some(list)+ });+ if data.uses_timezone&& let Some(timezone) = timezone_override.as_deref()&& let Some(options) = intl_datetime_options_with_default_timezone(scope,- arguments.get_index(scope, 1),+ (arguments.length() > 1)+ .then(|| arguments.get_index(scope, 1))+ .flatten(),timezone,){- let _ = arguments.set_index(scope, 1, options);+ let _ = define_v8_array_data_property(scope, arguments, 1, options);}- applied_locale+ locale_list}-fn tag_intl_default_locale(- scope: &mut v8::PinScope<'_, '_>,- result: v8::Local<'_, v8::Value>,- locale: Option<&str>,+fn tag_intl_default_locale<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ result: v8::Local<'s, v8::Value>,+ locale_list: Option<v8::Local<'s, v8::Object>>,) {// Supplying the emulated default as an explicit locale can minimize a// service's resolved tag (for example Collator may report `fr`). ICU's// overridden default, and therefore Chromium, retains `fr-FR`. Tag the// instance so resolvedOptions can expose that same default identity.- if let Some(locale) = locale+ if let Some(list) = locale_list+ && let Some(locale) = get_private_value(scope, list, locales::DEFAULT_LOCALE_SLOT)&& let Ok(instance) = v8::Local::<v8::Object>::try_from(result)- && let Some(locale) = v8_string(scope, locale){- set_private_value(scope, instance, INTL_DEFAULT_LOCALE_SLOT, locale.into());+ set_private_value(scope, instance, INTL_DEFAULT_LOCALE_SLOT, locale);}}+pub(super) fn intl_date_locales_with_default<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ original: v8::Local<'s, v8::Value>,+ locale: &str,+) -> Option<v8::Local<'s, v8::Value>> {+ locales::defer_date_locale_list(scope, original, locale).map(Into::into)+}+fn intl_resolved_options_callback<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,@@ -273,10 +315,10 @@ pub(super) fn intl_datetime_options_with_default_timezone<'s>(timezone: &str,) -> Option<v8::Local<'s, v8::Value>> {if let Some(original) = original.filter(|value| !value.is_undefined()) {- if !original.is_object() {- // Let the native constructor preserve its TypeError for null and- // primitive options instead of converting them on the wrapper's- // behalf.+ if original.is_null() {+ // Native code owns when null throws (an invalid Date, for example,+ // returns before consulting options). Other primitives are boxed+ // by CoerceOptionsToObject and must receive the default too.return Some(original);}let original = original.to_object(scope)?;diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl/locales.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl/locales.rsnew file mode 100644index 000000000..73a8111d2--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl/locales.rs@@ -0,0 +1,156 @@+//! A per-call, lazy locale list. Let the native constructor decide *when* to+//! canonicalize locales: doing it in our outer Proxy trap would run page+//! getters before newTarget.prototype, or even for calls that should throw+//! without examining arguments. Date locale methods likewise return early for+//! an invalid Date. Only the native CanonicalizeLocaleList's length read opens+//! this adapter; it never eagerly inspects the page's options.++use crate::util::{+ call_script_visible_function, get_private_value, set_private_value, v8_string, v8str,+};+use crate::webidl;+use moli_webapi_declare::WebApiObject;++use super::super::bindings::callback_data;++const DATE_LOCALE_INTRINSICS_SLOT: &str = "__moliDateLocaleListIntrinsics";+pub(super) const DEFAULT_LOCALE_SLOT: &str = "__moliLocaleListDefault";++#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]+#[webapi(plain, data_properties)]+pub(super) struct LocaleIntrinsics<'s> {+ #[webidl(required)]+ pub canonicalize: v8::Local<'s, v8::Function>,+ #[webidl(required)]+ pub supported: v8::Local<'s, v8::Function>,+}++#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]+#[webapi(plain, data_properties)]+struct LocaleListData<'s> {+ requested: Option<v8::Local<'s, v8::Value>>,+ #[webidl(required)]+ fallback: v8::Local<'s, v8::Value>,+ #[webidl(required)]+ canonicalize: v8::Local<'s, v8::Function>,+ #[webidl(required)]+ supported: v8::Local<'s, v8::Function>,+}++#[derive(WebApiObject)]+#[webapi(plain)]+struct DeferredLocaleList<'s> {+ data: LocaleListData<'s>,+ #[webapi(accessor_property, getter = locale_list_length_callback, data = self.data)]+ length: (),+}++pub(super) fn defer_locale_list<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ original: v8::Local<'s, v8::Value>,+ fallback: &str,+ intrinsics: LocaleIntrinsics<'s>,+) -> Option<v8::Local<'s, v8::Object>> {+ let fallback = v8_string(scope, fallback)?;+ DeferredLocaleList::new(LocaleListData::new(+ Some(original),+ fallback.into(),+ intrinsics.canonicalize,+ intrinsics.supported,+ ))+ .bind(scope)+ .ok()+}++pub(super) fn retain_date_locale_intrinsics<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ global: v8::Local<'s, v8::Object>,+ intrinsics: LocaleIntrinsics<'s>,+) -> Result<(), moli_webapi_declare::BindError> {+ let value = intrinsics.bind(scope)?;+ set_private_value(scope, global, DATE_LOCALE_INTRINSICS_SLOT, value.into());+ Ok(())+}++pub(super) fn defer_date_locale_list<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ original: v8::Local<'s, v8::Value>,+ fallback: &str,+) -> Option<v8::Local<'s, v8::Object>> {+ let global = scope.get_current_context().global(scope);+ let data = get_private_value(scope, global, DATE_LOCALE_INTRINSICS_SLOT)?;+ let intrinsics = callback_data::<LocaleIntrinsics>(scope, data)?;+ defer_locale_list(scope, original, fallback, intrinsics)+}++fn locale_list_length_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Some(data) = callback_data::<LocaleListData>(scope, args.data()) else {+ return;+ };+ let receiver = v8::undefined(scope);+ let Some(canonical) = call_script_visible_function(+ scope,+ data.canonicalize,+ receiver.into(),+ &[data.requested.unwrap_or_else(|| receiver.into())],+ "canonicalize emulated Intl locales",+ )+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok()) else {+ return;+ };++ // Match on the native service's available locales, using only canonical+ // strings, not the page's array-like again. This records default identity+ // for resolvedOptions (e.g. Collator otherwise minimizes fr-FR to fr).+ // Actual selection remains native: preserve the ordered request list and+ // put our default last, including when a caller selects localeMatcher.+ let Some(supported) = call_script_visible_function(+ scope,+ data.supported,+ receiver.into(),+ &[canonical.into()],+ "check native Intl locale support",+ )+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok()) else {+ return;+ };+ if supported.length() == 0 {+ set_private_value(scope, args.this(), DEFAULT_LOCALE_SLOT, data.fallback);+ }+ for index in 0..canonical.length() {+ let Some(value) = canonical.get_index(scope, index) else {+ return;+ };+ let Some(key) = v8_string(scope, &index.to_string()) else {+ return;+ };+ if args.this().create_data_property(scope, key.into(), value) != Some(true) {+ return;+ }+ }+ let Some(key) = v8_string(scope, &canonical.length().to_string()) else {+ return;+ };+ if args+ .this()+ .create_data_property(scope, key.into(), data.fallback)+ != Some(true)+ {+ return;+ }+ let length = v8::Number::new(scope, f64::from(canonical.length()) + 1.0);+ // Replace the getter with an own data property. Repeated reads of this+ // internal list must never repeat the page's getters or coercion hooks.+ let key = v8str(scope, "length");+ if args+ .this()+ .create_data_property(scope, key.into(), length.into())+ == Some(true)+ {+ rv.set(length.into());+ }+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rsindex 300f23418..6d7bb4d79 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs@@ -1,5 +1,189 @@use super::*;+#[test]+fn emulation_date_constructor_converts_objects_once_with_default_hint() {+ let mut vm = new_storage_test_vm("https://date-object-conversion.test/");+ for timezone in ["UTC", "Europe/Paris", "America/New_York", "Asia/Shanghai"] {+ vm.set_timezone_override(Some(timezone));+ assert_eq!(vm.eval(r#"JSON.stringify((() => {+ const input = '2024-01-01T00:00:00';+ const expected = +new Date(2024, 0, 1);+ const calls = [];+ const objects = [new String(input), [input],+ {[Symbol.toPrimitive](hint) { calls.push(hint); return input; }},+ {valueOf() { calls.push('valueOf'); return {}; },+ toString() { calls.push('toString'); return input; }}];+ const dates = objects.map(value => +new Date(value) === expected);+ const original = new Date(1234);+ const sentinel = {};+ Object.defineProperty(original, Symbol.toPrimitive, {get() {throw sentinel;}});+ const copied = +new Date(original) === 1234;+ const primitiveValues = [1234, null, true, false, undefined];+ const numeric = primitiveValues.every(value =>+ Object.is(+new Date({[Symbol.toPrimitive]() {return value;}}), +new Date(value)));+ const errors = [+ [{[Symbol.toPrimitive]() {throw sentinel;}}, sentinel],+ [{get [Symbol.toPrimitive]() {throw sentinel;}}, sentinel],+ [{[Symbol.toPrimitive]: 1}, TypeError],+ [{[Symbol.toPrimitive]() {return {};}}, TypeError],+ [{valueOf() {return {};}, toString() {return {};}}, TypeError],+ [{[Symbol.toPrimitive]() {return Symbol();}}, TypeError],+ [{[Symbol.toPrimitive]() {return 1n;}}, TypeError]+ ].every(([value, expected]) => {+ try { new Date(value); return false; }+ catch (error) {return expected === sentinel ? error === sentinel : error instanceof expected;}+ });+ return [dates, calls, copied, numeric, errors];+ })())"#).unwrap(),+ r#"[[true,true,true,true],["default","valueOf","toString"],true,true,true]"#, "{timezone}");+ }+}++#[test]+fn emulation_locale_fallback_covers_empty_and_unmatched_lists() {+ let mut vm = new_storage_test_vm("https://intl-locale-fallback.test/");+ vm.set_locale_override(Some("fr_FR"));+ vm.set_timezone_override(Some("Europe/Paris"));+ assert_eq!(vm.eval(r#"JSON.stringify((() => {+ const constructors = ['Collator', 'DateTimeFormat', 'DisplayNames', 'DurationFormat',+ 'ListFormat', 'NumberFormat', 'PluralRules', 'RelativeTimeFormat', 'Segmenter'];+ const date = new Date('2024-01-01T00:00:00Z');+ const cases = [undefined, [], {}, ['zz-ZZ']];+ const resolved = constructors.every(name => {+ const Ctor = Intl[name];+ if (!Ctor) return true;+ return ['lookup', 'best fit'].every(localeMatcher => {+ const options = {localeMatcher, type: name === 'DisplayNames' ? 'language' : undefined};+ const expected = new Ctor(undefined, options).resolvedOptions().locale;+ return cases.every(locales => new Ctor(locales, options).resolvedOptions().locale === expected);+ });+ });+ const numbers = cases.every(locales => new Intl.NumberFormat(locales).format(1234.5) ===+ new Intl.NumberFormat('fr-FR').format(1234.5));+ const dates = ['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].every(method =>+ cases.every(locales => date[method](locales) === date[method]('fr-FR')));+ const explicit = [new Intl.Locale('en-US'), ['zz-ZZ', 'en-US'], ['en-US', 'fr-FR']].every(+ locales => new Intl.NumberFormat(locales).format(1234.5) === '1,234.5');+ return [resolved, numbers, dates, explicit];+ })())"#).unwrap(), "[true,true,true,true]");+}++#[test]+fn emulation_locale_fallback_preserves_native_observation_order() {+ let mut vm = new_storage_test_vm("https://intl-locale-coercion.test/");+ let probe = r#"JSON.stringify((() => {+ const date = new Date(0);+ return ['Collator', 'DateTimeFormat', 'NumberFormat', 'PluralRules',+ 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(name => {+ const trace = [];+ const locales = new Proxy({length: 1, 0: {toString() {trace.push('locale:string'); return 'zz-ZZ';}}}, {+ get(target, key, receiver) {trace.push(`locales:get:${String(key)}`); return Reflect.get(target, key, receiver);},+ has(target, key) {trace.push(`locales:has:${String(key)}`); return Reflect.has(target, key);}+ });+ const options = new Proxy({localeMatcher: {toString() {trace.push('matcher:string'); return 'lookup';}}}, {+ get(target, key, receiver) {trace.push(`options:get:${String(key)}`); return Reflect.get(target, key, receiver);}+ });+ if (name.startsWith('toLocale')) date[name](locales, options);+ else {+ const newTarget = new Proxy(function() {}, {get(target, key, receiver) {+ trace.push(`newTarget:get:${String(key)}`); return Reflect.get(target, key, receiver);+ }});+ Reflect.construct(Intl[name], [locales, options], newTarget);+ }+ return trace;+ });+ })())"#;+ let baseline = vm.eval(probe).unwrap();+ vm.set_locale_override(Some("fr_FR"));+ vm.set_timezone_override(Some("Europe/Paris"));+ assert_eq!(vm.eval(probe).unwrap(), baseline);+ assert_eq!(+ vm.eval(+ r#"JSON.stringify((() => {+ const sentinel = {};+ const poison = new Proxy({}, {get() {throw sentinel;}});+ const invalidDate = new Date(NaN).toLocaleString(poison, poison) === 'Invalid Date';+ let getterError = false;+ try {new Intl.NumberFormat(poison);} catch (error) {getterError = error === sentinel;}+ const invalidLocales = [null, ['en_US'], [1]].every(locales => {+ try {new Intl.NumberFormat(locales); return false;}+ catch (error) {return error instanceof TypeError || error instanceof RangeError;}+ });+ return [invalidDate, getterError, invalidLocales];+ })())"#+ )+ .unwrap(),+ "[true,true,true]"+ );+}++#[test]+fn emulation_default_arguments_do_not_read_array_prototype() {+ let mut vm = new_storage_test_vm("https://intl-private-arguments.test/");+ vm.set_locale_override(Some("fr_FR"));+ vm.set_timezone_override(Some("Europe/Paris"));+ assert_eq!(+ vm.eval(+ r#"(() => {+ const sentinel = {};+ const zero = Object.getOwnPropertyDescriptor(Array.prototype, '0');+ const one = Object.getOwnPropertyDescriptor(Array.prototype, '1');+ try {+ for (const key of ['0', '1']) Object.defineProperty(Array.prototype, key, {+ get() {throw sentinel;}, set() {throw sentinel;}, configurable: true+ });+ return new Intl.NumberFormat().resolvedOptions().locale === 'fr-FR' &&+ new Intl.DateTimeFormat().resolvedOptions().timeZone === 'Europe/Paris' &&+ new Intl.DateTimeFormat(undefined, {}).resolvedOptions().timeZone === 'Europe/Paris';+ } finally {+ if (zero) Object.defineProperty(Array.prototype, '0', zero); else delete Array.prototype[0];+ if (one) Object.defineProperty(Array.prototype, '1', one); else delete Array.prototype[1];+ }+ })()"#+ )+ .unwrap(),+ "true"+ );+}++#[test]+fn emulation_timezone_boxes_primitive_options_without_losing_defaults() {+ let mut vm = new_storage_test_vm("https://intl-primitive-options.test/");+ vm.set_timezone_override(Some("Europe/Paris"));+ assert_eq!(vm.eval(r#"JSON.stringify((() => {+ const date = new Date('2024-01-01T00:00:00Z');+ const options = [42, true, '', Symbol(), 1n];+ const zones = options.every(value =>+ new Intl.DateTimeFormat('en-US', value).resolvedOptions().timeZone === 'Europe/Paris');+ const dates = ['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].every(method =>+ options.every(value => date[method]('en-US', value) === date[method]('en-US', {timeZone: 'Europe/Paris'})));+ let nullRejected = false;+ try {new Intl.DateTimeFormat('en-US', null);} catch (error) {nullRejected = error instanceof TypeError;}+ return [zones, dates, nullRejected];+ })())"#).unwrap(), "[true,true,true]");+}++#[test]+fn emulation_date_time_first_legacy_hyphens_are_not_timezone_offsets() {+ let mut vm = new_storage_test_vm("https://date-time-first.test/");+ for timezone in ["Europe/Paris", "America/New_York", "Asia/Shanghai"] {+ vm.set_timezone_override(Some(timezone));+ assert_eq!(+ vm.eval(+ r#"JSON.stringify([+ '00:00:00 Jan-01-2024', '00:00:00 01-01-2024',+ '00:00 Jan-01-2024', '00:00:00.000 Jan-01-2024',+ '00:00:00 January-01-2024', '00:00:00 Jan-01-2024 (PST)'+ ].map(input => [Date.parse(input) === +new Date(2024, 0, 1),+ +new Date(input) === +new Date(2024, 0, 1)]))"#+ )+ .unwrap(),+ "[[true,true],[true,true],[true,true],[true,true],[true,true],[true,true]]",+ "{timezone}"+ );+ }+}+#[test]fn date_and_intl_declared_wrappers_preserve_native_method_descriptors() {let mut vm = new_storage_test_vm("https://date-intl-declarations.test/");