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 locale and timezone semantics
ldm0ae7e1067e661
diff --git a/Cargo.lock b/Cargo.lockindex c43e3cfbd..f58675d22 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -635,6 +635,16 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]+name = "combine"+version = "4.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"+dependencies = [+ "bytes",+ "memchr",+]+[[package]]name = "compact-enc-det"version = "0.1.0"@@ -2052,6 +2062,12 @@ version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "84de9d95a6d2547d9b77ee3f25fa0ee32e3c3a6484d47a55adebc0439c077992"+[[package]]+name = "jiff-tzdb"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"+[[package]]name = "jobserver"version = "0.1.34"@@ -2792,6 +2808,7 @@ dependencies = ["moli-site","moli-storage-key","moli-storage-service",+ "moli-time","moli-trace","moli-url","moli-url-policy",@@ -3115,6 +3132,7 @@ dependencies = [name = "moli-time"version = "0.1.0"dependencies = [+ "temporal_rs","time",]@@ -5075,7 +5093,10 @@ version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52"dependencies = [+ "combine",+ "jiff-tzdb","tinystr",+ "tzif","zerotrie","zerovec","zoneinfo64",@@ -5382,6 +5403,15 @@ version = "1.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+[[package]]+name = "tzif"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0376dfa52cce372f3b095010fd064fb850a5d8fbfd5be8b0ffa3d64eeab5a5d"+dependencies = [+ "combine",+]+[[package]]name = "uluru"version = "3.1.0"diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex ce53ff11d..c5fa6d0fe 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -25,6 +25,19 @@ observed, but it does not replace the executable probe when one can be run. IfChromium cannot be tested, document that limitation explicitly instead ofpresenting an inferred expectation as verified behavior.+The detailed `emulation-storage` locale/timezone matrix was calibrated on+2026-09-01 against Debian Chromium 145.0.7632.116. In addition to resolved+locale, timezone, local getters, and formatted strings, the executable probe+now covers Intl and Date subclass `newTarget`, constructor reflection, options+accessor count/receiver identity, winter/summer and DST-gap Date construction,+local versus date-only/offset parsing, local setters with millisecond+preservation, and explicit locale/timezone precedence. The invalid-zone probe+is deliberately performed before installing a valid override: Chromium 145+returns `InvalidParams` on initial admission, while its active override+`change()` path silently retains the old zone for an invalid replacement.+Moli additionally locks down the latter state-preservation case in a focused+Rust protocol test.+For example, Chromium resolves Playwright`page.goto(..., wait_until="load")` after `Page.loadEventFired` but before thelater `Page.frameStoppedLoading` delivery. A smoke scenario that starts a new@@ -401,7 +414,7 @@ Runner layout:transformed single and nested iframe hover, click, wheel, child-local eventcoordinates, exact used frame viewport propagation, and Moli's nested-frameUA scrollbar routing boundary.-- `groups/emulation_storage.py`: viewport and Playwright screenshot-clip boundary, storage/cookie isolation, IndexedDB baseline, and browser-context profile overrides.+- `groups/emulation_storage.py`: viewport and Playwright screenshot-clip boundary, detailed geolocation plus locale/timezone runtime overrides, storage/cookie isolation, IndexedDB baseline, and browser-context profile overrides.- `groups/media_error.py`: process-isolated HTMLMediaElement MediaError lifecycle contracts.- `groups/target_semantics.py`: raw Target-domain identity, attachment,activation, visibility, and lifecycle contracts calibrated against Chromium.diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py b/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.pyindex 785d14088..7e3d14c87 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py@@ -4,15 +4,16 @@ import jsonimport timeimport urllib.parseimport urllib.request-from typing import Any+from typing import Any, Awaitable-from ..assertions import SmokeError, assert_equal, record+from ..assertions import SmokeError, assert_equal, record, record_contractfrom ..png_image import decode_pngasync def run_emulation_storage_group(browser: Any, fixture: str, results: list[dict[str, Any]]) -> None:await run_playwright_screenshot_clip_surface(browser, fixture, results)await run_geolocation_override_smoke(browser, fixture, results)+ await run_locale_timezone_runtime_surface_smoke(browser, fixture, results)await run_storage_and_cookie_isolation_smoke(browser, fixture, results)await run_indexeddb_baseline_smoke(browser, fixture, results)await run_browser_context_profile_smoke(browser, fixture, results)@@ -118,6 +119,386 @@ async def _read_geolocation(page: Any) -> dict[str, Any]:)+async def run_locale_timezone_runtime_surface_smoke(+ browser: Any,+ fixture: str,+ results: list[dict[str, Any]],+) -> None:+ context = await browser.new_context()+ try:+ page = await context.new_page()+ await page.goto(f"{fixture}/plain", wait_until="load", timeout=10_000)+ baseline = await _read_locale_timezone_runtime(page)+ cdp = await context.new_cdp_session(page)+ try:+ await cdp.send("Emulation.setLocaleOverride", {"locale": "fr-FR"})+ invalid_timezone_error = await _expect_protocol_error(+ cdp.send(+ "Emulation.setTimezoneOverride",+ {"timezoneId": "Mars/Olympus"},+ ),+ "invalid timezone override",+ )+ if "invalid timezone" not in invalid_timezone_error.lower():+ raise SmokeError(+ "invalid timezone returned an unexpected protocol error: "+ f"{invalid_timezone_error}"+ )+ after_invalid_timezone = await _read_locale_timezone_runtime(page)+ assert_equal(+ [+ after_invalid_timezone.get("timezone"),+ after_invalid_timezone.get("winter"),+ ],+ [baseline.get("timezone"), baseline.get("winter")],+ "rejected initial timezone override leaves native timezone state unchanged",+ )+ await cdp.send(+ "Emulation.setTimezoneOverride",+ {"timezoneId": "Europe/Paris"},+ )+ runtime = await _read_locale_timezone_runtime(page)+ assert_equal(+ runtime.get("navigatorLanguage"),+ baseline.get("navigatorLanguage"),+ "locale override does not impersonate Accept-Language",+ )+ assert_equal(+ runtime.get("intlLocales"),+ {+ "Collator": "fr-FR",+ "DateTimeFormat": "fr-FR",+ "ListFormat": "fr-FR",+ "NumberFormat": "fr-FR",+ "PluralRules": "fr-FR",+ "RelativeTimeFormat": "fr-FR",+ "Segmenter": "fr-FR",+ },+ "locale override drives default Intl constructors",+ )+ assert_equal(runtime.get("timezone"), "Europe/Paris", "Intl timezone override")+ assert_equal(runtime.get("frenchDecimal"), True, "Intl locale formatting override")+ assert_equal(+ runtime.get("winter"),+ [-60, 2024, 0, 1, 1, 1, 0, 0, 0],+ "winter Date timezone override",+ )+ assert_equal(+ runtime.get("summer"),+ [-120, 2024, 6, 1, 1, 2],+ "summer Date timezone override",+ )+ assert_equal(+ runtime.get("dateBoundary"),+ [2024, 0, 1, 1, 0, 30],+ "timezone override crosses the local calendar boundary",+ )+ assert_equal(+ runtime.get("localeDateStrings"),+ ["01/01/2024 01:00:00", "01/01/2024", "01:00:00"],+ "Date locale methods consume both overrides",+ )+ assert_equal(+ runtime.get("explicitOptions"),+ ["en-US", "UTC"],+ "explicit Intl options win over emulation defaults",+ )+ assert_equal(+ runtime.get("invalidOptions"),+ "TypeError",+ "Intl option validation survives default injection",+ )+ assert_equal(+ runtime.get("intlConstruction"),+ [True, True, True, "fr-FR"],+ "Intl constructor proxy preserves subclass newTarget",+ )+ assert_equal(+ runtime.get("intlOptionAccess"),+ [1, True, "Europe/Paris"],+ "Intl timezone default preserves option accessor semantics",+ )+ assert_equal(+ runtime.get("dateConstruction"),+ [+ "2023-12-31T23:00:00.000Z",+ "2024-06-30T22:00:00.000Z",+ "2024-03-31T01:30:00.000Z",+ True,+ True,+ ],+ "Date local constructors and derived newTarget use the emulated timezone",+ )+ assert_equal(+ runtime.get("dateParsing"),+ [+ "2023-12-31T23:00:00.000Z",+ "2023-12-31T23:00:00.000Z",+ "2024-01-01T00:00:00.000Z",+ "2023-12-31T22:00:00.000Z",+ ],+ "Date local parsing distinguishes local, date-only, and offset forms",+ )+ assert_equal(+ runtime.get("dateSetters"),+ [+ 1704108896789,+ "2024-01-01T11:34:56.789Z",+ "2024-03-31T01:30:00.000Z",+ "2023-12-31T23:00:00.000Z",+ ],+ "Date local setters preserve milliseconds and DST disambiguation",+ )+ assert_equal(+ runtime.get("explicitDateLocalePreserved"),+ True,+ "Date locale methods preserve explicit locale and timezone options",+ )+ assert_equal(+ runtime.get("constructorReflection"),+ ["Date", 7, "function", "NumberFormat", 0, "function"],+ "Date and Intl constructor reflection remains native-compatible",+ )+ date_strings = runtime.get("dateStrings")+ if not isinstance(date_strings, list) or len(date_strings) != 3:+ raise SmokeError(f"Date string override returned an invalid shape: {date_strings!r}")+ expected_prefixes = (+ "Mon Jan 01 2024 01:00:00 GMT+0100",+ "Mon Jan 01 2024",+ "01:00:00 GMT+0100",+ )+ for value, prefix in zip(date_strings, expected_prefixes, strict=True):+ if not isinstance(value, str) or not value.startswith(prefix):+ raise SmokeError(+ f"Date string override: expected prefix {prefix!r}, got {value!r}"+ )++ await cdp.send("Emulation.setLocaleOverride", {"locale": ""})+ locale_cleared = await _read_locale_timezone_runtime(page)+ assert_equal(+ locale_cleared.get("intlLocales"),+ baseline.get("intlLocales"),+ "locale override can be cleared independently",+ )+ assert_equal(+ [locale_cleared.get("timezone"), locale_cleared.get("winter")],+ ["Europe/Paris", runtime.get("winter")],+ "clearing locale preserves timezone Date semantics",+ )++ await cdp.send("Emulation.setLocaleOverride", {"locale": "fr-FR"})+ await cdp.send("Emulation.setTimezoneOverride", {"timezoneId": ""})+ timezone_cleared = await _read_locale_timezone_runtime(page)+ assert_equal(+ timezone_cleared.get("intlLocales"),+ runtime.get("intlLocales"),+ "clearing timezone preserves locale defaults",+ )+ assert_equal(+ [timezone_cleared.get("timezone"), timezone_cleared.get("winter")],+ [baseline.get("timezone"), baseline.get("winter")],+ "timezone override can be cleared independently",+ )++ await cdp.send(+ "Emulation.setTimezoneOverride",+ {"timezoneId": "Europe/Paris"},+ )+ await page.reload(wait_until="load", timeout=10_000)+ assert_equal(+ await _read_locale_timezone_runtime(page),+ runtime,+ "locale/timezone overrides survive navigation",+ )+ await cdp.send("Emulation.setLocaleOverride", {"locale": ""})+ await cdp.send("Emulation.setTimezoneOverride", {"timezoneId": ""})+ assert_equal(+ await _read_locale_timezone_runtime(page),+ baseline,+ "clearing locale/timezone overrides restores native defaults",+ )+ record_contract(+ results,+ "locale_timezone_runtime_surfaces",+ contract=(+ "Locale and timezone overrides drive default Intl and local Date "+ "surfaces, survive navigation, remain independently clearable, and "+ "reject an invalid timezone without changing the prior state."+ ),+ source="Debian Chromium 145 CDP executable oracle",+ commands=[+ "Emulation.setLocaleOverride",+ "Emulation.setTimezoneOverride",+ "Runtime.evaluate",+ "Page.reload",+ ],+ observed={+ "locale": "fr-FR",+ "timezone": "Europe/Paris",+ "winterOffsetMinutes": -60,+ "summerOffsetMinutes": -120,+ "invalidTimezoneRejected": True,+ "intlSubclassNewTarget": True,+ "dateLocalConstructionParsingAndSetters": True,+ },+ )+ finally:+ await cdp.detach()+ finally:+ await context.close()+++async def _read_locale_timezone_runtime(page: Any) -> dict[str, Any]:+ return await page.evaluate(+ """() => {+ const winter = new Date('2024-01-01T00:00:00Z');+ const summer = new Date('2024-07-01T00:00:00Z');+ const dateBoundary = new Date('2023-12-31T23:30:00Z');+ const intlConstructors = [+ 'Collator',+ 'DateTimeFormat',+ 'ListFormat',+ 'NumberFormat',+ 'PluralRules',+ 'RelativeTimeFormat',+ 'Segmenter',+ ];+ let timeZoneReads = 0;+ let getterReceiverPreserved = false;+ const options = {+ get timeZone() {+ timeZoneReads += 1;+ getterReceiverPreserved = this === options;+ return undefined;+ },+ };+ const optionFormat = new Intl.DateTimeFormat(undefined, options);+ class DerivedNumberFormat extends Intl.NumberFormat {}+ const derivedNumberFormat = new DerivedNumberFormat();+ class DerivedDate extends Date {}+ const derivedDate = new DerivedDate(2024, 0, 1);+ const setter = new Date('2024-01-01T00:00:00Z');+ const setterResult = setter.setHours(12, 34, 56, 789);+ const gapSetter = new Date('2024-03-31T00:30:00Z');+ gapSetter.setHours(2, 30, 0, 0);+ const revived = new Date(NaN);+ revived.setFullYear(2024, 0, 1);+ const explicitLocaleOptions = {+ timeZone: 'UTC', year: 'numeric', month: '2-digit', day: '2-digit',+ hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',+ };+ return {+ navigatorLanguage: navigator.language,+ intlLocales: Object.fromEntries(intlConstructors.map(name => [+ name,+ new Intl[name]().resolvedOptions().locale,+ ])),+ timezone: new Intl.DateTimeFormat().resolvedOptions().timeZone,+ frenchDecimal: new Intl.NumberFormat().format(1.5).endsWith(',5'),+ winter: [+ winter.getTimezoneOffset(),+ winter.getFullYear(),+ winter.getMonth(),+ winter.getDate(),+ winter.getDay(),+ winter.getHours(),+ winter.getMinutes(),+ winter.getSeconds(),+ winter.getMilliseconds(),+ ],+ summer: [+ summer.getTimezoneOffset(),+ summer.getFullYear(),+ summer.getMonth(),+ summer.getDate(),+ summer.getDay(),+ summer.getHours(),+ ],+ dateBoundary: [+ dateBoundary.getFullYear(),+ dateBoundary.getMonth(),+ dateBoundary.getDate(),+ dateBoundary.getDay(),+ dateBoundary.getHours(),+ dateBoundary.getMinutes(),+ ],+ dateStrings: [+ winter.toString(),+ winter.toDateString(),+ winter.toTimeString(),+ ],+ localeDateStrings: [+ winter.toLocaleString(),+ winter.toLocaleDateString(),+ winter.toLocaleTimeString(),+ ],+ explicitOptions: [+ new Intl.NumberFormat('en-US').resolvedOptions().locale,+ new Intl.DateTimeFormat('en-US', {timeZone: 'UTC'})+ .resolvedOptions().timeZone,+ ],+ invalidOptions: (() => {+ try {+ new Intl.DateTimeFormat(undefined, null);+ return 'accepted';+ } catch (error) {+ return error.name;+ }+ })(),+ intlConstruction: [+ derivedNumberFormat instanceof DerivedNumberFormat,+ derivedNumberFormat instanceof Intl.NumberFormat,+ Object.getPrototypeOf(derivedNumberFormat) === DerivedNumberFormat.prototype,+ derivedNumberFormat.resolvedOptions().locale,+ ],+ intlOptionAccess: [+ timeZoneReads,+ getterReceiverPreserved,+ optionFormat.resolvedOptions().timeZone,+ ],+ dateConstruction: [+ new Date(2024, 0, 1).toISOString(),+ new Date(2024, 6, 1).toISOString(),+ new Date(2024, 2, 31, 2, 30).toISOString(),+ derivedDate instanceof DerivedDate,+ Object.getPrototypeOf(derivedDate) === DerivedDate.prototype,+ ],+ dateParsing: [+ new Date('2024-01-01T00:00:00').toISOString(),+ new Date(Date.parse('2024-01-01T00:00:00')).toISOString(),+ new Date('2024-01-01').toISOString(),+ new Date('2024-01-01T00:00:00+02:00').toISOString(),+ ],+ dateSetters: [+ setterResult,+ setter.toISOString(),+ gapSetter.toISOString(),+ revived.toISOString(),+ ],+ explicitDateLocalePreserved:+ new Date(0).toLocaleString('en-US', explicitLocaleOptions) ===+ new Intl.DateTimeFormat('en-US', explicitLocaleOptions).format(new Date(0)),+ constructorReflection: [+ Date.name,+ Date.length,+ typeof Date.UTC,+ Intl.NumberFormat.name,+ Intl.NumberFormat.length,+ typeof Intl.NumberFormat.supportedLocalesOf,+ ],+ };+ }"""+ )+++async def _expect_protocol_error(awaitable: Awaitable[Any], label: str) -> str:+ try:+ await awaitable+ except Exception as error: # Playwright exposes protocol failures as Error.+ return str(error)+ raise SmokeError(f"{label}: expected a protocol error")++async def run_storage_and_cookie_isolation_smoke(browser: Any, fixture: str, results: list[dict[str, Any]]) -> None:context_a = await browser.new_context()context_b = await browser.new_context()diff --git a/moli-protocol/Cargo.toml b/moli-protocol/Cargo.tomlindex 70af91bf8..d7ea42cbf 100644--- a/moli-protocol/Cargo.toml+++ b/moli-protocol/Cargo.toml@@ -25,6 +25,7 @@ moli-css-parse = { path = "../moli-css-parse" }moli-shared-worker = { path = "../moli-shared-worker" }moli-site = { path = "../moli-site" }moli-storage-key = { path = "../moli-storage-key" }+moli-time = { path = "../moli-time" }moli-trace = { path = "../moli-trace" }moli-url = { path = "../moli-url" }moli-url-policy = { path = "../moli-url-policy" }diff --git a/moli-protocol/src/domains/emulation.rs b/moli-protocol/src/domains/emulation.rsindex b185a07bf..a45d599ce 100644--- a/moli-protocol/src/domains/emulation.rs+++ b/moli-protocol/src/domains/emulation.rs@@ -621,6 +621,9 @@ fn start_timezone_override_command(let trimmed = params.timezone_id.trim();(!trimmed.is_empty()).then(|| trimmed.to_owned())};+ if let Err(message) = validate_timezone_override(timezone_override.as_deref()) {+ return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(-32602, message));+ }if let Err(message) = conn.set_devtools_timezone_override_for_session_owner(cmd.session_id, timezone_override.clone()){@@ -1817,6 +1820,8 @@ async fn execute_devtools_set_timezone_override_command_async(conn: &mut CdpConnection,command: DevToolsSetTimezoneOverrideCommand,) -> Result<DevToolsCommandResult, DevToolsError> {+ validate_timezone_override(command.timezone.as_deref())+ .map_err(|message| DevToolsError::new(DevToolsErrorKind::InvalidArgument, message))?;if !command.target_ids.is_empty() {return execute_devtools_set_timezone_override_for_targets(conn, command).await;}@@ -1829,6 +1834,13 @@ async fn execute_devtools_set_timezone_override_command_async())}+fn validate_timezone_override(timezone: Option<&str>) -> Result<(), &'static str> {+ if timezone.is_some_and(|timezone| !moli_time::is_valid_time_zone_identifier(timezone)) {+ return Err("Invalid timezone id");+ }+ Ok(())+}+async fn execute_devtools_set_timezone_override_for_targets(conn: &mut CdpConnection,command: DevToolsSetTimezoneOverrideCommand,diff --git a/moli-protocol/src/domains/emulation/tests.rs b/moli-protocol/src/domains/emulation/tests.rsindex 2ae558aea..3b61a7f99 100644--- a/moli-protocol/src/domains/emulation/tests.rs+++ b/moli-protocol/src/domains/emulation/tests.rs@@ -1120,6 +1120,40 @@ async fn set_timezone_override_without_loaded_browser_context_errors() {ctx.expect_error(7, -31998, "BrowserContextNotLoaded");}+#[tokio::test(flavor = "multi_thread")]+async fn invalid_timezone_override_is_rejected_without_replacing_active_state() {+ let mut ctx = TestContext::new();+ load_session_page_for_pending_emulation_test(&mut ctx).await;++ ctx.process_async(json!({+ "id": 7_001,+ "method": "Emulation.setTimezoneOverride",+ "sessionId": "SID-1",+ "params": { "timezoneId": "Europe/Paris" }+ }))+ .await;+ ctx.expect_result(7_001, json!({}), Some("SID-1"));++ ctx.process_async(json!({+ "id": 7_002,+ "method": "Emulation.setTimezoneOverride",+ "sessionId": "SID-1",+ "params": { "timezoneId": "Mars/Olympus" }+ }))+ .await;+ ctx.expect_error(7_002, -32602, "Invalid timezone id");+ assert_eq!(+ ctx.conn+ .browser_context+ .as_ref()+ .expect("browser context")+ .active_page_target()+ .effective_policy()+ .timezone_override(),+ Some("Europe/Paris")+ );+}+#[tokio::test(flavor = "multi_thread")]async fn multi_session_locale_and_timezone_claims_match_chromium() {const LOCALE: &str = "Emulation.setLocaleOverride";diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rsindex 11753cfe7..02079db99 100644--- a/moli-renderer-v8/src/context_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap.rs@@ -154,9 +154,6 @@ pub(crate) use selection_surface::{selection_value_for_window, sync_selection_owner_document_for_window,};pub(crate) use shared::{dom_time_since_origin_millis, unix_epoch_millis};-pub(crate) use window_runtime::{- set_date_locale_override_for_current_context, set_date_timezone_override_for_current_context,-};mod specs;mod stream_adapter;mod stream_objects;diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rsindex eee903092..1e71cddbe 100644--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs@@ -1,154 +1,27 @@-use super::window_runtime::{- current_date_locale_overrides, date_to_locale_date_string_callback,- date_to_locale_string_callback, date_to_locale_time_string_callback,-};use super::*;-use crate::util::{call_script_visible_function, get_private_value, set_private_value};-use anyhow::{Result, anyhow};-use moli_webapi_declare::WebApiObject;+use crate::util::{get_private_value, set_private_value};+use anyhow::Result;-const ORIGINAL_INTL_DATETIME_FORMAT_RESOLVED_OPTIONS_SLOT: &str =- "__moliOriginalIntlDateTimeFormatResolvedOptions";+mod date;+mod intl;+mod overrides;-#[derive(Default, WebApiObject)]-#[webapi(fragment, prototype = "Date")]-struct DateLocalePrototypeDeclaration {- #[webapi(method, length = 0, callback = date_to_locale_string_callback)]- to_locale_string: (),- #[webapi(method, length = 0, callback = date_to_locale_date_string_callback)]- to_locale_date_string: (),- #[webapi(method, length = 0, callback = date_to_locale_time_string_callback)]- to_locale_time_string: (),-}--#[derive(Default, WebApiObject)]-#[webapi(fragment, prototype = "Intl.DateTimeFormat")]-struct IntlDateTimeFormatPrototypeDeclaration {- #[webapi(- method = "resolvedOptions",- length = 0,- callback = intl_date_time_format_resolved_options_callback- )]- resolved_options: (),-}+const DATE_LOCALE_RUNTIME_INSTALLED_SLOT: &str = "__moliDateLocaleRuntimeInstalled";pub(super) fn install_date_locale_runtime_state<'s>(scope: &mut v8::PinScope<'s, '_>,global: v8::Local<'s, v8::Object>,) -> Result<()> {- let Some(date_ctor_value) = global.get(scope, v8str(scope, "Date").into()) else {- return Ok(());- };- let Ok(date_ctor) = v8::Local::<v8::Object>::try_from(date_ctor_value) else {- return Ok(());- };- let Some(date_proto_value) = date_ctor.get(scope, v8str(scope, "prototype").into()) else {- return Ok(());- };- let Ok(date_proto) = v8::Local::<v8::Object>::try_from(date_proto_value) else {- return Ok(());- };-- DateLocalePrototypeDeclaration::default()- .initialize(scope, date_proto)- .map_err(|err| anyhow!("failed to initialize Date locale methods: {err}"))?;- install_intl_date_time_format_resolved_options(scope, global)-}--fn install_intl_date_time_format_resolved_options<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,-) -> Result<()> {- let Some(intl_value) = global.get(scope, v8str(scope, "Intl").into()) else {- return Ok(());- };- let Ok(intl) = v8::Local::<v8::Object>::try_from(intl_value) else {+ if get_private_value(scope, global, DATE_LOCALE_RUNTIME_INSTALLED_SLOT).is_some() {return Ok(());- };- let Some(date_time_format_value) = intl.get(scope, v8str(scope, "DateTimeFormat").into())- else {- return Ok(());- };- let Ok(date_time_format) = v8::Local::<v8::Object>::try_from(date_time_format_value) else {- return Ok(());- };- let Some(prototype_value) = date_time_format.get(scope, v8str(scope, "prototype").into())- else {- return Ok(());- };- let Ok(prototype) = v8::Local::<v8::Object>::try_from(prototype_value) else {- return Ok(());- };- if get_private_value(- scope,- prototype,- ORIGINAL_INTL_DATETIME_FORMAT_RESOLVED_OPTIONS_SLOT,- )- .is_none()- && let Some(original) = prototype.get(scope, v8str(scope, "resolvedOptions").into())- {- set_private_value(- scope,- prototype,- ORIGINAL_INTL_DATETIME_FORMAT_RESOLVED_OPTIONS_SLOT,- original,- );- }- IntlDateTimeFormatPrototypeDeclaration::default()- .initialize(scope, prototype)- .map_err(|err| anyhow!("failed to initialize Intl.DateTimeFormat locale methods: {err}"))-}--fn intl_date_time_format_resolved_options_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(original) = original_intl_date_time_format_resolved_options(scope) else {- rv.set_undefined();- return;- };- let Some(result) = call_script_visible_function(- scope,- original,- args.this().into(),- &[],- "Intl.DateTimeFormat.resolvedOptions",- ) else {- return;- };- let Ok(options) = v8::Local::<v8::Object>::try_from(result) else {- rv.set(result);- return;- };- let (locale_override, timezone_override) = current_date_locale_overrides(scope);- if let Some(locale) = locale_override.as_deref()- && let Some(value) = v8_string(scope, locale)- {- let _ = options.set(scope, v8str(scope, "locale").into(), value.into());- }- if let Some(timezone) = timezone_override.as_deref()- && let Some(value) = v8_string(scope, timezone)- {- let _ = options.set(scope, v8str(scope, "timeZone").into(), value.into());}- rv.set(options.into());-}--fn original_intl_date_time_format_resolved_options<'s>(- scope: &mut v8::PinScope<'s, '_>,-) -> Option<v8::Local<'s, v8::Function>> {- let global = scope.get_current_context().global(scope);- let intl = global.get(scope, v8str(scope, "Intl").into())?;- let intl = v8::Local::<v8::Object>::try_from(intl).ok()?;- let date_time_format = intl.get(scope, v8str(scope, "DateTimeFormat").into())?;- let date_time_format = v8::Local::<v8::Object>::try_from(date_time_format).ok()?;- let prototype = date_time_format.get(scope, v8str(scope, "prototype").into())?;- let prototype = v8::Local::<v8::Object>::try_from(prototype).ok()?;- let original = get_private_value(+ date::install_date_runtime_state(scope, global)?;+ intl::install_intl_default_override_constructors(scope, global)?;+ set_private_value(scope,- prototype,- ORIGINAL_INTL_DATETIME_FORMAT_RESOLVED_OPTIONS_SLOT,- )?;- v8::Local::<v8::Function>::try_from(original).ok()+ global,+ DATE_LOCALE_RUNTIME_INSTALLED_SLOT,+ v8::Boolean::new(scope, true).into(),+ );+ Ok(())}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rsnew file mode 100644index 000000000..83fee24b7--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rs@@ -0,0 +1,218 @@+use super::*;+use crate::util::{callback_data_index_value, get_private_value, set_private_value};+use anyhow::{Result, anyhow};+use moli_webapi_declare::WebApiObject;++mod constructor;+mod prototype;++use constructor::{install_date_constructor_proxy, install_date_parse_override};+use prototype::{+ date_get_timezone_offset_callback, date_local_field_callback, date_local_setter_callback,+ date_to_date_string_callback, date_to_locale_date_string_callback,+ date_to_locale_string_callback, date_to_locale_time_string_callback, date_to_string_callback,+ date_to_time_string_callback,+};++const RETAINED_DATE_INTRINSICS_SLOT: &str = "__moliRetainedDateIntrinsics";+#[derive(Clone, Copy)]+#[repr(u32)]+enum DateIntrinsic {+ Parse,+ Utc,+ Now,+ ToString,+ ToDateString,+ ToTimeString,+ ToLocaleString,+ ToLocaleDateString,+ ToLocaleTimeString,+ GetTimezoneOffset,+ GetFullYear,+ GetMonth,+ GetDate,+ GetDay,+ GetHours,+ GetMinutes,+ GetSeconds,+ GetMilliseconds,+ SetDate,+ SetFullYear,+ SetHours,+ SetMilliseconds,+ SetMinutes,+ SetMonth,+ SetSeconds,+ SetTime,+ SetUtcDate,+ SetUtcFullYear,+ SetUtcHours,+ SetUtcMilliseconds,+ SetUtcMinutes,+ SetUtcMonth,+ SetUtcSeconds,+}++impl DateIntrinsic {+ const COUNT: i32 = Self::SetUtcSeconds as i32 + 1;++ const fn index(self) -> u32 {+ self as u32+ }+}++const DATE_STATIC_INTRINSICS: &[(DateIntrinsic, &str)] = &[+ (DateIntrinsic::Parse, "parse"),+ (DateIntrinsic::Utc, "UTC"),+ (DateIntrinsic::Now, "now"),+];++const DATE_PROTOTYPE_INTRINSICS: &[(DateIntrinsic, &str)] = &[+ (DateIntrinsic::ToString, "toString"),+ (DateIntrinsic::ToDateString, "toDateString"),+ (DateIntrinsic::ToTimeString, "toTimeString"),+ (DateIntrinsic::ToLocaleString, "toLocaleString"),+ (DateIntrinsic::ToLocaleDateString, "toLocaleDateString"),+ (DateIntrinsic::ToLocaleTimeString, "toLocaleTimeString"),+ (DateIntrinsic::GetTimezoneOffset, "getTimezoneOffset"),+ (DateIntrinsic::GetFullYear, "getFullYear"),+ (DateIntrinsic::GetMonth, "getMonth"),+ (DateIntrinsic::GetDate, "getDate"),+ (DateIntrinsic::GetDay, "getDay"),+ (DateIntrinsic::GetHours, "getHours"),+ (DateIntrinsic::GetMinutes, "getMinutes"),+ (DateIntrinsic::GetSeconds, "getSeconds"),+ (DateIntrinsic::GetMilliseconds, "getMilliseconds"),+ (DateIntrinsic::SetDate, "setDate"),+ (DateIntrinsic::SetFullYear, "setFullYear"),+ (DateIntrinsic::SetHours, "setHours"),+ (DateIntrinsic::SetMilliseconds, "setMilliseconds"),+ (DateIntrinsic::SetMinutes, "setMinutes"),+ (DateIntrinsic::SetMonth, "setMonth"),+ (DateIntrinsic::SetSeconds, "setSeconds"),+ (DateIntrinsic::SetTime, "setTime"),+ (DateIntrinsic::SetUtcDate, "setUTCDate"),+ (DateIntrinsic::SetUtcFullYear, "setUTCFullYear"),+ (DateIntrinsic::SetUtcHours, "setUTCHours"),+ (DateIntrinsic::SetUtcMilliseconds, "setUTCMilliseconds"),+ (DateIntrinsic::SetUtcMinutes, "setUTCMinutes"),+ (DateIntrinsic::SetUtcMonth, "setUTCMonth"),+ (DateIntrinsic::SetUtcSeconds, "setUTCSeconds"),+];++#[derive(Default, WebApiObject)]+#[webapi(fragment, prototype = "Date")]+struct DateLocalePrototypeDeclaration {+ #[webapi(method = "toString", length = 0, callback = date_to_string_callback)]+ to_string: (),+ #[webapi(method = "toDateString", length = 0, callback = date_to_date_string_callback)]+ to_date_string: (),+ #[webapi(method = "toTimeString", length = 0, callback = date_to_time_string_callback)]+ to_time_string: (),+ #[webapi(method, length = 0, callback = date_to_locale_string_callback)]+ to_locale_string: (),+ #[webapi(method, length = 0, callback = date_to_locale_date_string_callback)]+ to_locale_date_string: (),+ #[webapi(method, length = 0, callback = date_to_locale_time_string_callback)]+ to_locale_time_string: (),+ #[webapi(+ method = "getTimezoneOffset",+ length = 0,+ callback = date_get_timezone_offset_callback+ )]+ get_timezone_offset: (),+ #[webapi(method = "getFullYear", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 0))]+ get_full_year: (),+ #[webapi(method = "getMonth", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 1))]+ get_month: (),+ #[webapi(method = "getDate", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 2))]+ get_date: (),+ #[webapi(method = "getDay", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 3))]+ get_day: (),+ #[webapi(method = "getHours", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 4))]+ get_hours: (),+ #[webapi(method = "getMinutes", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 5))]+ get_minutes: (),+ #[webapi(method = "getSeconds", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 6))]+ get_seconds: (),+ #[webapi(method = "getMilliseconds", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 7))]+ get_milliseconds: (),+ #[webapi(method = "setDate", length = 1, callback = date_local_setter_callback, data = callback_data_index_value(scope, 0))]+ set_date: (),+ #[webapi(method = "setFullYear", length = 3, callback = date_local_setter_callback, data = callback_data_index_value(scope, 1))]+ set_full_year: (),+ #[webapi(method = "setHours", length = 4, callback = date_local_setter_callback, data = callback_data_index_value(scope, 2))]+ set_hours: (),+ #[webapi(method = "setMilliseconds", length = 1, callback = date_local_setter_callback, data = callback_data_index_value(scope, 3))]+ set_milliseconds: (),+ #[webapi(method = "setMinutes", length = 3, callback = date_local_setter_callback, data = callback_data_index_value(scope, 4))]+ set_minutes: (),+ #[webapi(method = "setMonth", length = 2, callback = date_local_setter_callback, data = callback_data_index_value(scope, 5))]+ set_month: (),+ #[webapi(method = "setSeconds", length = 2, callback = date_local_setter_callback, data = callback_data_index_value(scope, 6))]+ set_seconds: (),+}++pub(super) fn install_date_runtime_state<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ global: v8::Local<'s, v8::Object>,+) -> Result<()> {+ if get_private_value(scope, global, RETAINED_DATE_INTRINSICS_SLOT).is_some() {+ return Ok(());+ }+ let Some(date_ctor_value) = global.get(scope, v8str(scope, "Date").into()) else {+ return Ok(());+ };+ let Ok(date_ctor) = v8::Local::<v8::Function>::try_from(date_ctor_value) else {+ return Ok(());+ };+ let Some(date_proto_value) = date_ctor.get(scope, v8str(scope, "prototype").into()) else {+ return Ok(());+ };+ let Ok(date_proto) = v8::Local::<v8::Object>::try_from(date_proto_value) else {+ return Ok(());+ };++ let Some(retained) = retain_date_intrinsics(scope, date_ctor, date_proto) else {+ return Ok(());+ };+ set_private_value(+ scope,+ global,+ RETAINED_DATE_INTRINSICS_SLOT,+ retained.into(),+ );+ DateLocalePrototypeDeclaration::default()+ .initialize(scope, date_proto)+ .map_err(|err| anyhow!("failed to initialize Date locale methods: {err}"))?;+ install_date_parse_override(scope, date_ctor)?;+ install_date_constructor_proxy(scope, global, date_ctor, date_proto)+}++fn retain_date_intrinsics<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ constructor: v8::Local<'s, v8::Function>,+ prototype: v8::Local<'s, v8::Object>,+) -> Option<v8::Local<'s, v8::Array>> {+ let retained = v8::Array::new(scope, DateIntrinsic::COUNT);+ for &(intrinsic, name) in DATE_STATIC_INTRINSICS {+ let value = constructor.get(scope, v8str(scope, name).into())?;+ let _ = retained.set_index(scope, intrinsic.index(), value);+ }+ for &(intrinsic, name) in DATE_PROTOTYPE_INTRINSICS {+ let value = prototype.get(scope, v8str(scope, name).into())?;+ let _ = retained.set_index(scope, intrinsic.index(), value);+ }+ Some(retained)+}++fn original_date_method<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ intrinsic: DateIntrinsic,+) -> Option<v8::Local<'s, v8::Function>> {+ let global = scope.get_current_context().global(scope);+ get_private_value(scope, global, RETAINED_DATE_INTRINSICS_SLOT)+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())+ .and_then(|retained| retained.get_index(scope, intrinsic.index()))+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+}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.rsnew file mode 100644index 000000000..9e993a75d--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rs@@ -0,0 +1,375 @@+use super::*;+use crate::util::call_script_visible_function;+use anyhow::{Result, anyhow};++use super::super::overrides::current_date_locale_overrides;++pub(super) fn install_date_parse_override<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ constructor: v8::Local<'s, v8::Function>,+) -> Result<()> {+ let Some(original) = original_date_method(scope, DateIntrinsic::Parse) else {+ return Ok(());+ };+ let Some(wrapper) = v8::Function::builder(date_parse_callback)+ .data(original.into())+ .length(1)+ .build(scope)+ else {+ return Err(anyhow!("failed to create Date.parse override"));+ };+ let name = v8str(scope, "parse");+ wrapper.set_name(name);+ let _ = constructor.set(scope, name.into(), wrapper.into());+ Ok(())+}++pub(super) fn install_date_constructor_proxy<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ global: v8::Local<'s, v8::Object>,+ original: v8::Local<'s, v8::Function>,+ prototype: v8::Local<'s, v8::Object>,+) -> Result<()> {+ let Some(reflect) = global+ .get(scope, v8str(scope, "Reflect").into())+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ else {+ return Ok(());+ };+ let Some(reflect_apply) = reflect+ .get(scope, v8str(scope, "apply").into())+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ return Ok(());+ };+ let Some(reflect_construct) = reflect+ .get(scope, v8str(scope, "construct").into())+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ return Ok(());+ };+ let Some(date_now) = original_date_method(scope, DateIntrinsic::Now) else {+ return Ok(());+ };+ let Some(date_utc) = original_date_method(scope, DateIntrinsic::Utc) else {+ return Ok(());+ };+ let Some(date_parse) = original_date_method(scope, DateIntrinsic::Parse) else {+ return Ok(());+ };++ let apply_data = v8::Array::new(scope, 2);+ let _ = apply_data.set_index(scope, 0, reflect_apply.into());+ let _ = apply_data.set_index(scope, 1, date_now.into());+ let Some(apply) = v8::Function::builder(date_constructor_proxy_apply_callback)+ .data(apply_data.into())+ .length(3)+ .build(scope)+ else {+ return Err(anyhow!("failed to create Date constructor apply trap"));+ };++ let construct_data = v8::Array::new(scope, 3);+ let _ = construct_data.set_index(scope, 0, reflect_construct.into());+ let _ = construct_data.set_index(scope, 1, date_utc.into());+ let _ = construct_data.set_index(scope, 2, date_parse.into());+ let Some(construct) = v8::Function::builder(date_constructor_proxy_construct_callback)+ .data(construct_data.into())+ .length(3)+ .build(scope)+ else {+ return Err(anyhow!("failed to create Date constructor construct trap"));+ };++ let handler = v8::Object::new(scope);+ let _ = handler.set(scope, v8str(scope, "apply").into(), apply.into());+ let _ = handler.set(scope, v8str(scope, "construct").into(), construct.into());+ let Some(proxy) = v8::Proxy::new(scope, original.into(), handler) else {+ return Err(anyhow!("failed to create Date constructor proxy"));+ };+ let _ = global.set(scope, v8str(scope, "Date").into(), proxy.into());+ let _ = prototype.set(scope, v8str(scope, "constructor").into(), proxy.into());+ Ok(())+}++fn date_constructor_proxy_apply_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Ok(data) = v8::Local::<v8::Array>::try_from(args.data()) else {+ rv.set_undefined();+ return;+ };+ let Some(reflect_apply) = data+ .get_index(scope, 0)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ rv.set_undefined();+ return;+ };+ let Some(date_now) = data+ .get_index(scope, 1)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ rv.set_undefined();+ return;+ };+ let (_, timezone_override) = current_date_locale_overrides(scope);+ let Some(timezone) = timezone_override.as_deref() else {+ let invoke_args = [args.get(0), args.get(1), args.get(2)];+ let receiver = v8::undefined(scope);+ if let Some(result) = call_script_visible_function(+ scope,+ reflect_apply,+ receiver.into(),+ &invoke_args,+ "invoke Date through Reflect.apply",+ ) {+ rv.set(result);+ }+ return;+ };++ // Calling Date as a function ignores every argument and returns the same+ // local representation as a freshly constructed Date's toString(). Use+ // the retained native clock, then apply only the target-local timezone.+ let receiver = v8::undefined(scope);+ let Some(now) = call_script_visible_function(+ scope,+ date_now,+ receiver.into(),+ &[],+ "read Date.now for the Date function",+ ) else {+ return;+ };+ let Some(timestamp_ms) = now.number_value(scope) else {+ return;+ };+ let value = moli_time::format_date_local_string(timestamp_ms, Some(timezone));+ if let Some(value) = v8_string(scope, &value) {+ rv.set(value.into());+ }+}++fn date_constructor_proxy_construct_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Ok(data) = v8::Local::<v8::Array>::try_from(args.data()) else {+ rv.set_undefined();+ return;+ };+ let Some(reflect_construct) = data+ .get_index(scope, 0)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ rv.set_undefined();+ return;+ };+ let Some(date_utc) = data+ .get_index(scope, 1)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ rv.set_undefined();+ return;+ };+ let Some(date_parse) = data+ .get_index(scope, 2)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ rv.set_undefined();+ return;+ };+ let Ok(arguments) = v8::Local::<v8::Array>::try_from(args.get(1)) else {+ rv.set_undefined();+ return;+ };+ let (_, timezone_override) = current_date_locale_overrides(scope);+ let replacement = match timezone_override.as_deref() {+ Some(timezone) => match date_constructor_timezone_arguments(+ scope, arguments, date_utc, date_parse, timezone,+ ) {+ Ok(replacement) => replacement,+ Err(()) => return,+ },+ None => None,+ };+ let arguments = replacement.unwrap_or(arguments);+ let invoke_args = [args.get(0), arguments.into(), args.get(2)];+ let receiver = v8::undefined(scope);+ if let Some(result) = call_script_visible_function(+ scope,+ reflect_construct,+ receiver.into(),+ &invoke_args,+ "invoke Date through Reflect.construct",+ ) {+ rv.set(result);+ }+}++fn date_constructor_timezone_arguments<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ arguments: v8::Local<'s, v8::Array>,+ date_utc: v8::Local<'s, v8::Function>,+ date_parse: v8::Local<'s, v8::Function>,+ timezone: &str,+) -> Result<Option<v8::Local<'s, v8::Array>>, ()> {+ let wall_clock = if arguments.length() >= 2 {+ let forwarded = (0..arguments.length())+ .filter_map(|index| arguments.get_index(scope, index))+ .collect::<Vec<_>>();+ let receiver = v8::undefined(scope);+ call_script_visible_function(+ scope,+ date_utc,+ receiver.into(),+ &forwarded,+ "normalize local Date constructor fields with Date.UTC",+ )+ .ok_or(())?+ } else if arguments.length() == 1 {+ let input = arguments.get_index(scope, 0).ok_or(())?;+ if !input.is_string() {+ return Ok(None);+ }+ let input = input.to_rust_string_lossy(scope);+ let Some(utc_input) = local_date_parse_input_as_utc(&input) else {+ return Ok(None);+ };+ let utc_input = v8_string(scope, &utc_input).ok_or(())?;+ let receiver = v8::undefined(scope);+ call_script_visible_function(+ scope,+ date_parse,+ receiver.into(),+ &[utc_input.into()],+ "parse a local Date constructor string as UTC fields",+ )+ .ok_or(())?+ } else {+ return Ok(None);+ };+ Ok(Some(single_date_epoch_argument(+ scope,+ wall_clock.number_value(scope),+ timezone,+ )))+}++fn single_date_epoch_argument<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ wall_clock_utc_ms: Option<f64>,+ timezone: &str,+) -> v8::Local<'s, v8::Array> {+ let epoch_ms = wall_clock_utc_ms+ .filter(|value| value.is_finite())+ .and_then(|value| moli_time::epoch_millis_for_local_wall_clock(value, timezone))+ .unwrap_or(f64::NAN);+ let epoch_ms = v8::Number::new(scope, epoch_ms);+ v8::Array::new_with_elements(scope, &[epoch_ms.into()])+}++fn date_parse_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Ok(original) = v8::Local::<v8::Function>::try_from(args.data()) else {+ rv.set_undefined();+ return;+ };+ // Date.parse performs ToString exactly once. Convert here before deciding+ // whether the string denotes local time so observable conversion hooks are+ // neither skipped nor invoked twice.+ let Some(input) = args.get(0).to_string(scope) else {+ return;+ };+ let (_, timezone_override) = current_date_locale_overrides(scope);+ let utc_input = timezone_override+ .as_deref()+ .and_then(|_| local_date_parse_input_as_utc(&input.to_rust_string_lossy(scope)));+ let parse_input: v8::Local<'s, v8::Value> = match utc_input.as_deref() {+ Some(utc_input) => {+ let Some(utc_input) = v8_string(scope, utc_input) else {+ return;+ };+ utc_input.into()+ }+ None => input.into(),+ };+ let receiver = v8::undefined(scope);+ let Some(parsed) = call_script_visible_function(+ scope,+ original,+ receiver.into(),+ &[parse_input],+ "Date.parse",+ ) else {+ return;+ };+ let Some(timezone) = timezone_override.as_deref() else {+ rv.set(parsed);+ return;+ };+ if utc_input.is_none() {+ rv.set(parsed);+ return;+ }+ let epoch = single_date_epoch_argument(scope, parsed.number_value(scope), timezone);+ if let Some(epoch) = epoch.get_index(scope, 0) {+ rv.set(epoch);+ }+}++fn local_date_parse_input_as_utc(input: &str) -> Option<String> {+ let input = input.trim();+ if input.is_empty() || iso_date_only_uses_utc(input) {+ return None;+ }+ let lower = input.to_ascii_lowercase();+ if lower.ends_with('z') || lower.contains("gmt") || lower.contains("utc") {+ return None;+ }+ let time_start = input+ .find(['T', 't'])+ .or_else(|| input.find(':'))+ .unwrap_or(input.len());+ if input[time_start..].contains(['+', '-']) {+ return None;+ }+ if input.contains(['T', 't']) {+ Some(format!("{input}Z"))+ } else {+ // Legacy date grammars generally recognize a UTC suffix more reliably+ // than a trailing ISO `Z`.+ Some(format!("{input} UTC"))+ }+}++fn iso_date_only_uses_utc(input: &str) -> bool {+ let (year_len, rest) = match input.as_bytes().first() {+ Some(b'+' | b'-') if input.len() >= 7 => (7, &input[7..]),+ _ if input.len() >= 4 => (4, &input[4..]),+ _ => return false,+ };+ if !input.as_bytes()[..year_len]+ .iter()+ .enumerate()+ .all(|(index, byte)| (index == 0 && matches!(byte, b'+' | b'-')) || byte.is_ascii_digit())+ {+ return false;+ }+ rest.is_empty()+ || (rest.len() == 3+ && rest.as_bytes()[0] == b'-'+ && rest.as_bytes()[1..3].iter().all(u8::is_ascii_digit))+ || (rest.len() == 6+ && rest.as_bytes()[0] == b'-'+ && rest.as_bytes()[3] == b'-'+ && rest.as_bytes()[1..3].iter().all(u8::is_ascii_digit)+ && rest.as_bytes()[4..6].iter().all(u8::is_ascii_digit))+}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.rsnew file mode 100644index 000000000..dd8391731--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rs@@ -0,0 +1,354 @@+use super::*;+use crate::util::call_script_visible_function;++use super::super::{+ intl::intl_datetime_options_with_default_timezone, overrides::current_date_locale_overrides,+};++const DATE_LOCAL_FIELD_INTRINSICS: &[DateIntrinsic] = &[+ DateIntrinsic::GetFullYear,+ DateIntrinsic::GetMonth,+ DateIntrinsic::GetDate,+ DateIntrinsic::GetDay,+ DateIntrinsic::GetHours,+ DateIntrinsic::GetMinutes,+ DateIntrinsic::GetSeconds,+ DateIntrinsic::GetMilliseconds,+];++const DATE_LOCAL_SETTER_INTRINSICS: &[(DateIntrinsic, DateIntrinsic)] = &[+ (DateIntrinsic::SetDate, DateIntrinsic::SetUtcDate),+ (DateIntrinsic::SetFullYear, DateIntrinsic::SetUtcFullYear),+ (DateIntrinsic::SetHours, DateIntrinsic::SetUtcHours),+ (+ DateIntrinsic::SetMilliseconds,+ DateIntrinsic::SetUtcMilliseconds,+ ),+ (DateIntrinsic::SetMinutes, DateIntrinsic::SetUtcMinutes),+ (DateIntrinsic::SetMonth, DateIntrinsic::SetUtcMonth),+ (DateIntrinsic::SetSeconds, DateIntrinsic::SetUtcSeconds),+];++pub(super) fn date_to_locale_string_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'s, v8::Value>,+) {+ set_date_locale_method_result(+ scope,+ args,+ rv,+ DateIntrinsic::ToLocaleString,+ "Date.prototype.toLocaleString",+ );+}++pub(super) fn date_to_locale_date_string_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'s, v8::Value>,+) {+ set_date_locale_method_result(+ scope,+ args,+ rv,+ DateIntrinsic::ToLocaleDateString,+ "Date.prototype.toLocaleDateString",+ );+}++pub(super) fn date_to_locale_time_string_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'s, v8::Value>,+) {+ set_date_locale_method_result(+ scope,+ args,+ rv,+ DateIntrinsic::ToLocaleTimeString,+ "Date.prototype.toLocaleTimeString",+ );+}++fn set_date_locale_method_result<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+ original: DateIntrinsic,+ action: &str,+) {+ let Some(original) = original_date_method(scope, original) else {+ rv.set_undefined();+ return;+ };+ let (locale_override, timezone_override) = current_date_locale_overrides(scope);+ let mut forwarded = (0..args.length())+ .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)+ {+ if forwarded.is_empty() {+ forwarded.push(locale.into());+ } else {+ forwarded[0] = locale.into();+ }+ }+ if let Some(timezone) = timezone_override.as_deref()+ && let Some(options) =+ intl_datetime_options_with_default_timezone(scope, forwarded.get(1).copied(), timezone)+ {+ while forwarded.len() < 2 {+ forwarded.push(v8::undefined(scope).into());+ }+ forwarded[1] = options;+ }+ if let Some(value) =+ call_script_visible_function(scope, original, args.this().into(), &forwarded, action)+ {+ rv.set(value);+ }+}++pub(super) fn date_get_timezone_offset_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let (_, timezone_override) = current_date_locale_overrides(scope);+ // Preserve V8's complete native Date behavior outside emulation. The+ // target-local path below exists because V8's Date cache is also driven by+ // process-global timezone state.+ if timezone_override.is_none()+ && set_original_date_method_result(+ scope,+ &args,+ &mut rv,+ DateIntrinsic::GetTimezoneOffset,+ "Date.prototype.getTimezoneOffset",+ )+ {+ return;+ }+ let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {+ throw_type_error(+ scope,+ "Method Date.prototype.getTimezoneOffset called on incompatible receiver.",+ );+ return;+ };+ let timestamp = date.value_of();+ let offset_minutes = timezone_override+ .as_deref()+ .and_then(|timezone| moli_time::time_zone_offset_seconds(timestamp, timezone))+ .or_else(|| moli_time::local_time_zone_offset_seconds(timestamp))+ .map(|seconds| -f64::from(seconds) / 60.0)+ .unwrap_or(f64::NAN);+ rv.set(v8::Number::new(scope, offset_minutes).into());+}++pub(super) fn date_local_field_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let field = args.data().uint32_value(scope).unwrap_or(u32::MAX);+ let (_, timezone_override) = current_date_locale_overrides(scope);+ if timezone_override.is_none()+ && let Some(&intrinsic) = DATE_LOCAL_FIELD_INTRINSICS.get(field as usize)+ && set_original_date_method_result(+ scope,+ &args,+ &mut rv,+ intrinsic,+ "Date local field getter",+ )+ {+ return;+ }+ let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {+ throw_type_error(scope, "Date method called on incompatible receiver.");+ return;+ };+ let Some(fields) = moli_time::local_date_fields(date.value_of(), timezone_override.as_deref())+ else {+ rv.set(v8::Number::new(scope, f64::NAN).into());+ return;+ };+ let value = match field {+ 0 => f64::from(fields.year),+ 1 => f64::from(fields.month_zero_based),+ 2 => f64::from(fields.day),+ 3 => f64::from(fields.weekday_sunday_zero),+ 4 => f64::from(fields.hour),+ 5 => f64::from(fields.minute),+ 6 => f64::from(fields.second),+ 7 => f64::from(fields.millisecond),+ _ => f64::NAN,+ };+ rv.set(v8::Number::new(scope, value).into());+}++pub(super) fn date_local_setter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let setter = args.data().uint32_value(scope).unwrap_or(u32::MAX);+ let Some(&(local_intrinsic, utc_intrinsic)) = DATE_LOCAL_SETTER_INTRINSICS.get(setter as usize)+ else {+ rv.set(v8::Number::new(scope, f64::NAN).into());+ return;+ };+ let forwarded = (0..args.length())+ .map(|index| args.get(index))+ .collect::<Vec<_>>();+ let (_, timezone_override) = current_date_locale_overrides(scope);+ let Some(timezone) = timezone_override.as_deref() else {+ let Some(method) = original_date_method(scope, local_intrinsic) else {+ rv.set_undefined();+ return;+ };+ if let Some(value) = call_script_visible_function(+ scope,+ method,+ args.this().into(),+ &forwarded,+ "Date local field setter",+ ) {+ rv.set(value);+ }+ return;+ };+ let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {+ throw_type_error(scope, "Date method called on incompatible receiver.");+ return;+ };+ let wall_clock =+ moli_time::local_wall_clock_as_utc_millis(date.value_of(), timezone).unwrap_or(f64::NAN);+ let Some(temporary) = v8::Date::new(scope, wall_clock) else {+ rv.set(v8::Number::new(scope, f64::NAN).into());+ return;+ };+ let Some(utc_setter) = original_date_method(scope, utc_intrinsic) else {+ rv.set_undefined();+ return;+ };+ let Some(next_wall_clock) = call_script_visible_function(+ scope,+ utc_setter,+ temporary.into(),+ &forwarded,+ "normalize a Date local setter through its UTC counterpart",+ ) else {+ return;+ };+ let epoch_ms = next_wall_clock+ .number_value(scope)+ .filter(|value| value.is_finite())+ .and_then(|value| moli_time::epoch_millis_for_local_wall_clock(value, timezone))+ .unwrap_or(f64::NAN);+ let Some(set_time) = original_date_method(scope, DateIntrinsic::SetTime) else {+ rv.set_undefined();+ return;+ };+ let epoch_ms = v8::Number::new(scope, epoch_ms);+ if let Some(value) = call_script_visible_function(+ scope,+ set_time,+ args.this().into(),+ &[epoch_ms.into()],+ "commit a Date local setter",+ ) {+ rv.set(value);+ }+}++pub(super) fn date_to_string_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'s, v8::Value>,+) {+ set_date_local_string_result(+ scope,+ args,+ rv,+ moli_time::format_date_local_string,+ DateIntrinsic::ToString,+ "Date.prototype.toString",+ );+}++pub(super) fn date_to_date_string_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'s, v8::Value>,+) {+ set_date_local_string_result(+ scope,+ args,+ rv,+ moli_time::format_date_local_date_string,+ DateIntrinsic::ToDateString,+ "Date.prototype.toDateString",+ );+}++pub(super) fn date_to_time_string_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'s, v8::Value>,+) {+ set_date_local_string_result(+ scope,+ args,+ rv,+ moli_time::format_date_local_time_string,+ DateIntrinsic::ToTimeString,+ "Date.prototype.toTimeString",+ );+}++fn set_date_local_string_result<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+ format: fn(f64, Option<&str>) -> String,+ original: DateIntrinsic,+ action: &str,+) {+ let (_, timezone_override) = current_date_locale_overrides(scope);+ if timezone_override.is_none()+ && set_original_date_method_result(scope, &args, &mut rv, original, action)+ {+ return;+ }+ let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {+ throw_type_error(scope, "Date method called on incompatible receiver.");+ return;+ };+ let value = format(date.value_of(), timezone_override.as_deref());+ if let Some(value) = v8_string(scope, &value) {+ rv.set(value.into());+ }+}++fn set_original_date_method_result<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: &v8::FunctionCallbackArguments<'s>,+ rv: &mut v8::ReturnValue<'s, v8::Value>,+ intrinsic: DateIntrinsic,+ action: &str,+) -> bool {+ let Some(method) = original_date_method(scope, intrinsic) else {+ return false;+ };+ if let Some(value) =+ call_script_visible_function(scope, method, args.this().into(), &[], action)+ {+ rv.set(value);+ }+ true+}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.rsnew file mode 100644index 000000000..340f5f768--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs@@ -0,0 +1,346 @@+use super::*;+use crate::util::{call_script_visible_function, get_private_value, set_private_value};+use anyhow::{Result, anyhow};++use super::overrides::current_date_locale_overrides;++const INTL_DEFAULT_LOCALE_SLOT: &str = "__moliIntlDefaultLocale";++#[derive(Clone, Copy)]+enum IntlConstructorKind {+ Collator,+ DateTimeFormat,+ DisplayNames,+ DurationFormat,+ ListFormat,+ NumberFormat,+ PluralRules,+ RelativeTimeFormat,+ Segmenter,+}++impl IntlConstructorKind {+ const ALL: &[(Self, &str)] = &[+ (Self::Collator, "Collator"),+ (Self::DateTimeFormat, "DateTimeFormat"),+ (Self::DisplayNames, "DisplayNames"),+ (Self::DurationFormat, "DurationFormat"),+ (Self::ListFormat, "ListFormat"),+ (Self::NumberFormat, "NumberFormat"),+ (Self::PluralRules, "PluralRules"),+ (Self::RelativeTimeFormat, "RelativeTimeFormat"),+ (Self::Segmenter, "Segmenter"),+ ];++ fn from_index(index: u32) -> Option<Self> {+ Self::ALL.get(index as usize).map(|(kind, _)| *kind)+ }++ fn uses_timezone(self) -> bool {+ matches!(self, Self::DateTimeFormat)+ }+}+pub(super) fn install_intl_default_override_constructors<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ global: v8::Local<'s, v8::Object>,+) -> Result<()> {+ // 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.+ let Some(intl_value) = global.get(scope, v8str(scope, "Intl").into()) else {+ return Ok(());+ };+ let Ok(intl) = v8::Local::<v8::Object>::try_from(intl_value) else {+ return Ok(());+ };+ let Some(reflect) = global+ .get(scope, v8str(scope, "Reflect").into())+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ else {+ return Ok(());+ };+ let Some(reflect_apply) = reflect+ .get(scope, v8str(scope, "apply").into())+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ return Ok(());+ };+ let Some(reflect_construct) = reflect+ .get(scope, v8str(scope, "construct").into())+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ else {+ return Ok(());+ };+ for (index, (_, name)) in IntlConstructorKind::ALL.iter().enumerate() {+ let key = v8str(scope, name);+ let Some(original_value) = intl.get(scope, key.into()) else {+ continue;+ };+ let Ok(original) = v8::Local::<v8::Function>::try_from(original_value) else {+ continue;+ };+ if let Some(prototype) = original+ .get(scope, v8str(scope, "prototype").into())+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ {+ install_intl_resolved_options_override(scope, prototype)?;+ }+ let kind = v8::Integer::new_from_unsigned(scope, index as u32);+ let apply_data = v8::Array::new(scope, 2);+ let _ = apply_data.set_index(scope, 0, kind.into());+ let _ = apply_data.set_index(scope, 1, reflect_apply.into());+ let Some(apply) = v8::Function::builder(intl_constructor_proxy_apply_callback)+ .data(apply_data.into())+ .length(3)+ .build(scope)+ else {+ return Err(anyhow!("failed to create Intl.{name} apply trap"));+ };+ let construct_data = v8::Array::new(scope, 2);+ let _ = construct_data.set_index(scope, 0, kind.into());+ let _ = construct_data.set_index(scope, 1, reflect_construct.into());+ let Some(construct) = v8::Function::builder(intl_constructor_proxy_construct_callback)+ .data(construct_data.into())+ .length(3)+ .build(scope)+ else {+ return Err(anyhow!("failed to create Intl.{name} construct trap"));+ };+ let handler = v8::Object::new(scope);+ let _ = handler.set(scope, v8str(scope, "apply").into(), apply.into());+ let _ = handler.set(scope, v8str(scope, "construct").into(), construct.into());+ let Some(proxy) = v8::Proxy::new(scope, original.into(), handler) else {+ return Err(anyhow!("failed to create Intl.{name} constructor proxy"));+ };+ let _ = intl.set(scope, key.into(), proxy.into());+ if let Some(prototype) = original+ .get(scope, v8str(scope, "prototype").into())+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ {+ let _ = prototype.set(scope, v8str(scope, "constructor").into(), proxy.into());+ }+ }+ Ok(())+}++fn install_intl_resolved_options_override<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ prototype: v8::Local<'s, v8::Object>,+) -> Result<()> {+ let key = v8str(scope, "resolvedOptions");+ let Some(original) = prototype.get(scope, key.into()) else {+ return Ok(());+ };+ let Ok(original) = v8::Local::<v8::Function>::try_from(original) else {+ return Ok(());+ };+ let Some(wrapper) = v8::Function::builder(intl_resolved_options_callback)+ .data(original.into())+ .length(0)+ .build(scope)+ else {+ return Err(anyhow!("failed to create Intl resolvedOptions wrapper"));+ };+ wrapper.set_name(key);+ let _ = prototype.set(scope, key.into(), wrapper.into());+ Ok(())+}++fn intl_constructor_proxy_apply_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Some((kind, reflect_apply)) = intl_constructor_callback_data(scope, args.data()) else {+ rv.set_undefined();+ return;+ };+ let Ok(arguments) = v8::Local::<v8::Array>::try_from(args.get(2)) else {+ rv.set_undefined();+ return;+ };+ let applied_locale = apply_intl_constructor_defaults(scope, arguments, kind);+ let invoke_args = [args.get(0), args.get(1), arguments.into()];+ let receiver = v8::undefined(scope);+ if let Some(result) = call_script_visible_function(+ scope,+ reflect_apply,+ receiver.into(),+ &invoke_args,+ "invoke Intl constructor through Reflect.apply",+ ) {+ tag_intl_default_locale(scope, result, applied_locale.as_deref());+ rv.set(result);+ }+}++fn intl_constructor_proxy_construct_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Some((kind, reflect_construct)) = intl_constructor_callback_data(scope, args.data()) else {+ rv.set_undefined();+ return;+ };+ let Ok(arguments) = v8::Local::<v8::Array>::try_from(args.get(1)) else {+ rv.set_undefined();+ return;+ };+ let applied_locale = apply_intl_constructor_defaults(scope, arguments, kind);+ let invoke_args = [args.get(0), arguments.into(), args.get(2)];+ let receiver = v8::undefined(scope);+ if let Some(result) = call_script_visible_function(+ scope,+ reflect_construct,+ receiver.into(),+ &invoke_args,+ "invoke Intl constructor through Reflect.construct",+ ) {+ tag_intl_default_locale(scope, result, applied_locale.as_deref());+ rv.set(result);+ }+}++fn apply_intl_constructor_defaults<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ arguments: v8::Local<'s, v8::Array>,+ kind: IntlConstructorKind,+) -> Option<String> {+ 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 kind.uses_timezone()+ && let Some(timezone) = timezone_override.as_deref()+ && let Some(options) = intl_datetime_options_with_default_timezone(+ scope,+ arguments.get_index(scope, 1),+ timezone,+ )+ {+ let _ = arguments.set_index(scope, 1, options);+ }+ applied_locale+}++fn tag_intl_default_locale(+ scope: &mut v8::PinScope<'_, '_>,+ result: v8::Local<'_, v8::Value>,+ locale: Option<&str>,+) {+ // 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+ && 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());+ }+}++fn intl_resolved_options_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Ok(original) = v8::Local::<v8::Function>::try_from(args.data()) else {+ rv.set_undefined();+ return;+ };+ let Some(result) = call_script_visible_function(+ scope,+ original,+ args.this().into(),+ &[],+ "Intl resolvedOptions",+ ) else {+ return;+ };+ let Ok(options) = v8::Local::<v8::Object>::try_from(result) else {+ rv.set(result);+ return;+ };+ if let Some(locale) = get_private_value(scope, args.this(), INTL_DEFAULT_LOCALE_SLOT) {+ let _ = options.set(scope, v8str(scope, "locale").into(), locale);+ }+ rv.set(options.into());+}++fn intl_constructor_callback_data<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+) -> Option<(IntlConstructorKind, v8::Local<'s, v8::Function>)> {+ let data = v8::Local::<v8::Array>::try_from(value).ok()?;+ let index = data.get_index(scope, 0)?.uint32_value(scope)?;+ let builtin = data+ .get_index(scope, 1)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())?;+ Some((IntlConstructorKind::from_index(index)?, builtin))+}++pub(super) fn intl_datetime_options_with_default_timezone<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ original: Option<v8::Local<'s, v8::Value>>,+ timezone: &str,+) -> Option<v8::Local<'s, v8::Value>> {+ let key = v8str(scope, "timeZone");+ 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.+ return Some(original);+ }+ let target = original.to_object(scope)?;+ // Do not inspect `timeZone` here. Reading it before V8 processes the+ // remaining options changes observable getter/Proxy ordering and can+ // read an explicit accessor twice. The transparent proxy supplies the+ // default exactly when V8 performs its ordinary [[Get]].+ let handler = v8::Object::new(scope);+ let timezone = v8_string(scope, timezone)?;+ let get = v8::Function::builder(intl_datetime_options_get_callback)+ .data(timezone.into())+ .length(3)+ .build(scope)?;+ let _ = handler.set(scope, v8str(scope, "get").into(), get.into());+ return v8::Proxy::new(scope, target, handler).map(Into::into);+ }+ let options = v8::Object::new(scope);+ let timezone = v8_string(scope, timezone)?;+ let _ = options.set(scope, key.into(), timezone.into());+ Some(options.into())+}++fn intl_datetime_options_get_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Ok(target) = v8::Local::<v8::Object>::try_from(args.get(0)) else {+ rv.set_undefined();+ return;+ };+ let key = args.get(1);+ // The outer proxy is an implementation detail. Forward with the page's+ // original options object as receiver so an accessor observes exactly the+ // same `this` value it would have seen without emulation.+ let Some(value) = target.get(scope, key) else {+ return;+ };+ if key.strict_equals(v8str(scope, "timeZone").into()) && value.is_undefined() {+ rv.set(args.data());+ } else {+ rv.set(value);+ }+}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/overrides.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/overrides.rsnew file mode 100644index 000000000..4d8f408bd--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/overrides.rs@@ -0,0 +1,17 @@+use crate::util::date_locale_runtime_state_from_context;++/// Copies the target-owned Date/Intl emulation state for the current realm.+///+/// Every Window realm installed by a `ScriptVm` receives the same reference-+/// counted runtime-state slot, so main, child, and isolated worlds observe one+/// applied renderer state without mirroring values into each V8 global object+/// or dereferencing the re-entrant `JsContextHost` callback pointer.+pub(super) fn current_date_locale_overrides(+ scope: &mut v8::PinScope<'_, '_>,+) -> (Option<String>, Option<String>) {+ let context = scope.get_current_context();+ let Some(state) = date_locale_runtime_state_from_context(context) else {+ return (None, None);+ };+ state.snapshot()+}diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime.rsindex 8a1f35c6e..54d95624d 100644--- a/moli-renderer-v8/src/context_bootstrap/window_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_runtime.rs@@ -1,7 +1,6 @@use super::*;mod base64;-mod date_locale;mod dialogs;mod navigator;mod obsolete;@@ -12,13 +11,6 @@ mod structured_clone;use moli_webapi_declare::WebApiObject;pub(super) use base64::{window_atob_callback, window_btoa_callback};-pub(super) use date_locale::{- current_date_locale_overrides, date_to_locale_date_string_callback,- date_to_locale_string_callback, date_to_locale_time_string_callback,-};-pub(crate) use date_locale::{- set_date_locale_override_for_current_context, set_date_timezone_override_for_current_context,-};pub(super) use dialogs::entered_window_api_base_url;pub(super) use dialogs::{window_alert_callback, window_confirm_callback, window_prompt_callback};pub(crate) use dialogs::{diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/date_locale.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/date_locale.rsdeleted file mode 100644index eb2aa1884..000000000--- a/moli-renderer-v8/src/context_bootstrap/window_runtime/date_locale.rs+++ /dev/null@@ -1,121 +0,0 @@-use super::*;-use crate::util::{get_private_value, set_private_value};-use moli_time::{DateLocaleFormatKind, format_date_locale_value};--const DATE_LOCALE_OVERRIDE_SLOT: &str = "__moliLocaleOverride";-const DATE_TIMEZONE_OVERRIDE_SLOT: &str = "__moliTimeZoneOverride";--pub(crate) fn set_date_locale_override_for_current_context<'s>(- scope: &mut v8::PinScope<'s, '_>,- locale: Option<&str>,-) {- let global = scope.get_current_context().global(scope);- set_date_override_private_value(scope, global, DATE_LOCALE_OVERRIDE_SLOT, locale);-}--pub(crate) fn set_date_timezone_override_for_current_context<'s>(- scope: &mut v8::PinScope<'s, '_>,- timezone: Option<&str>,-) {- let global = scope.get_current_context().global(scope);- set_date_override_private_value(scope, global, DATE_TIMEZONE_OVERRIDE_SLOT, timezone);-}--pub(in crate::context_bootstrap) fn current_date_locale_overrides<'s>(- scope: &mut v8::PinScope<'s, '_>,-) -> (Option<String>, Option<String>) {- let (mut locale_override, mut timezone_override) = context_host_ptr_from_global_bridge(scope)- .map(|host_ptr| unsafe {- let host = &*host_ptr;- (- host.locale_override().map(str::to_owned),- host.timezone_override().map(str::to_owned),- )- })- .unwrap_or((None, None));- if locale_override.is_none() || timezone_override.is_none() {- let global = scope.get_current_context().global(scope);- if locale_override.is_none() {- locale_override = date_override_private_value(scope, global, DATE_LOCALE_OVERRIDE_SLOT);- }- if timezone_override.is_none() {- timezone_override =- date_override_private_value(scope, global, DATE_TIMEZONE_OVERRIDE_SLOT);- }- }- (locale_override, timezone_override)-}--pub(in crate::context_bootstrap) fn date_to_locale_string_callback(- scope: &mut v8::PinScope<'_, '_>,- args: v8::FunctionCallbackArguments<'_>,- mut rv: v8::ReturnValue<'_, v8::Value>,-) {- set_date_locale_result(scope, &args, &mut rv, DateLocaleFormatKind::DateTime);-}--pub(in crate::context_bootstrap) fn date_to_locale_date_string_callback(- scope: &mut v8::PinScope<'_, '_>,- args: v8::FunctionCallbackArguments<'_>,- mut rv: v8::ReturnValue<'_, v8::Value>,-) {- set_date_locale_result(scope, &args, &mut rv, DateLocaleFormatKind::DateOnly);-}--pub(in crate::context_bootstrap) fn date_to_locale_time_string_callback(- scope: &mut v8::PinScope<'_, '_>,- args: v8::FunctionCallbackArguments<'_>,- mut rv: v8::ReturnValue<'_, v8::Value>,-) {- set_date_locale_result(scope, &args, &mut rv, DateLocaleFormatKind::TimeOnly);-}--fn set_date_locale_result(- scope: &mut v8::PinScope<'_, '_>,- args: &v8::FunctionCallbackArguments<'_>,- rv: &mut v8::ReturnValue<'_, v8::Value>,- kind: DateLocaleFormatKind,-) {- let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {- throw_type_error(- scope,- "Method Date.prototype.toLocaleString called on incompatible receiver.",- );- return;- };- let (locale_override, timezone_override) = current_date_locale_overrides(scope);- let formatted = format_date_locale_value(- date.value_of(),- kind,- locale_override.as_deref(),- timezone_override.as_deref(),- );- if let Some(value) = v8_string(scope, &formatted) {- rv.set(value.into());- } else {- rv.set(v8::String::empty(scope).into());- }-}--fn set_date_override_private_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,- slot: &'static str,- value: Option<&str>,-) {- let value = value- .and_then(|value| v8_string(scope, value).map(Into::into))- .unwrap_or_else(|| v8::undefined(scope).into());- set_private_value(scope, global, slot, value);-}--fn date_override_private_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,- slot: &'static str,-) -> Option<String> {- get_private_value(scope, global, slot)- .and_then(|value| value.to_string(scope))- .map(|value| value.to_rust_string_lossy(scope))- .filter(|value| !value.is_empty() && value != "null" && value != "undefined")-}diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rsindex e64247c19..e40c7d2a7 100644--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs@@ -263,8 +263,7 @@ impl JsContextHost {app_manifest_link_change_epoch: 0,extra_http_headers: Vec::new(),permission_overrides: Vec::new(),- locale_override: None,- timezone_override: None,+ date_locale_runtime_state: Rc::new(DateLocaleRuntimeState::default()),idle_override: None,protocol_user_gesture_activation_depth: 0,current_input_event: None,diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rsindex 0c35bde13..d8960a4f2 100644--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs@@ -1,7 +1,7 @@-use std::collections::HashSet;+use std::{collections::HashSet, rc::Rc};use super::{- JsContextHost,+ DateLocaleRuntimeState, JsContextHost,permissions::{permission_names_match, permission_override_name},};use crate::{@@ -704,20 +704,20 @@ impl JsContextHost {&self.permission_overrides}- pub(crate) fn set_locale_override(&mut self, locale: Option<&str>) {- self.locale_override = locale.map(str::to_owned);+ pub(crate) fn set_locale_override(&self, locale: Option<&str>) {+ self.date_locale_runtime_state.set_locale(locale);}- pub(crate) fn set_timezone_override(&mut self, timezone: Option<&str>) {- self.timezone_override = timezone.map(str::to_owned);+ pub(crate) fn set_timezone_override(&self, timezone: Option<&str>) {+ self.date_locale_runtime_state.set_timezone(timezone);}- pub(crate) fn locale_override(&self) -> Option<&str> {- self.locale_override.as_deref()+ pub(crate) fn date_locale_runtime_state(&self) -> Rc<DateLocaleRuntimeState> {+ Rc::clone(&self.date_locale_runtime_state)}- pub(crate) fn timezone_override(&self) -> Option<&str> {- self.timezone_override.as_deref()+ pub(crate) fn timezone_override(&self) -> Option<String> {+ self.date_locale_runtime_state.timezone()}pub(crate) fn set_idle_override(diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex 7624aa16b..e89ce96c0 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -797,6 +797,36 @@ impl PendingImageLoadEvent {pub(crate) type JsContextHostPageTaskCapabilities =crate::page_task_queue::RendererPageJsContextTaskSenders;+#[derive(Debug, Default)]+pub(crate) struct DateLocaleRuntimeState {+ overrides: RefCell<DateLocaleOverrides>,+}++#[derive(Debug, Default)]+struct DateLocaleOverrides {+ locale: Option<String>,+ timezone: Option<String>,+}++impl DateLocaleRuntimeState {+ pub(crate) fn set_locale(&self, locale: Option<&str>) {+ self.overrides.borrow_mut().locale = locale.map(str::to_owned);+ }++ pub(crate) fn set_timezone(&self, timezone: Option<&str>) {+ self.overrides.borrow_mut().timezone = timezone.map(str::to_owned);+ }++ pub(crate) fn snapshot(&self) -> (Option<String>, Option<String>) {+ let overrides = self.overrides.borrow();+ (overrides.locale.clone(), overrides.timezone.clone())+ }++ pub(crate) fn timezone(&self) -> Option<String> {+ self.overrides.borrow().timezone.clone()+ }+}+pub(crate) struct JsContextHost {runtime: *mut DocumentRuntime,layout_policy: moli_page_types::LayoutPolicy,@@ -867,8 +897,7 @@ pub(crate) struct JsContextHost {app_manifest_link_change_epoch: u64,extra_http_headers: Vec<(String, String)>,permission_overrides: Vec<crate::protocol_types::PermissionOverrideRegistration>,- locale_override: Option<String>,- timezone_override: Option<String>,+ date_locale_runtime_state: Rc<DateLocaleRuntimeState>,idle_override: Option<crate::protocol_types::EmulatedIdleOverride>,protocol_user_gesture_activation_depth: usize,current_input_event: Option<crate::native_bridge::CurrentInputEvent>,diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rsindex d81794542..1d83686aa 100644--- a/moli-renderer-v8/src/native_bridge/document.rs+++ b/moli-renderer-v8/src/native_bridge/document.rs@@ -968,12 +968,13 @@ fn document_last_modified_getter_function<'s>(return;};let runtime = unsafe { &*runtime_ptr };+ let timezone_override = runtime.timezone_override();let value = moli_time::format_document_last_modified_value(runtime.dom_host().document_source_last_modified_for_handle(handle),moli_time::unix_epoch_millis(),- runtime.timezone_override(),+ timezone_override.as_deref(),);set_document_string_return_value(scope, &mut rv, &value);}diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rsindex 5f9cdf755..48482eb2d 100644--- a/moli-renderer-v8/src/native_bridge/mod.rs+++ b/moli-renderer-v8/src/native_bridge/mod.rs@@ -7,8 +7,8 @@ mod collections;mod context_host;mod current_input;pub(crate) use context_host::{- JsContextHost, JsContextHostPageTaskCapabilities, PendingScrollObservableEffects,- PostParseAutofocusAdmission, ServiceWorkerWindowOwner,+ DateLocaleRuntimeState, JsContextHost, JsContextHostPageTaskCapabilities,+ PendingScrollObservableEffects, PostParseAutofocusAdmission, ServiceWorkerWindowOwner,};pub(crate) use current_input::{CurrentInputEvent, CurrentInputEventScope, InputNavigationPolicy, navigation_policy_from_event,diff --git a/moli-renderer-v8/src/runtime/page_network.rs b/moli-renderer-v8/src/runtime/page_network.rsindex 108b985a7..38519c34a 100644--- a/moli-renderer-v8/src/runtime/page_network.rs+++ b/moli-renderer-v8/src/runtime/page_network.rs@@ -150,12 +150,13 @@ impl PageVm {}pub(crate) fn set_locale_override(&mut self, locale: Option<&str>) -> Result<()> {- self.vm_mut().set_locale_override_and_sync_surface(locale)+ self.vm_mut().set_locale_override(locale);+ Ok(())}pub(crate) fn set_timezone_override(&mut self, timezone: Option<&str>) -> Result<()> {- self.vm_mut()- .set_timezone_override_and_sync_surface(timezone)+ self.vm_mut().set_timezone_override(timezone);+ Ok(())}pub(crate) fn set_script_execution_disabled(&mut self, disabled: bool) {diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex 583382458..d2f77a959 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -628,9 +628,7 @@ use super::native_bridge::element::ClientRect;use super::{context_bootstrap::{dispatch_media_query_list_change_events as dispatch_media_query_list_change_events_for_scope,- set_date_locale_override_for_current_context,- set_date_timezone_override_for_current_context, set_window_navigator_identity,- sync_global_location_runtime_state,+ set_window_navigator_identity, sync_global_location_runtime_state,},custom_elements,document_runtime::{CurrentScriptContextSpec, DocumentRuntime, DomHandle},@@ -5003,38 +5001,12 @@ impl ScriptVm {.set_permission_overrides(overrides);}- pub(super) fn set_locale_override(&mut self, locale: Option<&str>) {- self._context_host.borrow_mut().set_locale_override(locale);+ pub(super) fn set_locale_override(&self, locale: Option<&str>) {+ self._context_host.borrow().set_locale_override(locale);}- pub(super) fn set_locale_override_and_sync_surface(- &mut self,- locale: Option<&str>,- ) -> Result<()> {- self.set_locale_override(locale);- let context_ptr: *const v8::Global<v8::Context> = &self.page_default_context;- self.with_context_scope_by_ptr(context_ptr, |scope, _| {- set_date_locale_override_for_current_context(scope, locale);- Ok(())- })- }-- pub(super) fn set_timezone_override(&mut self, timezone: Option<&str>) {- self._context_host- .borrow_mut()- .set_timezone_override(timezone);- }-- pub(super) fn set_timezone_override_and_sync_surface(- &mut self,- timezone: Option<&str>,- ) -> Result<()> {- self.set_timezone_override(timezone);- let context_ptr: *const v8::Global<v8::Context> = &self.page_default_context;- self.with_context_scope_by_ptr(context_ptr, |scope, _| {- set_date_timezone_override_for_current_context(scope, timezone);- Ok(())- })+ pub(super) fn set_timezone_override(&self, timezone: Option<&str>) {+ self._context_host.borrow().set_timezone_override(timezone);}pub(super) fn set_emulated_media(diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rsindex 5d80213a4..b3eb28012 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs@@ -92,16 +92,15 @@ fn service_worker_csp_report_seen(#[test]fn date_locale_methods_use_shared_time_formatting_surface() {let mut vm = new_storage_test_vm("https://date-locale-formatting.test/");+ vm.set_timezone_override(Some("UTC"));let us = vm.eval("new Date(0).toLocaleString()").expect("default Date locale formatting should evaluate");assert_eq!(us, "1/1/1970, 12:00:00 AM");- vm.set_locale_override_and_sync_surface(Some("fr-FR"))- .expect("Date locale override should sync into private surface");- vm.set_timezone_override_and_sync_surface(Some("Asia/Shanghai"))- .expect("Date timezone override should sync into private surface");+ vm.set_locale_override(Some("fr-FR"));+ vm.set_timezone_override(Some("Asia/Shanghai"));let result = vm.eval(@@ -140,9 +139,268 @@ fn date_locale_methods_use_shared_time_formatting_surface() {);}+#[test]+fn emulation_defaults_drive_real_intl_and_local_date_operations() {+ let mut vm = new_storage_test_vm("https://date-locale-emulation-surface.test/");+ let baseline = vm+ .eval(+ r#"+(() => {+ const date = new Date('2024-01-01T00:00:00Z');+ return JSON.stringify([+ new Intl.NumberFormat().resolvedOptions().locale,+ new Intl.DateTimeFormat().resolvedOptions().timeZone,+ date.getTimezoneOffset(),+ date.getFullYear(),+ date.getMonth(),+ date.getDate(),+ date.getDay(),+ date.getHours(),+ date.getMinutes(),+ date.getSeconds(),+ date.getMilliseconds(),+ date.toString(),+ date.toDateString(),+ date.toTimeString()+ ]);+})()+"#,+ )+ .expect("baseline Intl and Date surfaces should evaluate");+ vm.set_locale_override(Some("fr-FR"));+ vm.set_timezone_override(Some("Europe/Paris"));++ let result = vm+ .eval(+ r#"+(() => {+ const winter = new Date('2024-01-01T00:00:00Z');+ const summer = new Date('2024-07-01T00:00:00Z');+ return JSON.stringify({+ locales: [+ new Intl.Collator().resolvedOptions().locale,+ new Intl.DateTimeFormat().resolvedOptions().locale,+ new Intl.NumberFormat().resolvedOptions().locale,+ new Intl.PluralRules().resolvedOptions().locale+ ],+ timezone: new Intl.DateTimeFormat().resolvedOptions().timeZone,+ formattedAsFrench: new Intl.NumberFormat().format(1.5).endsWith(',5'),+ winter: [winter.getTimezoneOffset(), winter.getHours(), winter.getDate()],+ summer: [summer.getTimezoneOffset(), summer.getHours(), summer.getDate()],+ strings: [winter.toString(), winter.toDateString(), winter.toTimeString()],+ explicit: [+ new Intl.NumberFormat('en-US').resolvedOptions().locale,+ new Intl.DateTimeFormat('en-US', { timeZone: 'UTC' }).resolvedOptions().timeZone+ ],+ invalidOptions: (() => {+ try { new Intl.DateTimeFormat(undefined, null); return 'accepted'; }+ catch (error) { return error.name; }+ })(),+ navigatorLanguage: navigator.language+ });+})()+"#,+ )+ .expect("Intl and Date emulation surfaces should evaluate");++ assert_eq!(+ result,+ r#"{"locales":["fr-FR","fr-FR","fr-FR","fr-FR"],"timezone":"Europe/Paris","formattedAsFrench":true,"winter":[-60,1,1],"summer":[-120,2,1],"strings":["Mon Jan 01 2024 01:00:00 GMT+0100","Mon Jan 01 2024","01:00:00 GMT+0100"],"explicit":["en-US","UTC"],"invalidOptions":"TypeError","navigatorLanguage":"en-US"}"#+ );++ vm.set_locale_override(None);+ vm.set_timezone_override(None);+ let restored = vm+ .eval(+ r#"+(() => {+ const date = new Date('2024-01-01T00:00:00Z');+ return JSON.stringify([+ new Intl.NumberFormat().resolvedOptions().locale,+ new Intl.DateTimeFormat().resolvedOptions().timeZone,+ date.getTimezoneOffset(),+ date.getFullYear(),+ date.getMonth(),+ date.getDate(),+ date.getDay(),+ date.getHours(),+ date.getMinutes(),+ date.getSeconds(),+ date.getMilliseconds(),+ date.toString(),+ date.toDateString(),+ date.toTimeString()+ ]);+})()+"#,+ )+ .expect("restored Intl and Date surfaces should evaluate");+ assert_eq!(restored, baseline);+}++#[test]+fn emulation_preserves_intl_construction_and_complete_local_date_operations() {+ let mut vm = new_storage_test_vm("https://date-locale-native-semantics.test/");+ vm.set_locale_override(Some("fr-FR"));+ vm.set_timezone_override(Some("America/New_York"));++ let result = vm+ .eval(+ r#"+(() => {+ let timeZoneReads = 0;+ let getterReceiverPreserved = false;+ const options = {+ get timeZone() {+ timeZoneReads += 1;+ getterReceiverPreserved = this === options;+ return undefined;+ }+ };+ const optionFormat = new Intl.DateTimeFormat(undefined, options);++ class DerivedNumberFormat extends Intl.NumberFormat {}+ const numberFormat = new DerivedNumberFormat();+ class DerivedDate extends Date {}+ const derivedDate = new DerivedDate(2024, 0, 1);++ const setter = new Date('2024-01-01T05:00:00Z');+ const setterResult = setter.setHours(12, 34, 56, 789);+ const gapSetter = new Date('2024-03-10T06:30:00Z');+ gapSetter.setHours(2, 30, 0, 0);+ const revived = new Date(NaN);+ revived.setFullYear(2024, 0, 1);++ const explicitLocaleOptions = {+ timeZone: 'UTC', year: 'numeric', month: '2-digit', day: '2-digit',+ hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23'+ };+ const explicitLocaleDate = new Date('2024-01-01T00:00:00Z');++ return JSON.stringify({+ intlSubclass: [+ numberFormat instanceof DerivedNumberFormat,+ numberFormat instanceof Intl.NumberFormat,+ Object.getPrototypeOf(numberFormat) === DerivedNumberFormat.prototype,+ numberFormat.resolvedOptions().locale+ ],+ options: [+ timeZoneReads,+ getterReceiverPreserved,+ optionFormat.resolvedOptions().timeZone+ ],+ dateSubclass: [+ derivedDate instanceof DerivedDate,+ derivedDate instanceof Date,+ Object.getPrototypeOf(derivedDate) === DerivedDate.prototype,+ derivedDate.toISOString()+ ],+ constructors: [+ new Date(2024, 0, 1).toISOString(),+ new Date(2024, 6, 1).toISOString(),+ new Date(2024, 2, 10, 2, 30).toISOString(),+ new Date(2024, 10, 3, 1, 30).toISOString()+ ],+ parsing: [+ new Date('2024-01-01T00:00:00').toISOString(),+ new Date(Date.parse('2024-01-01T00:00:00')).toISOString(),+ new Date('2024-01-01').toISOString(),+ new Date('2024-01-01T00:00:00+02:00').toISOString()+ ],+ setters: [setterResult, setter.toISOString(), gapSetter.toISOString(), revived.toISOString()],+ functionCallUsesOverride: /GMT-0[45]00/.test(Date()),+ explicitLocalePreserved:+ explicitLocaleDate.toLocaleString('en-US', explicitLocaleOptions) ===+ new Intl.DateTimeFormat('en-US', explicitLocaleOptions).format(explicitLocaleDate),+ reflection: [+ Date.name,+ Date.length,+ typeof Date.UTC,+ typeof Date.parse,+ Object.getOwnPropertyDescriptor(Date, 'UTC').enumerable,+ Intl.NumberFormat.name,+ Intl.NumberFormat.length,+ typeof Intl.NumberFormat.supportedLocalesOf+ ]+ });+})()+"#,+ )+ .expect("native Intl and complete local Date semantics should evaluate");++ assert_eq!(+ result,+ r#"{"intlSubclass":[true,true,true,"fr-FR"],"options":[1,true,"America/New_York"],"dateSubclass":[true,true,true,"2024-01-01T05:00:00.000Z"],"constructors":["2024-01-01T05:00:00.000Z","2024-07-01T04:00:00.000Z","2024-03-10T07:30:00.000Z","2024-11-03T05:30:00.000Z"],"parsing":["2024-01-01T05:00:00.000Z","2024-01-01T05:00:00.000Z","2024-01-01T00:00:00.000Z","2023-12-31T22:00:00.000Z"],"setters":[1704130496789,"2024-01-01T17:34:56.789Z","2024-03-10T07:30:00.000Z","2024-01-01T05:00:00.000Z"],"functionCallUsesOverride":true,"explicitLocalePreserved":true,"reflection":["Date",7,"function","function",false,"NumberFormat",0,"function"]}"#+ );+}++#[test]+fn date_locale_override_updates_reach_existing_main_child_and_isolated_realms() {+ let mut vm = new_parsed_test_vm(+ "https://date-locale-shared-state.test/",+ "<!doctype html><html><body></body></html>",+ );+ vm.eval(+ r#"+const iframe = document.createElement("iframe");+iframe.srcdoc = "<!doctype html><html><body></body></html>";+document.body.appendChild(iframe);+"ready"+"#,+ )+ .expect("child Date/Intl realm setup should evaluate");+ vm.drain_pending_child_frame_work_for_test();++ let child_context_id = vm+ .live_child_default_runtime_realm_inventory()+ .into_iter()+ .next()+ .expect("child Date/Intl realm should be materialized")+ .context_id;+ let top_isolated_context_id = vm+ .create_isolated_world("date-locale-shared-state", false)+ .expect("top isolated Date/Intl realm should be created");+ const PROBE: &str = r#"+[+ new Intl.DateTimeFormat().resolvedOptions().locale,+ new Intl.DateTimeFormat().resolvedOptions().timeZone,+ new Date(0).getHours()+].join("|")+"#;++ vm.set_locale_override(Some("fr-FR"));+ vm.set_timezone_override(Some("Asia/Shanghai"));+ assert_eq!(vm.eval(PROBE).unwrap(), "fr-FR|Asia/Shanghai|8");+ assert_eq!(+ vm.eval_in_child_default_context(child_context_id, PROBE)+ .unwrap(),+ "fr-FR|Asia/Shanghai|8"+ );+ assert_eq!(+ vm.eval_in_isolated_context(top_isolated_context_id, PROBE)+ .unwrap(),+ "fr-FR|Asia/Shanghai|8"+ );++ vm.set_locale_override(Some("en-US"));+ vm.set_timezone_override(Some("America/New_York"));+ assert_eq!(vm.eval(PROBE).unwrap(), "en-US|America/New_York|19");+ assert_eq!(+ vm.eval_in_child_default_context(child_context_id, PROBE)+ .unwrap(),+ "en-US|America/New_York|19"+ );+ assert_eq!(+ vm.eval_in_isolated_context(top_isolated_context_id, PROBE)+ .unwrap(),+ "en-US|America/New_York|19"+ );+}+#[test]fn date_locale_methods_are_declared_on_date_prototype() {let mut vm = new_storage_test_vm("https://date-locale-declared.test/");+ vm.set_timezone_override(Some("UTC"));let result = vm.eval(diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rsindex 567783d92..021a57e66 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs@@ -3498,8 +3498,7 @@ fn document_last_modified_uses_source_time_and_readonly_document_accessor() {let mut vm = new_storage_test_vm("https://document-last-modified.test/");vm.document_runtime.set_document_source_last_modified(Some(5_025_000.0));- vm.set_timezone_override_and_sync_surface(Some("Asia/Shanghai"))- .expect("timezone override should sync into the Date surface");+ vm.set_timezone_override(Some("Asia/Shanghai"));let result = vm.eval(diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rsindex 154626bac..d9f3a61b2 100644--- a/moli-renderer-v8/src/util.rs+++ b/moli-renderer-v8/src/util.rs@@ -1,5 +1,5 @@use super::document_runtime::DomHandle;-use super::native_bridge::JsContextHost;+use super::native_bridge::{DateLocaleRuntimeState, JsContextHost};pub use moli_v8_util::{array_contains_strict, array_push_value, call_object_method, callback_data_index_value,callback_data_item, constructor_object, constructor_prototype, constructor_prototype_object,@@ -396,6 +396,10 @@ pub(super) fn install_context_host_pointer_slot() {let host_ptr =NonNull::new(host_ptr).expect("V8 context JsContextHost pointer should not be null");+ // SAFETY: the caller installs context slots while the owning ScriptVm's+ // `Rc<RefCell<JsContextHost>>` is alive. Clone the independently owned+ // Date/Intl state before exposing the context to script.+ let date_locale_runtime_state = unsafe { host_ptr.as_ref() }.date_locale_runtime_state();let previous = context.set_slot(Rc::new(ContextHostPointerSlot(host_ptr)));assert!(previous@@ -403,6 +407,19 @@ pub(super) fn install_context_host_pointer_slot(.is_none_or(|previous| previous.0 == host_ptr),"V8 context JsContextHost pointer must not be rebound");+ let previous = context.set_slot(Rc::clone(&date_locale_runtime_state));+ assert!(+ previous+ .as_ref()+ .is_none_or(|previous| Rc::ptr_eq(previous, &date_locale_runtime_state)),+ "V8 context Date/Intl runtime state must not be rebound"+ );+}++pub(super) fn date_locale_runtime_state_from_context(+ context: v8::Local<'_, v8::Context>,+) -> Option<Rc<DateLocaleRuntimeState>> {+ context.get_slot::<DateLocaleRuntimeState>()}pub(super) fn context_host_ptr_from_context_slot(diff --git a/moli-test-support/src/lib.rs b/moli-test-support/src/lib.rsindex 70976adbe..e5278d8ea 100644--- a/moli-test-support/src/lib.rs+++ b/moli-test-support/src/lib.rs@@ -139,7 +139,7 @@ const BROWSER_SURFACE_COMPAT_HTML: &str = concat!("document.body.setAttribute('data-location-after-replace', location.pathname + location.search);","</script></body></html>");-const DATE_LOCALE_DETAILS_HTML: &str = "<!doctype html><html><body data-locale-string=\"\" data-locale-date=\"\" data-locale-time=\"\" data-invalid=\"\"><script>const d=new Date(Date.UTC(2024,2,24,16,5,6));document.body.setAttribute('data-locale-string', d.toLocaleString('en-US'));document.body.setAttribute('data-locale-date', d.toLocaleDateString('en-US'));document.body.setAttribute('data-locale-time', d.toLocaleTimeString('en-US'));document.body.setAttribute('data-invalid', new Date(NaN).toLocaleString('en-US'));</script></body></html>";+const DATE_LOCALE_DETAILS_HTML: &str = "<!doctype html><html><body data-locale-string=\"\" data-locale-date=\"\" data-locale-time=\"\" data-invalid=\"\"><script>const d=new Date(Date.UTC(2024,2,24,16,5,6));const options={timeZone:'UTC'};document.body.setAttribute('data-locale-string', d.toLocaleString('en-US',options));document.body.setAttribute('data-locale-date', d.toLocaleDateString('en-US',options));document.body.setAttribute('data-locale-time', d.toLocaleTimeString('en-US',options));document.body.setAttribute('data-invalid', new Date(NaN).toLocaleString('en-US',options));</script></body></html>";const BROWSER_SURFACE_DETAILS_HTML: &str = "<!doctype html><html><body data-mime-tag=\"\" data-plugin-tag=\"\" data-storage-tag=\"\" data-mime-item-hit=\"\" data-mime-named-item-hit=\"\" data-plugin-item-hit=\"\" data-plugin-named-item-hit=\"\" data-mime-item-null=\"\" data-mime-named-item-null=\"\" data-plugin-item-null=\"\" data-plugin-named-item-null=\"\" data-plugin-refresh-undefined=\"\" data-storage-prototype=\"\" data-storage-roundtrip=\"\" data-storage-length-after-set=\"\" data-storage-key0=\"\" data-storage-length-after-remove=\"\" data-history-scroll-restoration=\"\"><script>document.body.setAttribute('data-mime-tag', Object.prototype.toString.call(navigator.mimeTypes));document.body.setAttribute('data-plugin-tag', Object.prototype.toString.call(navigator.plugins));document.body.setAttribute('data-storage-tag', Object.prototype.toString.call(localStorage));document.body.setAttribute('data-mime-item-hit', String(navigator.mimeTypes.item(0)?.type ?? 'null'));document.body.setAttribute('data-mime-named-item-hit', String(navigator.mimeTypes.namedItem('application/pdf')?.type ?? 'null'));document.body.setAttribute('data-plugin-item-hit', String(navigator.plugins.item(0)?.name ?? 'null'));document.body.setAttribute('data-plugin-named-item-hit', String(navigator.plugins.namedItem('PDF Viewer')?.name ?? 'null'));document.body.setAttribute('data-mime-item-null', String(navigator.mimeTypes.item(999)===null));document.body.setAttribute('data-mime-named-item-null', String(navigator.mimeTypes.namedItem('application/x-missing')===null));document.body.setAttribute('data-plugin-item-null', String(navigator.plugins.item(999)===null));document.body.setAttribute('data-plugin-named-item-null', String(navigator.plugins.namedItem('Missing Plugin')===null));document.body.setAttribute('data-plugin-refresh-undefined', String(navigator.plugins.refresh()===undefined));document.body.setAttribute('data-storage-prototype', String(Storage.prototype.isPrototypeOf(localStorage) && Storage.prototype.isPrototypeOf(sessionStorage)));localStorage.clear();localStorage.setItem('alpha','1');document.body.setAttribute('data-storage-roundtrip', String(localStorage.getItem('alpha')));document.body.setAttribute('data-storage-length-after-set', String(localStorage.length));document.body.setAttribute('data-storage-key0', String(localStorage.key(0)));localStorage.removeItem('alpha');document.body.setAttribute('data-storage-length-after-remove', String(localStorage.length));document.body.setAttribute('data-history-scroll-restoration', String(history.scrollRestoration));</script></body></html>";const HISTORY_RELATIVE_URL_UPDATE_HTML: &str =include_str!("../../moli-core/tests/fixtures/runtime/history_relative_url_update.html");diff --git a/moli-time/Cargo.toml b/moli-time/Cargo.tomlindex 4827470f9..aa84172be 100644--- a/moli-time/Cargo.toml+++ b/moli-time/Cargo.toml@@ -5,6 +5,7 @@ version = "0.1.0"edition = "2024"[dependencies]+temporal_rs = { version = "0.2.6", default-features = false, features = ["compiled_data"] }time = { version = "0.3", features = ["large-dates", "local-offset"] }[lints]diff --git a/moli-time/src/lib.rs b/moli-time/src/lib.rsindex 871c05a53..bb499e28c 100644--- a/moli-time/src/lib.rs+++ b/moli-time/src/lib.rs@@ -8,16 +8,26 @@ use std::{sync::OnceLock,time::{Duration, Instant, SystemTime, UNIX_EPOCH},};+use temporal_rs::{+ PlainDateTime, TimeZone,+ options::Disambiguation,+ provider::{COMPILED_TZ_PROVIDER, TimeZoneProvider},+};mod timers;pub use timers::{ReadyTimer, TimerId, TimerReadyAllowance, TimerScheduler};#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub enum DateLocaleFormatKind {- DateTime,- DateOnly,- TimeOnly,+pub struct LocalDateFields {+ pub year: i32,+ pub month_zero_based: u8,+ pub day: u8,+ pub weekday_sunday_zero: u8,+ pub hour: u8,+ pub minute: u8,+ pub second: u8,+ pub millisecond: u16,}pub fn unix_epoch_millis() -> f64 {@@ -63,47 +73,6 @@ pub fn dom_time_since_origin_millis(time_origin: f64) -> f64 {coarsened_dom_time_millis((unix_epoch_millis() - time_origin).max(0.0))}-pub fn format_date_locale_value(- timestamp_ms: f64,- kind: DateLocaleFormatKind,- locale_override: Option<&str>,- timezone_override: Option<&str>,-) -> String {- let Some(datetime) = offset_datetime_from_unix_millis(timestamp_ms) else {- return "Invalid Date".to_owned();- };- let datetime = datetime.to_offset(resolve_time_zone_offset(timezone_override));- let month = u8::from(datetime.month());- let day = datetime.day();- let year = datetime.year();- let hour24 = datetime.hour();- let minute = datetime.minute();- let second = datetime.second();- let (hour12, meridiem) = match hour24 {- 0 => (12, "AM"),- 1..=11 => (hour24, "AM"),- 12 => (12, "PM"),- _ => (hour24 - 12, "PM"),- };- let locale = locale_override.unwrap_or("en-US").to_ascii_lowercase();- let is_french_like = locale.starts_with("fr");-- match kind {- DateLocaleFormatKind::DateTime if is_french_like => {- format!("{day:02}/{month:02}/{year} {hour24:02}:{minute:02}:{second:02}")- }- DateLocaleFormatKind::DateOnly if is_french_like => format!("{day:02}/{month:02}/{year}"),- DateLocaleFormatKind::TimeOnly if is_french_like => {- format!("{hour24:02}:{minute:02}:{second:02}")- }- DateLocaleFormatKind::DateTime => {- format!("{month}/{day}/{year}, {hour12}:{minute:02}:{second:02} {meridiem}")- }- DateLocaleFormatKind::DateOnly => format!("{month}/{day}/{year}"),- DateLocaleFormatKind::TimeOnly => format!("{hour12}:{minute:02}:{second:02} {meridiem}"),- }-}-/// Formats the source modification time exposed by `Document.lastModified`.////// The HTML surface uses the user's local time zone unless CDP has installed@@ -120,7 +89,7 @@ pub fn format_document_last_modified_value(.or_else(|| offset_datetime_from_unix_millis(current_timestamp_ms)).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);let offset = match timezone_override {- Some(timezone) => resolve_time_zone_offset(Some(timezone)),+ Some(timezone) => resolve_time_zone_offset(datetime, timezone),None => time::UtcOffset::local_offset_at(datetime).unwrap_or(time::UtcOffset::UTC),};let datetime = datetime.to_offset(offset);@@ -140,19 +109,196 @@ fn offset_datetime_from_unix_millis(timestamp_ms: f64) -> Option<time::OffsetDatif !timestamp_ms.is_finite() {return None;}- let nanos = (timestamp_ms * 1_000_000.0).round();- if !nanos.is_finite() || nanos < i128::MIN as f64 || nanos > i128::MAX as f64 {+ let whole_millis = timestamp_ms.trunc();+ if whole_millis < i128::MIN as f64 || whole_millis > i128::MAX as f64 {return None;}- time::OffsetDateTime::from_unix_timestamp_nanos(nanos as i128).ok()+ // Multiplying an epoch-sized millisecond value by 1e6 in f64 first loses+ // precision (current dates are already around 1.7e18 nanoseconds). Split+ // the value before scaling so integral ECMAScript Date milliseconds remain+ // exact and only the sub-millisecond remainder is rounded.+ let whole_nanos = (whole_millis as i128).checked_mul(1_000_000)?;+ let fractional_nanos = ((timestamp_ms - whole_millis) * 1_000_000.0).round() as i128;+ time::OffsetDateTime::from_unix_timestamp_nanos(whole_nanos.checked_add(fractional_nanos)?).ok()}-fn resolve_time_zone_offset(timezone_override: Option<&str>) -> time::UtcOffset {- match timezone_override.unwrap_or_default() {- "Asia/Shanghai" => time::UtcOffset::from_hms(8, 0, 0).unwrap_or(time::UtcOffset::UTC),- "UTC" | "Etc/UTC" | "GMT" => time::UtcOffset::UTC,- _ => time::UtcOffset::UTC,- }+fn unix_millis_from_offset_datetime(datetime: time::OffsetDateTime) -> f64 {+ const NANOS_PER_MILLISECOND: i128 = 1_000_000;+ let nanos = datetime.unix_timestamp_nanos();+ let whole_millis = nanos.div_euclid(NANOS_PER_MILLISECOND);+ let fractional_nanos = nanos.rem_euclid(NANOS_PER_MILLISECOND);+ whole_millis as f64 + fractional_nanos as f64 / NANOS_PER_MILLISECOND as f64+}++fn resolve_time_zone_offset(datetime: time::OffsetDateTime, timezone: &str) -> time::UtcOffset {+ let Some(offset_seconds) =+ time_zone_offset_seconds_at(datetime.unix_timestamp_nanos(), timezone)+ else {+ return time::UtcOffset::UTC;+ };+ time::UtcOffset::from_whole_seconds(offset_seconds).unwrap_or(time::UtcOffset::UTC)+}++/// Resolves the IANA time-zone offset used by local `Date` operations.+///+/// The lookup is timestamp-sensitive, so daylight-saving transitions follow+/// the same tzdb data used by Temporal instead of a fixed per-zone table.+pub fn time_zone_offset_seconds(timestamp_ms: f64, timezone: &str) -> Option<i32> {+ let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;+ time_zone_offset_seconds_at(datetime.unix_timestamp_nanos(), timezone)+}++pub fn local_time_zone_offset_seconds(timestamp_ms: f64) -> Option<i32> {+ let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;+ Some(+ time::UtcOffset::local_offset_at(datetime)+ .unwrap_or(time::UtcOffset::UTC)+ .whole_seconds(),+ )+}++/// Returns whether the compiled IANA database recognizes a time-zone name.+///+/// Protocol surfaces must reject an unknown override before publishing it to+/// a target. Date formatting deliberately has a UTC fallback for defensive+/// rendering, so using an offset lookup as validation after committing state+/// would turn an invalid CDP command into a misleading success.+pub fn is_valid_time_zone_identifier(timezone: &str) -> bool {+ !timezone.is_empty() && COMPILED_TZ_PROVIDER.get(timezone.as_bytes()).is_ok()+}++pub fn local_date_fields(timestamp_ms: f64, timezone: Option<&str>) -> Option<LocalDateFields> {+ let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;+ let offset = timezone+ .map(|timezone| resolve_time_zone_offset(datetime, timezone))+ .unwrap_or_else(|| {+ time::UtcOffset::local_offset_at(datetime).unwrap_or(time::UtcOffset::UTC)+ });+ let datetime = datetime.to_offset(offset);+ Some(LocalDateFields {+ year: datetime.year(),+ month_zero_based: u8::from(datetime.month()).saturating_sub(1),+ day: datetime.day(),+ weekday_sunday_zero: datetime.weekday().number_days_from_sunday(),+ hour: datetime.hour(),+ minute: datetime.minute(),+ second: datetime.second(),+ millisecond: datetime.millisecond(),+ })+}++/// Projects an instant into a UTC-shaped millisecond value whose fields are+/// the instant's local wall-clock fields in `timezone`.+///+/// V8's UTC Date setters already implement ECMAScript argument conversion and+/// field balancing. The renderer uses this projection as their temporary input+/// and converts the resulting fields back with+/// [`epoch_millis_for_local_wall_clock`], avoiding a second implementation of+/// Date's normalization rules.+pub fn local_wall_clock_as_utc_millis(timestamp_ms: f64, timezone: &str) -> Option<f64> {+ let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;+ let offset = resolve_time_zone_offset(datetime, timezone);+ let wall_clock = datetime+ .to_offset(offset)+ .replace_offset(time::UtcOffset::UTC);+ Some(unix_millis_from_offset_datetime(wall_clock))+}++/// Interprets the UTC fields of `wall_clock_utc_ms` as a local wall-clock time+/// in `timezone` and returns the corresponding ECMAScript epoch milliseconds.+///+/// Temporal's `Compatible` disambiguation matches legacy Date behavior: it+/// chooses the earlier instant for a repeated clock time and advances across a+/// daylight-saving gap.+pub fn epoch_millis_for_local_wall_clock(wall_clock_utc_ms: f64, timezone: &str) -> Option<f64> {+ let fields = offset_datetime_from_unix_millis(wall_clock_utc_ms)?;+ let date_time = PlainDateTime::try_new_iso(+ fields.year(),+ u8::from(fields.month()),+ fields.day(),+ fields.hour(),+ fields.minute(),+ fields.second(),+ fields.millisecond(),+ 0,+ 0,+ )+ .ok()?;+ let time_zone = TimeZone::try_from_identifier_str(timezone).ok()?;+ let zoned = date_time+ .to_zoned_date_time(time_zone, Disambiguation::Compatible)+ .ok()?;+ Some(zoned.epoch_milliseconds() as f64)+}++pub fn format_date_local_string(timestamp_ms: f64, timezone: Option<&str>) -> String {+ let Some(fields) = local_date_fields(timestamp_ms, timezone) else {+ return "Invalid Date".to_owned();+ };+ format!(+ "{} {} {:02} {:04} {}",+ weekday_name(fields.weekday_sunday_zero),+ month_name(fields.month_zero_based),+ fields.day,+ fields.year,+ format_date_local_time_string(timestamp_ms, timezone),+ )+}++pub fn format_date_local_date_string(timestamp_ms: f64, timezone: Option<&str>) -> String {+ let Some(fields) = local_date_fields(timestamp_ms, timezone) else {+ return "Invalid Date".to_owned();+ };+ format!(+ "{} {} {:02} {:04}",+ weekday_name(fields.weekday_sunday_zero),+ month_name(fields.month_zero_based),+ fields.day,+ fields.year,+ )+}++pub fn format_date_local_time_string(timestamp_ms: f64, timezone: Option<&str>) -> String {+ let Some(fields) = local_date_fields(timestamp_ms, timezone) else {+ return "Invalid Date".to_owned();+ };+ let offset_seconds = timezone+ .and_then(|timezone| time_zone_offset_seconds(timestamp_ms, timezone))+ .or_else(|| local_time_zone_offset_seconds(timestamp_ms))+ .unwrap_or_default();+ let sign = if offset_seconds < 0 { '-' } else { '+' };+ let offset_minutes = offset_seconds.unsigned_abs() / 60;+ let offset_hours = offset_minutes / 60;+ let offset_minutes = offset_minutes % 60;+ format!(+ "{:02}:{:02}:{:02} GMT{sign}{offset_hours:02}{offset_minutes:02}",+ fields.hour, fields.minute, fields.second,+ )+}++fn weekday_name(weekday_sunday_zero: u8) -> &'static str {+ ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]+ .get(usize::from(weekday_sunday_zero))+ .copied()+ .unwrap_or("Invalid")+}++fn month_name(month_zero_based: u8) -> &'static str {+ [+ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",+ ]+ .get(usize::from(month_zero_based))+ .copied()+ .unwrap_or("Invalid")+}++fn time_zone_offset_seconds_at(epoch_nanoseconds: i128, timezone: &str) -> Option<i32> {+ let id = COMPILED_TZ_PROVIDER.get(timezone.as_bytes()).ok()?;+ let seconds = COMPILED_TZ_PROVIDER+ .transition_nanoseconds_for_utc_epoch_nanoseconds(id, epoch_nanoseconds)+ .ok()?+ .0;+ i32::try_from(seconds).ok()}#[cfg(test)]@@ -160,86 +306,90 @@ mod tests {use super::*;#[test]- fn date_locale_format_matches_existing_en_us_and_fr_surface() {- let timestamp = 1_704_067_384_005.0;+ fn iana_timezone_offsets_follow_daylight_saving_transitions() {+ let winter = 1_704_067_200_000.0; // 2024-01-01T00:00:00Z+ let summer = 1_719_792_000_000.0; // 2024-07-01T00:00:00Z+ assert_eq!(time_zone_offset_seconds(winter, "Europe/Paris"), Some(3600));+ assert_eq!(time_zone_offset_seconds(summer, "Europe/Paris"), Some(7200));assert_eq!(- format_date_locale_value(timestamp, DateLocaleFormatKind::DateTime, None, Some("UTC")),- "1/1/2024, 12:03:04 AM"+ time_zone_offset_seconds(winter, "America/New_York"),+ Some(-18_000));+ assert_eq!(time_zone_offset_seconds(winter, "Not/AZone"), None);assert_eq!(- format_date_locale_value(- timestamp,- DateLocaleFormatKind::DateOnly,- Some("fr-FR"),- Some("UTC")- ),- "01/01/2024"+ local_date_fields(winter, Some("Europe/Paris")),+ Some(LocalDateFields {+ year: 2024,+ month_zero_based: 0,+ day: 1,+ weekday_sunday_zero: 1,+ hour: 1,+ minute: 0,+ second: 0,+ millisecond: 0,+ }));assert_eq!(- format_date_locale_value(- timestamp,- DateLocaleFormatKind::TimeOnly,- Some("fr"),- Some("UTC")- ),- "00:03:04"+ format_date_local_string(winter, Some("Europe/Paris")),+ "Mon Jan 01 2024 01:00:00 GMT+0100");}#[test]- fn date_locale_timezone_override_shifts_display_time() {+ fn time_zone_identifier_validation_uses_the_same_compiled_database() {+ assert!(is_valid_time_zone_identifier("UTC"));+ assert!(is_valid_time_zone_identifier("Europe/Paris"));+ assert!(!is_valid_time_zone_identifier(""));+ assert!(!is_valid_time_zone_identifier("Mars/Olympus"));+ }++ #[test]+ fn local_wall_clock_round_trips_through_the_selected_timezone() {+ let instant = 1_704_067_200_123.0; // 2024-01-01T00:00:00.123Z+ let wall_clock = local_wall_clock_as_utc_millis(instant, "Europe/Paris")+ .expect("Paris wall clock should project");+ assert_eq!(wall_clock, 1_704_070_800_123.0);assert_eq!(- format_date_locale_value(- 0.0,- DateLocaleFormatKind::DateTime,- Some("en-US"),- Some("Asia/Shanghai")- ),- "1/1/1970, 8:00:00 AM"+ epoch_millis_for_local_wall_clock(wall_clock, "Europe/Paris"),+ Some(instant));}#[test]- fn document_last_modified_uses_source_time_and_current_fallback() {+ fn epoch_millisecond_conversion_does_not_round_through_large_f64_nanoseconds() {+ for timestamp_ms in [-1.0, 0.0, 1_704_130_496_789.0] {+ let datetime = offset_datetime_from_unix_millis(timestamp_ms)+ .expect("ECMAScript timestamp should be representable");+ assert_eq!(unix_millis_from_offset_datetime(datetime), timestamp_ms);+ }+ }++ #[test]+ fn local_wall_clock_uses_legacy_date_dst_disambiguation() {+ // 2024-03-10T02:30 does not exist in New York. Compatible+ // disambiguation advances it to 03:30 EDT (07:30Z).assert_eq!(- format_document_last_modified_value(Some(5_025_000.0), 0.0, Some("Asia/Shanghai")),- "01/01/1970 09:23:45"+ epoch_millis_for_local_wall_clock(1_710_037_800_000.0, "America/New_York"),+ Some(1_710_055_800_000.0));+ // 2024-11-03T01:30 occurs twice. Legacy Date selects the earlier EDT+ // occurrence (05:30Z).assert_eq!(- format_document_last_modified_value(None, 1_704_067_384_005.0, Some("UTC")),- "01/01/2024 00:03:04"+ epoch_millis_for_local_wall_clock(1_730_597_400_000.0, "America/New_York"),+ Some(1_730_611_800_000.0));}#[test]- fn chromium_js_date_limits_stay_representable_with_large_dates() {- assert_eq!(- format_date_locale_value(- 8_640_000_000_000_000.0,- DateLocaleFormatKind::DateTime,- Some("en-US"),- Some("UTC")- ),- "9/13/275760, 12:00:00 AM"- );+ fn document_last_modified_uses_source_time_and_current_fallback() {assert_eq!(- format_date_locale_value(- f64::INFINITY,- DateLocaleFormatKind::DateTime,- Some("en-US"),- Some("UTC")- ),- "Invalid Date"+ format_document_last_modified_value(Some(5_025_000.0), 0.0, Some("Asia/Shanghai")),+ "01/01/1970 09:23:45");assert_eq!(- format_date_locale_value(- f64::NAN,- DateLocaleFormatKind::DateTime,- Some("en-US"),- Some("UTC")- ),- "Invalid Date"+ format_document_last_modified_value(None, 1_704_067_384_005.0, Some("UTC")),+ "01/01/2024 00:03:04");}