Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(history): extract native Window history storage
ldm074e924c8640a
diff --git a/Cargo.lock b/Cargo.lockindex 48764e4db..0fd014a86 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2719,6 +2719,14 @@ dependencies = ["serde_json",]+[[package]]+name = "moli-history"+version = "0.1.0"+dependencies = [+ "moli-session-history",+ "moli-structured-clone",+]+[[package]]name = "moli-html-input-temporal"version = "0.1.0"@@ -2888,6 +2896,7 @@ dependencies = ["moli-disk-pool","moli-dom","moli-fetch",+ "moli-history","moli-parkable-image","moli-session-history","moli-web-mime",@@ -3094,6 +3103,7 @@ dependencies = ["moli-fetch","moli-file-api","moli-geometry",+ "moli-history","moli-html2md","moli-http-cache","moli-image",diff --git a/Cargo.toml b/Cargo.tomlindex 2cabafaad..bedd19076 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -81,6 +81,7 @@ members = ["moli-file-api","moli-geometry","moli-header-field",+ "moli-history","moli-html-input-type","moli-html2md","moli-html-input-temporal",diff --git a/moli-history/Cargo.toml b/moli-history/Cargo.tomlnew file mode 100644index 000000000..c844feffe--- /dev/null+++ b/moli-history/Cargo.toml@@ -0,0 +1,13 @@+[package]+license.workspace = true+name = "moli-history"+version = "0.1.0"+edition = "2024"+description = "Native Window history records and state for Moli"++[dependencies]+moli-session-history = { path = "../moli-session-history" }+moli-structured-clone = { path = "../moli-structured-clone" }++[lints]+workspace = truediff --git a/moli-history/README.md b/moli-history/README.mdnew file mode 100644index 000000000..f0c4ab8ab--- /dev/null+++ b/moli-history/README.md@@ -0,0 +1,11 @@+# moli-history++Native per-Window history storage. This crate has no dependency on V8 or JavaScript objects.++- `WindowHistory` owns the entry list, current index, and state cache revision. Push and replace operations preserve forward-entry and scroll-restoration semantics.+- `HistoryEntry` stores URL and identity metadata, scroll position and restoration mode, and immutable serialized History/Navigation state.+- Entry references can outlive their membership in a history, so a retained `NavigationHistoryEntry` remains readable after replacement or pruning.++`moli-session-history` coordinates the traversable's joint history across documents and frames. `moli-history` stores each Window's native view of those entries. `moli-page-types` transports serialized snapshots across document or VM replacement.++The renderer provides the structured-clone codec and JS bindings. World-specific `History` wrappers share the same native `WindowHistory`; each caches its own deserialized `history.state`. Weak V8 wrapper registrations lease native records without keeping JS contexts alive. Serialized values contain immutable bytes and trusted native attachments such as Blob data, never realm-local JS handles.diff --git a/moli-history/src/entry.rs b/moli-history/src/entry.rsnew file mode 100644index 000000000..1911ac21d--- /dev/null+++ b/moli-history/src/entry.rs@@ -0,0 +1,42 @@+use std::{cell::RefCell, rc::Rc};++use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};+use moli_structured_clone::SerializedScriptValue;++pub type HistoryEntryRef = Rc<RefCell<HistoryEntry>>;++#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub enum ScrollRestoration {+ #[default]+ Auto,+ Manual,+}++impl ScrollRestoration {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Auto => "auto",+ Self::Manual => "manual",+ }+ }+}++#[derive(Clone, Debug)]+pub struct HistoryEntry {+ pub url: String,+ pub id: String,+ pub key: NavigationHistoryEntryKey,+ pub document: NavigationHistoryDocumentId,+ pub index: u32,+ pub referrer_policy: Option<String>,+ pub history_state: Option<SerializedScriptValue>,+ pub navigation_state: Option<SerializedScriptValue>,+ pub scroll_restoration: ScrollRestoration,+ pub scroll_offset: Option<(f64, f64)>,+}++impl HistoryEntry {+ pub fn into_ref(self) -> HistoryEntryRef {+ Rc::new(RefCell::new(self))+ }+}diff --git a/moli-history/src/lib.rs b/moli-history/src/lib.rsnew file mode 100644index 000000000..5f28e0115--- /dev/null+++ b/moli-history/src/lib.rs@@ -0,0 +1,16 @@+//! Native history owned by a Window, independent of JavaScript objects.+//!+//! `moli-session-history` remains the authority for the traversable's joint+//! steps. This crate owns the Window's entries, cursor, and serialized state.+//! Bindings may retain an entry after it leaves the history (for example for+//! NavigationHistoryEntry.dispose), without retaining its former Window.++mod entry;+mod window;++pub use entry::{HistoryEntry, HistoryEntryRef, ScrollRestoration};+pub use moli_structured_clone::SerializedScriptValue;+pub use window::WindowHistory;++#[cfg(test)]+mod tests;diff --git a/moli-history/src/tests.rs b/moli-history/src/tests.rsnew file mode 100644index 000000000..00b94345c--- /dev/null+++ b/moli-history/src/tests.rs@@ -0,0 +1,94 @@+use std::rc::Rc;++use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};++use crate::*;++fn entry(id: &str) -> HistoryEntryRef {+ HistoryEntry {+ url: format!("https://example.test/#{id}"),+ id: id.to_owned(),+ key: NavigationHistoryEntryKey::allocate(),+ document: NavigationHistoryDocumentId::allocate(),+ index: 0,+ referrer_policy: None,+ history_state: None,+ navigation_state: None,+ scroll_restoration: ScrollRestoration::Auto,+ scroll_offset: None,+ }+ .into_ref()+}++#[test]+fn pushing_after_a_traversal_discards_only_forward_entries() {+ let first = entry("first");+ let second = entry("second");+ let third = entry("third");+ let mut history = WindowHistory::new(vec![first.clone(), second.clone(), third.clone()], 2);+ history.set_current_index(0);+ let replacement = entry("replacement");+ let removed = history.push(replacement.clone());+ assert_eq!(history.current_index(), 1);+ assert_eq!(history.entries().len(), 2);+ assert!(Rc::ptr_eq(&history.entries()[0], &first));+ assert!(Rc::ptr_eq(history.current_entry().unwrap(), &replacement));+ assert!(Rc::ptr_eq(&removed[0], &second));+ assert!(Rc::ptr_eq(&removed[1], &third));+ // A retained entry remains readable after leaving its former history.+ drop(history);+ assert_eq!(removed[0].borrow().url, "https://example.test/#second");+}++#[test]+fn replacement_preserves_forward_history_and_retained_old_entry() {+ let first = entry("first");+ let next = entry("next");+ let mut history = WindowHistory::new(vec![first.clone(), next.clone()], 0);+ let replacement = entry("replacement");+ let old = history.replace(replacement.clone()).unwrap();+ assert!(Rc::ptr_eq(&old, &first));+ assert_eq!(history.current_index(), 0);+ assert!(Rc::ptr_eq(&history.entries()[1], &next));+ assert!(Rc::ptr_eq(history.current_entry().unwrap(), &replacement));+}++#[test]+fn scroll_restoration_is_inherited_then_restored_per_entry() {+ let mut history = WindowHistory::new(vec![entry("first")], 0);+ history.set_scroll_restoration(ScrollRestoration::Manual);+ history.push(entry("second"));+ assert_eq!(history.scroll_restoration(), ScrollRestoration::Manual);+ history.set_scroll_restoration(ScrollRestoration::Auto);+ history.set_current_index(0);+ assert_eq!(history.scroll_restoration(), ScrollRestoration::Manual);+ history.set_current_index(1);+ assert_eq!(history.scroll_restoration(), ScrollRestoration::Auto);+}++#[test]+fn revisiting_a_serialized_snapshot_invalidates_the_bindings_cache() {+ let snapshot = SerializedScriptValue::new(vec![1, 2, 3], ());+ let mut history = WindowHistory::new(vec![entry("first")], 0);+ history.set_state(Some(snapshot.clone()));+ let first_revision = history.revision();+ history.push(entry("second"));+ history.set_current_index(0);+ assert!(history.revision() > first_revision);+ assert_eq!(history.state(), Some(snapshot.clone()));+ drop(history);+ assert_eq!(snapshot.bytes(), &[1, 2, 3]);+}++#[test]+fn pruning_other_entries_preserves_current_state_identity() {+ let current = entry("current");+ let mut history =+ WindowHistory::new(vec![entry("previous"), current.clone(), entry("next")], 1);+ let revision = history.revision();+ history.restore_entries(vec![current.clone()]);+ history.set_current_index(0);+ assert_eq!(history.current_index(), 0);+ assert_eq!(history.revision(), revision);+ assert!(Rc::ptr_eq(history.current_entry().unwrap(), ¤t));+}diff --git a/moli-history/src/window.rs b/moli-history/src/window.rsnew file mode 100644index 000000000..6e0b6af71--- /dev/null+++ b/moli-history/src/window.rs@@ -0,0 +1,112 @@+use crate::{HistoryEntryRef, ScrollRestoration, SerializedScriptValue};++/// No wrappers or engine handles are stored here. A binding's state cache is+/// invalidated by `revision`, including when a traversal returns to an entry+/// whose original serialized state has not changed.+#[derive(Debug)]+pub struct WindowHistory {+ entries: Vec<HistoryEntryRef>,+ current: u32,+ revision: u64,+}++impl WindowHistory {+ pub fn new(entries: Vec<HistoryEntryRef>, current: u32) -> Self {+ Self {+ entries,+ current,+ revision: 0,+ }+ }++ pub fn entries(&self) -> &[HistoryEntryRef] {+ &self.entries+ }++ pub fn current_index(&self) -> u32 {+ self.current+ }++ pub fn current_entry(&self) -> Option<&HistoryEntryRef> {+ self.entries.get(self.current as usize)+ }++ pub fn revision(&self) -> u64 {+ self.revision+ }++ fn invalidate_state_cache(&mut self) {+ self.revision = self+ .revision+ .checked_add(1)+ .expect("history revision exhausted");+ }++ pub fn set_current_index(&mut self, index: u32) {+ if self.current != index {+ self.current = index;+ self.invalidate_state_cache();+ }+ }++ /// Preserve the selected record and its JS state identity when pruning+ /// unrelated entries. The binding can then select a different restored+ /// index explicitly when installing a new history view.+ pub fn restore_entries(&mut self, entries: Vec<HistoryEntryRef>) {+ let retained_current = self.current_entry().and_then(|current| {+ entries+ .iter()+ .position(|entry| std::rc::Rc::ptr_eq(current, entry))+ });+ self.entries = entries;+ if let Some(index) = retained_current {+ self.current = index as u32;+ } else {+ self.invalidate_state_cache();+ }+ }++ pub fn push(&mut self, entry: HistoryEntryRef) -> Vec<HistoryEntryRef> {+ let restoration = self.scroll_restoration();+ entry.borrow_mut().scroll_restoration = restoration;+ let next = (self.current as usize + 1).min(self.entries.len());+ let removed = self.entries.split_off(next);+ self.entries.push(entry);+ self.current = next as u32;+ self.invalidate_state_cache();+ removed+ }++ pub fn replace(&mut self, entry: HistoryEntryRef) -> Option<HistoryEntryRef> {+ let restoration = self.scroll_restoration();+ entry.borrow_mut().scroll_restoration = restoration;+ let current = self.entries.get_mut(self.current as usize)?;+ let previous = std::mem::replace(current, entry);+ self.invalidate_state_cache();+ Some(previous)+ }++ pub fn state(&self) -> Option<SerializedScriptValue> {+ self.current_entry()?.borrow().history_state.clone()+ }++ pub fn set_state(&mut self, state: Option<SerializedScriptValue>) {+ if let Some(entry) = self.current_entry() {+ entry.borrow_mut().history_state = state;+ }+ self.invalidate_state_cache();+ }++ pub fn scroll_restoration(&self) -> ScrollRestoration {+ self.current_entry()+ .map_or(ScrollRestoration::Auto, |entry| {+ entry.borrow().scroll_restoration+ })+ }++ pub fn set_scroll_restoration(&mut self, value: ScrollRestoration) {+ if let Some(entry) = self.current_entry() {+ entry.borrow_mut().scroll_restoration = value;+ }+ }+}diff --git a/moli-page-types/Cargo.toml b/moli-page-types/Cargo.tomlindex 6e40b840b..e233bc27a 100644--- a/moli-page-types/Cargo.toml+++ b/moli-page-types/Cargo.toml@@ -16,6 +16,7 @@ moli-disk-pool = { path = "../moli-disk-pool" }moli-fetch = { path = "../moli-fetch" }moli-parkable-image = { path = "../moli-parkable-image" }moli-session-history = { path = "../moli-session-history" }+moli-history = { path = "../moli-history" }moli-web-mime = { path = "../moli-web-mime" }http-auth = { version = "0.1.10", default-features = false }regex = "1.12.3"diff --git a/moli-page-types/src/navigation_history.rs b/moli-page-types/src/navigation_history.rsindex bd32d135d..358c4b4d0 100644--- a/moli-page-types/src/navigation_history.rs+++ b/moli-page-types/src/navigation_history.rs@@ -47,7 +47,13 @@ fn allocate_navigation_history_entry_id(counter: &AtomicU64) -> NavigationHistor#[derive(Debug, Clone, PartialEq, Eq)]pub struct NavigationHistorySerializedEntry {pub url: String,+ /// Authoritative structured state, preserved across renderer replacement.+ pub history_state: Option<moli_history::SerializedScriptValue>,+ pub navigation_state: Option<moli_history::SerializedScriptValue>,+ pub scroll_restoration: moli_history::ScrollRestoration,+ /// Legacy/bootstrap input only; native snapshots use `history_state`.pub history_state_json: Option<String>,+ /// Legacy/bootstrap input only; native snapshots use `navigation_state`.pub navigation_state_json: Option<String>,pub referrer_policy: Option<String>,pub document_id: NavigationHistoryDocumentId,@@ -516,6 +522,9 @@ fn navigation_history_entry() -> NavigationHistorySerializedEntry {NavigationHistorySerializedEntry {url: url.to_owned(),+ history_state: None,+ navigation_state: None,+ scroll_restoration: Default::default(),history_state_json,navigation_state_json,referrer_policy: None,diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.tomlindex 39d56a0f0..7282e0e0c 100644--- a/moli-renderer-v8/Cargo.toml+++ b/moli-renderer-v8/Cargo.toml@@ -69,6 +69,7 @@ moli-owner-queue = { path = "../moli-owner-queue" }moli-paint = { path = "../moli-paint" }moli-script = { path = "../moli-script" }moli-session-history = { path = "../moli-session-history" }+moli-history = { path = "../moli-history" }moli-stylesheet-blocking = { path = "../moli-stylesheet-blocking" }moli-storage-key = { path = "../moli-storage-key" }moli-streams = { path = "../moli-streams" }diff --git a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs b/moli-renderer-v8/src/context_bootstrap/history_mutation.rsindex bd7e17b3f..d65001644 100644--- a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs+++ b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs@@ -1,14 +1,15 @@use super::history_runtime::require_fully_active_history_owner;+use super::history_runtime::state::{push_history_entry, replace_history_entry};use super::location_runtime::{location_href_slot, sync_location_object};use super::navigation_activation::bind_navigation_entry_runtime_owner;use super::navigation_callbacks::cancel_active_intercepted_same_document_navigation;use super::navigation_entry::{- copy_navigation_entry_document_id, create_navigation_entry, history_entries, history_index,+ cache_current_history_state, copy_navigation_entry_document_id, create_navigation_entry,navigation_current_entry, navigation_current_entry_index, navigation_entry_key_value,- new_navigation_entry_id, new_navigation_entry_key, set_history_entries, set_history_index,- set_history_state, stringify_history_state, sync_navigation_current_entry_from_history_entry,+ new_navigation_entry_id, new_navigation_entry_key,+ sync_navigation_current_entry_from_history_entry,};-use super::navigation_entry_state::{clone_history_entry_state, set_history_entry_state};+use super::navigation_entry_state::clone_history_entry_state;use super::navigation_events::{cancel_active_navigation_event, dispatch_navigation_currententrychange,dispatch_navigation_entry_dispose, dispatch_navigation_navigate_event_with_outcome,@@ -26,6 +27,7 @@ use super::navigation_window::{runtime_window_is_global, window_location_for_holder, window_navigation_for_holder,};use super::*;+use crate::structured_clone::{deserialize_history_state, serialize_history_state};use crate::webidl;struct ParsedHistoryMutationArgs<'s> {@@ -105,7 +107,7 @@ fn mutate_history_object<'s>(let Some(owner) = require_fully_active_history_owner(scope, history) else {return;};- let Some(state) = structured_clone_value_for_storage(scope, parsed.state) else {+ let Some(snapshot) = serialize_history_state(scope, parsed.state) else {return;};// Argument conversion/serialization belongs to the caller. Entry objects@@ -114,7 +116,9 @@ fn mutate_history_object<'s>(return;};let scope = &mut v8::ContextScope::new(scope, context);- let state_json = stringify_history_state(scope, state);+ let Some(state) = deserialize_history_state(scope, &snapshot) else {+ return;+ };let Some(location) = window_location_for_holder(scope, owner) else {return;};@@ -184,33 +188,16 @@ fn mutate_history_object<'s>(navigate_outcome = Some(outcome);}- let entries = history_entries(scope, history).unwrap_or_else(|| v8::Array::new(scope, 0));- let current_index = history_index(scope, history);let current_navigation_index = navigation_current_entry_index(scope, owner).unwrap_or(0);let previous_entry = navigation_current_entry(scope, owner);let mut pruned = Vec::new();let entry = match kind {HistoryMutationKind::Push => {- for index in current_index + 1..entries.length() {- if let Some(entry) = entries- .get_index(scope, index)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- {- pruned.push(entry);- }- }- let next_entries = v8::Array::new(scope, (current_index + 2) as i32);- for index in 0..=current_index {- if let Some(entry) = entries.get_index(scope, index) {- let _ = next_entries.set_index(scope, index, entry);- }- }- let next_index = current_index + 1;let next_navigation_index = current_navigation_index + 1;let entry = create_navigation_entry(scope,url.as_str(),- state_json.as_deref(),+ None,None,None,next_navigation_index,@@ -221,9 +208,7 @@ fn mutate_history_object<'s>(copy_navigation_entry_document_id(scope, previous_entry, entry);}bind_navigation_entry_runtime_owner(scope, entry, owner);- let _ = next_entries.set_index(scope, next_index, entry.into());- set_history_entries(scope, history, next_entries);- set_history_index(scope, history, next_index);+ pruned = push_history_entry(scope, history, entry);entry}HistoryMutationKind::Replace => {@@ -233,7 +218,7 @@ fn mutate_history_object<'s>(let entry = create_navigation_entry(scope,url.as_str(),- state_json.as_deref(),+ None,None,None,current_navigation_index,@@ -244,19 +229,18 @@ fn mutate_history_object<'s>(copy_navigation_entry_document_id(scope, previous_entry, entry);}bind_navigation_entry_runtime_owner(scope, entry, owner);- let _ = entries.set_index(scope, current_index, entry.into());- set_history_entries(scope, history, entries);+ replace_history_entry(scope, history, entry);entry}};- // `history.state` is a structured-clone value, not a JSON value. Keep the- // live entry's cloned snapshot authoritative even when the optional- // cross-runtime JSON projection cannot represent values such as Map,- // ArrayBuffer, or BigInt.- set_history_entry_state(scope, entry, state);+ // Keep the pre-event serialized snapshot authoritative even if a callback+ // has modified an exposed JS value during the navigation.+ if let Some(record) = super::history_runtime::native::entry(scope, entry) {+ record.borrow_mut().history_state = Some(snapshot);+ }let current_state =clone_history_entry_state(scope, entry).unwrap_or_else(|| v8::null(scope).into());- set_history_state(scope, history, current_state);+ cache_current_history_state(scope, history, current_state);sync_location_object(scope, location, url.as_str());sync_navigation_current_entry_from_history_entry(scope, owner, entry);super::session_history::commit(diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime.rsindex 46af67426..d6c46fca9 100644--- a/moli-renderer-v8/src/context_bootstrap/history_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime.rs@@ -1,5 +1,6 @@mod admission;pub(super) mod apply;+pub(super) mod native;pub(super) mod results;pub(super) mod state;pub(super) mod traversal;diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rsindex 15e755a63..3750c4724 100644--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs@@ -2,8 +2,8 @@ use super::super::location_runtime::{is_same_document_fragment_navigation, location_href_slot, sync_location_object,};use super::super::navigation_entry::{- history_entries, history_index, navigation_current_entry, navigation_entries_share_document,- navigation_entry_url_value, set_history_index, set_history_state,+ cache_current_history_state, history_entries, history_index, navigation_current_entry,+ navigation_entries_share_document, navigation_entry_url_value, set_history_index,sync_navigation_current_entry_from_history_entry,};use super::super::navigation_events::{@@ -87,7 +87,7 @@ pub(in crate::context_bootstrap) fn commit_prepared_history_entry<'s>(mut applied,} = prepared;set_history_index(scope, history, applied.history_index);- set_history_state(scope, history, applied.state);+ cache_current_history_state(scope, history, applied.state);sync_location_object(scope, location, &applied.url);sync_navigation_current_entry_from_history_entry(scope, applied.owner, applied.entry);applied.resolved_entry = navigation_current_entry(scope, applied.owner)diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rsnew file mode 100644index 000000000..3844fa9c1--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs@@ -0,0 +1,266 @@+//! Realm wrappers lease native records. The registry holds only weak V8+//! handles, so a wrapper/Window cycle cannot keep a retired history alive.++use std::{cell::RefCell, collections::HashMap, rc::Rc};++use moli_history::{HistoryEntryRef, WindowHistory};++use crate::util::{get_private_value, set_private_value, v8_string};++pub(in crate::context_bootstrap) type HistoryRef = Rc<RefCell<WindowHistory>>;+type Store = Rc<RefCell<NativeRecords>>;+const HISTORY_ID: &str = "__moliNativeHistory";+const ENTRY_ID: &str = "__moliNativeHistoryEntry";+const ENTRY_WRAPPERS: &str = "__moliNavigationEntryWrappers";++#[derive(Default)]+struct NativeRecords {+ next_id: u64,+ histories: HashMap<u64, (v8::Weak<v8::Object>, HistoryRef)>,+ entries: HashMap<u64, (v8::Weak<v8::Object>, HistoryEntryRef)>,+}++fn store(scope: &mut v8::PinScope<'_, '_>) -> Store {+ if let Some(store) = scope.get_slot::<Store>() {+ return store.clone();+ }+ let store = Store::default();+ scope.set_slot(store.clone());+ store+}++fn next_id(store: &Store) -> u64 {+ let mut store = store.borrow_mut();+ store.next_id = store+ .next_id+ .checked_add(1)+ .expect("native history identity exhausted");+ store.next_id+}++fn id<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ slot: &str,+) -> Option<u64> {+ let value = get_private_value(scope, object, slot)?;+ let value = v8::Local::<v8::BigInt>::try_from(value).ok()?;+ let (id, lossless) = value.u64_value();+ lossless.then_some(id)+}++pub(in crate::context_bootstrap) fn bind_history<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ wrapper: v8::Local<'s, v8::Object>,+ history: HistoryRef,+) {+ let store = store(scope);+ let id = next_id(&store);+ let weak_store = Rc::downgrade(&store);+ let weak = v8::Weak::with_finalizer(+ scope,+ wrapper,+ Box::new(move |_| {+ if let Some(store) = weak_store.upgrade() {+ store.borrow_mut().histories.remove(&id);+ }+ }),+ );+ store.borrow_mut().histories.insert(id, (weak, history));+ set_private_value(+ scope,+ wrapper,+ HISTORY_ID,+ v8::BigInt::new_from_u64(scope, id).into(),+ );+}++pub(in crate::context_bootstrap) fn history<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ wrapper: v8::Local<'s, v8::Object>,+) -> Option<HistoryRef> {+ let id = id(scope, wrapper, HISTORY_ID)?;+ scope+ .get_slot::<Store>()?+ .borrow()+ .histories+ .get(&id)+ .map(|(_, record)| record.clone())+}++pub(in crate::context_bootstrap) fn bind_entry<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ wrapper: v8::Local<'s, v8::Object>,+ entry: HistoryEntryRef,+) {+ let store = store(scope);+ let id = next_id(&store);+ let weak_store = Rc::downgrade(&store);+ let weak = v8::Weak::with_finalizer(+ scope,+ wrapper,+ Box::new(move |_| {+ if let Some(store) = weak_store.upgrade() {+ store.borrow_mut().entries.remove(&id);+ }+ }),+ );+ store.borrow_mut().entries.insert(id, (weak, entry));+ set_private_value(+ scope,+ wrapper,+ ENTRY_ID,+ v8::BigInt::new_from_u64(scope, id).into(),+ );+}++pub(in crate::context_bootstrap) fn entry<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ wrapper: v8::Local<'s, v8::Object>,+) -> Option<HistoryEntryRef> {+ let id = id(scope, wrapper, ENTRY_ID)?;+ scope+ .get_slot::<Store>()?+ .borrow()+ .entries+ .get(&id)+ .map(|(_, record)| record.clone())+}++fn wrappers<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ owner: v8::Local<'s, v8::Object>,+) -> v8::Local<'s, v8::Map> {+ if let Some(map) = get_private_value(scope, owner, ENTRY_WRAPPERS)+ .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())+ {+ return map;+ }+ let map = v8::Map::new(scope);+ set_private_value(scope, owner, ENTRY_WRAPPERS, map.into());+ map+}++pub(in crate::context_bootstrap) fn cache_entry<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ owner: v8::Local<'s, v8::Object>,+ wrapper: v8::Local<'s, v8::Object>,+) {+ let Some(entry) = entry(scope, wrapper) else {+ return;+ };+ let id = entry.borrow().id.clone();+ let Some(key) = v8_string(scope, &id) else {+ return;+ };+ let _ = wrappers(scope, owner).set(scope, key.into(), wrapper.into());+}++pub(in crate::context_bootstrap) fn entry_wrapper<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ owner: v8::Local<'s, v8::Object>,+ entry: HistoryEntryRef,+) -> v8::Local<'s, v8::Object> {+ let id = entry.borrow().id.clone();+ let map = wrappers(scope, owner);+ if let Some(key) = v8_string(scope, &id)+ && let Some(wrapper) = map+ .get(scope, key.into())+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ {+ return wrapper;+ }+ let wrapper = super::super::navigation_entry::wrap_native_navigation_entry(scope, entry);+ super::super::navigation_activation::bind_navigation_entry_runtime_owner(scope, wrapper, owner);+ wrapper+}++pub(in crate::context_bootstrap) fn prune_entry_wrappers<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ owner: v8::Local<'s, v8::Object>,+ entries: &[HistoryEntryRef],+) {+ let live: std::collections::HashSet<String> = entries+ .iter()+ .map(|entry| entry.borrow().id.clone())+ .collect();+ let map = wrappers(scope, owner);+ let pairs = map.as_array(scope);+ for index in (0..pairs.length()).step_by(2) {+ if let Some(key) = pairs.get_index(scope, index)+ && let Some(id) = key.to_string(scope)+ && !live.contains(&id.to_rust_string_lossy(scope))+ {+ let _ = map.delete(scope, key);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use moli_history::{HistoryEntry, ScrollRestoration};+ use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};++ #[test]+ fn native_history_outlives_entry_wrappers_and_is_reclaimed_with_its_last_wrapper() {+ moli_v8_test_util::ensure_v8();+ let mut isolate = v8::Isolate::new(Default::default());+ let (keep_alive, history_weak, entry_weak) = {+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, context);+ let entry = HistoryEntry {+ url: "https://example.test/".to_owned(),+ id: "entry".to_owned(),+ key: NavigationHistoryEntryKey::allocate(),+ document: NavigationHistoryDocumentId::allocate(),+ index: 0,+ referrer_policy: None,+ history_state: None,+ navigation_state: None,+ scroll_restoration: ScrollRestoration::Auto,+ scroll_offset: None,+ }+ .into_ref();+ let history = Rc::new(RefCell::new(WindowHistory::new(vec![entry.clone()], 0)));+ let history_weak = Rc::downgrade(&history);+ let entry_weak = Rc::downgrade(&entry);+ let entry_wrapper = v8::Object::new(scope);+ bind_entry(scope, entry_wrapper, entry);+ let default_wrapper = v8::Object::new(scope);+ bind_history(scope, default_wrapper, history.clone());+ let isolated_wrapper = v8::Object::new(scope);+ bind_history(scope, isolated_wrapper, history);+ (+ v8::Global::new(scope, isolated_wrapper),+ history_weak,+ entry_weak,+ )+ };+ isolate.low_memory_notification();+ assert!(history_weak.upgrade().is_some());+ assert!(entry_weak.upgrade().is_some());+ assert!(+ isolate+ .get_slot::<Store>()+ .unwrap()+ .borrow()+ .entries+ .is_empty()+ );+ drop(keep_alive);+ isolate.low_memory_notification();+ assert!(history_weak.upgrade().is_none());+ assert!(entry_weak.upgrade().is_none());+ assert!(+ isolate+ .get_slot::<Store>()+ .unwrap()+ .borrow()+ .histories+ .is_empty()+ );+ }+}diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rsindex 11acdea62..2bd8e8a81 100644--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs@@ -1,36 +1,15 @@-//! One History implementation per Window, with realm-local public wrappers.-//!-//! The private backing object keeps V8 payloads in the GC graph. Wrappers share-//! it rather than copying entry identities, the cursor, or restoration policy.-//! Only the deserialized `history.state` cache belongs to a particular wrapper.--use super::super::navigation_window::window_history_for_holder;-use super::super::structured_clone_value;+//! Native History state with realm-local caches of deserialized JS values.++use super::super::navigation_window::runtime_window_owner;+use super::native;+use crate::structured_clone::deserialize_history_state;use crate::util::{get_private_value, private_key, set_private_value, v8_string};-use moli_webapi_declare::WebApiObject;+use moli_history::ScrollRestoration;-pub(in crate::context_bootstrap) const HISTORY_BACKING_SLOT: &str = "__moliHistoryBacking";const WINDOW_HISTORY_OWNER_SLOT: &str = "__moliWindowHistoryOwner";-const ENTRIES_SLOT: &str = "entries";-const INDEX_SLOT: &str = "index";-const STATE_SLOT: &str = "state";-const SCROLL_RESTORATION_SLOT: &str = "scrollRestoration";-const CACHED_SNAPSHOT_SLOT: &str = "__moliHistoryCachedSnapshot";+const CACHED_REVISION_SLOT: &str = "__moliHistoryCachedRevision";const CACHED_STATE_SLOT: &str = "__moliHistoryCachedState";-#[derive(WebApiObject)]-#[webapi(plain)]-struct HistoryBackingDeclaration<'scope> {- #[webapi(slot = ENTRIES_SLOT)]- entries: v8::Local<'scope, v8::Array>,- #[webapi(slot = INDEX_SLOT)]- index: f64,- #[webapi(slot = STATE_SLOT)]- state: v8::Local<'scope, v8::Value>,- #[webapi(slot = SCROLL_RESTORATION_SLOT)]- scroll_restoration: &'static str,-}-/// Bind once during realm creation; never resolve an old wrapper to a new/// document's current Window by looking up its frame at call time.pub(crate) fn bind_isolated_window_history_owner<'s>(@@ -57,63 +36,97 @@ pub(in crate::context_bootstrap) fn window_has_shared_history<'s>(!history_window_owner(scope, window).strict_equals(window.into())}-pub(in crate::context_bootstrap) fn shared_history_backing<'s>(+pub(in crate::context_bootstrap) fn history_entries<'s>(scope: &mut v8::PinScope<'s, '_>,- window: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Object>> {- if !window_has_shared_history(scope, window) {- return None;+ history: v8::Local<'s, v8::Object>,+) -> Option<v8::Local<'s, v8::Array>> {+ let record = native::history(scope, history)?;+ let entries = record.borrow().entries().to_vec();+ let owner = runtime_window_owner(scope, history);+ // This array is a binding projection. The native vector is authoritative.+ let array = v8::Array::new(scope, entries.len() as i32);+ for (index, entry) in entries.into_iter().enumerate() {+ let wrapper = native::entry_wrapper(scope, owner, entry);+ let _ = array.set_index(scope, index as u32, wrapper.into());}- let owner = history_window_owner(scope, window);- let history = window_history_for_holder(scope, owner)?;- backing(scope, history)-}--pub(in crate::context_bootstrap) fn new_history_backing<'s>(- scope: &mut v8::PinScope<'s, '_>,- entries: v8::Local<'s, v8::Array>,- index: u32,-) -> v8::Local<'s, v8::Object> {- HistoryBackingDeclaration::new(entries, index as f64, v8::null(scope).into(), "auto")- .bind(scope)- .expect("History backing declaration should bind")+ Some(array)}-fn backing<'s>(+pub(in crate::context_bootstrap) fn set_history_entries<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Object>> {- get_private_value(scope, history, HISTORY_BACKING_SLOT)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ entries: v8::Local<'s, v8::Array>,+) {+ let Some(record) = native::history(scope, history) else {+ return;+ };+ let owner = runtime_window_owner(scope, history);+ let mut native_entries = Vec::with_capacity(entries.length() as usize);+ for index in 0..entries.length() {+ let Some(wrapper) = entries+ .get_index(scope, index)+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ else {+ return;+ };+ let Some(entry) = native::entry(scope, wrapper) else {+ return;+ };+ super::super::navigation_activation::bind_navigation_entry_runtime_owner(+ scope, wrapper, owner,+ );+ native_entries.push(entry);+ }+ native::prune_entry_wrappers(scope, owner, &native_entries);+ record.borrow_mut().restore_entries(native_entries);}-pub(in crate::context_bootstrap) fn history_entries<'s>(+pub(in crate::context_bootstrap) fn push_history_entry<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Array>> {- let backing = backing(scope, history)?;- get_private_value(scope, backing, ENTRIES_SLOT)- .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())+ wrapper: v8::Local<'s, v8::Object>,+) -> Vec<v8::Local<'s, v8::Object>> {+ let Some(record) = native::history(scope, history) else {+ return Vec::new();+ };+ let Some(entry) = native::entry(scope, wrapper) else {+ return Vec::new();+ };+ let owner = runtime_window_owner(scope, history);+ super::super::navigation_activation::bind_navigation_entry_runtime_owner(scope, wrapper, owner);+ let removed = record.borrow_mut().push(entry);+ let removed = removed+ .into_iter()+ .map(|entry| native::entry_wrapper(scope, owner, entry))+ .collect();+ let retained = record.borrow().entries().to_vec();+ native::prune_entry_wrappers(scope, owner, &retained);+ removed}-pub(in crate::context_bootstrap) fn set_history_entries<'s>(+pub(in crate::context_bootstrap) fn replace_history_entry<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,- entries: v8::Local<'s, v8::Array>,+ wrapper: v8::Local<'s, v8::Object>,) {- if let Some(backing) = backing(scope, history) {- set_private_value(scope, backing, ENTRIES_SLOT, entries.into());- }+ let Some(record) = native::history(scope, history) else {+ return;+ };+ let Some(entry) = native::entry(scope, wrapper) else {+ return;+ };+ let owner = runtime_window_owner(scope, history);+ super::super::navigation_activation::bind_navigation_entry_runtime_owner(scope, wrapper, owner);+ record.borrow_mut().replace(entry);+ let retained = record.borrow().entries().to_vec();+ native::prune_entry_wrappers(scope, owner, &retained);}pub(in crate::context_bootstrap) fn history_index<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,) -> u32 {- backing(scope, history)- .and_then(|backing| get_private_value(scope, backing, INDEX_SLOT))- .and_then(|value| value.uint32_value(scope))- .unwrap_or(0)+ native::history(scope, history).map_or(0, |record| record.borrow().current_index())}pub(in crate::context_bootstrap) fn set_history_index<'s>(@@ -121,13 +134,8 @@ pub(in crate::context_bootstrap) fn set_history_index<'s>(history: v8::Local<'s, v8::Object>,index: u32,) {- if let Some(backing) = backing(scope, history) {- set_private_value(- scope,- backing,- INDEX_SLOT,- v8::Integer::new_from_unsigned(scope, index).into(),- );+ if let Some(record) = native::history(scope, history) {+ record.borrow_mut().set_current_index(index);}}@@ -135,8 +143,9 @@ pub(in crate::context_bootstrap) fn history_scroll_restoration_value<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Value>> {- let backing = backing(scope, history)?;- get_private_value(scope, backing, SCROLL_RESTORATION_SLOT)+ let record = native::history(scope, history)?;+ let value = record.borrow().scroll_restoration().as_str();+ v8_string(scope, value).map(Into::into)}pub(in crate::context_bootstrap) fn set_history_scroll_restoration<'s>(@@ -144,10 +153,11 @@ pub(in crate::context_bootstrap) fn set_history_scroll_restoration<'s>(history: v8::Local<'s, v8::Object>,value: &str,) {- if let Some(backing) = backing(scope, history)- && let Some(value) = v8_string(scope, value)- {- set_private_value(scope, backing, SCROLL_RESTORATION_SLOT, value.into());+ if let Some(record) = native::history(scope, history) {+ record.borrow_mut().set_scroll_restoration(match value {+ "manual" => ScrollRestoration::Manual,+ _ => ScrollRestoration::Auto,+ });}}@@ -155,18 +165,19 @@ pub(in crate::context_bootstrap) fn history_state_value<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,) -> v8::Local<'s, v8::Value> {- let snapshot = backing(scope, history)- .and_then(|backing| {- let key = private_key(scope, STATE_SLOT)?;- backing.get_private(scope, key)- })- .unwrap_or_else(|| v8::null(scope).into());- if !snapshot.is_object() {- return snapshot;- }- if get_private_value(scope, history, CACHED_SNAPSHOT_SLOT)- .is_some_and(|cached| cached.same_value(snapshot))- && let Some(value) = get_private_value(scope, history, CACHED_STATE_SLOT)+ let Some(record) = native::history(scope, history) else {+ return v8::null(scope).into();+ };+ let (revision, snapshot) = {+ let record = record.borrow();+ (record.revision(), record.state())+ };+ let cached_revision = get_private_value(scope, history, CACHED_REVISION_SLOT)+ .and_then(|value| v8::Local::<v8::BigInt>::try_from(value).ok())+ .map(|value| value.u64_value().0);+ if cached_revision == Some(revision)+ && let Some(key) = private_key(scope, CACHED_STATE_SLOT)+ && let Some(value) = history.get_private(scope, key){return value;}@@ -174,26 +185,42 @@ pub(in crate::context_bootstrap) fn history_state_value<'s>(return v8::null(scope).into();};let scope = &mut v8::ContextScope::new(scope, context);- let value = structured_clone_value(scope, snapshot).unwrap_or_else(|| v8::null(scope).into());- set_private_value(scope, history, CACHED_SNAPSHOT_SLOT, snapshot);- set_private_value(scope, history, CACHED_STATE_SLOT, value);+ let value = snapshot+ .as_ref()+ .and_then(|state| deserialize_history_state(scope, state))+ .unwrap_or_else(|| v8::null(scope).into());+ cache_history_state(scope, history, revision, value);value}-pub(in crate::context_bootstrap) fn set_history_state<'s>(+fn cache_history_state<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+ revision: u64,+ value: v8::Local<'s, v8::Value>,+) {+ set_private_value(+ scope,+ history,+ CACHED_REVISION_SLOT,+ v8::BigInt::new_from_u64(scope, revision).into(),+ );+ set_private_value(scope, history, CACHED_STATE_SLOT, value);+}++/// Cache an already deserialized value after a native history transition.+/// The entry's serialized state stays authoritative and is never rewritten+/// from a mutable JS cache during traversal.+pub(in crate::context_bootstrap) fn cache_current_history_state<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,state: v8::Local<'s, v8::Value>,) {- let Some(backing) = backing(scope, history) else {+ let Some(record) = native::history(scope, history) else {return;};- // The cache can be mutated by script (and is also popstate.state). Keep a- // separate snapshot so another realm never deserializes those mutations.- let snapshot = structured_clone_value(scope, state).unwrap_or_else(|| v8::null(scope).into());- set_private_value(scope, backing, STATE_SLOT, snapshot);+ let revision = record.borrow().revision();if history.get_creation_context(scope) == Some(scope.get_current_context()) {- set_private_value(scope, history, CACHED_SNAPSHOT_SLOT, snapshot);- set_private_value(scope, history, CACHED_STATE_SLOT, state);+ cache_history_state(scope, history, revision, state);}}diff --git a/moli-renderer-v8/src/context_bootstrap/location_history_storage.rs b/moli-renderer-v8/src/context_bootstrap/location_history_storage.rsindex 23a734495..22aa13647 100644--- a/moli-renderer-v8/src/context_bootstrap/location_history_storage.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_history_storage.rs@@ -1,6 +1,3 @@-pub(super) const HISTORY_ENTRY_STATE_SNAPSHOT_SLOT: &str = "__lmHistoryEntryStateSnapshot";-pub(super) const NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT: &str = "__lmNavigationEntryStateSnapshot";-pub(super) const NAVIGATION_ENTRY_DOCUMENT_ID_SLOT: &str = "__lmNavigationEntryDocumentId";pub(super) const NAVIGATION_ENTRY_EVENT_LISTENERS_SLOT: &str = "__lmNavigationEntryEventListeners";pub(super) const NAVIGATION_EVENT_LISTENERS_SLOT: &str = "__lmNavigationEventListeners";pub(super) const NAVIGATION_CURRENT_ENTRY_SLOT: &str = "__lmNavigationCurrentEntry";diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rsindex 1b2b94a19..808e11ed4 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs@@ -147,6 +147,7 @@ pub(super) fn navigation_entry_object_from_snapshot<'s>(&snapshot.key,);set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());+ super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);bind_navigation_entry_runtime_owner(scope, entry, owner);entry}@@ -168,6 +169,7 @@ pub(super) fn bind_navigation_entry_runtime_owner<'s>(owner: v8::Local<'s, v8::Object>,) {set_runtime_window_owner(scope, entry, owner);+ super::history_runtime::native::cache_entry(scope, owner, entry);}pub(super) fn create_navigation_activation_object<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rsindex bec1fa2fa..ca934c736 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs@@ -1913,7 +1913,7 @@ pub(in crate::context_bootstrap) fn navigation_update_current_entry_callback<'s>);return;}- let Some(cloned_state) = structured_clone_value(scope, requested_state) else {+ let Some(cloned_state) = structured_clone_value_for_storage(scope, requested_state) else {return;};set_navigation_entry_state(scope, current_entry, cloned_state);diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rsindex cb1ebaffb..842051de3 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs@@ -1,11 +1,10 @@+use super::history_runtime::native;pub(super) use super::history_runtime::state::{- history_entries, history_index, history_scroll_restoration_value, history_state_value,- set_history_entries, set_history_index, set_history_scroll_restoration, set_history_state,+ cache_current_history_state, history_entries, history_index, history_scroll_restoration_value,+ history_state_value, set_history_entries, set_history_index, set_history_scroll_restoration,};use super::location_history_storage::{- HISTORY_ENTRY_STATE_SNAPSHOT_SLOT, NAVIGATION_CURRENT_ENTRY_SLOT,- NAVIGATION_ENTRY_DOCUMENT_ID_SLOT, NAVIGATION_ENTRY_EVENT_LISTENERS_SLOT,- NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT,+ NAVIGATION_CURRENT_ENTRY_SLOT, NAVIGATION_ENTRY_EVENT_LISTENERS_SLOT,};use super::location_runtime::urls_refer_to_same_document;use super::navigation_activation::set_navigation_current_entry;@@ -16,62 +15,31 @@ use super::navigation_window::{window_location_for_holder, window_navigation_for_holder,};use super::*;-use crate::util::{get_private_value, set_private_value};+use crate::util::get_private_value;use crate::web_api_interfaces;+use moli_history::{HistoryEntry, HistoryEntryRef, ScrollRestoration};use moli_page_types::NavigationHistoryEntryId;+use moli_session_history::NavigationHistoryDocumentId;use moli_session_history::NavigationHistoryEntryKey;use moli_webapi_declare::WebApiObject;-const NAVIGATION_ENTRY_INITIAL_INDEX_SLOT: &str = "__lmNavigationEntryInitialIndex";-const NAVIGATION_ENTRY_URL_SLOT: &str = "__lmNavigationEntryUrl";-const NAVIGATION_ENTRY_REFERRER_POLICY_SLOT: &str = "__lmNavigationEntryReferrerPolicy";-const NAVIGATION_ENTRY_ID_SLOT: &str = "__lmNavigationEntryId";-const NAVIGATION_ENTRY_KEY_SLOT: &str = "__lmNavigationEntryKey";-const NAVIGATION_ENTRY_SCROLL_X_SLOT: &str = "__lmNavigationEntryScrollX";-const NAVIGATION_ENTRY_SCROLL_Y_SLOT: &str = "__lmNavigationEntryScrollY";+#[derive(Clone, Copy)]+enum EntryStringField {+ Document,+ Url,+ ReferrerPolicy,+ Id,+ Key,+}#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::NavigationHistoryEntry,own_to_string_tag = "NavigationHistoryEntry",readonly_to_string_tag,- enumerable,- scope_lifetime = 'scope+ enumerable)]-struct NavigationHistoryEntryObjectDeclaration<'scope, 'value> {- #[webapi(slot = NAVIGATION_ENTRY_URL_SLOT)]- stored_url: &'value str,-- #[webapi(slot = NAVIGATION_ENTRY_REFERRER_POLICY_SLOT)]- stored_referrer_policy: Option<&'value str>,-- #[webapi(slot = HISTORY_ENTRY_STATE_SNAPSHOT_SLOT)]- history_snapshot: v8::Local<'scope, v8::Value>,-- #[webapi(slot = NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT)]- navigation_snapshot: v8::Local<'scope, v8::Value>,-- #[webapi(slot = "state")]- exposed_state: v8::Local<'scope, v8::Value>,-- #[webapi(slot = NAVIGATION_ENTRY_INITIAL_INDEX_SLOT)]- initial_index: f64,-- #[webapi(slot = NAVIGATION_ENTRY_SCROLL_X_SLOT, init = "undefined")]- scroll_x: (),-- #[webapi(slot = NAVIGATION_ENTRY_SCROLL_Y_SLOT, init = "undefined")]- scroll_y: (),-- #[webapi(slot = NAVIGATION_ENTRY_ID_SLOT)]- public_id: &'value str,-- #[webapi(slot = NAVIGATION_ENTRY_KEY_SLOT)]- public_key: &'value str,-- #[webapi(slot = NAVIGATION_ENTRY_DOCUMENT_ID_SLOT)]- document_id: &'value str,-+struct NavigationHistoryEntryObjectDeclaration {#[webapi(accessor_property, getter = navigation_entry_url_getter)]url: (),@@ -97,24 +65,13 @@ struct NavigationHistoryEntryObjectDeclaration<'scope, 'value> {fn finite_window_number_slot<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,- slot: &'static str,+ slot: &str,) -> Option<f64> {get_private_value(scope, object, slot).and_then(|value| value.number_value(scope)).filter(|value| value.is_finite())}-fn finite_navigation_entry_number_slot<'s>(- scope: &mut v8::PinScope<'s, '_>,- entry: v8::Local<'s, v8::Object>,- slot: &'static str,-) -> Option<f64> {- navigation_entry_slot_value(scope, entry, slot)- .filter(|value| !value.is_undefined())- .and_then(|value| value.number_value(scope))- .filter(|value| value.is_finite())-}-pub(super) fn sync_navigation_current_entry_from_history_entry<'s>(scope: &mut v8::PinScope<'s, '_>,owner: v8::Local<'s, v8::Object>,@@ -135,8 +92,9 @@ pub(super) fn save_current_navigation_entry_scroll_position<'s>(};let scroll_x = finite_window_number_slot(scope, owner, WINDOW_SCROLL_X_SLOT).unwrap_or(0.0);let scroll_y = finite_window_number_slot(scope, owner, WINDOW_SCROLL_Y_SLOT).unwrap_or(0.0);- set_navigation_entry_number_slot(scope, entry, NAVIGATION_ENTRY_SCROLL_X_SLOT, scroll_x);- set_navigation_entry_number_slot(scope, entry, NAVIGATION_ENTRY_SCROLL_Y_SLOT, scroll_y);+ if let Some(entry) = native::entry(scope, entry) {+ entry.borrow_mut().scroll_offset = Some((scroll_x, scroll_y));+ }}pub(super) fn restore_current_navigation_entry_scroll_position<'s>(@@ -146,13 +104,8 @@ pub(super) fn restore_current_navigation_entry_scroll_position<'s>(let Some(entry) = navigation_current_entry(scope, owner) else {return false;};- let Some(scroll_x) =- finite_navigation_entry_number_slot(scope, entry, NAVIGATION_ENTRY_SCROLL_X_SLOT)- else {- return false;- };- let Some(scroll_y) =- finite_navigation_entry_number_slot(scope, entry, NAVIGATION_ENTRY_SCROLL_Y_SLOT)+ let Some((scroll_x, scroll_y)) =+ native::entry(scope, entry).and_then(|entry| entry.borrow().scroll_offset)else {return false;};@@ -177,24 +130,35 @@ pub(super) fn create_navigation_entry<'s>(super::navigation_serialize::parse_history_entry_state(scope, history_state_json);let navigation_snapshot =super::navigation_serialize::parse_navigation_entry_state(scope, navigation_state_json);- let exposed_state = structured_clone_value(scope, navigation_snapshot)- .or(Some(navigation_snapshot))- .unwrap_or_else(|| v8::undefined(scope).into());let public_id = navigation_entry_public_token(id);let public_key = navigation_entry_public_token(key);- let entry = NavigationHistoryEntryObjectDeclaration::new(- url,- referrer_policy,- history_snapshot,- navigation_snapshot,- exposed_state,- index as f64,- &public_id,- &public_key,- &public_id,- )- .bind(scope)- .expect("NavigationHistoryEntry declaration should bind");+ let entry = HistoryEntry {+ url: url.to_owned(),+ referrer_policy: referrer_policy.map(str::to_owned),+ history_state: crate::structured_clone::serialize_history_state(scope, history_snapshot),+ navigation_state: crate::structured_clone::serialize_history_state(+ scope,+ navigation_snapshot,+ ),+ id: public_id.clone(),+ key: NavigationHistoryEntryKey::from_serialized(public_key),+ document: NavigationHistoryDocumentId::from_serialized(public_id),+ index,+ scroll_restoration: ScrollRestoration::Auto,+ scroll_offset: None,+ }+ .into_ref();+ wrap_native_navigation_entry(scope, entry)+}++pub(in crate::context_bootstrap) fn wrap_native_navigation_entry<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ record: HistoryEntryRef,+) -> v8::Local<'s, v8::Object> {+ let entry = NavigationHistoryEntryObjectDeclaration::new()+ .bind(scope)+ .expect("NavigationHistoryEntry declaration should bind");+ native::bind_entry(scope, entry, record);super::media_queries::install_simple_event_target_methods(scope,entry,@@ -216,31 +180,28 @@ pub(super) fn navigation_entry_key_value<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<String> {- navigation_entry_stored_string(scope, entry, NAVIGATION_ENTRY_KEY_SLOT)+ navigation_entry_stored_string(scope, entry, EntryStringField::Key)}pub(super) fn navigation_entry_id_value<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<String> {- navigation_entry_stored_string(scope, entry, NAVIGATION_ENTRY_ID_SLOT)+ navigation_entry_stored_string(scope, entry, EntryStringField::Id)}pub(super) fn navigation_entry_url_value<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<String> {- navigation_entry_stored_string(scope, entry, NAVIGATION_ENTRY_URL_SLOT)+ navigation_entry_stored_string(scope, entry, EntryStringField::Url)}pub(super) fn navigation_entry_initial_index<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<u32> {- navigation_entry_slot_value(scope, entry, NAVIGATION_ENTRY_INITIAL_INDEX_SLOT)- .and_then(|value| value.integer_value(scope))- .filter(|value| *value >= 0)- .map(|value| value as u32)+ native::entry(scope, entry).map(|entry| entry.borrow().index)}pub(super) fn set_navigation_entry_initial_index<'s>(@@ -248,19 +209,16 @@ pub(super) fn set_navigation_entry_initial_index<'s>(entry: v8::Local<'s, v8::Object>,index: u32,) {- set_navigation_entry_number_slot(- scope,- entry,- NAVIGATION_ENTRY_INITIAL_INDEX_SLOT,- index as f64,- );+ if let Some(entry) = native::entry(scope, entry) {+ entry.borrow_mut().index = index;+ }}pub(super) fn navigation_entry_referrer_policy_value<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<String> {- navigation_entry_stored_string(scope, entry, NAVIGATION_ENTRY_REFERRER_POLICY_SLOT)+ navigation_entry_stored_string(scope, entry, EntryStringField::ReferrerPolicy)}pub(super) fn navigation_entry_public_token(token: &str) -> String {@@ -305,7 +263,7 @@ pub(super) fn navigation_entry_document_id<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<String> {- navigation_entry_stored_string(scope, entry, NAVIGATION_ENTRY_DOCUMENT_ID_SLOT)+ navigation_entry_stored_string(scope, entry, EntryStringField::Document)}pub(super) fn set_navigation_entry_document_id<'s>(@@ -313,7 +271,10 @@ pub(super) fn set_navigation_entry_document_id<'s>(entry: v8::Local<'s, v8::Object>,document_id: &str,) {- set_navigation_entry_string_slot(scope, entry, NAVIGATION_ENTRY_DOCUMENT_ID_SLOT, document_id);+ if let Some(entry) = native::entry(scope, entry) {+ entry.borrow_mut().document =+ NavigationHistoryDocumentId::from_serialized(document_id.to_owned());+ }}pub(super) fn copy_navigation_entry_document_id<'s>(@@ -342,9 +303,8 @@ fn navigation_entry_get_state_callback<'s>(mut rv: v8::ReturnValue<'_, v8::Value>,) {let this = args.this();- let state = navigation_entry_state_snapshot(scope, this)- .and_then(|snapshot| structured_clone_value(scope, snapshot).or(Some(snapshot)))- .unwrap_or_else(|| v8::undefined(scope).into());+ let state =+ navigation_entry_state_snapshot(scope, this).unwrap_or_else(|| v8::undefined(scope).into());rv.set(state);}@@ -359,12 +319,18 @@ fn navigation_entry_is_active<'s>(fn navigation_entry_stored_string<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,- slot: &'static str,+ field: EntryStringField,) -> Option<String> {- navigation_entry_slot_value(scope, entry, slot)- .and_then(|value| value.to_string(scope))- .map(|value| value.to_rust_string_lossy(scope))- .filter(|value| !value.is_empty())+ let record = native::entry(scope, entry)?;+ let record = record.borrow();+ match field {+ EntryStringField::Url => Some(record.url.clone()),+ EntryStringField::Id => Some(record.id.clone()),+ EntryStringField::Key => Some(record.key.as_str().to_owned()),+ EntryStringField::Document => Some(record.document.as_str().to_owned()),+ EntryStringField::ReferrerPolicy => record.referrer_policy.clone(),+ }+ .filter(|value| !value.is_empty())}fn navigation_entry_url_getter<'s>(@@ -388,7 +354,7 @@ fn navigation_entry_url_getter<'s>(rv.set(v8::null(scope).into());return;}- let value = navigation_entry_stored_string(scope, args.this(), NAVIGATION_ENTRY_URL_SLOT)+ let value = navigation_entry_stored_string(scope, args.this(), EntryStringField::Url).and_then(|value| v8_string(scope, &value)).map(v8::Local::<v8::Value>::from).unwrap_or_else(|| v8::null(scope).into());@@ -400,7 +366,7 @@ fn navigation_entry_id_getter<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,) {- let value = navigation_entry_active_token(scope, args.this(), NAVIGATION_ENTRY_ID_SLOT);+ let value = navigation_entry_active_token(scope, args.this(), EntryStringField::Id);rv.set(value);}@@ -409,19 +375,19 @@ fn navigation_entry_key_getter<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,) {- let value = navigation_entry_active_token(scope, args.this(), NAVIGATION_ENTRY_KEY_SLOT);+ let value = navigation_entry_active_token(scope, args.this(), EntryStringField::Key);rv.set(value);}fn navigation_entry_active_token<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,- slot: &'static str,+ field: EntryStringField,) -> v8::Local<'s, v8::Value> {if !navigation_entry_is_active(scope, entry) {return v8str(scope, "").into();}- navigation_entry_stored_string(scope, entry, slot)+ navigation_entry_stored_string(scope, entry, field).and_then(|value| v8_string(scope, &value)).map(v8::Local::<v8::Value>::from).unwrap_or_else(|| v8str(scope, "").into())@@ -453,7 +419,7 @@ fn navigation_entry_same_document_getter<'s>(return;};let Some(entry_href) =- navigation_entry_stored_string(scope, args.this(), NAVIGATION_ENTRY_URL_SLOT)+ navigation_entry_stored_string(scope, args.this(), EntryStringField::Url)else {rv.set_bool(false);return;@@ -484,63 +450,10 @@ fn navigation_entry_index_getter<'s>(rv.set(v8::Number::new(scope, -1.0).into());return;}- let fallback =- navigation_entry_slot_value(scope, args.this(), NAVIGATION_ENTRY_INITIAL_INDEX_SLOT)- .and_then(|value| value.integer_value(scope))- .unwrap_or(-1);+ let fallback = navigation_entry_initial_index(scope, args.this()).map_or(-1, i64::from);rv.set(v8::Number::new(scope, fallback as f64).into());}-fn navigation_entry_slot_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- entry: v8::Local<'s, v8::Object>,- slot: &str,-) -> Option<v8::Local<'s, v8::Value>> {- get_private_value(scope, entry, slot)-}--pub(super) fn navigation_entry_private_slot_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- entry: v8::Local<'s, v8::Object>,- slot: &str,-) -> Option<v8::Local<'s, v8::Value>> {- navigation_entry_slot_value(scope, entry, slot)-}--pub(super) fn set_navigation_entry_private_slot_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- entry: v8::Local<'s, v8::Object>,- slot: &str,- value: v8::Local<'s, v8::Value>,-) {- set_private_value(scope, entry, slot, value);-}--fn set_navigation_entry_number_slot<'s>(- scope: &mut v8::PinScope<'s, '_>,- entry: v8::Local<'s, v8::Object>,- slot: &str,- value: f64,-) {- set_navigation_entry_private_slot_value(- scope,- entry,- slot,- v8::Number::new(scope, value).into(),- );-}--fn set_navigation_entry_string_slot<'s>(- scope: &mut v8::PinScope<'s, '_>,- entry: v8::Local<'s, v8::Object>,- slot: &str,- value: &str,-) {- if let Some(value) = v8_string(scope, value) {- set_navigation_entry_private_slot_value(scope, entry, slot, value.into());- }-}-pub(super) fn navigation_current_entry_index<'s>(scope: &mut v8::PinScope<'s, '_>,owner: v8::Local<'s, v8::Object>,@@ -558,16 +471,3 @@ pub(super) fn navigation_current_entry<'s>(get_private_value(scope, navigation, NAVIGATION_CURRENT_ENTRY_SLOT).and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())}--pub(super) fn stringify_history_state<'s>(- scope: &mut v8::PinScope<'s, '_>,- state: v8::Local<'s, v8::Value>,-) -> Option<String> {- let try_catch = std::pin::pin!(v8::TryCatch::new(scope));- let mut scope = try_catch.init();- let serialized = v8::json::stringify(&scope, state)- .map(|value| value.to_rust_string_lossy(&scope))- .filter(|value| value != "null");- scope.reset();- serialized-}diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rsindex 1508403c4..d8f7247b4 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs@@ -1,42 +1,41 @@-use super::location_history_storage::{- HISTORY_ENTRY_STATE_SNAPSHOT_SLOT, NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT,-};-use super::navigation_entry::{- navigation_entry_private_slot_value, set_navigation_entry_private_slot_value,-};+use super::history_runtime::native;use super::*;+use crate::structured_clone::{deserialize_history_state, serialize_history_state};pub(super) fn navigation_entry_state_snapshot<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Value>> {- navigation_entry_private_slot_value(scope, entry, NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT)- .filter(|value| !value.is_undefined())+ let state = native::entry(scope, entry)?+ .borrow()+ .navigation_state+ .clone()?;+ deserialize_history_state(scope, &state)}pub(super) fn history_entry_state_snapshot<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Value>> {- // Unlike an absent optional slot, undefined is a valid History state.- let key = crate::util::private_key(scope, HISTORY_ENTRY_STATE_SNAPSHOT_SLOT)?;- entry.get_private(scope, key)+ let state = native::entry(scope, entry)?+ .borrow()+ .history_state+ .clone()?;+ deserialize_history_state(scope, &state)}pub(super) fn clone_navigation_entry_state<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Value>> {- let snapshot = navigation_entry_state_snapshot(scope, entry)?;- structured_clone_value(scope, snapshot).or(Some(snapshot))+ navigation_entry_state_snapshot(scope, entry)}pub(super) fn clone_history_entry_state<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Value>> {- let snapshot = history_entry_state_snapshot(scope, entry)?;- structured_clone_value(scope, snapshot).or(Some(snapshot))+ history_entry_state_snapshot(scope, entry)}pub(super) fn set_history_entry_state<'s>(@@ -44,7 +43,32 @@ pub(super) fn set_history_entry_state<'s>(entry: v8::Local<'s, v8::Object>,state: v8::Local<'s, v8::Value>,) {- set_navigation_entry_private_slot_value(scope, entry, HISTORY_ENTRY_STATE_SNAPSHOT_SLOT, state);+ let Some(record) = native::entry(scope, entry) else {+ return;+ };+ if let Some(state) = serialize_history_state(scope, state) {+ record.borrow_mut().history_state = Some(state);+ }+}++pub(super) fn copy_entry_serialized_states<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ from: v8::Local<'s, v8::Object>,+ to: v8::Local<'s, v8::Object>,+) {+ let Some(from) = native::entry(scope, from) else {+ return;+ };+ let Some(to) = native::entry(scope, to) else {+ return;+ };+ let (history_state, navigation_state) = {+ let from = from.borrow();+ (from.history_state.clone(), from.navigation_state.clone())+ };+ let mut to = to.borrow_mut();+ to.history_state = history_state;+ to.navigation_state = navigation_state;}pub(super) fn set_navigation_entry_state<'s>(@@ -52,14 +76,30 @@ pub(super) fn set_navigation_entry_state<'s>(entry: v8::Local<'s, v8::Object>,state: v8::Local<'s, v8::Value>,) {- let exposed_state = structured_clone_value(scope, state).unwrap_or(state);- set_navigation_entry_private_slot_value(- scope,- entry,- NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT,- state,- );- set_navigation_entry_private_slot_value(scope, entry, "state", exposed_state);+ let Some(record) = native::entry(scope, entry) else {+ return;+ };+ if let Some(state) = serialize_history_state(scope, state) {+ record.borrow_mut().navigation_state = Some(state);+ }+}++pub(super) fn restore_serialized_entry_state<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ entry: v8::Local<'s, v8::Object>,+ snapshot: &moli_page_types::NavigationHistorySerializedEntry,+) {+ let Some(record) = native::entry(scope, entry) else {+ return;+ };+ let mut record = record.borrow_mut();+ if snapshot.history_state.is_some() {+ record.history_state = snapshot.history_state.clone();+ }+ if snapshot.navigation_state.is_some() {+ record.navigation_state = snapshot.navigation_state.clone();+ }+ record.scroll_restoration = snapshot.scroll_restoration;}pub(super) fn clone_navigation_state_arg_for_result<'s>(@@ -77,7 +117,7 @@ pub(super) fn clone_navigation_state_arg_for_result<'s>(let try_catch = std::pin::pin!(v8::TryCatch::new(scope));let mut scope = try_catch.init();- let cloned_state = structured_clone_value(&mut scope, raw_state);+ let cloned_state = structured_clone_value_for_storage(&mut scope, raw_state);if let Some(error) = scope.exception() {scope.reset();return Err(error);diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_mutation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_mutation.rsindex fbbd47d7c..01102941a 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_mutation.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_mutation.rs@@ -5,15 +5,13 @@ use super::navigation_activation::{set_navigation_current_entry,};use super::navigation_entry::{- copy_navigation_entry_document_id, create_navigation_entry, history_entries, history_index,- navigation_current_entry, navigation_current_entry_index, navigation_entry_key_value,- navigation_entry_url_value, new_navigation_entry_id, new_navigation_entry_key,- set_history_entries, set_history_index, set_history_state, set_navigation_entry_document_id,- stringify_history_state, sync_navigation_current_entry_from_history_entry,-};-use super::navigation_entry_state::{- clone_history_entry_state, clone_navigation_entry_state, set_navigation_entry_state,+ cache_current_history_state, copy_navigation_entry_document_id, create_navigation_entry,+ history_entries, history_index, navigation_current_entry, navigation_current_entry_index,+ navigation_entry_key_value, navigation_entry_url_value, new_navigation_entry_id,+ new_navigation_entry_key, set_navigation_entry_document_id,+ sync_navigation_current_entry_from_history_entry,};+use super::navigation_entry_state::{copy_entry_serialized_states, set_navigation_entry_state};use super::navigation_events::{dispatch_navigation_currententrychange, dispatch_navigation_entry_dispose,refresh_navigation_destination_indexes,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rsindex 7037586ee..ad18a7504 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs@@ -1,3 +1,4 @@+use super::super::history_runtime::state::{push_history_entry, replace_history_entry};use super::*;pub(crate) fn apply_local_window_location_navigation<'s>(@@ -19,14 +20,7 @@ pub(crate) fn apply_local_window_location_navigation<'s>(match kind {LocationNavigationKind::Assign => {- let next_index = current_index + 1;let next_navigation_index = current_navigation_index + 1;- let next_entries = v8::Array::new(scope, (current_index + 2) as i32);- for index in 0..=current_index {- if let Some(entry) = entries.get_index(scope, index) {- let _ = next_entries.set_index(scope, index, entry);- }- }let state = v8::null(scope).into();let next_entry = create_navigation_entry(scope,@@ -41,9 +35,7 @@ pub(crate) fn apply_local_window_location_navigation<'s>(let document_id = moli_session_history::NavigationHistoryDocumentId::allocate();set_navigation_entry_document_id(scope, next_entry, document_id.as_str());bind_navigation_entry_runtime_owner(scope, next_entry, owner);- let _ = next_entries.set_index(scope, next_index, next_entry.into());- set_history_entries(scope, history, next_entries);- set_history_index(scope, history, next_index);+ let _ = push_history_entry(scope, history, next_entry);if super::super::navigation_window::child_browsing_context_handle_for_runtime_owner(scope, owner,)@@ -56,7 +48,7 @@ pub(crate) fn apply_local_window_location_navigation<'s>(moli_page_types::SessionHistoryCommit::Push,);}- set_history_state(scope, history, state);+ cache_current_history_state(scope, history, state);set_navigation_current_entry(scope, navigation, next_entry);dispatch_navigation_currententrychange(scope, navigation, previous_entry, Some("push"));}@@ -79,9 +71,8 @@ pub(crate) fn apply_local_window_location_navigation<'s>(let document_id = moli_session_history::NavigationHistoryDocumentId::allocate();set_navigation_entry_document_id(scope, entry, document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);- let _ = entries.set_index(scope, current_index, entry.into());- set_history_entries(scope, history, entries);- set_history_state(scope, history, state);+ replace_history_entry(scope, history, entry);+ cache_current_history_state(scope, history, state);set_navigation_current_entry(scope, navigation, entry);if super::super::navigation_window::child_browsing_context_handle_for_runtime_owner(scope, owner,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rs b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rsindex 52924b8e1..ebe7eefbf 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rs@@ -1,3 +1,4 @@+use super::super::history_runtime::state::{push_history_entry, replace_history_entry};use super::*;pub(in crate::context_bootstrap) fn update_navigation_current_entry_for_same_document<'s>(@@ -20,53 +21,29 @@ pub(in crate::context_bootstrap) fn update_navigation_current_entry_for_same_doc.and_then(|value| value.integer_value(scope)).unwrap_or(0).max(0) as u32;- let current_index = history_index(scope, history);- let history_state = history_entries(scope, history)- .and_then(|entries| {- entries- .get_index(scope, current_index)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- })- .and_then(|entry| clone_history_entry_state(scope, entry))- .unwrap_or_else(|| v8::null(scope).into());- let navigation_state = clone_navigation_entry_state(scope, current_entry);- let history_state_json = stringify_history_state(scope, history_state);- let navigation_state_json =- navigation_state.and_then(|state| stringify_history_state(scope, state));- let entries = history_entries(scope, history).unwrap_or_else(|| v8::Array::new(scope, 0));let mut pruned_entries = Vec::new();match kind {LocationNavigationKind::Assign => {- let next_index = current_index + 1;let next_navigation_index = current_navigation_index + 1;- pruned_entries = pruned_history_entries(scope, entries, next_index);let next_entry = create_navigation_entry(scope,href,- history_state_json.as_deref(),- navigation_state_json.as_deref(),+ None,+ None,None,next_navigation_index,&new_navigation_entry_id(),&new_navigation_entry_key(),);copy_navigation_entry_document_id(scope, current_entry, next_entry);- let next_entries = v8::Array::new(scope, (next_index + 1) as i32);- for index in 0..next_index {- if let Some(entry) = entries.get_index(scope, index) {- let _ = next_entries.set_index(scope, index, entry);- }- }- let _ = next_entries.set_index(scope, next_index, next_entry.into());- set_history_entries(scope, history, next_entries);- set_history_index(scope, history, next_index);+ copy_entry_serialized_states(scope, current_entry, next_entry);+ pruned_entries = push_history_entry(scope, history, next_entry);super::super::session_history::commit(scope,owner,next_entry,moli_page_types::SessionHistoryCommit::Push,);- set_history_state(scope, history, history_state);set_navigation_current_entry(scope, navigation, next_entry);}LocationNavigationKind::Replace => {@@ -75,17 +52,16 @@ pub(in crate::context_bootstrap) fn update_navigation_current_entry_for_same_doclet entry = create_navigation_entry(scope,href,- history_state_json.as_deref(),- navigation_state_json.as_deref(),+ None,+ None,None,current_navigation_index,&new_navigation_entry_id(),&key,);copy_navigation_entry_document_id(scope, current_entry, entry);- let _ = entries.set_index(scope, current_index, entry.into());- set_history_entries(scope, history, entries);- set_history_state(scope, history, history_state);+ copy_entry_serialized_states(scope, current_entry, entry);+ replace_history_entry(scope, history, entry);set_navigation_current_entry(scope, navigation, entry);super::super::session_history::commit(scope,@@ -127,22 +103,12 @@ pub(in crate::context_bootstrap) fn apply_navigation_navigate_same_document<'s>(return;};let previous_entry = navigation_current_entry(scope, owner);- let entries = history_entries(scope, history).unwrap_or_else(|| v8::Array::new(scope, 0));- let current_index = history_index(scope, history);let current_navigation_index = navigation_current_entry_index(scope, owner).unwrap_or(0);let history_state = v8::null(scope).into();match kind {LocationNavigationKind::Assign => {- let next_index = current_index + 1;let next_navigation_index = current_navigation_index + 1;- let pruned_entries = pruned_history_entries(scope, entries, next_index);- let next_entries = v8::Array::new(scope, (current_index + 2) as i32);- for index in 0..=current_index {- if let Some(entry) = entries.get_index(scope, index) {- let _ = next_entries.set_index(scope, index, entry);- }- }let next_entry = create_navigation_entry(scope,href,@@ -160,16 +126,14 @@ pub(in crate::context_bootstrap) fn apply_navigation_navigate_same_document<'s>(if let Some(state) = navigation_state {set_navigation_entry_state(scope, next_entry, state);}- let _ = next_entries.set_index(scope, next_index, next_entry.into());- set_history_entries(scope, history, next_entries);- set_history_index(scope, history, next_index);+ let pruned_entries = push_history_entry(scope, history, next_entry);super::super::session_history::commit(scope,owner,next_entry,moli_page_types::SessionHistoryCommit::Push,);- set_history_state(scope, history, history_state);+ cache_current_history_state(scope, history, history_state);set_navigation_current_entry(scope, navigation, next_entry);if let Some(location) = window_location_for_holder(scope, owner) {sync_location_object(scope, location, href);@@ -200,9 +164,8 @@ pub(in crate::context_bootstrap) fn apply_navigation_navigate_same_document<'s>(if let Some(state) = navigation_state {set_navigation_entry_state(scope, entry, state);}- let _ = entries.set_index(scope, current_index, entry.into());- set_history_entries(scope, history, entries);- set_history_state(scope, history, history_state);+ replace_history_entry(scope, history, entry);+ cache_current_history_state(scope, history, history_state);set_navigation_current_entry(scope, navigation, entry);super::super::session_history::commit(scope,@@ -229,17 +192,6 @@ pub(in crate::context_bootstrap) fn apply_navigation_navigate_same_document<'s>(sync_child_navigation_entry_seed_from_owner(scope, owner);}-fn pruned_history_entries<'s>(- scope: &mut v8::PinScope<'s, '_>,- entries: v8::Local<'s, v8::Array>,- first_pruned_index: u32,-) -> Vec<v8::Local<'s, v8::Object>> {- (first_pruned_index..entries.length())- .filter_map(|index| entries.get_index(scope, index))- .filter_map(|entry| v8::Local::<v8::Object>::try_from(entry).ok())- .collect()-}-fn dispatch_pruned_history_entry_disposes<'s>(scope: &mut v8::PinScope<'s, '_>,entries: Vec<v8::Local<'s, v8::Object>>,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rsindex be56c4104..6f91e67ea 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs@@ -3,7 +3,7 @@ use super::navigation_activation::{set_navigation_current_entry,};use super::navigation_entry::{- create_navigation_entry, set_history_entries, set_history_index, set_history_state,+ cache_current_history_state, create_navigation_entry, set_history_entries, set_history_index,set_navigation_entry_document_id,};use super::navigation_entry_state::clone_history_entry_state;@@ -77,6 +77,7 @@ pub(crate) fn install_navigation_entry_view_for_holder<'s>(&snapshot.key,);set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());+ super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);bind_navigation_entry_runtime_owner(scope, entry, owner);let _ = entries.set_index(scope, snapshot.history_index, entry.into());if snapshot.history_index == entry_seed.current_index {@@ -107,7 +108,7 @@ pub(crate) fn install_navigation_entry_view_for_holder<'s>(});set_history_entries(scope, history, entries);set_history_index(scope, history, entry_seed.current_index);- set_history_state(+ cache_current_history_state(scope,history,current_state.unwrap_or_else(|| v8::null(scope).into()),diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rsindex 2a947e206..416a99674 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs@@ -2,8 +2,8 @@ use super::location_runtime::is_same_document_fragment_navigation;use super::navigation_activation::bind_navigation_entry_runtime_owner;use super::navigation_entry::{create_navigation_entry, history_index, set_navigation_entry_document_id,- stringify_history_state,};+use super::navigation_entry_state::{set_history_entry_state, set_navigation_entry_state};use super::navigation_serialize::{apply_current_document_referrer_policy_to_entry_snapshots, serialize_history_entries,};@@ -47,6 +47,7 @@ pub(super) fn build_history_entries_array_from_seed<'s>(&snapshot.key,);set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());+ super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);bind_navigation_entry_runtime_owner(scope, entry, owner);let _ = entries.set_index(scope, snapshot.history_index, entry.into());}@@ -64,19 +65,20 @@ pub(super) fn build_current_navigation_entry_from_seed<'s>(.iter().find(|entry| entry.history_index == seed.current_index)else {- let fallback_state_json = stringify_history_state(scope, fallback_state);let entry_id = NavigationHistoryEntryId::allocate();let entry_key = NavigationHistoryEntryKey::allocate();let entry = create_navigation_entry(scope,"about:blank",- fallback_state_json.as_deref(),- fallback_state_json.as_deref(),+ None,+ None,None,0,entry_id.as_str(),entry_key.as_str(),);+ set_history_entry_state(scope, entry, fallback_state);+ set_navigation_entry_state(scope, entry, fallback_state);let document_id = NavigationHistoryDocumentId::allocate();set_navigation_entry_document_id(scope, entry, document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);@@ -93,6 +95,7 @@ pub(super) fn build_current_navigation_entry_from_seed<'s>(&snapshot.key,);set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());+ super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);bind_navigation_entry_runtime_owner(scope, entry, owner);entry}diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rsindex 2c29b8cc4..c843f1f37 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs@@ -1,11 +1,6 @@use super::navigation_activation::navigation_activation_value;use super::navigation_entry::{- history_entries, history_index, navigation_current_entry, navigation_entry_document_id,- navigation_entry_id_value, navigation_entry_key_value, navigation_entry_referrer_policy_value,- navigation_entry_url_value,-};-use super::navigation_entry_state::{- history_entry_state_snapshot, navigation_entry_state_snapshot,+ history_index, navigation_current_entry, navigation_entry_referrer_policy_value,};use super::navigation_window::{child_browsing_context_handle_for_runtime_owner, runtime_window_is_global,@@ -101,45 +96,51 @@ pub(super) fn serialize_navigation_entry_object<'s>(entry: v8::Local<'s, v8::Object>,history_entries: &[NavigationHistorySerializedEntry],) -> NavigationHistorySerializedEntry {- let id = navigation_entry_id_value(scope, entry)- .map(NavigationHistoryEntryId::from_serialized)- .unwrap_or_else(NavigationHistoryEntryId::allocate);- let key = navigation_entry_key_value(scope, entry)- .map(NavigationHistoryEntryKey::from_serialized)- .unwrap_or_else(NavigationHistoryEntryKey::allocate);+ let Some(record) = super::history_runtime::native::entry(scope, entry) else {+ return NavigationHistorySerializedEntry {+ url: "about:blank".to_owned(),+ history_state: None,+ navigation_state: None,+ history_state_json: None,+ navigation_state_json: None,+ scroll_restoration: Default::default(),+ referrer_policy: None,+ document_id: NavigationHistoryDocumentId::allocate(),+ history_index: 0,+ index: 0,+ id: NavigationHistoryEntryId::allocate(),+ key: NavigationHistoryEntryKey::allocate(),+ };+ };+ let record = record.borrow();if let Some(snapshot) = history_entries.iter()- .find(|snapshot| snapshot.id == id && snapshot.key == key)+ .find(|snapshot| snapshot.id.as_str() == record.id && snapshot.key == record.key){return snapshot.clone();}- let url = navigation_entry_url_value(scope, entry).unwrap_or_else(|| "about:blank".to_owned());- let history_state_json = history_entry_state_snapshot(scope, entry)- .and_then(|value| v8::json::stringify(scope, value))- .map(|value| value.to_rust_string_lossy(scope))- .filter(|value| value != "null");- let navigation_state_json = navigation_entry_state_snapshot(scope, entry)- .and_then(|value| v8::json::stringify(scope, value))- .map(|value| value.to_rust_string_lossy(scope))- .filter(|value| value != "null");- let entry_index = get_own_static_property(scope, entry, "index")- .and_then(|value| value.integer_value(scope))- .filter(|value| *value >= 0)- .map(|value| value as u32)- .unwrap_or(0);- let document_id = navigation_entry_document_id(scope, entry)- .map(NavigationHistoryDocumentId::from_serialized)- .unwrap_or_else(NavigationHistoryDocumentId::allocate);+ snapshot_native_entry(&record, record.index)+}++fn snapshot_native_entry(+ entry: &moli_history::HistoryEntry,+ history_index: u32,+) -> NavigationHistorySerializedEntry {NavigationHistorySerializedEntry {- url,- history_state_json,- navigation_state_json,- referrer_policy: navigation_entry_referrer_policy_value(scope, entry),- document_id,- history_index: entry_index,- index: entry_index,- id,- key,+ url: entry.url.clone(),+ history_state: entry.history_state.clone(),+ navigation_state: entry.navigation_state.clone(),+ // JSON is accepted only for legacy/bootstrap seeds. Capturing a native+ // snapshot never deserializes state or invokes script's toJSON hooks.+ history_state_json: None,+ navigation_state_json: None,+ scroll_restoration: entry.scroll_restoration,+ referrer_policy: entry.referrer_policy.clone(),+ document_id: entry.document.clone(),+ history_index,+ index: entry.index,+ id: NavigationHistoryEntryId::from_serialized(entry.id.clone()),+ key: entry.key.clone(),}}@@ -199,57 +200,16 @@ pub(super) fn serialize_history_entries<'s>(scope: &mut v8::PinScope<'s, '_>,history: v8::Local<'s, v8::Object>,) -> Vec<NavigationHistorySerializedEntry> {- let Some(entries) = history_entries(scope, history) else {+ let Some(record) = super::history_runtime::native::history(scope, history) else {return Vec::new();};- let mut snapshots = Vec::new();- for index in 0..entries.length() {- let Some(entry) = entries- .get_index(scope, index)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- else {- continue;- };- let url =- navigation_entry_url_value(scope, entry).unwrap_or_else(|| "about:blank".to_owned());- let history_state_json = history_entry_state_snapshot(scope, entry)- .and_then(|value| v8::json::stringify(scope, value))- .map(|value| value.to_rust_string_lossy(scope))- .filter(|value| value != "null");- let navigation_state_json = navigation_entry_state_snapshot(scope, entry)- .and_then(|value| v8::json::stringify(scope, value))- .map(|value| value.to_rust_string_lossy(scope))- .filter(|value| value != "null");- let entry_index = get_own_static_property(scope, entry, "index")- .and_then(|value| value.integer_value(scope))- .filter(|value| *value >= 0)- .map(|value| value as u32)- .unwrap_or(index);- // Public Navigation getters may hide entries from an inactive view.- // Persist their stored identities so restoration still matches the- // shared session history, including a popup's forward entries.- let id = navigation_entry_id_value(scope, entry)- .map(NavigationHistoryEntryId::from_serialized)- .unwrap_or_else(NavigationHistoryEntryId::allocate);- let key = navigation_entry_key_value(scope, entry)- .map(NavigationHistoryEntryKey::from_serialized)- .unwrap_or_else(NavigationHistoryEntryKey::allocate);- let document_id = navigation_entry_document_id(scope, entry)- .map(NavigationHistoryDocumentId::from_serialized)- .unwrap_or_else(NavigationHistoryDocumentId::allocate);- snapshots.push(NavigationHistorySerializedEntry {- url,- history_state_json,- navigation_state_json,- referrer_policy: navigation_entry_referrer_policy_value(scope, entry),- document_id,- history_index: index,- index: entry_index,- id,- key,- });- }- snapshots+ record+ .borrow()+ .entries()+ .iter()+ .enumerate()+ .map(|(index, entry)| snapshot_native_entry(&entry.borrow(), index as u32))+ .collect()}pub(super) fn apply_current_document_referrer_policy_to_entry_snapshots<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rsindex c6f1d836c..b9b310faa 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs@@ -1,8 +1,9 @@-use super::super::history_runtime::state::{- HISTORY_BACKING_SLOT, new_history_backing, shared_history_backing, window_has_shared_history,+use super::super::history_runtime::{+ native,+ state::{history_window_owner, window_has_shared_history},};use super::super::navigation_entry::{- history_entries, history_index, set_history_scroll_restoration, set_history_state,+ cache_current_history_state, history_entries, history_index, set_history_scroll_restoration,};use super::accessors::{install_history_prototype_accessors, install_navigation_prototype_accessors,@@ -15,10 +16,7 @@ use moli_webapi_declare::WebApiObject;#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::History)]-struct HistoryRuntimeObjectDeclaration<'scope> {- #[webapi(slot = HISTORY_BACKING_SLOT)]- backing: v8::Local<'scope, v8::Object>,-}+struct HistoryRuntimeObjectDeclaration {}#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::Navigation)]@@ -47,16 +45,31 @@ pub(in crate::context_bootstrap) fn build_history_runtime_state<'s>(if let Some(prototype) = global_constructor_prototype(scope, "History") {install_history_prototype_accessors(scope, prototype);}- let backing = if window_has_shared_history(scope, window) {- shared_history_backing(scope, window)- .ok_or_else(|| anyhow::anyhow!("isolated History is missing its Window's backing"))?+ let record = if window_has_shared_history(scope, window) {+ let owner = history_window_owner(scope, window);+ super::super::navigation_window::window_history_for_holder(scope, owner)+ .and_then(|history| native::history(scope, history))+ .ok_or_else(|| {+ anyhow::anyhow!("isolated History is missing its native Window history")+ })?} else {let entries = build_history_entries_array_from_seed(scope, window, initial_seed);- new_history_backing(scope, entries, initial_seed.current_index)+ let records = (0..entries.length())+ .filter_map(|index| {+ let entry = entries.get_index(scope, index)?;+ let entry = v8::Local::<v8::Object>::try_from(entry).ok()?;+ native::entry(scope, entry)+ })+ .collect();+ std::rc::Rc::new(std::cell::RefCell::new(moli_history::WindowHistory::new(+ records,+ initial_seed.current_index,+ )))};- let history = HistoryRuntimeObjectDeclaration::new(backing)+ let history = HistoryRuntimeObjectDeclaration::new().bind(scope).map_err(anyhow::Error::from)?;+ native::bind_history(scope, history, record);Ok(history)}@@ -124,5 +137,5 @@ pub(in crate::context_bootstrap) fn install_history_state_runtime_state<'s>(history: v8::Local<'s, v8::Object>,state: v8::Local<'s, v8::Value>,) {- set_history_state(scope, history, state);+ cache_current_history_state(scope, history, state);}diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rsindex 41495e6b7..d7f806a8a 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs@@ -795,6 +795,9 @@ impl ChildBrowsingContextEntry {.entries.push(NavigationHistorySerializedEntry {url: url.as_str().to_owned(),+ history_state: None,+ navigation_state: None,+ scroll_restoration: Default::default(),history_state_json: None,navigation_state_json: None,referrer_policy: None,diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rsindex 6ad4d277c..de2a89ec6 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs@@ -101,7 +101,7 @@ async fn history_worlds_share_mutations_but_keep_wrappers_and_state_caches_separ);assert_eq!(vm.eval_in_isolated_context(isolated, READ_STATE).unwrap(),- r##"[1,true,true,true,3,true,true,"auto","#one",true,true]"##+ r##"[1,true,true,true,3,true,true,"manual","#one",true,true]"##);assert_eq!(vm.eval("String(history.state.value)").unwrap(), "1");vm.eval_in_isolated_context(later, "history.forward(); 'queued'")@@ -212,7 +212,7 @@ async fn history_worlds_child_mutations_share_only_the_child_window_history() {);assert_eq!(vm.eval_in_isolated_context(isolated, READ_CHILD).unwrap(),- "child:auto:#child"+ "child:manual:#child");vm.eval_in_isolated_context(isolated, "history.forward(); 'queued'").unwrap();@@ -332,3 +332,78 @@ fn history_worlds_share_primitive_state_without_coercion() {assert_eq!(vm.eval(&check).unwrap(), "true", "state: {state}");}}++#[test]+fn history_native_snapshot_survives_isolate_replacement_with_structured_values() {+ let seed = {+ let mut vm = new_storage_test_vm("https://example.com/base");+ vm.eval(r##"+ globalThis.jsonHooks = 0;+ Object.defineProperty(Object.prototype, 'toJSON', {configurable: true, get() {+ jsonHooks++;+ throw new Error('history must not call toJSON');+ }});+ const state = {map: new Map([['answer', 42n]]), bytes: new Uint8Array([3, 4]), missing: undefined, zero: -0, blob: new Blob(['native'], {type: 'text/plain'})};+ state.self = state;+ history.replaceState(state, '', '#saved');+ history.scrollRestoration = 'manual';+ navigation.updateCurrentEntry({state: new Set([7n])});+ history.state.map.set('answer', 99n);+ location.href = '/next';+ 'queued'+ "##).unwrap();+ let pending = vm.take_pending_location_navigation_with_seed().unwrap();+ assert_eq!(vm.eval("String(jsonHooks)").unwrap(), "0");+ let mut seed = pending.entry_seed.unwrap();+ seed.current_index = seed+ .entries+ .iter()+ .find(|entry| entry.url.ends_with("#saved"))+ .unwrap()+ .history_index;+ seed.activation = None;+ seed+ };+ // The source VM (including its isolate and all JS objects) is gone.+ let mut restored = new_storage_test_vm("https://example.com/base#saved");+ restored.install_navigation_bootstrap_entry(Some(seed));+ let isolated = restored+ .create_isolated_world("restored-history", false)+ .unwrap();+ const READ: &str = r#"JSON.stringify([+ history.state.map instanceof Map,+ history.state.map.get('answer') === 42n,+ history.state.bytes instanceof Uint8Array,+ history.state.bytes[1] === 4,+ 'missing' in history.state && history.state.missing === undefined,+ Object.is(history.state.zero, -0),+ history.state.self === history.state,+ history.scrollRestoration,+ navigation.currentEntry.getState().has(7n),+ history.state.blob instanceof Blob && history.state.blob.size === 6 && history.state.blob.type === 'text/plain'+ ])"#;+ assert_eq!(+ restored.eval(READ).unwrap(),+ r#"[true,true,true,true,true,true,true,"manual",true,true]"#+ );+ assert_eq!(+ restored.eval_in_isolated_context(isolated, READ).unwrap(),+ r#"[true,true,true,true,true,true,true,"manual",true,true]"#+ );+}++#[test]+fn history_native_fragment_navigation_preserves_structured_navigation_state() {+ let mut vm = new_storage_test_vm("https://example.com/base");+ vm.eval(+ r##"+ history.replaceState({value: 5n}, '');+ navigation.updateCurrentEntry({state: new Map([['value', 9n]])});+ globalThis.retained = navigation.currentEntry;+ location.hash = '#next';+ 'changed'+ "##,+ )+ .unwrap();+ assert_eq!(vm.eval("String(history.state.value === 5n && navigation.currentEntry.getState().get('value') === 9n && retained.getState().get('value') === 9n)").unwrap(), "true");+}diff --git a/moli-renderer-v8/src/structured_clone.rs b/moli-renderer-v8/src/structured_clone.rsindex dc527fef7..77535e6ba 100644--- a/moli-renderer-v8/src/structured_clone.rs+++ b/moli-renderer-v8/src/structured_clone.rs@@ -63,6 +63,45 @@ impl V8StructuredClonePayload {}}+#[derive(Clone)]+struct StoredCloneAttachments {+ blobs: Vec<ClonedBlob>,+ file_system_handles: Vec<ClonedFileSystemHandle>,+}++/// History retains serialized bytes and native capabilities, never a live JS+/// graph. Storage serialization rejects transferred objects and Wasm modules.+pub(crate) fn serialize_history_state<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+) -> Option<moli_history::SerializedScriptValue> {+ let payload = serialize_for_wire_for_storage(scope, value)?;+ Some(moli_history::SerializedScriptValue::new(+ payload.base.wire_bytes,+ StoredCloneAttachments {+ blobs: payload.blobs,+ file_system_handles: payload.file_system_handles,+ },+ ))+}++pub(crate) fn deserialize_history_state<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: &moli_history::SerializedScriptValue,+) -> Option<v8::Local<'s, v8::Value>> {+ let attachments = value.attachments::<StoredCloneAttachments>()?;+ let payload = V8StructuredClonePayload {+ base: StructuredCloneWireBytes {+ wire_bytes: value.bytes().to_vec(),+ ..Default::default()+ },+ blobs: attachments.blobs.clone(),+ file_system_handles: attachments.file_system_handles.clone(),+ ..Default::default()+ };+ deserialize_from_wire(scope, &payload)+}+#[derive(Clone)]struct ClonedWasmModule {clone_id: u32,diff --git a/moli-structured-clone/src/lib.rs b/moli-structured-clone/src/lib.rsindex 874f4b94c..b627dbaf2 100644--- a/moli-structured-clone/src/lib.rs+++ b/moli-structured-clone/src/lib.rs@@ -6,5 +6,7 @@//! services such as MessagePort and BroadcastChannel.mod payload;+mod stored;pub use payload::{StructuredCloneBytes, TransferredArrayBuffer};+pub use stored::SerializedScriptValue;diff --git a/moli-structured-clone/src/stored.rs b/moli-structured-clone/src/stored.rsnew file mode 100644index 000000000..455d56575--- /dev/null+++ b/moli-structured-clone/src/stored.rs@@ -0,0 +1,50 @@+use std::{any::Any, fmt, sync::Arc};++/// An immutable serialized value, with optional trusted native host-object+/// attachments (Blob data and storage capabilities, for example).+///+/// Attachments are separate from script-controlled wire bytes. `Send + Sync`+/// rules out realm-local JS handles. The embedding's codec is responsible for+/// their concrete type and validates capabilities when deserializing them.+#[derive(Clone)]+pub struct SerializedScriptValue(Arc<StoredValue>);++struct StoredValue {+ bytes: Vec<u8>,+ attachments: Box<dyn Any + Send + Sync>,+}++impl SerializedScriptValue {+ pub fn new(bytes: Vec<u8>, attachments: impl Any + Send + Sync) -> Self {+ Self(Arc::new(StoredValue {+ bytes,+ attachments: Box::new(attachments),+ }))+ }++ pub fn bytes(&self) -> &[u8] {+ &self.0.bytes+ }++ pub fn attachments<T: Any + Send + Sync>(&self) -> Option<&T> {+ self.0.attachments.downcast_ref()+ }+}++// Serialized state has snapshot identity. Cloning a history seed preserves+// that identity without copying bytes or comparing native capabilities.+impl PartialEq for SerializedScriptValue {+ fn eq(&self, other: &Self) -> bool {+ Arc::ptr_eq(&self.0, &other.0)+ }+}++impl Eq for SerializedScriptValue {}++impl fmt::Debug for SerializedScriptValue {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("SerializedScriptValue")+ .field("byte_length", &self.0.bytes.len())+ .finish_non_exhaustive()+ }+}