Truly independent web browser
LibWeb: Implement IndexedDB in Rust
Shannon Boothc1f262bdea50
diff --git a/AK/Debug.h.in b/AK/Debug.h.inindex f6f89313d40..8daedfc8366 100644--- a/AK/Debug.h.in+++ b/AK/Debug.h.in@@ -98,10 +98,6 @@# cmakedefine01 ICO_DEBUG#endif-#ifndef IDB_DEBUG-# cmakedefine01 IDB_DEBUG-#endif-#ifndef IDL_DEBUG# cmakedefine01 IDL_DEBUG#endifdiff --git a/AK/JsonValue.h b/AK/JsonValue.hindex 70d92a67bef..c0255362efa 100644--- a/AK/JsonValue.h+++ b/AK/JsonValue.h@@ -15,6 +15,8 @@namespace AK {class JsonValue {+ AK_ALLOC_WITH_KMALLOC;+public:enum class Type {Null,diff --git a/Cargo.lock b/Cargo.lockindex 3f520e0dbfa..2024b9457b5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -922,6 +922,7 @@ dependencies = ["libgfx_rust","libjs_rust","libtextcodec_rust",+ "libunicode_rust","liburl_rust","libwasm_engine","libweb_rust",diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.tomlindex 775827a7e85..20d6bd8be08 100644--- a/Libraries/LibWeb/Bindings/Rust/Cargo.toml+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml@@ -26,6 +26,7 @@ libcompress_rust = { path = "../../../LibCompress/Rust" }libgfx_rust = { path = "../../../LibGfx/Rust", default-features = false }libjs_rust = { path = "../../../LibJS/Rust", default-features = false }libtextcodec_rust = { path = "../../../LibTextCodec/Rust" }+libunicode_rust = { path = "../../../LibUnicode/Rust", default-features = false }liburl_rust = { path = "../../../LibURL/Rust", default-features = false }libwasm_engine = { path = "../../../LibWasm/Engine" }libweb_rust = { path = "../../Rust" }diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rsnew file mode 100644index 00000000000..8615f31e740--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs@@ -0,0 +1,282 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What IndexedDB asks of LibWeb's C++ code, defined in Libraries/LibWeb/IndexedDB/RustIntegration.cpp.++use std::rc::Rc;++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, Gc, Object, RawNativeFunctionResult, Realm, Trace, Value, Vm};+use liburl_rust::FfiOrigin;+use liburl_rust::origin::Origin;++use crate::bindings::conversions::CppInterface;+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::indexed_db::idb_record::StorageSerializationRecord;+use crate::indexed_db::internal::database::Database;+use crate::indexed_db::internal::function::{Function, FunctionCell, call_function};+use crate::indexed_db::internal::key::{Key, KeyValue};+use crate::indexed_db::internal::mutation_log::{TransactionChange, TransactionChanges};+use crate::indexed_db::internal::storage::StorageKey;++unsafe extern "C" {+ fn web_indexed_db_create_dom_exception(name: ak::Span<'_, u8>, message: usize) -> *mut c_void;+ fn web_indexed_db_dom_exception_from_value(value: u64) -> *mut c_void;+ fn web_indexed_db_wrap_dom_exception(realm: *mut c_void, exception: *mut c_void) -> *mut c_void;+ fn web_indexed_db_obtain_a_storage_key(+ realm: *mut c_void,+ ctx: *mut c_void,+ on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),+ ) -> bool;+ fn web_indexed_db_create_dom_string_list(realm: *mut c_void, strings: *const usize, count: usize) -> *mut c_void;+ fn web_indexed_db_structured_serialize_for_storage(+ realm: *mut c_void,+ value: u64,+ bytes: *mut c_void,+ append: unsafe extern "C" fn(*mut c_void, *const u8, usize),+ ) -> RawNativeFunctionResult;+ fn web_indexed_db_structured_deserialize(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> RawNativeFunctionResult;+ fn web_indexed_db_queue_a_database_task(cell: *mut c_void, steps: unsafe extern "C" fn(*mut c_void, *mut c_void));+ fn web_indexed_db_run_in_parallel(cell: *mut c_void, steps: unsafe extern "C" fn(*mut c_void, *mut c_void));+ fn web_indexed_db_main_thread_event_loop() -> *mut c_void;+ fn web_indexed_db_enqueue_check_pending_connection_wait(database: *mut c_void);+ fn web_indexed_db_devtools_client_is_active(realm: *mut c_void) -> bool;+ fn web_indexed_db_create_transaction_changes() -> *mut c_void;+ fn web_indexed_db_append_transaction_change(+ changes: *mut c_void,+ kind: u8,+ database_name: usize,+ object_store_name: usize,+ key: *mut c_void,+ );+ fn web_indexed_db_notify_devtools(realm: *mut c_void, changes: *mut c_void);+ fn web_indexed_db_json_number(value: f64) -> *mut c_void;+ fn web_indexed_db_json_string(value: usize) -> *mut c_void;+ fn web_indexed_db_json_binary(bytes: ak::Span<'_, u8>) -> *mut c_void;+ fn web_indexed_db_json_null() -> *mut c_void;+ fn web_indexed_db_json_array() -> *mut c_void;+ fn web_indexed_db_json_array_append(array: *mut c_void, value: *mut c_void);+}++/// A WebIDL::DOMException of LibWeb.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DomException(CppCell);++impl DomException {+ pub(crate) fn create(name: &str, message: &str) -> Self {+ Self::create_with_utf16_message(name, &Utf16String::from_utf8(message))+ }++ fn create_with_utf16_message(name: &str, message: &Utf16String) -> Self {+ // SAFETY: The name and the message are lent for the call, and LibWeb returns a live DOMException.+ Self(unsafe {+ CppCell::from_raw(web_indexed_db_create_dom_exception(+ ak::Span::new(name.as_bytes()),+ message.raw_identity(),+ ))+ })+ }++ /// The operations of requests only throw DOMExceptions.+ pub(crate) fn from_exception(exception: Exception) -> Self {+ match exception {+ Exception::Dom(name, message) => Self::create_with_utf16_message(name, &message),+ Exception::Thrown(throw) => {+ // SAFETY: The value is live while the call reads it.+ let exception = unsafe { web_indexed_db_dom_exception_from_value(throw.value().to_raw()) };+ assert!(!exception.is_null(), "the operation of a request threw a DOMException");+ // SAFETY: LibWeb returns a live DOMException.+ Self(unsafe { CppCell::from_raw(exception) })+ }+ Exception::TypeError(_) | Exception::RangeError(_) => {+ unreachable!("the operation of a request threw a DOMException")+ }+ }+ }++ pub(crate) fn wrapper(&self, cx: &CallContext) -> CppInterface {+ // SAFETY: The realm and the DOMException are live, and LibWeb returns a live wrapper.+ let wrapper = unsafe { web_indexed_db_wrap_dom_exception(cx.realm().as_ptr().cast(), self.0.as_ptr()) };+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns a wrapper");+ // SAFETY: The wrapper is a live wrapper of a DOMException.+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }+ }+}++/// https://storage.spec.whatwg.org/#obtain-a-storage-key, given the relevant settings object of the realm's global+/// object.+pub(crate) fn obtain_a_storage_key(realm: Gc<Realm>) -> Option<StorageKey> {+ unsafe extern "C" fn on_origin(ctx: *mut c_void, ffi_origin: *const FfiOrigin) {+ // SAFETY: ctx is the origin below, and LibWeb lends the origin for the call.+ unsafe { *ctx.cast::<Option<Origin>>() = Some((*ffi_origin).to_origin()) };+ }++ let mut origin: Option<Origin> = None;+ // SAFETY: The realm is live, and the origin outlives the call.+ unsafe { web_indexed_db_obtain_a_storage_key(realm.as_ptr().cast(), (&raw mut origin).cast(), on_origin) };+ origin.map(|origin| StorageKey { origin })+}++pub(crate) fn create_dom_string_list(cx: &CallContext, strings: &[Utf16String]) -> CppInterface {+ let raw_strings: Vec<usize> = strings.iter().map(Utf16String::raw_identity).collect();+ // SAFETY: The realm is live, the strings are lent for the call, and LibWeb returns a live wrapper.+ let wrapper = unsafe {+ web_indexed_db_create_dom_string_list(cx.realm().as_ptr().cast(), raw_strings.as_ptr(), raw_strings.len())+ };+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns a wrapper");+ // SAFETY: The wrapper is a live wrapper of a DOMStringList.+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }+}++// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage+pub(crate) fn structured_serialize_for_storage(+ cx: &CallContext,+ value: Value,+) -> WebIdlResult<StorageSerializationRecord> {+ unsafe extern "C" fn append(bytes: *mut c_void, data: *const u8, length: usize) {+ // SAFETY: The bytes are the Vec below, and LibWeb passes that many bytes.+ unsafe { (*bytes.cast::<Vec<u8>>()).extend_from_slice(ak::slice_from_raw_parts(data, length)) };+ }++ let mut bytes: Vec<u8> = Vec::new();+ // SAFETY: The realm and the value are live, and the bytes outlive the call.+ unsafe {+ web_indexed_db_structured_serialize_for_storage(+ cx.realm().as_ptr().cast(),+ value.to_raw(),+ (&raw mut bytes).cast(),+ append,+ )+ }+ .into_completion()?;+ Ok(Rc::from(bytes))+}++// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize+pub(crate) fn structured_deserialize(cx: &CallContext, serialized: &StorageSerializationRecord) -> WebIdlResult<Value> {+ // SAFETY: The realm is live, and the bytes are lent for the call.+ Ok(+ unsafe { web_indexed_db_structured_deserialize(cx.realm().as_ptr().cast(), ak::Span::new(serialized)) }+ .into_completion()?,+ )+}++unsafe extern "C" fn run_function(vm: *mut c_void, cell: *mut c_void) {+ // SAFETY: LibWeb passes the VM and the cell of the function, which it kept alive.+ let (vm, function) = unsafe {+ (+ &*vm.cast::<Vm>(),+ Function::from_cell(Gc::from_non_null(NonNull::new_unchecked(+ cell.cast::<EmbedderCell<FunctionCell>>(),+ ))),+ )+ };+ call_function(vm, function);+}++/// Queues the task with no document and no event loop, as the C++ did.+pub(crate) fn queue_a_task_on_the_database_access_task_source(_: &Vm, steps: Function) {+ // SAFETY: The function is live, and the task keeps it alive until it runs.+ unsafe { web_indexed_db_queue_a_database_task(steps.cell_as_ptr(), run_function) };+}++/// Runs the function from a deferred invocation, as the C++ ran steps "in parallel".+pub(crate) fn run_in_parallel(_: &Vm, steps: Function) {+ // SAFETY: The function is live, and the deferred invocation keeps it alive until it runs.+ unsafe { web_indexed_db_run_in_parallel(steps.cell_as_ptr(), run_function) };+}++/// https://html.spec.whatwg.org/multipage/webappapis.html#main-thread-event-loop+pub(crate) fn main_thread_event_loop() -> CppCell {+ // SAFETY: LibWeb returns the live event loop.+ unsafe { CppCell::from_raw(web_indexed_db_main_thread_event_loop()) }+}++/// Checks the database's pending connection wait after the collection that runs a finalizer, if the database is still+/// alive then. Must not allocate a cell.+pub(crate) fn enqueue_post_gc_task(database: crate::indexed_db::internal::database::DatabaseRef) {+ // SAFETY: The database is live while LibGC finalizes the connection.+ unsafe { web_indexed_db_enqueue_check_pending_connection_wait(database.as_ptr().cast()) };+}++/// Runs the check that enqueue_post_gc_task() enqueued.+///+/// # Safety+///+/// The pointers must be the live VM and the live cell of a database.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_check_pending_connection_wait(vm: *mut c_void, database: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live database.+ let (vm, database) = unsafe {+ (+ &*vm.cast::<Vm>(),+ Gc::from_non_null(NonNull::new_unchecked(database.cast::<EmbedderCell<Database>>())),+ )+ };+ database.check_pending_connection_wait(vm);+}++pub(crate) fn devtools_client_is_active(realm: Gc<Realm>) -> bool {+ // SAFETY: The realm is live.+ unsafe { web_indexed_db_devtools_client_is_active(realm.as_ptr().cast()) }+}++/// A JsonValue of the key, which the caller takes over.+pub(crate) fn json_value_of_key(key: &Key) -> *mut c_void {+ // SAFETY: Each call hands over a new JsonValue, which the array takes over when it is appended.+ unsafe {+ match key.value() {+ _ if key.is_invalid() => web_indexed_db_json_null(),+ KeyValue::Double(value) => web_indexed_db_json_number(*value),+ KeyValue::String(value) => web_indexed_db_json_string(value.raw_identity()),+ KeyValue::Bytes(value) => web_indexed_db_json_binary(ak::Span::new(value)),+ KeyValue::Keys(subkeys) => {+ let array = web_indexed_db_json_array();+ for subkey in subkeys {+ web_indexed_db_json_array_append(array, json_value_of_key(subkey));+ }+ array+ }+ }+ }+}++pub(crate) fn notify_devtools_of_committed_changes(realm: Gc<Realm>, changes: &TransactionChanges) {+ // SAFETY: LibWeb returns new changes, which the notification takes over.+ let cpp_changes = unsafe { web_indexed_db_create_transaction_changes() };+ let append = |kind: u8, change: &TransactionChange| {+ let key = change+ .key+ .as_ref()+ .map_or(core::ptr::null_mut(), |key| json_value_of_key(key));+ // SAFETY: The changes are live, the names are lent for the call, and the call takes over the key.+ unsafe {+ web_indexed_db_append_transaction_change(+ cpp_changes,+ kind,+ change.database_name.raw_identity(),+ change.object_store_name.raw_identity(),+ key,+ );+ }+ };+ for change in &changes.added {+ append(0, change);+ }+ for change in &changes.changed {+ append(1, change);+ }+ for change in &changes.deleted {+ append(2, change);+ }+ // SAFETY: The realm is live, and the call takes over the changes.+ unsafe { web_indexed_db_notify_devtools(realm.as_ptr().cast(), cpp_changes) };+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/exports.rsnew file mode 100644index 00000000000..e9713d3efc9--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/exports.rs@@ -0,0 +1,376 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The C ABI of IndexedDB for LibWeb's C++ code: Libraries/LibWeb/IndexedDB/IDBFactory.cpp and Inspection.cpp.++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::Vm;+use liburl_rust::FfiOrigin;++use crate::bindings::cpp_cell::CppCell;+use crate::bindings::interface::{cell_into_abi, realm_arguments};+use crate::indexed_db::cpp::json_value_of_key;+use crate::indexed_db::idb_factory::IDBFactory;+use crate::indexed_db::idb_key_range::IDBKeyRange;+use crate::indexed_db::internal::algorithms::{+ KeyPath, cleanup_indexed_database_transactions, clear_an_object_store, close_a_database_connection,+ delete_records_from_an_object_store,+};+use crate::indexed_db::internal::database::Database;+use crate::indexed_db::internal::storage::StorageKey;++/// # Safety+///+/// The origin must be one that LibWeb lends.+unsafe fn storage_key_from_abi(origin: *const FfiOrigin) -> StorageKey {+ // SAFETY: The caller lends a live origin.+ StorageKey {+ origin: unsafe { (*origin).to_origin() },+ }+}++/// # Safety+///+/// `vm` must be the live VM.+unsafe fn vm_from_abi<'vm>(vm: *mut c_void) -> &'vm Vm {+ // SAFETY: The caller passes the live VM.+ unsafe { &*vm.cast::<Vm>() }+}++/// # Safety+///+/// `string` must be a raw AK::Utf16String that LibWeb lends.+unsafe fn utf16_string_from_abi(string: usize) -> Utf16String {+ // SAFETY: The caller lends a live string, whose reference the copy takes one of its own.+ unsafe {+ ak::reference_utf16_string(string);+ Utf16String::from_raw_owned(string)+ }+}++/// # Safety+///+/// The pointers must be the live VM and a live realm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_create_factory(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ cell_into_abi(IDBFactory::create(vm, realm))+}++/// https://w3c.github.io/IndexedDB/#cleanup-indexed-database-transactions+///+/// # Safety+///+/// The pointers must be the live VM and a live HTML::EventLoop.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_cleanup_indexed_database_transactions(+ vm: *mut c_void,+ event_loop: *mut c_void,+) -> bool {+ // SAFETY: The caller passes the live VM and a live event loop.+ let (vm, event_loop) = unsafe { (vm_from_abi(vm), CppCell::from_raw(event_loop)) };+ cleanup_indexed_database_transactions(vm, &event_loop)+}++/// Runs close a database connection with every connection of the realm's global object whose close pending flag is+/// unset.+///+/// # Safety+///+/// The pointers must be the live VM and a live realm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_close_all_connections(vm: *mut c_void, realm: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ Database::for_each_database(vm, |database| {+ for connection in database.associated_connections(vm).values().iter() {+ if connection.close_pending() {+ continue;+ }+ if connection.realm() == realm {+ close_a_database_connection(vm, *connection, None, false);+ }+ }+ });+}++/// A key path as the inspection callbacks receive it: none, a string, or a list of strings.+#[repr(C)]+pub struct KeyPathAbi {+ kind: u8,+ strings: *const usize,+ count: usize,+}++fn with_key_path_abi<R>(key_path: Option<&KeyPath>, function: impl FnOnce(&KeyPathAbi) -> R) -> R {+ match key_path {+ None => function(&KeyPathAbi {+ kind: 0,+ strings: core::ptr::null(),+ count: 0,+ }),+ Some(KeyPath::String(string)) => {+ let raw = [string.raw_identity()];+ function(&KeyPathAbi {+ kind: 1,+ strings: raw.as_ptr(),+ count: 1,+ })+ }+ Some(KeyPath::Sequence(strings)) => {+ let raw: Vec<usize> = strings.iter().map(Utf16String::raw_identity).collect();+ function(&KeyPathAbi {+ kind: 2,+ strings: raw.as_ptr(),+ count: raw.len(),+ })+ }+ }+}++/// Calls `on_database` with each database of the storage key: its name, its version, and the names of its object+/// stores, which the call borrows.+///+/// # Safety+///+/// The VM must be live, the origin lent, and `on_database` must not keep what it borrows.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_inspect_databases(+ vm: *mut c_void,+ origin: *const FfiOrigin,+ ctx: *mut c_void,+ on_database: unsafe extern "C" fn(*mut c_void, usize, u64, *const usize, usize),+) {+ // SAFETY: The caller passes the live VM and lends the origin.+ let (vm, storage_key) = unsafe { (vm_from_abi(vm), storage_key_from_abi(origin)) };+ for database in Database::for_key(vm, &storage_key).values().iter() {+ let names: Vec<Utf16String> = database+ .object_stores(vm)+ .values()+ .iter()+ .map(|object_store| object_store.name())+ .collect();+ let raw_names: Vec<usize> = names.iter().map(Utf16String::raw_identity).collect();+ let name = database.name();+ // SAFETY: The strings are lent for the call.+ unsafe {+ on_database(+ ctx,+ name.raw_identity(),+ database.version(),+ raw_names.as_ptr(),+ raw_names.len(),+ );+ }+ }+}++/// Calls `on_object_store` with each object store of the database of the storage key with the name, and then+/// `on_index` with each of its indexes. Returns whether the database exists.+///+/// # Safety+///+/// The VM must be live, the origin and the name lent, and the callbacks must not keep what they borrow.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_inspect_object_stores(+ vm: *mut c_void,+ origin: *const FfiOrigin,+ database_name: usize,+ ctx: *mut c_void,+ on_object_store: unsafe extern "C" fn(*mut c_void, usize, *const KeyPathAbi, bool),+ on_index: unsafe extern "C" fn(*mut c_void, usize, *const KeyPathAbi, bool, bool),+) -> bool {+ // SAFETY: The caller passes the live VM and lends the origin and the name.+ let (vm, storage_key, database_name) = unsafe {+ (+ vm_from_abi(vm),+ storage_key_from_abi(origin),+ utf16_string_from_abi(database_name),+ )+ };+ let Some(database) = Database::for_key_and_name(vm, &storage_key, &database_name) else {+ return false;+ };+ for object_store in database.object_stores(vm).values().iter() {+ let name = object_store.name();+ with_key_path_abi(object_store.key_path(), |key_path| {+ // SAFETY: What the callback receives is lent for the call.+ unsafe { on_object_store(ctx, name.raw_identity(), key_path, object_store.uses_a_key_generator()) };+ });+ for index in object_store.indexes(vm).values().iter() {+ let index_name = index.name();+ with_key_path_abi(Some(index.key_path()), |key_path| {+ // SAFETY: What the callback receives is lent for the call.+ unsafe {+ on_index(+ ctx,+ index_name.raw_identity(),+ key_path,+ index.unique(),+ index.multi_entry(),+ );+ }+ });+ }+ }+ true+}++/// Calls `on_record` with each record of the object store with the name in the database of the storage key with the+/// name: its key, a JsonValue that the callback takes over, and the bytes of its value, which the call borrows.+///+/// # Safety+///+/// The VM must be live, the origin and the names lent, and the callback must not keep the bytes.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_inspect_records(+ vm: *mut c_void,+ origin: *const FfiOrigin,+ database_name: usize,+ object_store_name: usize,+ ctx: *mut c_void,+ on_record: unsafe extern "C" fn(*mut c_void, *mut c_void, ak::Span<'_, u8>),+) {+ // SAFETY: The caller passes the live VM and lends the origin and the names.+ let (vm, storage_key, database_name, object_store_name) = unsafe {+ (+ vm_from_abi(vm),+ storage_key_from_abi(origin),+ utf16_string_from_abi(database_name),+ utf16_string_from_abi(object_store_name),+ )+ };+ let Some(database) = Database::for_key_and_name(vm, &storage_key, &database_name) else {+ return;+ };+ let Some(object_store) = database.object_store_with_name(&object_store_name) else {+ return;+ };+ for record in object_store.records().iter() {+ // SAFETY: The callback takes over the key and borrows the bytes for the call.+ unsafe { on_record(ctx, json_value_of_key(&record.key), ak::Span::new(&record.value)) };+ }+}++/// The outcome of an inspection operation.+#[repr(u8)]+pub enum InspectionStatus {+ Done = 0,+ NoDatabase = 1,+ NoObjectStore = 2,+ NoRecord = 3,+ Blocked = 4,+}++/// Deletes the database of the storage key with the name, unless a connection to it is open.+///+/// # Safety+///+/// The VM must be live, and the origin and the name lent.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_delete_database_for_inspection(+ vm: *mut c_void,+ origin: *const FfiOrigin,+ database_name: usize,+) -> InspectionStatus {+ // SAFETY: The caller passes the live VM and lends the origin and the name.+ let (vm, storage_key, database_name) = unsafe {+ (+ vm_from_abi(vm),+ storage_key_from_abi(origin),+ utf16_string_from_abi(database_name),+ )+ };+ if let Some(database) = Database::for_key_and_name(vm, &storage_key, &database_name)+ && !database.associated_connections(vm).is_empty()+ {+ return InspectionStatus::Blocked;+ }++ Database::delete_for_key_and_name(vm, &storage_key, &database_name);+ InspectionStatus::Done+}++/// Clears the object store with the name of the database of the storage key with the name.+///+/// # Safety+///+/// The VM must be live, and the origin and the names lent.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_clear_object_store_for_inspection(+ vm: *mut c_void,+ origin: *const FfiOrigin,+ database_name: usize,+ object_store_name: usize,+) -> InspectionStatus {+ // SAFETY: The caller passes the live VM and lends the origin and the names.+ let (vm, storage_key, database_name, object_store_name) = unsafe {+ (+ vm_from_abi(vm),+ storage_key_from_abi(origin),+ utf16_string_from_abi(database_name),+ utf16_string_from_abi(object_store_name),+ )+ };+ let Some(database) = Database::for_key_and_name(vm, &storage_key, &database_name) else {+ return InspectionStatus::NoDatabase;+ };+ let Some(object_store) = database.object_store_with_name(&object_store_name) else {+ return InspectionStatus::NoObjectStore;+ };++ clear_an_object_store(vm, object_store);+ InspectionStatus::Done+}++/// Deletes the first record of the object store with the name of the database of the storage key with the name whose+/// key `matches` accepts. `matches` takes over the key it is given.+///+/// # Safety+///+/// The VM must be live, and the origin and the names lent.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_indexed_db_delete_record_for_inspection(+ vm: *mut c_void,+ origin: *const FfiOrigin,+ database_name: usize,+ object_store_name: usize,+ ctx: *mut c_void,+ matches: unsafe extern "C" fn(*mut c_void, *mut c_void) -> bool,+) -> InspectionStatus {+ // SAFETY: The caller passes the live VM and lends the origin and the names.+ let (vm, storage_key, database_name, object_store_name) = unsafe {+ (+ vm_from_abi(vm),+ storage_key_from_abi(origin),+ utf16_string_from_abi(database_name),+ utf16_string_from_abi(object_store_name),+ )+ };+ let Some(database) = Database::for_key_and_name(vm, &storage_key, &database_name) else {+ return InspectionStatus::NoDatabase;+ };+ let Some(object_store) = database.object_store_with_name(&object_store_name) else {+ return InspectionStatus::NoObjectStore;+ };++ let key = object_store+ .records()+ .iter()+ .map(|record| record.key.clone())+ // SAFETY: The callback takes over the key.+ .find(|key| unsafe { matches(ctx, json_value_of_key(key)) });+ let Some(key) = key else {+ return InspectionStatus::NoRecord;+ };++ let range = IDBKeyRange::create(vm, Some(key.clone()), Some(key), false, false);+ delete_records_from_an_object_store(vm, object_store, &range);+ InspectionStatus::Done+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_cursor.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_cursor.rsnew file mode 100644index 00000000000..fa08209e431--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_cursor.rs@@ -0,0 +1,860 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBCursor, https://w3c.github.io/IndexedDB/#cursor-interface++use std::rc::Rc;++use core::cell::{Cell, RefCell};+use core::ops::Deref;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, Realm, ThrowCompletionOr, Trace, Value, Vm};++use crate::bindings::conversions::ToJs;+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, with_temporary_execution_context_and_callbacks};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::indexed_db::idb_cursor_with_value::IDBCursorWithValue;+use crate::indexed_db::idb_index::IDBIndex;+use crate::indexed_db::idb_key_range::IDBKeyRange;+use crate::indexed_db::idb_object_store::{+ IDBObjectStore, data_error, idb_cursor_result, invalid_state_error, request_of, transaction_inactive_error,+};+use crate::indexed_db::idb_request::{AnyIDBRequest, IDBRequest, IDBRequestSource};+use crate::indexed_db::idb_transaction::IDBTransaction;+use crate::indexed_db::internal::algorithms::{+ RecordSource, asynchronously_execute_a_request, clone_in_realm, convert_a_key_to_a_value, convert_a_value_to_a_key,+ delete_records_from_an_object_store, extract_a_key_from_a_value_using_a_key_path, iterate_a_cursor,+ store_a_record_into_an_object_store,+};+use crate::indexed_db::internal::function::{NoCells, create_operation};+use crate::indexed_db::internal::key::Key;+use crate::indexed_db::internal::object_store::ObjectStoreRef;++/// The enumeration IDBCursorDirection of IndexedDB/IDBCursor.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum IDBCursorDirection {+ Next,+ Nextunique,+ Prev,+ Prevunique,+}++/// The union (IDBObjectStore or IDBIndex) of IndexedDB/IDBCursor.idl.+pub(crate) enum IDBObjectStoreOrIDBIndex {+ IDBObjectStore(Ref<IDBObjectStore>),+ IDBIndex(Ref<IDBIndex>),+}++/// The source handle of a cursor: the index handle or the object store handle that opened it.+#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum CursorSourceHandle {+ ObjectStore(Ref<IDBObjectStore>),+ Index(Ref<IDBIndex>),+}++impl From<CursorSourceHandle> for IDBRequestSource {+ fn from(source_handle: CursorSourceHandle) -> Self {+ match source_handle {+ CursorSourceHandle::ObjectStore(object_store) => IDBRequestSource::ObjectStore(object_store),+ CursorSourceHandle::Index(index) => IDBRequestSource::Index(index),+ }+ }+}++// NB: The key and primaryKey getters return the same object instance every time they are inspected, until the+// cursor's key or effective key changes. These cache the converted values along with the keys they came from.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct CachedKeyValue {+ #[gc(untraced)]+ key: Option<Rc<Key>>,+ value: Value,+}++// https://w3c.github.io/IndexedDB/#cursor-interface+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBCursor {+ // A cursor has a key and a value which represent the key and the value of the last iterated record.+ #[gc(untraced)]+ key: RefCell<Option<Rc<Key>>>,+ value: Cell<Option<Value>>,++ // A cursor has a position within its range.+ #[gc(untraced)]+ position: RefCell<Option<Rc<Key>>>,++ // When iterating indexes the cursor also has an object store position+ #[gc(untraced)]+ object_store_position: RefCell<Option<Rc<Key>>>,++ // A cursor has a direction that determines whether it moves in monotonically increasing or decreasing order of the record keys when iterated, and if it skips duplicated values when iterating indexes.+ #[gc(untraced)]+ direction: IDBCursorDirection,++ // A cursor has a got value flag.+ got_value: Cell<bool>,++ // A cursor has a source handle, which is the index handle or the object store handle that opened the cursor.+ source_handle: CursorSourceHandle,++ // A cursor has a range of records in either an index or an object store.+ range: Ref<IDBKeyRange>,++ // A cursor has a request, which is the request used to open the cursor.+ request: Cell<Option<Ref<IDBRequest>>>,++ // A cursor also has a key only flag, that indicates whether the cursor’s value is exposed via the API.+ key_only: bool,++ cached_key_value: GcRefCell<CachedKeyValue>,+ cached_primary_key_value: GcRefCell<CachedKeyValue>,++ // NB: The cursor as the interface it was created as, for the members of IDBCursor to return and pass on.+ this: Cell<Option<AnyIDBCursor>>,+}++impl Wrappable for IDBCursor {}++impl IDBCursor {+ #[allow(clippy::too_many_arguments, reason = "the C++ created a cursor with these")]+ fn new(+ source_handle: CursorSourceHandle,+ position: Option<Rc<Key>>,+ direction: IDBCursorDirection,+ got_value: bool,+ key: Option<Rc<Key>>,+ value: Option<Value>,+ range: Ref<IDBKeyRange>,+ key_only: bool,+ ) -> Self {+ Self {+ value: Cell::new(value),+ position: RefCell::new(position),+ object_store_position: RefCell::new(None),+ direction,+ got_value: Cell::new(got_value),+ key: RefCell::new(key),+ source_handle,+ range,+ request: Cell::new(None),+ key_only,+ cached_key_value: GcRefCell::new(CachedKeyValue {+ key: None,+ value: Value::UNDEFINED,+ }),+ cached_primary_key_value: GcRefCell::new(CachedKeyValue {+ key: None,+ value: Value::UNDEFINED,+ }),+ this: Cell::new(None),+ }+ }++ #[allow(clippy::too_many_arguments, reason = "the C++ created a cursor with these")]+ pub(crate) fn create(+ vm: &Vm,+ source_handle: CursorSourceHandle,+ position: Option<Rc<Key>>,+ direction: IDBCursorDirection,+ got_value: bool,+ key: Option<Rc<Key>>,+ value: Option<Value>,+ range: Ref<IDBKeyRange>,+ key_only: bool,+ ) -> AnyIDBCursor {+ let cursor = Self::new(+ source_handle,+ position,+ direction,+ got_value,+ key,+ value,+ range,+ key_only,+ );++ // A cursor that has its key only flag set to false implements the IDBCursorWithValue interface as well.+ let cursor = if key_only {+ AnyIDBCursor::IDBCursor(allocate(vm, |_| cursor))+ } else {+ AnyIDBCursor::IDBCursorWithValue(allocate(vm, |_| IDBCursorWithValue::new(cursor)))+ };+ cursor.this.set(Some(cursor));+ cursor+ }++ fn this(&self) -> AnyIDBCursor {+ self.this.get().expect("a cursor knows itself once it is created")+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ match self.source_handle {+ CursorSourceHandle::ObjectStore(object_store) => object_store.realm(),+ CursorSourceHandle::Index(index) => index.realm(),+ }+ }++ pub(crate) fn direction_value(&self) -> IDBCursorDirection {+ self.direction+ }++ pub(crate) fn range(&self) -> Ref<IDBKeyRange> {+ self.range+ }++ pub(crate) fn position(&self) -> Option<Rc<Key>> {+ self.position.borrow().clone()+ }++ pub(crate) fn current_key(&self) -> Option<Rc<Key>> {+ self.key.borrow().clone()+ }++ pub(crate) fn object_store_position(&self) -> Option<Rc<Key>> {+ self.object_store_position.borrow().clone()+ }++ pub(crate) fn key_only(&self) -> bool {+ self.key_only+ }++ pub(crate) fn current_value(&self) -> Option<Value> {+ self.value.get()+ }++ pub(crate) fn set_request(&self, request: Option<Ref<IDBRequest>>) {+ self.request.set(request);+ }++ pub(crate) fn set_position(&self, position: Option<Rc<Key>>) {+ *self.position.borrow_mut() = position;+ }++ pub(crate) fn set_got_value(&self, got_value: bool) {+ self.got_value.set(got_value);+ }++ pub(crate) fn set_key(&self, key: Option<Rc<Key>>) {+ *self.key.borrow_mut() = key;+ }++ pub(crate) fn set_value(&self, value: Option<Value>) {+ self.value.set(value);+ }++ pub(crate) fn set_object_store_position(&self, object_store_position: Option<Rc<Key>>) {+ *self.object_store_position.borrow_mut() = object_store_position;+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-source+ pub(crate) fn source(&self, _: &mut CallContext) -> WebIdlResult<IDBObjectStoreOrIDBIndex> {+ // The source getter steps are to return this’s source handle.+ Ok(match self.source_handle {+ CursorSourceHandle::ObjectStore(object_store) => IDBObjectStoreOrIDBIndex::IDBObjectStore(object_store),+ CursorSourceHandle::Index(index) => IDBObjectStoreOrIDBIndex::IDBIndex(index),+ })+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-direction+ pub(crate) fn direction(&self, _: &mut CallContext) -> WebIdlResult<IDBCursorDirection> {+ // The direction getter steps are to return this’s direction.+ Ok(self.direction)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-request+ pub(crate) fn request(&self, _: &mut CallContext) -> WebIdlResult<Ref<IDBRequest>> {+ // The request getter steps are to return this’s request.+ Ok(self.request.get().expect("a cursor has a request once it is returned"))+ }++ pub(crate) fn key(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The key getter steps are to return the result of converting a key to a+ // value with the cursor's current key.+ // NOTE: If key returns an object (e.g. a Date or Array), it returns the same object instance every time it is+ // inspected, until the cursor's key is changed. This means that if the object is modified, those+ // modifications will be seen by anyone inspecting the value of the cursor. However modifying such an object+ // does not modify the contents of the database.+ let Some(key) = self.current_key() else {+ return Ok(Value::UNDEFINED);+ };++ let is_cached = self+ .cached_key_value+ .borrow()+ .key+ .as_ref()+ .is_some_and(|cached| Rc::ptr_eq(cached, &key));+ if !is_cached {+ let value = convert_a_key_to_a_value(cx, &key);+ *self.cached_key_value.borrow_mut(cx.vm()) = CachedKeyValue { key: Some(key), value };+ }+ Ok(self.cached_key_value.borrow().value)+ }++ pub(crate) fn primary_key(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The primaryKey getter steps are to return the result of converting a key+ // to a value with the cursor's current effective key.+ // NOTE: If primaryKey returns an object (e.g. a Date or Array), it returns the same object instance every time+ // is inspected, until the cursor's effective key is changed. This means that if the object is modified,+ // those modifications will be seen by anyone inspecting the value of the cursor. However modifying such an+ // object does not modify the contents of the database.+ // AD-HOC: The effective key of a cursor whose key is undefined is undefined too, as in other engines.+ let Some(effective_key) = self.current_key().and_then(|_| self.effective_key()) else {+ return Ok(Value::UNDEFINED);+ };+ let is_cached = self+ .cached_primary_key_value+ .borrow()+ .key+ .as_ref()+ .is_some_and(|cached| Rc::ptr_eq(cached, &effective_key));+ if !is_cached {+ let value = convert_a_key_to_a_value(cx, &effective_key);+ *self.cached_primary_key_value.borrow_mut(cx.vm()) = CachedKeyValue {+ key: Some(effective_key),+ value,+ };+ }+ Ok(self.cached_primary_key_value.borrow().value)+ }++ pub(crate) fn is_source_or_object_store_deleted(&self) -> bool {+ match self.source_handle {+ CursorSourceHandle::ObjectStore(object_store) => object_store.store().is_deleted(),+ CursorSourceHandle::Index(index) => index.index().is_deleted() || index.index().object_store().is_deleted(),+ }+ }++ // https://w3c.github.io/IndexedDB/#cursor-transaction+ pub(crate) fn transaction_object(&self) -> Ref<IDBTransaction> {+ // A cursor has a transaction, which is the transaction from the cursor’s source handle.+ match self.source_handle {+ CursorSourceHandle::ObjectStore(object_store) => object_store.transaction_object(),+ CursorSourceHandle::Index(index) => index.transaction_object(),+ }+ }++ // https://w3c.github.io/IndexedDB/#cursor-source+ pub(crate) fn internal_source(&self) -> RecordSource {+ // A cursor has a source, which is an index or an object store from the cursor’s source handle.+ match self.source_handle {+ CursorSourceHandle::ObjectStore(object_store) => RecordSource::ObjectStore(object_store.store()),+ CursorSourceHandle::Index(index) => RecordSource::Index(index.index()),+ }+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-continue+ pub(crate) fn r#continue(&self, cx: &mut CallContext, key: Option<Value>) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = self.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this's transaction.+ let transaction = self.transaction_object();++ // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while continuing cursor",+ ));+ }++ // 3. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.+ if self.is_source_or_object_store_deleted() {+ return Err(invalid_state_error("Source or its object store has been deleted"));+ }++ // 4. If this's got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.+ if !self.got_value.get() {+ return Err(invalid_state_error("Cursor is active or EOL while continuing"));+ }++ // 5. If key is given, then:+ let mut key_value: Option<Rc<Key>> = None;+ if let Some(key) = key {+ // 1. Let r be the result of converting a value to a key with key. Rethrow any exceptions.+ let r = convert_a_value_to_a_key(&realm_cx, key, None)?;++ // 2. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if r.is_invalid() {+ return Err(Exception::Dom("DataError", r.value_as_string().clone()));+ }++ // 3. Let key be r.+ let position = self.position().expect("a cursor that got a value has a position");+ key_value = Some(r.clone());++ // 4. If key is less than or equal to this's position and this's direction is "next" or "nextunique", then throw a "DataError" DOMException.+ let is_less_than_or_equal_to = Key::less_than(&r, &position) || Key::equals(&r, &position);+ if is_less_than_or_equal_to+ && (self.direction == IDBCursorDirection::Next || self.direction == IDBCursorDirection::Nextunique)+ {+ return Err(data_error("Key is less than or equal to cursor's position"));+ }++ // 5. If key is greater than or equal to this's position and this's direction is "prev" or "prevunique", then throw a "DataError" DOMException.+ let is_greater_than_or_equal_to = Key::greater_than(&r, &position) || Key::equals(&r, &position);+ if is_greater_than_or_equal_to+ && (self.direction == IDBCursorDirection::Prev || self.direction == IDBCursorDirection::Prevunique)+ {+ return Err(data_error("Key is greater than or equal to cursor's position"));+ }+ }++ // 6. Set this's got value flag to false.+ self.got_value.set(false);++ // 7. Let request be this's request.+ let request = self.request.get().expect("a cursor has a request");++ // 8. Set request’s processed flag to false.+ request.set_processed(false);++ // 9. Set request’s done flag to false.+ request.set_done(false);++ // 10. Let operation be an algorithm to run iterate a cursor with the current Realm record, this, and key (if given).+ let operation = create_operation(+ vm,+ (self.this(), realm, NoCells(key_value)),+ |vm, &(this, realm, ref key_value)| {+ let cx = CallContext::new(vm, realm);+ let result = iterate_a_cursor(&cx, this, key_value.0.clone(), None, 1)?;+ Ok(idb_cursor_result(&cx, result))+ },+ );++ // 11. Run asynchronously execute a request with this’s source handle, operation, and request.+ asynchronously_execute_a_request(+ vm,+ self.source_handle.into(),+ operation,+ Some(AnyIDBRequest::IDBRequest(request)),+ );++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#cursor-effective-key+ pub(crate) fn effective_key(&self) -> Option<Rc<Key>> {+ match self.source_handle {+ // If the source of a cursor is an object store, the effective key of the cursor is the cursor’s position+ CursorSourceHandle::ObjectStore(_) => self.position(),+ // If the source of a cursor is an index, the effective key is the cursor’s object store position.+ CursorSourceHandle::Index(_) => self.object_store_position(),+ }+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-advance+ pub(crate) fn advance(&self, cx: &mut CallContext, count: u32) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = self.realm();++ // 1. If count is 0 (zero), throw a TypeError.+ if count == 0 {+ return Err(Exception::type_error("Count must not be zero (0)"));+ }++ // 2. Let transaction be this’s transaction.+ let transaction = self.transaction_object();++ // 3. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while advancing cursor",+ ));+ }++ // 4. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.+ if self.is_source_or_object_store_deleted() {+ return Err(invalid_state_error("Source or its object store has been deleted"));+ }++ // 5. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.+ if !self.got_value.get() {+ return Err(invalid_state_error("Cursor is active or EOL while advancing"));+ }++ // 6. Set this’s got value flag to false.+ self.got_value.set(false);++ // 7. Let request be this’s request.+ let request = self.request.get().expect("a cursor has a request");++ // 8. Set request’s processed flag to false.+ request.set_processed(false);++ // 9. Set request’s done flag to false.+ request.set_done(false);++ // 10. Let operation be an algorithm to run iterate a cursor with the current Realm record, this, and count.+ let operation = create_operation(vm, (self.this(), realm, count), |vm, &(this, realm, count)| {+ let cx = CallContext::new(vm, realm);+ let result = iterate_a_cursor(&cx, this, None, None, u64::from(count))?;+ Ok(idb_cursor_result(&cx, result))+ });++ // 11. Run asynchronously execute a request with this’s source handle, operation, and request.+ asynchronously_execute_a_request(+ vm,+ self.source_handle.into(),+ operation,+ Some(AnyIDBRequest::IDBRequest(request)),+ );++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey+ pub(crate) fn continue_primary_key(+ &self,+ cx: &mut CallContext,+ key_param: Value,+ primary_key_param: Value,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = self.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = self.transaction_object();++ // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while continuing cursor",+ ));+ }++ // 3. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.+ if self.is_source_or_object_store_deleted() {+ return Err(invalid_state_error("Source or its object store has been deleted"));+ }++ // 4. If this’s source is not an index throw an "InvalidAccessError" DOMException.+ if !matches!(self.source_handle, CursorSourceHandle::Index(_)) {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_utf8("Cursor source is not an index"),+ ));+ }++ // 5. If this’s direction is not "next" or "prev", throw an "InvalidAccessError" DOMException.+ if self.direction != IDBCursorDirection::Next && self.direction != IDBCursorDirection::Prev {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_utf8("Cursor direction is not next or prev"),+ ));+ }++ // 6. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.+ if !self.got_value.get() {+ return Err(invalid_state_error("Cursor is active or EOL while continuing"));+ }++ // 7. Let r be the result of converting a value to a key with key. Rethrow any exceptions.+ let mut r = convert_a_value_to_a_key(&realm_cx, key_param, None)?;++ // 8. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if r.is_invalid() {+ return Err(Exception::Dom("DataError", r.value_as_string().clone()));+ }++ // 9. Let key be r.+ let key = r;++ // 10. Let r be the result of converting a value to a key with primaryKey. Rethrow any exceptions.+ r = convert_a_value_to_a_key(&realm_cx, primary_key_param, None)?;++ // 11. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if r.is_invalid() {+ return Err(Exception::Dom("DataError", r.value_as_string().clone()));+ }++ // 12. Let primaryKey be r.+ let primary_key = r;++ let position = self.position().expect("a cursor that got a value has a position");+ let object_store_position = self+ .object_store_position()+ .expect("a cursor of an index that got a value has an object store position");++ // 13. If key is less than this’s position and this’s direction is "next", throw a "DataError" DOMException.+ if Key::less_than(&key, &position) && self.direction == IDBCursorDirection::Next {+ return Err(data_error("Key is less than cursor's position"));+ }++ // 14. If key is greater than this’s position and this’s direction is "prev", throw a "DataError" DOMException.+ if Key::greater_than(&key, &position) && self.direction == IDBCursorDirection::Prev {+ return Err(data_error("Key is greater than cursor's position"));+ }++ // 15. If key is equal to this’s position and primaryKey is less than or equal to this’s object store position and this’s direction is "next", throw a "DataError" DOMException.+ if Key::equals(&key, &position)+ && (Key::less_than(&primary_key, &object_store_position)+ || Key::equals(&primary_key, &object_store_position))+ && self.direction == IDBCursorDirection::Next+ {+ return Err(data_error("Key is equal to cursor's position"));+ }++ // 16. If key is equal to this’s position and primaryKey is greater than or equal to this’s object store position and this’s direction is "prev", throw a "DataError" DOMException.+ if Key::equals(&key, &position)+ && (Key::greater_than(&primary_key, &object_store_position)+ || Key::equals(&primary_key, &object_store_position))+ && self.direction == IDBCursorDirection::Prev+ {+ return Err(data_error("Key is equal to cursor's position"));+ }++ // 17. Set this’s got value flag to false.+ self.got_value.set(false);++ // 18. Let request be this’s request.+ let request = self.request.get().expect("a cursor has a request");++ // 19. Set request’s processed flag to false.+ request.set_processed(false);++ // 20. Set request’s done flag to false.+ request.set_done(false);++ // 21. Let operation be an algorithm to run iterate a cursor with the current Realm record, this, key, and primaryKey.+ let operation = create_operation(+ vm,+ (self.this(), realm, NoCells((key, primary_key))),+ |vm, &(this, realm, ref keys)| {+ let cx = CallContext::new(vm, realm);+ let result = iterate_a_cursor(&cx, this, Some(keys.0.0.clone()), Some(keys.0.1.clone()), 1)?;+ Ok(idb_cursor_result(&cx, result))+ },+ );++ // 22. Run asynchronously execute a request with this’s source handle, operation, and request.+ asynchronously_execute_a_request(+ vm,+ self.source_handle.into(),+ operation,+ Some(AnyIDBRequest::IDBRequest(request)),+ );++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#cursor-effective-object-store+ pub(crate) fn effective_object_store(&self) -> ObjectStoreRef {+ match self.source_handle {+ CursorSourceHandle::ObjectStore(store) => {+ // If the source of a cursor is an object store, the effective object store of the cursor is that object store.+ store.store()+ }+ CursorSourceHandle::Index(index) => {+ // If the source of a cursor is an index, the effective object store of the cursor is that index’s referenced object store.+ index.object_store_handle().store()+ }+ }+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-update+ pub(crate) fn update(&self, cx: &mut CallContext, value: Value) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = self.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = self.transaction_object();++ // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while updating cursor",+ ));+ }++ // 3. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.+ if transaction.is_readonly() {+ return Err(Exception::Dom(+ "ReadOnlyError",+ Utf16String::from_utf8("Transaction is read-only while updating cursor"),+ ));+ }++ // 4. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.+ if self.is_source_or_object_store_deleted() {+ return Err(invalid_state_error("Source or its object store has been deleted"));+ }++ // 5. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.+ if !self.got_value.get() {+ return Err(invalid_state_error("Cursor is active or EOL while updating"));+ }++ // 6. If this’s key only flag is true, throw an "InvalidStateError" DOMException.+ if self.key_only {+ return Err(invalid_state_error("Cursor is key-only while updating"));+ }++ // 7. Let targetRealm be a user-agent defined Realm.+ // NOTE: this is 'realm' above++ // 8. Let clone be a clone of value in targetRealm during transaction. Rethrow any exceptions.+ let clone = clone_in_realm(&realm_cx, value, transaction)?;++ // 9. If this’s effective object store uses in-line keys, then:+ let effective_object_store = self.effective_object_store();+ if effective_object_store.uses_inline_keys() {+ // 1. Let kpk be the result of extracting a key from a value using a key path with clone and the key path of this’s effective object store. Rethrow any exceptions.+ let kpk = extract_a_key_from_a_value_using_a_key_path(+ &realm_cx,+ clone,+ effective_object_store.key_path().expect("the store uses in-line keys"),+ false,+ )?;++ // 2. If kpk is failure, invalid, or not equal to this’s effective key, throw a "DataError" DOMException.+ let Ok(kpk_value) = kpk else {+ return Err(data_error("Key path is invalid"));+ };++ if kpk_value.is_invalid() {+ return Err(data_error("Key path is invalid"));+ }++ if !Key::equals(+ &kpk_value,+ &self+ .effective_key()+ .expect("a cursor with a value has an effective key"),+ ) {+ return Err(data_error("Key path is not equal to effective key"));+ }+ }++ // 10. Let operation be an algorithm to run store a record into an object store with this’s effective object store, clone, this’s effective key, and false.+ let operation = create_operation(vm, (self.this(), realm, clone), |vm, &(this, realm, clone)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ let cx = CallContext::new(vm, realm);+ let optional_key = store_a_record_into_an_object_store(+ &cx,+ this.effective_object_store(),+ clone,+ Some(+ this.effective_key()+ .expect("a cursor with a value has an effective key"),+ ),+ false,+ )?;++ let Some(optional_key) = optional_key.filter(|key| !key.is_invalid()) else {+ return Ok(Value::UNDEFINED);+ };++ Ok(convert_a_key_to_a_value(&cx, &optional_key))+ })+ });++ // 11. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::Cursor(self.this()),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursor-delete+ pub(crate) fn delete(&self, cx: &mut CallContext) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();++ // 1. Let transaction be this’s transaction.+ let transaction = self.transaction_object();++ // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while deleting cursor",+ ));+ }++ // 3. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.+ if transaction.is_readonly() {+ return Err(Exception::Dom(+ "ReadOnlyError",+ Utf16String::from_utf8("Transaction is read-only while deleting cursor"),+ ));+ }++ // 4. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.+ if self.is_source_or_object_store_deleted() {+ return Err(invalid_state_error("Source or its object store has been deleted"));+ }++ // 5. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.+ if !self.got_value.get() {+ return Err(invalid_state_error("Cursor is active or EOL while deleting"));+ }++ // 6. If this’s key only flag is true, throw an "InvalidStateError" DOMException.+ if self.key_only {+ return Err(invalid_state_error("Cursor is key-only while deleting"));+ }++ // 7. Let operation be an algorithm to run delete records from an object store with this’s effective object store and this’s effective key.+ let operation = create_operation(vm, self.this(), |vm, &this| {+ let effective_key = this+ .effective_key()+ .expect("a cursor with a value has an effective key");+ let range = IDBKeyRange::create(vm, Some(effective_key.clone()), Some(effective_key), false, false);+ Ok(delete_records_from_an_object_store(+ vm,+ this.effective_object_store(),+ &range,+ ))+ });++ // 8. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::Cursor(self.this()),+ operation,+ None,+ )))+ }+}++#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum AnyIDBCursor {+ IDBCursor(Ref<IDBCursor>),+ IDBCursorWithValue(Ref<IDBCursorWithValue>),+}++impl Deref for AnyIDBCursor {+ type Target = IDBCursor;++ fn deref(&self) -> &IDBCursor {+ match self {+ Self::IDBCursor(cursor) => cursor,+ Self::IDBCursorWithValue(cursor) => {+ let cursor: &IDBCursorWithValue = cursor;+ cursor.parent()+ }+ }+ }+}++impl ToJs for AnyIDBCursor {+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {+ match self {+ Self::IDBCursor(cursor) => cursor.to_js(cx),+ Self::IDBCursorWithValue(cursor) => cursor.to_js(cx),+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_cursor_with_value.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_cursor_with_value.rsnew file mode 100644index 00000000000..271ad10b2ca--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_cursor_with_value.rs@@ -0,0 +1,41 @@+/*+ * Copyright (c) 2024, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBCursorWithValue, https://w3c.github.io/IndexedDB/#idbcursorwithvalue++use libjs_rust::api::{Trace, Value};++use crate::bindings::interface::{Inherits, Wrappable};+use crate::bindings::{CallContext, WebIdlResult};+use crate::indexed_db::idb_cursor::IDBCursor;++// https://w3c.github.io/IndexedDB/#idbcursorwithvalue+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBCursorWithValue {+ cursor: IDBCursor,+}++impl Inherits<IDBCursor> for IDBCursorWithValue {+ fn parent(&self) -> &IDBCursor {+ &self.cursor+ }+}++impl Wrappable for IDBCursorWithValue {}++impl IDBCursorWithValue {+ pub(crate) fn new(cursor: IDBCursor) -> Self {+ Self { cursor }+ }++ // https://w3c.github.io/IndexedDB/#dom-idbcursorwithvalue-value+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<Value> {+ // The value getter steps are to return this’s current value.+ Ok(self.cursor.current_value().unwrap_or(Value::UNDEFINED))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_database.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_database.rsnew file mode 100644index 00000000000..e0626353b20--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_database.rs@@ -0,0 +1,558 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBDatabase, https://w3c.github.io/IndexedDB/#database-interface++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Realm, Trace, Vm};++use crate::bindings::conversions::{CppInterface, DOMStringOrDOMStringSequence};+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::indexed_db::cpp::{enqueue_post_gc_task, main_thread_event_loop};+use crate::indexed_db::idb_object_store::{+ IDBObjectStore, constraint_error, invalid_state_error, not_found_error, transaction_inactive_error,+};+use crate::indexed_db::idb_transaction::{IDBTransaction, IDBTransactionMode, TransactionState};+use crate::indexed_db::internal::algorithms::{+ KeyPath, close_a_database_connection, commit_a_transaction, create_a_sorted_name_list, is_valid_key_path,+ queue_a_database_task,+};+use crate::indexed_db::internal::database::{Database, DatabaseRef};+use crate::indexed_db::internal::function::{Function, call_function, create_function};+use crate::indexed_db::internal::object_store::{ObjectStore, ObjectStoreRef};++/// The enumeration IDBTransactionDurability of IndexedDB/IDBDatabase.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum IDBTransactionDurability {+ Default,+ Strict,+ Relaxed,+}++/// The dictionary IDBTransactionOptions of IndexedDB/IDBDatabase.idl.+pub(crate) struct IDBTransactionOptions {+ pub(crate) durability: IDBTransactionDurability,+}++/// The dictionary IDBObjectStoreParameters of IndexedDB/IDBDatabase.idl.+pub(crate) struct IDBObjectStoreParameters {+ pub(crate) auto_increment: bool,+ pub(crate) key_path: Option<DOMStringOrDOMStringSequence>,+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ConnectionState {+ Open,+ Closed,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct PendingTransactionWait {+ transactions: Vec<Ref<IDBTransaction>>,+ callback: Function,+}++// https://w3c.github.io/IndexedDB/#IDBDatabase-interface+// https://w3c.github.io/IndexedDB/#database-connection+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBDatabase {+ event_target: CppEventTarget,++ pending_transaction_waits: GcRefCell<Vec<PendingTransactionWait>>,++ version: Cell<u64>,+ name: Utf16String,++ // Each connection has a close pending flag which is initially false.+ close_pending: Cell<bool>,++ // When a connection is initially created it is in an opened state.+ #[gc(untraced)]+ state: Cell<ConnectionState>,++ // A connection has an object store set, which is initialized to the set of object stores in the associated database when the connection is created.+ // The contents of the set will remain constant except when an upgrade transaction is live.+ object_store_set: GcRefCell<Vec<ObjectStoreRef>>,++ // NOTE: There is an associated database in the spec, but there is no mention where it is assigned, nor where its from+ // So we stash the one we have when opening a connection.+ associated_database: DatabaseRef,+ realm: Gc<Realm>,++ // NOTE: We need to keep track of what transactions were created by this connection+ transactions: GcRefCell<Vec<Ref<IDBTransaction>>>,+}++impl Wrappable for IDBDatabase {+ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ object.associated_database.dissociate(object);+ enqueue_post_gc_task(object.associated_database);+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for IDBDatabase {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl IDBDatabase {+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>, db: DatabaseRef) -> Ref<IDBDatabase> {+ let object_stores = db.object_stores(vm);+ let connection = allocate(vm, |_| IDBDatabase {+ event_target: CppEventTarget::new(),+ pending_transaction_waits: GcRefCell::new(Vec::new()),+ version: Cell::new(0),+ name: db.name(),+ close_pending: Cell::new(false),+ state: Cell::new(ConnectionState::Open),+ object_store_set: GcRefCell::new(object_stores.to_vec()),+ associated_database: db,+ realm,+ transactions: GcRefCell::new(Vec::new()),+ });+ connection.event_target.set_owner(connection);+ db.associate(vm, connection);+ connection+ }++ pub(crate) fn event_target(&self) -> &CppEventTarget {+ &self.event_target+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.realm+ }++ pub(crate) fn set_version(&self, version: u64) {+ self.version.set(version);+ }++ pub(crate) fn set_close_pending(&self, close_pending: bool) {+ self.close_pending.set(close_pending);+ }++ pub(crate) fn set_state(&self, state: ConnectionState) {+ self.state.set(state);+ }++ pub(crate) fn close_pending(&self) -> bool {+ self.close_pending.get()+ }++ pub(crate) fn state(&self) -> ConnectionState {+ self.state.get()+ }++ pub(crate) fn associated_database(&self) -> DatabaseRef {+ self.associated_database+ }++ pub(crate) fn object_store_set<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, ObjectStoreRef> {+ let object_store_set = MarkedVec::new(vm);+ object_store_set.extend_from_slice(&self.object_store_set.borrow());+ object_store_set+ }++ pub(crate) fn add_to_object_store_set(&self, vm: &Vm, object_store: ObjectStoreRef) {+ self.object_store_set.borrow_mut(vm).push(object_store);+ }++ pub(crate) fn remove_from_object_store_set(&self, vm: &Vm, object_store: ObjectStoreRef) {+ let mut object_store_set = self.object_store_set.borrow_mut(vm);+ if let Some(position) = object_store_set.iter().position(|entry| *entry == object_store) {+ object_store_set.remove(position);+ }+ }++ pub(crate) fn transactions<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Ref<IDBTransaction>> {+ let transactions = MarkedVec::new(vm);+ transactions.extend_from_slice(&self.transactions.borrow());+ transactions+ }++ pub(crate) fn add_transaction(&self, vm: &Vm, transaction: Ref<IDBTransaction>) {+ self.transactions.borrow_mut(vm).push(transaction);+ }++ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.name.clone())+ }++ pub(crate) fn version(&self, _: &mut CallContext) -> WebIdlResult<u64> {+ Ok(self.version.get())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbdatabase-close+ pub(crate) fn close(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. Run close a database connection with this connection.+ close_a_database_connection(cx.vm(), *this, None, false);+ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore+ pub(crate) fn create_object_store(+ this: &Ref<Self>,+ cx: &mut CallContext,+ name: Utf16String,+ options: IDBObjectStoreParameters,+ ) -> WebIdlResult<Ref<IDBObjectStore>> {+ let vm = cx.vm();++ // 1. Let database be this's associated database.+ let database = this.associated_database;++ // 2. Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise.+ let Some(transaction) = database.upgrade_transaction() else {+ return Err(invalid_state_error("Upgrade transaction is null"));+ };++ // 3. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while creating object store",+ ));+ }++ // 4. Let keyPath be options’s keyPath member if it is not undefined or null, or null otherwise.+ let key_path = options.key_path.map(|key_path| match key_path {+ DOMStringOrDOMStringSequence::DOMString(value) => KeyPath::String(value),+ DOMStringOrDOMStringSequence::Sequence(values) => KeyPath::Sequence(values),+ });++ // 5. If keyPath is not null and is not a valid key path, throw a "SyntaxError" DOMException.+ if let Some(key_path) = &key_path+ && !is_valid_key_path(key_path)+ {+ return Err(Exception::Dom(+ "SyntaxError",+ Utf16String::from_utf8("Invalid key path"),+ ));+ }++ // 6. If an object store named name already exists in database throw a "ConstraintError" DOMException.+ if database.object_store_with_name(&name).is_some() {+ return Err(constraint_error("Object store already exists"));+ }++ // 7. Let autoIncrement be options’s autoIncrement member.+ let auto_increment = options.auto_increment;++ let is_empty_key_path_or_sequence = match &key_path {+ Some(KeyPath::String(value)) => value.is_empty(),+ Some(KeyPath::Sequence(_)) => true,+ None => false,+ };++ // 8. If autoIncrement is true and keyPath is an empty string or any sequence (empty or otherwise), throw an "InvalidAccessError" DOMException.+ if auto_increment && is_empty_key_path_or_sequence {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_utf8("Auto increment is true and key path is empty or sequence"),+ ));+ }++ // 9. Let store be a new object store in database.+ // Set the created object store's name to name.+ // If autoIncrement is true, then the created object store uses a key generator.+ // If keyPath is not null, set the created object store's key path to keyPath.+ let object_store = ObjectStore::create(vm, database, name, auto_increment, key_path);++ // AD-HOC: Add newly created object store to this's object store set.+ this.add_to_object_store_set(vm, object_store);++ // AD-HOC: Set up a mutation log for this store and log its creation for potential revert on abort.+ transaction.set_up_mutation_log_for_new_store(vm, object_store);++ // 10. Return a new object store handle associated with store and transaction.+ transaction.add_to_scope(vm, object_store);+ Ok(IDBTransaction::get_or_create_object_store_handle(+ transaction,+ vm,+ object_store,+ ))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbdatabase-objectstorenames+ pub(crate) fn object_store_names(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // 1. Let names be a list of the names of the object stores in this's object store set.+ let names = self+ .object_store_set+ .borrow()+ .iter()+ .map(|object_store| object_store.name())+ .collect();++ // 2. Return the result (a DOMStringList) of creating a sorted name list with names.+ Ok(create_a_sorted_name_list(cx, names))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbdatabase-deleteobjectstore+ pub(crate) fn delete_object_store(&self, cx: &mut CallContext, name: Utf16String) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let database be this's associated database.+ let database = self.associated_database;++ // 2. Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise.+ let Some(transaction) = database.upgrade_transaction() else {+ return Err(invalid_state_error("Upgrade transaction is null"));+ };++ // 3. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while deleting object store",+ ));+ }++ // 4. Let store be the object store named name in database, or throw a "NotFoundError" DOMException if none.+ let Some(store) = database.object_store_with_name(&name) else {+ return Err(not_found_error("Object store not found while trying to delete"));+ };++ // 5. Remove store from this's object store set.+ self.remove_from_object_store_set(vm, store);++ // NB: Upgrade transactions' scope is always the entire database. Since we removed this store from the database,+ // it no longer belongs in the scope.+ transaction.remove_from_scope(vm, store);++ // 6. If there is an object store handle associated with store and transaction, remove all entries from its index set.+ if let Some(handle) = transaction.object_store_handle_for(store) {+ handle.index_set_clear(vm);+ }++ // AD-HOC: Mark the store and its indexes as deleted so that stale handles throw InvalidStateError.+ store.set_deleted(true);+ for index in store.indexes(vm).values().iter() {+ index.set_deleted(true);+ }++ // AD-HOC: Log the deletion for potential revert on abort.+ store+ .mutation_log()+ .expect("an upgrade transaction logs the mutations of its stores")+ .note_object_store_deleted(vm);++ // 7. Destroy store.+ Database::remove_object_store(database, vm, store);++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbdatabase-transaction+ pub(crate) fn transaction(+ this: &Ref<Self>,+ cx: &mut CallContext,+ store_names: DOMStringOrDOMStringSequence,+ mode: IDBTransactionMode,+ options: IDBTransactionOptions,+ ) -> WebIdlResult<Ref<IDBTransaction>> {+ let vm = cx.vm();++ // 1. If a live upgrade transaction is associated with the connection, throw an "InvalidStateError" DOMException.+ let database = this.associated_database;+ if database.upgrade_transaction().is_some() {+ return Err(invalid_state_error("Upgrade transaction is live"));+ }++ // 2. If this's close pending flag is true, then throw an "InvalidStateError" DOMException.+ if this.close_pending() {+ return Err(invalid_state_error("Close pending"));+ }++ // 3. Let scope be the set of unique strings in storeNames if it is a sequence, or a set containing one string equal to storeNames otherwise.+ let mut scope: Vec<Utf16String> = Vec::new();+ match store_names {+ DOMStringOrDOMStringSequence::Sequence(store_names) => {+ for store_name in store_names {+ if !scope.contains(&store_name) {+ scope.push(store_name);+ }+ }+ }+ DOMStringOrDOMStringSequence::DOMString(store_name) => {+ scope.push(store_name);+ }+ }++ // 4. If any string in scope is not the name of an object store in the connected database, throw a "NotFoundError" DOMException.+ for store_name in &scope {+ if database.object_store_with_name(store_name).is_none() {+ return Err(not_found_error(+ "Provided object store names does not exist in database",+ ));+ }+ }++ // 5. If scope is empty, throw an "InvalidAccessError" DOMException.+ if scope.is_empty() {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_utf8("Scope is empty"),+ ));+ }++ // 6. If mode is not "readonly" or "readwrite", throw a TypeError.+ if mode != IDBTransactionMode::Readonly && mode != IDBTransactionMode::Readwrite {+ return Err(Exception::type_error("Invalid transaction mode"));+ }++ // 7. Let transaction be a newly created transaction with this connection, mode, options’ durability member, and the set of object stores named in scope.+ let scope_stores = MarkedVec::new(vm);+ for store_name in &scope {+ let store = database+ .object_store_with_name(store_name)+ .expect("every name in scope is an object store");+ scope_stores.push(store);+ }++ let transaction = IDBTransaction::create(vm, *this, mode, options.durability, &scope_stores.values());++ // 8. Set transaction’s cleanup event loop to the current event loop.+ transaction.set_cleanup_event_loop(vm, Some(main_thread_event_loop()));++ Self::block_on_conflicting_transactions(*this, vm, transaction);++ // 9. Return an IDBTransaction object representing transaction.+ Ok(transaction)+ }++ pub(crate) fn wait_for_transactions_to_finish(+ &self,+ vm: &Vm,+ transactions: &[Ref<IDBTransaction>],+ on_complete: Function,+ ) {+ let all_finished = transactions.iter().all(|entry| entry.is_finished());++ if all_finished {+ queue_a_database_task(vm, on_complete);+ return;+ }++ self.pending_transaction_waits+ .borrow_mut(vm)+ .push(PendingTransactionWait {+ transactions: transactions.to_vec(),+ callback: on_complete,+ });+ }++ pub(crate) fn check_pending_transaction_waits(&self, vm: &Vm) {+ let mut i = 0;+ loop {+ let callback = {+ let mut waits = self.pending_transaction_waits.borrow_mut(vm);+ if i >= waits.len() {+ break;+ }+ let all_finished = waits[i]+ .transactions+ .iter()+ .all(|transaction| transaction.is_finished());+ if !all_finished {+ i += 1;+ continue;+ }+ waits.remove(i).callback+ };+ call_function(vm, callback);+ }+ }++ // https://w3c.github.io/IndexedDB/#transaction-scheduling+ pub(crate) fn block_on_conflicting_transactions(this: Ref<Self>, vm: &Vm, transaction: Ref<IDBTransaction>) {+ // The following constraints define when a transaction can be started:++ // - A read-only transactions tx can start when there are no read/write transactions which:+ // - A read/write transaction tx can start when there are no transactions which:++ let blocking = MarkedVec::new(vm);+ let transaction_scope = transaction.scope(vm);+ for other in this.transactions(vm).values().iter() {+ let other = *other;++ // - Were created before tx; and+ if other == transaction {+ break;+ }++ // NB: According to the above conditions, we only block on transactions if one is read/write.+ if transaction.is_readonly() && other.is_readonly() {+ continue;+ }++ // - have overlapping scopes with tx; and+ let other_scope = other.scope(vm);+ let have_overlapping_scopes = transaction_scope+ .values()+ .iter()+ .any(|store| other_scope.values().contains(store));+ if !have_overlapping_scopes {+ continue;+ }++ // - are not finished.+ if other.is_finished() {+ continue;+ }++ blocking.push(other);+ }++ if blocking.is_empty() {+ if !transaction.is_readonly() {+ transaction.set_up_mutation_logs(vm);+ }+ return;+ }++ transaction.request_list().block_execution();+ this.wait_for_transactions_to_finish(+ vm,+ &blocking.values(),+ create_function(vm, transaction, |vm, &transaction, ()| {+ assert!(transaction.state() != TransactionState::Active);+ if transaction.request_list().is_empty() {+ // https://w3c.github.io/IndexedDB/#transaction-commit+ // The implementation must attempt to commit an inactive transaction when all requests placed+ // against the transaction have completed and their returned results handled, no new requests have+ // been placed against the transaction, and the transaction has not been aborted++ // If we were blocked, that means that the JS task has had its chance to make requests. If the request+ // list is empty, then the cleanup in the microtask checkpoint already ran, but skipped auto-committing.+ // We have to do it here instead.++ // FIXME: Update if this becomes explicit:+ // https://github.com/w3c/IndexedDB/issues/489#issuecomment-3994928473+ commit_a_transaction(vm, transaction);+ return;+ }+ if !transaction.is_readonly() {+ transaction.set_up_mutation_logs(vm);+ }+ transaction.request_list().unblock_execution(vm);+ }),+ );+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_factory.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_factory.rsnew file mode 100644index 00000000000..c048eb85b3c--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_factory.rs@@ -0,0 +1,354 @@+/*+ * Copyright (c) 2024, Shannon Booth <[email protected]>+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBFactory, https://w3c.github.io/IndexedDB/#factory-interface++use ak::Utf16String;+use libjs_rust::api::{Array, Gc, Must, Object, PrimitiveString, PropertyKey, Realm, Trace, Value, Vm};++use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{WebIdlPromise, create_promise, reject_promise, resolve_promise};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::indexed_db::cpp::{obtain_a_storage_key, run_in_parallel};+use crate::indexed_db::idb_open_db_request::IDBOpenDBRequest;+use crate::indexed_db::idb_request::AnyIDBRequest;+use crate::indexed_db::internal::algorithms::{+ DeleteResult, OpenResult, convert_a_value_to_a_key, delete_a_database, fire_a_version_change_event,+ open_a_database_connection, queue_a_database_task, set_idb_request_result,+};+use crate::indexed_db::internal::database::{Database, DatabaseRef};+use crate::indexed_db::internal::function::{NoCells, create_function, create_function_with};+use crate::indexed_db::internal::key::Key;++/// The dictionary IDBDatabaseInfo of IndexedDB/IDBFactory.idl.+pub(crate) struct IDBDatabaseInfo {+ pub(crate) name: Option<Utf16String>,+ pub(crate) version: Option<u64>,+}++// https://w3c.github.io/IndexedDB/#idbfactory+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBFactory {+ realm: Gc<Realm>,+}++impl Wrappable for IDBFactory {+ fn relevant_realm(&self, _: &Vm) -> Option<Gc<Realm>> {+ Some(self.realm)+ }+}++impl IDBFactory {+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<IDBFactory> {+ allocate(vm, |_| IDBFactory { realm })+ }++ // https://w3c.github.io/IndexedDB/#dom-idbfactory-open+ pub(crate) fn open(+ &self,+ cx: &mut CallContext,+ name: Utf16String,+ version: Option<u64>,+ ) -> WebIdlResult<Ref<IDBOpenDBRequest>> {+ let vm = cx.vm();+ let realm = self.realm;++ // 1. If version is 0 (zero), throw a TypeError.+ if version == Some(0) {+ return Err(Exception::type_error("The version provided must not be 0"));+ }++ // 2. Let environment be this's relevant settings object.+ // 3. Let storageKey be the result of running obtain a storage key given environment.+ // If failure is returned, then throw a "SecurityError" DOMException and abort these steps.+ let Some(storage_key) = obtain_a_storage_key(realm) else {+ return Err(Exception::Dom(+ "SecurityError",+ Utf16String::from_utf8("Failed to obtain a storage key"),+ ));+ };++ // 4. Let request be a new open request.+ let request = IDBOpenDBRequest::create(vm, realm);++ // 5. Run these steps in parallel:+ // NB: We could defer these steps, but it wouldn't be observable anyway, since open_a_database_connection() will+ // put this work into a queue and then process it later in the event loop regardless.++ // 1. Let result be the result of opening a database connection, with storageKey, name, version if given and undefined otherwise, and request.+ open_a_database_connection(+ vm,+ realm,+ storage_key,+ name,+ version,+ AnyIDBRequest::IDBOpenDBRequest(request),+ create_function_with(vm, (realm, request), |vm, &(realm, request), result: OpenResult| {+ // 2. Set request’s processed flag to true.+ let request = AnyIDBRequest::IDBOpenDBRequest(request);+ request.set_processed(true);++ // 3. Queue a database task to run these steps:+ queue_a_database_task(+ vm,+ create_function(vm, (realm, request, result), |vm, &(realm, request, ref result), ()| {+ match result {+ // 1. If result is an error, then:+ Err(error) => {+ // 1. Set request’s result to undefined.+ request.set_result(Value::UNDEFINED);++ // 2. Set request’s error to result.+ request.set_error(vm, Some(error.clone()));++ // 3. Set request’s done flag to true.+ request.set_done(true);++ // 4. Fire an event named error at request with its bubbles and cancelable attributes initialized to true.+ request.event_target().dispatch_event(&CppEvent::create(+ request.realm(),+ "error",+ true,+ true,+ false,+ ));+ }+ // 2. Otherwise:+ Ok(connection) => {+ // 1. Set request’s result to result.+ set_idb_request_result(vm, realm, request, *connection);++ // 2. Set request’s done flag to true.+ request.set_done(true);++ // 3. Fire an event named success at request.+ request.event_target().dispatch_event(&CppEvent::create(+ request.realm(),+ "success",+ false,+ false,+ false,+ ));+ }+ }+ }),+ );+ }),+ );++ // 6. Return a new IDBOpenDBRequest object for request.+ Ok(request)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp+ pub(crate) fn cmp(&self, cx: &mut CallContext, first: Value, second: Value) -> WebIdlResult<i16> {+ let cx = CallContext::new(cx.vm(), self.realm);++ // 1. Let a be the result of converting a value to a key with first. Rethrow any exceptions.+ let a = convert_a_value_to_a_key(&cx, first, None)?;++ // 2. If a is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if a.is_invalid() {+ return Err(Exception::Dom(+ "DataError",+ Utf16String::from_utf8("Failed to convert a value to a key"),+ ));+ }++ // 3. Let b be the result of converting a value to a key with second. Rethrow any exceptions.+ let b = convert_a_value_to_a_key(&cx, second, None)?;++ // 4. If b is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if b.is_invalid() {+ return Err(Exception::Dom(+ "DataError",+ Utf16String::from_utf8("Failed to convert a value to a key"),+ ));+ }++ // 5. Return the results of comparing two keys with a and b.+ Ok(i16::from(Key::compare_two_keys(&a, &b)))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase+ pub(crate) fn delete_database(+ &self,+ cx: &mut CallContext,+ name: Utf16String,+ ) -> WebIdlResult<Ref<IDBOpenDBRequest>> {+ let vm = cx.vm();+ let realm = self.realm;++ // 1. Let environment be this's relevant settings object.+ // 2. Let storageKey be the result of running obtain a storage key given environment.+ // If failure is returned, then throw a "SecurityError" DOMException and abort these steps.+ let Some(storage_key) = obtain_a_storage_key(realm) else {+ return Err(Exception::Dom(+ "SecurityError",+ Utf16String::from_utf8("Failed to obtain a storage key"),+ ));+ };++ // 3. Let request be a new open request.+ let request = IDBOpenDBRequest::create(vm, realm);++ // 4. Run these steps in parallel:+ // NB: We could defer these steps, but it wouldn't be observable anyway, since delete_a_database() will+ // put this work into a queue and then process it later in the event loop regardless.++ // 1. Let result be the result of deleting a database, with storageKey, name, and request.+ delete_a_database(+ vm,+ realm,+ storage_key,+ name,+ AnyIDBRequest::IDBOpenDBRequest(request),+ create_function_with(vm, (realm, request), |vm, &(realm, request), result: DeleteResult| {+ // 2. Set request’s processed flag to true.+ let request = AnyIDBRequest::IDBOpenDBRequest(request);+ request.set_processed(true);++ // 3. Queue a database task to run these steps:+ queue_a_database_task(+ vm,+ create_function(vm, (realm, request, result), |vm, &(realm, request, ref result), ()| {+ match result {+ // 1. If result is an error, set request’s error to result, set request’s done flag to true, and fire an event+ // named error at request with its bubbles and cancelable attributes initialized to true.+ Err(error) => {+ request.set_error(vm, Some(error.clone()));+ request.set_done(true);+ request.event_target().dispatch_event(&CppEvent::create(+ request.realm(),+ "error",+ true,+ true,+ false,+ ));+ }+ // 2. Otherwise, set request’s result to undefined, set request’s done flag to true, and fire a version change+ // event named success at request with result and null.+ Ok(value) => {+ request.set_result(Value::UNDEFINED);+ request.set_done(true);+ fire_a_version_change_event(vm, realm, "success", request.event_target(), *value, None);+ }+ }+ }),+ );+ }),+ );++ // 5. Return a new IDBOpenDBRequest object for request.+ Ok(request)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases+ pub(crate) fn databases(&self, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ let vm = cx.vm();+ let realm = self.realm;+ let promise = create_promise(vm, realm);++ // 1. Let environment be this's relevant settings object.+ // 2. Let storageKey be the result of running obtain a storage key given environment.+ // If failure is returned, then return a promise rejected with a "SecurityError" DOMException+ let Some(storage_key) = obtain_a_storage_key(realm) else {+ let cx = CallContext::new(vm, realm);+ let error = Exception::Dom(+ "SecurityError",+ Utf16String::from_utf8("Failed to obtain a storage key"),+ )+ .throw(&cx);+ reject_promise(vm, promise, error.value());+ return Ok(promise);+ };++ // 3. Let p be a new promise.+ // NB: p is the promise created above.++ // 4. Run these steps in parallel:+ run_in_parallel(+ vm,+ create_function(+ vm,+ (realm, NoCells(storage_key), promise),+ |vm, &(realm, ref storage_key, promise), ()| {+ crate::bindings::interface::with_temporary_execution_context_and_callbacks(realm, || {+ // 1. Let databases be the set of databases in storageKey.+ // If this cannot be determined for any reason, then queue a database task to reject p with an appropriate error (e.g. an "UnknownError" DOMException) and terminate these steps.+ let databases = Database::for_key(vm, &storage_key.0);++ // 2. Let result be a new list.+ // 3. For each db of databases:+ // 1. If db's version is 0, then continue.+ // 2. Let info be a new IDBDatabaseInfo dictionary.+ // 3. Set info's name dictionary member to db's name.+ // 4. Set info's version dictionary member to db's version.+ // 5. Append info to result.+ // 4. Queue a database task to resolve p with result.+ // AD-HOC: p is resolved directly in a deferred invocation, not in a database task.+ resolve_database_info_list_promise(vm, realm, promise, &databases.values());+ });+ },+ ),+ );++ // 5. Return p.+ Ok(promise)+ }+}++// NB: The generated conversion of IDBDatabaseInfo is only built with the bindings, so the dictionaries are built here.+fn resolve_database_info_list_promise(vm: &Vm, realm: Gc<Realm>, promise: WebIdlPromise, databases: &[DatabaseRef]) {+ let result = Array::create(vm, realm, 0, None).must();++ let mut result_index: u64 = 0;+ for db in databases {+ // INTEROP: A database's version is not reported until its upgrade transaction commits, so that databases()+ // does not pick up changes that have not been committed.+ let mut version = db.version();+ if let Some(upgrade_transaction) = db.upgrade_transaction() {+ version = upgrade_transaction.original_version();+ }++ if version == 0 {+ continue;+ }++ let info = Object::create(vm, realm, Some(realm.intrinsics().object_prototype(vm)));+ info.create_data_property(+ vm,+ &PropertyKey::from_utf8("name"),+ Value::from_string(PrimitiveString::create(vm, db.name())),+ None,+ None,+ )+ .must();+ #[allow(+ clippy::cast_precision_loss,+ reason = "the C++ converted the version to a double as well"+ )]+ info.create_data_property(+ vm,+ &PropertyKey::from_utf8("version"),+ Value::from_f64(version as f64),+ None,+ None,+ )+ .must();+ result+ .create_data_property_or_throw(vm, &PropertyKey::from_number(result_index), Value::from_object(info))+ .must();+ result_index += 1;+ }++ resolve_promise(vm, promise, Value::from_object(result));+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_index.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_index.rsnew file mode 100644index 00000000000..fb8310a4a70--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_index.rs@@ -0,0 +1,510 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBIndex, https://w3c.github.io/IndexedDB/#index-interface++use core::cell::RefCell;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, Object, Realm, Trace, Value, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::indexed_db::idb_cursor::{CursorSourceHandle, IDBCursor, IDBCursorDirection};+use crate::indexed_db::idb_object_store::{+ IDBGetAllOptions, IDBObjectStore, constraint_error, idb_cursor_result, invalid_state_error, request_of,+ transaction_inactive_error,+};+use crate::indexed_db::idb_request::{IDBRequest, IDBRequestSource};+use crate::indexed_db::idb_transaction::IDBTransaction;+use crate::indexed_db::internal::algorithms::{+ KeyPath, RecordKind, RecordSource, asynchronously_execute_a_request, convert_a_key_path_to_a_value,+ convert_a_value_to_a_key_range, count_the_records_in_a_range, create_a_request_to_retrieve_multiple_items,+ create_a_request_to_retrieve_multiple_items_with_options, iterate_a_cursor,+ retrieve_a_referenced_value_from_an_index, retrieve_a_value_from_an_index,+};+use crate::indexed_db::internal::function::create_operation;+use crate::indexed_db::internal::index::{Index, IndexRef};++// https://w3c.github.io/IndexedDB/#index-interface+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBIndex {+ // An index handle has an associated index and an associated object store handle.+ index: IndexRef,+ object_store_handle: Ref<IDBObjectStore>,++ // An index handle has a name, which is initialized to the name of the associated index when the index handle is created.+ #[gc(untraced)]+ name: RefCell<Utf16String>,++ // NB: The keyPath getter returns the same Array every time it is inspected in the same realm.+ key_path_arrays: GcRefCell<Vec<(Gc<Object>, Gc<Object>)>>,+}++impl Wrappable for IDBIndex {}++impl IDBIndex {+ pub(crate) fn create(vm: &Vm, index: IndexRef, object_store: Ref<IDBObjectStore>) -> Ref<IDBIndex> {+ let handle = allocate(vm, |_| IDBIndex {+ index,+ object_store_handle: object_store,+ name: RefCell::new(index.name()),+ key_path_arrays: GcRefCell::new(Vec::new()),+ });+ object_store.transaction_object().register_index_handle(vm, handle);+ handle+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.object_store_handle.realm()+ }++ // The transaction of an index handle is the transaction of its associated object store handle.+ pub(crate) fn transaction_object(&self) -> Ref<IDBTransaction> {+ self.object_store_handle.transaction_object()+ }++ pub(crate) fn index(&self) -> IndexRef {+ self.index+ }++ pub(crate) fn object_store_handle(&self) -> Ref<IDBObjectStore> {+ self.object_store_handle+ }++ pub(crate) fn update_name(&self) {+ *self.name.borrow_mut() = self.index.name();+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-name+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ // The name getter steps are to return this’s name.+ Ok(self.name.borrow().clone())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-name+ pub(crate) fn set_name(&self, cx: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let name be the given value.+ let name = &value;++ // 2. Let transaction be this’s transaction.+ let transaction = self.transaction_object();++ // 3. Let index be this’s index.+ let index = self.index;++ // 4. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.+ if !transaction.is_upgrade_transaction() {+ return Err(invalid_state_error("Transaction is not an upgrade transaction"));+ }++ // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while updating index name",+ ));+ }++ // 6. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.+ if index.is_deleted() || index.object_store().is_deleted() {+ return Err(invalid_state_error("Index or its object store has been deleted"));+ }++ // 7. If index’s name is equal to name, terminate these steps.+ if index.name() == *name {+ return Ok(());+ }++ // 8. If an index named name already exists in index’s object store, throw a "ConstraintError" DOMException.+ if index.object_store().index_set_get(name).is_some() {+ return Err(constraint_error("An index with the given name already exists"));+ }++ // AD-HOC: Log the rename for potential revert on abort.+ self.object_store_handle+ .store()+ .mutation_log()+ .expect("an upgrade transaction logs the mutations of its stores")+ .note_index_renamed(vm, index, index.name());++ // 9. Set index’s name to name.+ Index::set_name(index, vm, name.clone());++ // NOTE: Update the key in the map so it still matches the name+ self.object_store_handle+ .rename_index_set_entry(vm, &self.name.borrow(), name.clone());++ // 10. Set this’s name to name.+ *self.name.borrow_mut() = name.clone();++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-objectstore+ pub(crate) fn object_store(&self, _: &mut CallContext) -> WebIdlResult<Ref<IDBObjectStore>> {+ // The objectStore getter steps are to return this’s object store handle.+ Ok(self.object_store_handle)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-keypath+ pub(crate) fn key_path(&self) -> &KeyPath {+ self.index.key_path()+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-keypath+ pub(crate) fn key_path_value(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The keyPath getter steps are to return this’s index’s key path. The key path is converted as a DOMString (if a+ // string) or a sequence<DOMString> (if a list of strings), per [WEBIDL].+ // NOTE: The returned value is not the same instance that was used when the index was created. However, if this+ // attribute returns an object (specifically an Array), it returns the same object instance every time it is+ // inspected. Changing the properties of the object has no effect on the index.+ let global_object = cx.realm().global_object();+ if let Some((_, array)) = self+ .key_path_arrays+ .borrow()+ .iter()+ .find(|(global, _)| *global == global_object)+ {+ return Ok(Value::from_object(*array));+ }++ let value = convert_a_key_path_to_a_value(cx, self.key_path());+ if value.is_object() {+ self.key_path_arrays+ .borrow_mut(cx.vm())+ .push((global_object, value.as_object()));+ }+ Ok(value)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-multientry+ pub(crate) fn multi_entry(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The multiEntry getter steps are to return this’s index’s multiEntry flag.+ Ok(self.index.multi_entry())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-unique+ pub(crate) fn unique(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The unique getter steps are to return this’s index’s unique flag.+ Ok(self.index.unique())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-opencursor+ pub(crate) fn open_cursor(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query: Option<Value>,+ direction: IDBCursorDirection,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction_object();++ // 2. Let index be this’s index.+ let index = this.index;++ // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.+ if index.is_deleted() || index.object_store().is_deleted() {+ return Err(invalid_state_error("Index or its object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while opening cursor",+ ));+ }++ // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, query, false)?;++ // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction, got value flag set to false, undefined key and value, range set to range, and key only flag set to false.+ let cursor = IDBCursor::create(+ vm,+ CursorSourceHandle::Index(*this),+ None,+ direction,+ false,+ None,+ None,+ range,+ false,+ );++ // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.+ let operation = create_operation(vm, (realm, cursor), |vm, &(realm, cursor)| {+ let cx = CallContext::new(vm, realm);+ let result = iterate_a_cursor(&cx, cursor, None, None, 1)?;+ Ok(idb_cursor_result(&cx, result))+ });++ // 8. Let request be the result of running asynchronously execute a request with this and operation.+ let request = request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::Index(*this),+ operation,+ None,+ ));++ // 9. Set cursor’s request to request.+ cursor.set_request(Some(request));++ // 10. Return request.+ Ok(request)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-get+ pub(crate) fn get(this: &Ref<Self>, cx: &mut CallContext, query: Value) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction_object();++ // 2. Let index be this’s index.+ let index = this.index;++ // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.+ if index.is_deleted() || index.object_store().is_deleted() {+ return Err(invalid_state_error("Index or its object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error("Transaction is not active while getting"));+ }++ // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, Some(query), true)?;++ // 6. Let operation be an algorithm to run retrieve a referenced value from an index with the current Realm record, index, and range.+ let operation = create_operation(vm, (realm, index, range), |vm, &(realm, index, range)| {+ retrieve_a_referenced_value_from_an_index(&CallContext::new(vm, realm), index, &range)+ });++ // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::Index(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-getkey+ pub(crate) fn get_key(this: &Ref<Self>, cx: &mut CallContext, query: Value) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction_object();++ // 2. Let index be this’s index.+ let index = this.index;++ // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.+ if index.is_deleted() || index.object_store().is_deleted() {+ return Err(invalid_state_error("Index or its object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while getting key",+ ));+ }++ // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, Some(query), true)?;++ // 6. Let operation be an algorithm to run retrieve a value from an index with index and range.+ let operation = create_operation(vm, (realm, index, range), |vm, &(realm, index, range)| {+ Ok(retrieve_a_value_from_an_index(+ &CallContext::new(vm, realm),+ index,+ &range,+ ))+ });++ // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::Index(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-getall+ pub(crate) fn get_all(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query_or_options: Option<Value>,+ count: Option<u32>,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,+ // "value", queryOrOptions, and count if given. Rethrow any exceptions.+ create_a_request_to_retrieve_multiple_items(+ &CallContext::new(cx.vm(), this.realm()),+ IDBRequestSource::Index(*this),+ RecordKind::Value,+ query_or_options.unwrap_or(Value::UNDEFINED),+ count,+ )+ .map(request_of)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys+ pub(crate) fn get_all_keys(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query_or_options: Option<Value>,+ count: Option<u32>,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this, "key",+ // queryOrOptions, and count if given. Rethrow any exceptions.+ create_a_request_to_retrieve_multiple_items(+ &CallContext::new(cx.vm(), this.realm()),+ IDBRequestSource::Index(*this),+ RecordKind::Key,+ query_or_options.unwrap_or(Value::UNDEFINED),+ count,+ )+ .map(request_of)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-count+ pub(crate) fn count(this: &Ref<Self>, cx: &mut CallContext, query: Option<Value>) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction_object();++ // 2. Let index be this’s index.+ let index = this.index;++ // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.+ if index.is_deleted() || index.object_store().is_deleted() {+ return Err(invalid_state_error("Index or its object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error("Transaction is not active while counting"));+ }++ // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, query, false)?;++ // 6. Let operation be an algorithm to run count the records in a range with index and range.+ let operation = create_operation(vm, (index, range), |_, &(index, range)| {+ Ok(count_the_records_in_a_range(RecordSource::Index(index), &range))+ });++ // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::Index(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-openkeycursor+ pub(crate) fn open_key_cursor(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query: Option<Value>,+ direction: IDBCursorDirection,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction_object();++ // 2. Let index be this’s index.+ let index = this.index;++ // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.+ if index.is_deleted() || index.object_store().is_deleted() {+ return Err(invalid_state_error("Index or its object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while opening key cursor",+ ));+ }++ // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, query, false)?;++ // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction, got value flag set to false, undefined key and value, range set to range, and key only flag set to true.+ let cursor = IDBCursor::create(+ vm,+ CursorSourceHandle::Index(*this),+ None,+ direction,+ false,+ None,+ None,+ range,+ true,+ );++ // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.+ let operation = create_operation(vm, (realm, cursor), |vm, &(realm, cursor)| {+ let cx = CallContext::new(vm, realm);+ let result = iterate_a_cursor(&cx, cursor, None, None, 1)?;+ Ok(idb_cursor_result(&cx, result))+ });++ // 8. Let request be the result of running asynchronously execute a request with this and operation.+ let request = request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::Index(*this),+ operation,+ None,+ ));++ // 9. Set cursor’s request to request.+ cursor.set_request(Some(request));++ // 10. Return request.+ Ok(request)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbindex-getallrecords+ pub(crate) fn get_all_records(+ this: &Ref<Self>,+ cx: &mut CallContext,+ options: IDBGetAllOptions,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,+ // "record", and options. Rethrow any exceptions.+ create_a_request_to_retrieve_multiple_items_with_options(+ &CallContext::new(cx.vm(), this.realm()),+ IDBRequestSource::Index(*this),+ RecordKind::Record,+ &options,+ )+ .map(request_of)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_key_range.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_key_range.rsnew file mode 100644index 00000000000..b6e8603bddd--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_key_range.rs@@ -0,0 +1,235 @@+/*+ * Copyright (c) 2024, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBKeyRange, https://w3c.github.io/IndexedDB/#keyrange++use std::rc::Rc;++use ak::Utf16String;+use libjs_rust::api::{Trace, Value, Vm, is_host_instance_of};++use crate::bindings::interface::{Interface, Ref, Wrappable, allocate, implementation_of};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::indexed_db::internal::algorithms::{convert_a_key_to_a_value, convert_a_value_to_a_key};+use crate::indexed_db::internal::key::Key;++// https://w3c.github.io/IndexedDB/#keyrange+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBKeyRange {+ // A key range has an associated lower bound (null or a key).+ #[gc(untraced)]+ lower_bound: Option<Rc<Key>>,++ // A key range has an associated upper bound (null or a key).+ #[gc(untraced)]+ upper_bound: Option<Rc<Key>>,++ // A key range has an associated lower open flag. Unless otherwise stated it is false.+ lower_open: bool,++ // A key range has an associated upper open flag. Unless otherwise stated it is false.+ upper_open: bool,+}++impl Wrappable for IDBKeyRange {}++impl IDBKeyRange {+ pub(crate) fn create(+ vm: &Vm,+ lower_bound: Option<Rc<Key>>,+ upper_bound: Option<Rc<Key>>,+ lower_open: bool,+ upper_open: bool,+ ) -> Ref<IDBKeyRange> {+ allocate(vm, |_| IDBKeyRange {+ lower_bound,+ upper_bound,+ lower_open,+ upper_open,+ })+ }++ pub(crate) fn is_lower_open(&self) -> bool {+ self.lower_open+ }++ pub(crate) fn is_upper_open(&self) -> bool {+ self.upper_open+ }++ pub(crate) fn lower_key(&self) -> Option<&Rc<Key>> {+ self.lower_bound.as_ref()+ }++ pub(crate) fn upper_key(&self) -> Option<&Rc<Key>> {+ self.upper_bound.as_ref()+ }++ // https://w3c.github.io/IndexedDB/#in+ pub(crate) fn is_in_range(&self, key: &Key) -> bool {+ // A key is in a key range range if both of the following conditions are fulfilled:++ // The range’s lower bound is null, or it is less than key, or it is both equal to key and the range’s lower open flag is false.+ let lower_bound_in_range = match self.lower_key() {+ None => true,+ Some(lower_key) => Key::less_than(lower_key, key) || (Key::equals(key, lower_key) && !self.is_lower_open()),+ };++ // The range’s upper bound is null, or it is greater than key, or it is both equal to key and the range’s upper open flag is false.+ let upper_bound_in_range = match self.upper_key() {+ None => true,+ Some(upper_key) => {+ Key::greater_than(upper_key, key) || (Key::equals(key, upper_key) && !self.is_upper_open())+ }+ };++ lower_bound_in_range && upper_bound_in_range+ }++ pub(crate) fn key_range_lower(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The lower getter steps are to return the result of converting a key to a+ // value with this's lower bound if it is not null, or undefined otherwise.+ if let Some(lower_key) = self.lower_key() {+ return Ok(convert_a_key_to_a_value(cx, lower_key));+ }++ Ok(Value::UNDEFINED)+ }++ pub(crate) fn key_range_upper(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The upper getter steps are to return the result of converting a key to a+ // value with this's upper bound if it is not null, or undefined otherwise.+ if let Some(upper_key) = self.upper_key() {+ return Ok(convert_a_key_to_a_value(cx, upper_key));+ }++ Ok(Value::UNDEFINED)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-loweropen+ pub(crate) fn lower_open(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The lowerOpen getter steps are to return this’s lower open flag.+ Ok(self.lower_open)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-upperopen+ pub(crate) fn upper_open(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The upperOpen getter steps are to return this’s upper open flag.+ Ok(self.upper_open)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-only+ pub(crate) fn only(cx: &mut CallContext, value: Value) -> WebIdlResult<Ref<IDBKeyRange>> {+ // 1. Let key be the result of converting a value to a key with value. Rethrow any exceptions.+ let key = convert_a_value_to_a_key(cx, value, None)?;++ // 2. If key is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if key.is_invalid() {+ return Err(data_error("Value is invalid"));+ }++ // 3. Create and return a new key range containing only key.+ Ok(IDBKeyRange::create(cx.vm(), Some(key.clone()), Some(key), false, false))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-lowerbound+ pub(crate) fn lower_bound(cx: &mut CallContext, lower: Value, open: bool) -> WebIdlResult<Ref<IDBKeyRange>> {+ // 1. Let lowerKey be the result of converting a value to a key with lower. Rethrow any exceptions.+ let key = convert_a_value_to_a_key(cx, lower, None)?;++ // 2. If lowerKey is invalid, throw a "DataError" DOMException.+ if key.is_invalid() {+ return Err(data_error("Value is invalid"));+ }++ // 3. Create and return a new key range with lower bound set to lowerKey, lower open flag set to open, upper bound set to null, and upper open flag set to true.+ Ok(IDBKeyRange::create(cx.vm(), Some(key), None, open, true))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-upperbound+ pub(crate) fn upper_bound(cx: &mut CallContext, upper: Value, open: bool) -> WebIdlResult<Ref<IDBKeyRange>> {+ // 1. Let upperKey be the result of converting a value to a key with upper. Rethrow any exceptions.+ let key = convert_a_value_to_a_key(cx, upper, None)?;++ // 2. If upperKey is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if key.is_invalid() {+ return Err(data_error("Value is invalid"));+ }++ // 3. Create and return a new key range with lower bound set to null, lower open flag set to true, upper bound set to upperKey, and upper open flag set to open.+ Ok(IDBKeyRange::create(cx.vm(), None, Some(key), true, open))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-bound+ pub(crate) fn bound(+ cx: &mut CallContext,+ lower: Value,+ upper: Value,+ lower_open: bool,+ upper_open: bool,+ ) -> WebIdlResult<Ref<IDBKeyRange>> {+ // 1. Let lowerKey be the result of converting a value to a key with lower. Rethrow any exceptions.+ let lower_key = convert_a_value_to_a_key(cx, lower, None)?;++ // 2. If lowerKey is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if lower_key.is_invalid() {+ return Err(data_error("Value is invalid"));+ }++ // 3. Let upperKey be the result of converting a value to a key with upper. Rethrow any exceptions.+ let upper_key = convert_a_value_to_a_key(cx, upper, None)?;++ // 4. If upperKey is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if upper_key.is_invalid() {+ return Err(data_error("Value is invalid"));+ }++ // 5. If lowerKey is greater than upperKey, throw a "DataError" DOMException.+ if Key::less_than(&upper_key, &lower_key) {+ return Err(data_error("Lower key is greater than upper key"));+ }++ // 6. Create and return a new key range with lower bound set to lowerKey, lower open flag set to lowerOpen, upper bound set to upperKey and upper open flag set to upperOpen.+ Ok(IDBKeyRange::create(+ cx.vm(),+ Some(lower_key),+ Some(upper_key),+ lower_open,+ upper_open,+ ))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes+ pub(crate) fn includes(&self, cx: &mut CallContext, key: Value) -> WebIdlResult<bool> {+ // 1. Let k be the result of converting a value to a key with key. Rethrow any exceptions.+ let converted_key = convert_a_value_to_a_key(cx, key, None)?;++ // 2. If k is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if converted_key.is_invalid() {+ return Err(data_error("Value is invalid"));+ }++ // 3. Return true if k is in this range, and false otherwise.+ Ok(self.is_in_range(&converted_key))+ }+}++fn data_error(message: &str) -> Exception {+ Exception::Dom("DataError", Utf16String::from_utf8(message))+}++pub(crate) fn key_range_from_value(value: Value) -> Option<Ref<IDBKeyRange>> {+ if !value.is_object() {+ return None;+ }+ let object = value.as_object();+ if !is_host_instance_of(&object, IDBKeyRange::wrapper_class()) {+ return None;+ }+ Some(implementation_of(object))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_object_store.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_object_store.rsnew file mode 100644index 00000000000..62402635529--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_object_store.rs@@ -0,0 +1,1032 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBObjectStore, https://w3c.github.io/IndexedDB/#object-store-interface++use std::rc::Rc;++use core::cell::RefCell;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, Must, Object, Realm, Trace, Value, Vm};++use crate::bindings::conversions::{CppInterface, DOMStringOrDOMStringSequence, ToJs};+use crate::bindings::interface::{Ref, Wrappable, allocate, with_temporary_execution_context_and_callbacks};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::indexed_db::idb_cursor::{AnyIDBCursor, CursorSourceHandle, IDBCursor, IDBCursorDirection};+use crate::indexed_db::idb_index::IDBIndex;+use crate::indexed_db::idb_request::{AnyIDBRequest, IDBRequest, IDBRequestSource};+use crate::indexed_db::idb_transaction::{IDBTransaction, TransactionState};+use crate::indexed_db::internal::algorithms::{+ KeyPath, RecordKind, RecordSource, asynchronously_execute_a_request,+ check_that_a_key_could_be_injected_into_a_value, clear_an_object_store, clone_in_realm,+ convert_a_key_path_to_a_value, convert_a_key_to_a_value, convert_a_value_to_a_key, convert_a_value_to_a_key_range,+ count_the_records_in_a_range, create_a_request_to_retrieve_multiple_items,+ create_a_request_to_retrieve_multiple_items_with_options, create_a_sorted_name_list,+ delete_records_from_an_object_store, extract_a_key_from_a_value_using_a_key_path, is_valid_key_path,+ iterate_a_cursor, queue_the_creation_of_an_index, retrieve_a_key_from_an_object_store,+ retrieve_a_value_from_an_object_store, store_a_record_into_an_object_store,+};+use crate::indexed_db::internal::function::{NoCells, create_operation};+use crate::indexed_db::internal::index::{Index, IndexRef};+use crate::indexed_db::internal::key::Key;+use crate::indexed_db::internal::object_store::ObjectStoreRef;++/// The dictionary IDBIndexParameters of IndexedDB/IDBObjectStore.idl.+pub(crate) struct IDBIndexParameters {+ pub(crate) multi_entry: bool,+ pub(crate) unique: bool,+}++/// The dictionary IDBGetAllOptions of IndexedDB/IDBObjectStore.idl.+pub(crate) struct IDBGetAllOptions {+ pub(crate) count: Option<u32>,+ pub(crate) direction: IDBCursorDirection,+ pub(crate) query: Value,+}++// https://w3c.github.io/IndexedDB/#object-store-interface+// https://w3c.github.io/IndexedDB/#object-store-handle-construct+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBObjectStore {+ // An object store handle has an associated object store and an associated transaction.+ store: ObjectStoreRef,+ transaction: Ref<IDBTransaction>,++ // An object store handle has a name, which is initialized to the name of the associated object store when the object store handle is created.+ #[gc(untraced)]+ name: RefCell<Utf16String>,++ // An object store handle has an index set+ indexes: GcRefCell<Vec<(Utf16String, IndexRef)>>,++ // NB: The keyPath getter returns the same Array every time it is inspected in the same realm.+ key_path_arrays: GcRefCell<Vec<(Gc<Object>, Gc<Object>)>>,++ // NB: Each call to index() on the same IDBObjectStore instance with the same name returns the same IDBIndex+ // instance. These are keyed by index so that they survive renames.+ index_handles: GcRefCell<Vec<(IndexRef, Ref<IDBIndex>)>>,+}++impl Wrappable for IDBObjectStore {}++impl IDBObjectStore {+ pub(crate) fn create(vm: &Vm, store: ObjectStoreRef, transaction: Ref<IDBTransaction>) -> Ref<IDBObjectStore> {+ allocate(vm, |defer| IDBObjectStore {+ store,+ transaction,+ name: RefCell::new(store.name()),+ // An object store handle has an index set, which is initialized to the set of indexes that reference the associated object store when the object store handle is created.+ indexes: GcRefCell::new(store.index_set(defer)),+ key_path_arrays: GcRefCell::new(Vec::new()),+ index_handles: GcRefCell::new(Vec::new()),+ })+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.transaction.realm()+ }++ pub(crate) fn store(&self) -> ObjectStoreRef {+ self.store+ }++ pub(crate) fn transaction_object(&self) -> Ref<IDBTransaction> {+ self.transaction+ }++ pub(crate) fn index_set_get(&self, name: &Utf16String) -> Option<IndexRef> {+ self.indexes+ .borrow()+ .iter()+ .find(|(index_name, _)| index_name == name)+ .map(|(_, index)| *index)+ }++ pub(crate) fn rename_index_set_entry(&self, vm: &Vm, old_name: &Utf16String, name: Utf16String) {+ let mut indexes = self.indexes.borrow_mut(vm);+ let position = indexes+ .iter()+ .position(|(index_name, _)| index_name == old_name)+ .expect("the index is in the index set of its handle");+ let (_, index) = indexes.remove(position);+ match indexes.iter_mut().find(|(index_name, _)| *index_name == name) {+ Some(entry) => entry.1 = index,+ None => indexes.push((name, index)),+ }+ }++ pub(crate) fn index_set_clear(&self, vm: &Vm) {+ self.indexes.borrow_mut(vm).clear();+ }++ pub(crate) fn update_name(&self) {+ *self.name.borrow_mut() = self.store.name();+ }++ pub(crate) fn update_index_set(&self, vm: &Vm) {+ self.store.copy_index_set_into(&mut self.indexes.borrow_mut(vm));+ }++ fn index_handle(this: &Ref<Self>, vm: &Vm, index: IndexRef) -> Ref<IDBIndex> {+ if let Some((_, handle)) = this.index_handles.borrow().iter().find(|(entry, _)| *entry == index) {+ return *handle;+ }+ let handle = IDBIndex::create(vm, index, *this);+ this.index_handles.borrow_mut(vm).push((index, handle));+ handle+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-name+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ // The name getter steps are to return this’s name.+ Ok(self.name.borrow().clone())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-name+ pub(crate) fn set_name(&self, cx: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let name be the given value.+ let name = &value;++ // 2. Let transaction be this’s transaction.+ let transaction = self.transaction;++ // 3. Let store be this’s object store.+ let store = self.store;++ // 4. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 5. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.+ if !transaction.is_upgrade_transaction() {+ return Err(invalid_state_error("Attempted to set name outside of version change"));+ }++ // 6. If transaction’s state is not active, throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while updating object store name",+ ));+ }++ // 7. If store’s name is equal to name, terminate these steps.+ if store.name() == *name {+ return Ok(());+ }++ // 8. If an object store named name already exists in store’s database, throw a "ConstraintError" DOMException.+ if store.database().object_store_with_name(name).is_some() {+ return Err(constraint_error("Object store with the given name already exists"));+ }++ // AD-HOC: Log the rename for potential revert on abort.+ store+ .mutation_log()+ .expect("an upgrade transaction logs the mutations of its stores")+ .note_object_store_renamed(vm, store.name());++ // 9. Set store’s name to name.+ store.set_name(name.clone());++ // 10. Set this’s name to name.+ *self.name.borrow_mut() = name.clone();++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-keypath+ pub(crate) fn key_path(&self) -> Option<&KeyPath> {+ self.store.key_path()+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-keypath+ pub(crate) fn key_path_value(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ let vm = cx.vm();++ // The keyPath getter steps are to return this’s object store’s key path, or null if none. The key path is+ // converted as a DOMString (if a string) or a sequence<DOMString> (if a list of strings), per [WEBIDL].+ let Some(key_path) = self.key_path() else {+ return Ok(Value::NULL);+ };++ // NOTE: The returned value is not the same instance that was used when the object store was created. However, if+ // this attribute returns an object (specifically an Array), it returns the same object instance every time+ // it is inspected. Changing the properties of the object has no effect on the object store.+ let global_object = cx.realm().global_object();+ if let Some((_, array)) = self+ .key_path_arrays+ .borrow()+ .iter()+ .find(|(global, _)| *global == global_object)+ {+ return Ok(Value::from_object(*array));+ }++ let value = convert_a_key_path_to_a_value(cx, key_path);+ if value.is_object() {+ self.key_path_arrays+ .borrow_mut(vm)+ .push((global_object, value.as_object()));+ }+ Ok(value)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-indexnames+ pub(crate) fn index_names(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // 1. Let names be a list of the names of the indexes in this's index set.+ let names = self.indexes.borrow().iter().map(|(name, _)| name.clone()).collect();++ // 2. Return the result (a DOMStringList) of creating a sorted name list with names.+ Ok(create_a_sorted_name_list(cx, names))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-transaction+ pub(crate) fn transaction(&self, _: &mut CallContext) -> WebIdlResult<Ref<IDBTransaction>> {+ // The transaction getter steps are to return this’s transaction.+ Ok(self.transaction)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-autoincrement+ pub(crate) fn auto_increment(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The autoIncrement getter steps are to return true if this’s object store has a key generator, and false otherwise.+ Ok(self.store.uses_a_key_generator())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-createindex+ pub(crate) fn create_index(+ this: &Ref<Self>,+ cx: &mut CallContext,+ name: Utf16String,+ key_path: DOMStringOrDOMStringSequence,+ options: IDBIndexParameters,+ ) -> WebIdlResult<Ref<IDBIndex>> {+ let vm = cx.vm();+ let key_path = match key_path {+ DOMStringOrDOMStringSequence::DOMString(value) => KeyPath::String(value),+ DOMStringOrDOMStringSequence::Sequence(values) => KeyPath::Sequence(values),+ };++ // 1. Let transaction be this's transaction.+ let transaction = this.transaction;++ // 2. Let store be this's object store.+ let store = this.store;++ // 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.+ if !transaction.is_upgrade_transaction() {+ return Err(invalid_state_error("Transaction is not an upgrade transaction"));+ }++ // 4. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while creating index",+ ));+ }++ // 6. If an index named name already exists in store, throw a "ConstraintError" DOMException.+ if store.index_set_get(&name).is_some() {+ return Err(constraint_error("An index with the given name already exists"));+ }++ // 7. If keyPath is not a valid key path, throw a "SyntaxError" DOMException.+ if !is_valid_key_path(&key_path) {+ return Err(Exception::Dom(+ "SyntaxError",+ Utf16String::from_utf8("Key path is not valid"),+ ));+ }++ // 8. Let unique be options’s unique member.+ let unique = options.unique;++ // 9. Let multiEntry be options’s multiEntry member.+ let multi_entry = options.multi_entry;++ // 10. If keyPath is a sequence and multiEntry is true, throw an "InvalidAccessError" DOMException.+ if matches!(key_path, KeyPath::Sequence(_)) && multi_entry {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_utf8("Key path is a sequence and multiEntry is true"),+ ));+ }++ // 11. Let index be a new index in store.+ // Set index’s name to name, key path to keyPath, unique flag to unique, and multiEntry flag to multiEntry.+ let index = Index::create(vm, store, &name, &key_path, unique, multi_entry);++ // 12. Add index to this's index set.+ {+ let mut indexes = this.indexes.borrow_mut(vm);+ match indexes.iter_mut().find(|(index_name, _)| *index_name == name) {+ Some(entry) => entry.1 = index,+ None => indexes.push((name, index)),+ }+ }++ // AD-HOC: Log the creation for potential revert on abort.+ store+ .mutation_log()+ .expect("an upgrade transaction logs the mutations of its stores")+ .note_index_created(vm, index);++ // AD-HOC: Fill the index with the records of store, as a request after the ones made before.+ queue_the_creation_of_an_index(vm, *this, index);++ // 13. Return a new index handle associated with index and this.+ Ok(Self::index_handle(this, vm, index))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index+ pub(crate) fn index(this: &Ref<Self>, cx: &mut CallContext, name: Utf16String) -> WebIdlResult<Ref<IDBIndex>> {+ let vm = cx.vm();++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction;++ // 2. Let store be this’s object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is finished, then throw an "InvalidStateError" DOMException.+ if transaction.state() == TransactionState::Finished {+ return Err(invalid_state_error("Transaction is finished"));+ }++ // 5. Let index be the index named name in this’s index set if one exists, or throw a "NotFoundError" DOMException otherwise.+ let Some(index) = this.index_set_get(&name) else {+ return Err(not_found_error("Index not found in object store"));+ };++ // 6. Return an index handle associated with index and this.+ // NOTE: Each call to this method on the same IDBObjectStore instance with the same name returns the same IDBIndex+ // instance.+ Ok(Self::index_handle(this, vm, index))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-deleteindex+ pub(crate) fn delete_index(&self, cx: &mut CallContext, name: Utf16String) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let transaction be this’s transaction.+ let transaction = self.transaction;++ // 2. Let store be this’s object store.+ let store = self.store;++ // 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.+ if !transaction.is_upgrade_transaction() {+ return Err(invalid_state_error("Transaction is not an upgrade transaction"));+ }++ // 4. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while deleting index",+ ));+ }++ // 6. Let index be the index named name in store if one exists, or throw a "NotFoundError" DOMException otherwise.+ let Some(index) = store.index_set_get(&name) else {+ return Err(not_found_error("Index not found while trying to delete it"));+ };++ // 7. Remove index from this’s index set.+ {+ let mut indexes = self.indexes.borrow_mut(vm);+ if let Some(position) = indexes.iter().position(|(index_name, _)| *index_name == name) {+ indexes.remove(position);+ }+ }++ // AD-HOC: Mark the index as deleted so that stale handles throw InvalidStateError.+ index.set_deleted(true);++ // AD-HOC: Log the deletion for potential revert on abort.+ store+ .mutation_log()+ .expect("an upgrade transaction logs the mutations of its stores")+ .note_index_deleted(vm, index);++ // 8. Destroy index.+ store.index_set_remove(vm, &name);++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#add-or-put+ fn add_or_put(+ handle: Ref<IDBObjectStore>,+ cx: &mut CallContext,+ value: Value,+ key: Option<Value>,+ no_overwrite: bool,+ ) -> WebIdlResult<AnyIDBRequest> {+ let vm = cx.vm();+ let realm = handle.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be handle’s transaction.+ let transaction = handle.transaction;++ // 2. Let store be handle’s object store.+ let store = handle.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while running add/put",+ ));+ }++ // 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.+ if transaction.is_readonly() {+ return Err(Exception::Dom(+ "ReadOnlyError",+ Utf16String::from_utf8("Transaction is read-only"),+ ));+ }++ let key_was_given = key.is_some_and(|key| !key.is_undefined());++ // 6. If store uses in-line keys and key was given, throw a "DataError" DOMException.+ if store.uses_inline_keys() && key_was_given {+ return Err(data_error("Store uses in-line keys and key was given"));+ }++ // 7. If store uses out-of-line keys and has no key generator and key was not given, throw a "DataError" DOMException.+ if store.uses_out_of_line_keys() && !store.uses_a_key_generator() && !key_was_given {+ return Err(data_error(+ "Store uses out-of-line keys and has no key generator and key was not given",+ ));+ }++ let mut key_value: Option<Rc<Key>> = None;+ // 8. If key was given, then:+ if key_was_given {+ // 1. Let r be the result of converting a value to a key with key. Rethrow any exceptions.+ let r = convert_a_value_to_a_key(&realm_cx, key.expect("key was given"), None)?;++ // 2. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if r.is_invalid() {+ return Err(data_error("Key is invalid"));+ }++ // 3. Let key be r.+ key_value = Some(r);+ }++ // 9. Let targetRealm be a user-agent defined Realm.+ let target_cx = &realm_cx;++ // 10. Let clone be a clone of value in targetRealm during transaction. Rethrow any exceptions.+ let clone = clone_in_realm(target_cx, value, transaction)?;++ // 11. If store uses in-line keys, then:+ if store.uses_inline_keys() {+ let store_key_path = store.key_path().expect("the store uses in-line keys");++ // 1. Let kpk be the result of extracting a key from a value using a key path with clone and store’s key path. Rethrow any exceptions.+ let maybe_kpk = extract_a_key_from_a_value_using_a_key_path(&realm_cx, clone, store_key_path, false)?;++ // NOTE: Step 2 and 3 is reversed here, since we check for failure before validity.+ // 3. If kpk is not failure, let key be kpk.+ if let Ok(kpk) = maybe_kpk {+ // 2. If kpk is invalid, throw a "DataError" DOMException.+ if kpk.is_invalid() {+ return Err(Exception::Dom("DataError", kpk.value_as_string().clone()));+ }+ key_value = Some(kpk);+ }+ // 4. Otherwise (kpk is failure):+ else {+ // 1. If store does not have a key generator, throw a "DataError" DOMException.+ if !store.uses_a_key_generator() {+ return Err(data_error("Store does not have a key generator"));+ }++ // 2. If check that a key could be injected into a value with clone and store’s key path return false, throw a "DataError" DOMException.+ if !check_that_a_key_could_be_injected_into_a_value(&realm_cx, clone, store_key_path) {+ return Err(data_error("Key could not be injected into value"));+ }+ }+ }++ // 12. Let operation be an algorithm to run store a record into an object store with store, clone, key, and no-overwrite flag.+ let operation = create_operation(+ vm,+ (realm, store, clone, NoCells(key_value), no_overwrite),+ |vm, &(realm, store, clone, ref key_value, no_overwrite)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ let cx = CallContext::new(vm, realm);+ let optional_key =+ store_a_record_into_an_object_store(&cx, store, clone, key_value.0.clone(), no_overwrite)?;++ let Some(optional_key) = optional_key.filter(|key| !key.is_invalid()) else {+ return Ok(Value::UNDEFINED);+ };++ Ok(convert_a_key_to_a_value(&cx, &optional_key))+ })+ },+ );++ // 13. Return the result (an IDBRequest) of running asynchronously execute a request with handle and operation.+ Ok(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(handle),+ operation,+ None,+ ))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-add+ pub(crate) fn add(+ this: &Ref<Self>,+ cx: &mut CallContext,+ value: Value,+ key: Option<Value>,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // The add(value, key) method steps are to return the result of running add or put with this, value, key and the no-overwrite flag true.+ Self::add_or_put(*this, cx, value, key, true).map(request_of)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-put+ pub(crate) fn put(+ this: &Ref<Self>,+ cx: &mut CallContext,+ value: Value,+ key: Option<Value>,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // The put(value, key) method steps are to return the result of running add or put with this, value, key and the no-overwrite flag false.+ Self::add_or_put(*this, cx, value, key, false).map(request_of)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-count+ pub(crate) fn count(this: &Ref<Self>, cx: &mut CallContext, query: Option<Value>) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this's transaction.+ let transaction = this.transaction;++ // 2. Let store be this's object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while doing count",+ ));+ }++ // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, query, false)?;++ // 6. Let operation be an algorithm to run count the records in a range with store and range.+ let operation = create_operation(vm, (store, range), |_, &(store, range)| {+ Ok(count_the_records_in_a_range(RecordSource::ObjectStore(store), &range))+ });++ // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-get+ pub(crate) fn get(this: &Ref<Self>, cx: &mut CallContext, query: Value) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this's transaction.+ let transaction = this.transaction;++ // 2. Let store be this's object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error("Transaction is not active while getting"));+ }++ // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, Some(query), true)?;++ // 6. Let operation be an algorithm to run retrieve a value from an object store with the current Realm record, store, and range.+ let operation = create_operation(vm, (realm, store, range), |vm, &(realm, store, range)| {+ retrieve_a_value_from_an_object_store(&CallContext::new(vm, realm), store, &range)+ });++ // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-opencursor+ pub(crate) fn open_cursor(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query: Option<Value>,+ direction: IDBCursorDirection,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this's transaction.+ let transaction = this.transaction;++ // 2. Let store be this’s object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while opening cursor",+ ));+ }++ // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, query, false)?;++ // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction,+ // got value flag set to false, undefined key and value, range set to range, and key only flag set to false.+ let cursor = IDBCursor::create(+ vm,+ CursorSourceHandle::ObjectStore(*this),+ None,+ direction,+ false,+ None,+ None,+ range,+ false,+ );++ // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.+ let operation = create_operation(vm, (realm, cursor), |vm, &(realm, cursor)| {+ let cx = CallContext::new(vm, realm);+ let result = iterate_a_cursor(&cx, cursor, None, None, 1)?;+ Ok(idb_cursor_result(&cx, result))+ });++ // 8. Let request be the result of running asynchronously execute a request with this and operation.+ let request = request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(*this),+ operation,+ None,+ ));++ // 9. Set cursor’s request to request.+ cursor.set_request(Some(request));++ // 10. Return request.+ Ok(request)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-delete+ pub(crate) fn delete(this: &Ref<Self>, cx: &mut CallContext, query: Value) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction;++ // 2. Let store be this’s object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while deleting object store",+ ));+ }++ // 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.+ if transaction.is_readonly() {+ return Err(Exception::Dom(+ "ReadOnlyError",+ Utf16String::from_utf8("Transaction is read-only while deleting object store"),+ ));+ }++ // 6. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, Some(query), true)?;++ // 7. Let operation be an algorithm to run delete records from an object store with store and range.+ let operation = create_operation(vm, (store, range), |vm, &(store, range)| {+ Ok(delete_records_from_an_object_store(vm, store, &range))+ });++ // 8. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-clear+ pub(crate) fn clear(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction;++ // 2. Let store be this’s object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while clearing object store",+ ));+ }++ // 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.+ if transaction.is_readonly() {+ return Err(Exception::Dom(+ "ReadOnlyError",+ Utf16String::from_utf8("Transaction is read-only while clearing object store"),+ ));+ }++ // 6. Let operation be an algorithm to run clear an object store with store.+ let operation = create_operation(vm, store, |vm, &store| Ok(clear_an_object_store(vm, store)));++ // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey+ pub(crate) fn get_key(this: &Ref<Self>, cx: &mut CallContext, query: Value) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this’s transaction.+ let transaction = this.transaction;++ // 2. Let store be this’s object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while getting key",+ ));+ }++ // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, Some(query), true)?;++ // 6. Let operation be an algorithm to run retrieve a key from an object store with store and range.+ let operation = create_operation(vm, (realm, store, range), |vm, &(realm, store, range)| {+ Ok(retrieve_a_key_from_an_object_store(+ &CallContext::new(vm, realm),+ store,+ &range,+ ))+ });++ // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.+ Ok(request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(*this),+ operation,+ None,+ )))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall+ pub(crate) fn get_all(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query_or_options: Option<Value>,+ count: Option<u32>,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,+ // "value", queryOrOptions, and count if given. Rethrow any exceptions.+ create_a_request_to_retrieve_multiple_items(+ &CallContext::new(cx.vm(), this.realm()),+ IDBRequestSource::ObjectStore(*this),+ RecordKind::Value,+ query_or_options.unwrap_or(Value::UNDEFINED),+ count,+ )+ .map(request_of)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-openkeycursor+ pub(crate) fn open_key_cursor(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query: Option<Value>,+ direction: IDBCursorDirection,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ let vm = cx.vm();+ let realm = this.realm();+ let realm_cx = CallContext::new(vm, realm);++ // 1. Let transaction be this's transaction.+ let transaction = this.transaction;++ // 2. Let store be this’s object store.+ let store = this.store;++ // 3. If store has been deleted, throw an "InvalidStateError" DOMException.+ if store.is_deleted() {+ return Err(invalid_state_error("Object store has been deleted"));+ }++ // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(transaction_inactive_error(+ "Transaction is not active while opening key cursor",+ ));+ }++ // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.+ let range = convert_a_value_to_a_key_range(&realm_cx, query, false)?;++ // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction, got value flag set to false, undefined key and value, range set to range, and key only flag set to true.+ let cursor = IDBCursor::create(+ vm,+ CursorSourceHandle::ObjectStore(*this),+ None,+ direction,+ false,+ None,+ None,+ range,+ true,+ );++ // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.+ let operation = create_operation(vm, (realm, cursor), |vm, &(realm, cursor)| {+ let cx = CallContext::new(vm, realm);+ let result = iterate_a_cursor(&cx, cursor, None, None, 1)?;+ Ok(idb_cursor_result(&cx, result))+ });++ // 8. Let request be the result of running asynchronously execute a request with this and operation.+ let request = request_of(asynchronously_execute_a_request(+ vm,+ IDBRequestSource::ObjectStore(*this),+ operation,+ None,+ ));++ // 9. Set cursor’s request to request.+ cursor.set_request(Some(request));++ // 10. Return request.+ Ok(request)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys+ pub(crate) fn get_all_keys(+ this: &Ref<Self>,+ cx: &mut CallContext,+ query_or_options: Option<Value>,+ count: Option<u32>,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this, "key",+ // queryOrOptions, and count if given. Rethrow any exceptions.+ create_a_request_to_retrieve_multiple_items(+ &CallContext::new(cx.vm(), this.realm()),+ IDBRequestSource::ObjectStore(*this),+ RecordKind::Key,+ query_or_options.unwrap_or(Value::UNDEFINED),+ count,+ )+ .map(request_of)+ }++ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallrecords+ pub(crate) fn get_all_records(+ this: &Ref<Self>,+ cx: &mut CallContext,+ options: IDBGetAllOptions,+ ) -> WebIdlResult<Ref<IDBRequest>> {+ // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,+ // "record", and options. Rethrow any exceptions.+ create_a_request_to_retrieve_multiple_items_with_options(+ &CallContext::new(cx.vm(), this.realm()),+ IDBRequestSource::ObjectStore(*this),+ RecordKind::Record,+ &options,+ )+ .map(request_of)+ }+}++pub(crate) fn request_of(request: AnyIDBRequest) -> Ref<IDBRequest> {+ match request {+ AnyIDBRequest::IDBRequest(request) => request,+ AnyIDBRequest::IDBOpenDBRequest(_) => unreachable!("a request against a transaction is not an open request"),+ }+}++pub(crate) fn idb_cursor_result(cx: &CallContext, cursor: Option<AnyIDBCursor>) -> Value {+ match cursor {+ None => Value::NULL,+ Some(cursor) => cursor.to_js(cx).must(),+ }+}++pub(crate) fn invalid_state_error(message: &str) -> Exception {+ Exception::Dom("InvalidStateError", Utf16String::from_utf8(message))+}++pub(crate) fn transaction_inactive_error(message: &str) -> Exception {+ Exception::Dom("TransactionInactiveError", Utf16String::from_utf8(message))+}++pub(crate) fn constraint_error(message: &str) -> Exception {+ Exception::Dom("ConstraintError", Utf16String::from_utf8(message))+}++pub(crate) fn not_found_error(message: &str) -> Exception {+ Exception::Dom("NotFoundError", Utf16String::from_utf8(message))+}++pub(crate) fn data_error(message: &str) -> Exception {+ Exception::Dom("DataError", Utf16String::from_utf8(message))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_open_db_request.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_open_db_request.rsnew file mode 100644index 00000000000..8dd306f7419--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_open_db_request.rs@@ -0,0 +1,57 @@+/*+ * Copyright (c) 2024, Shannon Booth <[email protected]>+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBOpenDBRequest, https://w3c.github.io/IndexedDB/#idbopendbrequest++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::indexed_db::idb_request::{IDBRequest, IDBRequestSource};++// https://w3c.github.io/IndexedDB/#idbopendbrequest+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBOpenDBRequest {+ request: IDBRequest,+}++impl Inherits<IDBRequest> for IDBOpenDBRequest {+ fn parent(&self) -> &IDBRequest {+ &self.request+ }+}++impl Wrappable for IDBOpenDBRequest {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.request.cpp_parent()+ }+}++impl GetTheParent for IDBOpenDBRequest {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ // https://w3c.github.io/IndexedDB/#open-requests+ // An open request’s get the parent algorithm returns null.+ None+ }+}++impl IDBOpenDBRequest {+ // NOTE: The source of an open request is always null.+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<IDBOpenDBRequest> {+ let request = allocate(vm, |_| IDBOpenDBRequest {+ request: IDBRequest::new(realm, IDBRequestSource::Empty),+ });+ request.request.event_target().set_owner(request);+ request+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_record.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_record.rsnew file mode 100644index 00000000000..e18b7dd6fc2--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_record.rs@@ -0,0 +1,76 @@+/*+ * Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBRecord, https://w3c.github.io/IndexedDB/#record-interface++use std::rc::Rc;++use libjs_rust::api::{Trace, Value, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::indexed_db::internal::algorithms::convert_a_key_to_a_value;+use crate::indexed_db::internal::key::Key;++/// The bytes of a Web::HTML::StorageSerializationRecord, which records share.+pub(crate) type StorageSerializationRecord = Rc<[u8]>;++// https://w3c.github.io/IndexedDB/#object-store-record+#[derive(Clone)]+pub(crate) struct ObjectStoreRecord {+ pub(crate) key: Rc<Key>,+ pub(crate) value: StorageSerializationRecord,+}++// https://w3c.github.io/IndexedDB/#index-list-of-records+#[derive(Clone)]+pub(crate) struct IndexRecord {+ pub(crate) key: Rc<Key>,+ pub(crate) value: Rc<Key>,+}++// https://w3c.github.io/IndexedDB/#record-snapshot+// https://w3c.github.io/IndexedDB/#record-interface+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBRecord {+ #[gc(untraced)]+ key: Rc<Key>,+ value: Value,+ #[gc(untraced)]+ primary_key: Rc<Key>,+}++impl Wrappable for IDBRecord {}++impl IDBRecord {+ pub(crate) fn create(vm: &Vm, key: Rc<Key>, value: Value, primary_key: Rc<Key>) -> Ref<IDBRecord> {+ allocate(vm, |_| IDBRecord {+ key,+ value,+ primary_key,+ })+ }++ pub(crate) fn key(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The key getter steps are to return the result of converting a key to a+ // value with this's key.+ Ok(convert_a_key_to_a_value(cx, &self.key))+ }++ pub(crate) fn primary_key(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The primaryKey getter steps are to return the result of converting a key+ // to a value with this's primary key.+ Ok(convert_a_key_to_a_value(cx, &self.primary_key))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbrecord-value+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<Value> {+ // The value getter steps are to return this’s value.+ Ok(self.value)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_request.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_request.rsnew file mode 100644index 00000000000..dd3f6c85512--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_request.rs@@ -0,0 +1,287 @@+/*+ * Copyright (c) 2024, Shannon Booth <[email protected]>+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBRequest, https://w3c.github.io/IndexedDB/#request-api++use core::cell::Cell;+use core::ffi::c_void;+use core::ops::Deref;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, Gc, GcRefCell, GcWeak, Realm, Trace, Value, Vm};++use crate::bindings::conversions::{CppInterface, ToJs};+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Inherits, Ref, Wrappable, Wrapped, allocate};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::indexed_db::cpp::DomException;+use crate::indexed_db::idb_cursor::AnyIDBCursor;+use crate::indexed_db::idb_index::IDBIndex;+use crate::indexed_db::idb_object_store::IDBObjectStore;+use crate::indexed_db::idb_open_db_request::IDBOpenDBRequest;+use crate::indexed_db::idb_transaction::IDBTransaction;++/// The enumeration IDBRequestReadyState of IndexedDB/IDBRequest.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum IDBRequestReadyState {+ Pending,+ Done,+}++/// The union (IDBObjectStore or IDBIndex or IDBCursor) of IndexedDB/IDBRequest.idl.+#[allow(+ clippy::enum_variant_names,+ reason = "the variants have the names of the interfaces of the union"+)]+pub(crate) enum IDBObjectStoreOrIDBIndexOrIDBCursor {+ IDBObjectStore(Ref<IDBObjectStore>),+ IDBIndex(Ref<IDBIndex>),+ IDBCursor(AnyIDBCursor),+}++/// The source of a request: an object store handle, an index handle, or a cursor, or none for an open request.+#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum IDBRequestSource {+ Empty,+ ObjectStore(Ref<IDBObjectStore>),+ Index(Ref<IDBIndex>),+ Cursor(AnyIDBCursor),+}++// https://w3c.github.io/IndexedDB/#request-api+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBRequest {+ event_target: CppEventTarget,++ // A request has a processed flag which is initially false.+ processed: Cell<bool>,++ // A request has a done flag which is initially false.+ done: Cell<bool>,++ // A request has a result and an error+ result: Cell<Value>,+ error: GcRefCell<Option<DomException>>,++ // A request has a source object.+ source: Cell<IDBRequestSource>,+ realm: Gc<Realm>,++ // A request has a transaction which is initially null.+ transaction: Cell<Option<Ref<IDBTransaction>>>,++ // AD-HOC: Set to true to prevent queued operations and result events from executing.+ aborted: Cell<bool>,+}++impl Wrappable for IDBRequest {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for IDBRequest {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ // https://w3c.github.io/IndexedDB/#request-construct+ // A request’s get the parent algorithm returns the request’s transaction.+ self.transaction+ .get()+ .map(|transaction| transaction.event_target().clone())+ }+}++impl IDBRequest {+ pub(crate) fn new(realm: Gc<Realm>, source: IDBRequestSource) -> Self {+ Self {+ event_target: CppEventTarget::new(),+ processed: Cell::new(false),+ done: Cell::new(false),+ result: Cell::new(Value::UNDEFINED),+ error: GcRefCell::new(None),+ source: Cell::new(source),+ realm,+ transaction: Cell::new(None),+ aborted: Cell::new(false),+ }+ }++ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>, source: IDBRequestSource) -> Ref<IDBRequest> {+ let request = allocate(vm, |_| IDBRequest::new(realm, source));+ request.event_target.set_owner(request);+ request+ }++ pub(crate) fn event_target(&self) -> &CppEventTarget {+ &self.event_target+ }++ pub(crate) fn done(&self) -> bool {+ self.done.get()+ }++ pub(crate) fn processed(&self) -> bool {+ self.processed.get()+ }++ pub(crate) fn transaction_object(&self) -> Option<Ref<IDBTransaction>> {+ self.transaction.get()+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.realm+ }++ pub(crate) fn set_done(&self, done: bool) {+ self.done.set(done);+ }++ pub(crate) fn set_result(&self, result: Value) {+ self.result.set(result);+ }++ pub(crate) fn set_error(&self, vm: &Vm, error: Option<DomException>) {+ *self.error.borrow_mut(vm) = error;+ }++ pub(crate) fn set_processed(&self, processed: bool) {+ self.processed.set(processed);+ }++ pub(crate) fn set_transaction(&self, transaction: Option<Ref<IDBTransaction>>) {+ self.transaction.set(transaction);+ }++ pub(crate) fn has_error(&self) -> bool {+ self.error.borrow().is_some()+ }++ pub(crate) fn aborted(&self) -> bool {+ self.aborted.get()+ }++ pub(crate) fn set_aborted(&self, aborted: bool) {+ self.aborted.set(aborted);+ }++ /// The error, without the done flag check of the getter.+ pub(crate) fn error_object(&self) -> Option<DomException> {+ self.error.borrow().clone()+ }++ // https://w3c.github.io/IndexedDB/#dom-idbrequest-result+ pub(crate) fn result(&self, _: &mut CallContext) -> WebIdlResult<Value> {+ // 1. If this's done flag is false, then throw an "InvalidStateError" DOMException.+ if !self.done() {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8("The request is not done"),+ ));+ }++ // 2. Return this's result, or undefined if the request resulted in an error.+ if self.has_error() {+ return Ok(Value::UNDEFINED);+ }++ Ok(self.result.get())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbrequest-error+ pub(crate) fn error(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ // 1. If this's done flag is false, then throw an "InvalidStateError" DOMException.+ if !self.done.get() {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8("The request is not done"),+ ));+ }++ // 2. Return this's error, or null if no error occurred.+ Ok(self.error_object().map(|error| error.wrapper(cx)))+ }++ pub(crate) fn source(&self, _: &mut CallContext) -> WebIdlResult<Option<IDBObjectStoreOrIDBIndexOrIDBCursor>> {+ Ok(match self.source.get() {+ IDBRequestSource::Empty => None,+ IDBRequestSource::ObjectStore(object_store) => {+ Some(IDBObjectStoreOrIDBIndexOrIDBCursor::IDBObjectStore(object_store))+ }+ IDBRequestSource::Index(index) => Some(IDBObjectStoreOrIDBIndexOrIDBCursor::IDBIndex(index)),+ IDBRequestSource::Cursor(cursor) => Some(IDBObjectStoreOrIDBIndexOrIDBCursor::IDBCursor(cursor)),+ })+ }++ pub(crate) fn transaction(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<IDBTransaction>>> {+ Ok(self.transaction.get())+ }++ pub(crate) fn ready_state(&self, _: &mut CallContext) -> WebIdlResult<IDBRequestReadyState> {+ // The readyState getter steps are to return "pending" if this's done flag is false, and "done" otherwise.+ Ok(if self.done() {+ IDBRequestReadyState::Done+ } else {+ IDBRequestReadyState::Pending+ })+ }+}++#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum AnyIDBRequest {+ IDBRequest(Ref<IDBRequest>),+ IDBOpenDBRequest(Ref<IDBOpenDBRequest>),+}++impl Deref for AnyIDBRequest {+ type Target = IDBRequest;++ fn deref(&self) -> &IDBRequest {+ match self {+ Self::IDBRequest(request) => request,+ Self::IDBOpenDBRequest(request) => {+ let request: &IDBOpenDBRequest = request;+ request.parent()+ }+ }+ }+}++impl ToJs for AnyIDBRequest {+ fn to_js(self, cx: &CallContext) -> libjs_rust::api::ThrowCompletionOr<Value> {+ match self {+ Self::IDBRequest(request) => request.to_js(cx),+ Self::IDBOpenDBRequest(request) => request.to_js(cx),+ }+ }+}++pub(crate) enum WeakIDBRequest {+ IDBRequest(GcWeak<EmbedderCell<Wrapped<IDBRequest>>>),+ IDBOpenDBRequest(GcWeak<EmbedderCell<Wrapped<IDBOpenDBRequest>>>),+}++impl WeakIDBRequest {+ pub(crate) fn new(vm: &Vm, request: AnyIDBRequest) -> Self {+ match request {+ AnyIDBRequest::IDBRequest(request) => Self::IDBRequest(GcWeak::new(vm.heap(), request)),+ AnyIDBRequest::IDBOpenDBRequest(request) => Self::IDBOpenDBRequest(GcWeak::new(vm.heap(), request)),+ }+ }++ pub(crate) fn get(&self) -> Option<AnyIDBRequest> {+ match self {+ Self::IDBRequest(request) => request.get().map(AnyIDBRequest::IDBRequest),+ Self::IDBOpenDBRequest(request) => request.get().map(AnyIDBRequest::IDBOpenDBRequest),+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_transaction.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_transaction.rsnew file mode 100644index 00000000000..a1f9214ca11--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_transaction.rs@@ -0,0 +1,429 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBTransaction, https://w3c.github.io/IndexedDB/#transaction++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Realm, Trace, Vm};++use crate::bindings::conversions::CppInterface;+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::indexed_db::cpp::{DomException, devtools_client_is_active, notify_devtools_of_committed_changes};+use crate::indexed_db::idb_database::{IDBDatabase, IDBTransactionDurability};+use crate::indexed_db::idb_index::IDBIndex;+use crate::indexed_db::idb_object_store::{IDBObjectStore, invalid_state_error, not_found_error};+use crate::indexed_db::idb_request::AnyIDBRequest;+use crate::indexed_db::internal::algorithms::{abort_a_transaction, commit_a_transaction, create_a_sorted_name_list};+use crate::indexed_db::internal::mutation_log::{MutationLog, MutationLogRef, TransactionChanges};+use crate::indexed_db::internal::object_store::ObjectStoreRef;+use crate::indexed_db::internal::request_list::RequestList;++/// The enumeration IDBTransactionMode of IndexedDB/IDBTransaction.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum IDBTransactionMode {+ Readonly,+ Readwrite,+ Versionchange,+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum TransactionState {+ Active,+ Inactive,+ Committing,+ Finished,+}++// AD-HOC: Per-store mutation logs for data and schema change reversion.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct StoreMutationLog {+ store: ObjectStoreRef,+ log: MutationLogRef,+}++// https://w3c.github.io/IndexedDB/#transaction+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBTransaction {+ event_target: CppEventTarget,++ // AD-HOC: The transaction has a connection+ connection: Ref<IDBDatabase>,++ // A transaction has a mode that determines which types of interactions can be performed upon that transaction.+ #[gc(untraced)]+ mode: IDBTransactionMode,++ // A transaction has a durability hint. This is a hint to the user agent of whether to prioritize performance or durability when committing the transaction.+ #[gc(untraced)]+ durability: IDBTransactionDurability,++ // A transaction has a state+ #[gc(untraced)]+ state: Cell<TransactionState>,++ // A transaction has a error which is set if the transaction is aborted.+ error: GcRefCell<Option<DomException>>,++ // A transaction has an associated upgrade request+ associated_request: Cell<Option<AnyIDBRequest>>,++ // AD-HOC: We need to track abort state separately, since we cannot rely on only the error.+ aborted: Cell<bool>,++ // A transaction has a scope which is a set of object stores that the transaction may interact with.+ scope: GcRefCell<Vec<ObjectStoreRef>>,++ // A transaction has a request list of pending requests which have been made against the transaction.+ request_list: RequestList,++ // A transaction optionally has a cleanup event loop which is an event loop.+ cleanup_event_loop: GcRefCell<Option<CppCell>>,++ object_store_handles: GcRefCell<Vec<(ObjectStoreRef, Ref<IDBObjectStore>)>>,+ index_handles: GcRefCell<Vec<Ref<IDBIndex>>>,++ store_mutation_logs: GcRefCell<Vec<StoreMutationLog>>,+ original_version: Cell<u64>,+}++impl Wrappable for IDBTransaction {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for IDBTransaction {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ // https://w3c.github.io/IndexedDB/#transaction-construct+ // A transaction’s get the parent algorithm returns the transaction’s connection.+ Some(self.connection.event_target().clone())+ }+}++impl IDBTransaction {+ pub(crate) fn create(+ vm: &Vm,+ connection: Ref<IDBDatabase>,+ mode: IDBTransactionMode,+ durability: IDBTransactionDurability,+ scope: &[ObjectStoreRef],+ ) -> Ref<IDBTransaction> {+ let transaction = allocate(vm, |defer| IDBTransaction {+ event_target: CppEventTarget::new(),+ connection,+ mode,+ durability,+ state: Cell::new(TransactionState::Active),+ error: GcRefCell::new(None),+ associated_request: Cell::new(None),+ aborted: Cell::new(false),+ scope: GcRefCell::new(scope.to_vec()),+ request_list: RequestList::new(defer),+ cleanup_event_loop: GcRefCell::new(None),+ object_store_handles: GcRefCell::new(Vec::new()),+ index_handles: GcRefCell::new(Vec::new()),+ store_mutation_logs: GcRefCell::new(Vec::new()),+ original_version: Cell::new(0),+ });+ transaction.event_target.set_owner(transaction);+ connection.add_transaction(vm, transaction);+ transaction+ }++ pub(crate) fn event_target(&self) -> &CppEventTarget {+ &self.event_target+ }++ pub(crate) fn state(&self) -> TransactionState {+ self.state.get()+ }++ pub(crate) fn error_object(&self) -> Option<DomException> {+ self.error.borrow().clone()+ }++ pub(crate) fn connection_object(&self) -> Ref<IDBDatabase> {+ self.connection+ }++ pub(crate) fn associated_request(&self) -> Option<AnyIDBRequest> {+ self.associated_request.get()+ }++ pub(crate) fn aborted(&self) -> bool {+ self.aborted.get()+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.connection.realm()+ }++ pub(crate) fn request_list(&self) -> &RequestList {+ &self.request_list+ }++ pub(crate) fn scope<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, ObjectStoreRef> {+ let scope = MarkedVec::new(vm);+ scope.extend_from_slice(&self.scope.borrow());+ scope+ }++ pub(crate) fn cleanup_event_loop(&self) -> Option<*mut c_void> {+ self.cleanup_event_loop.borrow().as_ref().map(CppCell::as_ptr)+ }++ pub(crate) fn set_error(&self, vm: &Vm, error: Option<DomException>) {+ *self.error.borrow_mut(vm) = error;+ }++ pub(crate) fn set_associated_request(&self, request: Option<AnyIDBRequest>) {+ self.associated_request.set(request);+ }++ pub(crate) fn set_aborted(&self, aborted: bool) {+ self.aborted.set(aborted);+ }++ pub(crate) fn set_cleanup_event_loop(&self, vm: &Vm, event_loop: Option<CppCell>) {+ *self.cleanup_event_loop.borrow_mut(vm) = event_loop;+ }++ pub(crate) fn set_state(&self, state: TransactionState) {+ self.state.set(state);+ }++ pub(crate) fn is_upgrade_transaction(&self) -> bool {+ self.mode == IDBTransactionMode::Versionchange+ }++ pub(crate) fn is_readonly(&self) -> bool {+ self.mode == IDBTransactionMode::Readonly+ }++ pub(crate) fn is_finished(&self) -> bool {+ self.state.get() == TransactionState::Finished+ }++ pub(crate) fn is_active(&self) -> bool {+ self.state.get() == TransactionState::Active+ }++ pub(crate) fn object_store_named(&self, name: &Utf16String) -> Option<ObjectStoreRef> {+ self.scope.borrow().iter().find(|store| store.name() == *name).copied()+ }++ pub(crate) fn add_to_scope(&self, vm: &Vm, object_store: ObjectStoreRef) {+ self.scope.borrow_mut(vm).push(object_store);+ }++ pub(crate) fn remove_from_scope(&self, vm: &Vm, object_store: ObjectStoreRef) {+ let mut scope = self.scope.borrow_mut(vm);+ if let Some(position) = scope.iter().position(|other| *other == object_store) {+ scope.remove(position);+ }+ }++ pub(crate) fn set_scope(&self, vm: &Vm, scope: &[ObjectStoreRef]) {+ *self.scope.borrow_mut(vm) = scope.to_vec();+ }++ pub(crate) fn get_or_create_object_store_handle(+ this: Ref<Self>,+ vm: &Vm,+ store: ObjectStoreRef,+ ) -> Ref<IDBObjectStore> {+ if let Some(handle) = this.object_store_handle_for(store) {+ return handle;+ }++ let handle = IDBObjectStore::create(vm, store, this);+ this.object_store_handles.borrow_mut(vm).push((store, handle));+ handle+ }++ pub(crate) fn object_store_handle_for(&self, store: ObjectStoreRef) -> Option<Ref<IDBObjectStore>> {+ self.object_store_handles+ .borrow()+ .iter()+ .find(|(entry, _)| *entry == store)+ .map(|(_, handle)| *handle)+ }++ pub(crate) fn object_store_handles<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Ref<IDBObjectStore>> {+ let handles = MarkedVec::new(vm);+ for (_, handle) in self.object_store_handles.borrow().iter() {+ handles.push(*handle);+ }+ handles+ }++ pub(crate) fn register_index_handle(&self, vm: &Vm, handle: Ref<IDBIndex>) {+ self.index_handles.borrow_mut(vm).push(handle);+ }++ pub(crate) fn index_handles<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Ref<IDBIndex>> {+ let handles = MarkedVec::new(vm);+ handles.extend_from_slice(&self.index_handles.borrow());+ handles+ }++ // Mutation log management. Logs are per-store and track both data and schema mutations.+ pub(crate) fn set_up_mutation_logs(&self, vm: &Vm) {+ self.original_version+ .set(self.connection.associated_database().version());++ for store in self.scope(vm).values().iter() {+ let log = MutationLog::create(vm);+ store.set_mutation_log(Some(log));+ self.store_mutation_logs+ .borrow_mut(vm)+ .push(StoreMutationLog { store: *store, log });+ }+ }++ pub(crate) fn original_version(&self) -> u64 {+ self.original_version.get()+ }++ pub(crate) fn set_up_mutation_log_for_new_store(&self, vm: &Vm, store: ObjectStoreRef) {+ let log = MutationLog::create(vm);+ store.set_mutation_log(Some(log));+ self.store_mutation_logs+ .borrow_mut(vm)+ .push(StoreMutationLog { store, log });+ log.note_object_store_created(vm);+ }++ pub(crate) fn revert_all_mutations(&self, vm: &Vm) {+ let database = self.connection.associated_database();+ let entries = MarkedVec::new(vm);+ for entry in self.store_mutation_logs.borrow().iter() {+ entries.push((entry.store, entry.log));+ }+ for (store, log) in entries.values().iter().rev() {+ log.revert(vm, *store, database, self.connection);+ }++ database.set_version(self.original_version.get());+ self.connection.set_version(self.original_version.get());+ }++ pub(crate) fn discard_mutation_logs(&self, vm: &Vm) {+ for entry in self.store_mutation_logs.borrow().iter() {+ entry.store.set_mutation_log(None);+ }+ self.store_mutation_logs.borrow_mut(vm).clear();+ }++ pub(crate) fn notify_devtools_of_committed_changes(&self) {+ if !devtools_client_is_active(self.realm()) {+ return;+ }++ let mut changes = TransactionChanges::default();+ let database_name = self.connection.associated_database().name();+ for entry in self.store_mutation_logs.borrow().iter() {+ entry+ .log+ .append_changes(&database_name, &entry.store.name(), &mut changes);+ }+ if changes.is_empty() {+ return;+ }++ notify_devtools_of_committed_changes(self.realm(), &changes);+ }++ // https://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstorenames+ pub(crate) fn object_store_names(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // 1. Let names be a list of the names of the object stores in this's scope.+ let names = self+ .scope+ .borrow()+ .iter()+ .map(|object_store| object_store.name())+ .collect();++ // 2. Return the result (a DOMStringList) of creating a sorted name list with names.+ Ok(create_a_sorted_name_list(cx, names))+ }++ pub(crate) fn mode(&self, _: &mut CallContext) -> WebIdlResult<IDBTransactionMode> {+ Ok(self.mode)+ }++ pub(crate) fn durability(&self, _: &mut CallContext) -> WebIdlResult<IDBTransactionDurability> {+ Ok(self.durability)+ }++ pub(crate) fn connection(&self, _: &mut CallContext) -> WebIdlResult<Ref<IDBDatabase>> {+ Ok(self.connection)+ }++ pub(crate) fn error(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ Ok(self.error_object().map(|error| error.wrapper(cx)))+ }++ // https://w3c.github.io/IndexedDB/#dom-idbtransaction-abort+ pub(crate) fn abort(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. If this's state is committing or finished, then throw an "InvalidStateError" DOMException.+ if this.state.get() == TransactionState::Committing || this.state.get() == TransactionState::Finished {+ return Err(invalid_state_error("Transaction is ending"));+ }++ // 2. Run abort a transaction with this and null.+ abort_a_transaction(cx.vm(), *this, None);+ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbtransaction-commit+ pub(crate) fn commit(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. If this's state is not active, then throw an "InvalidStateError" DOMException.+ if this.state.get() != TransactionState::Active {+ return Err(invalid_state_error("Transaction is not active while committing"));+ }++ // 2. Run commit a transaction with this.+ commit_a_transaction(cx.vm(), *this);++ Ok(())+ }++ // https://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore+ pub(crate) fn object_store(+ this: &Ref<Self>,+ cx: &mut CallContext,+ name: Utf16String,+ ) -> WebIdlResult<Ref<IDBObjectStore>> {+ // 1. If this's state is finished, then throw an "InvalidStateError" DOMException.+ if this.state.get() == TransactionState::Finished {+ return Err(invalid_state_error("Transaction is finished"));+ }++ // 2. Let store be the object store named name in this's scope, or throw a "NotFoundError" DOMException if none.+ let Some(store) = this.object_store_named(&name) else {+ return Err(not_found_error("Object store not found in transactions scope"));+ };++ // 3. Return an object store handle associated with store and this.++ // https://w3c.github.io/IndexedDB/#object-store-handle-construct+ // Multiple handles may be associated with the same object store in different transactions,+ // but there must be only one object store handle associated with a particular object store+ // within a transaction.+ Ok(Self::get_or_create_object_store_handle(*this, cx.vm(), store))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_version_change_event.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_version_change_event.rsnew file mode 100644index 00000000000..e96ae108652--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_version_change_event.rs@@ -0,0 +1,85 @@+/*+ * Copyright (c) 2024, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! IDBVersionChangeEvent, https://w3c.github.io/IndexedDB/#events++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::dom::event::EventInit;++/// The dictionary IDBVersionChangeEventInit of IndexedDB/IDBVersionChangeEvent.idl.+pub(crate) struct IDBVersionChangeEventInit {+ pub(crate) parent: EventInit,+ pub(crate) new_version: Option<u64>,+ pub(crate) old_version: u64,+}++// https://w3c.github.io/IndexedDB/#events+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct IDBVersionChangeEvent {+ event: CppEvent,+ old_version: u64,+ new_version: Option<u64>,+}++impl Wrappable for IDBVersionChangeEvent {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event.as_cpp_parent()+ }+}++impl IDBVersionChangeEvent {+ pub(crate) fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: &IDBVersionChangeEventInit,+ ) -> Ref<IDBVersionChangeEvent> {+ let event = CppEvent::create_for_owner(+ realm,+ event_name,+ event_init.parent.bubbles,+ event_init.parent.cancelable,+ event_init.parent.composed,+ );+ let object = allocate(vm, |_| IDBVersionChangeEvent {+ event,+ old_version: event_init.old_version,+ new_version: event_init.new_version,+ });+ object.event.set_owner(object);+ object+ }++ pub(crate) fn construct(+ cx: &mut CallContext,+ r#type: Utf16String,+ event_init_dict: IDBVersionChangeEventInit,+ ) -> WebIdlResult<Ref<IDBVersionChangeEvent>> {+ Ok(Self::create(cx.vm(), cx.realm(), &r#type, &event_init_dict))+ }++ pub(crate) fn event(&self) -> &CppEvent {+ &self.event+ }++ pub(crate) fn old_version(&self, _: &mut CallContext) -> WebIdlResult<u64> {+ Ok(self.old_version)+ }++ pub(crate) fn new_version(&self, _: &mut CallContext) -> WebIdlResult<Option<u64>> {+ Ok(self.new_version)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rsnew file mode 100644index 00000000000..218594ecaca--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs@@ -0,0 +1,3166 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The algorithms of the Indexed Database API, https://w3c.github.io/IndexedDB/#algorithms++use std::rc::Rc;++use core::cell::Cell;++use ak::Utf16String;+use libjs_rust::api::{+ Array, ArrayBuffer, ArrayBufferShared, CanonicalIndexMode, Date, EmbedderCell, EmbedderClass, EmbedderValue, Gc,+ MarkedVec, Must, Object, PrimitiveString, PropertyKey, Realm, Trace, TypedArrayBase, Value, Vm,+ canonical_numeric_index_string, is_host_instance_of, length_of_array_like,+};+use libunicode_rust::character_types::{+ code_point_has_identifier_continue_property, code_point_has_identifier_start_property,+};++use crate::bindings::conversions::{CppInterface, ToJs, buffer_source_type_of};+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::event_target::{CppEvent, CppEventTarget};+use crate::bindings::interface::{Interface, Ref, implementation_if, implementation_of};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::dom::event::EventInit;+use crate::file_api::blob::{AnyBlob, Blob};+use crate::file_api::file::File;+use crate::indexed_db::cpp::{+ DomException, create_dom_string_list, structured_deserialize, structured_serialize_for_storage,+};+use crate::indexed_db::idb_cursor::{AnyIDBCursor, IDBCursorDirection};+use crate::indexed_db::idb_database::{ConnectionState, IDBDatabase, IDBTransactionDurability};+use crate::indexed_db::idb_key_range::{IDBKeyRange, key_range_from_value};+use crate::indexed_db::idb_object_store::{IDBGetAllOptions, IDBObjectStore};+use crate::indexed_db::idb_record::{IDBRecord, IndexRecord, ObjectStoreRecord, StorageSerializationRecord};+use crate::indexed_db::idb_request::{AnyIDBRequest, IDBRequest, IDBRequestSource};+use crate::indexed_db::idb_transaction::{IDBTransaction, IDBTransactionMode, TransactionState};+use crate::indexed_db::idb_version_change_event::{IDBVersionChangeEvent, IDBVersionChangeEventInit};+use crate::indexed_db::internal::database::Database;+use crate::indexed_db::internal::function::{+ Function, FunctionWith, NoCells, Operation, create_function, create_operation, perform_operation,+};+use crate::indexed_db::internal::index::{Index, IndexRef};+use crate::indexed_db::internal::key::{Key, KeyType, code_unit_order};+use crate::indexed_db::internal::object_store::{ObjectStore, ObjectStoreRef};+use crate::indexed_db::internal::storage::{ConnectionQueueRef, StorageKey, storage};++/// A key path, https://w3c.github.io/IndexedDB/#key-path-construct: a string or a list of strings.+#[derive(Clone)]+pub(crate) enum KeyPath {+ String(Utf16String),+ Sequence(Vec<Utf16String>),+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct TaskCounterState {+ remaining_tasks: Cell<usize>,+ after_all: Cell<Option<Function>>,+}++static TASK_COUNTER_STATE_CLASS: EmbedderClass<TaskCounterState> = EmbedderClass::new("IndexedDBTaskCounterState");++impl EmbedderValue for TaskCounterState {+ const CLASS: &'static EmbedderClass<Self> = &TASK_COUNTER_STATE_CLASS;+}++type TaskCounterStateRef = Gc<EmbedderCell<TaskCounterState>>;++impl TaskCounterState {+ fn create(vm: &Vm) -> TaskCounterStateRef {+ TASK_COUNTER_STATE_CLASS.allocate(vm, |_| TaskCounterState {+ remaining_tasks: Cell::new(0),+ after_all: Cell::new(None),+ })+ }++ fn decrement_remaining_tasks(&self, vm: &Vm) {+ assert!(self.remaining_tasks.get() > 0);+ self.remaining_tasks.set(self.remaining_tasks.get() - 1);+ if self.remaining_tasks.get() > 0 {+ return;+ }++ queue_a_database_task(+ vm,+ self.after_all.get().expect("the steps to run after all tasks are set"),+ );+ }+}++fn strictly_split_key_path(key_path: &Utf16String) -> Vec<Utf16String> {+ key_path+ .to_utf16()+ .split(|code_unit| *code_unit == u16::from(b'.'))+ .map(Utf16String::from_utf16)+ .collect()+}++pub(crate) type OpenResult = Result<Ref<IDBDatabase>, DomException>;++fn call_completion<A: 'static>(vm: &Vm, queue: ConnectionQueueRef, completion: FunctionWith<A>, result: A) {+ completion.call(vm, result);+ queue.request_list.on_request_processed(vm);+}++// https://w3c.github.io/IndexedDB/#open-a-database-connection+pub(crate) fn open_a_database_connection(+ vm: &Vm,+ realm: Gc<Realm>,+ storage_key: StorageKey,+ name: Utf16String,+ maybe_version: Option<u64>,+ request: AnyIDBRequest,+ on_complete: FunctionWith<OpenResult>,+) {+ // 1. Let queue be the connection queue for storageKey and name.+ let queue = storage(vm).connection_queue_for_key_and_name(vm, &storage_key, &name);++ // 2. Add request to queue.+ // 3. Wait until all previous requests in queue have been processed.+ let steps = create_function(+ vm,+ (+ realm,+ queue,+ NoCells(storage_key),+ name,+ maybe_version,+ request,+ on_complete,+ ),+ |vm, &(realm, queue, ref storage_key, ref name, maybe_version, request, on_complete), ()| {+ // 4. Let db be the database named name in storageKey, or null otherwise.+ let maybe_db = Database::for_key_and_name(vm, &storage_key.0, name);++ // 5. If version is undefined, let version be 1 if db is null, or db’s version otherwise.+ let version = maybe_version.unwrap_or_else(|| maybe_db.map_or(1, |db| db.version()));++ // 6. If db is null, let db be a new database with name name, version 0 (zero), and with no object stores.+ // If this fails for any reason, return an appropriate error (e.g. a QuotaExceededError, or an "UnknownError" DOMException).+ let db = maybe_db.unwrap_or_else(|| Database::create_for_key_and_name(vm, &storage_key.0, name));++ // 7. If db’s version is greater than version, return a newly created "VersionError" DOMException and abort these steps.+ if db.version() > version {+ call_completion(+ vm,+ queue,+ on_complete,+ Err(DomException::create(+ "VersionError",+ "Database version is greater than the requested version",+ )),+ );+ return;+ }++ // 8. Let connection be a new connection to db.+ let connection = IDBDatabase::create(vm, realm, db);++ // 9. Set connection’s version to version.+ connection.set_version(version);++ // 10. If db’s version is less than version, then:+ if db.version() < version {+ // 1. Let openConnections be the set of all connections, except connection, associated with db.+ let open_connections = db.associated_connections_except(vm, connection);++ // 2. For each entry of openConnections that does not have its close pending flag set to true,+ // queue a database task to fire a version change event named versionchange at entry with db’s version and version.+ let mut task_counter_state: Option<TaskCounterStateRef> = None;+ for &entry in open_connections.values().iter() {+ if !entry.close_pending() {+ let state = *task_counter_state.get_or_insert_with(|| TaskCounterState::create(vm));++ state.remaining_tasks.set(state.remaining_tasks.get() + 1);+ queue_a_database_task(+ vm,+ create_function(+ vm,+ (realm, entry, db, version, state),+ |vm, &(realm, entry, db, version, state), ()| {+ fire_a_version_change_event(+ vm,+ realm,+ "versionchange",+ entry.event_target(),+ db.version(),+ Some(version),+ );+ state.decrement_remaining_tasks(vm);+ },+ ),+ );+ }+ }++ // 3. Wait for all of the events to be fired.+ let after_all = create_function(+ vm,+ (+ realm,+ queue,+ OpenConnections(open_connections.to_vec()),+ db,+ version,+ connection,+ request,+ on_complete,+ ),+ |vm, &(realm, queue, ref open_connections, db, version, connection, request, on_complete), ()| {+ // 4. If any of the connections in openConnections are still not closed,+ // queue a database task to fire a version change event named blocked at request with db’s version and version.+ let any_connection_is_not_closed = open_connections+ .0+ .iter()+ .any(|entry| entry.state() != ConnectionState::Closed);+ if any_connection_is_not_closed {+ queue_a_database_task(+ vm,+ create_function(+ vm,+ (realm, request, db, version),+ |vm, &(realm, request, db, version), ()| {+ fire_a_version_change_event(+ vm,+ realm,+ "blocked",+ request.event_target(),+ db.version(),+ Some(version),+ );+ },+ ),+ );+ }++ // 5. Wait until all connections in openConnections are closed.+ db.wait_for_connections_to_close(+ vm,+ &open_connections.0,+ create_function(+ vm,+ (realm, queue, connection, version, request, on_complete),+ |vm, &(realm, queue, connection, version, request, on_complete), ()| {+ // 6. Run upgrade a database using connection, version and request.+ upgrade_a_database(+ vm,+ realm,+ connection,+ version,+ request,+ create_function(+ vm,+ (queue, connection, request, on_complete),+ |vm, &(queue, connection, request, on_complete), ()| {+ // 7. If connection was closed, return a newly created "AbortError" DOMException and abort these steps.+ if connection.state() == ConnectionState::Closed {+ call_completion(+ vm,+ queue,+ on_complete,+ Err(DomException::create(+ "AbortError",+ "Connection was closed",+ )),+ );+ return;+ }++ // 8. If request's error is set, run the steps to close a database connection with connection,+ // return a newly created "AbortError" DOMException and abort these steps.+ if request.has_error() {+ close_a_database_connection(+ vm,+ connection,+ Some(create_function(+ vm,+ (queue, on_complete),+ |vm, &(queue, on_complete), ()| {+ call_completion(+ vm,+ queue,+ on_complete,+ Err(DomException::create(+ "AbortError",+ "Upgrade transaction was aborted",+ )),+ );+ },+ )),+ false,+ );+ return;+ }++ // 11. Return connection.+ call_completion(vm, queue, on_complete, Ok(connection));+ },+ ),+ );+ },+ ),+ );+ },+ );++ if let Some(state) = task_counter_state {+ state.after_all.set(Some(after_all));+ } else {+ queue_a_database_task(vm, after_all);+ }++ // NOTE: Because of the async nature of this function, we return here and call the on_complete function+ // with the connection when necessary.+ return;+ }++ // 11. Return connection.+ call_completion(vm, queue, on_complete, Ok(connection));+ },+ );+ queue.request_list.enqueue(vm, request, steps);+}++/// The connections that an algorithm waits on, which it keeps alive while it waits.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct OpenConnections(Vec<Ref<IDBDatabase>>);++// https://w3c.github.io/IndexedDB/#fire-a-version-change-event+pub(crate) fn fire_a_version_change_event(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &str,+ target: &CppEventTarget,+ old_version: u64,+ new_version: Option<u64>,+) -> bool {+ let event_init = IDBVersionChangeEventInit {+ // 3. Set event’s bubbles and cancelable attributes to false.+ parent: EventInit {+ bubbles: false,+ cancelable: false,+ composed: false,+ },+ // 4. Set event’s oldVersion attribute to oldVersion.+ old_version,+ // 5. Set event’s newVersion attribute to newVersion.+ new_version,+ };++ // 1. Let event be the result of creating an event using IDBVersionChangeEvent.+ // 2. Set event’s type attribute to e.+ let event = IDBVersionChangeEvent::create(vm, realm, &Utf16String::from_utf8(event_name), &event_init);++ // 6. Let legacyOutputDidListenersThrowFlag be false.+ // 7. Dispatch event at target with legacyOutputDidListenersThrowFlag.+ // 8. Return legacyOutputDidListenersThrowFlag.+ target.dispatch_event_with_legacy_output_did_listeners_throw_flag(event.event())+}++// https://w3c.github.io/IndexedDB/#convert-value-to-key+pub(crate) fn convert_a_value_to_a_key(+ cx: &CallContext,+ input: Value,+ seen_input: Option<&MarkedVec<'_, Value>>,+) -> WebIdlResult<Rc<Key>> {+ let vm = cx.vm();++ // 1. If seen was not given, then let seen be a new empty set.+ let seen = MarkedVec::new(vm);+ if let Some(seen_input) = seen_input {+ seen.extend_from_slice(&seen_input.values());+ }++ // 2. If seen contains input, then return "invalid value".+ if seen.values().iter().any(|value| value.to_raw() == input.to_raw()) {+ return Ok(Key::create_invalid("Already seen key"));+ }++ // 3. Jump to the appropriate step below:++ // - If Type(input) is Number+ if input.is_number() {+ // 1. If input is NaN then return "invalid value".+ if input.is_nan() {+ return Ok(Key::create_invalid("NaN key"));+ }++ // 2. Otherwise, return a new key with type number and value input.+ return Ok(Key::create_number(input.as_f64()));+ }++ // - If input is a Date (has a [[DateValue]] internal slot)+ if input.is_object()+ && let Some(date) = input.as_object().downcast::<Date>()+ {+ // 1. Let ms be the value of input’s [[DateValue]] internal slot.+ let ms = date.date_value();++ // 2. If ms is NaN then return "invalid value".+ if ms.is_nan() {+ return Ok(Key::create_invalid("NaN key"));+ }++ // 3. Otherwise, return a new key with type date and value ms.+ return Ok(Key::create_date(ms));+ }++ // - If Type(input) is String+ if input.is_string() {+ // 1. Return a new key with type string and value input.+ return Ok(Key::create_string(input.as_string().utf16_string()));+ }++ // - If input is a buffer source type+ if let Some(buffer_source) = buffer_source_type_of(input) {+ // 1. If input is detached then return "invalid value".+ if buffer_source.extent().buffer.is_detached() {+ return Ok(Key::create_invalid("Detached buffer is not supported as key"));+ }++ // 2. Let bytes be the result of getting a copy of the bytes held by the buffer source input.+ // SAFETY: Copying the bytes neither runs script nor allocates.+ let data_buffer = unsafe { buffer_source.with_bytes(<[u8]>::to_vec) };++ // 3. Return a new key with type binary and value bytes.+ return Ok(Key::create_binary(data_buffer));+ }++ // - If input is an Array exotic object+ if input.is_object()+ && let Some(array) = input.as_object().downcast::<Array>()+ {+ let array: Gc<Object> = array.upcast();++ // 1. Let len be ? ToLength( ? Get(input, "length")).+ let length = length_of_array_like(vm, &array)?;++ // 2. Append input to seen.+ seen.push(input);++ // 3. Let keys be a new empty list.+ let mut keys = Vec::new();++ // 4. Let index be 0.+ let mut index: u64 = 0;++ // 5. While index is less than len:+ while index < length {+ let property_key = PropertyKey::from_number(index);++ // 1. Let hop be ? HasOwnProperty(input, index).+ let hop = array.has_own_property(vm, &property_key)?;++ // 2. If hop is false, return "invalid value".+ if !hop {+ return Ok(Key::create_invalid("Array-like object has no property"));+ }++ // 3. Let entry be ? Get(input, index).+ let entry = array.get(vm, &property_key)?;++ // 4. Let key be the result of converting a value to a key with arguments entry and seen.+ // 5. ReturnIfAbrupt(key).+ let key = convert_a_value_to_a_key(cx, entry, Some(&seen))?;++ // 6. If key is "invalid value" or "invalid type" abort these steps and return "invalid value".+ if key.is_invalid() {+ return Ok(key);+ }++ // 7. Append key to keys.+ keys.push(key);++ // 8. Increase index by 1.+ index += 1;+ }++ // 6. Return a new array key with value keys.+ return Ok(Key::create_array(keys));+ }++ // - Otherwise+ // Return "invalid type".+ Ok(Key::create_invalid(+ "Unable to convert value to key. Its not of a known type",+ ))+}++// https://w3c.github.io/IndexedDB/#close-a-database-connection+pub(crate) fn close_a_database_connection(+ vm: &Vm,+ connection: Ref<IDBDatabase>,+ on_complete: Option<Function>,+ forced: bool,+) {+ // 1. Set connection’s close pending flag to true.+ connection.set_close_pending(true);++ // 2. If the forced flag is true, then for each transaction created using connection run abort a transaction with transaction and newly created "AbortError" DOMException.+ if forced {+ for transaction in connection.transactions(vm).values().iter() {+ abort_a_transaction(+ vm,+ *transaction,+ Some(DomException::create("AbortError", "Connection was closed")),+ );+ }+ }++ // 3. Wait for all transactions created using connection to complete. Once they are complete, connection is closed.+ let transactions = connection.transactions(vm);+ connection.wait_for_transactions_to_finish(+ vm,+ &transactions.values(),+ create_function(+ vm,+ (connection, forced, on_complete),+ |vm, &(connection, forced, on_complete), ()| {+ connection.set_state(ConnectionState::Closed);++ let database = connection.associated_database();+ database.dissociate(connection);++ // 4. If the forced flag is true, then fire an event named close at connection.+ if forced {+ connection.event_target().dispatch_event(&CppEvent::create(+ connection.realm(),+ "close",+ false,+ false,+ false,+ ));+ }++ if let Some(on_complete) = on_complete {+ queue_a_database_task(vm, on_complete);+ }++ database.check_pending_connection_wait(vm);+ },+ ),+ );+}++// https://w3c.github.io/IndexedDB/#upgrade-a-database+pub(crate) fn upgrade_a_database(+ vm: &Vm,+ realm: Gc<Realm>,+ connection: Ref<IDBDatabase>,+ version: u64,+ request: AnyIDBRequest,+ on_complete: Function,+) {+ // 1. Let db be connection’s database.+ let db = connection.associated_database();++ // 2. Let transaction be a new upgrade transaction with connection used as connection.+ // 3. Set transaction’s scope to connection’s object store set.+ let object_store_set = connection.object_store_set(vm);+ let transaction = IDBTransaction::create(+ vm,+ connection,+ IDBTransactionMode::Versionchange,+ IDBTransactionDurability::Default,+ &object_store_set.values(),+ );++ // 4. Set db’s upgrade transaction to transaction.+ db.set_upgrade_transaction(Some(transaction));++ // 5. Set transaction’s state to inactive.+ transaction.set_state(TransactionState::Inactive);++ // FIXME: 6. Start transaction.++ // 7. Let old version be db’s version.+ let old_version = db.version();++ // AD-HOC: Set up per-store mutation logs. This also records the current database version+ // so it can be restored if the transaction is aborted.+ transaction.set_up_mutation_logs(vm);++ // 8. Set db’s version to version. This change is considered part of the transaction, and so if the transaction is aborted, this change is reverted.+ db.set_version(version);++ // 9. Set request’s processed flag to true.+ request.set_processed(true);++ // 10. Queue a database task to run these steps:+ queue_a_database_task(+ vm,+ create_function(+ vm,+ (+ realm,+ request,+ connection,+ transaction,+ old_version,+ version,+ on_complete,+ ),+ |vm, &(realm, request, connection, transaction, old_version, version, on_complete), ()| {+ // 1. Set request’s result to connection.+ set_idb_request_result(vm, realm, request, connection);++ // 2. Set request’s transaction to transaction.+ // NOTE: We need to do a two-way binding here.+ request.set_transaction(Some(transaction));+ transaction.set_associated_request(Some(request));++ // 3. Set request’s done flag to true.+ request.set_done(true);++ // 4. Set transaction’s state to active.+ transaction.set_state(TransactionState::Active);++ // 5. Let didThrow be the result of firing a version change event named upgradeneeded at request with old version and version.+ let did_throw = fire_a_version_change_event(+ vm,+ realm,+ "upgradeneeded",+ request.event_target(),+ old_version,+ Some(version),+ );++ // 6. If transaction’s state is active, then:+ if transaction.state() == TransactionState::Active {+ // 1. Set transaction’s state to inactive.+ transaction.set_state(TransactionState::Inactive);++ // 2. If didThrow is true, run abort a transaction with transaction and a newly created "AbortError" DOMException.+ if did_throw {+ abort_a_transaction(+ vm,+ transaction,+ Some(DomException::create(+ "AbortError",+ "Version change event threw an exception",+ )),+ );+ }++ // https://w3c.github.io/IndexedDB/#transaction-commit+ // The implementation must attempt to commit an inactive transaction when all requests placed+ // against the transaction have completed and their returned results handled, no new requests have+ // been placed against the transaction, and the transaction has not been aborted+ if transaction.state() == TransactionState::Inactive+ && transaction.request_list().is_empty()+ && !transaction.aborted()+ {+ commit_a_transaction(vm, transaction);+ }+ }++ // 11. Wait for transaction to finish.+ connection.wait_for_transactions_to_finish(vm, &[transaction], on_complete);+ },+ ),+ );+}++pub(crate) type DeleteResult = Result<u64, DomException>;++// https://w3c.github.io/IndexedDB/#deleting-a-database+pub(crate) fn delete_a_database(+ vm: &Vm,+ realm: Gc<Realm>,+ storage_key: StorageKey,+ name: Utf16String,+ request: AnyIDBRequest,+ on_complete: FunctionWith<DeleteResult>,+) {+ // 1. Let queue be the connection queue for storageKey and name.+ let queue = storage(vm).connection_queue_for_key_and_name(vm, &storage_key, &name);++ // 2. Add request to queue.+ // 3. Wait until all previous requests in queue have been processed.+ let steps = create_function(+ vm,+ (realm, queue, NoCells(storage_key), name, request, on_complete),+ |vm, &(realm, queue, ref storage_key, ref name, request, on_complete), ()| {+ // 4. Let db be the database named name in storageKey, if one exists. Otherwise, return 0 (zero).+ let Some(db) = Database::for_key_and_name(vm, &storage_key.0, name) else {+ call_completion(vm, queue, on_complete, Ok(0));+ return;+ };++ // 5. Let openConnections be the set of all connections associated with db.+ let open_connections = db.associated_connections(vm);++ // 6. For each entry of openConnections that does not have its close pending flag set to true,+ // queue a database task to fire a version change event named versionchange at entry with db’s version and null.+ let mut task_counter_state: Option<TaskCounterStateRef> = None;+ for &entry in open_connections.values().iter() {+ if !entry.close_pending() {+ let state = *task_counter_state.get_or_insert_with(|| TaskCounterState::create(vm));++ state.remaining_tasks.set(state.remaining_tasks.get() + 1);+ queue_a_database_task(+ vm,+ create_function(vm, (realm, entry, db, state), |vm, &(realm, entry, db, state), ()| {+ fire_a_version_change_event(+ vm,+ realm,+ "versionchange",+ entry.event_target(),+ db.version(),+ None,+ );+ state.decrement_remaining_tasks(vm);+ }),+ );+ }+ }++ // 7. Wait for all of the events to be fired.+ let after_all = create_function(+ vm,+ (+ realm,+ queue,+ OpenConnections(open_connections.to_vec()),+ db,+ NoCells(storage_key.0.clone()),+ name.clone(),+ request,+ on_complete,+ ),+ |vm, &(realm, queue, ref open_connections, db, ref storage_key, ref name, request, on_complete), ()| {+ // 8. If any of the connections in openConnections are still not closed, queue a database task to fire a+ // version change event named blocked at request with db’s version and null.+ let any_connection_is_not_closed = open_connections+ .0+ .iter()+ .any(|entry| entry.state() != ConnectionState::Closed);+ if any_connection_is_not_closed {+ queue_a_database_task(+ vm,+ create_function(vm, (realm, request, db), |vm, &(realm, request, db), ()| {+ fire_a_version_change_event(+ vm,+ realm,+ "blocked",+ request.event_target(),+ db.version(),+ None,+ );+ }),+ );+ }++ // 9. Wait until all connections in openConnections are closed.+ db.wait_for_connections_to_close(+ vm,+ &open_connections.0,+ create_function(+ vm,+ (queue, db, storage_key.clone(), name.clone(), on_complete),+ |vm, &(queue, db, ref storage_key, ref name, on_complete), ()| {+ // 10. Let version be db’s version.+ let version = db.version();++ // 11. Delete db. If this fails for any reason, return an appropriate error (e.g. a QuotaExceededError, or an "UnknownError" DOMException).+ Database::delete_for_key_and_name(vm, &storage_key.0, name);++ // 12. Return version.+ call_completion(vm, queue, on_complete, Ok(version));+ },+ ),+ );+ },+ );++ if let Some(state) = task_counter_state {+ state.after_all.set(Some(after_all));+ } else {+ queue_a_database_task(vm, after_all);+ }+ },+ );+ queue.request_list.enqueue(vm, request, steps);+}++// https://w3c.github.io/IndexedDB/#abort-an-upgrade-transaction+fn abort_an_upgrade_transaction(vm: &Vm, transaction: Ref<IDBTransaction>) {+ // 1. Let connection be transaction’s connection.+ let connection = transaction.connection_object();++ // 2. Let database be connection’s database.+ let database = connection.associated_database();++ // 3. Set connection’s version to database’s version if database previously existed, or 0 (zero) if database was+ // newly created.+ connection.set_version(database.version());++ // 4. Set connection’s object store set to the set of object stores in database if database previously existed, or+ // the empty set if database was newly created.+ // NB: MutationLog reverts all changes to the connection's object store set alongside the deletion/creation of the+ // underlying ObjectStore instances.+ // However, the transaction scope will still be outdated here. Upgrade transactions are always scoped to the+ // entire database, so this is easy.+ let object_store_set = connection.object_store_set(vm);+ transaction.set_scope(vm, &object_store_set.values());++ // 5. For each object store handle handle associated with transaction, including those for object stores that were+ // created or deleted during transaction:+ let database_object_stores = database.object_stores(vm);+ for handle in transaction.object_store_handles(vm).values().iter() {+ // 1. If handle’s object store was not newly created during transaction, set handle’s name to its object+ // store’s name.+ if database_object_stores.values().contains(&handle.store()) {+ handle.update_name();+ }++ // 2. Set handle’s index set to the set of indexes that reference its object store.+ handle.update_index_set(vm);+ }++ // 6. For each index handle handle associated with transaction, including those for indexes that were created or+ // deleted during transaction:+ for handle in transaction.index_handles(vm).values().iter() {+ // 1. If handle’s index was not newly created during transaction, set handle’s name to its index’s name.+ if handle+ .index()+ .object_store()+ .index_set_get(&handle.index().name())+ .is_some()+ {+ handle.update_name();+ }+ }+}++// https://w3c.github.io/IndexedDB/#abort-a-transaction+pub(crate) fn abort_a_transaction(vm: &Vm, transaction: Ref<IDBTransaction>, error: Option<DomException>) {+ // NOTE: This is not spec'ed anywhere, but we need to know IF the transaction was aborted.+ transaction.set_aborted(true);++ // 1. If transaction’s state is finished, abort these steps.+ if transaction.is_finished() {+ return;+ }++ // 2. All the changes made to the database by the transaction are reverted.+ // For upgrade transactions this includes changes to the set of object stores and indexes, as well as the change to the version.+ // Any object stores and indexes which were created during the transaction are now considered deleted for the purposes of other algorithms.+ transaction.revert_all_mutations(vm);+ transaction.discard_mutation_logs(vm);++ // 3. If transaction is an upgrade transaction, run the steps to abort an upgrade transaction with transaction.+ if transaction.is_upgrade_transaction() {+ abort_an_upgrade_transaction(vm, transaction);+ }++ // 4. Set transaction’s state to finished.+ transaction.set_state(TransactionState::Finished);++ // AD-HOC: Clear the cleanup event loop so that the microtask checkpoint doesn't set the state to inactive on a+ // finished transaction.+ // https://github.com/w3c/IndexedDB/issues/489+ transaction.set_cleanup_event_loop(vm, None);++ // 5. Set transaction’s error to error.+ transaction.set_error(vm, error);++ // 6. For each request of transaction’s request list, abort the steps to asynchronously execute a request for request,+ // set request’s processed flag to true, and queue a database task to run these steps:+ for request in transaction.request_list().requests(vm).values().iter() {+ let request = *request;+ request.set_aborted(true);+ request.set_processed(true);+ queue_a_database_task(+ vm,+ create_function(vm, request, |vm, &request, ()| {+ // 1. Set request’s done flag to true.+ request.set_done(true);++ // 2. Set request’s result to undefined.+ request.set_result(Value::UNDEFINED);++ // 3. Set request’s error to a newly created "AbortError" DOMException.+ request.set_error(vm, Some(DomException::create("AbortError", "Transaction was aborted")));++ // 4. Fire an event named error at request with its bubbles and cancelable attributes initialized to true.+ request+ .event_target()+ .dispatch_event(&CppEvent::create(request.realm(), "error", true, true, false));+ }),+ );+ }++ // NB: Clear the commit wait callback, since the transaction is no longer committing.+ transaction.request_list().clear_on_all_processed();++ // 7. Queue a database task to run these steps:+ queue_a_database_task(+ vm,+ create_function(vm, transaction, |vm, &transaction, ()| {+ // 1. If transaction is an upgrade transaction, then set transaction’s connection's associated database's upgrade transaction to null.+ if transaction.is_upgrade_transaction() {+ transaction+ .connection_object()+ .associated_database()+ .set_upgrade_transaction(None);+ }++ // 2. Fire an event named abort at transaction with its bubbles attribute initialized to true.+ transaction.event_target().dispatch_event(&CppEvent::create(+ transaction.realm(),+ "abort",+ true,+ false,+ false,+ ));++ // 3. If transaction is an upgrade transaction, then:+ if transaction.is_upgrade_transaction() {+ // 1. Let request be the open request associated with transaction.+ let request = transaction+ .associated_request()+ .expect("an upgrade transaction has an open request");++ // 2. Set request’s transaction to null.+ // NOTE: Clear the two-way binding.+ request.set_transaction(None);+ transaction.set_associated_request(None);++ // 3. Set request’s result to undefined.+ request.set_result(Value::UNDEFINED);++ // FIXME: https://github.com/w3c/IndexedDB/issues/473+ // x. Set transaction's associated request's error to a newly created "AbortError" DOMException.+ request.set_error(+ vm,+ Some(DomException::create("AbortError", "Upgrade transaction was aborted")),+ );++ // 4. Set request’s processed flag to false.+ // FIXME: request->set_processed(false);++ // 5. Set request’s done flag to false.+ request.set_done(false);+ }++ // AD-HOC: Now that all abort tasks are queued, notify pending transaction waits.+ // This is done after step 7 so that the abort cleanup tasks above are queued+ // before any waiting transactions (e.g. upgrade completion callbacks) proceed.+ transaction.connection_object().check_pending_transaction_waits(vm);+ }),+ );+}++// https://w3c.github.io/IndexedDB/#convert-a-key-to-a-value+pub(crate) fn convert_a_key_to_a_value(cx: &CallContext, key: &Key) -> Value {+ let vm = cx.vm();+ let realm = cx.realm();++ // 1. Let type be key’s type.+ let r#type = key.r#type();++ // 2. Let value be key’s value.+ // NB: The steps read the value for its type below.++ // 3. Switch on type:+ match r#type {+ KeyType::Number => {+ // Return an ECMAScript Number value equal to value+ Value::from_f64(key.value_as_double())+ }++ KeyType::String => {+ // Return an ECMAScript String value equal to value+ Value::from_string(PrimitiveString::create(vm, key.value_as_string().clone()))+ }++ KeyType::Date => {+ // 1. Let date be the result of executing the ECMAScript Date constructor with the single argument value.+ let date = Date::create(vm, realm, key.value_as_double());++ // 2. Assert: date is not an abrupt completion.+ // NOTE: This is not possible in our implementation.++ // 3. Return date.+ Value::from_object(date)+ }++ KeyType::Binary => {+ let buffer = key.value_as_byte_buffer();++ // 1. Let len be value’s length.+ let len = buffer.len();++ // 2. Let buffer be the result of executing the ECMAScript ArrayBuffer constructor with len.+ // 3. Assert: buffer is not an abrupt completion.+ // 4. Set the entries in buffer’s [[ArrayBufferData]] internal slot to the entries in value.+ let array_buffer = ArrayBuffer::try_create_written_by(vm, realm, len, ArrayBufferShared::No, |output| {+ for (byte, value) in output.iter_mut().zip(buffer) {+ byte.write(*value);+ }+ len+ })+ .must();++ // 5. Return buffer.+ Value::from_object(array_buffer)+ }++ KeyType::Array => {+ let data = key.value_as_vector();++ // 1. Let array be the result of executing the ECMAScript Array constructor with no arguments.+ // 2. Assert: array is not an abrupt completion.+ let array = Array::create(vm, realm, 0, None).must();++ // 3. Let len be value’s size.+ let len = data.len();++ // 4. Let index be 0.+ let mut index: usize = 0;++ // 5. While index is less than len:+ while index < len {+ // 1. Let entry be the result of converting a key to a value with value[index].+ let entry = convert_a_key_to_a_value(cx, &data[index]);++ // 2. Let status be CreateDataProperty(array, index, entry).+ let status = array+ .create_data_property(vm, &PropertyKey::from_number(index as u64), entry, None, None)+ .must();++ // 3. Assert: status is true.+ assert!(status);++ // 4. Increase index by 1.+ index += 1;+ }++ // 6. Return array.+ Value::from_object(array)+ }+ KeyType::Invalid => unreachable!("an invalid key is not converted to a value"),+ }+}++// https://tc39.es/ecma262/#prod-IdentifierName+fn is_identifier_name(string: &[u16]) -> bool {+ // FIXME: Accept the UnicodeEscapeSequences that IdentifierStart and IdentifierPart allow.+ if string.is_empty() {+ return false;+ }++ let mut is_first_code_point = true;+ for code_point in char::decode_utf16(string.iter().copied()) {+ let code_point = code_point.map_or(0xFFFD, u32::from);+ // IdentifierStartChar ::+ // UnicodeIDStart+ // $+ // _+ // IdentifierPartChar ::+ // UnicodeIDContinue+ // $+ // <ZWNJ>+ // <ZWJ>+ let mut is_valid = code_point == u32::from('$') || code_point == u32::from('_');+ if is_first_code_point {+ is_valid = is_valid || code_point_has_identifier_start_property(code_point);+ } else {+ is_valid = is_valid+ || code_point == 0x200C+ || code_point == 0x200D+ || code_point_has_identifier_continue_property(code_point);+ }+ if !is_valid {+ return false;+ }+ is_first_code_point = false;+ }+ true+}++// https://w3c.github.io/IndexedDB/#valid-key-path+fn is_valid_key_path_string(value: &Utf16String) -> bool {+ // A valid key path is one of:++ // * An empty string.+ if value.is_empty() {+ return true;+ }++ // * An identifier, which is a string matching the IdentifierName production from the ECMAScript Language+ // Specification [ECMA-262].+ // * A string consisting of two or more identifiers separated by periods (U+002E FULL STOP).+ let view = value.to_utf16();+ let mut identifier_start = 0;+ for index in 0..=view.len() {+ if index < view.len() && view[index] != u16::from(b'.') {+ continue;+ }+ if !is_identifier_name(&view[identifier_start..index]) {+ return false;+ }+ identifier_start = index + 1;+ }+ true+}++// https://w3c.github.io/IndexedDB/#valid-key-path+pub(crate) fn is_valid_key_path(path: &KeyPath) -> bool {+ match path {+ KeyPath::String(value) => is_valid_key_path_string(value),+ // * A non-empty list containing only strings conforming to the above requirements.+ KeyPath::Sequence(values) => !values.is_empty() && values.iter().all(is_valid_key_path_string),+ }+}++// https://w3c.github.io/IndexedDB/#create-a-sorted-name-list+pub(crate) fn create_a_sorted_name_list(cx: &CallContext, mut names: Vec<Utf16String>) -> CppInterface {+ // 1. Let sorted be names sorted in ascending order with the code unit less than algorithm.+ names.sort_by(code_unit_order);++ // 2. Return a new DOMStringList associated with sorted.+ create_dom_string_list(cx, &names)+}++// https://w3c.github.io/IndexedDB/#commit-a-transaction+pub(crate) fn commit_a_transaction(vm: &Vm, transaction: Ref<IDBTransaction>) {+ // 1. Set transaction’s state to committing.+ transaction.set_state(TransactionState::Committing);++ // AD-HOC: Clear the cleanup event loop so that the microtask checkpoint+ // does not reset the state back to inactive.+ // https://github.com/w3c/IndexedDB/issues/489+ transaction.set_cleanup_event_loop(vm, None);++ // 2. Run the following steps in parallel:+ // 1. Wait until every item in transaction’s request list is processed.+ transaction.request_list().set_on_all_processed(+ vm,+ create_function(vm, transaction, |vm, &transaction, ()| {+ // 2. If transaction’s state is no longer committing, then terminate these steps.+ if transaction.state() != TransactionState::Committing {+ return;+ }++ // FIXME: 3. Attempt to write any outstanding changes made by transaction to the database, considering transaction’s durability hint.+ // FIXME: 4. If an error occurs while writing the changes to the database, then run abort a transaction with transaction and an appropriate type for the error, for example a QuotaExceededError or an "UnknownError" DOMException, and terminate these steps.++ // 5. Queue a database task to run these steps:+ queue_a_database_task(+ vm,+ create_function(vm, transaction, |vm, &transaction, ()| {+ // 1. If transaction is an upgrade transaction, then set transaction’s connection’s associated database’s upgrade transaction to null.+ if transaction.is_upgrade_transaction() {+ transaction+ .connection_object()+ .associated_database()+ .set_upgrade_transaction(None);+ }++ // AD-HOC: Discard mutation logs now that changes are permanent.+ transaction.notify_devtools_of_committed_changes();+ transaction.discard_mutation_logs(vm);++ // 2. Set transaction’s state to finished.+ transaction.set_state(TransactionState::Finished);++ // 3. Fire an event named complete at transaction.+ transaction.event_target().dispatch_event(&CppEvent::create(+ transaction.realm(),+ "complete",+ false,+ false,+ false,+ ));++ // 4. If transaction is an upgrade transaction, then let request be the request associated with transaction and set request’s transaction to null.+ if transaction.is_upgrade_transaction() {+ let request = transaction+ .associated_request()+ .expect("an upgrade transaction has an open request");+ request.set_transaction(None);++ // Ad-hoc: Clear the two-way binding.+ transaction.set_associated_request(None);+ }++ // AD-HOC: Notify pending transaction waits after the complete event fires, so that+ // upgrade completion callbacks are queued after any tasks JS creates during+ // the complete event handler.+ transaction.connection_object().check_pending_transaction_waits(vm);+ }),+ );+ }),+ );+}++// https://w3c.github.io/IndexedDB/#clone+pub(crate) fn clone_in_realm(cx: &CallContext, value: Value, transaction: Ref<IDBTransaction>) -> WebIdlResult<Value> {+ // 1. Assert: transaction’s state is active.+ assert!(transaction.state() == TransactionState::Active);++ // 2. Set transaction’s state to inactive.+ transaction.set_state(TransactionState::Inactive);++ // AD-HOC: Always reset the transaction state to active. Otherwise, passing an unserializable value to put()+ // will prevent any further requests on the transaction.+ // https://github.com/w3c/IndexedDB/issues/490+ let result = (|| {+ // 3. Let serialized be ? StructuredSerializeForStorage(value).+ let serialized = structured_serialize_for_storage(cx, value)?;++ // 4. Let clone be ? StructuredDeserialize(serialized, targetRealm).+ let clone = structured_deserialize(cx, &serialized)?;++ // 5. Set transaction’s state to active.+ // NB: This is handled by the scope guard after step 2.++ // 6. Return clone.+ Ok(clone)+ })();+ transaction.set_state(TransactionState::Active);+ result+}++// https://w3c.github.io/IndexedDB/#convert-a-value-to-a-multientry-key+pub(crate) fn convert_a_value_to_a_multi_entry_key(cx: &CallContext, value: Value) -> WebIdlResult<Rc<Key>> {+ let vm = cx.vm();++ // 1. If input is an Array exotic object, then:+ if value.is_object()+ && let Some(array) = value.as_object().downcast::<Array>()+ {+ let array: Gc<Object> = array.upcast();++ // 1. Let len be ? ToLength( ? Get(input, "length")).+ let len = length_of_array_like(vm, &array)?;++ // 2. Let seen be a new set containing only input.+ let seen = MarkedVec::new(vm);+ seen.push(value);++ // 3. Let keys be a new empty list.+ let mut keys: Vec<Rc<Key>> = Vec::new();++ // 4. Let index be 0.+ let mut index: u64 = 0;++ // 5. While index is less than len:+ while index < len {+ // 1. Let entry be Get(input, index).+ let maybe_entry = array.get(vm, &PropertyKey::from_number(index));++ // 2. If entry is not an abrupt completion, then:+ if let Ok(entry) = maybe_entry {+ // 1. Let key be the result of converting a value to a key with arguments entry and seen.+ let completion_key = convert_a_value_to_a_key(cx, entry, Some(&seen));++ // 2. If key is not "invalid value" or "invalid type" or an abrupt completion, and there is no item in keys equal to key, then append key to keys.+ if let Ok(key) = completion_key+ && !key.is_invalid()+ && !keys.iter().any(|other| Key::equals(other, &key))+ {+ keys.push(key);+ }+ }++ // 3. Increase index by 1.+ index += 1;+ }++ // 6. Return a new array key with value set to keys.+ return Ok(Key::create_array(keys));+ }++ // 2. Otherwise, return the result of converting a value to a key with argument input. Rethrow any exceptions.+ convert_a_value_to_a_key(cx, value, None)+}++pub(crate) struct KeyPathFailure;++// https://w3c.github.io/IndexedDB/#evaluate-a-key-path-on-a-value+pub(crate) fn evaluate_key_path_on_a_value(+ cx: &CallContext,+ mut value: Value,+ key_path: &KeyPath,+) -> WebIdlResult<Result<Value, KeyPathFailure>> {+ let vm = cx.vm();++ let key_path_string = match key_path {+ // 1. If keyPath is a list of strings, then:+ KeyPath::Sequence(key_path_list) => {+ // 1. Let result be a new Array object created as if by the expression [].+ let result = Array::create(vm, cx.realm(), 0, None).must();++ // 2. Let i be 0.+ let mut i: u64 = 0;++ // 3. For each item of keyPath:+ #[allow(clippy::explicit_counter_loop, reason = "the steps count i themselves")]+ for item in key_path_list {+ // 1. Let key be the result of recursively evaluating a key path on a value with item and value.+ let completion_key = evaluate_key_path_on_a_value(cx, value, &KeyPath::String(item.clone()));++ // 2. Assert: key is not an abrupt completion.+ // 3. If key is failure, abort the overall algorithm and return failure.+ let Ok(key) = completion_key.must() else {+ return Ok(Err(KeyPathFailure));+ };++ // 4. Let p be ! ToString(i).+ let p = PropertyKey::from_number(i);++ // 5. Let status be CreateDataProperty(result, p, key).+ let status = result.create_data_property(vm, &p, key, None, None).must();++ // 6. Assert: status is true.+ assert!(status);++ // 7. Increase i by 1.+ i += 1;+ }++ // 4. Return result.+ return Ok(Ok(Value::from_object(result)));+ }+ KeyPath::String(key_path_string) => key_path_string,+ };++ // 2. If keyPath is the empty string, return value and skip the remaining steps.+ if key_path_string.is_empty() {+ return Ok(Ok(value));+ }++ // 3. Let identifiers be the result of strictly splitting keyPath on U+002E FULL STOP characters (.).+ // 4. For each identifier of identifiers, jump to the appropriate step below:+ for identifier in strictly_split_key_path(key_path_string) {+ let is_length = identifier == Utf16String::from_utf8("length");++ // If Type(value) is String, and identifier is "length"+ if value.is_string() && is_length {+ // Let value be a Number equal to the number of elements in value.+ #[allow(clippy::cast_precision_loss, reason = "a string has fewer than 2^53 code units")]+ {+ value = Value::from_f64(value.as_string().utf16_string().length_in_code_units() as f64);+ }+ }+ // If value is an Array and identifier is "length"+ else if value.is_object() && value.as_object().downcast::<Array>().is_some() && is_length {+ // Let value be ! ToLength(! Get(value, "length")).+ #[allow(clippy::cast_precision_loss, reason = "a length is at most 2^53 - 1")]+ {+ value = Value::from_f64(length_of_array_like(vm, &value.as_object()).must() as f64);+ }+ }+ // If value is a Blob and identifier is "size"+ // Let value be a Number equal to value’s size.+ // If value is a Blob and identifier is "type"+ // Let value be a String equal to value’s type.+ // If value is a File and identifier is "name"+ // Let value be a String equal to value’s name.+ // If value is a File and identifier is "lastModified"+ // Let value be a Number equal to value’s lastModified.+ else if let Some(key_path_value) = key_path_value_for_blob_or_file(cx, value, &identifier) {+ value = key_path_value;+ }+ // Otherwise+ else {+ // 1. If Type(value) is not Object, return failure.+ if !value.is_object() {+ return Ok(Err(KeyPathFailure));+ }++ let identifier_property = PropertyKey::from_utf16_string(&identifier);++ // 2. Let hop be ! HasOwnProperty(value, identifier).+ let hop = value.as_object().has_own_property(vm, &identifier_property).must();++ // 3. If hop is false, return failure.+ if !hop {+ return Ok(Err(KeyPathFailure));+ }++ // 4. Let value be ! Get(value, identifier).+ value = value.as_object().get(vm, &identifier_property).must();++ // 5. If value is undefined, return failure.+ if value.is_undefined() {+ return Ok(Err(KeyPathFailure));+ }+ }+ }++ // 5. Assert: value is not an abrupt completion.+ // NOTE: Step 4 above makes this assertion via MUST++ // 6. Return value.+ Ok(Ok(value))+}++// https://w3c.github.io/IndexedDB/#extract-a-key-from-a-value-using-a-key-path+pub(crate) fn extract_a_key_from_a_value_using_a_key_path(+ cx: &CallContext,+ value: Value,+ key_path: &KeyPath,+ multi_entry: bool,+) -> WebIdlResult<Result<Rc<Key>, KeyPathFailure>> {+ // 1. Let r be the result of evaluating a key path on a value with value and keyPath. Rethrow any exceptions.+ // 2. If r is failure, return failure.+ let r = match evaluate_key_path_on_a_value(cx, value, key_path)? {+ Ok(r) => r,+ Err(failure) => return Ok(Err(failure)),+ };++ // 3. Let key be the result of converting a value to a key with r if the multiEntry flag is false,+ // and the result of converting a value to a multiEntry key with r otherwise. Rethrow any exceptions.+ // 4. If key is "invalid value" or "invalid type", return invalid.+ // 5. Return key.+ Ok(Ok(if multi_entry {+ convert_a_value_to_a_multi_entry_key(cx, r)?+ } else {+ convert_a_value_to_a_key(cx, r, None)?+ }))+}++/// AD-HOC: Whether CreateDataProperty(value, identifier, key) would succeed, which inject a key into a value using a+/// key path asserts: a TypedArray refuses a canonical numeric string, such as "Infinity", that is not an+/// index of it.+fn can_create_data_property(value: Gc<Object>, identifier: &Utf16String) -> bool {+ value.downcast::<TypedArrayBase>().is_none()+ || canonical_numeric_index_string(+ &PropertyKey::from_utf16_string(identifier),+ CanonicalIndexMode::DetectNumericRoundtrip,+ )+ .is_undefined()+}++// https://w3c.github.io/IndexedDB/#check-that-a-key-could-be-injected-into-a-value+pub(crate) fn check_that_a_key_could_be_injected_into_a_value(+ cx: &CallContext,+ mut value: Value,+ key_path: &KeyPath,+) -> bool {+ let vm = cx.vm();++ // NOTE: The key paths used in this section are always strings and never sequences+ let KeyPath::String(key_path) = key_path else {+ unreachable!("the key path is a string");+ };++ // 1. Let identifiers be the result of strictly splitting keyPath on U+002E FULL STOP characters (.).+ let mut identifiers = strictly_split_key_path(key_path);++ // 2. Assert: identifiers is not empty.+ assert!(!identifiers.is_empty());++ // 3. Remove the last item of identifiers.+ let last = identifiers.pop().expect("identifiers is not empty");++ // 4. For each remaining identifier of identifiers, if any:+ for identifier in &identifiers {+ // 1. If value is not an Object or an Array, return false.+ if !(value.is_object() || value.is_array(vm).must()) {+ return false;+ }++ let identifier_property = PropertyKey::from_utf16_string(identifier);++ // 2. Let hop be ! HasOwnProperty(value, identifier).+ let hop = value.as_object().has_own_property(vm, &identifier_property).must();++ // 3. If hop is false, return true.+ if !hop {+ return can_create_data_property(value.as_object(), identifier);+ }++ // 4. Let value be ! Get(value, identifier).+ value = value.as_object().get(vm, &identifier_property).must();+ }++ // 5. Return true if value is an Object or an Array, or false otherwise.+ (value.is_object() || value.is_array(vm).must()) && can_create_data_property(value.as_object(), &last)+}++// https://w3c.github.io/IndexedDB/#fire-an-error-event+pub(crate) fn fire_an_error_event(vm: &Vm, request: AnyIDBRequest) {+ // 1. Let event be the result of creating an event using Event.+ // 2. Set event’s type attribute to "error".+ // 3. Set event’s bubbles and cancelable attributes to true.+ let event = CppEvent::create(request.realm(), "error", true, true, false);++ // 4. Let transaction be request’s transaction.+ let transaction = request.transaction_object().expect("the request has a transaction");++ // 5. Let legacyOutputDidListenersThrowFlag be initially false.+ // 6. If transaction’s state is inactive, then set transaction’s state to active.+ if transaction.state() == TransactionState::Inactive {+ transaction.set_state(TransactionState::Active);+ }++ // 7. Dispatch event at request with legacyOutputDidListenersThrowFlag.+ let legacy_output_did_listeners_throw_flag = request+ .event_target()+ .dispatch_event_with_legacy_output_did_listeners_throw_flag(&event);++ // 8. If transaction’s state is active, then:+ if transaction.state() == TransactionState::Active {+ // 1. Set transaction’s state to inactive.+ transaction.set_state(TransactionState::Inactive);++ // 2. If legacyOutputDidListenersThrowFlag is true, then run abort a transaction with transaction and a newly created "AbortError" DOMException and terminate these steps.+ // This is done even if event’s canceled flag is false.+ if legacy_output_did_listeners_throw_flag {+ abort_a_transaction(+ vm,+ transaction,+ Some(DomException::create(+ "AbortError",+ "Error event interrupted by exception",+ )),+ );+ return;+ }++ // 3. If event’s canceled flag is false, then run abort a transaction using transaction and request's error, and terminate these steps.+ if !event.canceled() {+ abort_a_transaction(vm, transaction, request.error_object());+ return;+ }++ // 4. If transaction’s request list is empty, then run commit a transaction with transaction.+ if transaction.request_list().is_empty() {+ commit_a_transaction(vm, transaction);+ }+ }+}++// https://w3c.github.io/IndexedDB/#fire-a-success-event+pub(crate) fn fire_a_success_event(vm: &Vm, request: AnyIDBRequest) {+ // 1. Let event be the result of creating an event using Event.+ // 2. Set event’s type attribute to "success".+ // 3. Set event’s bubbles and cancelable attributes to false.+ let event = CppEvent::create(request.realm(), "success", false, false, false);++ // 4. Let transaction be request’s transaction.+ let transaction = request.transaction_object().expect("the request has a transaction");++ // 5. Let legacyOutputDidListenersThrowFlag be initially false.+ // 6. If transaction’s state is inactive, then set transaction’s state to active.+ if transaction.state() == TransactionState::Inactive {+ transaction.set_state(TransactionState::Active);+ }++ // 7. Dispatch event at request with legacyOutputDidListenersThrowFlag.+ let legacy_output_did_listeners_throw_flag = request+ .event_target()+ .dispatch_event_with_legacy_output_did_listeners_throw_flag(&event);++ // 8. If transaction’s state is active, then:+ if transaction.state() == TransactionState::Active {+ // 1. Set transaction’s state to inactive.+ transaction.set_state(TransactionState::Inactive);++ // 2. If legacyOutputDidListenersThrowFlag is true, then run abort a transaction with transaction and a newly created "AbortError" DOMException.+ if legacy_output_did_listeners_throw_flag {+ abort_a_transaction(+ vm,+ transaction,+ Some(DomException::create("AbortError", "An error occurred")),+ );+ return;+ }++ // 3. If transaction’s request list is empty, then run commit a transaction with transaction.+ if transaction.request_list().is_empty() {+ commit_a_transaction(vm, transaction);+ }+ }+}++// https://w3c.github.io/IndexedDB/#asynchronously-execute-a-request+pub(crate) fn asynchronously_execute_a_request(+ vm: &Vm,+ source: IDBRequestSource,+ operation: Operation,+ request_input: Option<AnyIDBRequest>,+) -> AnyIDBRequest {+ // 1. Let transaction be the transaction associated with source.+ let transaction = match source {+ IDBRequestSource::Empty => unreachable!("a request with a transaction has a source"),+ IDBRequestSource::ObjectStore(object_store) => object_store.transaction_object(),+ IDBRequestSource::Index(index) => index.transaction_object(),+ IDBRequestSource::Cursor(cursor) => cursor.transaction_object(),+ };++ // AD-HOC: Determine the object store being operated on so that we can get the exact mutation log this+ // operation will be writing to.+ let store = match source {+ IDBRequestSource::Empty => unreachable!("a request with a transaction has a source"),+ IDBRequestSource::ObjectStore(object_store) => object_store.store(),+ IDBRequestSource::Index(index) => index.object_store_handle().store(),+ IDBRequestSource::Cursor(cursor) => cursor.effective_object_store(),+ };++ // 2. Assert: transaction’s state is active.+ assert!(transaction.state() == TransactionState::Active);++ // 3. If request was not given, let request be a new request with source as source.+ let request = request_input.unwrap_or_else(|| {+ AnyIDBRequest::IDBRequest(IDBRequest::create(vm, transaction.connection_object().realm(), source))+ });++ // Set the two-way binding. (Missing spec step)+ // FIXME: https://github.com/w3c/IndexedDB/issues/433+ request.set_transaction(Some(transaction));++ // 4. Add request to the end of transaction’s request list.+ // 5. Run these steps in parallel:+ // 1. Wait until request is the first item in transaction’s request list that is not processed.+ transaction.request_list().enqueue(+ vm,+ request,+ create_function(+ vm,+ (transaction, store, operation, request),+ |vm, &(transaction, store, operation, request), ()| {+ if request.aborted() {+ return;+ }++ // AD-HOC: Determine where the mutation logs for this operation begin in case we need to revert.+ let log_position = store.mutation_log_position();++ // 2. Let result be the result of performing operation.+ let result = perform_operation(vm, operation).map_err(DomException::from_exception);++ // 3. If result is an error and transaction’s state is committing, then run abort a transaction with transaction and result, and terminate these steps.+ if let Err(error) = &result+ && transaction.state() == TransactionState::Committing+ {+ abort_a_transaction(vm, transaction, Some(error.clone()));+ return;+ }++ // 4. If result is an error, then revert all changes made by operation.+ if result.is_err() {+ ObjectStore::revert_mutations_from(store, vm, log_position);+ }++ // 5. Set request’s processed flag to true.+ request.set_processed(true);++ // 6. Queue a database task to run these steps:+ queue_a_database_task(+ vm,+ create_function(+ vm,+ (request, result, transaction),+ |vm, &(request, ref result, transaction), ()| {+ if request.aborted() {+ return;+ }++ // 1. Remove request from transaction’s request list.+ transaction.request_list().remove(vm, request);++ // 2. Set request’s done flag to true.+ request.set_done(true);++ // 3. If result is an error, then:+ match result {+ Err(error) => {+ // 1. Set request’s result to undefined.+ request.set_result(Value::UNDEFINED);++ // 2. Set request’s error to result.+ request.set_error(vm, Some(error.clone()));++ // 3. Fire an error event at request.+ fire_an_error_event(vm, request);+ }+ // 4. Otherwise:+ Ok(value) => {+ // 1. Set request’s result to result.+ request.set_result(*value);++ // 2. Set request’s error to undefined.+ request.set_error(vm, None);++ // 3. Fire a success event at request.+ fire_a_success_event(vm, request);+ }+ }++ // NB: Check if the commit wait is satisfied after firing the result event, so that the commit completion+ // runs after it. This models the parallel nature of the processing according to the spec, where a+ // request being processed necessitates sending a message from the IDB worker thread/process to the+ // main thread (most likely also triggering this task), meaning that the above events will necessarily+ // be fired before the transaction can be committed.+ transaction.request_list().check_all_processed(vm);+ },+ ),+ );++ // Allow the next operation in the queue to proceed. This runs after the above task to ensure that if another+ // request is ready, it will run after the success or failure events are fired. Otherwise, the next request may+ // throw an error and clobber the result of this request.+ transaction.request_list().on_request_processed(vm);+ },+ ),+ );++ // 6. Return request.+ request+}++// https://w3c.github.io/IndexedDB/#inject-a-key-into-a-value-using-a-key-path+pub(crate) fn inject_a_key_into_a_value_using_a_key_path(+ cx: &CallContext,+ mut value: Value,+ key: &Key,+ key_path: &KeyPath,+) {+ let vm = cx.vm();+ let realm = cx.realm();++ let KeyPath::String(key_path) = key_path else {+ unreachable!("the key path of an object store that uses a key generator and in-line keys is a string");+ };++ // 1. Let identifiers be the result of strictly splitting keyPath on U+002E FULL STOP characters (.).+ let mut identifiers = strictly_split_key_path(key_path);++ // 2. Assert: identifiers is not empty.+ assert!(!identifiers.is_empty());++ // 3. Let last be the last item of identifiers and remove it from the list.+ let last = identifiers.pop().expect("identifiers is not empty");++ // 4. For each remaining identifier of identifiers:+ for identifier in &identifiers {+ // 1. Assert: value is an Object or an Array.+ assert!(value.is_object() || value.is_array(vm).must());++ let identifier_property = PropertyKey::from_utf16_string(identifier);++ // 2. Let hop be ! HasOwnProperty(value, identifier).+ let hop = value.as_object().has_own_property(vm, &identifier_property).must();++ // 3. If hop is false, then:+ if !hop {+ // 1. Let o be a new Object created as if by the expression ({}).+ let o = Object::create(vm, realm, Some(realm.intrinsics().object_prototype(vm)));++ // 2. Let status be CreateDataProperty(value, identifier, o).+ let status = value+ .as_object()+ .create_data_property(vm, &identifier_property, Value::from_object(o), None, None)+ .must();++ // 3. Assert: status is true.+ assert!(status);+ }++ // 4. Let value be ! Get(value, identifier).+ value = value.as_object().get(vm, &identifier_property).must();+ }++ // 5. Assert: value is an Object or an Array.+ assert!(value.is_object() || value.is_array(vm).must());++ // 6. Let keyValue be the result of converting a key to a value with key.+ let key_value = convert_a_key_to_a_value(cx, key);++ // 7. Let status be CreateDataProperty(value, last, keyValue).+ let status = value+ .as_object()+ .create_data_property(vm, &PropertyKey::from_utf16_string(&last), key_value, None, None)+ .must();++ // 8. Assert: status is true.+ assert!(status);+}++// https://w3c.github.io/IndexedDB/#delete-records-from-an-object-store+pub(crate) fn delete_records_from_an_object_store(vm: &Vm, store: ObjectStoreRef, range: &IDBKeyRange) -> Value {+ // 1. Remove all records, if any, from store’s list of records with key in range.+ store.remove_records_in_range(vm, range);++ // 2. For each index which references store, remove every record from index’s list of records whose value is in range, if any such records exist.+ for index in store.indexes(vm).values().iter().copied() {+ Index::remove_records_with_value_in_range(index, vm, range);+ }++ // 3. Return undefined.+ Value::UNDEFINED+}++// https://w3c.github.io/IndexedDB/#store-a-record-into-an-object-store+// NB: The steps of storing a record into an object store for one index which references store, as step 5 runs them for+// each such index.+fn store_a_record_into_an_index(cx: &CallContext, index: IndexRef, value: Value, key: &Rc<Key>) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let index key be the result of extracting a key from a value using a key path with value, index’s key path, and index’s multiEntry flag.+ let completion_index_key =+ extract_a_key_from_a_value_using_a_key_path(cx, value, index.key_path(), index.multi_entry());++ // 2. If index key is an exception, or invalid, or failure, take no further actions for index, and continue these steps for the next index.+ let Ok(failure_index_key) = completion_index_key else {+ return Ok(());+ };++ let Ok(index_key) = failure_index_key else {+ return Ok(());+ };++ if index_key.is_invalid() {+ return Ok(());+ }++ let index_multi_entry = index.multi_entry();+ let index_key_is_array = index_key.r#type() == KeyType::Array;+ let index_is_unique = index.unique();++ // 3. If index’s multiEntry flag is false, or if index key is not an array key,+ // and if index already contains a record with key equal to index key,+ // and index’s unique flag is true,+ // then this operation failed with a "ConstraintError" DOMException.+ // Abort this algorithm without taking any further steps.+ if (!index_multi_entry || !index_key_is_array) && index_is_unique && index.has_record_with_key(&index_key) {+ return Err(Exception::Dom(+ "ConstraintError",+ Utf16String::from_utf8("Record already exists in index"),+ ));+ }++ // 4. If index’s multiEntry flag is true and index key is an array key,+ // and if index already contains a record with key equal to any of the subkeys of index key,+ // and index’s unique flag is true,+ // then this operation failed with a "ConstraintError" DOMException.+ // Abort this algorithm without taking any further steps.+ if index_multi_entry && index_key_is_array && index_is_unique {+ for subkey in index_key.subkeys() {+ if index.has_record_with_key(subkey) {+ return Err(Exception::Dom(+ "ConstraintError",+ Utf16String::from_utf8("Record already exists in index"),+ ));+ }+ }+ }++ // 5. If index’s multiEntry flag is false, or if index key is not an array key+ // then store a record in index containing index key as its key and key as its value.+ // The record is stored in index’s list of records such that the list is sorted primarily on the records keys,+ // and secondarily on the records values, in ascending order.+ if !index_multi_entry || !index_key_is_array {+ let index_record = IndexRecord {+ key: index_key.clone(),+ value: key.clone(),+ };+ Index::store_a_record(index, vm, &index_record);+ }++ // 6. If index’s multiEntry flag is true and index key is an array key,+ // then for each subkey of the subkeys of index key store a record in index containing subkey as its key and key as its value.+ // The records are stored in index’s list of records such that the list is sorted primarily on the records keys,+ // and secondarily on the records values, in ascending order.+ if index_multi_entry && index_key_is_array {+ for subkey in index_key.subkeys() {+ let index_record = IndexRecord {+ key: subkey.clone(),+ value: key.clone(),+ };+ Index::store_a_record(index, vm, &index_record);+ }+ }++ Ok(())+}++// https://w3c.github.io/IndexedDB/#store-a-record-into-an-object-store+pub(crate) fn store_a_record_into_an_object_store(+ cx: &CallContext,+ store: ObjectStoreRef,+ value: Value,+ mut key: Option<Rc<Key>>,+ no_overwrite: bool,+) -> WebIdlResult<Option<Rc<Key>>> {+ let vm = cx.vm();++ // 1. If store uses a key generator, then:+ if store.uses_a_key_generator() {+ match &key {+ // 1. If key is undefined, then:+ None => {+ // 1. Let key be the result of generating a key for store.+ let maybe_key = store.generate_a_key(vm);++ // 2. If key is failure, then this operation failed with a "ConstraintError" DOMException. Abort this algorithm without taking any further steps.+ let generated_key = match maybe_key {+ Ok(generated_key) => generated_key,+ Err(error) => return Err(Exception::Dom("ConstraintError", Utf16String::from_utf8(error))),+ };++ #[allow(clippy::cast_precision_loss, reason = "a generated key is at most 2^53")]+ let generated_key = Key::create_number(generated_key as f64);+ key = Some(generated_key.clone());++ // 3. If store also uses in-line keys, then run inject a key into a value using a key path with value, key and store’s key path.+ if store.uses_inline_keys() {+ inject_a_key_into_a_value_using_a_key_path(+ cx,+ value,+ &generated_key,+ store.key_path().expect("the store uses in-line keys"),+ );+ }+ }++ // 2. Otherwise, run possibly update the key generator for store with key.+ Some(key) => {+ store.possibly_update_the_key_generator(vm, key);+ }+ }+ }+ let key = key.expect("the key was given or generated");++ // 2. If the no-overwrite flag was given to these steps and is true, and a record already exists in store with its key equal to key,+ // then this operation failed with a "ConstraintError" DOMException. Abort this algorithm without taking any further steps.+ let has_record = store.has_record_with_key(&key);+ if no_overwrite && has_record {+ return Err(Exception::Dom(+ "ConstraintError",+ Utf16String::from_utf8("Record already exists"),+ ));+ }++ // 3. If a record already exists in store with its key equal to key, then remove the record from store using delete records from an object store.+ if has_record {+ let key_range = IDBKeyRange::create(vm, Some(key.clone()), Some(key.clone()), false, false);+ delete_records_from_an_object_store(vm, store, &key_range);+ }++ // 4. Store a record in store containing key as its key and ! StructuredSerializeForStorage(value) as its value.+ // The record is stored in the object store’s list of records such that the list is sorted according to the key of the records in ascending order.+ let record = ObjectStoreRecord {+ key: key.clone(),+ value: structured_serialize_for_storage(cx, value).must(),+ };+ store.store_a_record(vm, record);++ // 5. For each index which references store:+ for index in store.indexes(vm).values().iter().copied() {+ // AD-HOC: An index whose creation request has not been processed yet gets the records of store once it is.+ if index.is_pending_creation() {+ continue;+ }++ store_a_record_into_an_index(cx, index, value, &key)?;+ }++ // 6. Return key.+ Ok(Some(key))+}++// AD-HOC: The spec deserializes stored records infallibly, but a record read back from storage can be+// corrupt or written by a newer format version, so treat failure as the "error occurs while+// reading the value from the underlying storage" case: a "NotReadableError" DOMException.+fn deserialize_a_stored_record(cx: &CallContext, serialized: &StorageSerializationRecord) -> WebIdlResult<Value> {+ structured_deserialize(cx, serialized).map_err(|_| {+ Exception::Dom(+ "NotReadableError",+ Utf16String::from_utf8("Stored value could not be read"),+ )+ })+}++// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-createindex+// AD-HOC: The index creation itself is processed as an asynchronous request within the upgrade transaction, so the+// index gets the records that its object store has once the requests made before createIndex() are processed.+// If those records violate the index's unique flag, the upgrade transaction is aborted with a "ConstraintError"+// DOMException.+pub(crate) fn queue_the_creation_of_an_index(vm: &Vm, handle: Ref<IDBObjectStore>, index: IndexRef) {+ let realm = handle.realm();+ let transaction = handle.transaction_object();+ index.set_pending_creation(true);++ // NB: The request has no transaction, so that nothing observes it, and the events fired at it if the transaction+ // aborts first go nowhere.+ let request = AnyIDBRequest::IDBRequest(IDBRequest::create(+ vm,+ transaction.connection_object().realm(),+ IDBRequestSource::ObjectStore(handle),+ ));+ transaction.request_list().enqueue(+ vm,+ request,+ create_function(+ vm,+ (realm, transaction, index, request),+ |vm, &(realm, transaction, index, request), ()| {+ if request.aborted() {+ return;+ }++ index.set_pending_creation(false);+ let cx = CallContext::new(vm, realm);+ let store_the_records_into_the_index = || -> WebIdlResult<()> {+ for record in index.object_store().records().iter() {+ let value = deserialize_a_stored_record(&cx, &record.value)?;+ store_a_record_into_an_index(&cx, index, value, &record.key)?;+ }+ Ok(())+ };+ let result = store_the_records_into_the_index();++ request.set_processed(true);++ if let Err(exception) = result {+ abort_a_transaction(vm, transaction, Some(DomException::from_exception(exception)));+ return;+ }++ // NB: Finish up like a request whose success event nobody listens to: the transaction commits once its request+ // list is empty, if it is inactive by then.+ queue_a_database_task(+ vm,+ create_function(vm, (transaction, request), |vm, &(transaction, request), ()| {+ if request.aborted() {+ return;+ }++ transaction.request_list().remove(vm, request);+ if transaction.state() == TransactionState::Inactive && transaction.request_list().is_empty() {+ commit_a_transaction(vm, transaction);+ }+ transaction.request_list().check_all_processed(vm);+ }),+ );++ transaction.request_list().on_request_processed(vm);+ },+ ),+ );+}++// https://w3c.github.io/IndexedDB/#convert-a-value-to-a-key-range+pub(crate) fn convert_a_value_to_a_key_range(+ cx: &CallContext,+ value: Option<Value>,+ null_disallowed: bool,+) -> WebIdlResult<Ref<IDBKeyRange>> {+ // 1. If value is a key range, return value.+ if let Some(value) = value+ && let Some(key_range) = key_range_from_value(value)+ {+ return Ok(key_range);+ }++ // 2. If value is undefined or is null, then throw a "DataError" DOMException if null disallowed flag is true, or return an unbounded key range otherwise.+ let Some(value) = value.filter(|value| !value.is_nullish()) else {+ if null_disallowed {+ return Err(Exception::Dom(+ "DataError",+ Utf16String::from_utf8("Value is undefined or null"),+ ));+ }++ return Ok(IDBKeyRange::create(cx.vm(), None, None, false, false));+ };++ // 3. Let key be the result of converting a value to a key with value. Rethrow any exceptions.+ let key = convert_a_value_to_a_key(cx, value, None)?;++ // 4. If key is "invalid value" or "invalid type", throw a "DataError" DOMException.+ if key.is_invalid() {+ return Err(Exception::Dom("DataError", Utf16String::from_utf8("Value is invalid")));+ }++ // 5. Return a key range containing only key.+ Ok(IDBKeyRange::create(cx.vm(), Some(key.clone()), Some(key), false, false))+}++#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum RecordSource {+ ObjectStore(ObjectStoreRef),+ Index(IndexRef),+}++// https://w3c.github.io/IndexedDB/#count-the-records-in-a-range+pub(crate) fn count_the_records_in_a_range(source: RecordSource, range: &IDBKeyRange) -> Value {+ // 1. Let count be the number of records, if any, in source’s list of records with key in range.+ let count = match source {+ RecordSource::ObjectStore(object_store) => object_store.count_records_in_range(range),+ RecordSource::Index(index) => index.count_records_in_range(range),+ };++ // 2. Return count.+ #[allow(clippy::cast_precision_loss, reason = "a count of records is less than 2^53")]+ Value::from_f64(count as f64)+}++// https://w3c.github.io/IndexedDB/#retrieve-a-value-from-an-object-store+pub(crate) fn retrieve_a_value_from_an_object_store(+ cx: &CallContext,+ store: ObjectStoreRef,+ range: &IDBKeyRange,+) -> WebIdlResult<Value> {+ // 1. Let record be the first record in store’s list of records whose key is in range, if any.+ let record = store.first_in_range(range);++ // 2. If record was not found, return undefined.+ let Some(record) = record else {+ return Ok(Value::UNDEFINED);+ };++ // 3. Let serialized be record’s value. If an error occurs while reading the value from the underlying storage, return a newly created "NotReadableError" DOMException.+ let serialized = &record.value;++ // 4. Return ! StructuredDeserialize(serialized, targetRealm).+ deserialize_a_stored_record(cx, serialized)+}++#[derive(Clone)]+enum FoundRecord {+ ObjectStore(ObjectStoreRecord),+ Index(IndexRecord),+}++impl FoundRecord {+ fn key(&self) -> &Rc<Key> {+ match self {+ Self::ObjectStore(record) => &record.key,+ Self::Index(record) => &record.key,+ }+ }+}++#[derive(Clone, Copy)]+enum RecordInList<'a> {+ ObjectStore(&'a ObjectStoreRecord),+ Index(&'a IndexRecord),+}++impl RecordInList<'_> {+ fn key(&self) -> &Key {+ match self {+ Self::ObjectStore(record) => &record.key,+ Self::Index(record) => &record.key,+ }+ }++ fn index_record(&self) -> &IndexRecord {+ match self {+ Self::Index(record) => record,+ Self::ObjectStore(_) => unreachable!("the source of the cursor is an index"),+ }+ }++ fn to_found_record(self) -> FoundRecord {+ match self {+ Self::ObjectStore(record) => FoundRecord::ObjectStore(record.clone()),+ Self::Index(record) => FoundRecord::Index(record.clone()),+ }+ }+}++// https://w3c.github.io/IndexedDB/#iterate-a-cursor+pub(crate) fn iterate_a_cursor(+ cx: &CallContext,+ cursor: AnyIDBCursor,+ key: Option<Rc<Key>>,+ primary_key: Option<Rc<Key>>,+ mut count: u64,+) -> WebIdlResult<Option<AnyIDBCursor>> {+ // 1. Let source be cursor’s source.+ let source = cursor.internal_source();++ // 2. Let direction be cursor’s direction.+ let direction = cursor.direction_value();++ // 3. Assert: if primaryKey is given, source is an index and direction is "next" or "prev".+ let direction_is_next_or_prev = direction == IDBCursorDirection::Next || direction == IDBCursorDirection::Prev;+ if primary_key.is_some() {+ assert!(matches!(source, RecordSource::Index(_)) && direction_is_next_or_prev);+ }++ // 4. Let records be the list of records in source.+ // NB: The records are borrowed from the source below, while they are searched.++ // 5. Let range be cursor’s range.+ let range = cursor.range();++ // 6. Let position be cursor’s position.+ let mut position = cursor.position();++ // 7. Let object store position be cursor’s object store position.+ let mut object_store_position = cursor.object_store_position();++ // 8. If count is not given, let count be 1.+ // NOTE: This is handled by the default parameter++ let source_is_object_store = matches!(source, RecordSource::ObjectStore(_));+ let source_is_index = matches!(source, RecordSource::Index(_));++ let next_requirements =+ |record: RecordInList<'_>, position: &Option<Rc<Key>>, object_store_position: &Option<Rc<Key>>| -> bool {+ // * If key is defined:+ if let Some(key) = &key {+ // * The record’s key is greater than or equal to key.+ if !Key::greater_than_or_equal(record.key(), key) {+ return false;+ }+ }++ // * If primaryKey is defined:+ if let Some(primary_key) = &primary_key {+ let inner_record = record.index_record();+ let key = key.as_ref().expect("primaryKey is given with key");++ // * The record’s key is equal to key and the record’s value is greater than or equal to primaryKey+ if Key::equals(&inner_record.key, key) {+ if !Key::greater_than_or_equal(&inner_record.value, primary_key) {+ return false;+ }+ }+ // * The record’s key is greater than key.+ else if !Key::greater_than(&inner_record.key, key) {+ return false;+ }+ }++ // * If position is defined and source is an object store:+ if let Some(position) = position+ && source_is_object_store+ {+ // * The record’s key is greater than position.+ if !Key::greater_than(record.key(), position) {+ return false;+ }+ }++ // * If position is defined and source is an index:+ if let Some(position) = position+ && source_is_index+ {+ let inner_record = record.index_record();+ let object_store_position = object_store_position+ .as_ref()+ .expect("a cursor of an index with a position has an object store position");++ // * The record’s key is equal to position and the record’s value is greater than object store position+ if Key::equals(&inner_record.key, position) {+ if !Key::greater_than(&inner_record.value, object_store_position) {+ return false;+ }+ }+ // * The record’s key is greater than position.+ else if !Key::greater_than(&inner_record.key, position) {+ return false;+ }+ }++ // * The record’s key is in range.+ range.is_in_range(record.key())+ };++ let next_unique_requirements = |record: RecordInList<'_>, position: &Option<Rc<Key>>| -> bool {+ // * If key is defined:+ if let Some(key) = &key {+ // * The record’s key is greater than or equal to key.+ if !Key::greater_than_or_equal(record.key(), key) {+ return false;+ }+ }++ // * If position is defined:+ if let Some(position) = position {+ // * The record’s key is greater than position.+ if !Key::greater_than(record.key(), position) {+ return false;+ }+ }++ // * The record’s key is in range.+ range.is_in_range(record.key())+ };++ let prev_requirements =+ |record: RecordInList<'_>, position: &Option<Rc<Key>>, object_store_position: &Option<Rc<Key>>| -> bool {+ // * If key is defined:+ if let Some(key) = &key {+ // * The record’s key is less than or equal to key.+ if !Key::less_than_or_equal(record.key(), key) {+ return false;+ }+ }++ // * If primaryKey is defined:+ if let Some(primary_key) = &primary_key {+ let inner_record = record.index_record();+ let key = key.as_ref().expect("primaryKey is given with key");++ // * The record’s key is equal to key and the record’s value is less than or equal to primaryKey+ if Key::equals(&inner_record.key, key) {+ if !Key::less_than_or_equal(&inner_record.value, primary_key) {+ return false;+ }+ }+ // * The record’s key is less than key.+ else if !Key::less_than(&inner_record.key, key) {+ return false;+ }+ }++ // * If position is defined and source is an object store:+ if let Some(position) = position+ && source_is_object_store+ {+ // * The record’s key is less than position.+ if !Key::less_than(record.key(), position) {+ return false;+ }+ }++ // * If position is defined and source is an index:+ if let Some(position) = position+ && source_is_index+ {+ let inner_record = record.index_record();+ let object_store_position = object_store_position+ .as_ref()+ .expect("a cursor of an index with a position has an object store position");++ // * The record’s key is equal to position and the record’s value is less than object store position+ if Key::equals(&inner_record.key, position) {+ if !Key::less_than(&inner_record.value, object_store_position) {+ return false;+ }+ }+ // * The record’s key is less than position.+ else if !Key::less_than(&inner_record.key, position) {+ return false;+ }+ }++ // * The record’s key is in range.+ range.is_in_range(record.key())+ };++ let prev_unique_requirements = |record: RecordInList<'_>, position: &Option<Rc<Key>>| -> bool {+ // * If key is defined:+ if let Some(key) = &key {+ // * The record’s key is less than or equal to key.+ if !Key::less_than_or_equal(record.key(), key) {+ return false;+ }+ }++ // * If position is defined:+ if let Some(position) = position {+ // * The record’s key is less than position.+ if !Key::less_than(record.key(), position) {+ return false;+ }+ }++ // * The record’s key is in range.+ range.is_in_range(record.key())+ };++ let records_of_source = |search: &mut dyn FnMut(+ &mut dyn DoubleEndedIterator<Item = RecordInList<'_>>,+ ) -> Option<FoundRecord>|+ -> Option<FoundRecord> {+ match source {+ RecordSource::ObjectStore(object_store) => {+ let records = object_store.records();+ search(&mut records.iter().map(RecordInList::ObjectStore))+ }+ RecordSource::Index(index) => {+ let records = index.records();+ search(&mut records.iter().map(RecordInList::Index))+ }+ }+ };++ // 9. While count is greater than 0:+ let mut found_record: Option<FoundRecord> = None;+ while count > 0 {+ // 1. Switch on direction:+ match direction {+ IDBCursorDirection::Next => {+ // Let found record be the first record in records which satisfy all of the following requirements:+ found_record = records_of_source(&mut |mut records| {+ Iterator::find(&mut records, |record| {+ next_requirements(*record, &position, &object_store_position)+ })+ .map(RecordInList::to_found_record)+ });+ }+ IDBCursorDirection::Nextunique => {+ // Let found record be the first record in records which satisfy all of the following requirements:+ found_record = records_of_source(&mut |mut records| {+ Iterator::find(&mut records, |record| next_unique_requirements(*record, &position))+ .map(RecordInList::to_found_record)+ });+ }+ IDBCursorDirection::Prev => {+ // Let found record be the last record in records which satisfy all of the following requirements:+ found_record = records_of_source(&mut |records| {+ records+ .rev()+ .find(|record| prev_requirements(*record, &position, &object_store_position))+ .map(RecordInList::to_found_record)+ });+ }+ IDBCursorDirection::Prevunique => {+ // Let temp record be the last record in records which satisfy all of the following requirements:+ let temp_record = records_of_source(&mut |records| {+ records+ .rev()+ .find(|record| prev_unique_requirements(*record, &position))+ .map(RecordInList::to_found_record)+ });++ // If temp record is defined, let found record be the first record in records whose key is equal to temp record’s key.+ found_record = None;+ if let Some(temp_record) = temp_record {+ let temp_record_key = temp_record.key().clone();++ found_record = records_of_source(&mut |mut records| {+ Iterator::find(&mut records, |content_record| {+ Key::equals(content_record.key(), &temp_record_key)+ })+ .map(RecordInList::to_found_record)+ });+ }+ }+ }++ // 2. If found record is not defined, then:+ let Some(found) = &found_record else {+ // 1. Set cursor’s key to undefined.+ cursor.set_key(None);++ // 2. If source is an index, set cursor’s object store position to undefined.+ if source_is_index {+ cursor.set_object_store_position(None);+ }++ // 3. If cursor’s key only flag is false, set cursor’s value to undefined.+ if !cursor.key_only() {+ cursor.set_value(Some(Value::UNDEFINED));+ }++ // 4. Return null.+ return Ok(None);+ };++ // 3. Let position be found record’s key.+ position = Some(found.key().clone());++ // 4. If source is an index, let object store position be found record’s value.+ if let FoundRecord::Index(record) = found {+ object_store_position = Some(record.value.clone());+ }++ // 5. Decrease count by 1.+ count -= 1;+ }+ let found_record = found_record.expect("a record was found");++ // 10. Set cursor’s position to position.+ cursor.set_position(position);++ // 11. If source is an index, set cursor’s object store position to object store position.+ if source_is_index {+ cursor.set_object_store_position(object_store_position);+ }++ // 12. Set cursor’s key to found record’s key.+ cursor.set_key(Some(found_record.key().clone()));++ // 13. If cursor’s key only flag is false, then:+ if !cursor.key_only() {+ // 1. Let serialized be found record’s value if source is an object store, or found record’s referenced value otherwise.+ let serialized = match (&found_record, source) {+ (FoundRecord::ObjectStore(record), _) => record.value.clone(),+ (FoundRecord::Index(record), RecordSource::Index(index)) => index.referenced_value(record),+ (FoundRecord::Index(_), RecordSource::ObjectStore(_)) => {+ unreachable!("a record of an index is found in an index")+ }+ };++ // 2. Set cursor’s value to ! StructuredDeserialize(serialized, targetRealm)+ cursor.set_value(Some(deserialize_a_stored_record(cx, &serialized)?));+ }++ // 14. Set cursor’s got value flag to true.+ cursor.set_got_value(true);++ // 15. Return cursor.+ Ok(Some(cursor))+}++// https://w3c.github.io/IndexedDB/#clear-an-object-store+pub(crate) fn clear_an_object_store(vm: &Vm, store: ObjectStoreRef) -> Value {+ // 1. Remove all records from store.+ store.clear_records(vm);++ // 2. In all indexes which reference store, remove all records.+ for index in store.indexes(vm).values().iter().copied() {+ Index::clear_records(index, vm);+ }++ // 3. Return undefined.+ Value::UNDEFINED+}++// https://w3c.github.io/IndexedDB/#retrieve-a-key-from-an-object-store+pub(crate) fn retrieve_a_key_from_an_object_store(+ cx: &CallContext,+ store: ObjectStoreRef,+ range: &IDBKeyRange,+) -> Value {+ // 1. Let record be the first record in store’s list of records whose key is in range, if any.+ let record = store.first_in_range(range);++ // 2. If record was not found, return undefined.+ let Some(record) = record else {+ return Value::UNDEFINED;+ };++ // 3. Return the result of converting a key to a value with record’s key.+ convert_a_key_to_a_value(cx, &record.key)+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum RecordKind {+ Key,+ Value,+ Record,+}++// https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-object-store+pub(crate) fn retrieve_multiple_items_from_an_object_store(+ cx: &CallContext,+ store: ObjectStoreRef,+ range: &IDBKeyRange,+ kind: RecordKind,+ direction: IDBCursorDirection,+ mut count: Option<u32>,+) -> WebIdlResult<Gc<Array>> {+ let vm = cx.vm();++ // 1. If count is not given or is 0 (zero), let count be infinity.+ if count == Some(0) {+ count = None;+ }++ // 2. Let records be an empty list of records.+ let mut records = Vec::new();++ // 3. If direction is "next" or "nextunique", set records to the first count of store’s list of records whose key is in range.+ if direction == IDBCursorDirection::Next || direction == IDBCursorDirection::Nextunique {+ records.extend(store.first_n_in_range(range, count));+ }++ // 4. If direction is "prev" or "prevunique", set records to the last count of store’s list of records whose key is in range.+ if direction == IDBCursorDirection::Prev || direction == IDBCursorDirection::Prevunique {+ records.extend(store.last_n_in_range(range, count));+ }++ // 5. Let list be an empty list.+ let list = Array::create(vm, cx.realm(), records.len() as u64, None).must();++ // 6. For each record of records, switching on kind:+ for (i, record) in records.iter().enumerate() {+ let property_key = PropertyKey::from_number(i as u64);+ match kind {+ RecordKind::Key => {+ // 1. Let key be the result of converting a key to a value with record’s key.+ let key = convert_a_key_to_a_value(cx, &record.key);++ // 2. Append key to list.+ list.create_data_property_or_throw(vm, &property_key, key).must();+ }+ RecordKind::Value => {+ // 1. Let serialized be record’s value.+ let serialized = &record.value;++ // 2. Let value be ! StructuredDeserialize(serialized, targetRealm).+ let entry = deserialize_a_stored_record(cx, serialized)?;++ // 3. Append value to list.+ list.create_data_property_or_throw(vm, &property_key, entry).must();+ }+ RecordKind::Record => {+ // 1. Let key be the record’s key.+ let key = record.key.clone();++ // 2. Let serialized be record’s value.+ let serialized = &record.value;++ // 3. Let value be ! StructuredDeserialize(serialized, targetRealm).+ let value = deserialize_a_stored_record(cx, serialized)?;++ // 4. Let recordSnapshot be a new record snapshot with its key set to key, value set to value, and primary key set to key.+ let record_snapshot = IDBRecord::create(vm, key.clone(), value, key);++ // 5. Append recordSnapshot to list.+ list.create_data_property_or_throw(vm, &property_key, record_snapshot.to_js(cx)?)+ .must();+ }+ }+ }++ // 7. Return list.+ Ok(list)+}++// https://w3c.github.io/IndexedDB/#retrieve-a-referenced-value-from-an-index+pub(crate) fn retrieve_a_referenced_value_from_an_index(+ cx: &CallContext,+ index: IndexRef,+ range: &IDBKeyRange,+) -> WebIdlResult<Value> {+ // 1. Let record be the first record in index’s list of records whose key is in range, if any.+ let record = index.first_in_range(range);++ // 2. If record was not found, return undefined.+ let Some(record) = record else {+ return Ok(Value::UNDEFINED);+ };++ // 3. Let serialized be record’s referenced value.+ let serialized = index.referenced_value(&record);++ // 4. Return ! StructuredDeserialize(serialized, targetRealm).+ deserialize_a_stored_record(cx, &serialized)+}++// https://w3c.github.io/IndexedDB/#retrieve-a-value-from-an-index+pub(crate) fn retrieve_a_value_from_an_index(cx: &CallContext, index: IndexRef, range: &IDBKeyRange) -> Value {+ // 1. Let record be the first record in index’s list of records whose key is in range, if any.+ let record = index.first_in_range(range);++ // 2. If record was not found, return undefined.+ let Some(record) = record else {+ return Value::UNDEFINED;+ };++ // 3. Return the result of converting a key to a value with record’s value.+ convert_a_key_to_a_value(cx, &record.value)+}++// https://w3c.github.io/IndexedDB/#queue-a-database-task+pub(crate) fn queue_a_database_task(vm: &Vm, steps: Function) {+ // To queue a database task, perform queue a task on the database access task source.+ crate::indexed_db::cpp::queue_a_task_on_the_database_access_task_source(vm, steps);+}++// https://w3c.github.io/IndexedDB/#cleanup-indexed-database-transactions+pub(crate) fn cleanup_indexed_database_transactions(vm: &Vm, event_loop: &CppCell) -> bool {+ let mut has_matching_event_loop = false;++ Database::for_each_database(vm, |database| {+ for connection in database.associated_connections(vm).values().iter() {+ for transaction in connection.transactions(vm).values().iter() {+ let transaction = *transaction;++ // 2. For each transaction transaction with cleanup event loop matching the current event loop:+ if transaction.cleanup_event_loop() == Some(event_loop.as_ptr()) {+ has_matching_event_loop = true;++ // 1. Set transaction’s state to inactive.+ assert!(transaction.state() == TransactionState::Active);+ transaction.set_state(TransactionState::Inactive);++ // https://w3c.github.io/IndexedDB/#transaction-commit+ // The implementation must attempt to commit an inactive transaction when all requests placed+ // against the transaction have completed and their returned results handled, no new requests have+ // been placed against the transaction, and the transaction has not been aborted++ // FIXME: We skip committing if the transaction is waiting for prior writes.+ // Update the steps here text if this becomes explicit in the spec:+ // https://github.com/w3c/IndexedDB/issues/489#issuecomment-3994928473+ if !transaction.request_list().execution_is_blocked() && transaction.request_list().is_empty() {+ commit_a_transaction(vm, transaction);+ }++ // 2. Clear transaction’s cleanup event loop.+ transaction.set_cleanup_event_loop(vm, None);+ }+ }+ }+ });++ // 1. If there are no transactions with cleanup event loop matching the current event loop, return false.+ // 3. Return true.+ has_matching_event_loop+}++// https://w3c.github.io/IndexedDB/#is-a-potentially-valid-key-range+pub(crate) fn is_a_potentially_valid_key_range(cx: &CallContext, value: Value) -> bool {+ // 1. If value is a key range, return true.+ if key_range_from_value(value).is_some() {+ return true;+ }++ // 2. Let key be the result of converting a value to a key with value.+ // 3. If key is "invalid type" return false.+ // 4. Else return true.+ // AD-HOC: The type of value is checked instead, which is what decides whether the conversion returns+ // "invalid type", so that the getters of an array's elements do not run twice.+ if value.is_number() || value.is_string() {+ return true;+ }+ if value.is_object() && value.as_object().downcast::<Date>().is_some() {+ return true;+ }+ if buffer_source_type_of(value).is_some() {+ return true;+ }+ if value.is_object() && value.is_array(cx.vm()).must() {+ return true;+ }+ false+}++// https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-index+pub(crate) fn retrieve_multiple_items_from_an_index(+ target_cx: &CallContext,+ index: IndexRef,+ range: &IDBKeyRange,+ kind: RecordKind,+ direction: IDBCursorDirection,+ mut count: Option<u32>,+) -> WebIdlResult<Gc<Array>> {+ let vm = target_cx.vm();++ // 1. If count is not given or is 0 (zero), let count be infinity.+ if count == Some(0) {+ count = None;+ }++ // 2. Let records be an empty list of records.+ let mut records: Vec<IndexRecord> = Vec::new();++ // 3. Switching on direction:+ match direction {+ // "next"+ IDBCursorDirection::Next => {+ // 1. Set records to the first count of index’s list of records whose key is in range.+ records.extend(index.first_n_in_range(range, count));+ }+ // "nextunique"+ IDBCursorDirection::Nextunique => {+ // 1. Let rangeRecords be a list containing the index’s list of records whose key is in range.+ let range_records = index.first_n_in_range(range, None);++ // 2. Let rangeRecordsLength be rangeRecords’s size.+ let range_records_length = range_records.len();++ // 3. Let i be 0.+ let mut i = 0;++ // x. Append |rangeRecords[0]| to records.+ // FIXME: https://github.com/w3c/IndexedDB/issues/480+ if range_records_length > 0 {+ records.push(range_records[0].clone());+ }++ // 4. While i is less than rangeRecordsLength, then:+ while i + 1 < range_records_length {+ // 1. Increase i by 1.+ i += 1;++ // 2. if record’s size is equal to count, then break.+ if count.is_some_and(|count| records.len() == count as usize) {+ break;+ }++ // 3. If the result of comparing two keys using the keys from |rangeRecords[i]| and |rangeRecords[i-1]| is equal, then continue.+ if Key::equals(&range_records[i].key, &range_records[i - 1].key) {+ continue;+ }++ // 4. Else append |rangeRecords[i]| to records.+ records.push(range_records[i].clone());+ }+ }+ // "prev"+ IDBCursorDirection::Prev => {+ // 1. Set records to the last count of index’s list of records whose key is in range.+ records.extend(index.last_n_in_range(range, count));+ }+ // "prevunique"+ IDBCursorDirection::Prevunique => {+ // 1. Let rangeRecords be a list containing the index’s list of records whose key is in range.+ let range_records = index.first_n_in_range(range, None);++ // 2. Let rangeRecordsLength be rangeRecords’s size.+ let range_records_length = range_records.len();++ // 3. Let i be 0.+ let mut i = 0;++ // x. Append |rangeRecords[0]| to records.+ // FIXME: https://github.com/w3c/IndexedDB/issues/480+ if range_records_length > 0 {+ records.push(range_records[0].clone());+ }++ // 4. While i is less than rangeRecordsLength, then:+ while i + 1 < range_records_length {+ // 1. Increase i by 1.+ i += 1;++ // 2. if record’s size is equal to count, then break.+ if count.is_some_and(|count| records.len() == count as usize) {+ break;+ }++ // 3. If the result of comparing two keys using the keys from |rangeRecords[i]| and |rangeRecords[i-1]| is equal, then continue.+ if Key::equals(&range_records[i].key, &range_records[i - 1].key) {+ continue;+ }++ // 4. Else prepend |rangeRecords[i]| to records.+ records.insert(0, range_records[i].clone());+ }+ }+ }++ // 4. Let list be an empty list.+ let list = Array::create(vm, target_cx.realm(), records.len() as u64, None).must();++ // 5. For each record of records, switching on kind:+ for (i, record) in records.iter().enumerate() {+ let property_key = PropertyKey::from_number(i as u64);+ match kind {+ // "key"+ RecordKind::Key => {+ // 1. Let key be the result of converting a key to a value with record’s value.+ let key = convert_a_key_to_a_value(target_cx, &record.value);++ // 2. Append key to list.+ list.create_data_property_or_throw(vm, &property_key, key).must();+ }+ // "value"+ RecordKind::Value => {+ // 1. Let serialized be record’s referenced value.+ let serialized = index.referenced_value(record);++ // 2. Let value be ! StructuredDeserialize(serialized, targetRealm).+ let value = deserialize_a_stored_record(target_cx, &serialized)?;++ // 3. Append value to list.+ list.create_data_property_or_throw(vm, &property_key, value).must();+ }++ // "record"+ RecordKind::Record => {+ // 1. Let index key be the record’s key.+ let index_key = record.key.clone();++ // 2. Let key be the record’s value.+ let key = record.value.clone();++ // 3. Let serialized be record’s referenced value.+ let serialized = index.referenced_value(record);++ // 4. Let value be ! StructuredDeserialize(serialized, targetRealm).+ let value = deserialize_a_stored_record(target_cx, &serialized)?;++ // 5. Let recordSnapshot be a new record snapshot with its key set to index key, value set to value, and primary key set to key.+ let record_snapshot = IDBRecord::create(vm, index_key, value, key);++ // 6. Append recordSnapshot to list.+ list.create_data_property_or_throw(vm, &property_key, record_snapshot.to_js(target_cx)?)+ .must();+ }+ }+ }++ // 6. Return list.+ Ok(list)+}++fn source_of_source_handle(source_handle: IDBRequestSource) -> (RecordSource, Ref<IDBTransaction>) {+ // 1. Let source be an index or an object store from sourceHandle.+ // If sourceHandle is an index handle, then source is the index handle’s associated index.+ // Otherwise, source is the object store handle’s associated object store.+ // 4. Let transaction be sourceHandle’s transaction.+ match source_handle {+ IDBRequestSource::Index(index) => (RecordSource::Index(index.index()), index.transaction_object()),+ IDBRequestSource::ObjectStore(object_store) => (+ RecordSource::ObjectStore(object_store.store()),+ object_store.transaction_object(),+ ),+ IDBRequestSource::Empty | IDBRequestSource::Cursor(_) => {+ unreachable!("the source handle is an index handle or an object store handle")+ }+ }+}++fn retrieve_multiple_items_operation(+ vm: &Vm,+ realm: Gc<Realm>,+ source: RecordSource,+ range: Ref<IDBKeyRange>,+ kind: RecordKind,+ direction: IDBCursorDirection,+ count: Option<u32>,+) -> Operation {+ match source {+ // 11. If source is an index, set operation to retrieve multiple items from an index with targetRealm, source, range, kind, direction, and count if given.+ RecordSource::Index(index) => create_operation(+ vm,+ (realm, index, range, NoCells(kind), NoCells(direction), count),+ |vm, &(realm, index, range, ref kind, ref direction, count)| {+ let cx = CallContext::new(vm, realm);+ Ok(Value::from_object(retrieve_multiple_items_from_an_index(+ &cx,+ index,+ &range,+ kind.0,+ direction.0,+ count,+ )?))+ },+ ),+ // 12. Else set operation to retrieve multiple items from an object store with targetRealm, source, range, kind, direction, and count if given.+ RecordSource::ObjectStore(object_store) => create_operation(+ vm,+ (realm, object_store, range, NoCells(kind), NoCells(direction), count),+ |vm, &(realm, object_store, range, ref kind, ref direction, count)| {+ let cx = CallContext::new(vm, realm);+ Ok(Value::from_object(retrieve_multiple_items_from_an_object_store(+ &cx,+ object_store,+ &range,+ kind.0,+ direction.0,+ count,+ )?))+ },+ ),+ }+}++// https://w3c.github.io/IndexedDB/#create-a-request-to-retrieve-multiple-items+pub(crate) fn create_a_request_to_retrieve_multiple_items(+ cx: &CallContext,+ source_handle: IDBRequestSource,+ kind: RecordKind,+ query_or_options: Value,+ mut count: Option<u32>,+) -> WebIdlResult<AnyIDBRequest> {+ let vm = cx.vm();++ // 1. Let source be an index or an object store from sourceHandle.+ // If sourceHandle is an index handle, then source is the index handle’s associated index.+ // Otherwise, source is the object store handle’s associated object store.+ let (source, transaction) = source_of_source_handle(source_handle);++ // 2. If source has been deleted, throw an "InvalidStateError" DOMException.+ // 3. If source is an index and source’s object store has been deleted, throw an "InvalidStateError" DOMException.+ let is_source_or_object_store_deleted = match source {+ RecordSource::ObjectStore(object_store) => object_store.is_deleted(),+ RecordSource::Index(index) => index.is_deleted() || index.object_store().is_deleted(),+ };+ if is_source_or_object_store_deleted {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8("Source or its object store has been deleted"),+ ));+ }++ // 4. Let transaction be sourceHandle’s transaction.+ // NB: source_of_source_handle() found the transaction with the source.++ // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(Exception::Dom(+ "TransactionInactiveError",+ Utf16String::from_utf8("Transaction is not active while creating retrieve multiple items request"),+ ));+ }++ // 6. Let range be a key range.+ let range;++ // 7. Let direction be a cursor direction.+ let mut direction = IDBCursorDirection::Next;++ // 8. If running is a potentially valid key range with queryOrOptions is true, then:+ // AD-HOC: Check if query_or_options is null following https://github.com/w3c/IndexedDB/issues/475+ if query_or_options.is_nullish() || is_a_potentially_valid_key_range(cx, query_or_options) {+ // 1. Set range to the result of converting a value to a key range with queryOrOptions. Rethrow any exceptions.+ range = convert_a_value_to_a_key_range(cx, Some(query_or_options), false)?;++ // 2. Set direction to "next".+ direction = IDBCursorDirection::Next;+ }+ // 9. Else:+ else {+ // 1. Set range to the result of converting a value to a key range with queryOrOptions["query"]. Rethrow any exceptions.+ range = convert_a_value_to_a_key_range(+ cx,+ Some(query_or_options.get(vm, &PropertyKey::from_utf8("query"))?),+ false,+ )?;++ // 2. Set count to queryOrOptions["count"].+ count = Some(query_or_options.get(vm, &PropertyKey::from_utf8("count"))?.to_u32(vm)?);++ // 3. Set direction to queryOrOptions["direction"].+ let direction_value = query_or_options+ .get(vm, &PropertyKey::from_utf8("direction"))?+ .to_utf16_string(vm)?;+ if direction_value == Utf16String::from_utf8("next") {+ direction = IDBCursorDirection::Next;+ } else if direction_value == Utf16String::from_utf8("nextunique") {+ direction = IDBCursorDirection::Nextunique;+ } else if direction_value == Utf16String::from_utf8("prev") {+ direction = IDBCursorDirection::Prev;+ } else if direction_value == Utf16String::from_utf8("prevunique") {+ direction = IDBCursorDirection::Prevunique;+ }+ }++ // 10. Let operation be an algorithm to run.+ let operation = retrieve_multiple_items_operation(vm, cx.realm(), source, range, kind, direction, count);++ // 13. Return the result (an IDBRequest) of running asynchronously execute a request with sourceHandle and operation.+ Ok(asynchronously_execute_a_request(vm, source_handle, operation, None))+}++// https://w3c.github.io/IndexedDB/#create-a-request-to-retrieve-multiple-items+pub(crate) fn create_a_request_to_retrieve_multiple_items_with_options(+ cx: &CallContext,+ source_handle: IDBRequestSource,+ kind: RecordKind,+ options: &IDBGetAllOptions,+) -> WebIdlResult<AnyIDBRequest> {+ let vm = cx.vm();++ // 1. Let source be an index or an object store from sourceHandle.+ // If sourceHandle is an index handle, then source is the index handle’s associated index.+ // Otherwise, source is the object store handle’s associated object store.+ let (source, transaction) = source_of_source_handle(source_handle);++ // 2. If source has been deleted, throw an "InvalidStateError" DOMException.+ // 3. If source is an index and source’s object store has been deleted, throw an "InvalidStateError" DOMException.+ let is_source_or_object_store_deleted = match source {+ RecordSource::ObjectStore(object_store) => object_store.is_deleted(),+ RecordSource::Index(index) => index.is_deleted() || index.object_store().is_deleted(),+ };+ if is_source_or_object_store_deleted {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8("Source or its object store has been deleted"),+ ));+ }++ // 4. Let transaction be sourceHandle’s transaction.+ // NB: source_of_source_handle() found the transaction with the source.++ // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.+ if !transaction.is_active() {+ return Err(Exception::Dom(+ "TransactionInactiveError",+ Utf16String::from_utf8("Transaction is not active while creating retrieve multiple items request"),+ ));+ }++ // 6. Let range be a key range.+ let range = convert_a_value_to_a_key_range(cx, Some(options.query), false)?;++ // 10. Let operation be an algorithm to run.+ let operation =+ retrieve_multiple_items_operation(vm, cx.realm(), source, range, kind, options.direction, options.count);++ // 13. Return the result (an IDBRequest) of running asynchronously execute a request with sourceHandle and operation.+ Ok(asynchronously_execute_a_request(vm, source_handle, operation, None))+}++pub(crate) fn convert_a_key_path_to_a_value(cx: &CallContext, key_path: &KeyPath) -> Value {+ let vm = cx.vm();+ match key_path {+ KeyPath::String(value) => Value::from_string(PrimitiveString::create(vm, value.clone())),+ KeyPath::Sequence(values) => {+ let list = MarkedVec::with_capacity(vm, values.len());+ for entry in values {+ list.push(Value::from_string(PrimitiveString::create(vm, entry.clone())));+ }+ Value::from_object(Array::create_from_list(vm, cx.realm(), &list))+ }+ }+}++pub(crate) fn set_idb_request_result(vm: &Vm, realm: Gc<Realm>, request: AnyIDBRequest, database: Ref<IDBDatabase>) {+ let cx = CallContext::new(vm, realm);+ request.set_result(database.to_js(&cx).must());+}++/// The value of a special key path property of a Blob or a File, https://w3c.github.io/IndexedDB/#key-path-construct+fn key_path_value_for_blob_or_file(cx: &CallContext, value: Value, identifier: &Utf16String) -> Option<Value> {+ if !value.is_object() {+ return None;+ }+ let object = value.as_object();+ if !is_host_instance_of(&object, Blob::wrapper_class()) {+ return None;+ }+ let blob = match implementation_if::<Blob>(object) {+ Some(blob) => AnyBlob::Blob(blob),+ None => AnyBlob::File(implementation_of::<File>(object)),+ };+ if *identifier == Utf16String::from_utf8("size") {+ #[allow(+ clippy::cast_precision_loss,+ reason = "the C++ converted the size to a double as well"+ )]+ return Some(Value::from_f64(blob.raw_bytes().len() as f64));+ }+ if *identifier == Utf16String::from_utf8("type") {+ return Some(Value::from_string(PrimitiveString::create(+ cx.vm(),+ blob.type_string().clone(),+ )));+ }++ if let AnyBlob::File(file) = blob {+ if *identifier == Utf16String::from_utf8("name") {+ return Some(Value::from_string(PrimitiveString::create(+ cx.vm(),+ file.name_string().clone(),+ )));+ }+ if *identifier == Utf16String::from_utf8("lastModified") {+ #[allow(+ clippy::cast_precision_loss,+ reason = "the C++ converted the time to a double as well"+ )]+ return Some(Value::from_f64(file.last_modified_value() as f64));+ }+ }++ None+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/database.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/database.rsnew file mode 100644index 00000000000..5df403b6636--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/database.rs@@ -0,0 +1,224 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Databases, https://w3c.github.io/IndexedDB/#database-construct, and the connections associated with them++use core::cell::{Cell, RefCell};++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, GcWeak, MarkedVec, Trace, Vm};++use crate::bindings::interface::Ref;+use crate::indexed_db::idb_database::{ConnectionState, IDBDatabase};+use crate::indexed_db::idb_transaction::IDBTransaction;+use crate::indexed_db::internal::algorithms::queue_a_database_task;+use crate::indexed_db::internal::function::Function;+use crate::indexed_db::internal::object_store::ObjectStoreRef;+use crate::indexed_db::internal::storage::{StorageKey, storage};++type WeakConnection = GcWeak<EmbedderCell<crate::bindings::interface::Wrapped<IDBDatabase>>>;++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct PendingConnectionWait {+ #[gc(untraced = "the connections are weak")]+ connections: Vec<WeakConnection>,+ callback: Function,+}++// https://w3c.github.io/IndexedDB/#database-construct+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Database {+ #[gc(untraced = "the connections are weak")]+ associated_connections: RefCell<Vec<WeakConnection>>,+ pending_connection_wait: GcRefCell<Option<PendingConnectionWait>>,++ // A database has a name which identifies it within a specific storage key.+ name: Utf16String,++ // A database has a version. When a database is first created, its version is 0 (zero).+ version: Cell<u64>,++ // A database has at most one associated upgrade transaction, which is either null or an upgrade transaction, and is initially null.+ upgrade_transaction: Cell<Option<Ref<IDBTransaction>>>,++ // A database has zero or more object stores which hold the data stored in the database.+ object_stores: GcRefCell<Vec<ObjectStoreRef>>,+}++static DATABASE_CLASS: EmbedderClass<Database> = EmbedderClass::new("IndexedDBDatabase");++impl EmbedderValue for Database {+ const CLASS: &'static EmbedderClass<Self> = &DATABASE_CLASS;+}++pub(crate) type DatabaseRef = Gc<EmbedderCell<Database>>;++impl Database {+ pub(crate) fn create(vm: &Vm, name: &Utf16String) -> DatabaseRef {+ DATABASE_CLASS.allocate(vm, |_| Database {+ associated_connections: RefCell::new(Vec::new()),+ pending_connection_wait: GcRefCell::new(None),+ name: name.clone(),+ version: Cell::new(0),+ upgrade_transaction: Cell::new(None),+ object_stores: GcRefCell::new(Vec::new()),+ })+ }++ pub(crate) fn set_version(&self, version: u64) {+ self.version.set(version);+ }++ pub(crate) fn version(&self) -> u64 {+ self.version.get()+ }++ pub(crate) fn name(&self) -> Utf16String {+ self.name.clone()+ }++ pub(crate) fn set_upgrade_transaction(&self, transaction: Option<Ref<IDBTransaction>>) {+ self.upgrade_transaction.set(transaction);+ }++ pub(crate) fn upgrade_transaction(&self) -> Option<Ref<IDBTransaction>> {+ self.upgrade_transaction.get()+ }++ pub(crate) fn object_stores<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, ObjectStoreRef> {+ let object_stores = MarkedVec::new(vm);+ object_stores.extend_from_slice(&self.object_stores.borrow());+ object_stores+ }++ pub(crate) fn object_store_with_name(&self, name: &Utf16String) -> Option<ObjectStoreRef> {+ self.object_stores+ .borrow()+ .iter()+ .find(|object_store| object_store.name() == *name)+ .copied()+ }++ pub(crate) fn add_object_store(this: DatabaseRef, vm: &Vm, object_store: ObjectStoreRef) {+ this.object_stores.borrow_mut(vm).push(object_store);+ }++ pub(crate) fn remove_object_store(this: DatabaseRef, vm: &Vm, object_store: ObjectStoreRef) {+ let mut object_stores = this.object_stores.borrow_mut(vm);+ if let Some(position) = object_stores.iter().position(|entry| *entry == object_store) {+ object_stores.remove(position);+ }+ }++ pub(crate) fn associate(&self, vm: &Vm, connection: Ref<IDBDatabase>) {+ self.associated_connections+ .borrow_mut()+ .push(GcWeak::new(vm.heap(), connection));+ }++ pub(crate) fn dissociate(&self, connection: Ref<IDBDatabase>) {+ self.associated_connections+ .borrow_mut()+ .retain(|entry| entry.get().is_some_and(|entry| entry != connection));+ }++ pub(crate) fn associated_connections<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Ref<IDBDatabase>> {+ let connections = MarkedVec::new(vm);+ for connection in self.associated_connections.borrow().iter() {+ if let Some(connection) = connection.get() {+ connections.push(connection);+ }+ }+ connections+ }++ pub(crate) fn associated_connections_except<'vm>(+ &self,+ vm: &'vm Vm,+ connection: Ref<IDBDatabase>,+ ) -> MarkedVec<'vm, Ref<IDBDatabase>> {+ let connections = MarkedVec::new(vm);+ for associated_connection in self.associated_connections.borrow().iter() {+ if let Some(associated_connection) = associated_connection.get()+ && associated_connection != connection+ {+ connections.push(associated_connection);+ }+ }+ connections+ }++ pub(crate) fn for_key<'vm>(vm: &'vm Vm, key: &StorageKey) -> MarkedVec<'vm, DatabaseRef> {+ let databases = MarkedVec::new(vm);+ storage(vm).for_each_database_of_key(key, |database| databases.push(database));+ databases+ }++ pub(crate) fn for_key_and_name(vm: &Vm, key: &StorageKey, name: &Utf16String) -> Option<DatabaseRef> {+ storage(vm).database(key, name)+ }++ pub(crate) fn create_for_key_and_name(vm: &Vm, key: &StorageKey, name: &Utf16String) -> DatabaseRef {+ let value = Database::create(vm, name);+ storage(vm).set_database(vm, key, name, value);+ value+ }++ pub(crate) fn delete_for_key_and_name(vm: &Vm, key: &StorageKey, name: &Utf16String) {+ storage(vm).remove_database(vm, key, name);+ }++ pub(crate) fn for_each_database(vm: &Vm, mut visitor: impl FnMut(DatabaseRef)) {+ let databases = MarkedVec::new(vm);+ storage(vm).for_each_database(|database| databases.push(database));+ for database in databases.values().iter() {+ visitor(*database);+ }+ }++ pub(crate) fn wait_for_connections_to_close(&self, vm: &Vm, connections: &[Ref<IDBDatabase>], after_all: Function) {+ let all_closed = connections.iter().all(|entry| entry.state() == ConnectionState::Closed);++ if all_closed {+ queue_a_database_task(vm, after_all);+ return;+ }++ assert!(self.pending_connection_wait.borrow().is_none());+ let weak_connections = connections+ .iter()+ .map(|connection| GcWeak::new(vm.heap(), *connection))+ .collect();+ *self.pending_connection_wait.borrow_mut(vm) = Some(PendingConnectionWait {+ connections: weak_connections,+ callback: after_all,+ });+ }++ pub(crate) fn check_pending_connection_wait(&self, vm: &Vm) {+ let callback = {+ let wait = self.pending_connection_wait.borrow();+ let Some(wait) = &*wait else {+ return;+ };+ for connection in &wait.connections {+ if let Some(connection) = connection.get()+ && connection.state() != ConnectionState::Closed+ {+ return;+ }+ }+ wait.callback+ };++ // All connections are closed - invoke the callback and clear the wait+ *self.pending_connection_wait.borrow_mut(vm) = None;+ queue_a_database_task(vm, callback);+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/function.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/function.rsnew file mode 100644index 00000000000..1780076ccf4--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/function.rs@@ -0,0 +1,200 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! GC::Function as the C++ implementation used it: steps that run later, which keep their captures alive until then.++use core::any::Any;+use core::marker::PhantomData;++use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, Trace, Value, Visitor, Vm};++use crate::bindings::WebIdlResult;++trait Steps: Trace {+ /// Takes the argument, an Option<A>, and runs the steps with it.+ fn call(&self, vm: &Vm, argument: &mut dyn Any);+}++struct CapturedSteps<C, A> {+ captures: C,+ steps: fn(&Vm, &C, A),+}++// SAFETY: The steps are a plain function, which holds no cells.+unsafe impl<C: Trace, A> Trace for CapturedSteps<C, A> {+ fn trace(&self, visitor: &mut Visitor) {+ self.captures.trace(visitor);+ }+}++impl<C: Trace, A: 'static> Steps for CapturedSteps<C, A> {+ fn call(&self, vm: &Vm, argument: &mut dyn Any) {+ let argument = argument+ .downcast_mut::<Option<A>>()+ .and_then(Option::take)+ .expect("a function is called with an argument of its type");+ (self.steps)(vm, &self.captures, argument);+ }+}++pub(crate) struct FunctionCell(Box<dyn Steps>);++// SAFETY: The captures of the steps are all the cells this reaches.+unsafe impl Trace for FunctionCell {+ fn trace(&self, visitor: &mut Visitor) {+ self.0.trace(visitor);+ }+}++static FUNCTION_CLASS: EmbedderClass<FunctionCell> = EmbedderClass::new("IndexedDBFunction");++impl EmbedderValue for FunctionCell {+ const CLASS: &'static EmbedderClass<Self> = &FUNCTION_CLASS;+}++/// A GC::Function<void(A)>.+pub(crate) struct FunctionWith<A> {+ cell: Gc<EmbedderCell<FunctionCell>>,+ _argument: PhantomData<fn(A)>,+}++impl<A> Clone for FunctionWith<A> {+ fn clone(&self) -> Self {+ *self+ }+}++impl<A> Copy for FunctionWith<A> {}++// SAFETY: The cell is all the function reaches.+unsafe impl<A> Trace for FunctionWith<A> {+ fn trace(&self, visitor: &mut Visitor) {+ self.cell.trace(visitor);+ }+}++/// A GC::Function<void()>.+pub(crate) type Function = FunctionWith<()>;++/// GC::create_function(), with captures that the function keeps alive.+pub(crate) fn create_function_with<A: 'static, C: Trace + 'static>(+ vm: &Vm,+ captures: C,+ steps: fn(&Vm, &C, A),+) -> FunctionWith<A> {+ let cell = FUNCTION_CLASS.allocate(vm, |_| {+ let steps: Box<dyn Steps> = Box::new(CapturedSteps { captures, steps });+ FunctionCell(steps)+ });+ FunctionWith {+ cell,+ _argument: PhantomData,+ }+}++pub(crate) fn create_function<C: Trace + 'static>(vm: &Vm, captures: C, steps: fn(&Vm, &C, ())) -> Function {+ create_function_with(vm, captures, steps)+}++impl<A: 'static> FunctionWith<A> {+ pub(crate) fn call(self, vm: &Vm, argument: A) {+ let mut argument = Some(argument);+ self.cell.0.call(vm, &mut argument);+ // NB: The function keeps its captures alive while it runs.+ core::hint::black_box(self.cell);+ }+}++pub(crate) fn call_function(vm: &Vm, function: Function) {+ function.call(vm, ());+}++/// A value that holds no cells, for the captures of a function: keys and plain data.+#[derive(Clone)]+pub(crate) struct NoCells<T>(pub(crate) T);++// SAFETY: The value holds no cells.+unsafe impl<T> Trace for NoCells<T> {+ fn trace(&self, _: &mut Visitor) {}+}++trait OperationSteps: Trace {+ fn call(&self, vm: &Vm) -> WebIdlResult<Value>;+}++struct CapturedOperation<C> {+ captures: C,+ steps: fn(&Vm, &C) -> WebIdlResult<Value>,+}++// SAFETY: The steps are a plain function, which holds no cells.+unsafe impl<C: Trace> Trace for CapturedOperation<C> {+ fn trace(&self, visitor: &mut Visitor) {+ self.captures.trace(visitor);+ }+}++impl<C: Trace> OperationSteps for CapturedOperation<C> {+ fn call(&self, vm: &Vm) -> WebIdlResult<Value> {+ (self.steps)(vm, &self.captures)+ }+}++pub(crate) struct OperationCell(Box<dyn OperationSteps>);++// SAFETY: The captures of the steps are all the cells this reaches.+unsafe impl Trace for OperationCell {+ fn trace(&self, visitor: &mut Visitor) {+ self.0.trace(visitor);+ }+}++static OPERATION_CLASS: EmbedderClass<OperationCell> = EmbedderClass::new("IndexedDBOperation");++impl EmbedderValue for OperationCell {+ const CLASS: &'static EmbedderClass<Self> = &OPERATION_CLASS;+}++/// A GC::Function<WebIDL::ExceptionOr<JS::Value>()>: the operation of a request.+pub(crate) type Operation = Gc<EmbedderCell<OperationCell>>;++/// GC::create_function() for an operation, with captures that it keeps alive.+pub(crate) fn create_operation<C: Trace + 'static>(+ vm: &Vm,+ captures: C,+ steps: fn(&Vm, &C) -> WebIdlResult<Value>,+) -> Operation {+ OPERATION_CLASS.allocate(vm, |_| {+ let steps: Box<dyn OperationSteps> = Box::new(CapturedOperation { captures, steps });+ OperationCell(steps)+ })+}++pub(crate) fn perform_operation(vm: &Vm, operation: Operation) -> WebIdlResult<Value> {+ let result = operation.0.call(vm);+ // NB: The operation keeps its captures alive while it runs.+ core::hint::black_box(operation);+ result+}++impl Function {+ /// The cell, for LibWeb's C++ code to hold until it runs the function.+ pub(crate) fn cell_as_ptr(self) -> *mut core::ffi::c_void {+ self.cell.as_ptr().cast()+ }++ /// The function whose cell cell_as_ptr() handed out.+ ///+ /// # Safety+ ///+ /// The cell must be that of a function that takes no argument.+ pub(crate) unsafe fn from_cell(cell: Gc<EmbedderCell<FunctionCell>>) -> Self {+ Self {+ cell,+ _argument: PhantomData,+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/index.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/index.rsnew file mode 100644index 00000000000..f153ae9981d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/index.rs@@ -0,0 +1,272 @@+/*+ * Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Indexes, https://w3c.github.io/IndexedDB/#index-construct++use core::cell::{Cell, Ref, RefCell};+use core::cmp::Ordering;++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, Trace, Vm};++use crate::indexed_db::idb_key_range::IDBKeyRange;+use crate::indexed_db::idb_record::{IndexRecord, StorageSerializationRecord};+use crate::indexed_db::internal::algorithms::KeyPath;+use crate::indexed_db::internal::key::Key;+use crate::indexed_db::internal::object_store::ObjectStoreRef;+use crate::indexed_db::internal::record_range::{KeyedRecord, record_range_for_key_range};++impl KeyedRecord for IndexRecord {+ fn key(&self) -> &Key {+ &self.key+ }+}++fn compare_index_records(a: &IndexRecord, b: &IndexRecord) -> Ordering {+ let key_comparison = Key::compare_two_keys(&a.key, &b.key);+ if key_comparison != 0 {+ return key_comparison.cmp(&0);+ }++ Key::compare_two_keys(&a.value, &b.value).cmp(&0)+}++// https://w3c.github.io/IndexedDB/#index-construct+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Index {+ // An index [...] has a referenced object store.+ object_store: ObjectStoreRef,++ // The index has a list of records which hold the data stored in the index.+ #[gc(untraced)]+ records: RefCell<Vec<IndexRecord>>,++ // An index has a name, which is a name. At any one time, the name is unique within index’s referenced object store.+ #[gc(untraced)]+ name: RefCell<Utf16String>,++ // An index has a unique flag. When true, the index enforces that no two records in the index has the same key.+ unique: bool,++ // An index has a multiEntry flag. This flag affects how the index behaves when the result of evaluating the index’s key path yields an array key.+ multi_entry: bool,++ // The keys are derived from the referenced object store’s values using a key path.+ #[gc(untraced)]+ key_path: KeyPath,++ deleted: Cell<bool>,++ // NB: Whether the request that creates the index in its upgrade transaction has yet to be processed. Until then,+ // storing records into the object store leaves the index alone.+ pending_creation: Cell<bool>,+}++static INDEX_CLASS: EmbedderClass<Index> = EmbedderClass::new("IndexedDBIndex");++impl EmbedderValue for Index {+ const CLASS: &'static EmbedderClass<Self> = &INDEX_CLASS;+}++pub(crate) type IndexRef = Gc<EmbedderCell<Index>>;++impl Index {+ pub(crate) fn create(+ vm: &Vm,+ store: ObjectStoreRef,+ name: &Utf16String,+ key_path: &KeyPath,+ unique: bool,+ multi_entry: bool,+ ) -> IndexRef {+ let index = INDEX_CLASS.allocate(vm, |_| Index {+ object_store: store,+ records: RefCell::new(Vec::new()),+ name: RefCell::new(name.clone()),+ unique,+ multi_entry,+ key_path: key_path.clone(),+ deleted: Cell::new(false),+ pending_creation: Cell::new(false),+ });+ store.index_set_set(vm, name.clone(), index);+ index+ }++ pub(crate) fn set_name(this: IndexRef, vm: &Vm, name: Utf16String) {+ // NOTE: Update the key in the map so it still matches the name+ let old_value = this+ .object_store+ .index_set_take(vm, &this.name())+ .expect("the index is in its object store's index set");+ this.object_store.index_set_set(vm, name.clone(), old_value);++ *this.name.borrow_mut() = name;+ }++ pub(crate) fn name(&self) -> Utf16String {+ self.name.borrow().clone()+ }++ pub(crate) fn unique(&self) -> bool {+ self.unique+ }++ pub(crate) fn multi_entry(&self) -> bool {+ self.multi_entry+ }++ pub(crate) fn object_store(&self) -> ObjectStoreRef {+ self.object_store+ }++ pub(crate) fn records(&self) -> Ref<'_, Vec<IndexRecord>> {+ self.records.borrow()+ }++ pub(crate) fn key_path(&self) -> &KeyPath {+ &self.key_path+ }++ pub(crate) fn is_deleted(&self) -> bool {+ self.deleted.get()+ }++ pub(crate) fn set_deleted(&self, deleted: bool) {+ self.deleted.set(deleted);+ }++ pub(crate) fn is_pending_creation(&self) -> bool {+ self.pending_creation.get()+ }++ pub(crate) fn set_pending_creation(&self, pending_creation: bool) {+ self.pending_creation.set(pending_creation);+ }++ pub(crate) fn has_record_with_key(&self, key: &Key) -> bool {+ self.records+ .borrow()+ .binary_search_by(|record| Key::ordering(&record.key, key))+ .is_ok()+ }++ // https://w3c.github.io/IndexedDB/#index-referenced-value+ pub(crate) fn referenced_value(&self, index_record: &IndexRecord) -> StorageSerializationRecord {+ // Records in an index are said to have a referenced value.+ // This is the value of the record in the index’s referenced object store which has a key equal to the index’s record’s value.+ let store_records = self.object_store.records();+ let position = store_records+ .binary_search_by(|record| Key::ordering(&record.key, &index_record.value))+ .expect("the referenced object store has a record with the index record's value as its key");+ store_records[position].value.clone()+ }++ pub(crate) fn clear_records(this: IndexRef, vm: &Vm) {+ let deleted = core::mem::take(&mut *this.records.borrow_mut());+ if let Some(log) = this.object_store.mutation_log()+ && !deleted.is_empty()+ {+ log.note_index_records_deleted(vm, this, deleted);+ }+ }++ pub(crate) fn first_in_range(&self, range: &IDBKeyRange) -> Option<IndexRecord> {+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ if record_range.start == record_range.end {+ return None;+ }+ Some(records[record_range.start].clone())+ }++ pub(crate) fn first_n_in_range(&self, range: &IDBKeyRange, count: Option<u32>) -> Vec<IndexRecord> {+ let mut result = Vec::new();+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ for record in &records[record_range.start..record_range.end] {+ result.push(record.clone());++ if count.is_some_and(|count| result.len() >= count as usize) {+ break;+ }+ }++ result+ }++ pub(crate) fn last_n_in_range(&self, range: &IDBKeyRange, count: Option<u32>) -> Vec<IndexRecord> {+ let mut result = Vec::new();+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ for record in records[record_range.start..record_range.end].iter().rev() {+ result.push(record.clone());++ if count.is_some_and(|count| result.len() >= count as usize) {+ break;+ }+ }++ result+ }++ pub(crate) fn count_records_in_range(&self, range: &IDBKeyRange) -> u64 {+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ (record_range.end - record_range.start) as u64+ }++ pub(crate) fn store_a_record(this: IndexRef, vm: &Vm, record: &IndexRecord) {+ if let Some(log) = this.object_store.mutation_log() {+ log.note_index_record_stored(vm, this, record.clone());+ }++ // NOTE: The record is stored in index’s list of records such that the list is sorted primarily on the records keys, and secondarily on the records values, in ascending order.+ let mut records = this.records.borrow_mut();+ if records+ .last()+ .is_none_or(|last| compare_index_records(last, record) != Ordering::Greater)+ {+ records.push(record.clone());+ return;+ }++ let position = records.partition_point(|existing| compare_index_records(existing, record) == Ordering::Less);+ records.insert(position, record.clone());+ }++ pub(crate) fn remove_record(&self, record: &IndexRecord) {+ let mut records = self.records.borrow_mut();+ let position = records.partition_point(|existing| compare_index_records(existing, record) == Ordering::Less);+ if position < records.len() && compare_index_records(&records[position], record) == Ordering::Equal {+ records.remove(position);+ }+ }++ pub(crate) fn remove_records_with_value_in_range(this: IndexRef, vm: &Vm, range: &IDBKeyRange) {+ let log = this.object_store.mutation_log();+ let mut removed_records = Vec::new();+ let mut records = this.records.borrow_mut();+ let mut i = 0;+ while i < records.len() {+ if range.is_in_range(&records[i].value) {+ let removed_record = records.remove(i);+ if log.is_some() {+ removed_records.push(removed_record);+ }+ continue;+ }+ i += 1;+ }+ drop(records);+ if !removed_records.is_empty() {+ log.expect("records are only collected for a mutation log")+ .note_index_records_deleted(vm, this, removed_records);+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/key.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/key.rsnew file mode 100644index 00000000000..a2d40c87914--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/key.rs@@ -0,0 +1,323 @@+/*+ * Copyright (c) 2024, stelar7 <[email protected]>+ * Copyright (c) 2026, Sam Atkins <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Keys, https://w3c.github.io/IndexedDB/#key-construct++use std::rc::Rc;++use core::cmp::Ordering;++use ak::{Utf16String, Utf16StringUnits};++// A key has an associated type which is one of: number, date, string, binary, or array.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub(crate) enum KeyType {+ Invalid,+ Number,+ Date,+ String,+ Binary,+ Array,+}++// A key also has an associated value, which will be either:+// * an unrestricted double if type is number or date,+// * a DOMString if type is string,+// * a byte sequence if type is binary,+// * a list of other keys if type is array.+pub(crate) enum KeyValue {+ Double(f64),+ String(Utf16String),+ Bytes(Vec<u8>),+ Keys(Vec<Rc<Key>>),+}++// https://w3c.github.io/IndexedDB/#key-construct+pub(crate) struct Key {+ r#type: KeyType,+ value: KeyValue,+}++impl Key {+ pub(crate) fn create(r#type: KeyType, value: KeyValue) -> Rc<Key> {+ Rc::new(Key { r#type, value })+ }++ pub(crate) fn r#type(&self) -> KeyType {+ self.r#type+ }++ pub(crate) fn value(&self) -> &KeyValue {+ &self.value+ }++ pub(crate) fn is_invalid(&self) -> bool {+ self.r#type == KeyType::Invalid+ }++ pub(crate) fn value_as_double(&self) -> f64 {+ match self.value {+ KeyValue::Double(value) => value,+ _ => unreachable!("the key's value is a double"),+ }+ }++ pub(crate) fn value_as_string(&self) -> &Utf16String {+ match &self.value {+ KeyValue::String(value) => value,+ _ => unreachable!("the key's value is a string"),+ }+ }++ pub(crate) fn value_as_byte_buffer(&self) -> &[u8] {+ match &self.value {+ KeyValue::Bytes(value) => value,+ _ => unreachable!("the key's value is a byte sequence"),+ }+ }++ pub(crate) fn value_as_vector(&self) -> &[Rc<Key>] {+ match &self.value {+ KeyValue::Keys(value) => value,+ _ => unreachable!("the key's value is a list of keys"),+ }+ }++ pub(crate) fn subkeys(&self) -> &[Rc<Key>] {+ assert_eq!(self.r#type, KeyType::Array);+ self.value_as_vector()+ }++ pub(crate) fn create_number(value: f64) -> Rc<Key> {+ Self::create(KeyType::Number, KeyValue::Double(value))+ }++ pub(crate) fn create_date(value: f64) -> Rc<Key> {+ Self::create(KeyType::Date, KeyValue::Double(value))+ }++ pub(crate) fn create_string(value: Utf16String) -> Rc<Key> {+ Self::create(KeyType::String, KeyValue::String(value))+ }++ pub(crate) fn create_binary(value: Vec<u8>) -> Rc<Key> {+ Self::create(KeyType::Binary, KeyValue::Bytes(value))+ }++ pub(crate) fn create_array(value: Vec<Rc<Key>>) -> Rc<Key> {+ Self::create(KeyType::Array, KeyValue::Keys(value))+ }++ pub(crate) fn create_invalid(value: &str) -> Rc<Key> {+ Self::create(KeyType::Invalid, KeyValue::String(Utf16String::from_utf8(value)))+ }++ // https://w3c.github.io/IndexedDB/#compare-two-keys+ pub(crate) fn compare_two_keys(a: &Key, b: &Key) -> i8 {+ // 1. Let ta be the type of a.+ let ta = a.r#type();++ // 2. Let tb be the type of b.+ let tb = b.r#type();++ // 3. If ta does not equal tb, then run these steps:+ if ta != tb {+ // 1. If ta is array, then return 1.+ if ta == KeyType::Array {+ return 1;+ }++ // 2. If tb is array, then return -1.+ if tb == KeyType::Array {+ return -1;+ }++ // 3. If ta is binary, then return 1.+ if ta == KeyType::Binary {+ return 1;+ }++ // 4. If tb is binary, then return -1.+ if tb == KeyType::Binary {+ return -1;+ }++ // 5. If ta is string, then return 1.+ if ta == KeyType::String {+ return 1;+ }++ // 6. If tb is string, then return -1.+ if tb == KeyType::String {+ return -1;+ }++ // 7. If ta is date, then return 1.+ if ta == KeyType::Date {+ return 1;+ }++ // 8. Assert: tb is date.+ assert_eq!(tb, KeyType::Date);++ // 9. Return -1.+ return -1;+ }++ // 4. Let va be the value of a.+ let va = &a.value;++ // 5. Let vb be the value of b.+ let vb = &b.value;++ // 6. Switch on ta:+ match ta {+ KeyType::Invalid => unreachable!("invalid keys are not compared"),+ // number+ // date+ KeyType::Number | KeyType::Date => {+ let (KeyValue::Double(a_value), KeyValue::Double(b_value)) = (va, vb) else {+ unreachable!("the value of a number or a date key is a double");+ };++ // 1. If va is greater than vb, then return 1.+ if a_value > b_value {+ return 1;+ }++ // 2. If va is less than vb, then return -1.+ if a_value < b_value {+ return -1;+ }++ // 3. Return 0.+ 0+ }+ // string+ KeyType::String => {+ let (KeyValue::String(a_value), KeyValue::String(b_value)) = (va, vb) else {+ unreachable!("the value of a string key is a string");+ };++ // 1. If va is code unit less than vb, then return -1.+ if code_unit_less_than(a_value, b_value) {+ return -1;+ }++ // 2. If vb is code unit less than va, then return 1.+ if code_unit_less_than(b_value, a_value) {+ return 1;+ }++ // 3. Return 0.+ 0+ }+ // binary+ KeyType::Binary => {+ let (KeyValue::Bytes(a_value), KeyValue::Bytes(b_value)) = (va, vb) else {+ unreachable!("the value of a binary key is a byte sequence");+ };++ // 1. If va is byte less than vb, then return -1.+ if is_byte_less_than(a_value, b_value) {+ return -1;+ }++ // 2. If vb is byte less than va, then return 1.+ if is_byte_less_than(b_value, a_value) {+ return 1;+ }++ // 3. Return 0.+ 0+ }+ // array+ KeyType::Array => {+ let (KeyValue::Keys(a_value), KeyValue::Keys(b_value)) = (va, vb) else {+ unreachable!("the value of an array key is a list of keys");+ };++ // 1. Let length be the lesser of va’s size and vb’s size.+ let length = a_value.len().min(b_value.len());++ // 2. Let i be 0.+ let mut i = 0;++ // 3. While i is less than length, then:+ while i < length {+ // 1. Let c be the result of recursively comparing two keys with va[i] and vb[i].+ let c = Self::compare_two_keys(&a_value[i], &b_value[i]);++ // 2. If c is not 0, return c.+ if c != 0 {+ return c;+ }++ // 3. Increase i by 1.+ i += 1;+ }++ // 4. If va’s size is greater than vb’s size, then return 1.+ if a_value.len() > b_value.len() {+ return 1;+ }++ // 5. If va’s size is less than vb’s size, then return -1.+ if a_value.len() < b_value.len() {+ return -1;+ }++ // 6. Return 0.+ 0+ }+ }+ }++ pub(crate) fn equals(a: &Key, b: &Key) -> bool {+ Self::compare_two_keys(a, b) == 0+ }++ pub(crate) fn less_than(a: &Key, b: &Key) -> bool {+ Self::compare_two_keys(a, b) < 0+ }++ pub(crate) fn greater_than(a: &Key, b: &Key) -> bool {+ Self::compare_two_keys(a, b) > 0+ }++ pub(crate) fn less_than_or_equal(a: &Key, b: &Key) -> bool {+ Self::compare_two_keys(a, b) <= 0+ }++ pub(crate) fn greater_than_or_equal(a: &Key, b: &Key) -> bool {+ Self::compare_two_keys(a, b) >= 0+ }++ /// compare two keys, as an Ordering.+ pub(crate) fn ordering(a: &Key, b: &Key) -> Ordering {+ Self::compare_two_keys(a, b).cmp(&0)+ }+}++// https://infra.spec.whatwg.org/#code-unit-less-than+fn code_unit_less_than(a: &Utf16String, b: &Utf16String) -> bool {+ code_unit_order(a, b) == Ordering::Less+}++/// https://infra.spec.whatwg.org/#code-unit-less-than, as an Ordering.+pub(crate) fn code_unit_order(a: &Utf16String, b: &Utf16String) -> Ordering {+ match (a.as_units(), b.as_units()) {+ (Utf16StringUnits::Ascii(a), Utf16StringUnits::Ascii(b)) => a.cmp(b),+ _ => a.to_utf16().cmp(&b.to_utf16()),+ }+}++// https://infra.spec.whatwg.org/#byte-less-than+fn is_byte_less_than(a: &[u8], b: &[u8]) -> bool {+ a < b+}diff --git a/Libraries/LibWeb/IndexedDB/Internal/KeyGenerator.h b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/key_generator.rssimilarity index 51%rename from Libraries/LibWeb/IndexedDB/Internal/KeyGenerator.hrename to Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/key_generator.rsindex 757041a0996..b15939980de 100644--- a/Libraries/LibWeb/IndexedDB/Internal/KeyGenerator.h+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/key_generator.rs@@ -1,32 +1,39 @@/** Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#pragma once--#include <AK/Types.h>--namespace Web::IndexedDB {+//! Key generators, https://w3c.github.io/IndexedDB/#key-generator-construct// https://w3c.github.io/IndexedDB/#key-generator-construct// The current number is always a positive integer less than or equal to 2^53 (9007199254740992) + 1.-static constexpr double MAX_KEY_GENERATOR_VALUE = 9007199254740992.0;+pub(crate) const MAX_KEY_GENERATOR_VALUE: f64 = 9007199254740992.0;-class KeyGenerator {-public:- [[nodiscard]] u64 current_number() const { return m_current_number; }- void increment(u64 amount) { m_current_number += amount; }- void set(u64 value) { m_current_number = value; }--private:+pub(crate) struct KeyGenerator {// A key generator has a current number.// The current number is always a positive integer less than or equal to 2^53 (9007199254740992) + 1.// The initial value of a key generator's current number is 1, set when the associated object store is created.// The current number is incremented as keys are generated, and may be updated to a specific value by using explicit keys.- u64 m_current_number { 1 };-};+ current_number: u64,+}++impl KeyGenerator {+ pub(crate) fn new() -> Self {+ Self { current_number: 1 }+ }++ pub(crate) fn current_number(&self) -> u64 {+ self.current_number+ }++ pub(crate) fn increment(&mut self, amount: u64) {+ self.current_number += amount;+ }+ pub(crate) fn set(&mut self, value: u64) {+ self.current_number = value;+ }}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/mod.rsnew file mode 100644index 00000000000..be74d52d756--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/mod.rs@@ -0,0 +1,19 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The constructs that script does not see: databases, object stores, indexes, keys, and their algorithms.++pub(crate) mod algorithms;+pub(crate) mod database;+pub(crate) mod function;+pub(crate) mod index;+pub(crate) mod key;+pub(crate) mod key_generator;+pub(crate) mod mutation_log;+pub(crate) mod object_store;+pub(crate) mod record_range;+pub(crate) mod request_list;+pub(crate) mod storage;diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/mutation_log.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/mutation_log.rsnew file mode 100644index 00000000000..4cf714c8c57--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/mutation_log.rs@@ -0,0 +1,346 @@+/*+ * Copyright (c) 2025, zaggy1024+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The log of what a transaction changed in an object store, which an abort reverts++use std::rc::Rc;++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, Trace, Vm};++use crate::bindings::interface::Ref;+use crate::indexed_db::idb_database::IDBDatabase;+use crate::indexed_db::idb_record::{IndexRecord, ObjectStoreRecord};+use crate::indexed_db::internal::database::{Database, DatabaseRef};+use crate::indexed_db::internal::index::{Index, IndexRef};+use crate::indexed_db::internal::key::Key;+use crate::indexed_db::internal::object_store::ObjectStoreRef;++// https://w3c.github.io/IndexedDB/ has no notion of these changes: they are what DevTools reports of a transaction+// that commits, as Web::IndexedDB::TransactionChanges of LibWebCommon.+pub(crate) struct TransactionChange {+ pub(crate) database_name: Utf16String,+ pub(crate) object_store_name: Utf16String,+ pub(crate) key: Option<Rc<Key>>,+}++#[derive(Default)]+pub(crate) struct TransactionChanges {+ pub(crate) added: Vec<TransactionChange>,+ pub(crate) changed: Vec<TransactionChange>,+ pub(crate) deleted: Vec<TransactionChange>,+}++impl TransactionChanges {+ pub(crate) fn is_empty(&self) -> bool {+ self.added.is_empty() && self.changed.is_empty() && self.deleted.is_empty()+ }+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+enum Entry {+ ObjectStoreCreated,+ ObjectStoreDeleted,+ ObjectStoreRenamed {+ old_name: Utf16String,+ },+ IndexCreated {+ index: IndexRef,+ },+ IndexDeleted {+ index: IndexRef,+ },+ IndexRenamed {+ index: IndexRef,+ old_name: Utf16String,+ },+ KeyGeneratorChanged {+ old_value: u64,+ },+ RecordsDeleted {+ #[gc(untraced)]+ records: Vec<ObjectStoreRecord>,+ },+ RecordStored {+ #[gc(untraced)]+ key: Rc<Key>,+ },+ IndexRecordsDeleted {+ index: IndexRef,+ #[gc(untraced)]+ records: Vec<IndexRecord>,+ },+ IndexRecordStored {+ index: IndexRef,+ #[gc(untraced)]+ record: IndexRecord,+ },+}++// Tracks mutations to an object store and its indexes so they can be reverted on request failure+// (asynchronously execute a request step 5.4) or transaction abort (abort a transaction step 2).+//+// For upgrade transactions, this also tracks schema-level changes (store/index creation and deletion).+// Schema entries are always at the boundaries: ObjectStoreCreated is always first (if present),+// and ObjectStoreDeleted is always last (if present). Index schema entries appear in order between+// data mutations.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct MutationLog {+ entries: GcRefCell<Vec<Entry>>,+}++static MUTATION_LOG_CLASS: EmbedderClass<MutationLog> = EmbedderClass::new("IndexedDBMutationLog");++impl EmbedderValue for MutationLog {+ const CLASS: &'static EmbedderClass<Self> = &MUTATION_LOG_CLASS;+}++pub(crate) type MutationLogRef = Gc<EmbedderCell<MutationLog>>;++impl MutationLog {+ pub(crate) fn create(vm: &Vm) -> MutationLogRef {+ MUTATION_LOG_CLASS.allocate(vm, |_| MutationLog {+ entries: GcRefCell::new(Vec::new()),+ })+ }++ fn append(&self, vm: &Vm, entry: Entry) {+ self.entries.borrow_mut(vm).push(entry);+ }++ // Schema-level entries (upgrade transactions only).+ pub(crate) fn note_object_store_created(&self, vm: &Vm) {+ self.append(vm, Entry::ObjectStoreCreated);+ }++ pub(crate) fn note_object_store_deleted(&self, vm: &Vm) {+ self.append(vm, Entry::ObjectStoreDeleted);+ }++ pub(crate) fn note_object_store_renamed(&self, vm: &Vm, old_name: Utf16String) {+ self.append(vm, Entry::ObjectStoreRenamed { old_name });+ }++ pub(crate) fn note_index_created(&self, vm: &Vm, index: IndexRef) {+ self.append(vm, Entry::IndexCreated { index });+ }++ pub(crate) fn note_index_deleted(&self, vm: &Vm, index: IndexRef) {+ self.append(vm, Entry::IndexDeleted { index });+ }++ pub(crate) fn note_index_renamed(&self, vm: &Vm, index: IndexRef, old_name: Utf16String) {+ self.append(vm, Entry::IndexRenamed { index, old_name });+ }++ // Record that the key generator value was changed, saving the old value for revert.+ pub(crate) fn note_key_generator_changed(&self, vm: &Vm, old_value: u64) {+ self.append(vm, Entry::KeyGeneratorChanged { old_value });+ }++ // Record that records were deleted from the object store, saving them for re-insertion on revert.+ pub(crate) fn note_records_deleted(&self, vm: &Vm, records: Vec<ObjectStoreRecord>) {+ self.append(vm, Entry::RecordsDeleted { records });+ }++ // Record that a new record was stored in the object store, saving the key for deletion on revert.+ pub(crate) fn note_record_stored(&self, vm: &Vm, key: Rc<Key>) {+ self.append(vm, Entry::RecordStored { key });+ }++ // Record that records were deleted from an index, saving them for re-insertion on revert.+ pub(crate) fn note_index_records_deleted(&self, vm: &Vm, index: IndexRef, records: Vec<IndexRecord>) {+ self.append(vm, Entry::IndexRecordsDeleted { index, records });+ }++ // Record that a new record was stored in an index, saving it for deletion on revert.+ pub(crate) fn note_index_record_stored(&self, vm: &Vm, index: IndexRef, record: IndexRecord) {+ self.append(vm, Entry::IndexRecordStored { index, record });+ }++ pub(crate) fn position(&self) -> usize {+ self.entries.borrow().len()+ }++ pub(crate) fn append_changes(+ &self,+ database_name: &Utf16String,+ object_store_name: &Utf16String,+ changes: &mut TransactionChanges,+ ) {+ let mut stored_keys: Vec<Rc<Key>> = Vec::new();+ let mut changed_keys: Vec<Rc<Key>> = Vec::new();+ let mut deleted_keys: Vec<Rc<Key>> = Vec::new();++ fn remove_key(keys: &mut Vec<Rc<Key>>, key: &Key) -> bool {+ match keys.iter().position(|existing| Key::equals(existing, key)) {+ Some(position) => {+ keys.remove(position);+ true+ }+ None => false,+ }+ }++ let change = |key: Option<Rc<Key>>| TransactionChange {+ database_name: database_name.clone(),+ object_store_name: object_store_name.clone(),+ key,+ };++ for entry in self.entries.borrow().iter() {+ match entry {+ Entry::ObjectStoreCreated => {+ changes.added.push(change(None));+ }+ Entry::ObjectStoreDeleted => {+ changes.deleted.push(change(None));+ }+ Entry::ObjectStoreRenamed { old_name } => {+ changes.deleted.push(TransactionChange {+ database_name: database_name.clone(),+ object_store_name: old_name.clone(),+ key: None,+ });+ changes.added.push(change(None));+ }+ Entry::IndexCreated { .. } | Entry::IndexDeleted { .. } | Entry::IndexRenamed { .. } => {}+ Entry::KeyGeneratorChanged { .. } => {}+ Entry::RecordsDeleted { records } => {+ for record in records {+ if remove_key(&mut stored_keys, &record.key) {+ continue;+ }+ remove_key(&mut changed_keys, &record.key);+ deleted_keys.push(record.key.clone());+ }+ }+ Entry::RecordStored { key } => {+ if remove_key(&mut deleted_keys, key) {+ changed_keys.push(key.clone());+ continue;+ }+ stored_keys.push(key.clone());+ }+ Entry::IndexRecordsDeleted { .. } | Entry::IndexRecordStored { .. } => {}+ }+ }++ for key in stored_keys {+ changes.added.push(change(Some(key)));+ }++ for key in changed_keys {+ changes.changed.push(change(Some(key)));+ }++ for key in deleted_keys {+ changes.deleted.push(change(Some(key)));+ }+ }++ // Undo all logged mutations in reverse order. Database and connection are required for schema entries.+ pub(crate) fn revert(&self, vm: &Vm, store: ObjectStoreRef, database: DatabaseRef, connection: Ref<IDBDatabase>) {+ self.revert_entries(vm, store, 0, Some((database, connection)));+ }++ // Undo logged mutations from the given position forward (used for per-request revert on failure).+ // Asserts that no schema entries are encountered.+ pub(crate) fn revert_from(&self, vm: &Vm, store: ObjectStoreRef, position: usize) {+ self.revert_entries(vm, store, position, None);+ }++ fn revert_entries(+ &self,+ vm: &Vm,+ store: ObjectStoreRef,+ from_position: usize,+ schema: Option<(DatabaseRef, Ref<IDBDatabase>)>,+ ) {+ // Temporarily clear the store's mutation log pointer so that the operations below+ // don't re-log into this log while we're reverting it.+ let saved_log = store.mutation_log();+ store.set_mutation_log(None);++ loop {+ let entry = {+ let mut entries = self.entries.borrow_mut(vm);+ if entries.len() <= from_position {+ break;+ }+ entries.pop().expect("the log has an entry past the position")+ };+ match entry {+ Entry::ObjectStoreCreated => {+ let (database, connection) = schema.expect("schema entries are reverted with the database");+ Database::remove_object_store(database, vm, store);+ connection.remove_from_object_store_set(vm, store);++ // https://w3c.github.io/IndexedDB/#abort-a-transaction+ // Any object stores and indexes which were created during the transaction are now considered deleted+ // for the purposes of other algorithms.+ store.set_deleted(true);+ for index in store.indexes(vm).values().iter() {+ index.set_deleted(true);+ }+ }+ Entry::ObjectStoreDeleted => {+ let (database, connection) = schema.expect("schema entries are reverted with the database");+ store.set_deleted(false);+ for index in store.indexes(vm).values().iter() {+ index.set_deleted(false);+ }+ Database::add_object_store(database, vm, store);+ connection.add_to_object_store_set(vm, store);+ }+ Entry::IndexCreated { index } => {+ assert!(schema.is_some(), "schema entries are reverted with the database");+ index.object_store().index_set_remove(vm, &index.name());++ // https://w3c.github.io/IndexedDB/#abort-a-transaction+ // Any object stores and indexes which were created during the transaction are now considered deleted+ // for the purposes of other algorithms.+ index.set_deleted(true);+ }+ Entry::IndexDeleted { index } => {+ assert!(schema.is_some(), "schema entries are reverted with the database");+ index.set_deleted(false);+ index.object_store().index_set_set(vm, index.name(), index);+ }+ Entry::ObjectStoreRenamed { old_name } => {+ store.set_name(old_name);+ }+ Entry::IndexRenamed { index, old_name } => {+ Index::set_name(index, vm, old_name);+ }+ Entry::KeyGeneratorChanged { old_value } => {+ store.key_generator().set(old_value);+ }+ Entry::RecordsDeleted { records } => {+ for record in records {+ store.store_a_record(vm, record);+ }+ }+ Entry::RecordStored { key } => {+ store.remove_record_with_key(&key);+ }+ Entry::IndexRecordsDeleted { index, records } => {+ for record in &records {+ Index::store_a_record(index, vm, record);+ }+ }+ Entry::IndexRecordStored { index, record } => {+ index.remove_record(&record);+ }+ }+ }++ store.set_mutation_log(saved_log);+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/object_store.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/object_store.rsnew file mode 100644index 00000000000..132ef389889--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/object_store.rs@@ -0,0 +1,368 @@+/*+ * Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Object stores, https://w3c.github.io/IndexedDB/#object-store-construct++use core::cell::{Cell, Ref, RefCell, RefMut};++use ak::Utf16String;+use libjs_rust::api::{DeferGc, EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, MarkedVec, Trace, Vm};++use crate::indexed_db::idb_key_range::IDBKeyRange;+use crate::indexed_db::idb_record::ObjectStoreRecord;+use crate::indexed_db::internal::algorithms::KeyPath;+use crate::indexed_db::internal::database::{Database, DatabaseRef};+use crate::indexed_db::internal::index::IndexRef;+use crate::indexed_db::internal::key::{Key, KeyType};+use crate::indexed_db::internal::key_generator::{KeyGenerator, MAX_KEY_GENERATOR_VALUE};+use crate::indexed_db::internal::mutation_log::MutationLogRef;+use crate::indexed_db::internal::record_range::{KeyedRecord, record_range_for_key_range};++impl KeyedRecord for ObjectStoreRecord {+ fn key(&self) -> &Key {+ &self.key+ }+}++// https://w3c.github.io/IndexedDB/#object-store-construct+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ObjectStore {+ // AD-HOC: An ObjectStore needs to know what Database it belongs to...+ database: DatabaseRef,++ // AD-HOC: An Index has referenced ObjectStores, we also need the reverse mapping+ indexes: GcRefCell<Vec<(Utf16String, IndexRef)>>,++ // An object store has a name, which is a name. At any one time, the name is unique within the database to which it belongs.+ #[gc(untraced)]+ name: RefCell<Utf16String>,++ // An object store optionally has a key path. If the object store has a key path it is said to use in-line keys. Otherwise it is said to use out-of-line keys.+ #[gc(untraced)]+ key_path: Option<KeyPath>,++ // An object store optionally has a key generator.+ #[gc(untraced)]+ key_generator: RefCell<Option<KeyGenerator>>,++ // An object store has a list of records+ #[gc(untraced)]+ records: RefCell<Vec<ObjectStoreRecord>>,++ deleted: Cell<bool>,++ // AD-HOC: Tracks mutations for revert on request failure or transaction abort.+ mutation_log: Cell<Option<MutationLogRef>>,+}++static OBJECT_STORE_CLASS: EmbedderClass<ObjectStore> = EmbedderClass::new("IndexedDBObjectStore");++impl EmbedderValue for ObjectStore {+ const CLASS: &'static EmbedderClass<Self> = &OBJECT_STORE_CLASS;+}++pub(crate) type ObjectStoreRef = Gc<EmbedderCell<ObjectStore>>;++impl ObjectStore {+ pub(crate) fn create(+ vm: &Vm,+ database: DatabaseRef,+ name: Utf16String,+ auto_increment: bool,+ key_path: Option<KeyPath>,+ ) -> ObjectStoreRef {+ let object_store = OBJECT_STORE_CLASS.allocate(vm, |_| ObjectStore {+ database,+ indexes: GcRefCell::new(Vec::new()),+ name: RefCell::new(name),+ key_path,+ key_generator: RefCell::new(auto_increment.then(KeyGenerator::new)),+ records: RefCell::new(Vec::new()),+ deleted: Cell::new(false),+ mutation_log: Cell::new(None),+ });+ Database::add_object_store(database, vm, object_store);+ object_store+ }++ pub(crate) fn name(&self) -> Utf16String {+ self.name.borrow().clone()+ }++ pub(crate) fn set_name(&self, name: Utf16String) {+ *self.name.borrow_mut() = name;+ }++ pub(crate) fn key_path(&self) -> Option<&KeyPath> {+ self.key_path.as_ref()+ }++ pub(crate) fn uses_inline_keys(&self) -> bool {+ self.key_path.is_some()+ }++ pub(crate) fn uses_out_of_line_keys(&self) -> bool {+ self.key_path.is_none()+ }++ pub(crate) fn key_generator(&self) -> RefMut<'_, KeyGenerator> {+ RefMut::map(self.key_generator.borrow_mut(), |generator| {+ generator.as_mut().expect("the object store has a key generator")+ })+ }++ pub(crate) fn uses_a_key_generator(&self) -> bool {+ self.key_generator.borrow().is_some()+ }++ /// The index set, as a list of the indexes with their names, for the storage of a cell being built.+ pub(crate) fn index_set(&self, _: &DeferGc<'_>) -> Vec<(Utf16String, IndexRef)> {+ self.indexes.borrow().clone()+ }++ pub(crate) fn copy_index_set_into(&self, indexes: &mut Vec<(Utf16String, IndexRef)>) {+ indexes.clone_from(&self.indexes.borrow());+ }++ pub(crate) fn indexes<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, IndexRef> {+ let indexes = MarkedVec::new(vm);+ for (_, index) in self.indexes.borrow().iter() {+ indexes.push(*index);+ }+ indexes+ }++ pub(crate) fn index_set_get(&self, name: &Utf16String) -> Option<IndexRef> {+ self.indexes+ .borrow()+ .iter()+ .find(|(index_name, _)| index_name == name)+ .map(|(_, index)| *index)+ }++ pub(crate) fn index_set_set(&self, vm: &Vm, name: Utf16String, index: IndexRef) {+ let mut indexes = self.indexes.borrow_mut(vm);+ if let Some(entry) = indexes.iter_mut().find(|(index_name, _)| *index_name == name) {+ entry.1 = index;+ return;+ }+ indexes.push((name, index));+ }++ pub(crate) fn index_set_take(&self, vm: &Vm, name: &Utf16String) -> Option<IndexRef> {+ let mut indexes = self.indexes.borrow_mut(vm);+ let position = indexes.iter().position(|(index_name, _)| index_name == name)?;+ Some(indexes.remove(position).1)+ }++ pub(crate) fn index_set_remove(&self, vm: &Vm, name: &Utf16String) {+ self.index_set_take(vm, name);+ }++ pub(crate) fn is_deleted(&self) -> bool {+ self.deleted.get()+ }++ pub(crate) fn set_deleted(&self, deleted: bool) {+ self.deleted.set(deleted);+ }++ pub(crate) fn database(&self) -> DatabaseRef {+ self.database+ }++ pub(crate) fn records(&self) -> Ref<'_, Vec<ObjectStoreRecord>> {+ self.records.borrow()+ }++ // Mutation log access. The log is set externally by the readwrite transaction that owns it.+ pub(crate) fn mutation_log(&self) -> Option<MutationLogRef> {+ self.mutation_log.get()+ }++ pub(crate) fn set_mutation_log(&self, log: Option<MutationLogRef>) {+ self.mutation_log.set(log);+ }++ pub(crate) fn mutation_log_position(&self) -> usize {+ match self.mutation_log.get() {+ None => 0,+ Some(log) => log.position(),+ }+ }++ pub(crate) fn revert_mutations_from(this: ObjectStoreRef, vm: &Vm, position: usize) {+ if let Some(log) = this.mutation_log.get() {+ log.revert_from(vm, this, position);+ }+ }++ pub(crate) fn remove_records_in_range(&self, vm: &Vm, range: &IDBKeyRange) {+ let mut records = self.records.borrow_mut();+ if records.is_empty() {+ return;+ }++ // Since records are sorted by key, records in range form a contiguous block.+ let record_range = record_range_for_key_range(&records, range);++ if record_range.start < record_range.end {+ let deleted: Vec<ObjectStoreRecord> = records.drain(record_range.start..record_range.end).collect();+ drop(records);+ if let Some(log) = self.mutation_log.get() {+ log.note_records_deleted(vm, deleted);+ }+ }+ }++ pub(crate) fn remove_record_with_key(&self, key: &Key) {+ let mut records = self.records.borrow_mut();+ if let Ok(index) = records.binary_search_by(|record| Key::ordering(&record.key, key)) {+ records.remove(index);+ }+ }++ pub(crate) fn has_record_with_key(&self, key: &Key) -> bool {+ self.records+ .borrow()+ .binary_search_by(|record| Key::ordering(&record.key, key))+ .is_ok()+ }++ pub(crate) fn store_a_record(&self, vm: &Vm, record: ObjectStoreRecord) {+ if let Some(log) = self.mutation_log.get() {+ log.note_record_stored(vm, record.key.clone());+ }++ // NOTE: The record is stored in the object store’s list of records such that the list is sorted according to the key of the records in ascending order.+ let mut records = self.records.borrow_mut();+ if records+ .last()+ .is_none_or(|last| Key::compare_two_keys(&last.key, &record.key) <= 0)+ {+ records.push(record);+ return;+ }++ let position = records.partition_point(|existing| Key::compare_two_keys(&existing.key, &record.key) < 0);+ records.insert(position, record);+ }++ pub(crate) fn count_records_in_range(&self, range: &IDBKeyRange) -> u64 {+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ (record_range.end - record_range.start) as u64+ }++ pub(crate) fn first_in_range(&self, range: &IDBKeyRange) -> Option<ObjectStoreRecord> {+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ if record_range.start == record_range.end {+ return None;+ }+ Some(records[record_range.start].clone())+ }++ pub(crate) fn clear_records(&self, vm: &Vm) {+ let deleted_records = core::mem::take(&mut *self.records.borrow_mut());+ if let Some(log) = self.mutation_log.get()+ && !deleted_records.is_empty()+ {+ log.note_records_deleted(vm, deleted_records);+ }+ }++ // https://w3c.github.io/IndexedDB/#generate-a-key+ pub(crate) fn generate_a_key(&self, vm: &Vm) -> Result<u64, &'static str> {+ // 1. Let generator be store's key generator.+ let mut generator = self.key_generator();++ // 2. Let key be generator's current number.+ let key = generator.current_number();++ // 3. If key is greater than 2^53 (9007199254740992), then return failure.+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "2^53 is a u64")]+ if key > MAX_KEY_GENERATOR_VALUE as u64 {+ return Err("Key is greater than 2^53 while trying to generate a key");+ }++ // 4. Increase generator's current number by 1.+ if let Some(log) = self.mutation_log.get() {+ log.note_key_generator_changed(vm, key);+ }+ generator.increment(1);++ // 5. Return key.+ Ok(key)+ }++ // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator+ pub(crate) fn possibly_update_the_key_generator(&self, vm: &Vm, key: &Key) {+ // 1. If the type of key is not number, abort these steps.+ if key.r#type() != KeyType::Number {+ return;+ }++ // 2. Let value be the value of key.+ let mut value = key.value_as_double();++ // 3. Set value to the minimum of value and 2^53 (9007199254740992).+ value = value.min(MAX_KEY_GENERATOR_VALUE);++ // 4. Set value to the largest integer not greater than value.+ value = value.floor();++ // 5. Let generator be store's key generator.+ let mut generator = self.key_generator();++ // 6. If value is greater than or equal to generator's current number, then set generator's current number to value + 1.+ #[allow(clippy::cast_precision_loss, reason = "the current number is at most 2^53 + 1")]+ if value >= generator.current_number() as f64 {+ if let Some(log) = self.mutation_log.get() {+ log.note_key_generator_changed(vm, generator.current_number());+ }+ // NB: value + 1 is computed as an integer, as 2^53 + 1 does not fit in a double.+ #[allow(+ clippy::cast_possible_truncation,+ clippy::cast_sign_loss,+ reason = "value is an integer in the range of the current number"+ )]+ generator.set(value as u64 + 1);+ }+ }++ pub(crate) fn first_n_in_range(&self, range: &IDBKeyRange, count: Option<u32>) -> Vec<ObjectStoreRecord> {+ let mut result = Vec::new();+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ for record in &records[record_range.start..record_range.end] {+ result.push(record.clone());++ if count.is_some_and(|count| result.len() >= count as usize) {+ break;+ }+ }++ result+ }++ pub(crate) fn last_n_in_range(&self, range: &IDBKeyRange, count: Option<u32>) -> Vec<ObjectStoreRecord> {+ let mut result = Vec::new();+ let records = self.records.borrow();+ let record_range = record_range_for_key_range(&records, range);+ for record in records[record_range.start..record_range.end].iter().rev() {+ result.push(record.clone());++ if count.is_some_and(|count| result.len() >= count as usize) {+ break;+ }+ }++ result+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/record_range.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/record_range.rsnew file mode 100644index 00000000000..c32b23d59eb--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/record_range.rs@@ -0,0 +1,69 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The records of a sorted list of records whose keys a key range selects++use crate::indexed_db::idb_key_range::IDBKeyRange;+use crate::indexed_db::internal::key::Key;++/// A record of an object store's or an index's list of records, which is sorted on its keys.+pub(crate) trait KeyedRecord {+ fn key(&self) -> &Key;+}++pub(crate) struct RecordRange {+ pub(crate) start: usize,+ pub(crate) end: usize,+}++fn first_record_index_with_key_at_or_after<R: KeyedRecord>(records: &[R], key: &Key, open: bool) -> usize {+ let mut low = 0;+ let mut high = records.len();++ while low < high {+ let middle = low + (high - low) / 2;+ let comparison = Key::compare_two_keys(records[middle].key(), key);+ if comparison < 0 || (comparison == 0 && open) {+ low = middle + 1;+ } else {+ high = middle;+ }+ }++ low+}++fn first_record_index_with_key_after<R: KeyedRecord>(records: &[R], key: &Key, open: bool, start: usize) -> usize {+ let mut low = start;+ let mut high = records.len();++ while low < high {+ let middle = low + (high - low) / 2;+ let comparison = Key::compare_two_keys(records[middle].key(), key);+ if comparison < 0 || (comparison == 0 && !open) {+ low = middle + 1;+ } else {+ high = middle;+ }+ }++ low+}++pub(crate) fn record_range_for_key_range<R: KeyedRecord>(records: &[R], range: &IDBKeyRange) -> RecordRange {+ let mut start = 0;+ let mut end = records.len();++ if let Some(lower) = range.lower_key() {+ start = first_record_index_with_key_at_or_after(records, lower, range.is_lower_open());+ }++ if let Some(upper) = range.upper_key() {+ end = first_record_index_with_key_after(records, upper, range.is_upper_open(), start);+ }++ RecordRange { start, end }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/request_list.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/request_list.rsnew file mode 100644index 00000000000..0dd141f2413--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/request_list.rs@@ -0,0 +1,156 @@+/*+ * Copyright (c) 2024, stelar7 <[email protected]>+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The request lists of transactions, https://w3c.github.io/IndexedDB/#transaction-request-list, and of connection queues++use core::cell::Cell;++use libjs_rust::api::{DeferGc, GcRefCell, MarkedVec, Trace, Vm};++use crate::indexed_db::idb_request::{AnyIDBRequest, WeakIDBRequest};+use crate::indexed_db::internal::algorithms::queue_a_database_task;+use crate::indexed_db::internal::function::{Function, call_function};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct Entry {+ #[gc(untraced = "the request is weak")]+ request: WeakIDBRequest,+ steps: Option<Function>,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct RequestList {+ entries: GcRefCell<Vec<Entry>>,+ on_all_processed: Cell<Option<Function>>,+ blocked: Cell<bool>,+}++impl RequestList {+ pub(crate) fn new(_: &DeferGc<'_>) -> Self {+ Self {+ entries: GcRefCell::new(Vec::new()),+ on_all_processed: Cell::new(None),+ blocked: Cell::new(false),+ }+ }++ pub(crate) fn enqueue(&self, vm: &Vm, request: AnyIDBRequest, steps: Function) {+ self.entries.borrow_mut(vm).push(Entry {+ request: WeakIDBRequest::new(vm, request),+ steps: Some(steps),+ });+ self.maybe_process_next_request(vm);+ }++ pub(crate) fn maybe_process_next_request(&self, vm: &Vm) {+ if self.blocked.get() {+ return;+ }++ let mut entries = self.entries.borrow_mut(vm);+ while entries.first().is_some_and(|entry| entry.request.get().is_none()) {+ entries.remove(0);+ }++ let mut steps_to_queue = None;+ for entry in entries.iter_mut() {+ let Some(request) = entry.request.get() else {+ continue;+ };+ if request.processed() {+ continue;+ }+ if request.aborted() {+ continue;+ }++ // If the steps are null here, the request is still executing, so we should wait until it is finished.+ let Some(steps) = entry.steps else {+ return;+ };++ steps_to_queue = Some(steps);+ entry.steps = None;+ break;+ }+ drop(entries);++ if let Some(steps) = steps_to_queue {+ queue_a_database_task(vm, steps);+ }+ }++ pub(crate) fn on_request_processed(&self, vm: &Vm) {+ self.maybe_process_next_request(vm);+ }++ pub(crate) fn remove(&self, vm: &Vm, request: AnyIDBRequest) {+ let mut entries = self.entries.borrow_mut(vm);+ if let Some(position) = entries.iter().position(|entry| entry.request.get() == Some(request)) {+ entries.remove(position);+ }+ }++ pub(crate) fn is_empty(&self) -> bool {+ self.entries.borrow().is_empty()+ }++ pub(crate) fn block_execution(&self) {+ self.blocked.set(true);+ }++ pub(crate) fn execution_is_blocked(&self) -> bool {+ self.blocked.get()+ }++ pub(crate) fn unblock_execution(&self, vm: &Vm) {+ self.blocked.set(false);+ self.maybe_process_next_request(vm);+ }++ pub(crate) fn set_on_all_processed(&self, vm: &Vm, callback: Function) {+ self.on_all_processed.set(Some(callback));+ self.check_all_processed(vm);+ }++ pub(crate) fn clear_on_all_processed(&self) {+ self.on_all_processed.set(None);+ }++ pub(crate) fn check_all_processed(&self, vm: &Vm) {+ if self.on_all_processed.get().is_none() {+ return;+ }++ {+ let mut entries = self.entries.borrow_mut(vm);+ entries.retain(|entry| entry.request.get().is_some());++ for entry in entries.iter() {+ if !entry.request.get().expect("the request is live").processed() {+ return;+ }+ }+ }++ let callback = self.on_all_processed.take().expect("a callback is set");+ call_function(vm, callback);+ }++ pub(crate) fn requests<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, AnyIDBRequest> {+ let requests = MarkedVec::new(vm);+ for entry in self.entries.borrow().iter() {+ if let Some(request) = entry.request.get() {+ requests.push(request);+ }+ }+ requests+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/storage.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/storage.rsnew file mode 100644index 00000000000..b75849b416d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/storage.rs@@ -0,0 +1,196 @@+/*+ * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The databases of the agent, by their storage key and name, and the connection queues of those,+//! https://w3c.github.io/IndexedDB/#connection-queues. They live as long as the thread of the agent.++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, Trace, Vm};+use liburl_rust::origin::Origin;++use crate::indexed_db::internal::database::DatabaseRef;+use crate::indexed_db::internal::request_list::RequestList;++unsafe extern "C" {+ fn gc_root_create(cell: *mut c_void) -> *mut c_void;+}++// https://storage.spec.whatwg.org/#storage-keys+#[derive(Clone)]+pub(crate) struct StorageKey {+ // A storage key is a tuple consisting of an origin (an origin). [HTML]+ // NOTE: This is expected to change; see Client-Side Storage Partitioning https://privacycg.github.io/storage-partitioning/.+ pub(crate) origin: Origin,+}++impl PartialEq for StorageKey {+ fn eq(&self, other: &Self) -> bool {+ // To determine whether a storage key A equals storage key B, run these steps:+ // 1. If A’s origin is not same origin with B’s origin, then return false.+ // 2. Return true.+ self.origin.is_same_origin(&other.origin)+ }+}++// https://w3c.github.io/IndexedDB/#connection-queues+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ConnectionQueue {+ #[gc(untraced)]+ storage_key: StorageKey,+ name: Utf16String,+ pub(crate) request_list: RequestList,+}++static CONNECTION_QUEUE_CLASS: EmbedderClass<ConnectionQueue> = EmbedderClass::new("IndexedDBConnectionQueue");++impl EmbedderValue for ConnectionQueue {+ const CLASS: &'static EmbedderClass<Self> = &CONNECTION_QUEUE_CLASS;+}++pub(crate) type ConnectionQueueRef = Gc<EmbedderCell<ConnectionQueue>>;++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct DatabasesOfKey {+ #[gc(untraced)]+ storage_key: StorageKey,+ databases: Vec<(Utf16String, DatabaseRef)>,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Storage {+ databases: GcRefCell<Vec<DatabasesOfKey>>,+ connection_queues: GcRefCell<Vec<ConnectionQueueRef>>,+}++static STORAGE_CLASS: EmbedderClass<Storage> = EmbedderClass::new("IndexedDBStorage");++impl EmbedderValue for Storage {+ const CLASS: &'static EmbedderClass<Self> = &STORAGE_CLASS;+}++pub(crate) type StorageRef = Gc<EmbedderCell<Storage>>;++thread_local! {+ // NB: Keeping the root here lets the leak checker see it as reachable.+ static STORAGE: Cell<Option<(StorageRef, NonNull<c_void>)>> = const { Cell::new(None) };+}++/// The storage of the current thread's agent, created on first use.+pub(crate) fn storage(vm: &Vm) -> StorageRef {+ if let Some((storage, _)) = STORAGE.get() {+ return storage;+ }+ let storage = STORAGE_CLASS.allocate(vm, |_| Storage {+ databases: GcRefCell::new(Vec::new()),+ connection_queues: GcRefCell::new(Vec::new()),+ });+ // NB: The storage lives as long as the thread, which roots its cell.+ // SAFETY: The cell is a live cell of the heap.+ let root = NonNull::new(unsafe { gc_root_create(storage.as_ptr().cast()) }).expect("a root is allocated");+ STORAGE.set(Some((storage, root)));+ storage+}++impl Storage {+ pub(crate) fn for_each_database(&self, mut visitor: impl FnMut(DatabaseRef)) {+ for databases_of_key in self.databases.borrow().iter() {+ for (_, database) in &databases_of_key.databases {+ visitor(*database);+ }+ }+ }++ pub(crate) fn for_each_database_of_key(&self, key: &StorageKey, mut visitor: impl FnMut(DatabaseRef)) {+ for databases_of_key in self.databases.borrow().iter() {+ if databases_of_key.storage_key != *key {+ continue;+ }+ for (_, database) in &databases_of_key.databases {+ visitor(*database);+ }+ }+ }++ pub(crate) fn database(&self, key: &StorageKey, name: &Utf16String) -> Option<DatabaseRef> {+ let databases = self.databases.borrow();+ let databases_of_key = databases.iter().find(|entry| entry.storage_key == *key)?;+ databases_of_key+ .databases+ .iter()+ .find(|(database_name, _)| database_name == name)+ .map(|(_, database)| *database)+ }++ pub(crate) fn set_database(&self, vm: &Vm, key: &StorageKey, name: &Utf16String, database: DatabaseRef) {+ let mut databases = self.databases.borrow_mut(vm);+ let databases_of_key = match databases.iter().position(|entry| entry.storage_key == *key) {+ Some(position) => &mut databases[position],+ None => {+ databases.push(DatabasesOfKey {+ storage_key: key.clone(),+ databases: Vec::new(),+ });+ databases.last_mut().expect("an entry was just added")+ }+ };+ if let Some(entry) = databases_of_key+ .databases+ .iter_mut()+ .find(|(database_name, _)| database_name == name)+ {+ entry.1 = database;+ return;+ }+ databases_of_key.databases.push((name.clone(), database));+ }++ pub(crate) fn remove_database(&self, vm: &Vm, key: &StorageKey, name: &Utf16String) {+ let mut databases = self.databases.borrow_mut(vm);+ let Some(databases_of_key) = databases.iter_mut().find(|entry| entry.storage_key == *key) else {+ return;+ };+ if let Some(position) = databases_of_key+ .databases+ .iter()+ .position(|(database_name, _)| database_name == name)+ {+ databases_of_key.databases.remove(position);+ }+ }++ // https://w3c.github.io/IndexedDB/#connection-queue+ pub(crate) fn connection_queue_for_key_and_name(+ &self,+ vm: &Vm,+ key: &StorageKey,+ name: &Utf16String,+ ) -> ConnectionQueueRef {+ if let Some(queue) = self+ .connection_queues+ .borrow()+ .iter()+ .find(|queue| queue.storage_key == *key && queue.name == *name)+ {+ return *queue;+ }++ let new_queue = CONNECTION_QUEUE_CLASS.allocate(vm, |defer| ConnectionQueue {+ storage_key: key.clone(),+ name: name.clone(),+ request_list: RequestList::new(defer),+ });+ self.connection_queues.borrow_mut(vm).push(new_queue);+ new_queue+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/mod.rsnew file mode 100644index 00000000000..b6ee4c19fdb--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/mod.rs@@ -0,0 +1,23 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Indexed Database API, https://w3c.github.io/IndexedDB/++pub(crate) mod cpp;+pub(crate) mod exports;+pub(crate) mod idb_cursor;+pub(crate) mod idb_cursor_with_value;+pub(crate) mod idb_database;+pub(crate) mod idb_factory;+pub(crate) mod idb_index;+pub(crate) mod idb_key_range;+pub(crate) mod idb_object_store;+pub(crate) mod idb_open_db_request;+pub(crate) mod idb_record;+pub(crate) mod idb_request;+pub(crate) mod idb_transaction;+pub(crate) mod idb_version_change_event;+pub(crate) mod internal;diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 360d35459f3..920eecbb876 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -95,6 +95,16 @@ pub(crate) mod geometry;reason = "the bindings call every attribute and operation as one that can throw")]pub(crate) mod html;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]+pub(crate) mod indexed_db;#[cfg_attr(not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces")diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex ac12248c790..d82b336724a 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -694,25 +694,9 @@ set(SOURCESHTML/Worklet.cppHTML/WorkletGlobalScope.cppHTML/XMLSerializer.cpp- IndexedDB/Inspection.cpp- IndexedDB/IDBCursor.cpp- IndexedDB/IDBDatabase.cppIndexedDB/IDBFactory.cpp- IndexedDB/IDBIndex.cpp- IndexedDB/IDBKeyRange.cpp- IndexedDB/IDBObjectStore.cpp- IndexedDB/IDBOpenDBRequest.cpp- IndexedDB/IDBRecord.cpp- IndexedDB/IDBRequest.cpp- IndexedDB/IDBTransaction.cpp- IndexedDB/IDBVersionChangeEvent.cpp- IndexedDB/Internal/Algorithms.cpp- IndexedDB/Internal/Database.cpp- IndexedDB/Internal/Index.cpp- IndexedDB/Internal/Key.cpp- IndexedDB/Internal/MutationLog.cpp- IndexedDB/Internal/ObjectStore.cpp- IndexedDB/Internal/RequestList.cpp+ IndexedDB/Inspection.cpp+ IndexedDB/RustIntegration.cppInfra/ByteSequences.cppInfra/JSON.cppInternals/FakeXRDevice.cppdiff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 804571740f6..e0000e2a83c 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -858,25 +858,7 @@ class Performance;namespace Web::IndexedDB {-class Database;-class IDBCursor;-class IDBCursorWithValue;-class IDBDatabase;class IDBFactory;-class IDBIndex;-class IDBKeyRange;-class IDBObjectStore;-class IDBOpenDBRequest;-class IDBRecord;-class IDBRequest;-class IDBTransaction;-class IDBVersionChangeEvent;-class Index;-class Key;-class ObjectStore;-class RequestList;--using CursorDirection = Bindings::IDBCursorDirection;}diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cppindex 7bb99f92a58..1eb4de86bd0 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp@@ -41,7 +41,7 @@#include <LibWeb/HTML/WorkletGlobalScope.h>#include <LibWeb/HighResolutionTime/Performance.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>+#include <LibWeb/IndexedDB/IDBFactory.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/Layout/NodeArena.h>#include <LibWeb/Layout/TreeBuilderRustFFI.h>diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex 3f651948cc7..3816b9bec8e 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -60,9 +60,7 @@#include <LibWeb/HighResolutionTime/Performance.h>#include <LibWeb/HighResolutionTime/SupportedPerformanceTypes.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/IndexedDB/IDBDatabase.h>#include <LibWeb/IndexedDB/IDBFactory.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>#include <LibWeb/Infra/SerializedURL.h>#include <LibWeb/LargestContentfulPaint/LargestContentfulPaint.h>#include <LibWeb/Loader/LoaderConfig.h>@@ -1349,14 +1347,7 @@ void WindowOrWorkerGlobalScopeMixin::remove_strong_reference_to_broadcast_channevoid WindowOrWorkerGlobalScopeMixin::close_all_idb_connections(){- IndexedDB::Database::for_each_database([&](IndexedDB::Database& database) {- for (auto& connection : database.associated_connections_as_root_vector()) {- if (connection->close_pending())- continue;- if (&connection->relevant_global_scope() == this)- IndexedDB::close_a_database_connection(connection);- }- });+ IndexedDB::close_all_database_connections(relevant_realm(*this));}void WindowOrWorkerGlobalScopeMixin::register_web_socket(Badge<WebSockets::WebSocket>, GC::Ref<WebSockets::WebSocket> web_socket)@@ -1683,7 +1674,7 @@ GC::Ref<HighResolutionTime::Performance> WindowOrWorkerGlobalScopeMixin::performGC::Ref<IndexedDB::IDBFactory> WindowOrWorkerGlobalScopeMixin::indexed_db(){if (!m_indexed_db)- m_indexed_db = GC::Heap::the().allocate<IndexedDB::IDBFactory>(*this);+ m_indexed_db = IndexedDB::IDBFactory::create(relevant_realm(*this));return *m_indexed_db;}diff --git a/Libraries/LibWeb/IndexedDB/BindingsGlue.h b/Libraries/LibWeb/IndexedDB/BindingsGlue.hdeleted file mode 100644index 6f889e65e41..00000000000--- a/Libraries/LibWeb/IndexedDB/BindingsGlue.h+++ /dev/null@@ -1,33 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Types.h>-#include <LibGC/Forward.h>-#include <LibJS/Forward.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Export.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::IndexedDB {--class IDBKeyRange;--}--namespace Web::Bindings {--WEB_API IndexedDB::IDBKeyRange* key_range_from_value(JS::Value);-WEB_API WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> only(JS::Realm&, JS::Value);-WEB_API WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> lower_bound(JS::Realm&, JS::Value, bool open);-WEB_API WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> upper_bound(JS::Realm&, JS::Value, bool open);-WEB_API WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> bound(JS::Realm&, JS::Value lower, JS::Value upper, bool lower_open, bool upper_open);-WEB_API WebIDL::ExceptionOr<bool> includes(JS::Realm&, IndexedDB::IDBKeyRange&, JS::Value key);-WEB_API JS::Value key_range_lower(JS::Realm&, IndexedDB::IDBKeyRange&);-WEB_API JS::Value key_range_upper(JS::Realm&, IndexedDB::IDBKeyRange&);--}diff --git a/Libraries/LibWeb/IndexedDB/ConnectionState.h b/Libraries/LibWeb/IndexedDB/ConnectionState.hdeleted file mode 100644index 24fc4b3ab62..00000000000--- a/Libraries/LibWeb/IndexedDB/ConnectionState.h+++ /dev/null@@ -1,16 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--namespace Web::IndexedDB {--enum ConnectionState {- Open,- Closed,-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBCursor.cpp b/Libraries/LibWeb/IndexedDB/IDBCursor.cppdeleted file mode 100644index b5cfb0bec4c..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBCursor.cpp+++ /dev/null@@ -1,487 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/IndexedDB/IDBCursor.h>-#include <LibWeb/IndexedDB/IDBCursorWithValue.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBCursor);--IDBCursor::~IDBCursor() = default;--JS::Value IDBCursor::key(JS::Realm& realm)-{- // The key getter steps are to return the result of converting a key to a- // value with the cursor's current key.- // NOTE: If key returns an object (e.g. a Date or Array), it returns the same object instance every time it is- // inspected, until the cursor's key is changed. This means that if the object is modified, those- // modifications will be seen by anyone inspecting the value of the cursor. However modifying such an object- // does not modify the contents of the database.- auto key = current_key();- if (!key)- return JS::js_undefined();-- if (m_cached_key_value.key != key)- m_cached_key_value = { key, convert_a_key_to_a_value(realm, *key) };- return m_cached_key_value.value;-}--JS::Value IDBCursor::primary_key(JS::Realm& realm)-{- // The primaryKey getter steps are to return the result of converting a key- // to a value with the cursor's current effective key.- // NOTE: If primaryKey returns an object (e.g. a Date or Array), it returns the same object instance every time it- // is inspected, until the cursor's effective key is changed. This means that if the object is modified,- // those modifications will be seen by anyone inspecting the value of the cursor. However modifying such an- // object does not modify the contents of the database.- // AD-HOC: The effective key of a cursor whose key is undefined is undefined too, as in other engines.- if (!current_key())- return JS::js_undefined();-- auto effective_key = this->effective_key();- if (m_cached_primary_key_value.key.ptr() != effective_key.ptr())- m_cached_primary_key_value = { effective_key, convert_a_key_to_a_value(realm, effective_key) };- return m_cached_primary_key_value.value;-}--IDBCursor::IDBCursor(CursorSourceHandle source_handle, GC::Ptr<Key> position, CursorDirection direction, GotValue got_value, GC::Ptr<Key> key, JS::Value value, GC::Ref<IDBKeyRange> range, KeyOnly key_only)- : m_key(key)- , m_value(value)- , m_position(position)- , m_direction(direction)- , m_got_value(got_value == GotValue::Yes)- , m_source_handle(source_handle)- , m_range(range)- , m_key_only(key_only == KeyOnly::Yes)-{-}--GC::Ref<IDBCursor> IDBCursor::create(CursorSourceHandle source_handle, GC::Ptr<Key> position, CursorDirection direction, GotValue got_value, GC::Ptr<Key> key, JS::Value value, GC::Ref<IDBKeyRange> range, KeyOnly key_only)-{- // A cursor that has its key only flag set to false implements the IDBCursorWithValue interface as well.- if (key_only == KeyOnly::No)- return GC::Heap::the().allocate<IDBCursorWithValue>(source_handle, position, direction, got_value, key, value, range, key_only);-- return GC::Heap::the().allocate<IDBCursor>(source_handle, position, direction, got_value, key, value, range, key_only);-}--void IDBCursor::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_position);- visitor.visit(m_object_store_position);- visitor.visit(m_key);- visitor.visit(m_range);- visitor.visit(m_request);-- visitor.visit(m_value);- visitor.visit(m_cached_key_value.key);- visitor.visit(m_cached_key_value.value);- visitor.visit(m_cached_primary_key_value.key);- visitor.visit(m_cached_primary_key_value.value);-- m_source_handle.visit([&](auto& source) {- visitor.visit(source);- });-}--GC_DEFINE_ALLOCATOR(IDBCursorWithValue);--IDBCursorWithValue::~IDBCursorWithValue() = default;--IDBCursorWithValue::IDBCursorWithValue(CursorSourceHandle source_handle, GC::Ptr<Key> position, CursorDirection direction, GotValue got_value, GC::Ptr<Key> key, JS::Value value, GC::Ref<IDBKeyRange> range, KeyOnly key_only)- : IDBCursor(source_handle, position, direction, got_value, key, value, range, key_only)-{-}--bool IDBCursor::is_source_or_object_store_deleted() const-{- return m_source_handle.visit(- [](GC::Ref<IDBObjectStore> object_store) {- return object_store->store()->is_deleted();- },- [](GC::Ref<IDBIndex> index) {- return index->index()->is_deleted() || index->index()->object_store()->is_deleted();- });-}--// https://w3c.github.io/IndexedDB/#cursor-transaction-GC::Ref<IDBTransaction> IDBCursor::transaction()-{- // A cursor has a transaction, which is the transaction from the cursor’s source handle.- return m_source_handle.visit(- [](GC::Ref<IDBObjectStore> object_store) { return object_store->transaction(); },- [](GC::Ref<IDBIndex> index) { return index->transaction(); });-}--JS::Object& IDBCursor::relevant_global_object() const-{- return m_source_handle.visit([](auto const& source) -> JS::Object& {- return source->relevant_global_object();- });-}--// https://w3c.github.io/IndexedDB/#cursor-source-CursorSource IDBCursor::internal_source()-{- // A cursor has a source, which is an index or an object store from the cursor’s source handle.- return m_source_handle.visit(- [](GC::Ref<IDBObjectStore> object_store) -> CursorSource { return object_store->store(); },- [](GC::Ref<IDBIndex> index) -> CursorSource { return index->index(); });-}--// https://w3c.github.io/IndexedDB/#dom-idbcursor-continue-WebIDL::ExceptionOr<void> IDBCursor::continue_(Optional<JS::Value> key)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this's transaction.- auto transaction = this->transaction();-- // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while continuing cursor"_utf16);-- // 3. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.- if (is_source_or_object_store_deleted())- return WebIDL::InvalidStateError::create("Source or its object store has been deleted"_utf16);-- // 4. If this's got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.- if (!m_got_value)- return WebIDL::InvalidStateError::create("Cursor is active or EOL while continuing"_utf16);-- // 5. If key is given, then:- GC::Ptr<Key> key_value;- if (key.has_value()) {- // 1. Let r be the result of converting a value to a key with key. Rethrow any exceptions.- auto r = TRY(convert_a_value_to_a_key(realm, *key));-- // 2. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (r->is_invalid())- return WebIDL::DataError::create(r->value_as_string());-- // 3. Let key be r.- key_value = r;-- // 4. If key is less than or equal to this's position and this's direction is "next" or "nextunique", then throw a "DataError" DOMException.- auto is_less_than_or_equal_to = Key::less_than(*key_value, *this->position()) || Key::equals(*key_value, *this->position());- if (is_less_than_or_equal_to && (m_direction == CursorDirection::Next || m_direction == CursorDirection::Nextunique))- return WebIDL::DataError::create("Key is less than or equal to cursor's position"_utf16);-- // 5. If key is greater than or equal to this's position and this's direction is "prev" or "prevunique", then throw a "DataError" DOMException.- auto is_greater_than_or_equal_to = Key::greater_than(*key_value, *this->position()) || Key::equals(*key_value, *this->position());- if (is_greater_than_or_equal_to && (m_direction == CursorDirection::Prev || m_direction == CursorDirection::Prevunique))- return WebIDL::DataError::create("Key is greater than or equal to cursor's position"_utf16);- }-- // 6. Set this's got value flag to false.- m_got_value = false;-- // 7. Let request be this's request.- auto request = this->request();-- // 8. Set request’s processed flag to false.- request->set_processed(false);-- // 9. Set request’s done flag to false.- request->set_done(false);-- // 10. Let operation be an algorithm to run iterate a cursor with the current Realm record, this, and key (if given).- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [this, &realm, key_value] -> WebIDL::ExceptionOr<JS::Value> {- auto result = TRY(iterate_a_cursor(realm, *this, key_value));- return Bindings::idb_cursor_result(realm, result);- });-- // 11. Run asynchronously execute a request with this’s source handle, operation, and request.- asynchronously_execute_a_request(realm, source_handle(), operation, request);- dbgln_if(IDB_DEBUG, "Executing request for cursor continue with uuid {}", request->uuid());-- return {};-}--// https://w3c.github.io/IndexedDB/#cursor-effective-key-[[nodiscard]] GC::Ref<Key> IDBCursor::effective_key() const-{- return m_source_handle.visit(- [&](GC::Ref<IDBObjectStore>) -> GC::Ref<Key> {- // If the source of a cursor is an object store, the effective key of the cursor is the cursor’s position- return *m_position;- },- [&](GC::Ref<IDBIndex>) -> GC::Ref<Key> {- // If the source of a cursor is an index, the effective key is the cursor’s object store position.- return *m_object_store_position;- });-}--// https://w3c.github.io/IndexedDB/#dom-idbcursor-advance-WebIDL::ExceptionOr<void> IDBCursor::advance(WebIDL::UnsignedLong count)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. If count is 0 (zero), throw a TypeError.- if (count == 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Count must not be zero (0)"_utf16 };-- // 2. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 3. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while advancing cursor"_utf16);-- // 4. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.- if (is_source_or_object_store_deleted())- return WebIDL::InvalidStateError::create("Source or its object store has been deleted"_utf16);-- // 5. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.- if (!m_got_value)- return WebIDL::InvalidStateError::create("Cursor is active or EOL while advancing"_utf16);-- // 6. Set this’s got value flag to false.- m_got_value = false;-- // 7. Let request be this’s request.- auto request = this->request();-- // 8. Set request’s processed flag to false.- request->set_processed(false);-- // 9. Set request’s done flag to false.- request->set_done(false);-- // 10. Let operation be an algorithm to run iterate a cursor with the current Realm record, this, and count.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [this, &realm, count] -> WebIDL::ExceptionOr<JS::Value> {- auto result = TRY(iterate_a_cursor(realm, *this, nullptr, nullptr, count));- return Bindings::idb_cursor_result(realm, result);- });-- // 11. Run asynchronously execute a request with this’s source handle, operation, and request.- asynchronously_execute_a_request(realm, source_handle(), operation, request);- dbgln_if(IDB_DEBUG, "Executing request for cursor advance with uuid {}", request->uuid());-- return {};-}--// https://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey-WebIDL::ExceptionOr<void> IDBCursor::continue_primary_key(JS::Value key_param, JS::Value primary_key_param)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while continuing cursor"_utf16);-- // 3. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.- if (is_source_or_object_store_deleted())- return WebIDL::InvalidStateError::create("Source or its object store has been deleted"_utf16);-- // 4. If this’s source is not an index throw an "InvalidAccessError" DOMException.- if (!m_source_handle.has<GC::Ref<IDBIndex>>())- return WebIDL::InvalidAccessError::create("Cursor source is not an index"_utf16);-- // 5. If this’s direction is not "next" or "prev", throw an "InvalidAccessError" DOMException.- if (m_direction != CursorDirection::Next && m_direction != CursorDirection::Prev)- return WebIDL::InvalidAccessError::create("Cursor direction is not next or prev"_utf16);-- // 6. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.- if (!m_got_value)- return WebIDL::InvalidStateError::create("Cursor is active or EOL while continuing"_utf16);-- // 7. Let r be the result of converting a value to a key with key. Rethrow any exceptions.- auto r = TRY(convert_a_value_to_a_key(realm, key_param));-- // 8. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (r->is_invalid())- return WebIDL::DataError::create(r->value_as_string());-- // 9. Let key be r.- auto key = r;-- // 10. Let r be the result of converting a value to a key with primaryKey. Rethrow any exceptions.- r = TRY(convert_a_value_to_a_key(realm, primary_key_param));-- // 11. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (r->is_invalid())- return WebIDL::DataError::create(r->value_as_string());-- // 12. Let primaryKey be r.- auto primary_key = r;-- // 13. If key is less than this’s position and this’s direction is "next", throw a "DataError" DOMException.- if (Key::less_than(*key, *this->position()) && m_direction == CursorDirection::Next)- return WebIDL::DataError::create("Key is less than cursor's position"_utf16);-- // 14. If key is greater than this’s position and this’s direction is "prev", throw a "DataError" DOMException.- if (Key::greater_than(*key, *this->position()) && m_direction == CursorDirection::Prev)- return WebIDL::DataError::create("Key is greater than cursor's position"_utf16);-- // 15. If key is equal to this’s position and primaryKey is less than or equal to this’s object store position and this’s direction is "next", throw a "DataError" DOMException.- if (Key::equals(*key, *this->position()) && (Key::less_than(*primary_key, *this->object_store_position()) || Key::equals(*primary_key, *this->object_store_position())) && m_direction == CursorDirection::Next)- return WebIDL::DataError::create("Key is equal to cursor's position"_utf16);-- // 16. If key is equal to this’s position and primaryKey is greater than or equal to this’s object store position and this’s direction is "prev", throw a "DataError" DOMException.- if (Key::equals(*key, *this->position()) && (Key::greater_than(*primary_key, *this->object_store_position()) || Key::equals(*primary_key, *this->object_store_position())) && m_direction == CursorDirection::Prev)- return WebIDL::DataError::create("Key is equal to cursor's position"_utf16);-- // 17. Set this’s got value flag to false.- m_got_value = false;-- // 18. Let request be this’s request.- auto request = this->request();-- // 19. Set request’s processed flag to false.- request->set_processed(false);-- // 20. Set request’s done flag to false.- request->set_done(false);-- // 21. Let operation be an algorithm to run iterate a cursor with the current Realm record, this, key, and primaryKey.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [this, &realm, key, primary_key] -> WebIDL::ExceptionOr<JS::Value> {- auto result = TRY(iterate_a_cursor(realm, *this, key, primary_key));- return Bindings::idb_cursor_result(realm, result);- });-- // 22. Run asynchronously execute a request with this’s source handle, operation, and request.- asynchronously_execute_a_request(realm, source_handle(), operation, request);- dbgln_if(IDB_DEBUG, "Executing request for cursor continue with primary key with uuid {}", request->uuid());-- return {};-}--// https://w3c.github.io/IndexedDB/#cursor-effective-object-store-GC::Ref<ObjectStore> IDBCursor::effective_object_store() const-{- return m_source_handle.visit(- [&](GC::Ref<IDBObjectStore> store) -> GC::Ref<ObjectStore> {- // If the source of a cursor is an object store, the effective object store of the cursor is that object store.- return store->store();- },- [&](GC::Ref<IDBIndex> index) -> GC::Ref<ObjectStore> {- // If the source of a cursor is an index, the effective object store of the cursor is that index’s referenced object store.- return index->object_store()->store();- });-}--// https://w3c.github.io/IndexedDB/#dom-idbcursor-update-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBCursor::update(JS::Value value)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while updating cursor"_utf16);-- // 3. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.- if (transaction->is_readonly())- return WebIDL::ReadOnlyError::create("Transaction is read-only while updating cursor"_utf16);-- // 4. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.- if (is_source_or_object_store_deleted())- return WebIDL::InvalidStateError::create("Source or its object store has been deleted"_utf16);-- // 5. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.- if (!m_got_value)- return WebIDL::InvalidStateError::create("Cursor is active or EOL while updating"_utf16);-- // 6. If this’s key only flag is true, throw an "InvalidStateError" DOMException.- if (m_key_only)- return WebIDL::InvalidStateError::create("Cursor is key-only while updating"_utf16);-- // 7. Let targetRealm be a user-agent defined Realm.- // NOTE: this is 'realm' above-- // 8. Let clone be a clone of value in targetRealm during transaction. Rethrow any exceptions.- auto clone = TRY(clone_in_realm(realm, value, transaction));-- // 9. If this’s effective object store uses in-line keys, then:- auto effective_object_store = this->effective_object_store();- if (effective_object_store->uses_inline_keys()) {- // 1. Let kpk be the result of extracting a key from a value using a key path with clone and the key path of this’s effective object store. Rethrow any exceptions.- auto kpk = TRY(extract_a_key_from_a_value_using_a_key_path(realm, clone, *effective_object_store->key_path()));-- // 2. If kpk is failure, invalid, or not equal to this’s effective key, throw a "DataError" DOMException.- if (kpk.is_error())- return WebIDL::DataError::create("Key path is invalid"_utf16);-- auto kpk_value = kpk.release_value();- if (kpk_value->is_invalid())- return WebIDL::DataError::create("Key path is invalid"_utf16);-- if (!Key::equals(*kpk_value, *this->effective_key()))- return WebIDL::DataError::create("Key path is not equal to effective key"_utf16);- }-- // 10. Let operation be an algorithm to run store a record into an object store with this’s effective object store, clone, this’s effective key, and false.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [this, &realm, clone] -> WebIDL::ExceptionOr<JS::Value> {- HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- auto optional_key = TRY(store_a_record_into_an_object_store(realm, *this->effective_object_store(), clone, this->effective_key(), false));-- if (!optional_key || optional_key->is_invalid())- return JS::js_undefined();-- return convert_a_key_to_a_value(realm, GC::Ref(*optional_key));- });-- // 11. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto request = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for cursor update with uuid {}", request->uuid());- return request;-}--// https://w3c.github.io/IndexedDB/#dom-idbcursor-delete-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBCursor::delete_()-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while deleting cursor"_utf16);-- // 3. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.- if (transaction->is_readonly())- return WebIDL::ReadOnlyError::create("Transaction is read-only while deleting cursor"_utf16);-- // 4. If this’s source or effective object store has been deleted, throw an "InvalidStateError" DOMException.- if (is_source_or_object_store_deleted())- return WebIDL::InvalidStateError::create("Source or its object store has been deleted"_utf16);-- // 5. If this’s got value flag is false, indicating that the cursor is being iterated or has iterated past its end, throw an "InvalidStateError" DOMException.- if (!m_got_value)- return WebIDL::InvalidStateError::create("Cursor is active or EOL while deleting"_utf16);-- // 6. If this’s key only flag is true, throw an "InvalidStateError" DOMException.- if (m_key_only)- return WebIDL::InvalidStateError::create("Cursor is key-only while deleting"_utf16);-- // 7. Let operation be an algorithm to run delete records from an object store with this’s effective object store and this’s effective key.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [this] -> WebIDL::ExceptionOr<JS::Value> {- auto effective_key = this->effective_key();- auto range = IDBKeyRange::create(effective_key, effective_key, IDBKeyRange::LowerOpen::No, IDBKeyRange::UpperOpen::No);- return delete_records_from_an_object_store(*this->effective_object_store(), range);- });-- // 8. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto request = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for cursor delete with uuid {}", request->uuid());- return request;-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBCursor.h b/Libraries/LibWeb/IndexedDB/IDBCursor.hdeleted file mode 100644index b9ac80c1e74..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBCursor.h+++ /dev/null@@ -1,120 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Heap.h>-#include <LibWeb/Bindings/IDBCursor.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/IndexedDB/IDBIndex.h>-#include <LibWeb/IndexedDB/IDBKeyRange.h>-#include <LibWeb/IndexedDB/IDBObjectStore.h>-#include <LibWeb/IndexedDB/IDBTransaction.h>-#include <LibWeb/IndexedDB/Internal/Key.h>--namespace Web::IndexedDB {--using CursorSourceHandle = Variant<GC::Ref<IDBObjectStore>, GC::Ref<IDBIndex>>;-using CursorSource = Variant<GC::Ref<ObjectStore>, GC::Ref<Index>>;--// https://w3c.github.io/IndexedDB/#cursor-interface-class IDBCursor : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(IDBCursor, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(IDBCursor);-- enum class GotValue {- No,- Yes,- };-- enum class KeyOnly {- No,- Yes,- };--public:- static constexpr size_t request_offset() { return offsetof(IDBCursor, m_request); }- virtual ~IDBCursor() override;- [[nodiscard]] static GC::Ref<IDBCursor> create(CursorSourceHandle, GC::Ptr<Key>, CursorDirection, GotValue, GC::Ptr<Key>, JS::Value, GC::Ref<IDBKeyRange>, KeyOnly);-- [[nodiscard]] CursorSourceHandle source_handle() { return m_source_handle; }- [[nodiscard]] CursorDirection direction() { return m_direction; }- JS::Value key(JS::Realm&);- JS::Value primary_key(JS::Realm&);- [[nodiscard]] GC::Ptr<IDBRequest> request() { return m_request; }-- WebIDL::ExceptionOr<void> advance(WebIDL::UnsignedLong);- WebIDL::ExceptionOr<void> continue_(Optional<JS::Value>);- WebIDL::ExceptionOr<void> continue_primary_key(JS::Value, JS::Value);-- WebIDL::ExceptionOr<GC::Ref<IDBRequest>> update(JS::Value);- WebIDL::ExceptionOr<GC::Ref<IDBRequest>> delete_();-- [[nodiscard]] bool is_source_or_object_store_deleted() const;-- [[nodiscard]] GC::Ref<IDBKeyRange> range() { return m_range; }- [[nodiscard]] GC::Ptr<Key> position() { return m_position; }- [[nodiscard]] GC::Ptr<Key> current_key() const { return m_key; }- [[nodiscard]] GC::Ptr<Key> object_store_position() { return m_object_store_position; }- [[nodiscard]] bool key_only() const { return m_key_only; }- [[nodiscard]] bool got_value() const { return m_got_value; }- [[nodiscard]] GC::Ref<IDBTransaction> transaction();- [[nodiscard]] JS::Object& relevant_global_object() const;- [[nodiscard]] CursorSource internal_source();- [[nodiscard]] GC::Ref<Key> effective_key() const;- [[nodiscard]] GC::Ref<ObjectStore> effective_object_store() const;-- void set_request(GC::Ptr<IDBRequest> request) { m_request = request; }- void set_position(GC::Ptr<Key> position) { m_position = position; }- void set_got_value(bool got_value) { m_got_value = got_value; }- void set_key(GC::Ptr<Key> key) { m_key = key; }- void set_value(JS::Value value) { m_value = value; }- void set_object_store_position(GC::Ptr<Key> object_store_position) { m_object_store_position = object_store_position; }--protected:- explicit IDBCursor(CursorSourceHandle, GC::Ptr<Key>, CursorDirection, GotValue, GC::Ptr<Key>, JS::Value, GC::Ref<IDBKeyRange>, KeyOnly);- virtual void visit_edges(GC::Cell::Visitor& visitor) override;-- // A cursor has a key and a value which represent the key and the value of the last iterated record.- GC::Ptr<Key> m_key;- Optional<JS::Value> m_value;--private:- // A cursor has a position within its range.- GC::Ptr<Key> m_position;-- // When iterating indexes the cursor also has an object store position- GC::Ptr<Key> m_object_store_position;-- // A cursor has a direction that determines whether it moves in monotonically increasing or decreasing order of the record keys when iterated, and if it skips duplicated values when iterating indexes.- CursorDirection m_direction;-- // A cursor has a got value flag.- bool m_got_value { false };-- // A cursor has a source handle, which is the index handle or the object store handle that opened the cursor.- CursorSourceHandle m_source_handle;-- // A cursor has a range of records in either an index or an object store.- GC::Ref<IDBKeyRange> m_range;-- // A cursor has a request, which is the request used to open the cursor.- GC::Ptr<IDBRequest> m_request;-- // A cursor also has a key only flag, that indicates whether the cursor’s value is exposed via the API.- bool m_key_only { false };-- // NB: The key and primaryKey getters return the same object instance every time they are inspected, until the- // cursor's key or effective key changes. These cache the converted values along with the keys they came from.- struct CachedKeyValue {- GC::Ptr<Key> key;- JS::Value value;- };- CachedKeyValue m_cached_key_value;- CachedKeyValue m_cached_primary_key_value;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBCursor.idl b/Libraries/LibWeb/IndexedDB/IDBCursor.idlindex f9b0d7ddc06..7306301a3a2 100644--- a/Libraries/LibWeb/IndexedDB/IDBCursor.idl+++ b/Libraries/LibWeb/IndexedDB/IDBCursor.idl@@ -1,10 +1,10 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBCursor {- [ImplementedAs=source_handle] readonly attribute (IDBObjectStore or IDBIndex) source;+ readonly attribute (IDBObjectStore or IDBIndex) source;readonly attribute IDBCursorDirection direction;[NeedsCallerRealm] readonly attribute any key;[NeedsCallerRealm] readonly attribute any primaryKey;- [DirectGetter, SameObject] readonly attribute IDBRequest request;+ [SameObject] readonly attribute IDBRequest request;undefined advance([EnforceRange] unsigned long count);undefined continue(optional any key);undefined continuePrimaryKey(any key, any primaryKey);diff --git a/Libraries/LibWeb/IndexedDB/IDBCursorWithValue.h b/Libraries/LibWeb/IndexedDB/IDBCursorWithValue.hdeleted file mode 100644index 3e6b117f0cc..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBCursorWithValue.h+++ /dev/null@@ -1,28 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/IndexedDB/IDBCursor.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#idbcursorwithvalue-class IDBCursorWithValue : public IDBCursor {- WEB_WRAPPABLE(IDBCursorWithValue, IDBCursor);- GC_DECLARE_ALLOCATOR(IDBCursorWithValue);--public:- virtual ~IDBCursorWithValue() override;-- [[nodiscard]] Optional<JS::Value> const& current_value() const { return m_value; }- [[nodiscard]] JS::Value value() const { return m_value.value_or(JS::js_undefined()); }--private:- explicit IDBCursorWithValue(CursorSourceHandle, GC::Ptr<Key>, CursorDirection, GotValue, GC::Ptr<Key>, JS::Value, GC::Ref<IDBKeyRange>, KeyOnly);-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBCursorWithValue.idl b/Libraries/LibWeb/IndexedDB/IDBCursorWithValue.idlindex 3551c9f8208..c423118a25a 100644--- a/Libraries/LibWeb/IndexedDB/IDBCursorWithValue.idl+++ b/Libraries/LibWeb/IndexedDB/IDBCursorWithValue.idl@@ -1,4 +1,4 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBCursorWithValue : IDBCursor {readonly attribute any value;};diff --git a/Libraries/LibWeb/IndexedDB/IDBDatabase.cpp b/Libraries/LibWeb/IndexedDB/IDBDatabase.cppdeleted file mode 100644index b7b6179a3ce..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBDatabase.cpp+++ /dev/null@@ -1,399 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/AnyOf.h>-#include <LibGC/Heap.h>-#include <LibWeb/Crypto/Crypto.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/IndexedDB/IDBDatabase.h>-#include <LibWeb/IndexedDB/IDBObjectStore.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBDatabase);--IDBDatabase::IDBDatabase(GC::Ref<DOM::EventTarget> relevant_global_object, Database& db)- : EventTarget()- , m_name(db.name())- , m_associated_database(db)- , m_global_object(relevant_global_object)- , m_uuid(Crypto::generate_random_uuid())-{- db.associate(*this);- m_object_store_set = Vector<GC::Ref<ObjectStore>> { db.object_stores() };-}--IDBDatabase::~IDBDatabase() = default;--void IDBDatabase::finalize()-{- Base::finalize();-- m_associated_database->dissociate(*this);- heap().enqueue_post_gc_task([database = GC::Weak(m_associated_database)] {- if (!database)- return;- database->check_pending_connection_wait();- });-}--GC::Ref<IDBDatabase> IDBDatabase::create(GC::Ref<DOM::EventTarget> relevant_global_object, Database& db)-{- return GC::Heap::the().allocate<IDBDatabase>(relevant_global_object, db);-}--void IDBDatabase::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_object_store_set);- visitor.visit(m_associated_database);- visitor.visit(m_global_object);- visitor.visit(m_transactions);-- for (auto& wait : m_pending_transaction_waits) {- visitor.visit(wait.transactions);- visitor.visit(wait.callback);- }-}--HTML::WindowOrWorkerGlobalScopeMixin& IDBDatabase::relevant_global_scope() const-{- return HTML::relevant_window_or_worker_global_scope(*m_global_object);-}--JS::Object& IDBDatabase::relevant_global_object() const-{- return HTML::relevant_global_object(relevant_global_scope());-}--void IDBDatabase::set_onabort(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::abort, event_handler);-}--WebIDL::CallbackType* IDBDatabase::onabort()-{- return event_handler_attribute(HTML::EventNames::abort);-}--void IDBDatabase::set_onerror(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::error, event_handler);-}--WebIDL::CallbackType* IDBDatabase::onerror()-{- return event_handler_attribute(HTML::EventNames::error);-}--void IDBDatabase::set_onclose(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::close, event_handler);-}--WebIDL::CallbackType* IDBDatabase::onclose()-{- return event_handler_attribute(HTML::EventNames::close);-}--void IDBDatabase::set_onversionchange(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::versionchange, event_handler);-}--WebIDL::CallbackType* IDBDatabase::onversionchange()-{- return event_handler_attribute(HTML::EventNames::versionchange);-}--// https://w3c.github.io/IndexedDB/#dom-idbdatabase-close-void IDBDatabase::close()-{- // 1. Run close a database connection with this connection.- close_a_database_connection(*this);-}--// https://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore-WebIDL::ExceptionOr<GC::Ref<IDBObjectStore>> IDBDatabase::create_object_store(Utf16String const& name, ObjectStoreParameters const& options)-{- // 1. Let database be this's associated database.- auto database = associated_database();-- // 2. Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise.- auto transaction = database->upgrade_transaction();- if (!transaction)- return WebIDL::InvalidStateError::create("Upgrade transaction is null"_utf16);-- // 3. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while creating object store"_utf16);-- // 4. Let keyPath be options’s keyPath member if it is not undefined or null, or null otherwise.- auto const& nullable_key_path = options.key_path;- Optional<KeyPath> key_path;- if (!nullable_key_path.has<Empty>())- key_path = nullable_key_path.downcast<Utf16String, Vector<Utf16String>>();-- // 5. If keyPath is not null and is not a valid key path, throw a "SyntaxError" DOMException.- if (key_path.has_value() && !is_valid_key_path(key_path.value()))- return WebIDL::SyntaxError::create("Invalid key path"_utf16);-- // 6. If an object store named name already exists in database throw a "ConstraintError" DOMException.- if (database->object_store_with_name(name))- return WebIDL::ConstraintError::create("Object store already exists"_utf16);-- // 7. Let autoIncrement be options’s autoIncrement member.- auto auto_increment = options.auto_increment;-- bool is_empty_key_path_or_sequence = key_path.has_value() && key_path.value().visit([](Utf16String const& value) -> bool { return value.is_empty(); }, [](Vector<Utf16String> const&) -> bool { return true; });-- // 8. If autoIncrement is true and keyPath is an empty string or any sequence (empty or otherwise), throw an "InvalidAccessError" DOMException.- if (auto_increment && is_empty_key_path_or_sequence)- return WebIDL::InvalidAccessError::create("Auto increment is true and key path is empty or sequence"_utf16);-- // 9. Let store be a new object store in database.- // Set the created object store's name to name.- // If autoIncrement is true, then the created object store uses a key generator.- // If keyPath is not null, set the created object store's key path to keyPath.- auto object_store = ObjectStore::create(database, name, auto_increment, key_path);-- // AD-HOC: Add newly created object store to this's object store set.- add_to_object_store_set(object_store);-- // AD-HOC: Set up a mutation log for this store and log its creation for potential revert on abort.- transaction->set_up_mutation_log_for_new_store(object_store);-- // 10. Return a new object store handle associated with store and transaction.- transaction->add_to_scope(object_store);- return transaction->get_or_create_object_store_handle(object_store);-}--// https://w3c.github.io/IndexedDB/#dom-idbdatabase-objectstorenames-GC::Ref<HTML::DOMStringList> IDBDatabase::object_store_names()-{- // 1. Let names be a list of the names of the object stores in this's object store set.- Vector<Utf16String> names;- for (auto const& object_store : this->object_store_set())- names.append(object_store->name());-- // 2. Return the result (a DOMStringList) of creating a sorted name list with names.- return create_a_sorted_name_list(names);-}--// https://w3c.github.io/IndexedDB/#dom-idbdatabase-deleteobjectstore-WebIDL::ExceptionOr<void> IDBDatabase::delete_object_store(Utf16String const& name)-{- // 1. Let database be this's associated database.- auto database = associated_database();-- // 2. Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise.- auto transaction = database->upgrade_transaction();- if (!transaction)- return WebIDL::InvalidStateError::create("Upgrade transaction is null"_utf16);-- // 3. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while deleting object store"_utf16);-- // 4. Let store be the object store named name in database, or throw a "NotFoundError" DOMException if none.- auto store = database->object_store_with_name(name);- if (!store)- return WebIDL::NotFoundError::create("Object store not found while trying to delete"_utf16);-- // 5. Remove store from this's object store set.- this->remove_from_object_store_set(*store);-- // NB: Upgrade transactions' scope is always the entire database. Since we removed this store from the database,- // it no longer belongs in the scope.- transaction->remove_from_scope(*store);-- // 6. If there is an object store handle associated with store and transaction, remove all entries from its index set.- if (auto handle = transaction->object_store_handle_for(*store))- handle->index_set().clear();-- // AD-HOC: Mark the store and its indexes as deleted so that stale handles throw InvalidStateError.- store->set_deleted(true);- for (auto const& [_, index] : store->index_set())- index->set_deleted(true);-- // AD-HOC: Log the deletion for potential revert on abort.- store->mutation_log()->note_object_store_deleted();-- // 7. Destroy store.- database->remove_object_store(*store);-- return {};-}--// https://w3c.github.io/IndexedDB/#dom-idbdatabase-transaction-WebIDL::ExceptionOr<GC::Ref<IDBTransaction>> IDBDatabase::transaction(Variant<Utf16String, Vector<Utf16String>> store_names, TransactionMode mode, TransactionOptions options)-{- // 1. If a live upgrade transaction is associated with the connection, throw an "InvalidStateError" DOMException.- auto database = associated_database();- if (database->upgrade_transaction())- return WebIDL::InvalidStateError::create("Upgrade transaction is live"_utf16);-- // 2. If this's close pending flag is true, then throw an "InvalidStateError" DOMException.- if (close_pending())- return WebIDL::InvalidStateError::create("Close pending"_utf16);-- // 3. Let scope be the set of unique strings in storeNames if it is a sequence, or a set containing one string equal to storeNames otherwise.- Vector<Utf16String> scope;- if (store_names.has<Vector<Utf16String>>()) {- for (auto const& store_name : store_names.get<Vector<Utf16String>>()) {- if (!scope.contains_slow(store_name))- scope.append(store_name);- }- } else {- scope.append(store_names.get<Utf16String>());- }-- // 4. If any string in scope is not the name of an object store in the connected database, throw a "NotFoundError" DOMException.- for (auto const& store_name : scope) {- if (!database->object_store_with_name(store_name))- return WebIDL::NotFoundError::create("Provided object store names does not exist in database"_utf16);- }-- // 5. If scope is empty, throw an "InvalidAccessError" DOMException.- if (scope.is_empty())- return WebIDL::InvalidAccessError::create("Scope is empty"_utf16);-- // 6. If mode is not "readonly" or "readwrite", throw a TypeError.- if (mode != TransactionMode::Readonly && mode != TransactionMode::Readwrite)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid transaction mode"_utf16 };-- // 7. Let transaction be a newly created transaction with this connection, mode, options’ durability member, and the set of object stores named in scope.- GC::RootVector<GC::Ref<ObjectStore>> scope_stores;- for (auto const& store_name : scope) {- auto store = database->object_store_with_name(store_name);- scope_stores.append(*store);- }-- auto transaction = IDBTransaction::create(*this, mode, options.durability, move(scope_stores));-- // 8. Set transaction’s cleanup event loop to the current event loop.- transaction->set_cleanup_event_loop(HTML::main_thread_event_loop());-- block_on_conflicting_transactions(HTML::relevant_realm(relevant_global_object()), transaction);-- // 9. Return an IDBTransaction object representing transaction.- return transaction;-}--void IDBDatabase::set_state(ConnectionState state)-{- m_state = state;-}--void IDBDatabase::wait_for_transactions_to_finish(ReadonlySpan<GC::Ref<IDBTransaction>> transactions, GC::Ref<GC::Function<void()>> on_complete)-{- auto all_finished = [&] {- for (auto const& entry : transactions) {- if (!entry->is_finished()) {- return false;- break;- }- }- return true;- }();-- if (all_finished) {- queue_a_database_task(on_complete);- return;- }-- m_pending_transaction_waits.append(PendingTransactionWait {- .transactions = Vector<GC::Ref<IDBTransaction>> { transactions },- .callback = on_complete,- });-}--void IDBDatabase::check_pending_transaction_waits()-{- for (size_t i = 0; i < m_pending_transaction_waits.size();) {- auto all_finished = [&] {- for (auto const& transaction : m_pending_transaction_waits[i].transactions) {- if (!transaction->is_finished())- return false;- }- return true;- }();- if (all_finished) {- auto callback = m_pending_transaction_waits.take(i).callback;- callback->function()();- continue;- }-- i++;- }-}--// https://w3c.github.io/IndexedDB/#transaction-scheduling-void IDBDatabase::block_on_conflicting_transactions(JS::Realm& realm, GC::Ref<IDBTransaction> transaction)-{- // The following constraints define when a transaction can be started:-- // - A read-only transactions tx can start when there are no read/write transactions which:- // - A read/write transaction tx can start when there are no transactions which:-- GC::RootVector<GC::Ref<IDBTransaction>> blocking;- for (auto const& other : m_transactions) {- // - Were created before tx; and- if (other.ptr() == transaction.ptr())- break;-- // NB: According to the above conditions, we only block on transactions if one is read/write.- if (transaction->is_readonly() && other->is_readonly())- continue;-- // - have overlapping scopes with tx; and- bool have_overlapping_scopes = any_of(transaction->scope(), [&](auto const& store) {- return other->scope().contains_slow(store);- });- if (!have_overlapping_scopes)- continue;-- // - are not finished.- if (other->is_finished())- continue;-- blocking.append(other);- }-- if (blocking.is_empty()) {- if (!transaction->is_readonly())- transaction->set_up_mutation_logs();- return;- }-- transaction->request_list().block_execution();- wait_for_transactions_to_finish(blocking, GC::create_function(GC::Heap::the(), [&realm, transaction] {- VERIFY(transaction->state() != IDBTransaction::TransactionState::Active);- if (transaction->request_list().is_empty()) {- // https://w3c.github.io/IndexedDB/#transaction-commit- // The implementation must attempt to commit an inactive transaction when all requests placed- // against the transaction have completed and their returned results handled, no new requests have- // been placed against the transaction, and the transaction has not been aborted-- // If we were blocked, that means that the JS task has had its chance to make requests. If the request- // list is empty, then the cleanup in the microtask checkpoint already ran, but skipped auto-committing.- // We have to do it here instead.-- // FIXME: Update if this becomes explicit:- // https://github.com/w3c/IndexedDB/issues/489#issuecomment-3994928473- commit_a_transaction(realm, transaction);- return;- }- if (!transaction->is_readonly())- transaction->set_up_mutation_logs();- transaction->request_list().unblock_execution();- }));-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBDatabase.h b/Libraries/LibWeb/IndexedDB/IDBDatabase.hdeleted file mode 100644index b92994c443d..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBDatabase.h+++ /dev/null@@ -1,117 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Ptr.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/HTML/DOMStringList.h>-#include <LibWeb/IndexedDB/ConnectionState.h>-#include <LibWeb/IndexedDB/IDBRequest.h>-#include <LibWeb/IndexedDB/IDBTransaction.h>-#include <LibWeb/IndexedDB/Internal/Database.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>-#include <LibWeb/StorageAPI/StorageKey.h>--namespace Web::IndexedDB {--using ObjectStoreParameters = Bindings::IDBObjectStoreParameters;-using TransactionOptions = Bindings::IDBTransactionOptions;--// https://w3c.github.io/IndexedDB/#IDBDatabase-interface-// https://w3c.github.io/IndexedDB/#database-connection-class IDBDatabase : public DOM::EventTarget {- WEB_WRAPPABLE(IDBDatabase, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(IDBDatabase);--public:- virtual ~IDBDatabase() override;- virtual void finalize() override;-- [[nodiscard]] static GC::Ref<IDBDatabase> create(GC::Ref<DOM::EventTarget> relevant_global_object, Database&);-- void set_version(u64 version) { m_version = version; }- void set_close_pending(bool close_pending) { m_close_pending = close_pending; }- void set_state(ConnectionState state);-- [[nodiscard]] String uuid() const { return m_uuid; }- [[nodiscard]] Utf16String name() const { return m_name; }- [[nodiscard]] u64 version() const { return m_version; }- [[nodiscard]] bool close_pending() const { return m_close_pending; }- [[nodiscard]] ConnectionState state() const { return m_state; }- [[nodiscard]] GC::Ref<Database> associated_database() { return m_associated_database; }- [[nodiscard]] ReadonlySpan<GC::Ref<ObjectStore>> object_store_set() { return m_object_store_set; }- void add_to_object_store_set(GC::Ref<ObjectStore> object_store) { m_object_store_set.append(object_store); }- void remove_from_object_store_set(GC::Ref<ObjectStore> object_store)- {- m_object_store_set.remove_first_matching([&](auto& entry) { return entry == object_store; });- }-- [[nodiscard]] ReadonlySpan<GC::Ref<IDBTransaction>> transactions() { return m_transactions; }- void add_transaction(GC::Ref<IDBTransaction> transaction) { m_transactions.append(transaction); }-- [[nodiscard]] HTML::WindowOrWorkerGlobalScopeMixin& relevant_global_scope() const;- [[nodiscard]] JS::Object& relevant_global_object() const;- [[nodiscard]] GC::Ref<HTML::DOMStringList> object_store_names();- WebIDL::ExceptionOr<GC::Ref<IDBObjectStore>> create_object_store(Utf16String const&, ObjectStoreParameters const&);- WebIDL::ExceptionOr<void> delete_object_store(Utf16String const&);-- WebIDL::ExceptionOr<GC::Ref<IDBTransaction>> transaction(Variant<Utf16String, Vector<Utf16String>>, TransactionMode = TransactionMode::Readonly, TransactionOptions = {});-- void close();-- void set_onabort(WebIDL::CallbackType*);- WebIDL::CallbackType* onabort();- void set_onclose(WebIDL::CallbackType*);- WebIDL::CallbackType* onclose();- void set_onerror(WebIDL::CallbackType*);- WebIDL::CallbackType* onerror();- void set_onversionchange(WebIDL::CallbackType*);- WebIDL::CallbackType* onversionchange();-- void wait_for_transactions_to_finish(ReadonlySpan<GC::Ref<IDBTransaction>>, GC::Ref<GC::Function<void()>> on_complete);- void check_pending_transaction_waits();- void block_on_conflicting_transactions(JS::Realm&, GC::Ref<IDBTransaction>);--protected:- IDBDatabase(GC::Ref<DOM::EventTarget> relevant_global_object, Database&);-- virtual void visit_edges(Visitor& visitor) override;--private:- struct PendingTransactionWait {- Vector<GC::Ref<IDBTransaction>> transactions;- GC::Ref<GC::Function<void()>> callback;- };-- Vector<PendingTransactionWait> m_pending_transaction_waits;-- u64 m_version { 0 };- Utf16String m_name;-- // Each connection has a close pending flag which is initially false.- bool m_close_pending { false };-- // When a connection is initially created it is in an opened state.- ConnectionState m_state { ConnectionState::Open };-- // A connection has an object store set, which is initialized to the set of object stores in the associated database when the connection is created.- // The contents of the set will remain constant except when an upgrade transaction is live.- Vector<GC::Ref<ObjectStore>> m_object_store_set;-- // NOTE: There is an associated database in the spec, but there is no mention where it is assigned, nor where its from- // So we stash the one we have when opening a connection.- GC::Ref<Database> m_associated_database;- GC::Ref<DOM::EventTarget> m_global_object;-- // NOTE: We need to keep track of what transactions were created by this connection- Vector<GC::Ref<IDBTransaction>> m_transactions;-- // NOTE: Used for debug purposes- String m_uuid;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBDatabase.idl b/Libraries/LibWeb/IndexedDB/IDBDatabase.idlindex 735297c8f90..68740c1c732 100644--- a/Libraries/LibWeb/IndexedDB/IDBDatabase.idl+++ b/Libraries/LibWeb/IndexedDB/IDBDatabase.idl@@ -1,4 +1,4 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBDatabase : EventTarget {readonly attribute DOMString name;readonly attribute unsigned long long version;diff --git a/Libraries/LibWeb/IndexedDB/IDBFactory.cpp b/Libraries/LibWeb/IndexedDB/IDBFactory.cppindex 4494b8f479e..483efc036dc 100644--- a/Libraries/LibWeb/IndexedDB/IDBFactory.cpp+++ b/Libraries/LibWeb/IndexedDB/IDBFactory.cpp@@ -1,258 +1,37 @@/*- * Copyright (c) 2024, Shannon Booth <[email protected]>- * Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Vector.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/IndexedDB/IDBDatabase.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibWeb/Bindings/MainThreadVM.h>+#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/IndexedDB/IDBFactory.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/Key.h>-#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/StorageAPI/StorageKey.h>-namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBFactory);--static auto current_high_resolution_time(HTML::WindowOrWorkerGlobalScopeMixin& global_scope)-{- return HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(global_scope));-}--IDBFactory::IDBFactory(HTML::WindowOrWorkerGlobalScopeMixin& global)- : m_global(global.this_impl())-{-}--IDBFactory::~IDBFactory() = default;--void IDBFactory::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_global);-}--HTML::WindowOrWorkerGlobalScopeMixin& IDBFactory::relevant_global_scope() const-{- return HTML::relevant_window_or_worker_global_scope(*m_global);-}--JS::Object& IDBFactory::relevant_global_object() const-{- return HTML::relevant_global_object(relevant_global_scope());-}--HTML::EnvironmentSettingsObject& IDBFactory::relevant_settings_object() const-{- return HTML::relevant_settings_object(relevant_global_scope());-}--// https://w3c.github.io/IndexedDB/#dom-idbfactory-open-WebIDL::ExceptionOr<GC::Ref<IDBOpenDBRequest>> IDBFactory::open(Utf16String const& name, Optional<u64> version)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. If version is 0 (zero), throw a TypeError.- if (version.has_value() && version.value() == 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The version provided must not be 0"_utf16 };-- // 2. Let environment be this's relevant settings object.- auto& environment = relevant_settings_object();-- // 3. Let storageKey be the result of running obtain a storage key given environment.- // If failure is returned, then throw a "SecurityError" DOMException and abort these steps.- auto storage_key = StorageAPI::obtain_a_storage_key(environment);- if (!storage_key.has_value())- return WebIDL::SecurityError::create("Failed to obtain a storage key"_utf16);-- // 4. Let request be a new open request.- auto request = IDBOpenDBRequest::create(m_global);-- // 5. Run these steps in parallel:- // NB: We could defer these steps, but it wouldn't be observable anyway, since open_a_database_connection() will- // put this work into a queue and then process it later in the event loop regardless.-- // 1. Let result be the result of opening a database connection, with storageKey, name, version if given and undefined otherwise, and request.- open_a_database_connection(realm, storage_key.value(), name, version, request, GC::create_function(GC::Heap::the(), [&realm, request](WebIDL::ExceptionOr<GC::Ref<IDBDatabase>> result) {- // 2. Set request’s processed flag to true.- request->set_processed(true);-- // 3. Queue a database task to run these steps:- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, request, result = move(result)]() mutable {- // 1. If result is an error, then:- if (result.is_error()) {- // 1. Set request’s result to undefined.- request->set_result(JS::js_undefined());-- // 2. Set request’s error to result.- request->set_error(result.exception().get<GC::Ref<WebIDL::DOMException>>());-- // 3. Set request’s done flag to true.- request->set_done(true);-- // 4. Fire an event named error at request with its bubbles and cancelable attributes initialized to true.- request->dispatch_event(DOM::Event::create(- HTML::EventNames::error,- { .bubbles = true, .cancelable = true },- current_high_resolution_time(request->relevant_global_scope())));- }- // 2. Otherwise:- else {- // 1. Set request’s result to result.- Bindings::set_idb_request_result(realm, request, result.release_value());-- // 2. Set request’s done flag to true.- request->set_done(true);-- // 3. Fire an event named success at request.- request->dispatch_event(DOM::Event::create(- HTML::EventNames::success,- current_high_resolution_time(request->relevant_global_scope())));- }- }));- }));-- // 6. Return a new IDBOpenDBRequest object for request.- return request;+// The C ABI of the Rust implementation of IndexedDB, Libraries/LibWeb/Bindings/Rust/src/indexed_db/exports.rs.+extern "C" {+void* web_rust_indexed_db_create_factory(JSVM*, void* realm);+bool web_rust_indexed_db_cleanup_indexed_database_transactions(JSVM*, void* event_loop);+void web_rust_indexed_db_close_all_connections(JSVM*, void* realm);}-// https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp-WebIDL::ExceptionOr<i8> IDBFactory::cmp(JS::Value first, JS::Value second)-{- // 1. Let a be the result of converting a value to a key with first. Rethrow any exceptions.- auto a = TRY(convert_a_value_to_a_key(HTML::relevant_realm(relevant_global_object()), first));-- // 2. If a is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (a->is_invalid())- return WebIDL::DataError::create("Failed to convert a value to a key"_utf16);-- // 3. Let b be the result of converting a value to a key with second. Rethrow any exceptions.- auto b = TRY(convert_a_value_to_a_key(HTML::relevant_realm(relevant_global_object()), second));-- // 4. If b is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (b->is_invalid())- return WebIDL::DataError::create("Failed to convert a value to a key"_utf16);-- // 5. Return the results of comparing two keys with a and b.- return Key::compare_two_keys(a, b);-}+namespace Web::IndexedDB {-// https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase-WebIDL::ExceptionOr<GC::Ref<IDBOpenDBRequest>> IDBFactory::delete_database(Utf16String const& name)+GC::Ref<IDBFactory> IDBFactory::create(JS::Realm& realm){- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let environment be this's relevant settings object.- auto& environment = relevant_settings_object();-- // 2. Let storageKey be the result of running obtain a storage key given environment.- // If failure is returned, then throw a "SecurityError" DOMException and abort these steps.- auto storage_key = StorageAPI::obtain_a_storage_key(environment);- if (!storage_key.has_value())- return WebIDL::SecurityError::create("Failed to obtain a storage key"_utf16);-- // 3. Let request be a new open request.- auto request = IDBOpenDBRequest::create(m_global);-- // 4. Run these steps in parallel:- // NB: We could defer these steps, but it wouldn't be observable anyway, since delete_a_database() will- // put this work into a queue and then process it later in the event loop regardless.-- // 1. Let result be the result of deleting a database, with storageKey, name, and request.- delete_a_database(realm, storage_key.value(), name, request, GC::create_function(GC::Heap::the(), [&realm, request](WebIDL::ExceptionOr<u64> result) {- // 2. Set request’s processed flag to true.- request->set_processed(true);-- // 3. Queue a database task to run these steps:- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, request, result = move(result)]() mutable {- // 1. If result is an error, set request’s error to result, set request’s done flag to true, and fire an event- // named error at request with its bubbles and cancelable attributes initialized to true.- if (result.is_error()) {- request->set_error(result.exception().get<GC::Ref<WebIDL::DOMException>>());- request->set_done(true);- request->dispatch_event(DOM::Event::create(- HTML::EventNames::error,- { .bubbles = true, .cancelable = true },- current_high_resolution_time(request->relevant_global_scope())));- }- // 2. Otherwise, set request’s result to undefined, set request’s done flag to true, and fire a version change- // event named success at request with result and null.- else {- request->set_result(JS::js_undefined());- request->set_done(true);- auto value = result.release_value();- fire_a_version_change_event(realm, HTML::EventNames::success, request, value, {});- }- }));- }));-- // 5. Return a new IDBOpenDBRequest object for request.- return request;+ return *static_cast<IDBFactory*>(web_rust_indexed_db_create_factory(JS::HostABI::vm_to_abi(realm.vm()), &realm));}-// https://w3c.github.io/IndexedDB/#dom-idbfactory-databases-GC::Ref<WebIDL::Promise> IDBFactory::databases()+bool cleanup_indexed_database_transactions(HTML::EventLoop& event_loop){- auto promise = WebIDL::create_promise_for(relevant_settings_object());- databases(promise);- return promise;+ return web_rust_indexed_db_cleanup_indexed_database_transactions(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), &event_loop);}-// https://w3c.github.io/IndexedDB/#dom-idbfactory-databases-void IDBFactory::databases(GC::Ref<WebIDL::Promise> promise)+void close_all_database_connections(JS::Realm& realm){- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let environment be this's relevant settings object.- auto& environment = relevant_settings_object();-- // 2. Let storageKey be the result of running obtain a storage key given environment.- // If failure is returned, then return a promise rejected with a "SecurityError" DOMException- auto maybe_storage_key = StorageAPI::obtain_a_storage_key(environment);- if (!maybe_storage_key.has_value()) {- WebIDL::reject_promise(promise, WebIDL::SecurityError::create("Failed to obtain a storage key"_utf16));- return;- }-- auto storage_key = maybe_storage_key.release_value();-- // 3. Let p be a new promise.- // NB: p is the promise that databases() created.-- // 4. Run these steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, storage_key, promise]() {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 1. Let databases be the set of databases in storageKey.- // If this cannot be determined for any reason, then queue a database task to reject p with an appropriate error (e.g. an "UnknownError" DOMException) and terminate these steps.- auto databases = Database::for_key(storage_key);-- // 2. Let result be a new list.- // 3. For each db of databases:- // 1. If db's version is 0, then continue.- // 2. Let info be a new IDBDatabaseInfo dictionary.- // 3. Set info's name dictionary member to db's name.- // 4. Set info's version dictionary member to db's version.- // 5. Append info to result.- // 4. Queue a database task to resolve p with result.- // AD-HOC: p is resolved directly in a deferred invocation, not in a database task.- Bindings::resolve_database_info_list_promise(realm, promise, databases);- }));-- // 5. Return p.- // NB: databases() returns p.+ web_rust_indexed_db_close_all_connections(JS::HostABI::vm_to_abi(realm.vm()), &realm);}}diff --git a/Libraries/LibWeb/IndexedDB/IDBFactory.h b/Libraries/LibWeb/IndexedDB/IDBFactory.hindex c39b30a546c..89bab125285 100644--- a/Libraries/LibWeb/IndexedDB/IDBFactory.h+++ b/Libraries/LibWeb/IndexedDB/IDBFactory.h@@ -1,45 +1,35 @@/** Copyright (c) 2024, Shannon Booth <[email protected]>* Copyright (c) 2024-2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/#pragma once-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibJS/Forward.h>+#include <LibWeb/Bindings/IDBFactory.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>#include <LibWeb/Forward.h>-#include <LibWeb/IndexedDB/IDBOpenDBRequest.h>namespace Web::IndexedDB {// https://w3c.github.io/IndexedDB/#idbfactory-class IDBFactory : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(IDBFactory, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(IDBFactory);+// The C++ side of an IDBFactory, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/indexed_db).+class WEB_API IDBFactory : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(IDBFactory, idb_factory)public:- virtual ~IDBFactory() override;-- WebIDL::ExceptionOr<GC::Ref<IDBOpenDBRequest>> open(Utf16String const& name, Optional<u64> version);- WebIDL::ExceptionOr<GC::Ref<IDBOpenDBRequest>> delete_database(Utf16String const& name);- GC::Ref<WebIDL::Promise> databases();- void databases(GC::Ref<WebIDL::Promise>);-- WebIDL::ExceptionOr<i8> cmp(JS::Value first, JS::Value second);--protected:- explicit IDBFactory(HTML::WindowOrWorkerGlobalScopeMixin&);-- virtual void visit_edges(GC::Cell::Visitor&) override;+ [[nodiscard]] static GC::Ref<IDBFactory> create(JS::Realm&);+};-private:- HTML::WindowOrWorkerGlobalScopeMixin& relevant_global_scope() const;- JS::Object& relevant_global_object() const;- HTML::EnvironmentSettingsObject& relevant_settings_object() const;+// https://w3c.github.io/IndexedDB/#cleanup-indexed-database-transactions+bool cleanup_indexed_database_transactions(HTML::EventLoop&);- GC::Ref<DOM::EventTarget> m_global;-};+// Runs close a database connection with every connection of the realm's global object whose close pending flag is+// unset.+void close_all_database_connections(JS::Realm&);}diff --git a/Libraries/LibWeb/IndexedDB/IDBFactory.idl b/Libraries/LibWeb/IndexedDB/IDBFactory.idlindex 9203f685956..2654dfbda18 100644--- a/Libraries/LibWeb/IndexedDB/IDBFactory.idl+++ b/Libraries/LibWeb/IndexedDB/IDBFactory.idl@@ -4,7 +4,7 @@ partial interface mixin WindowOrWorkerGlobalScope {};// https://w3c.github.io/IndexedDB/#idbfactory-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBFactory {[NewObject] IDBOpenDBRequest open(DOMString name, optional [EnforceRange] unsigned long long version);[NewObject] IDBOpenDBRequest deleteDatabase(DOMString name);diff --git a/Libraries/LibWeb/IndexedDB/IDBIndex.cpp b/Libraries/LibWeb/IndexedDB/IDBIndex.cppdeleted file mode 100644index 48a29e33f28..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBIndex.cpp+++ /dev/null@@ -1,323 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/IndexedDB/IDBCursor.h>-#include <LibWeb/IndexedDB/IDBCursorWithValue.h>-#include <LibWeb/IndexedDB/IDBIndex.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBIndex);--IDBIndex::~IDBIndex() = default;--IDBIndex::IDBIndex(GC::Ref<Index> index, GC::Ref<IDBObjectStore> object_store)- : m_index(index)- , m_object_store_handle(object_store)- , m_name(index->name())-{-}--GC::Ref<IDBIndex> IDBIndex::create(GC::Ref<Index> index, GC::Ref<IDBObjectStore> object_store)-{- auto handle = GC::Heap::the().allocate<IDBIndex>(index, object_store);- object_store->transaction()->register_index_handle({}, handle);- return handle;-}--void IDBIndex::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_index);- visitor.visit(m_object_store_handle);- visitor.visit(m_key_path_arrays);-}--JS::Object& IDBIndex::relevant_global_object() const-{- return m_object_store_handle->relevant_global_object();-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-name-WebIDL::ExceptionOr<void> IDBIndex::set_name(Utf16String const& value)-{- // 1. Let name be the given value.- auto const& name = value;-- // 2. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 3. Let index be this’s index.- auto index = this->index();-- // 4. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.- if (!transaction->is_upgrade_transaction())- return WebIDL::InvalidStateError::create("Transaction is not an upgrade transaction"_utf16);-- // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while updating index name"_utf16);-- // 6. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.- if (index->is_deleted() || index->object_store()->is_deleted())- return WebIDL::InvalidStateError::create("Index or its object store has been deleted"_utf16);-- // 7. If index’s name is equal to name, terminate these steps.- if (index->name() == name)- return {};-- // 8. If an index named name already exists in index’s object store, throw a "ConstraintError" DOMException.- if (index->object_store()->index_set().contains(name))- return WebIDL::ConstraintError::create("An index with the given name already exists"_utf16);-- // AD-HOC: Log the rename for potential revert on abort.- m_object_store_handle->store()->mutation_log()->note_index_renamed(index, index->name());-- // 9. Set index’s name to name.- index->set_name(name);-- // NOTE: Update the key in the map so it still matches the name- auto old_value = m_object_store_handle->index_set().take(m_name).release_value();- m_object_store_handle->index_set().set(name, old_value);-- // 10. Set this’s name to name.- m_name = name;-- return {};-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-keypath-KeyPath const& IDBIndex::key_path() const-{- return m_index->key_path();-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-keypath-JS::ThrowCompletionOr<JS::Value> IDBIndex::key_path_value(JS::Realm& realm)-{- // The keyPath getter steps are to return this’s index’s key path. The key path is converted as a DOMString (if a- // string) or a sequence<DOMString> (if a list of strings), per [WEBIDL].- // NOTE: The returned value is not the same instance that was used when the index was created. However, if this- // attribute returns an object (specifically an Array), it returns the same object instance every time it is- // inspected. Changing the properties of the object has no effect on the index.- if (auto array = m_key_path_arrays.get(realm.global_object()); array.has_value())- return *array;-- auto value = TRY(convert_a_key_path_to_a_value(realm, key_path()));- if (value.is_object())- m_key_path_arrays.set(realm.global_object(), value.as_object());- return value;-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-opencursor-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::open_cursor(Optional<JS::Value> query, CursorDirection direction)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let index be this’s index.- auto index = this->index();-- // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.- if (index->is_deleted() || index->object_store()->is_deleted())- return WebIDL::InvalidStateError::create("Index or its object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while opening cursor"_utf16);-- // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query));-- // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction, got value flag set to false, undefined key and value, range set to range, and key only flag set to false.- auto cursor = IDBCursor::create(GC::Ref(*this), {}, direction, IDBCursor::GotValue::No, {}, {}, range, IDBCursor::KeyOnly::No);-- // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, cursor] -> WebIDL::ExceptionOr<JS::Value> {- auto result = TRY(iterate_a_cursor(realm, cursor));- return Bindings::idb_cursor_result(realm, result);- });-- // 8. Let request be the result of running asynchronously execute a request with this and operation.- auto request = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);-- // 9. Set cursor’s request to request.- cursor->set_request(request);-- // 10. Return request.- return request;-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-get-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::get(JS::Value query)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let index be this’s index.- auto index = this->index();-- // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.- if (index->is_deleted() || index->object_store()->is_deleted())- return WebIDL::InvalidStateError::create("Index or its object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while getting"_utf16);-- // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query, true));-- // 6. Let operation be an algorithm to run retrieve a referenced value from an index with the current Realm record, index, and range.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, index, range] -> WebIDL::ExceptionOr<JS::Value> {- return retrieve_a_referenced_value_from_an_index(realm, index, range);- });-- // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for get with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-getkey-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::get_key(JS::Value query)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let index be this’s index.- auto index = this->index();-- // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.- if (index->is_deleted() || index->object_store()->is_deleted())- return WebIDL::InvalidStateError::create("Index or its object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while getting key"_utf16);-- // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query, true));-- // 6. Let operation be an algorithm to run retrieve a value from an index with index and range.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, index, range] -> WebIDL::ExceptionOr<JS::Value> {- return retrieve_a_value_from_an_index(realm, index, range);- });-- // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for get key with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-getall-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::get_all(Optional<JS::Value> query_or_options, Optional<WebIDL::UnsignedLong> count)-{- // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,- // "value", queryOrOptions, and count if given. Rethrow any exceptions.- return create_a_request_to_retrieve_multiple_items(HTML::relevant_realm(relevant_global_object()), GC::Ref(*this), RecordKind::Value, query_or_options.value_or(JS::js_undefined()), count);-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::get_all_keys(Optional<JS::Value> query_or_options, Optional<WebIDL::UnsignedLong> count)-{- // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this, "key",- // queryOrOptions, and count if given. Rethrow any exceptions.- return create_a_request_to_retrieve_multiple_items(HTML::relevant_realm(relevant_global_object()), GC::Ref(*this), RecordKind::Key, query_or_options.value_or(JS::js_undefined()), count);-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-count-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::count(Optional<JS::Value> query)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let index be this’s index.- auto index = this->index();-- // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.- if (index->is_deleted() || index->object_store()->is_deleted())- return WebIDL::InvalidStateError::create("Index or its object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while counting"_utf16);-- // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query));-- // 6. Let operation be an algorithm to run count the records in a range with index and range.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [index, range] -> WebIDL::ExceptionOr<JS::Value> {- return count_the_records_in_a_range(index, range);- });-- // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for count with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbindex-openkeycursor-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::open_key_cursor(Optional<JS::Value> query, CursorDirection direction)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let index be this’s index.- auto index = this->index();-- // 3. If index or index’s object store has been deleted, throw an "InvalidStateError" DOMException.- if (index->is_deleted() || index->object_store()->is_deleted())- return WebIDL::InvalidStateError::create("Index or its object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while opening key cursor"_utf16);-- // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query));-- // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction, got value flag set to false, undefined key and value, range set to range, and key only flag set to true.- auto cursor = IDBCursor::create(GC::Ref(*this), {}, direction, IDBCursor::GotValue::No, {}, {}, range, IDBCursor::KeyOnly::Yes);-- // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, cursor] -> WebIDL::ExceptionOr<JS::Value> {- auto result = TRY(iterate_a_cursor(realm, cursor));- return Bindings::idb_cursor_result(realm, result);- });-- // 8. Let request be the result of running asynchronously execute a request with this and operation.- auto request = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for open key cursor with uuid {}", request->uuid());-- // 9. Set cursor’s request to request.- cursor->set_request(request);-- // 10. Return request.- return request;-}--WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBIndex::get_all_records(RetrieveMultipleItemsOptions const& options)-{- // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,- // "record", and options. Rethrow any exceptions.- return create_a_request_to_retrieve_multiple_items(HTML::relevant_realm(relevant_global_object()), GC::Ref(*this), RecordKind::Record, options);-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBIndex.h b/Libraries/LibWeb/IndexedDB/IDBIndex.hdeleted file mode 100644index c5303a122e6..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBIndex.h+++ /dev/null@@ -1,69 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/IDBCursor.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/IndexedDB/IDBObjectStore.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/Index.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#index-interface-class IDBIndex : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(IDBIndex, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(IDBIndex);--public:- static constexpr size_t object_store_handle_offset() { return offsetof(IDBIndex, m_object_store_handle); }- virtual ~IDBIndex() override;- [[nodiscard]] static GC::Ref<IDBIndex> create(GC::Ref<Index>, GC::Ref<IDBObjectStore>);-- WebIDL::ExceptionOr<void> set_name(Utf16String const& value);- Utf16String name() const { return m_name; }- GC::Ref<IDBObjectStore> object_store() { return m_object_store_handle; }- KeyPath const& key_path() const;- JS::ThrowCompletionOr<JS::Value> key_path_value(JS::Realm&);- bool multi_entry() const { return m_index->multi_entry(); }- bool unique() const { return m_index->unique(); }-- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get(JS::Value);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_key(JS::Value);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_all(Optional<JS::Value>, Optional<WebIDL::UnsignedLong>);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_all_keys(Optional<JS::Value>, Optional<WebIDL::UnsignedLong>);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_all_records(RetrieveMultipleItemsOptions const&);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> count(Optional<JS::Value>);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> open_cursor(Optional<JS::Value>, CursorDirection);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> open_key_cursor(Optional<JS::Value>, CursorDirection);-- // The transaction of an index handle is the transaction of its associated object store handle.- GC::Ref<IDBTransaction> transaction() { return m_object_store_handle->transaction(); }- JS::Object& relevant_global_object() const;- GC::Ref<Index> index() { return m_index; }-- void update_name() { m_name = m_index->name(); }--protected:- explicit IDBIndex(GC::Ref<Index>, GC::Ref<IDBObjectStore>);- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- // An index handle has an associated index and an associated object store handle.- GC::Ref<Index> m_index;- GC::Ref<IDBObjectStore> m_object_store_handle;-- // An index handle has a name, which is initialized to the name of the associated index when the index handle is created.- Utf16String m_name;-- // NB: The keyPath getter returns the same Array every time it is inspected in the same realm.- HashMap<GC::Ref<JS::Object>, GC::Ref<JS::Object>> m_key_path_arrays;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBIndex.idl b/Libraries/LibWeb/IndexedDB/IDBIndex.idlindex 905bf0a2ce9..2ff335ee05c 100644--- a/Libraries/LibWeb/IndexedDB/IDBIndex.idl+++ b/Libraries/LibWeb/IndexedDB/IDBIndex.idl@@ -1,7 +1,7 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBIndex {attribute DOMString name;- [DirectGetter=object_store_handle, SameObject] readonly attribute IDBObjectStore objectStore;+ [SameObject] readonly attribute IDBObjectStore objectStore;[ImplementedAs=key_path_value, NeedsCallerRealm] readonly attribute any keyPath;readonly attribute boolean multiEntry;readonly attribute boolean unique;diff --git a/Libraries/LibWeb/IndexedDB/IDBKeyRange.cpp b/Libraries/LibWeb/IndexedDB/IDBKeyRange.cppdeleted file mode 100644index 0ed99611424..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBKeyRange.cpp+++ /dev/null@@ -1,167 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Optional.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/IndexedDB/BindingsGlue.h>-#include <LibWeb/IndexedDB/IDBKeyRange.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBKeyRange);--IDBKeyRange::~IDBKeyRange() = default;--IDBKeyRange::IDBKeyRange(GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, LowerOpen lower_open, UpperOpen upper_open)- : m_lower_bound(lower_bound)- , m_upper_bound(upper_bound)- , m_lower_open(lower_open == LowerOpen::Yes)- , m_upper_open(upper_open == UpperOpen::Yes)-{-}--GC::Ref<IDBKeyRange> IDBKeyRange::create(GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, LowerOpen lower_open, UpperOpen upper_open)-{- return GC::Heap::the().allocate<IDBKeyRange>(lower_bound, upper_bound, lower_open, upper_open);-}--void IDBKeyRange::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_lower_bound);- visitor.visit(m_upper_bound);-}--// https://w3c.github.io/IndexedDB/#in-bool IDBKeyRange::is_in_range(GC::Ref<Key> key) const-{- // A key is in a key range range if both of the following conditions are fulfilled:-- // The range’s lower bound is null, or it is less than key, or it is both equal to key and the range’s lower open flag is false.- auto lower_bound_in_range = this->lower_key() == nullptr || Key::less_than(*this->lower_key(), key) || (Key::equals(key, *this->lower_key()) && !this->lower_open());-- // The range’s upper bound is null, or it is greater than key, or it is both equal to key and the range’s upper open flag is false.- auto upper_bound_in_range = this->upper_key() == nullptr || Key::greater_than(*this->upper_key(), key) || (Key::equals(key, *this->upper_key()) && !this->upper_open());-- return lower_bound_in_range && upper_bound_in_range;-}--}--namespace Web::Bindings {--IndexedDB::IDBKeyRange* key_range_from_value(JS::Value value)-{- if (!value.is_object())- return nullptr;- return Bindings::impl_from<IndexedDB::IDBKeyRange>(&value.as_object());-}--// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-only-WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> only(JS::Realm& realm, JS::Value value)-{- // 1. Let key be the result of converting a value to a key with value. Rethrow any exceptions.- auto key = TRY(IndexedDB::convert_a_value_to_a_key(realm, value));-- // 2. If key is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (key->is_invalid())- return WebIDL::DataError::create(realm, "Value is invalid"_utf16);-- // 3. Create and return a new key range containing only key.- return IndexedDB::IDBKeyRange::create(key, key, IndexedDB::IDBKeyRange::LowerOpen::No, IndexedDB::IDBKeyRange::UpperOpen::No);-}--// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-lowerbound-WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> lower_bound(JS::Realm& realm, JS::Value lower, bool open)-{- // 1. Let lowerKey be the result of converting a value to a key with lower. Rethrow any exceptions.- auto key = TRY(IndexedDB::convert_a_value_to_a_key(realm, lower));-- // 2. If lowerKey is invalid, throw a "DataError" DOMException.- if (key->is_invalid())- return WebIDL::DataError::create(realm, "Value is invalid"_utf16);-- // 3. Create and return a new key range with lower bound set to lowerKey, lower open flag set to open, upper bound set to null, and upper open flag set to true.- return IndexedDB::IDBKeyRange::create(key, {}, open ? IndexedDB::IDBKeyRange::LowerOpen::Yes : IndexedDB::IDBKeyRange::LowerOpen::No, IndexedDB::IDBKeyRange::UpperOpen::Yes);-}--// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-upperbound-WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> upper_bound(JS::Realm& realm, JS::Value upper, bool open)-{- // 1. Let upperKey be the result of converting a value to a key with upper. Rethrow any exceptions.- auto key = TRY(IndexedDB::convert_a_value_to_a_key(realm, upper));-- // 2. If upperKey is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (key->is_invalid())- return WebIDL::DataError::create(realm, "Value is invalid"_utf16);-- // 3. Create and return a new key range with lower bound set to null, lower open flag set to true, upper bound set to upperKey, and upper open flag set to open.- return IndexedDB::IDBKeyRange::create({}, key, IndexedDB::IDBKeyRange::LowerOpen::Yes, open ? IndexedDB::IDBKeyRange::UpperOpen::Yes : IndexedDB::IDBKeyRange::UpperOpen::No);-}--// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-bound-WebIDL::ExceptionOr<GC::Ref<IndexedDB::IDBKeyRange>> bound(JS::Realm& realm, JS::Value lower, JS::Value upper, bool lower_open, bool upper_open)-{- // 1. Let lowerKey be the result of converting a value to a key with lower. Rethrow any exceptions.- auto lower_key = TRY(IndexedDB::convert_a_value_to_a_key(realm, lower));-- // 2. If lowerKey is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (lower_key->is_invalid())- return WebIDL::DataError::create(realm, "Value is invalid"_utf16);-- // 3. Let upperKey be the result of converting a value to a key with upper. Rethrow any exceptions.- auto upper_key = TRY(IndexedDB::convert_a_value_to_a_key(realm, upper));-- // 4. If upperKey is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (upper_key->is_invalid())- return WebIDL::DataError::create(realm, "Value is invalid"_utf16);-- // 5. If lowerKey is greater than upperKey, throw a "DataError" DOMException.- if (IndexedDB::Key::less_than(upper_key, lower_key))- return WebIDL::DataError::create(realm, "Lower key is greater than upper key"_utf16);-- // 6. Create and return a new key range with lower bound set to lowerKey, lower open flag set to lowerOpen, upper bound set to upperKey and upper open flag set to upperOpen.- return IndexedDB::IDBKeyRange::create(lower_key, upper_key, lower_open ? IndexedDB::IDBKeyRange::LowerOpen::Yes : IndexedDB::IDBKeyRange::LowerOpen::No, upper_open ? IndexedDB::IDBKeyRange::UpperOpen::Yes : IndexedDB::IDBKeyRange::UpperOpen::No);-}--// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes-WebIDL::ExceptionOr<bool> includes(JS::Realm& realm, IndexedDB::IDBKeyRange& key_range, JS::Value key)-{- // 1. Let k be the result of converting a value to a key with key. Rethrow any exceptions.- auto converted_key = TRY(IndexedDB::convert_a_value_to_a_key(realm, key));-- // 2. If k is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (converted_key->is_invalid())- return WebIDL::DataError::create(realm, "Value is invalid"_utf16);-- // 3. Return true if k is in this range, and false otherwise.- return key_range.is_in_range(converted_key);-}--JS::Value key_range_lower(JS::Realm& realm, IndexedDB::IDBKeyRange& key_range)-{- // The lower getter steps are to return the result of converting a key to a- // value with this's lower bound if it is not null, or undefined otherwise.- if (auto lower_key = key_range.lower_key())- return IndexedDB::convert_a_key_to_a_value(realm, *lower_key);-- return JS::js_undefined();-}--JS::Value key_range_upper(JS::Realm& realm, IndexedDB::IDBKeyRange& key_range)-{- // The upper getter steps are to return the result of converting a key to a- // value with this's upper bound if it is not null, or undefined otherwise.- if (auto upper_key = key_range.upper_key())- return IndexedDB::convert_a_key_to_a_value(realm, *upper_key);-- return JS::js_undefined();-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBKeyRange.h b/Libraries/LibWeb/IndexedDB/IDBKeyRange.hdeleted file mode 100644index ae45aabeb1c..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBKeyRange.h+++ /dev/null@@ -1,62 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Types.h>-#include <LibGC/Heap.h>-#include <LibGC/Ptr.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/IndexedDB/Internal/Key.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#keyrange-class IDBKeyRange : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(IDBKeyRange, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(IDBKeyRange);--public:- enum class LowerOpen {- No,- Yes,- };-- enum class UpperOpen {- No,- Yes,- };-- virtual ~IDBKeyRange() override;- [[nodiscard]] static GC::Ref<IDBKeyRange> create(GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, LowerOpen lower_open, UpperOpen upper_open);-- bool lower_open() const { return m_lower_open; }- bool upper_open() const { return m_upper_open; }-- bool is_unbound() const { return m_lower_bound == nullptr && m_upper_bound == nullptr; }- bool is_in_range(GC::Ref<Key>) const;- GC::Ptr<Key> lower_key() const { return m_lower_bound; }- GC::Ptr<Key> upper_key() const { return m_upper_bound; }--protected:- explicit IDBKeyRange(GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, LowerOpen lower_open, UpperOpen upper_open);- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- // A key range has an associated lower bound (null or a key).- GC::Ptr<Key> m_lower_bound;-- // A key range has an associated upper bound (null or a key).- GC::Ptr<Key> m_upper_bound;-- // A key range has an associated lower open flag. Unless otherwise stated it is false.- bool m_lower_open { false };-- // A key range has an associated upper open flag. Unless otherwise stated it is false.- bool m_upper_open { false };-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBKeyRange.idl b/Libraries/LibWeb/IndexedDB/IDBKeyRange.idlindex 2ee91ed08a6..16fa3db3d5b 100644--- a/Libraries/LibWeb/IndexedDB/IDBKeyRange.idl+++ b/Libraries/LibWeb/IndexedDB/IDBKeyRange.idl@@ -1,15 +1,15 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBKeyRange {- [ImplementedAs=key_range_lower, ImplementedInBindings, NeedsCallerRealm] readonly attribute any lower;- [ImplementedAs=key_range_upper, ImplementedInBindings, NeedsCallerRealm] readonly attribute any upper;+ [ImplementedAs=key_range_lower, NeedsCallerRealm] readonly attribute any lower;+ [ImplementedAs=key_range_upper, NeedsCallerRealm] readonly attribute any upper;readonly attribute boolean lowerOpen;readonly attribute boolean upperOpen;// Static construction methods:- [ImplementedInBindings, NeedsCallerRealm, NewObject] static IDBKeyRange only(any value);- [ImplementedInBindings, NeedsCallerRealm, NewObject] static IDBKeyRange lowerBound(any lower, optional boolean open = false);- [ImplementedInBindings, NeedsCallerRealm, NewObject] static IDBKeyRange upperBound(any upper, optional boolean open = false);- [ImplementedInBindings, NeedsCallerRealm, NewObject] static IDBKeyRange bound(any lower, any upper, optional boolean lowerOpen = false, optional boolean upperOpen = false);+ [NeedsCallerRealm, NewObject] static IDBKeyRange only(any value);+ [NeedsCallerRealm, NewObject] static IDBKeyRange lowerBound(any lower, optional boolean open = false);+ [NeedsCallerRealm, NewObject] static IDBKeyRange upperBound(any upper, optional boolean open = false);+ [NeedsCallerRealm, NewObject] static IDBKeyRange bound(any lower, any upper, optional boolean lowerOpen = false, optional boolean upperOpen = false);- [ImplementedInBindings, NeedsCallerRealm] boolean includes(any key);+ [NeedsCallerRealm] boolean includes(any key);};diff --git a/Libraries/LibWeb/IndexedDB/IDBObjectStore.cpp b/Libraries/LibWeb/IndexedDB/IDBObjectStore.cppdeleted file mode 100644index 3522571548e..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBObjectStore.cpp+++ /dev/null@@ -1,671 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/String.h>-#include <LibGC/Heap.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/IndexedDB/IDBCursor.h>-#include <LibWeb/IndexedDB/IDBCursorWithValue.h>-#include <LibWeb/IndexedDB/IDBIndex.h>-#include <LibWeb/IndexedDB/IDBObjectStore.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBObjectStore);--IDBObjectStore::~IDBObjectStore() = default;--IDBObjectStore::IDBObjectStore(GC::Ref<ObjectStore> store, GC::Ref<IDBTransaction> transaction)- : m_store(store)- , m_transaction(transaction)- , m_name(store->name())-{- // An object store handle has an index set, which is initialized to the set of indexes that reference the associated object store when the object store handle is created.- m_indexes = store->index_set();-}--GC::Ref<IDBObjectStore> IDBObjectStore::create(GC::Ref<ObjectStore> store, GC::Ref<IDBTransaction> transaction)-{- return GC::Heap::the().allocate<IDBObjectStore>(store, transaction);-}--void IDBObjectStore::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_store);- visitor.visit(m_transaction);- visitor.visit(m_indexes);- visitor.visit(m_key_path_arrays);- visitor.visit(m_index_handles);-}--JS::Object& IDBObjectStore::relevant_global_object() const-{- return m_transaction->relevant_global_object();-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-name-Utf16String IDBObjectStore::name() const-{- // The name getter steps are to return this’s name.- return m_name;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-name-WebIDL::ExceptionOr<void> IDBObjectStore::set_name(Utf16String const& value)-{- // 1. Let name be the given value.- auto const& name = value;-- // 2. Let transaction be this’s transaction.- auto& transaction = m_transaction;-- // 3. Let store be this’s object store.- auto& store = m_store;-- // 4. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 5. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.- if (!transaction->is_upgrade_transaction())- return WebIDL::InvalidStateError::create("Attempted to set name outside of version change"_utf16);-- // 6. If transaction’s state is not active, throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while updating object store name"_utf16);-- // 7. If store’s name is equal to name, terminate these steps.- if (store->name() == name)- return {};-- // 8. If an object store named name already exists in store’s database, throw a "ConstraintError" DOMException.- if (store->database()->object_store_with_name(name))- return WebIDL::ConstraintError::create("Object store with the given name already exists"_utf16);-- // AD-HOC: Log the rename for potential revert on abort.- store->mutation_log()->note_object_store_renamed(store->name());-- // 9. Set store’s name to name.- store->set_name(name);-- // 10. Set this’s name to name.- m_name = name;-- return {};-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-keypath-Optional<KeyPath> const& IDBObjectStore::key_path() const-{- return m_store->key_path();-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-keypath-JS::ThrowCompletionOr<JS::Value> IDBObjectStore::key_path_value(JS::Realm& realm)-{- // The keyPath getter steps are to return this’s object store’s key path, or null if none. The key path is- // converted as a DOMString (if a string) or a sequence<DOMString> (if a list of strings), per [WEBIDL].- auto const& key_path = this->key_path();- if (!key_path.has_value())- return JS::js_null();-- // NOTE: The returned value is not the same instance that was used when the object store was created. However, if- // this attribute returns an object (specifically an Array), it returns the same object instance every time- // it is inspected. Changing the properties of the object has no effect on the object store.- if (auto array = m_key_path_arrays.get(realm.global_object()); array.has_value())- return *array;-- auto value = TRY(convert_a_key_path_to_a_value(realm, key_path.value()));- if (value.is_object())- m_key_path_arrays.set(realm.global_object(), value.as_object());- return value;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-indexnames-GC::Ref<HTML::DOMStringList> IDBObjectStore::index_names()-{- // 1. Let names be a list of the names of the indexes in this's index set.- Vector<Utf16String> names;- for (auto const& [name, index] : m_indexes)- names.append(name);-- // 2. Return the result (a DOMStringList) of creating a sorted name list with names.- return create_a_sorted_name_list(names);-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-transaction-GC::Ref<IDBTransaction> IDBObjectStore::transaction() const-{- // The transaction getter steps are to return this’s transaction.- return m_transaction;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-autoincrement-bool IDBObjectStore::auto_increment() const-{- // The autoIncrement getter steps are to return true if this’s object store has a key generator, and false otherwise.- return m_store->uses_a_key_generator();-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-createindex-WebIDL::ExceptionOr<GC::Ref<IDBIndex>> IDBObjectStore::create_index(Utf16String const& name, KeyPath key_path, IndexParameters const& options)-{- // 1. Let transaction be this's transaction.- auto transaction = this->transaction();-- // 2. Let store be this's object store.- auto store = this->store();-- // 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.- if (!transaction->is_upgrade_transaction())- return WebIDL::InvalidStateError::create("Transaction is not an upgrade transaction"_utf16);-- // 4. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while creating index"_utf16);-- // 6. If an index named name already exists in store, throw a "ConstraintError" DOMException.- if (store->index_set().contains(name))- return WebIDL::ConstraintError::create("An index with the given name already exists"_utf16);-- // 7. If keyPath is not a valid key path, throw a "SyntaxError" DOMException.- if (!is_valid_key_path(key_path))- return WebIDL::SyntaxError::create("Key path is not valid"_utf16);-- // 8. Let unique be options’s unique member.- auto unique = options.unique;-- // 9. Let multiEntry be options’s multiEntry member.- auto multi_entry = options.multi_entry;-- // 10. If keyPath is a sequence and multiEntry is true, throw an "InvalidAccessError" DOMException.- if (key_path.has<Vector<Utf16String>>() && multi_entry)- return WebIDL::InvalidAccessError::create("Key path is a sequence and multiEntry is true"_utf16);-- // 11. Let index be a new index in store.- // Set index’s name to name, key path to keyPath, unique flag to unique, and multiEntry flag to multiEntry.- auto index = Index::create(store, name, key_path, unique, multi_entry);-- // 12. Add index to this's index set.- this->index_set().set(name, index);-- // AD-HOC: Log the creation for potential revert on abort.- store->mutation_log()->note_index_created(index);-- // AD-HOC: Fill the index with the records of store, as a request after the ones made before.- queue_the_creation_of_an_index(*this, index);-- // 13. Return a new index handle associated with index and this.- return m_index_handles.ensure(index, [&] { return IDBIndex::create(index, *this); });-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index-WebIDL::ExceptionOr<GC::Ref<IDBIndex>> IDBObjectStore::index(Utf16String const& name)-{- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let store be this’s object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is finished, then throw an "InvalidStateError" DOMException.- if (transaction->state() == IDBTransaction::TransactionState::Finished)- return WebIDL::InvalidStateError::create("Transaction is finished"_utf16);-- // 5. Let index be the index named name in this’s index set if one exists, or throw a "NotFoundError" DOMException otherwise.- auto index = m_indexes.get(name);- if (!index.has_value())- return WebIDL::NotFoundError::create("Index not found in object store"_utf16);-- // 6. Return an index handle associated with index and this.- // NOTE: Each call to this method on the same IDBObjectStore instance with the same name returns the same IDBIndex- // instance.- return m_index_handles.ensure(*index, [&] { return IDBIndex::create(*index, *this); });-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-deleteindex-WebIDL::ExceptionOr<void> IDBObjectStore::delete_index(Utf16String const& name)-{- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let store be this’s object store.- auto store = this->store();-- // 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.- if (!transaction->is_upgrade_transaction())- return WebIDL::InvalidStateError::create("Transaction is not an upgrade transaction"_utf16);-- // 4. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while deleting index"_utf16);-- // 6. Let index be the index named name in store if one exists, or throw a "NotFoundError" DOMException otherwise.- auto index = m_indexes.get(name);- if (!index.has_value())- return WebIDL::NotFoundError::create("Index not found while trying to delete it"_utf16);-- // 7. Remove index from this’s index set.- m_indexes.remove(name);-- // AD-HOC: Mark the index as deleted so that stale handles throw InvalidStateError.- index.value()->set_deleted(true);-- // AD-HOC: Log the deletion for potential revert on abort.- store->mutation_log()->note_index_deleted(*index.value());-- // 8. Destroy index.- store->index_set().remove(name);-- return {};-}--// https://w3c.github.io/IndexedDB/#add-or-put-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::add_or_put(GC::Ref<IDBObjectStore> handle, JS::Value value, Optional<JS::Value> const& key, bool no_overwrite)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be handle’s transaction.- auto transaction = handle->transaction();-- // 2. Let store be handle’s object store.- auto& store = *handle->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store.is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while running add/put"_utf16);-- // 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.- if (transaction->is_readonly())- return WebIDL::ReadOnlyError::create("Transaction is read-only"_utf16);-- auto key_was_given = key.has_value() && key != JS::js_undefined();-- // 6. If store uses in-line keys and key was given, throw a "DataError" DOMException.- if (store.uses_inline_keys() && key_was_given)- return WebIDL::DataError::create("Store uses in-line keys and key was given"_utf16);-- // 7. If store uses out-of-line keys and has no key generator and key was not given, throw a "DataError" DOMException.- if (store.uses_out_of_line_keys() && !store.uses_a_key_generator() && !key_was_given)- return WebIDL::DataError::create("Store uses out-of-line keys and has no key generator and key was not given"_utf16);-- GC::Ptr<Key> key_value;- // 8. If key was given, then:- if (key_was_given) {- // 1. Let r be the result of converting a value to a key with key. Rethrow any exceptions.- auto r = TRY(convert_a_value_to_a_key(realm, key.value()));-- // 2. If r is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (r->is_invalid())- return WebIDL::DataError::create("Key is invalid"_utf16);-- // 3. Let key be r.- key_value = r;- }-- // 9. Let targetRealm be a user-agent defined Realm.- auto& target_realm = realm;-- // 10. Let clone be a clone of value in targetRealm during transaction. Rethrow any exceptions.- auto clone = TRY(clone_in_realm(target_realm, value, transaction));-- // 11. If store uses in-line keys, then:- if (store.uses_inline_keys()) {- // 1. Let kpk be the result of extracting a key from a value using a key path with clone and store’s key path. Rethrow any exceptions.- auto maybe_kpk = TRY(extract_a_key_from_a_value_using_a_key_path(realm, clone, store.key_path().value()));-- // NOTE: Step 2 and 3 is reversed here, since we check for failure before validity.- // 3. If kpk is not failure, let key be kpk.- if (!maybe_kpk.is_error()) {- key_value = maybe_kpk.release_value();-- // 2. If kpk is invalid, throw a "DataError" DOMException.- if (key_value->is_invalid())- return WebIDL::DataError::create(key_value->value_as_string());- }-- // 4. Otherwise (kpk is failure):- else {- // 1. If store does not have a key generator, throw a "DataError" DOMException.- if (!store.uses_a_key_generator())- return WebIDL::DataError::create("Store does not have a key generator"_utf16);-- // 2. If check that a key could be injected into a value with clone and store’s key path return false, throw a "DataError" DOMException.- if (!check_that_a_key_could_be_injected_into_a_value(realm, clone, store.key_path().value()))- return WebIDL::DataError::create("Key could not be injected into value"_utf16);- }- }-- // 12. Let operation be an algorithm to run store a record into an object store with store, clone, key, and no-overwrite flag.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, &store, clone, key_value, no_overwrite] -> WebIDL::ExceptionOr<JS::Value> {- HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- auto optional_key = TRY(store_a_record_into_an_object_store(realm, store, clone, key_value, no_overwrite));-- if (!optional_key || optional_key->is_invalid())- return JS::js_undefined();-- return convert_a_key_to_a_value(realm, GC::Ref(*optional_key));- });-- // 13. Return the result (an IDBRequest) of running asynchronously execute a request with handle and operation.- auto result = asynchronously_execute_a_request(realm, handle, operation);- dbgln_if(IDB_DEBUG, "Executing request for add/put with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-add-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::add(JS::Value value, Optional<JS::Value> const& key)-{- // The add(value, key) method steps are to return the result of running add or put with this, value, key and the no-overwrite flag true.- return add_or_put(*this, value, key, true);-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-put-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::put(JS::Value value, Optional<JS::Value> const& key)-{- // The put(value, key) method steps are to return the result of running add or put with this, value, key and the no-overwrite flag false.- return add_or_put(*this, value, key, false);-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-count-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::count(Optional<JS::Value> query)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this's transaction.- auto transaction = this->transaction();-- // 2. Let store be this's object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while doing count"_utf16);-- // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, move(query)));-- // 6. Let operation be an algorithm to run count the records in a range with store and range.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [store, range] -> WebIDL::ExceptionOr<JS::Value> {- return count_the_records_in_a_range(store, range);- });-- // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for count with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-get-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::get(JS::Value query)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this's transaction.- auto transaction = this->transaction();-- // 2. Let store be this's object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while getting"_utf16);-- // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query, true));-- // 6. Let operation be an algorithm to run retrieve a value from an object store with the current Realm record, store, and range.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, store, range] -> WebIDL::ExceptionOr<JS::Value> {- return retrieve_a_value_from_an_object_store(realm, store, range);- });-- // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for get with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-opencursor-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::open_cursor(Optional<JS::Value> query, CursorDirection direction)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this's transaction.- auto transaction = this->transaction();-- // 2. Let store be this’s object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while opening cursor"_utf16);-- // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query, false));-- // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction,- // got value flag set to false, undefined key and value, range set to range, and key only flag set to false.- auto cursor = IDBCursor::create(GC::Ref(*this), {}, direction, IDBCursor::GotValue::No, {}, {}, range, IDBCursor::KeyOnly::No);-- // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, cursor] -> WebIDL::ExceptionOr<JS::Value> {- auto result = TRY(iterate_a_cursor(realm, cursor));- return Bindings::idb_cursor_result(realm, result);- });-- // 8. Let request be the result of running asynchronously execute a request with this and operation.- auto request = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for open cursor with uuid {}", request->uuid());-- // 9. Set cursor’s request to request.- cursor->set_request(request);-- // 10. Return request.- return request;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-delete-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::delete_(JS::Value query)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let store be this’s object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while deleting object store"_utf16);-- // 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.- if (transaction->is_readonly())- return WebIDL::ReadOnlyError::create("Transaction is read-only while deleting object store"_utf16);-- // 6. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query, true));-- // 7. Let operation be an algorithm to run delete records from an object store with store and range.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [store, range] -> WebIDL::ExceptionOr<JS::Value> {- return delete_records_from_an_object_store(store, range);- });-- // 8. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for delete with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-clear-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::clear()-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let store be this’s object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while clearing object store"_utf16);-- // 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.- if (transaction->is_readonly())- return WebIDL::ReadOnlyError::create("Transaction is read-only while clearing object store"_utf16);-- // 6. Let operation be an algorithm to run clear an object store with store.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [store] -> WebIDL::ExceptionOr<JS::Value> {- return clear_an_object_store(store);- });-- // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for clear with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::get_key(JS::Value query)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let store be this’s object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while getting key"_utf16);-- // 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query, true));-- // 6. Let operation be an algorithm to run retrieve a key from an object store with store and range.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, store, range] -> WebIDL::ExceptionOr<JS::Value> {- return retrieve_a_key_from_an_object_store(realm, store, range);- });-- // 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.- auto result = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for get key with uuid {}", result->uuid());- return result;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::get_all(Optional<JS::Value> query_or_options, Optional<WebIDL::UnsignedLong> count)-{- // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,- // "value", queryOrOptions, and count if given. Rethrow any exceptions.- return create_a_request_to_retrieve_multiple_items(HTML::relevant_realm(relevant_global_object()), GC::Ref(*this), RecordKind::Value, query_or_options.value_or(JS::js_undefined()), count);-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-openkeycursor-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::open_key_cursor(Optional<JS::Value> query, CursorDirection direction)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let transaction be this’s transaction.- auto transaction = this->transaction();-- // 2. Let store be this’s object store.- auto store = this->store();-- // 3. If store has been deleted, throw an "InvalidStateError" DOMException.- if (store->is_deleted())- return WebIDL::InvalidStateError::create("Object store has been deleted"_utf16);-- // 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while opening key cursor"_utf16);-- // 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.- auto range = TRY(convert_a_value_to_a_key_range(realm, query));-- // 6. Let cursor be a new cursor with its source handle set to this, undefined position, direction set to direction, got value flag set to false, undefined key and value, range set to range, and key only flag set to true.- auto cursor = IDBCursor::create(GC::Ref(*this), {}, direction, IDBCursor::GotValue::No, {}, {}, range, IDBCursor::KeyOnly::Yes);-- // 7. Let operation be an algorithm to run iterate a cursor with the current Realm record and cursor.- auto operation = GC::Function<WebIDL::ExceptionOr<JS::Value>()>::create(GC::Heap::the(), [&realm, cursor] -> WebIDL::ExceptionOr<JS::Value> {- auto result = TRY(iterate_a_cursor(realm, cursor));- return Bindings::idb_cursor_result(realm, result);- });-- // 8. Let request be the result of running asynchronously execute a request with this and operation.- auto request = asynchronously_execute_a_request(realm, GC::Ref(*this), operation);- dbgln_if(IDB_DEBUG, "Executing request for open key cursor with uuid {}", request->uuid());-- // 9. Set cursor’s request to request.- cursor->set_request(request);-- // 10. Return request.- return request;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::get_all_keys(Optional<JS::Value> query_or_options, Optional<WebIDL::UnsignedLong> count)-{- // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this, "key",- // queryOrOptions, and count if given. Rethrow any exceptions.- return create_a_request_to_retrieve_multiple_items(HTML::relevant_realm(relevant_global_object()), GC::Ref(*this), RecordKind::Key, query_or_options.value_or(JS::js_undefined()), count);-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallrecords-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> IDBObjectStore::get_all_records(RetrieveMultipleItemsOptions const& options)-{- // 1. Return the result of creating a request to retrieve multiple items with the current Realm record, this,- // "record", and options. Rethrow any exceptions.- return create_a_request_to_retrieve_multiple_items(HTML::relevant_realm(relevant_global_object()), GC::Ref(*this), RecordKind::Record, options);-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBObjectStore.h b/Libraries/LibWeb/IndexedDB/IDBObjectStore.hdeleted file mode 100644index b33ea13fce9..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBObjectStore.h+++ /dev/null@@ -1,90 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/IDBCursor.h>-#include <LibWeb/Bindings/IDBObjectStore.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/IndexedDB/IDBTransaction.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/Index.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>--namespace Web::IndexedDB {--using IndexParameters = Bindings::IDBIndexParameters;--// https://w3c.github.io/IndexedDB/#object-store-interface-// https://w3c.github.io/IndexedDB/#object-store-handle-construct-class IDBObjectStore : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(IDBObjectStore, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(IDBObjectStore);--public:- virtual ~IDBObjectStore() override;- [[nodiscard]] static GC::Ref<IDBObjectStore> create(GC::Ref<ObjectStore>, GC::Ref<IDBTransaction>);-- Utf16String name() const;- WebIDL::ExceptionOr<void> set_name(Utf16String const& value);- Optional<KeyPath> const& key_path() const;- JS::ThrowCompletionOr<JS::Value> key_path_value(JS::Realm&);- [[nodiscard]] GC::Ref<HTML::DOMStringList> index_names();- GC::Ref<IDBTransaction> transaction() const;- bool auto_increment() const;-- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> put(JS::Value value, Optional<JS::Value> const& key);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> add(JS::Value value, Optional<JS::Value> const& key);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> delete_(JS::Value);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> clear();- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get(JS::Value);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_key(JS::Value);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_all(Optional<JS::Value>, Optional<WebIDL::UnsignedLong>);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_all_keys(Optional<JS::Value>, Optional<WebIDL::UnsignedLong>);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> get_all_records(RetrieveMultipleItemsOptions const&);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> count(Optional<JS::Value>);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> open_cursor(Optional<JS::Value>, CursorDirection);- [[nodiscard]] WebIDL::ExceptionOr<GC::Ref<IDBRequest>> open_key_cursor(Optional<JS::Value>, CursorDirection);-- WebIDL::ExceptionOr<GC::Ref<IDBIndex>> index(Utf16String const&);-- WebIDL::ExceptionOr<GC::Ref<IDBIndex>> create_index(Utf16String const&, KeyPath, IndexParameters const&);- WebIDL::ExceptionOr<void> delete_index(Utf16String const&);-- JS::Object& relevant_global_object() const;- AK::HashMap<Utf16String, GC::Ref<Index>>& index_set() { return m_indexes; }- WebIDL::ExceptionOr<GC::Ref<IDBRequest>> add_or_put(GC::Ref<IDBObjectStore>, JS::Value, Optional<JS::Value> const&, bool);- GC::Ref<ObjectStore> store() const { return m_store; }-- void update_name() { m_name = m_store->name(); }- void update_index_set() { m_indexes = m_store->index_set(); }--protected:- explicit IDBObjectStore(GC::Ref<ObjectStore>, GC::Ref<IDBTransaction>);- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- // An object store handle has an associated object store and an associated transaction.- GC::Ref<ObjectStore> m_store;- GC::Ref<IDBTransaction> m_transaction;-- // An object store handle has a name, which is initialized to the name of the associated object store when the object store handle is created.- Utf16String m_name;-- // An object store handle has an index set- AK::HashMap<Utf16String, GC::Ref<Index>> m_indexes;-- // NB: The keyPath getter returns the same Array every time it is inspected in the same realm.- HashMap<GC::Ref<JS::Object>, GC::Ref<JS::Object>> m_key_path_arrays;-- // NB: Each call to index() on the same IDBObjectStore instance with the same name returns the same IDBIndex- // instance. These are keyed by index so that they survive renames.- HashMap<GC::Ref<Index>, GC::Ref<IDBIndex>> m_index_handles;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBObjectStore.idl b/Libraries/LibWeb/IndexedDB/IDBObjectStore.idlindex 01617c80db9..f788dc9c93b 100644--- a/Libraries/LibWeb/IndexedDB/IDBObjectStore.idl+++ b/Libraries/LibWeb/IndexedDB/IDBObjectStore.idl@@ -1,4 +1,4 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBObjectStore {attribute DOMString name;[ImplementedAs=key_path_value, NeedsCallerRealm] readonly attribute any keyPath;diff --git a/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.cpp b/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.cppdeleted file mode 100644index 065b8520347..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.cpp+++ /dev/null@@ -1,63 +0,0 @@-/*- * Copyright (c) 2024, Shannon Booth <[email protected]>- * Copyright (c) 2024, Jamie Mansfield <[email protected]>- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/IndexedDB/IDBOpenDBRequest.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBOpenDBRequest);--IDBOpenDBRequest::~IDBOpenDBRequest() = default;--// NOTE: The source of an open request is always null.-IDBOpenDBRequest::IDBOpenDBRequest(GC::Ref<DOM::EventTarget> relevant_global_object)- : IDBRequest(relevant_global_object, {})-{-}--GC::Ref<IDBOpenDBRequest> IDBOpenDBRequest::create(GC::Ref<DOM::EventTarget> relevant_global_object)-{- return GC::Heap::the().allocate<IDBOpenDBRequest>(relevant_global_object);-}--DOM::EventTarget* IDBOpenDBRequest::get_parent(DOM::Event const&)-{- // https://w3c.github.io/IndexedDB/#open-requests- // An open request’s get the parent algorithm returns null.- return nullptr;-}--// https://w3c.github.io/IndexedDB/#dom-idbopendbrequest-onblocked-void IDBOpenDBRequest::set_onblocked(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::blocked, event_handler);-}--// https://w3c.github.io/IndexedDB/#dom-idbopendbrequest-onblocked-WebIDL::CallbackType* IDBOpenDBRequest::onblocked()-{- return event_handler_attribute(HTML::EventNames::blocked);-}--// https://w3c.github.io/IndexedDB/#dom-idbopendbrequest-onupgradeneeded-void IDBOpenDBRequest::set_onupgradeneeded(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::upgradeneeded, event_handler);-}--// https://w3c.github.io/IndexedDB/#dom-idbopendbrequest-onupgradeneeded-WebIDL::CallbackType* IDBOpenDBRequest::onupgradeneeded()-{- return event_handler_attribute(HTML::EventNames::upgradeneeded);-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.h b/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.hdeleted file mode 100644index 7860dc9edd2..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.h+++ /dev/null@@ -1,36 +0,0 @@-/*- * Copyright (c) 2024, Shannon Booth <[email protected]>- * Copyright (c) 2024, Jamie Mansfield <[email protected]>- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/IndexedDB/IDBRequest.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#idbopendbrequest-class IDBOpenDBRequest : public IDBRequest {- WEB_WRAPPABLE(IDBOpenDBRequest, IDBRequest);- GC_DECLARE_ALLOCATOR(IDBOpenDBRequest);--public:- virtual ~IDBOpenDBRequest();-- [[nodiscard]] static GC::Ref<IDBOpenDBRequest> create(GC::Ref<DOM::EventTarget> relevant_global_object);-- void set_onblocked(WebIDL::CallbackType*);- WebIDL::CallbackType* onblocked();- void set_onupgradeneeded(WebIDL::CallbackType*);- WebIDL::CallbackType* onupgradeneeded();--protected:- explicit IDBOpenDBRequest(GC::Ref<DOM::EventTarget> relevant_global_object);-- virtual EventTarget* get_parent(DOM::Event const&) override;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.idl b/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.idlindex 74a4d3a4368..9aa5eefed40 100644--- a/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.idl+++ b/Libraries/LibWeb/IndexedDB/IDBOpenDBRequest.idl@@ -1,5 +1,5 @@// https://w3c.github.io/IndexedDB/#idbopendbrequest-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBOpenDBRequest : IDBRequest {// Event handlers:attribute EventHandler onblocked;diff --git a/Libraries/LibWeb/IndexedDB/IDBRecord.cpp b/Libraries/LibWeb/IndexedDB/IDBRecord.cppdeleted file mode 100644index 34d071377d0..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBRecord.cpp+++ /dev/null@@ -1,51 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/IndexedDB/IDBRecord.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBRecord);--IDBRecord::~IDBRecord() = default;--GC::Ref<IDBRecord> IDBRecord::create(GC::Ref<Key> key, JS::Value value, GC::Ref<Key> primary_key)-{- return GC::Heap::the().allocate<IDBRecord>(move(key), move(value), move(primary_key));-}--IDBRecord::IDBRecord(GC::Ref<Key> key, JS::Value value, GC::Ref<Key> primary_key)- : m_key(move(key))- , m_value(move(value))- , m_primary_key(move(primary_key))-{-}--JS::Value IDBRecord::key(JS::Realm& realm) const-{- // The key getter steps are to return the result of converting a key to a- // value with this's key.- return convert_a_key_to_a_value(realm, m_key);-}--JS::Value IDBRecord::primary_key(JS::Realm& realm) const-{- // The primaryKey getter steps are to return the result of converting a key- // to a value with this's primary key.- return convert_a_key_to_a_value(realm, m_primary_key);-}--void IDBRecord::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_key);- visitor.visit(m_value);- visitor.visit(m_primary_key);-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBRecord.h b/Libraries/LibWeb/IndexedDB/IDBRecord.hdeleted file mode 100644index 3e48bfccfef..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBRecord.h+++ /dev/null@@ -1,71 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/OwnPtr.h>-#include <LibGC/Ptr.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Export.h>-#include <LibWeb/HTML/StructuredSerializeTypes.h>-#include <LibWeb/IndexedDB/Internal/Key.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#object-store-record-struct ObjectStoreRecord {- GC::Ref<Key> key;- OwnPtr<HTML::StorageSerializationRecord> value;-- ObjectStoreRecord(GC::Ref<Key> key, NonnullOwnPtr<HTML::StorageSerializationRecord> value)- : key(key)- , value(move(value))- {- }-- ObjectStoreRecord(ObjectStoreRecord const& other)- : key(other.key)- , value(make<HTML::StorageSerializationRecord>(*other.value))- {- }-- ObjectStoreRecord(ObjectStoreRecord&&) = default;- ObjectStoreRecord& operator=(ObjectStoreRecord&&) = default;- ObjectStoreRecord& operator=(ObjectStoreRecord const&) = delete;-};--// https://w3c.github.io/IndexedDB/#index-list-of-records-struct IndexRecord {- GC::Ref<Key> key;- GC::Ref<Key> value;-};--// https://w3c.github.io/IndexedDB/#record-snapshot-// https://w3c.github.io/IndexedDB/#record-interface-class IDBRecord : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(IDBRecord, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(IDBRecord);--public:- [[nodiscard]] static GC::Ref<IDBRecord> create(GC::Ref<Key> key, JS::Value value, GC::Ref<Key> primary_key);- virtual ~IDBRecord();-- JS::Value key(JS::Realm&) const;- JS::Value primary_key(JS::Realm&) const;- JS::Value const& value() const { return m_value; }--protected:- explicit IDBRecord(GC::Ref<Key> key, JS::Value value, GC::Ref<Key> primary_key);- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- GC::Ref<Key> m_key;- JS::Value m_value;- GC::Ref<Key> m_primary_key;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBRecord.idl b/Libraries/LibWeb/IndexedDB/IDBRecord.idlindex a9b85c2be35..689c95fa946 100644--- a/Libraries/LibWeb/IndexedDB/IDBRecord.idl+++ b/Libraries/LibWeb/IndexedDB/IDBRecord.idl@@ -1,5 +1,5 @@// https://w3c.github.io/IndexedDB/#record-interface-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBRecord {[NeedsCallerRealm] readonly attribute any key;[NeedsCallerRealm] readonly attribute any primaryKey;diff --git a/Libraries/LibWeb/IndexedDB/IDBRequest.cpp b/Libraries/LibWeb/IndexedDB/IDBRequest.cppdeleted file mode 100644index c1e4755fde3..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBRequest.cpp+++ /dev/null@@ -1,122 +0,0 @@-/*- * Copyright (c) 2024, Shannon Booth <[email protected]>- * Copyright (c) 2024, Jamie Mansfield <[email protected]>- * Copyright (c) 2024-2025, stelar7 <[email protected]>- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Crypto/Crypto.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/IndexedDB/IDBCursor.h>-#include <LibWeb/IndexedDB/IDBIndex.h>-#include <LibWeb/IndexedDB/IDBObjectStore.h>-#include <LibWeb/IndexedDB/IDBRequest.h>-#include <LibWeb/IndexedDB/IDBTransaction.h>-#include <LibWeb/WebIDL/DOMException.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBRequest);--IDBRequest::~IDBRequest() = default;--IDBRequest::IDBRequest(GC::Ref<DOM::EventTarget> relevant_global_object, IDBRequestSource source)- : EventTarget()- , m_source(source)- , m_global_object(relevant_global_object)- , m_uuid(Crypto::generate_random_uuid())-{-}--GC::Ref<IDBRequest> IDBRequest::create(GC::Ref<DOM::EventTarget> relevant_global_object, IDBRequestSource source)-{- return GC::Heap::the().allocate<IDBRequest>(relevant_global_object, source);-}--// https://w3c.github.io/IndexedDB/#dom-idbrequest-result-WebIDL::ExceptionOr<JS::Value> IDBRequest::result() const-{- // 1. If this's done flag is false, then throw an "InvalidStateError" DOMException.- if (!done())- return WebIDL::InvalidStateError::create("The request is not done"_utf16);-- // 2. Return this's result, or undefined if the request resulted in an error.- if (has_error())- return JS::js_undefined();-- return m_result;-}--void IDBRequest::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_result);- visitor.visit(m_transaction);- visitor.visit(m_source);- visitor.visit(m_global_object);- visitor.visit(m_error);-}--JS::Object& IDBRequest::relevant_global_object() const-{- return HTML::relevant_global_object(relevant_global_scope());-}--HTML::WindowOrWorkerGlobalScopeMixin& IDBRequest::relevant_global_scope() const-{- return HTML::relevant_window_or_worker_global_scope(*m_global_object);-}--DOM::EventTarget* IDBRequest::get_parent(DOM::Event const&)-{- // https://w3c.github.io/IndexedDB/#request-construct- // A request’s get the parent algorithm returns the request’s transaction.- return m_transaction.ptr();-}--// https://w3c.github.io/IndexedDB/#dom-idbrequest-onsuccess-void IDBRequest::set_onsuccess(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::success, event_handler);-}--// https://w3c.github.io/IndexedDB/#dom-idbrequest-onsuccess-WebIDL::CallbackType* IDBRequest::onsuccess()-{- return event_handler_attribute(HTML::EventNames::success);-}--// https://w3c.github.io/IndexedDB/#dom-idbrequest-onerror-void IDBRequest::set_onerror(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::error, event_handler);-}--// https://w3c.github.io/IndexedDB/#dom-idbrequest-onerror-WebIDL::CallbackType* IDBRequest::onerror()-{- return event_handler_attribute(HTML::EventNames::error);-}--// https://w3c.github.io/IndexedDB/#dom-idbrequest-error-WebIDL::ExceptionOr<GC::Ptr<WebIDL::DOMException>> IDBRequest::error() const-{- // 1. If this's done flag is false, then throw an "InvalidStateError" DOMException.- if (!m_done)- return WebIDL::InvalidStateError::create("The request is not done"_utf16);-- // 2. Return this's error, or null if no error occurred.- return m_error.value_or(nullptr);-}--Bindings::IDBRequestReadyState IDBRequest::ready_state() const-{- // The readyState getter steps are to return "pending" if this's done flag is false, and "done" otherwise.- return done() ? Bindings::IDBRequestReadyState::Done : Bindings::IDBRequestReadyState::Pending;-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBRequest.h b/Libraries/LibWeb/IndexedDB/IDBRequest.hdeleted file mode 100644index 61baa89065b..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBRequest.h+++ /dev/null@@ -1,96 +0,0 @@-/*- * Copyright (c) 2024, Shannon Booth <[email protected]>- * Copyright (c) 2024, Jamie Mansfield <[email protected]>- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Bindings/IDBRequest.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::HTML {--class WindowOrWorkerGlobalScopeMixin;--}--namespace Web::IndexedDB {--using IDBRequestSource = Variant<Empty, GC::Ref<IDBObjectStore>, GC::Ref<IDBIndex>, GC::Ref<IDBCursor>>;--// https://w3c.github.io/IndexedDB/#request-api-class IDBRequest : public DOM::EventTarget {- WEB_WRAPPABLE(IDBRequest, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(IDBRequest);--public:- virtual ~IDBRequest() override;-- [[nodiscard]] static GC::Ref<IDBRequest> create(GC::Ref<DOM::EventTarget> relevant_global_object, IDBRequestSource);-- [[nodiscard]] bool done() const { return m_done; }- [[nodiscard]] bool processed() const { return m_processed; }- [[nodiscard]] IDBRequestSource source() const { return m_source; }- [[nodiscard]] GC::Ptr<IDBTransaction> transaction() const { return m_transaction; }- static constexpr size_t transaction_offset() { return offsetof(IDBRequest, m_transaction); }- [[nodiscard]] String uuid() const { return m_uuid; }-- [[nodiscard]] HTML::WindowOrWorkerGlobalScopeMixin& relevant_global_scope() const;- [[nodiscard]] JS::Object& relevant_global_object() const;- [[nodiscard]] WebIDL::ExceptionOr<GC::Ptr<WebIDL::DOMException>> error() const;- [[nodiscard]] WebIDL::ExceptionOr<JS::Value> result() const;- [[nodiscard]] Bindings::IDBRequestReadyState ready_state() const;-- void set_done(bool done) { m_done = done; }- void set_result(JS::Value result) { m_result = result; }- void set_error(Optional<GC::Ptr<WebIDL::DOMException>> error) { m_error = error; }- void set_processed(bool processed) { m_processed = processed; }- void set_source(IDBRequestSource source) { m_source = source; }- void set_transaction(GC::Ptr<IDBTransaction> transaction) { m_transaction = transaction; }-- bool has_error() const { return m_error.has_value(); }-- void set_onsuccess(WebIDL::CallbackType*);- WebIDL::CallbackType* onsuccess();- void set_onerror(WebIDL::CallbackType*);- WebIDL::CallbackType* onerror();-- [[nodiscard]] bool aborted() const { return m_aborted; }- void set_aborted(bool aborted) { m_aborted = aborted; }--protected:- IDBRequest(GC::Ref<DOM::EventTarget> relevant_global_object, IDBRequestSource);-- virtual void visit_edges(Visitor& visitor) override;- virtual EventTarget* get_parent(DOM::Event const&) override;--private:- // A request has a processed flag which is initially false.- bool m_processed { false };-- // A request has a done flag which is initially false.- bool m_done { false };-- // A request has a result and an error- JS::Value m_result;- Optional<GC::Ptr<WebIDL::DOMException>> m_error;-- // A request has a source object.- IDBRequestSource m_source;- GC::Ref<DOM::EventTarget> m_global_object;-- // A request has a transaction which is initially null.- GC::Ptr<IDBTransaction> m_transaction;-- // AD-HOC: Set to true to prevent queued operations and result events from executing.- bool m_aborted { false };-- // NOTE: Used for debug purposes- String m_uuid;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBRequest.idl b/Libraries/LibWeb/IndexedDB/IDBRequest.idlindex d40ec819c48..cfbe11165fc 100644--- a/Libraries/LibWeb/IndexedDB/IDBRequest.idl+++ b/Libraries/LibWeb/IndexedDB/IDBRequest.idl@@ -1,10 +1,10 @@// https://w3c.github.io/IndexedDB/#idbrequest-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBRequest : EventTarget {readonly attribute any result;readonly attribute DOMException? error;readonly attribute (IDBObjectStore or IDBIndex or IDBCursor)? source;- [DirectGetter] readonly attribute IDBTransaction? transaction;+ readonly attribute IDBTransaction? transaction;readonly attribute IDBRequestReadyState readyState;// Event handlers:diff --git a/Libraries/LibWeb/IndexedDB/IDBTransaction.cpp b/Libraries/LibWeb/IndexedDB/IDBTransaction.cppdeleted file mode 100644index 18262320eba..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBTransaction.cpp+++ /dev/null@@ -1,264 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Crypto/Crypto.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/IndexedDB/IDBDatabase.h>-#include <LibWeb/IndexedDB/IDBIndex.h>-#include <LibWeb/IndexedDB/IDBObjectStore.h>-#include <LibWeb/IndexedDB/IDBTransaction.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/Page/Page.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBTransaction);--IDBTransaction::~IDBTransaction() = default;--IDBTransaction::IDBTransaction(GC::Ref<IDBDatabase> connection, TransactionMode mode, TransactionDurability durability, Vector<GC::Ref<ObjectStore>>&& scopes)- : EventTarget()- , m_connection(connection)- , m_mode(mode)- , m_durability(durability)- , m_scope(move(scopes))- , m_uuid(Crypto::generate_random_uuid())-{- connection->add_transaction(*this);-}--GC::Ref<IDBTransaction> IDBTransaction::create(GC::Ref<IDBDatabase> connection, TransactionMode mode, TransactionDurability durability, GC::RootVector<GC::Ref<ObjectStore>> scopes)-{- return GC::Heap::the().allocate<IDBTransaction>(connection, mode, durability, move(scopes));-}--void IDBTransaction::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_connection);- visitor.visit(m_error);- visitor.visit(m_associated_request);- visitor.visit(m_scope);- visitor.visit(m_cleanup_event_loop);-- for (auto& [store, handle] : m_object_store_handles)- visitor.visit(handle);- visitor.visit(m_index_handles);-- for (auto& entry : m_store_mutation_logs) {- visitor.visit(entry.store);- visitor.visit(entry.log);- }-}--JS::Object& IDBTransaction::relevant_global_object() const-{- return m_connection->relevant_global_object();-}--HTML::WindowOrWorkerGlobalScopeMixin& IDBTransaction::relevant_global_scope() const-{- return m_connection->relevant_global_scope();-}--DOM::EventTarget* IDBTransaction::get_parent(DOM::Event const&)-{- // https://w3c.github.io/IndexedDB/#transaction-construct- // A transaction’s get the parent algorithm returns the transaction’s connection.- return m_connection.ptr();-}--void IDBTransaction::set_onabort(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::abort, event_handler);-}--WebIDL::CallbackType* IDBTransaction::onabort()-{- return event_handler_attribute(HTML::EventNames::abort);-}--void IDBTransaction::set_oncomplete(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::complete, event_handler);-}--WebIDL::CallbackType* IDBTransaction::oncomplete()-{- return event_handler_attribute(HTML::EventNames::complete);-}--void IDBTransaction::set_onerror(WebIDL::CallbackType* event_handler)-{- set_event_handler_attribute(HTML::EventNames::error, event_handler);-}--WebIDL::CallbackType* IDBTransaction::onerror()-{- return event_handler_attribute(HTML::EventNames::error);-}--// https://w3c.github.io/IndexedDB/#dom-idbtransaction-abort-WebIDL::ExceptionOr<void> IDBTransaction::abort()-{- // 1. If this's state is committing or finished, then throw an "InvalidStateError" DOMException.- if (m_state == TransactionState::Committing || m_state == TransactionState::Finished)- return WebIDL::InvalidStateError::create("Transaction is ending"_utf16);-- // 2. Run abort a transaction with this and null.- abort_a_transaction(*this, nullptr);- return {};-}--// https://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstorenames-GC::Ref<HTML::DOMStringList> IDBTransaction::object_store_names()-{- // 1. Let names be a list of the names of the object stores in this's scope.- Vector<Utf16String> names;- for (auto const& object_store : this->scope())- names.append(object_store->name());-- // 2. Return the result (a DOMStringList) of creating a sorted name list with names.- return create_a_sorted_name_list(names);-}--// https://w3c.github.io/IndexedDB/#dom-idbtransaction-commit-WebIDL::ExceptionOr<void> IDBTransaction::commit()-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. If this's state is not active, then throw an "InvalidStateError" DOMException.- if (m_state != TransactionState::Active)- return WebIDL::InvalidStateError::create("Transaction is not active while committing"_utf16);-- // 2. Run commit a transaction with this.- commit_a_transaction(realm, *this);-- return {};-}--GC::Ptr<ObjectStore> IDBTransaction::object_store_named(Utf16String const& name) const-{- for (auto const& store : m_scope) {- if (store->name() == name)- return store;- }-- return nullptr;-}--// https://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore-WebIDL::ExceptionOr<GC::Ref<IDBObjectStore>> IDBTransaction::object_store(Utf16String const& name)-{- // 1. If this's state is finished, then throw an "InvalidStateError" DOMException.- if (m_state == TransactionState::Finished)- return WebIDL::InvalidStateError::create("Transaction is finished"_utf16);-- // 2. Let store be the object store named name in this's scope, or throw a "NotFoundError" DOMException if none.- auto store = object_store_named(name);- if (!store)- return WebIDL::NotFoundError::create("Object store not found in transactions scope"_utf16);-- // 3. Return an object store handle associated with store and this.-- // https://w3c.github.io/IndexedDB/#object-store-handle-construct- // Multiple handles may be associated with the same object store in different transactions,- // but there must be only one object store handle associated with a particular object store- // within a transaction.- return get_or_create_object_store_handle(*store);-}--GC::Ref<IDBObjectStore> IDBTransaction::get_or_create_object_store_handle(GC::Ref<ObjectStore> store)-{- // NOTE: We have to do two lookups here. If we use ensure() with a constructor callback, the garbage collector- // may run when we construct the handle, and then we visit the HashMap in an invalid state.- if (auto handle = m_object_store_handles.get(store); handle.has_value())- return handle.value();-- auto handle = IDBObjectStore::create(store, *this);- m_object_store_handles.set(store, handle);- return handle;-}--GC::Ptr<IDBObjectStore> IDBTransaction::object_store_handle_for(GC::Ref<ObjectStore> store)-{- auto maybe_handle = m_object_store_handles.find(store);- if (maybe_handle == m_object_store_handles.end())- return nullptr;- return maybe_handle->value;-}--void IDBTransaction::set_state(TransactionState state)-{- m_state = state;-}--void IDBTransaction::register_index_handle(Badge<IDBIndex>, GC::Ref<IDBIndex> handle)-{- m_index_handles.append(handle);-}--void IDBTransaction::set_up_mutation_logs()-{- m_original_version = m_connection->associated_database()->version();-- for (auto& store : m_scope) {- auto log = MutationLog::create();- store->set_mutation_log(log);- m_store_mutation_logs.append({ store, log });- }-}--void IDBTransaction::set_up_mutation_log_for_new_store(GC::Ref<ObjectStore> store)-{- auto log = MutationLog::create();- store->set_mutation_log(log);- m_store_mutation_logs.append({ store, log });- log->note_object_store_created();-}--void IDBTransaction::revert_all_mutations()-{- auto database = m_connection->associated_database();- for (size_t i = m_store_mutation_logs.size(); i > 0; --i) {- auto& entry = m_store_mutation_logs[i - 1];- entry.log->revert(*entry.store, database, m_connection);- }-- database->set_version(m_original_version);- m_connection->set_version(m_original_version);-}--void IDBTransaction::discard_mutation_logs()-{- for (auto& entry : m_store_mutation_logs)- entry.store->set_mutation_log(nullptr);- m_store_mutation_logs.clear();-}--void IDBTransaction::notify_devtools_of_committed_changes()-{- auto document = HTML::relevant_settings_object(relevant_global_object()).responsible_document();- if (!document)- return;-- if (!document->page().client().has_active_devtools_client())- return;-- TransactionChanges changes;- auto database_name = m_connection->associated_database()->name();- for (auto const& entry : m_store_mutation_logs)- entry.log->append_changes(database_name, entry.store->name(), changes);- if (changes.is_empty())- return;-- document->page().client().page_did_update_indexed_database(document->url().serialize(), changes);-}--}diff --git a/Libraries/LibWeb/IndexedDB/IDBTransaction.h b/Libraries/LibWeb/IndexedDB/IDBTransaction.hdeleted file mode 100644index 31363668ab1..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBTransaction.h+++ /dev/null@@ -1,174 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Badge.h>-#include <AK/HashMap.h>-#include <AK/Types.h>-#include <AK/Vector.h>-#include <LibGC/Ptr.h>-#include <LibGC/RootVector.h>-#include <LibWeb/Bindings/IDBDatabase.h>-#include <LibWeb/Bindings/IDBTransaction.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/IndexedDB/Internal/MutationLog.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>-#include <LibWeb/IndexedDB/Internal/RequestList.h>--namespace Web::IndexedDB {--class IDBDatabase;-class IDBIndex;-class IDBObjectStore;-class IDBRequest;--using TransactionMode = Bindings::IDBTransactionMode;-using TransactionDurability = Bindings::IDBTransactionDurability;--// https://w3c.github.io/IndexedDB/#transaction-class IDBTransaction : public DOM::EventTarget {- WEB_WRAPPABLE(IDBTransaction, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(IDBTransaction);-- enum TransactionState {- Active,- Inactive,- Committing,- Finished- };--public:- static constexpr size_t connection_offset() { return offsetof(IDBTransaction, m_connection); }- virtual ~IDBTransaction() override;-- [[nodiscard]] static GC::Ref<IDBTransaction> create(GC::Ref<IDBDatabase>, TransactionMode, TransactionDurability, GC::RootVector<GC::Ref<ObjectStore>>);- [[nodiscard]] TransactionMode mode() const { return m_mode; }- [[nodiscard]] TransactionState state() const { return m_state; }- [[nodiscard]] GC::Ptr<WebIDL::DOMException> error() const { return m_error; }- static constexpr size_t error_offset() { return offsetof(IDBTransaction, m_error); }- [[nodiscard]] GC::Ref<IDBDatabase> connection() const { return m_connection; }- [[nodiscard]] TransactionDurability durability() const { return m_durability; }- [[nodiscard]] GC::Ptr<IDBRequest> associated_request() const { return m_associated_request; }- [[nodiscard]] bool aborted() const { return m_aborted; }- [[nodiscard]] HTML::WindowOrWorkerGlobalScopeMixin& relevant_global_scope() const;- [[nodiscard]] JS::Object& relevant_global_object() const;- [[nodiscard]] GC::Ref<HTML::DOMStringList> object_store_names();- [[nodiscard]] RequestList& request_list() { return m_request_list; }- [[nodiscard]] ReadonlySpan<GC::Ref<ObjectStore>> scope() const { return m_scope; }- [[nodiscard]] String uuid() const { return m_uuid; }- [[nodiscard]] GC::Ptr<HTML::EventLoop> cleanup_event_loop() const { return m_cleanup_event_loop; }-- void set_mode(TransactionMode mode) { m_mode = mode; }- void set_error(GC::Ptr<WebIDL::DOMException> error) { m_error = error; }- void set_associated_request(GC::Ptr<IDBRequest> request) { m_associated_request = request; }- void set_aborted(bool aborted) { m_aborted = aborted; }- void set_cleanup_event_loop(GC::Ptr<HTML::EventLoop> event_loop) { m_cleanup_event_loop = event_loop; }- void set_state(TransactionState state);-- [[nodiscard]] bool is_upgrade_transaction() const { return m_mode == TransactionMode::Versionchange; }- [[nodiscard]] bool is_readonly() const { return m_mode == TransactionMode::Readonly; }- [[nodiscard]] bool is_readwrite() const { return m_mode == TransactionMode::Readwrite; }- [[nodiscard]] bool is_finished() const { return m_state == TransactionState::Finished; }- [[nodiscard]] bool is_active() const { return m_state == TransactionState::Active; }- [[nodiscard]] bool is_inactive() const { return m_state == TransactionState::Inactive; }- [[nodiscard]] bool is_committing() const { return m_state == TransactionState::Committing; }-- GC::Ptr<ObjectStore> object_store_named(Utf16String const& name) const;- void add_to_scope(GC::Ref<ObjectStore> object_store) { m_scope.append(object_store); }- void remove_from_scope(GC::Ref<ObjectStore> object_store)- {- m_scope.remove_first_matching([&](auto& other) { return object_store == other; });- }- void set_scope(Vector<GC::Ref<ObjectStore>>&& scope) { m_scope = move(scope); }-- GC::Ref<IDBObjectStore> get_or_create_object_store_handle(GC::Ref<ObjectStore>);- GC::Ptr<IDBObjectStore> object_store_handle_for(GC::Ref<ObjectStore>);- void for_each_object_store_handle(CallableAs<IterationDecision, GC::Ref<IDBObjectStore>> auto callback)- {- for (auto const& [object_store, handle] : m_object_store_handles) {- if (callback(handle) == IterationDecision::Break)- break;- }- }-- void register_index_handle(Badge<IDBIndex>, GC::Ref<IDBIndex>);- ReadonlySpan<GC::Ref<IDBIndex>> index_handles() const { return m_index_handles; }-- // Mutation log management. Logs are per-store and track both data and schema mutations.- void set_up_mutation_logs();- u64 original_version() const { return m_original_version; }- void set_up_mutation_log_for_new_store(GC::Ref<ObjectStore>);- void revert_all_mutations();- void discard_mutation_logs();-- WebIDL::ExceptionOr<void> abort();- WebIDL::ExceptionOr<void> commit();- WebIDL::ExceptionOr<GC::Ref<IDBObjectStore>> object_store(Utf16String const& name);-- void set_onabort(WebIDL::CallbackType*);- WebIDL::CallbackType* onabort();- void set_oncomplete(WebIDL::CallbackType*);- WebIDL::CallbackType* oncomplete();- void set_onerror(WebIDL::CallbackType*);- WebIDL::CallbackType* onerror();-- void notify_devtools_of_committed_changes();--protected:- IDBTransaction(GC::Ref<IDBDatabase>, TransactionMode, TransactionDurability, Vector<GC::Ref<ObjectStore>>&&);- virtual void visit_edges(Visitor& visitor) override;- virtual EventTarget* get_parent(DOM::Event const&) override;--private:- // AD-HOC: The transaction has a connection- GC::Ref<IDBDatabase> m_connection;-- // A transaction has a mode that determines which types of interactions can be performed upon that transaction.- TransactionMode m_mode;-- // A transaction has a durability hint. This is a hint to the user agent of whether to prioritize performance or durability when committing the transaction.- TransactionDurability m_durability { TransactionDurability::Default };-- // A transaction has a state- TransactionState m_state { TransactionState::Active };-- // A transaction has a error which is set if the transaction is aborted.- GC::Ptr<WebIDL::DOMException> m_error;-- // A transaction has an associated upgrade request- GC::Ptr<IDBRequest> m_associated_request;-- // AD-HOC: We need to track abort state separately, since we cannot rely on only the error.- bool m_aborted { false };-- // A transaction has a scope which is a set of object stores that the transaction may interact with.- Vector<GC::Ref<ObjectStore>> m_scope;-- // A transaction has a request list of pending requests which have been made against the transaction.- RequestList m_request_list;-- // A transaction optionally has a cleanup event loop which is an event loop.- GC::Ptr<HTML::EventLoop> m_cleanup_event_loop;-- HashMap<GC::RawPtr<ObjectStore>, GC::Ref<IDBObjectStore>> m_object_store_handles;- Vector<GC::Ref<IDBIndex>> m_index_handles;-- // AD-HOC: Per-store mutation logs for data and schema change reversion.- struct StoreMutationLog {- GC::Ref<ObjectStore> store;- GC::Ref<MutationLog> log;- };- Vector<StoreMutationLog> m_store_mutation_logs;- u64 m_original_version { 0 };-- // NOTE: Used for debug purposes- String m_uuid;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBTransaction.idl b/Libraries/LibWeb/IndexedDB/IDBTransaction.idlindex 95b2c73f2ad..ed1f6e3656a 100644--- a/Libraries/LibWeb/IndexedDB/IDBTransaction.idl+++ b/Libraries/LibWeb/IndexedDB/IDBTransaction.idl@@ -1,10 +1,10 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBTransaction : EventTarget {readonly attribute DOMStringList objectStoreNames;readonly attribute IDBTransactionMode mode;readonly attribute IDBTransactionDurability durability;- [DirectGetter=connection, SameObject, ImplementedAs=connection] readonly attribute IDBDatabase db;- [DirectGetter] readonly attribute DOMException? error;+ [SameObject, ImplementedAs=connection] readonly attribute IDBDatabase db;+ readonly attribute DOMException? error;IDBObjectStore objectStore(DOMString name);undefined commit();undefined abort();diff --git a/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.cpp b/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.cppdeleted file mode 100644index 4c3202a111f..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.cpp+++ /dev/null@@ -1,40 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Bindings/IDBVersionChangeEvent.h>-#include <LibWeb/IndexedDB/IDBVersionChangeEvent.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(IDBVersionChangeEvent);--GC::Ref<IDBVersionChangeEvent> IDBVersionChangeEvent::create(Utf16FlyString const& event_name, IDBVersionChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<IDBVersionChangeEvent>(event_name, event_init, time_stamp);-}--GC::Ref<IDBVersionChangeEvent> IDBVersionChangeEvent::create(Utf16FlyString const& event_name, Bindings::IDBVersionChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- IDBVersionChangeEventInit init;- init.bubbles = event_init.bubbles;- init.cancelable = event_init.cancelable;- init.composed = event_init.composed;- init.old_version = event_init.old_version;- init.new_version = event_init.new_version;- return create(event_name, init, time_stamp);-}--IDBVersionChangeEvent::IDBVersionChangeEvent(Utf16FlyString const& event_name, IDBVersionChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, event_init, time_stamp)- , m_old_version(event_init.old_version)- , m_new_version(event_init.new_version)-{-}--IDBVersionChangeEvent::~IDBVersionChangeEvent() = default;--}diff --git a/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.h b/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.hdeleted file mode 100644index 5f011709ce0..00000000000--- a/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.h+++ /dev/null@@ -1,50 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <LibGC/Ptr.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/Forward.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>--namespace Web::Bindings {--struct IDBVersionChangeEventInit;--}--namespace Web::IndexedDB {--struct IDBVersionChangeEventInit : public DOM::EventInit {- u64 old_version { 0 };- Optional<u64> new_version;-};--// https://w3c.github.io/IndexedDB/#events-class IDBVersionChangeEvent : public DOM::Event {- WEB_WRAPPABLE(IDBVersionChangeEvent, DOM::Event);- GC_DECLARE_ALLOCATOR(IDBVersionChangeEvent);--public:- virtual ~IDBVersionChangeEvent() override;-- static GC::Ref<IDBVersionChangeEvent> create(Utf16FlyString const&, IDBVersionChangeEventInit const&, HighResolutionTime::DOMHighResTimeStamp);- static GC::Ref<IDBVersionChangeEvent> create(Utf16FlyString const&, Bindings::IDBVersionChangeEventInit const&, HighResolutionTime::DOMHighResTimeStamp);-- u64 old_version() const { return m_old_version; }- Optional<u64> new_version() const { return m_new_version; }--protected:- explicit IDBVersionChangeEvent(Utf16FlyString const& event_name, IDBVersionChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);--private:- u64 m_old_version { 0 };- Optional<u64> m_new_version;-};--}diff --git a/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.idl b/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.idlindex e4e22662e86..c80dda93216 100644--- a/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.idl+++ b/Libraries/LibWeb/IndexedDB/IDBVersionChangeEvent.idl@@ -1,4 +1,4 @@-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface IDBVersionChangeEvent : Event {constructor(DOMString type, optional IDBVersionChangeEventInit eventInitDict = {});readonly attribute unsigned long long oldVersion;diff --git a/Libraries/LibWeb/IndexedDB/Inspection.cpp b/Libraries/LibWeb/IndexedDB/Inspection.cppindex 84124db9617..f1c6ed6a250 100644--- a/Libraries/LibWeb/IndexedDB/Inspection.cpp+++ b/Libraries/LibWeb/IndexedDB/Inspection.cpp@@ -5,22 +5,44 @@*/#include <AK/JsonArray.h>+#include <LibJS/HostClassBuilder.h>+#include <LibURL/RustIntegration.h>+#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/NavigableContainer.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/IndexedDB/IDBKeyRange.h>#include <LibWeb/IndexedDB/Inspection.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/Database.h>-#include <LibWeb/IndexedDB/Internal/Index.h>-#include <LibWeb/IndexedDB/Internal/Key.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>#include <LibWeb/Infra/JSON.h>#include <LibWeb/StorageAPI/StorageKey.h>+// The inspection entry points of the Rust implementation of IndexedDB, Libraries/LibWeb/Bindings/Rust/src/indexed_db/exports.rs.+extern "C" {++struct KeyPathAbi {+ u8 kind;+ FlatPtr const* strings;+ size_t count;+};++enum class InspectionStatus : u8 {+ Done = 0,+ NoDatabase = 1,+ NoObjectStore = 2,+ NoRecord = 3,+ Blocked = 4,+};++void web_rust_indexed_db_inspect_databases(JSVM*, URL::FFI::FfiOrigin const*, void* ctx, void (*on_database)(void*, FlatPtr name, u64 version, FlatPtr const* object_store_names, size_t count));+bool web_rust_indexed_db_inspect_object_stores(JSVM*, URL::FFI::FfiOrigin const*, FlatPtr database_name, void* ctx, void (*on_object_store)(void*, FlatPtr name, KeyPathAbi const*, bool auto_increment), void (*on_index)(void*, FlatPtr name, KeyPathAbi const*, bool unique, bool multi_entry));+void web_rust_indexed_db_inspect_records(JSVM*, URL::FFI::FfiOrigin const*, FlatPtr database_name, FlatPtr object_store_name, void* ctx, void (*on_record)(void*, JsonValue* key, ReadonlyBytes value));+InspectionStatus web_rust_indexed_db_delete_database_for_inspection(JSVM*, URL::FFI::FfiOrigin const*, FlatPtr database_name);+InspectionStatus web_rust_indexed_db_clear_object_store_for_inspection(JSVM*, URL::FFI::FfiOrigin const*, FlatPtr database_name, FlatPtr object_store_name);+InspectionStatus web_rust_indexed_db_delete_record_for_inspection(JSVM*, URL::FFI::FfiOrigin const*, FlatPtr database_name, FlatPtr object_store_name, void* ctx, bool (*matches)(void*, JsonValue* key));+}+namespace Web::IndexedDB {struct IndexedDatabaseDocument {@@ -29,47 +51,27 @@ struct IndexedDatabaseDocument {StorageAPI::StorageKey storage_key;};-JsonValue serialize_key_for_inspection(Key& key)+static JSVM* vm(){- switch (key.type()) {- case Key::Invalid:- return {};- case Key::Number:- case Key::Date:- return key.value_as_double();- case Key::String:- return key.value_as_string().to_utf8();- case Key::Binary:- return key.dump();- case Key::Array: {- JsonArray keys;- for (auto const& subkey : key.subkeys())- keys.must_append(serialize_key_for_inspection(*subkey));- return keys;- }- }-- VERIFY_NOT_REACHED();+ return JS::HostABI::vm_to_abi(Bindings::main_thread_vm());}-static String serialize_key_path(KeyPath const& key_path)+static String serialize_key_path(KeyPathAbi const& key_path){- return key_path.visit(- [](Utf16String const& value) {- return value.to_utf8();- },- [](Vector<Utf16String> const& values) {- JsonArray array;- for (auto const& value : values)- array.must_append(value.to_utf8());- return array.serialized();- });+ if (key_path.kind == 1)+ return Utf16String::from_raw(key_path.strings[0]).to_utf8();++ JsonArray array;+ for (size_t i = 0; i < key_path.count; ++i)+ array.must_append(Utf16String::from_raw(key_path.strings[i]).to_utf8());+ return array.serialized();}-static String serialize_record_value(JS::Realm& realm, HTML::StorageSerializationRecord const& record)+static String serialize_record_value(JS::Realm& realm, ReadonlyBytes bytes){HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);+ HTML::StorageSerializationRecord record { MUST(ByteBuffer::copy(bytes)) };auto value = HTML::structured_deserialize(realm.vm(), record, realm);if (value.is_exception())return "<unserializable>"_string;@@ -126,81 +128,106 @@ static Optional<IndexedDatabaseDocument> matching_document(DOM::Document& documereturn {};}+template<typename Callback>+static auto with_origin(StorageAPI::StorageKey const& storage_key, Callback callback)+{+ using Result = decltype(callback(declval<URL::FFI::FfiOrigin const*>()));+ if constexpr (IsSame<Result, void>) {+ URL::RustIntegration::lend_origin_to_ffi(storage_key.origin, [&](URL::FFI::FfiOrigin const& origin) { callback(&origin); });+ } else {+ Optional<Result> result;+ URL::RustIntegration::lend_origin_to_ffi(storage_key.origin, [&](URL::FFI::FfiOrigin const& origin) { result = callback(&origin); });+ return result.release_value();+ }+}++struct DatabaseVisitor {+ Function<void(String, u64, Vector<String>)> on_database;+};++static void for_each_database(StorageAPI::StorageKey const& storage_key, Function<void(String, u64, Vector<String>)> on_database)+{+ DatabaseVisitor visitor { move(on_database) };+ with_origin(storage_key, [&](URL::FFI::FfiOrigin const* origin) {+ web_rust_indexed_db_inspect_databases(vm(), origin, &visitor, [](void* ctx, FlatPtr name, u64 version, FlatPtr const* object_store_names, size_t count) {+ Vector<String> names;+ for (size_t i = 0; i < count; ++i)+ names.append(Utf16String::from_raw(object_store_names[i]).to_utf8());+ static_cast<DatabaseVisitor*>(ctx)->on_database(Utf16String::from_raw(name).to_utf8(), version, move(names));+ });+ });+}+Vector<InspectionStorageHost> inspect_indexed_database_storage(DOM::Document& document){Vector<InspectionStorageHost> hosts;for (auto const& entry : indexed_database_documents_for_inspection(document)) {Vector<InspectionDatabase> databases;- for (auto& database : Database::for_key(entry.storage_key)) {- if (!database || database->version() == 0)- continue;-- Vector<String> object_store_names;- for (auto const& object_store : database->object_stores())- object_store_names.append(object_store->name().to_utf8());+ for_each_database(entry.storage_key, [&](String name, u64 version, Vector<String> object_store_names) {+ if (version == 0)+ return;- databases.append({ database->name().to_utf8(), database->version(), move(object_store_names) });- }+ databases.append({ move(name), version, move(object_store_names) });+ });hosts.append({ entry.url, move(databases) });}return hosts;}-static InspectionObjectStore inspect_object_store(ObjectStore& object_store)-{- Vector<InspectionIndex> indexes;- for (auto const& entry : object_store.index_set()) {- auto const& index = *entry.value;- indexes.append({ index.name().to_utf8(), serialize_key_path(index.key_path()), index.unique(), index.multi_entry() });- }-- Optional<String> key_path;- if (auto value = object_store.key_path(); value.has_value())- key_path = serialize_key_path(*value);-- return { object_store.name().to_utf8(), move(key_path), object_store.uses_a_key_generator(), move(indexes) };-}-static void append_database_rows(Vector<InspectionObject>& rows, StorageAPI::StorageKey const& storage_key){- for (auto& database : Database::for_key(storage_key)) {- if (!database || database->version() == 0)- continue;+ for_each_database(storage_key, [&](String name, u64 version, Vector<String> object_store_names) {+ if (version == 0)+ return;- rows.append(InspectionDatabaseRow { database->name().to_utf8(), database->version(), database->object_stores().size() });- }+ rows.append(InspectionDatabaseRow { move(name), version, object_store_names.size() });+ });}static void append_object_store_rows(Vector<InspectionObject>& rows, StorageAPI::StorageKey const& storage_key, String const& database_name){- auto database = Database::for_key_and_name(storage_key, Utf16String::from_utf8(database_name));- if (!database.has_value())- return;-- for (auto const& object_store : database->object_stores())- rows.append(inspect_object_store(*object_store));+ auto name = Utf16String::from_utf8(database_name);+ with_origin(storage_key, [&](URL::FFI::FfiOrigin const* origin) {+ web_rust_indexed_db_inspect_object_stores(+ vm(), origin, name.raw_identity(), &rows,+ [](void* ctx, FlatPtr name, KeyPathAbi const* key_path, bool auto_increment) {+ Optional<String> serialized_key_path;+ if (key_path->kind != 0)+ serialized_key_path = serialize_key_path(*key_path);+ static_cast<Vector<InspectionObject>*>(ctx)->append(InspectionObjectStore { Utf16String::from_raw(name).to_utf8(), move(serialized_key_path), auto_increment, {} });+ },+ [](void* ctx, FlatPtr name, KeyPathAbi const* key_path, bool unique, bool multi_entry) {+ auto& object_store = static_cast<Vector<InspectionObject>*>(ctx)->last().get<InspectionObjectStore>();+ object_store.indexes.append({ Utf16String::from_raw(name).to_utf8(), serialize_key_path(*key_path), unique, multi_entry });+ });+ });}+struct RecordVisitor {+ Vector<InspectionObject>& rows;+ GC::Ref<JS::Realm> realm;+ InspectionPath const& path;+};+static void append_record_rows(Vector<InspectionObject>& rows, DOM::Document& document, StorageAPI::StorageKey const& storage_key, InspectionPath const& path){if (!path.object_store_name.has_value())return;- auto database = Database::for_key_and_name(storage_key, Utf16String::from_utf8(path.database_name));- if (!database.has_value())- return;-- auto object_store = database->object_store_with_name(Utf16String::from_utf8(*path.object_store_name));- if (!object_store)- return;-- for (auto const& record : object_store->records()) {- auto serialized_record_key = serialize_key_for_inspection(*record.key);- if (path.key.has_value() && serialized_record_key.serialized() != path.key->serialized())- continue;- rows.append(InspectionRecord { serialized_record_key, serialize_record_value(HTML::relevant_realm(document), *record.value) });- }+ auto database_name = Utf16String::from_utf8(path.database_name);+ auto object_store_name = Utf16String::from_utf8(*path.object_store_name);+ RecordVisitor visitor { rows, HTML::relevant_realm(document), path };+ with_origin(storage_key, [&](URL::FFI::FfiOrigin const* origin) {+ web_rust_indexed_db_inspect_records(vm(), origin, database_name.raw_identity(), object_store_name.raw_identity(), &visitor, [](void* ctx, JsonValue* key, ReadonlyBytes value) {+ auto& visitor = *static_cast<RecordVisitor*>(ctx);+ auto serialized_record_key = move(*key);+ delete key;+ if (visitor.path.key.has_value() && serialized_record_key.serialized() != visitor.path.key->serialized())+ return;+ visitor.rows.append(InspectionRecord { move(serialized_record_key), serialize_record_value(visitor.realm, value) });+ });+ });}Vector<InspectionObject> inspect_indexed_database_objects(DOM::Document& document, Function<bool(URL::URL const&)> const& document_matches, Optional<Vector<InspectionPath>> const& paths)@@ -232,12 +259,28 @@ ErrorOr<bool> delete_indexed_database_for_inspection(DOM::Document& document, Fuif (!entry.has_value())return Error::from_string_literal("Unable to find IndexedDB host");- auto database = Database::for_key_and_name(entry->storage_key, Utf16String::from_utf8(database_name));- if (database.has_value() && !database->associated_connections_as_root_vector().is_empty())- return true;+ auto name = Utf16String::from_utf8(database_name);+ auto status = with_origin(entry->storage_key, [&](URL::FFI::FfiOrigin const* origin) {+ return web_rust_indexed_db_delete_database_for_inspection(vm(), origin, name.raw_identity());+ });+ return status == InspectionStatus::Blocked;+}- TRY(Database::delete_for_key_and_name(entry->storage_key, Utf16String::from_utf8(database_name)));- return false;+static ErrorOr<void> error_for_status(InspectionStatus status)+{+ switch (status) {+ case InspectionStatus::Done:+ return {};+ case InspectionStatus::NoDatabase:+ return Error::from_string_literal("Unable to find IndexedDB database");+ case InspectionStatus::NoObjectStore:+ return Error::from_string_literal("Unable to find IndexedDB object store");+ case InspectionStatus::NoRecord:+ return Error::from_string_literal("Unable to find IndexedDB record");+ case InspectionStatus::Blocked:+ break;+ }+ VERIFY_NOT_REACHED();}ErrorOr<void> clear_indexed_database_object_store_for_inspection(DOM::Document& document, Function<bool(URL::URL const&)> const& document_matches, String const& database_name, String const& object_store_name)@@ -246,16 +289,12 @@ ErrorOr<void> clear_indexed_database_object_store_for_inspection(DOM::Document&if (!entry.has_value())return Error::from_string_literal("Unable to find IndexedDB host");- auto database = Database::for_key_and_name(entry->storage_key, Utf16String::from_utf8(database_name));- if (!database.has_value())- return Error::from_string_literal("Unable to find IndexedDB database");-- auto object_store = database->object_store_with_name(Utf16String::from_utf8(object_store_name));- if (!object_store)- return Error::from_string_literal("Unable to find IndexedDB object store");-- clear_an_object_store(*object_store);- return {};+ auto database = Utf16String::from_utf8(database_name);+ auto object_store = Utf16String::from_utf8(object_store_name);+ auto status = with_origin(entry->storage_key, [&](URL::FFI::FfiOrigin const* origin) {+ return web_rust_indexed_db_clear_object_store_for_inspection(vm(), origin, database.raw_identity(), object_store.raw_identity());+ });+ return error_for_status(status);}ErrorOr<void> delete_indexed_database_record_for_inspection(DOM::Document& document, Function<bool(URL::URL const&)> const& document_matches, String const& database_name, String const& object_store_name, JsonValue const& key)@@ -264,24 +303,17 @@ ErrorOr<void> delete_indexed_database_record_for_inspection(DOM::Document& documif (!entry.has_value())return Error::from_string_literal("Unable to find IndexedDB host");- auto database = Database::for_key_and_name(entry->storage_key, Utf16String::from_utf8(database_name));- if (!database.has_value())- return Error::from_string_literal("Unable to find IndexedDB database");-- auto object_store = database->object_store_with_name(Utf16String::from_utf8(object_store_name));- if (!object_store)- return Error::from_string_literal("Unable to find IndexedDB object store");-- for (auto const& record : object_store->records()) {- if (serialize_key_for_inspection(*record.key).serialized() != key.serialized())- continue;-- auto range = IDBKeyRange::create(record.key, record.key, IDBKeyRange::LowerOpen::No, IDBKeyRange::UpperOpen::No);- delete_records_from_an_object_store(*object_store, range);- return {};- }-- return Error::from_string_literal("Unable to find IndexedDB record");+ auto database = Utf16String::from_utf8(database_name);+ auto object_store = Utf16String::from_utf8(object_store_name);+ auto serialized_key = key.serialized();+ auto status = with_origin(entry->storage_key, [&](URL::FFI::FfiOrigin const* origin) {+ return web_rust_indexed_db_delete_record_for_inspection(vm(), origin, database.raw_identity(), object_store.raw_identity(), &serialized_key, [](void* ctx, JsonValue* record_key) {+ auto serialized_record_key = move(*record_key);+ delete record_key;+ return serialized_record_key.serialized() == *static_cast<String*>(ctx);+ });+ });+ return error_for_status(status);}}diff --git a/Libraries/LibWeb/IndexedDB/Inspection.h b/Libraries/LibWeb/IndexedDB/Inspection.hindex 157d0500760..371652029f9 100644--- a/Libraries/LibWeb/IndexedDB/Inspection.h+++ b/Libraries/LibWeb/IndexedDB/Inspection.h@@ -62,7 +62,6 @@ struct InspectionPath {Optional<JsonValue> key;};-WEB_API JsonValue serialize_key_for_inspection(Key&);WEB_API Vector<InspectionStorageHost> inspect_indexed_database_storage(DOM::Document&);WEB_API Vector<InspectionObject> inspect_indexed_database_objects(DOM::Document&, Function<bool(URL::URL const&)> const& document_matches, Optional<Vector<InspectionPath>> const& paths);WEB_API ErrorOr<bool> delete_indexed_database_for_inspection(DOM::Document&, Function<bool(URL::URL const&)> const& document_matches, String const& database_name);diff --git a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cppdeleted file mode 100644index a5a05e40ff2..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp+++ /dev/null@@ -1,2728 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/AnyOf.h>-#include <AK/Math.h>-#include <AK/NumericLimits.h>-#include <AK/QuickSort.h>-#include <LibGC/Heap.h>-#include <LibGC/HeapVector.h>-#include <LibJS/Runtime/AbstractOperations.h>-#include <LibJS/Runtime/Array.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/Completion.h>-#include <LibJS/Runtime/DataView.h>-#include <LibJS/Runtime/Date.h>-#include <LibJS/Runtime/Object.h>-#include <LibJS/Runtime/PrimitiveString.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibJS/Runtime/VM.h>-#include <LibUnicode/CharacterTypes.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/DOM/EventDispatcher.h>-#include <LibWeb/FileAPI/Blob.h>-#include <LibWeb/FileAPI/File.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/IndexedDB/BindingsGlue.h>-#include <LibWeb/IndexedDB/IDBCursor.h>-#include <LibWeb/IndexedDB/IDBDatabase.h>-#include <LibWeb/IndexedDB/IDBIndex.h>-#include <LibWeb/IndexedDB/IDBKeyRange.h>-#include <LibWeb/IndexedDB/IDBObjectStore.h>-#include <LibWeb/IndexedDB/IDBRecord.h>-#include <LibWeb/IndexedDB/IDBRequest.h>-#include <LibWeb/IndexedDB/IDBTransaction.h>-#include <LibWeb/IndexedDB/IDBVersionChangeEvent.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/ConnectionQueueHandler.h>-#include <LibWeb/IndexedDB/Internal/Database.h>-#include <LibWeb/IndexedDB/Internal/Index.h>-#include <LibWeb/IndexedDB/Internal/Key.h>-#include <LibWeb/StorageAPI/StorageKey.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWebCommon/Infra/Strings.h>--namespace Web::IndexedDB {--static auto current_high_resolution_time(HTML::WindowOrWorkerGlobalScopeMixin& global_scope)-{- return HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(global_scope));-}--struct TaskCounterState final : public GC::Cell {- GC_CELL(TaskCounterState, GC::Cell);- GC_DECLARE_ALLOCATOR(TaskCounterState);-- virtual void visit_edges(Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(after_all);- }-- void decrement_remaining_tasks()- {- VERIFY(remaining_tasks > 0);- --remaining_tasks;- if (remaining_tasks > 0)- return;-- queue_a_database_task(after_all.as_nonnull());- }-- size_t remaining_tasks { 0 };- GC::Ptr<GC::Function<void()>> after_all;-};--GC_DEFINE_ALLOCATOR(TaskCounterState);--static Vector<Utf16String> strictly_split_key_path(Utf16String const& key_path)-{- Vector<Utf16String> identifiers;- key_path.for_each_split_view(u'.', SplitBehavior::KeepEmpty, [&](Utf16View const& identifier) {- identifiers.append(Utf16String::from_utf16(identifier));- return IterationDecision::Continue;- });- return identifiers;-}--// https://w3c.github.io/IndexedDB/#open-a-database-connection-void open_a_database_connection(JS::Realm& realm, StorageAPI::StorageKey storage_key, Utf16String name, Optional<u64> maybe_version, GC::Ref<IDBRequest> request, GC::Ref<GC::Function<void(WebIDL::ExceptionOr<GC::Ref<IDBDatabase>>)>> on_complete)-{- // 1. Let queue be the connection queue for storageKey and name.- auto& queue = ConnectionQueueHandler::for_key_and_name(storage_key, name);-- dbgln_if(IDB_DEBUG, "open_a_database_connection: enqueuing request {}", request->uuid());-- // 2. Add request to queue.- // 3. Wait until all previous requests in queue have been processed.- queue.enqueue(request, GC::create_function(GC::Heap::the(), [&realm, &queue, storage_key = move(storage_key), name = move(name), maybe_version = move(maybe_version), request, on_complete] -> void {- static constexpr auto call_completion = [](auto& queue, auto completion, auto result) {- completion->function()(move(result));- queue.on_request_processed();- };-- // 4. Let db be the database named name in storageKey, or null otherwise.- GC::Ptr<Database> db;- auto maybe_db = Database::for_key_and_name(storage_key, name);- if (maybe_db.has_value()) {- db = &maybe_db.value();- }-- // 5. If version is undefined, let version be 1 if db is null, or db’s version otherwise.- auto version = maybe_version.value_or(maybe_db.has_value() ? maybe_db.value().version() : 1);-- // 6. If db is null, let db be a new database with name name, version 0 (zero), and with no object stores.- // If this fails for any reason, return an appropriate error (e.g. a QuotaExceededError, or an "UnknownError" DOMException).- if (!maybe_db.has_value()) {- auto maybe_database = Database::create_for_key_and_name(GC::Heap::the(), storage_key, name);-- if (maybe_database.is_error()) {- call_completion(queue, on_complete, WebIDL::OperationError::create("Unable to create a new database"_utf16));- return;- }-- db = maybe_database.release_value();- }-- // 7. If db’s version is greater than version, return a newly created "VersionError" DOMException and abort these steps.- if (db->version() > version) {- call_completion(queue, on_complete, WebIDL::VersionError::create("Database version is greater than the requested version"_utf16));- return;- }-- // 8. Let connection be a new connection to db.- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(realm.global_object());- VERIFY(global_scope);- auto connection = IDBDatabase::create(global_scope->this_impl(), *db);- dbgln_if(IDB_DEBUG, "Created new connection with UUID: {}", connection->uuid());-- // 9. Set connection’s version to version.- connection->set_version(version);-- // 10. If db’s version is less than version, then:- if (db->version() < version) {- dbgln_if(IDB_DEBUG, "open_a_database_connection: Upgrading database from version {} to {}", db->version(), version);-- // 1. Let openConnections be the set of all connections, except connection, associated with db.- auto open_connections = db->associated_connections_as_heap_vector_except(GC::Heap::the(), connection);-- // 2. For each entry of openConnections that does not have its close pending flag set to true,- // queue a database task to fire a version change event named versionchange at entry with db’s version and version.- GC::Ptr<TaskCounterState> task_counter_state;- for (auto const& entry : open_connections->elements()) {- if (!entry->close_pending()) {- if (!task_counter_state) {- task_counter_state = GC::Heap::the().allocate<TaskCounterState>();- }-- task_counter_state->remaining_tasks++;- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, entry, db, version, task_counter_state] {- fire_a_version_change_event(realm, HTML::EventNames::versionchange, *entry, db->version(), version);- task_counter_state->decrement_remaining_tasks();- }));- }- }-- // 3. Wait for all of the events to be fired.- if constexpr (IDB_DEBUG) {- dbgln("open_a_database_connection: waiting for step 10.3");- dbgln("remaining tasks: {}", task_counter_state ? task_counter_state->remaining_tasks : 0);- }-- auto after_all = GC::create_function(GC::Heap::the(), [&realm, &queue, open_connections, db, version, connection, request, on_complete] {- // 4. If any of the connections in openConnections are still not closed,- // queue a database task to fire a version change event named blocked at request with db’s version and version.- auto any_connection_is_not_closed = [&] {- for (auto const& entry : open_connections->elements()) {- if (entry->state() != ConnectionState::Closed)- return true;- }- return false;- }();- if (any_connection_is_not_closed) {- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, request, db, version]() {- fire_a_version_change_event(realm, HTML::EventNames::blocked, request, db->version(), version);- }));- }-- // 5. Wait until all connections in openConnections are closed.- if constexpr (IDB_DEBUG) {- dbgln("open_a_database_connection: waiting for step 10.5");- dbgln("open connections: {}", open_connections->elements().size());- for (auto const& open_connection : open_connections->elements()) {- dbgln(" - {}", open_connection->uuid());- }- }-- db->wait_for_connections_to_close(open_connections->elements(), GC::create_function(GC::Heap::the(), [&realm, &queue, connection, version, request, on_complete] {- dbgln_if(IDB_DEBUG, "open_a_database_connection: finished waiting for step 10.5");-- // 6. Run upgrade a database using connection, version and request.- dbgln_if(IDB_DEBUG, "open_a_database_connection: waiting for step 10.6");- upgrade_a_database(realm, connection, version, request, GC::create_function(GC::Heap::the(), [&queue, connection, request, on_complete] {- dbgln_if(IDB_DEBUG, "open_a_database_connection: finished waiting for step 10.6");-- // 7. If connection was closed, return a newly created "AbortError" DOMException and abort these steps.- if (connection->state() == ConnectionState::Closed) {- dbgln_if(IDB_DEBUG, "open_a_database_connection: step 10.7: connection was closed, aborting");- call_completion(queue, on_complete, (WebIDL::AbortError::create("Connection was closed"_utf16)));- return;- }-- // 8. If request's error is set, run the steps to close a database connection with connection,- // return a newly created "AbortError" DOMException and abort these steps.- if (request->has_error()) {- dbgln_if(IDB_DEBUG, "open_a_database_connection: step 10.8: request errored, waiting to close connection");- close_a_database_connection(*connection, GC::create_function(GC::Heap::the(), [&queue, on_complete] {- dbgln_if(IDB_DEBUG, "open_a_database_connection: step 10.8: connection closed, aborting");- call_completion(queue, on_complete, WebIDL::AbortError::create("Upgrade transaction was aborted"_utf16));- }));- return;- }-- // 11. Return connection.- dbgln_if(IDB_DEBUG, "open_a_database_connection: step 11: successfully upgraded database, completing with new connection");- call_completion(queue, on_complete, connection);- }));- }));- });-- if (task_counter_state) {- task_counter_state->after_all = after_all;- } else {- queue_a_database_task(after_all);- }-- // NOTE: Because of the async nature of this function, we return here and call the on_complete function- // with the connection when necessary.- return;- }-- // 11. Return connection.- dbgln_if(IDB_DEBUG, "open_a_database_connection: step 11: no upgrade required, completing with new connection");- call_completion(queue, on_complete, connection);- }));-}--bool fire_a_version_change_event(JS::Realm& realm, Utf16FlyString const& event_name, GC::Ref<DOM::EventTarget> target, u64 old_version, Optional<u64> new_version)-{- IDBVersionChangeEventInit event_init = {};- // 4. Set event’s oldVersion attribute to oldVersion.- event_init.old_version = old_version;- // 5. Set event’s newVersion attribute to newVersion.- event_init.new_version = new_version;-- // 1. Let event be the result of creating an event using IDBVersionChangeEvent.- // 2. Set event’s type attribute to e.- auto event = IDBVersionChangeEvent::create(event_name, event_init, HighResolutionTime::current_high_resolution_time(realm.global_object()));-- // 3. Set event’s bubbles and cancelable attributes to false.- event->set_bubbles(false);- event->set_cancelable(false);-- // 6. Let legacyOutputDidListenersThrowFlag be false.- auto legacy_output_did_listeners_throw_flag = false;-- // 7. Dispatch event at target with legacyOutputDidListenersThrowFlag.- DOM::EventDispatcher::dispatch(target, *event, false, legacy_output_did_listeners_throw_flag);-- // 8. Return legacyOutputDidListenersThrowFlag.- return legacy_output_did_listeners_throw_flag;-}--// https://w3c.github.io/IndexedDB/#convert-value-to-key-WebIDL::ExceptionOr<GC::Ref<Key>> convert_a_value_to_a_key(JS::Realm& realm, JS::Value input, GC::RootVector<JS::Value> seen)-{- // 1. If seen was not given, then let seen be a new empty set.- // NOTE: This is handled by the caller.-- // 2. If seen contains input, then return "invalid value".- if (seen.contains_slow(input))- return Key::create_invalid("Already seen key"_utf16);-- // 3. Jump to the appropriate step below:-- // - If Type(input) is Number- if (input.is_number()) {-- // 1. If input is NaN then return "invalid value".- if (input.is_nan())- return Key::create_invalid("NaN key"_utf16);-- // 2. Otherwise, return a new key with type number and value input.- return Key::create_number(input.as_double());- }-- // - If input is a Date (has a [[DateValue]] internal slot)- if (input.is_object() && is<JS::Date>(input.as_object())) {-- // 1. Let ms be the value of input’s [[DateValue]] internal slot.- auto& date = static_cast<JS::Date&>(input.as_object());- auto ms = date.date_value();-- // 2. If ms is NaN then return "invalid value".- if (isnan(ms))- return Key::create_invalid("NaN key"_utf16);-- // 3. Otherwise, return a new key with type date and value ms.- return Key::create_date(ms);- }-- // - If Type(input) is String- if (input.is_string()) {-- // 1. Return a new key with type string and value input.- return Key::create_string(input.as_string().utf16_string());- }-- // - If input is a buffer source type- if (input.is_object() && (is<JS::TypedArrayBase>(input.as_object()) || is<JS::ArrayBuffer>(input.as_object()) || is<JS::DataView>(input.as_object()))) {-- // 1. If input is detached then return "invalid value".- if (WebIDL::BufferSource::is_detached(input))- return Key::create_invalid("Detached buffer is not supported as key"_utf16);-- // 2. Let bytes be the result of getting a copy of the bytes held by the buffer source input.- auto data_buffer = MUST(WebIDL::get_buffer_source_copy(input.as_object()));-- // 3. Return a new key with type binary and value bytes.- return Key::create_binary(data_buffer);- }-- // - If input is an Array exotic object- if (input.is_object() && is<JS::Array>(input.as_object())) {-- // 1. Let len be ? ToLength( ? Get(input, "length")).- auto length = TRY(length_of_array_like(realm.vm(), input.as_object()));-- // 2. Append input to seen.- seen.append(input);-- // 3. Let keys be a new empty list.- auto keys = GC::Heap::the().allocate<GC::HeapVector<GC::Ref<Key>>>();-- // 4. Let index be 0.- u64 index = 0;-- // 5. While index is less than len:- while (index < length) {- // 1. Let hop be ? HasOwnProperty(input, index).- auto hop = TRY(input.as_object().has_own_property(index));-- // 2. If hop is false, return "invalid value".- if (!hop)- return Key::create_invalid("Array-like object has no property"_utf16);-- // 3. Let entry be ? Get(input, index).- auto entry = TRY(input.as_object().get(index));-- // 4. Let key be the result of converting a value to a key with arguments entry and seen.- // 5. ReturnIfAbrupt(key).- auto key = TRY(convert_a_value_to_a_key(realm, entry, seen));-- // 6. If key is "invalid value" or "invalid type" abort these steps and return "invalid value".- if (key->is_invalid())- return key;-- // 7. Append key to keys.- keys->elements().append(key);-- // 8. Increase index by 1.- index++;- }-- // 6. Return a new array key with value keys.- return Key::create_array(keys);- }-- // - Otherwise- // Return "invalid type".- return Key::create_invalid("Unable to convert value to key. Its not of a known type"_utf16);-}--// https://w3c.github.io/IndexedDB/#close-a-database-connection-void close_a_database_connection(GC::Ref<IDBDatabase> connection, GC::Ptr<GC::Function<void()>> on_complete, bool forced)-{- // 1. Set connection’s close pending flag to true.- connection->set_close_pending(true);-- // 2. If the forced flag is true, then for each transaction created using connection run abort a transaction with transaction and newly created "AbortError" DOMException.- if (forced) {- for (auto const& transaction : connection->transactions()) {- abort_a_transaction(*transaction, WebIDL::AbortError::create("Connection was closed"_utf16));- }- }-- // 3. Wait for all transactions created using connection to complete. Once they are complete, connection is closed.- if constexpr (IDB_DEBUG) {- dbgln("close_a_database_connection: waiting for step 3");- dbgln("transactions created using connection:");- for (auto const& transaction : connection->transactions()) {- dbgln(" - {} - {}", transaction->uuid(), (u8)transaction->state());- }- }-- connection->wait_for_transactions_to_finish(connection->transactions(), GC::create_function(GC::Heap::the(), [connection, forced, on_complete] {- dbgln_if(IDB_DEBUG, "close_a_database_connection: finished waiting for step 3, closing database connection");- connection->set_state(ConnectionState::Closed);-- auto database = connection->associated_database();- database->dissociate(*connection);-- // 4. If the forced flag is true, then fire an event named close at connection.- if (forced)- connection->dispatch_event(DOM::Event::create(- HTML::EventNames::close,- current_high_resolution_time(connection->relevant_global_scope())));-- if (on_complete)- queue_a_database_task(on_complete.as_nonnull());-- database->check_pending_connection_wait();- }));-}--// https://w3c.github.io/IndexedDB/#upgrade-a-database-void upgrade_a_database(JS::Realm& realm, GC::Ref<IDBDatabase> connection, u64 version, GC::Ref<IDBRequest> request, GC::Ref<GC::Function<void()>> on_complete)-{- // 1. Let db be connection’s database.- auto db = connection->associated_database();-- // 2. Let transaction be a new upgrade transaction with connection used as connection.- // 3. Set transaction’s scope to connection’s object store set.- auto transaction = IDBTransaction::create(connection, TransactionMode::Versionchange, TransactionDurability::Default, Vector(connection->object_store_set()));- dbgln_if(IDB_DEBUG, "Created new upgrade transaction with UUID: {}", transaction->uuid());-- // 4. Set db’s upgrade transaction to transaction.- db->set_upgrade_transaction(transaction);-- // 5. Set transaction’s state to inactive.- transaction->set_state(IDBTransaction::TransactionState::Inactive);-- // FIXME: 6. Start transaction.-- // 7. Let old version be db’s version.- auto old_version = db->version();-- // AD-HOC: Set up per-store mutation logs. This also records the current database version- // so it can be restored if the transaction is aborted.- transaction->set_up_mutation_logs();-- // 8. Set db’s version to version. This change is considered part of the transaction, and so if the transaction is aborted, this change is reverted.- db->set_version(version);-- // 9. Set request’s processed flag to true.- request->set_processed(true);-- // 10. Queue a database task to run these steps:- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, request, connection, transaction, old_version, version, on_complete]() {- // 1. Set request’s result to connection.- Bindings::set_idb_request_result(realm, request, connection);-- // 2. Set request’s transaction to transaction.- // NOTE: We need to do a two-way binding here.- request->set_transaction(transaction);- transaction->set_associated_request(request);-- // 3. Set request’s done flag to true.- request->set_done(true);-- // 4. Set transaction’s state to active.- transaction->set_state(IDBTransaction::TransactionState::Active);-- // 5. Let didThrow be the result of firing a version change event named upgradeneeded at request with old version and version.- auto did_throw = fire_a_version_change_event(realm, HTML::EventNames::upgradeneeded, request, old_version, version);-- // 6. If transaction’s state is active, then:- if (transaction->state() == IDBTransaction::TransactionState::Active) {-- // 1. Set transaction’s state to inactive.- transaction->set_state(IDBTransaction::TransactionState::Inactive);-- // 2. If didThrow is true, run abort a transaction with transaction and a newly created "AbortError" DOMException.- if (did_throw)- abort_a_transaction(transaction, WebIDL::AbortError::create("Version change event threw an exception"_utf16));-- // https://w3c.github.io/IndexedDB/#transaction-commit- // The implementation must attempt to commit an inactive transaction when all requests placed- // against the transaction have completed and their returned results handled, no new requests have- // been placed against the transaction, and the transaction has not been aborted- if (transaction->state() == IDBTransaction::TransactionState::Inactive && transaction->request_list().is_empty() && !transaction->aborted())- commit_a_transaction(realm, transaction);- }-- // 11. Wait for transaction to finish.- dbgln_if(IDB_DEBUG, "upgrade_a_database: waiting for step 11");- connection->wait_for_transactions_to_finish({ &transaction, 1 }, on_complete);- }));-}--// https://w3c.github.io/IndexedDB/#deleting-a-database-void delete_a_database(JS::Realm& realm, StorageAPI::StorageKey storage_key, Utf16String name, GC::Ref<IDBRequest> request, GC::Ref<GC::Function<void(WebIDL::ExceptionOr<u64>)>> on_complete)-{- // 1. Let queue be the connection queue for storageKey and name.- auto& queue = ConnectionQueueHandler::for_key_and_name(storage_key, name);-- dbgln_if(IDB_DEBUG, "delete_a_database: enqueuing request {}", request->uuid());-- // 2. Add request to queue.- // 3. Wait until all previous requests in queue have been processed.- queue.enqueue(request, GC::create_function(GC::Heap::the(), [&realm, &queue, storage_key = move(storage_key), name = move(name), request, on_complete] -> void {- static constexpr auto call_completion = [](auto& queue, auto completion, auto result) {- completion->function()(move(result));- queue.on_request_processed();- };-- // 4. Let db be the database named name in storageKey, if one exists. Otherwise, return 0 (zero).- auto maybe_db = Database::for_key_and_name(storage_key, name);- if (!maybe_db.has_value()) {- call_completion(queue, on_complete, 0);- return;- }-- GC::Ref db = maybe_db.value();-- // 5. Let openConnections be the set of all connections associated with db.- auto open_connections = db->associated_connections_as_heap_vector(GC::Heap::the());-- // 6. For each entry of openConnections that does not have its close pending flag set to true,- // queue a database task to fire a version change event named versionchange at entry with db’s version and null.- GC::Ptr<TaskCounterState> task_counter_state;- for (auto const& entry : open_connections->elements()) {- if (!entry->close_pending()) {- if (!task_counter_state) {- task_counter_state = GC::Heap::the().allocate<TaskCounterState>();- }-- task_counter_state->remaining_tasks++;- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, entry, db, task_counter_state] {- fire_a_version_change_event(realm, HTML::EventNames::versionchange, *entry, db->version(), {});- task_counter_state->decrement_remaining_tasks();- }));- }- }-- // 7. Wait for all of the events to be fired.- if constexpr (IDB_DEBUG) {- dbgln("delete_a_database: waiting for step 7");- dbgln("remaining tasks: {}", task_counter_state ? task_counter_state->remaining_tasks : 0);- }-- auto after_all = GC::create_function(GC::Heap::the(), [&realm, &queue, open_connections, db, storage_key, name, request, on_complete] {- // 8. If any of the connections in openConnections are still not closed, queue a database task to fire a- // version change event named blocked at request with db’s version and null.- auto any_connection_is_not_closed = [&] {- for (auto const& entry : open_connections->elements()) {- if (entry->state() != ConnectionState::Closed)- return true;- }- return false;- }();- if (any_connection_is_not_closed) {- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, request, db]() {- fire_a_version_change_event(realm, HTML::EventNames::blocked, request, db->version(), {});- }));- }-- // 9. Wait until all connections in openConnections are closed.- if constexpr (IDB_DEBUG) {- dbgln("delete_a_database: waiting for step 9");- dbgln("open connections: {}", open_connections->elements().size());- for (auto const& connection : open_connections->elements()) {- dbgln(" - {}", connection->uuid());- }- }-- db->wait_for_connections_to_close(open_connections->elements(), GC::create_function(GC::Heap::the(), [&queue, db, storage_key, name, on_complete] {- // 10. Let version be db’s version.- auto version = db->version();-- // 11. Delete db. If this fails for any reason, return an appropriate error (e.g. a QuotaExceededError, or an "UnknownError" DOMException).- auto maybe_deleted = Database::delete_for_key_and_name(storage_key, name);- if (maybe_deleted.is_error()) {- call_completion(queue, on_complete, WebIDL::OperationError::create("Unable to delete database"_utf16));- return;- }-- // 12. Return version.- call_completion(queue, on_complete, version);- }));- });-- if (task_counter_state) {- task_counter_state->after_all = after_all;- } else {- queue_a_database_task(after_all);- }- }));-}--// https://w3c.github.io/IndexedDB/#abort-an-upgrade-transaction-static void abort_an_upgrade_transaction(GC::Ref<IDBTransaction> transaction)-{- // 1. Let connection be transaction’s connection.- auto connection = transaction->connection();-- // 2. Let database be connection’s database.- auto database = connection->associated_database();-- // 3. Set connection’s version to database’s version if database previously existed, or 0 (zero) if database was- // newly created.- connection->set_version(database->version());-- // 4. Set connection’s object store set to the set of object stores in database if database previously existed, or- // the empty set if database was newly created.- // NB: MutationLog reverts all changes to the connection's object store set alongside the deletion/creation of the- // underlying ObjectStore instances.- // However, the transaction scope will still be outdated here. Upgrade transactions are always scoped to the- // entire database, so this is easy.- transaction->set_scope(Vector(connection->object_store_set()));-- // 5. For each object store handle handle associated with transaction, including those for object stores that were- // created or deleted during transaction:- transaction->for_each_object_store_handle([&](auto const& handle) {- // 1. If handle’s object store was not newly created during transaction, set handle’s name to its object- // store’s name.- if (database->object_stores().contains_slow(handle->store()))- handle->update_name();-- // 2. Set handle’s index set to the set of indexes that reference its object store.- handle->update_index_set();- return IterationDecision::Continue;- });-- // 6. For each index handle handle associated with transaction, including those for indexes that were created or- // deleted during transaction:- for (auto const& handle : transaction->index_handles()) {- // 1. If handle’s index was not newly created during transaction, set handle’s name to its index’s name.- if (handle->index()->object_store()->index_set().contains(handle->index()->name()))- handle->update_name();- }-}--// https://w3c.github.io/IndexedDB/#abort-a-transaction-void abort_a_transaction(GC::Ref<IDBTransaction> transaction, GC::Ptr<WebIDL::DOMException> error)-{- // NOTE: This is not spec'ed anywhere, but we need to know IF the transaction was aborted.- transaction->set_aborted(true);- dbgln_if(IDB_DEBUG, "abort_a_transaction: transaction {} is aborting", transaction->uuid());-- // 1. If transaction’s state is finished, abort these steps.- if (transaction->is_finished())- return;-- // 2. All the changes made to the database by the transaction are reverted.- // For upgrade transactions this includes changes to the set of object stores and indexes, as well as the change to the version.- // Any object stores and indexes which were created during the transaction are now considered deleted for the purposes of other algorithms.- transaction->revert_all_mutations();- transaction->discard_mutation_logs();-- // 3. If transaction is an upgrade transaction, run the steps to abort an upgrade transaction with transaction.- if (transaction->is_upgrade_transaction())- abort_an_upgrade_transaction(transaction);-- // 4. Set transaction’s state to finished.- transaction->set_state(IDBTransaction::TransactionState::Finished);-- // AD-HOC: Clear the cleanup event loop so that the microtask checkpoint doesn't set the state to inactive on a- // finished transaction.- // https://github.com/w3c/IndexedDB/issues/489- transaction->set_cleanup_event_loop(nullptr);-- // 5. Set transaction’s error to error.- transaction->set_error(error);-- // 6. For each request of transaction’s request list, abort the steps to asynchronously execute a request for request,- // set request’s processed flag to true, and queue a database task to run these steps:- for (auto const& request : transaction->request_list()) {- request->set_aborted(true);- request->set_processed(true);- queue_a_database_task(GC::create_function(GC::Heap::the(), [request]() {- // 1. Set request’s done flag to true.- request->set_done(true);-- // 2. Set request’s result to undefined.- request->set_result(JS::js_undefined());-- // 3. Set request’s error to a newly created "AbortError" DOMException.- request->set_error(WebIDL::AbortError::create("Transaction was aborted"_utf16));-- // 4. Fire an event named error at request with its bubbles and cancelable attributes initialized to true.- request->dispatch_event(DOM::Event::create(- HTML::EventNames::error,- { .bubbles = true, .cancelable = true },- current_high_resolution_time(request->relevant_global_scope())));- }));- }-- // NB: Clear the commit wait callback, since the transaction is no longer committing.- transaction->request_list().clear_on_all_processed();-- // 7. Queue a database task to run these steps:- queue_a_database_task(GC::create_function(GC::Heap::the(), [transaction]() {- // 1. If transaction is an upgrade transaction, then set transaction’s connection's associated database's upgrade transaction to null.- if (transaction->is_upgrade_transaction())- transaction->connection()->associated_database()->set_upgrade_transaction(nullptr);-- // 2. Fire an event named abort at transaction with its bubbles attribute initialized to true.- transaction->dispatch_event(DOM::Event::create(- HTML::EventNames::abort,- { .bubbles = true },- current_high_resolution_time(transaction->relevant_global_scope())));-- // 3. If transaction is an upgrade transaction, then:- if (transaction->is_upgrade_transaction()) {- // 1. Let request be the open request associated with transaction.- auto request = transaction->associated_request();-- // 2. Set request’s transaction to null.- // NOTE: Clear the two-way binding.- request->set_transaction(nullptr);- transaction->set_associated_request(nullptr);-- // 3. Set request’s result to undefined.- request->set_result(JS::js_undefined());-- // FIXME: https://github.com/w3c/IndexedDB/issues/473- // x. Set transaction's associated request's error to a newly created "AbortError" DOMException.- request->set_error(WebIDL::AbortError::create("Upgrade transaction was aborted"_utf16));-- // 4. Set request’s processed flag to false.- // FIXME: request->set_processed(false);-- // 5. Set request’s done flag to false.- request->set_done(false);- }-- // AD-HOC: Now that all abort tasks are queued, notify pending transaction waits.- // This is done after step 7 so that the abort cleanup tasks above are queued- // before any waiting transactions (e.g. upgrade completion callbacks) proceed.- transaction->connection()->check_pending_transaction_waits();- }));-}--// https://w3c.github.io/IndexedDB/#convert-a-key-to-a-value-JS::Value convert_a_key_to_a_value(JS::Realm& realm, GC::Ref<Key> key)-{- // 1. Let type be key’s type.- auto type = key->type();-- // 2. Let value be key’s value.- auto value = key->value();-- // 3. Switch on type:- switch (type) {- case Key::KeyType::Number: {- // Return an ECMAScript Number value equal to value- return JS::Value(key->value_as_double());- }-- case Key::KeyType::String: {- // Return an ECMAScript String value equal to value- return JS::PrimitiveString::create(realm.vm(), key->value_as_string());- }-- case Key::KeyType::Date: {- // 1. Let date be the result of executing the ECMAScript Date constructor with the single argument value.- auto date = JS::Date::create(realm, key->value_as_double());-- // 2. Assert: date is not an abrupt completion.- // NOTE: This is not possible in our implementation.-- // 3. Return date.- return date;- }-- case Key::KeyType::Binary: {- auto buffer = key->value_as_byte_buffer();-- // 1. Let len be value’s length.- auto len = buffer.size();-- // 2. Let buffer be the result of executing the ECMAScript ArrayBuffer constructor with len.- // 3. Assert: buffer is not an abrupt completion.- auto array_buffer = MUST(JS::ArrayBuffer::create(realm, len));-- // 4. Set the entries in buffer’s [[ArrayBufferData]] internal slot to the entries in value.- array_buffer->overwrite(0, buffer.data(), buffer.size());-- // 5. Return buffer.- return array_buffer;- }-- case Key::KeyType::Array: {- auto data = key->value_as_vector();-- // 1. Let array be the result of executing the ECMAScript Array constructor with no arguments.- // 2. Assert: array is not an abrupt completion.- auto array = MUST(JS::Array::create(realm, 0));-- // 3. Let len be value’s size.- auto len = data.size();-- // 4. Let index be 0.- u64 index = 0;-- // 5. While index is less than len:- while (index < len) {- // 1. Let entry be the result of converting a key to a value with value[index].- auto entry = convert_a_key_to_a_value(realm, *data[index]);-- // 2. Let status be CreateDataProperty(array, index, entry).- auto status = MUST(array->create_data_property(index, entry));-- // 3. Assert: status is true.- VERIFY(status);-- // 4. Increase index by 1.- index++;- }-- // 6. Return array.- return array;- }- case Key::KeyType::Invalid:- VERIFY_NOT_REACHED();- }-- VERIFY_NOT_REACHED();-}--// https://tc39.es/ecma262/#prod-IdentifierName-static bool is_identifier_name(Utf16View const& string)-{- // FIXME: Accept the UnicodeEscapeSequences that IdentifierStart and IdentifierPart allow.- if (string.is_empty())- return false;-- bool is_first_code_point = true;- for (auto code_point : string) {- // IdentifierStartChar ::- // UnicodeIDStart- // $- // _- // IdentifierPartChar ::- // UnicodeIDContinue- // $- // <ZWNJ>- // <ZWJ>- bool is_valid = code_point == '$' || code_point == '_';- if (is_first_code_point)- is_valid = is_valid || Unicode::code_point_has_identifier_start_property(code_point);- else- is_valid = is_valid || code_point == 0x200C || code_point == 0x200D || Unicode::code_point_has_identifier_continue_property(code_point);- if (!is_valid)- return false;- is_first_code_point = false;- }- return true;-}--// https://w3c.github.io/IndexedDB/#valid-key-path-bool is_valid_key_path(KeyPath const& path)-{- // A valid key path is one of:- return path.visit(- [](Utf16String const& value) -> bool {- // * An empty string.- if (value.is_empty())- return true;-- // * An identifier, which is a string matching the IdentifierName production from the ECMAScript Language- // Specification [ECMA-262].- // * A string consisting of two or more identifiers separated by periods (U+002E FULL STOP).- auto view = value.utf16_view();- size_t identifier_start = 0;- for (size_t index = 0; index <= view.length_in_code_units(); ++index) {- if (index < view.length_in_code_units() && view.code_unit_at(index) != '.')- continue;- if (!is_identifier_name(view.substring_view(identifier_start, index - identifier_start)))- return false;- identifier_start = index + 1;- }- return true;- },- [](Vector<Utf16String> const& values) -> bool {- // * A non-empty list containing only strings conforming to the above requirements.- if (values.is_empty())- return false;-- for (auto const& value : values) {- if (!is_valid_key_path(value))- return false;- }-- return true;- });-}--// https://w3c.github.io/IndexedDB/#create-a-sorted-name-list-GC::Ref<HTML::DOMStringList> create_a_sorted_name_list(Vector<String> names)-{- // 1. Let sorted be names sorted in ascending order with the code unit less than algorithm.- quick_sort(names, [](auto const& a, auto const& b) {- auto a_utf16 = Utf16String::from_utf8(a);- auto b_utf16 = Utf16String::from_utf8(b);- return a_utf16.utf16_view().is_code_unit_less_than(b_utf16.utf16_view());- });-- // 2. Return a new DOMStringList associated with sorted.- return HTML::DOMStringList::create(names);-}--GC::Ref<HTML::DOMStringList> create_a_sorted_name_list(Vector<Utf16String> names)-{- Vector<String> utf8_names;- utf8_names.ensure_capacity(names.size());- for (auto const& name : names)- utf8_names.append(name.to_utf8());- return create_a_sorted_name_list(move(utf8_names));-}--// https://w3c.github.io/IndexedDB/#commit-a-transaction-void commit_a_transaction(JS::Realm&, GC::Ref<IDBTransaction> transaction)-{- // 1. Set transaction’s state to committing.- transaction->set_state(IDBTransaction::TransactionState::Committing);-- // AD-HOC: Clear the cleanup event loop so that the microtask checkpoint- // does not reset the state back to inactive.- // https://github.com/w3c/IndexedDB/issues/489- transaction->set_cleanup_event_loop(nullptr);-- dbgln_if(IDB_DEBUG, "commit_a_transaction: transaction {} is committing", transaction->uuid());-- // 2. Run the following steps in parallel:- // 1. Wait until every item in transaction’s request list is processed.- dbgln_if(IDB_DEBUG, "commit_a_transaction: registering wait for all requests to be processed");-- transaction->request_list().set_on_all_processed(GC::create_function(GC::Heap::the(), [transaction] {- dbgln_if(IDB_DEBUG, "finish_committing_transaction: all requests processed for transaction {}", transaction->uuid());-- // 2. If transaction’s state is no longer committing, then terminate these steps.- if (transaction->state() != IDBTransaction::TransactionState::Committing)- return;-- // FIXME: 3. Attempt to write any outstanding changes made by transaction to the database, considering transaction’s durability hint.- // FIXME: 4. If an error occurs while writing the changes to the database, then run abort a transaction with transaction and an appropriate type for the error, for example a QuotaExceededError or an "UnknownError" DOMException, and terminate these steps.-- // 5. Queue a database task to run these steps:- queue_a_database_task(GC::create_function(GC::Heap::the(), [transaction]() {- // 1. If transaction is an upgrade transaction, then set transaction’s connection’s associated database’s upgrade transaction to null.- if (transaction->is_upgrade_transaction())- transaction->connection()->associated_database()->set_upgrade_transaction(nullptr);-- // AD-HOC: Discard mutation logs now that changes are permanent.- transaction->notify_devtools_of_committed_changes();- transaction->discard_mutation_logs();-- // 2. Set transaction’s state to finished.- transaction->set_state(IDBTransaction::TransactionState::Finished);-- // 3. Fire an event named complete at transaction.- transaction->dispatch_event(DOM::Event::create(- HTML::EventNames::complete,- current_high_resolution_time(transaction->relevant_global_scope())));-- // 4. If transaction is an upgrade transaction, then let request be the request associated with transaction and set request’s transaction to null.- if (transaction->is_upgrade_transaction()) {- auto request = transaction->associated_request();- request->set_transaction(nullptr);-- // Ad-hoc: Clear the two-way binding.- transaction->set_associated_request(nullptr);- }-- // AD-HOC: Notify pending transaction waits after the complete event fires, so that- // upgrade completion callbacks are queued after any tasks JS creates during- // the complete event handler.- transaction->connection()->check_pending_transaction_waits();- }));- }));-}--// https://w3c.github.io/IndexedDB/#clone-WebIDL::ExceptionOr<JS::Value> clone_in_realm(JS::Realm& target_realm, JS::Value value, GC::Ref<IDBTransaction> transaction)-{- auto& vm = target_realm.vm();-- // 1. Assert: transaction’s state is active.- VERIFY(transaction->state() == IDBTransaction::TransactionState::Active);-- // 2. Set transaction’s state to inactive.- transaction->set_state(IDBTransaction::TransactionState::Inactive);-- // AD-HOC: Always reset the transaction state to active. Otherwise, passing an unserializable value to put()- // will prevent any further requests on the transaction.- // https://github.com/w3c/IndexedDB/issues/490- ScopeGuard reset_state([&] { transaction->set_state(IDBTransaction::TransactionState::Active); });-- // 3. Let serialized be ? StructuredSerializeForStorage(value).- auto serialized = TRY(HTML::structured_serialize_for_storage(target_realm.vm(), value));-- // 4. Let clone be ? StructuredDeserialize(serialized, targetRealm).- auto clone = TRY(HTML::structured_deserialize(vm, serialized, target_realm));-- // 5. Set transaction’s state to active.- // NB: This is handled by the scope guard after step 2.-- // 6. Return clone.- return clone;-}--// https://w3c.github.io/IndexedDB/#convert-a-value-to-a-multientry-key-WebIDL::ExceptionOr<GC::Ref<Key>> convert_a_value_to_a_multi_entry_key(JS::Realm& realm, JS::Value value)-{- // 1. If input is an Array exotic object, then:- if (value.is_object() && is<JS::Array>(value.as_object())) {-- // 1. Let len be ? ToLength( ? Get(input, "length")).- auto len = TRY(length_of_array_like(realm.vm(), value.as_object()));-- // 2. Let seen be a new set containing only input.- GC::RootVector<JS::Value> seen;- seen.append(value);-- // 3. Let keys be a new empty list.- auto keys = GC::Heap::the().allocate<GC::HeapVector<GC::Ref<Key>>>();-- // 4. Let index be 0.- u64 index = 0;-- // 5. While index is less than len:- while (index < len) {-- // 1. Let entry be Get(input, index).- auto maybe_entry = value.as_object().get(index);-- // 2. If entry is not an abrupt completion, then:- if (!maybe_entry.is_error()) {-- // 1. Let key be the result of converting a value to a key with arguments entry and seen.- auto completion_key = convert_a_value_to_a_key(realm, maybe_entry.release_value(), seen);-- // 2. If key is not "invalid value" or "invalid type" or an abrupt completion, and there is no item in keys equal to key, then append key to keys.- if (!completion_key.is_error()) {- auto key = completion_key.release_value();-- if (!key->is_invalid() && !any_of(keys->elements(), [&](auto const& other) { return Key::equals(other, key); }))- keys->elements().append(key);- }- }-- // 3. Increase index by 1.- index++;- }-- // 6. Return a new array key with value set to keys.- return Key::create_array(keys);- }-- // 2. Otherwise, return the result of converting a value to a key with argument input. Rethrow any exceptions.- return convert_a_value_to_a_key(realm, value);-}--// https://w3c.github.io/IndexedDB/#evaluate-a-key-path-on-a-value-WebIDL::ExceptionOr<ErrorOr<JS::Value>> evaluate_key_path_on_a_value(JS::Realm& realm, JS::Value value, KeyPath const& key_path)-{- // 1. If keyPath is a list of strings, then:- if (key_path.has<Vector<Utf16String>>()) {- auto const& key_path_list = key_path.get<Vector<Utf16String>>();-- // 1. Let result be a new Array object created as if by the expression [].- auto result = MUST(JS::Array::create(realm, 0));-- // 2. Let i be 0.- u64 i = 0;-- // 3. For each item of keyPath:- for (auto const& item : key_path_list) {- // 1. Let key be the result of recursively evaluating a key path on a value with item and value.- auto completion_key = evaluate_key_path_on_a_value(realm, value, item);-- // 2. Assert: key is not an abrupt completion.- VERIFY(!completion_key.is_error());-- // 3. If key is failure, abort the overall algorithm and return failure.- auto key = TRY(TRY(completion_key));-- // 4. Let p be ! ToString(i).- auto p = JS::PropertyKey { i };-- // 5. Let status be CreateDataProperty(result, p, key).- auto status = MUST(result->create_data_property(p, key));-- // 6. Assert: status is true.- VERIFY(status);-- // 7. Increase i by 1.- i++;- }-- // 4. Return result.- return result;- }-- auto const& key_path_string = key_path.get<Utf16String>();-- // 2. If keyPath is the empty string, return value and skip the remaining steps.- if (key_path_string.is_empty())- return value;-- // 3. Let identifiers be the result of strictly splitting keyPath on U+002E FULL STOP characters (.).- // 4. For each identifier of identifiers, jump to the appropriate step below:- Optional<Error> failure;- key_path_string.for_each_split_view(u'.', SplitBehavior::KeepEmpty, [&](Utf16View const& identifier) {- // If Type(value) is String, and identifier is "length"- if (value.is_string() && identifier == "length"_utf16) {- // Let value be a Number equal to the number of elements in value.- value = JS::Value(value.as_string().length_in_utf16_code_units());- }-- // If value is an Array and identifier is "length"- else if (value.is_object() && is<JS::Array>(value.as_object()) && identifier == "length"_utf16) {- // Let value be ! ToLength(! Get(value, "length")).- value = JS::Value(MUST(length_of_array_like(realm.vm(), value.as_object())));- }-- // Otherwise- else {- // If value is a Blob and identifier is "size"- // Let value be a Number equal to value’s size.- // If value is a Blob and identifier is "type"- // Let value be a String equal to value’s type.- // If value is a File and identifier is "name"- // Let value be a String equal to value’s name.- // If value is a File and identifier is "lastModified"- // Let value be a Number equal to value’s lastModified.- auto identifier_utf8 = MUST(identifier.to_utf8());- if (auto key_path_value = Bindings::key_path_value_for_blob_or_file(realm, value, identifier_utf8.bytes_as_string_view()); key_path_value.has_value()) {- value = *key_path_value;- return IterationDecision::Continue;- }-- // 1. If Type(value) is not Object, return failure.- if (!value.is_object()) {- failure = Error::from_string_literal("Value is not an object during key path evaluation");- return IterationDecision::Break;- }-- auto identifier_property = JS::PropertyKey { Utf16String::from_utf16(identifier) };-- // 2. Let hop be ! HasOwnProperty(value, identifier).- auto hop = MUST(value.as_object().has_own_property(identifier_property));-- // 3. If hop is false, return failure.- if (!hop) {- failure = Error::from_string_literal("Failed to find property on object during key path evaluation");- return IterationDecision::Break;- }-- // 4. Let value be ! Get(value, identifier).- value = MUST(value.as_object().get(identifier_property));-- // 5. If value is undefined, return failure.- if (value.is_undefined()) {- failure = Error::from_string_literal("undefined value on object during key path evaluation");- return IterationDecision::Break;- }- }-- return IterationDecision::Continue;- });- if (failure.has_value())- return failure.release_value();-- // 5. Assert: value is not an abrupt completion.- // NOTE: Step 4 above makes this assertion via MUST-- // 6. Return value.- return value;-}--// https://w3c.github.io/IndexedDB/#extract-a-key-from-a-value-using-a-key-path-WebIDL::ExceptionOr<ErrorOr<GC::Ref<Key>>> extract_a_key_from_a_value_using_a_key_path(JS::Realm& realm, JS::Value value, KeyPath const& key_path, bool multi_entry)-{- // 1. Let r be the result of evaluating a key path on a value with value and keyPath. Rethrow any exceptions.- // 2. If r is failure, return failure.- auto r = TRY(TRY(evaluate_key_path_on_a_value(realm, value, key_path)));-- // 3. Let key be the result of converting a value to a key with r if the multiEntry flag is false,- // and the result of converting a value to a multiEntry key with r otherwise. Rethrow any exceptions.- // 4. If key is "invalid value" or "invalid type", return invalid.- // 5. Return key.- return multi_entry ? TRY(convert_a_value_to_a_multi_entry_key(realm, r)) : TRY(convert_a_value_to_a_key(realm, r));-}--// AD-HOC: Whether CreateDataProperty(value, identifier, key) would succeed, which inject a key into a value using a-// key path asserts: a TypedArray refuses a canonical numeric string, such as "Infinity", that is not an-// index of it.-static bool can_create_data_property(JS::VM& vm, JS::Object const& value, Utf16String const& identifier)-{- if (!is<JS::TypedArrayBase>(value))- return true;- if (identifier == u"-0"sv)- return false;- auto number = MUST(JS::Value { JS::PrimitiveString::create(vm, identifier) }.to_double(vm));- return JS::number_to_utf16_string(number) != identifier;-}--// https://w3c.github.io/IndexedDB/#check-that-a-key-could-be-injected-into-a-value-bool check_that_a_key_could_be_injected_into_a_value(JS::Realm& realm, JS::Value value, KeyPath const& key_path)-{- // NOTE: The key paths used in this section are always strings and never sequences-- // 1. Let identifiers be the result of strictly splitting keyPath on U+002E FULL STOP characters (.).- auto identifiers = strictly_split_key_path(key_path.get<Utf16String>());-- // 2. Assert: identifiers is not empty.- VERIFY(!identifiers.is_empty());-- // 3. Remove the last item of identifiers.- auto last = identifiers.take_last();-- // 4. For each remaining identifier of identifiers, if any:- for (auto const& identifier : identifiers) {- // 1. If value is not an Object or an Array, return false.- if (!(value.is_object() || MUST(value.is_array(realm.vm()))))- return false;-- auto identifier_property = JS::PropertyKey { identifier };-- // 2. Let hop be ! HasOwnProperty(value, identifier).- auto hop = MUST(value.as_object().has_own_property(identifier_property));-- // 3. If hop is false, return true.- if (!hop)- return can_create_data_property(realm.vm(), value.as_object(), identifier);-- // 4. Let value be ! Get(value, identifier).- value = MUST(value.as_object().get(identifier_property));- }-- // 5. Return true if value is an Object or an Array, or false otherwise.- return (value.is_object() || MUST(value.is_array(realm.vm()))) && can_create_data_property(realm.vm(), value.as_object(), last);-}--// https://w3c.github.io/IndexedDB/#fire-an-error-event-void fire_an_error_event(JS::Realm& realm, GC::Ref<IDBRequest> request)-{- // 1. Let event be the result of creating an event using Event.- // 2. Set event’s type attribute to "error".- // 3. Set event’s bubbles and cancelable attributes to true.- auto event = DOM::Event::create(- HTML::EventNames::error,- { .bubbles = true, .cancelable = true },- current_high_resolution_time(request->relevant_global_scope()));-- // 4. Let transaction be request’s transaction.- auto transaction = request->transaction();-- // 5. Let legacyOutputDidListenersThrowFlag be initially false.- bool legacy_output_did_listeners_throw_flag = false;-- // 6. If transaction’s state is inactive, then set transaction’s state to active.- if (transaction->state() == IDBTransaction::TransactionState::Inactive)- transaction->set_state(IDBTransaction::TransactionState::Active);-- // 7. Dispatch event at request with legacyOutputDidListenersThrowFlag.- DOM::EventDispatcher::dispatch(request, *event, false, legacy_output_did_listeners_throw_flag);-- // 8. If transaction’s state is active, then:- if (transaction->state() == IDBTransaction::TransactionState::Active) {- // 1. Set transaction’s state to inactive.- transaction->set_state(IDBTransaction::TransactionState::Inactive);-- // 2. If legacyOutputDidListenersThrowFlag is true, then run abort a transaction with transaction and a newly created "AbortError" DOMException and terminate these steps.- // This is done even if event’s canceled flag is false.- if (legacy_output_did_listeners_throw_flag) {- abort_a_transaction(*transaction, WebIDL::AbortError::create("Error event interrupted by exception"_utf16));- return;- }-- // 3. If event’s canceled flag is false, then run abort a transaction using transaction and request's error, and terminate these steps.- if (!event->cancelled()) {- abort_a_transaction(*transaction, MUST(request->error()));- return;- }-- // 4. If transaction’s request list is empty, then run commit a transaction with transaction.- if (transaction->request_list().is_empty())- commit_a_transaction(realm, *transaction);- }-}--// https://w3c.github.io/IndexedDB/#fire-a-success-event-void fire_a_success_event(JS::Realm& realm, GC::Ref<IDBRequest> request)-{- // 1. Let event be the result of creating an event using Event.- // 2. Set event’s type attribute to "success".- // 3. Set event’s bubbles and cancelable attributes to false.- auto event = DOM::Event::create(- HTML::EventNames::success,- { .bubbles = false, .cancelable = false },- current_high_resolution_time(request->relevant_global_scope()));-- // 4. Let transaction be request’s transaction.- auto transaction = request->transaction();-- // 5. Let legacyOutputDidListenersThrowFlag be initially false.- bool legacy_output_did_listeners_throw_flag = false;-- // 6. If transaction’s state is inactive, then set transaction’s state to active.- if (transaction->state() == IDBTransaction::TransactionState::Inactive)- transaction->set_state(IDBTransaction::TransactionState::Active);-- // 7. Dispatch event at request with legacyOutputDidListenersThrowFlag.- DOM::EventDispatcher::dispatch(request, *event, false, legacy_output_did_listeners_throw_flag);-- // 8. If transaction’s state is active, then:- if (transaction->state() == IDBTransaction::TransactionState::Active) {- // 1. Set transaction’s state to inactive.- transaction->set_state(IDBTransaction::TransactionState::Inactive);-- // 2. If legacyOutputDidListenersThrowFlag is true, then run abort a transaction with transaction and a newly created "AbortError" DOMException.- if (legacy_output_did_listeners_throw_flag) {- abort_a_transaction(*transaction, WebIDL::AbortError::create("An error occurred"_utf16));- return;- }-- // 3. If transaction’s request list is empty, then run commit a transaction with transaction.- if (transaction->request_list().is_empty())- commit_a_transaction(realm, *transaction);- }-}--// https://w3c.github.io/IndexedDB/#asynchronously-execute-a-request-GC::Ref<IDBRequest> asynchronously_execute_a_request(JS::Realm& realm, IDBRequestSource source, GC::Ref<GC::Function<WebIDL::ExceptionOr<JS::Value>()>> operation, GC::Ptr<IDBRequest> request_input)-{- // 1. Let transaction be the transaction associated with source.- auto transaction = source.visit(- [](Empty) -> GC::Ptr<IDBTransaction> {- VERIFY_NOT_REACHED();- },- [](GC::Ref<IDBObjectStore> object_store) -> GC::Ptr<IDBTransaction> {- return object_store->transaction();- },- [](GC::Ref<IDBIndex> index) -> GC::Ptr<IDBTransaction> {- return index->transaction();- },- [](GC::Ref<IDBCursor> cursor) -> GC::Ptr<IDBTransaction> {- return cursor->transaction();- });-- // AD-HOC: Determine the object store being operated on so that we can get the exact mutation log this- // operation will be writing to.- auto store = source.visit(- [](Empty) -> GC::Ref<ObjectStore> {- VERIFY_NOT_REACHED();- },- [](GC::Ref<IDBObjectStore> object_store) -> GC::Ref<ObjectStore> {- return object_store->store();- },- [](GC::Ref<IDBIndex> index) -> GC::Ref<ObjectStore> {- return index->object_store()->store();- },- [](GC::Ref<IDBCursor> cursor) -> GC::Ref<ObjectStore> {- return cursor->effective_object_store();- });-- // 2. Assert: transaction’s state is active.- VERIFY(transaction->state() == IDBTransaction::TransactionState::Active);-- // 3. If request was not given, let request be a new request with source as source.- GC::Ref<IDBRequest> request = request_input- ? GC::Ref(*request_input)- : IDBRequest::create(transaction->connection()->relevant_global_scope().this_impl(), source);-- // Set the two-way binding. (Missing spec step)- // FIXME: https://github.com/w3c/IndexedDB/issues/433- request->set_transaction(transaction);-- // 4. Add request to the end of transaction’s request list.- // 5. Run these steps in parallel:- // 1. Wait until request is the first item in transaction’s request list that is not processed.- transaction->request_list().enqueue(request, GC::create_function(GC::Heap::the(), [&realm, transaction, store, operation, request]() {- if (request->aborted()) {- dbgln_if(IDB_DEBUG, "asynchronously_execute_a_request: executing request {} canceled due to abort", request->uuid());- return;- }-- dbgln_if(IDB_DEBUG, "asynchronously_execute_a_request: step 5.1: performing operation for request {}", request->uuid());-- // AD-HOC: Determine where the mutation logs for this operation begin in case we need to revert.- auto log_position = store->mutation_log_position();-- // 2. Let result be the result of performing operation.- auto result = operation->function()();-- // 3. If result is an error and transaction’s state is committing, then run abort a transaction with transaction and result, and terminate these steps.- if (result.is_error() && transaction->state() == IDBTransaction::TransactionState::Committing) {- dbgln_if(IDB_DEBUG, "asynchronously_execute_a_request: step 5.3: request errored, aborting transaction");- abort_a_transaction(*transaction, result.exception().get<GC::Ref<WebIDL::DOMException>>());- return;- }-- // 4. If result is an error, then revert all changes made by operation.- if (result.is_error())- store->revert_mutations_from(log_position);-- // 5. Set request’s processed flag to true.- request->set_processed(true);-- // 6. Queue a database task to run these steps:- dbgln_if(IDB_DEBUG, "asynchronously_execute_a_request: step 5.6: request finished without error, queuing task to finish up");- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, request, result, transaction]() mutable {- if (request->aborted()) {- dbgln_if(IDB_DEBUG, "asynchronously_execute_a_request: aborted completion events for request {}", request->uuid());- return;- }-- dbgln_if(IDB_DEBUG, "asynchronously_execute_a_request: step 5.6: finish up task executing");-- // 1. Remove request from transaction’s request list.- transaction->request_list().remove(request);-- // 2. Set request’s done flag to true.- request->set_done(true);-- // 3. If result is an error, then:- if (result.is_error()) {- // 1. Set request’s result to undefined.- request->set_result(JS::js_undefined());-- // 2. Set request’s error to result.- request->set_error(result.exception().get<GC::Ref<WebIDL::DOMException>>());-- // 3. Fire an error event at request.- fire_an_error_event(realm, request);- }- // 4. Otherwise:- else {- // 1. Set request’s result to result.- request->set_result(result.release_value());-- // 2. Set request’s error to undefined.- request->set_error(Optional<GC::Ptr<WebIDL::DOMException>> {});-- // 3. Fire a success event at request.- fire_a_success_event(realm, request);- }-- // NB: Check if the commit wait is satisfied after firing the result event, so that the commit completion- // runs after it. This models the parallel nature of the processing according to the spec, where a- // request being processed necessitates sending a message from the IDB worker thread/process to the- // main thread (most likely also triggering this task), meaning that the above events will necessarily- // be fired before the transaction can be committed.- transaction->request_list().check_all_processed();- }));-- // Allow the next operation in the queue to proceed. This runs after the above task to ensure that if another- // request is ready, it will run after the success or failure events are fired. Otherwise, the next request may- // throw an error and clobber the result of this request.- transaction->request_list().on_request_processed();- }));-- // 6. Return request.- return request;-}--// https://w3c.github.io/IndexedDB/#inject-a-key-into-a-value-using-a-key-path-void inject_a_key_into_a_value_using_a_key_path(JS::Realm& realm, JS::Value value, GC::Ref<Key> key, KeyPath const& key_path)-{- // 1. Let identifiers be the result of strictly splitting keyPath on U+002E FULL STOP characters (.).- auto identifiers = strictly_split_key_path(key_path.get<Utf16String>());-- // 2. Assert: identifiers is not empty.- VERIFY(!identifiers.is_empty());-- // 3. Let last be the last item of identifiers and remove it from the list.- auto last = identifiers.take_last();-- // 4. For each remaining identifier of identifiers:- for (auto const& identifier : identifiers) {- // 1. Assert: value is an Object or an Array.- VERIFY(value.is_object() || MUST(value.is_array(realm.vm())));-- auto identifier_property = JS::PropertyKey { identifier };-- // 2. Let hop be ! HasOwnProperty(value, identifier).- auto hop = MUST(value.as_object().has_own_property(identifier_property));-- // 3. If hop is false, then:- if (!hop) {- // 1. Let o be a new Object created as if by the expression ({}).- auto o = JS::Object::create(realm, realm.intrinsics().object_prototype());-- // 2. Let status be CreateDataProperty(value, identifier, o).- auto status = MUST(value.as_object().create_data_property(identifier_property, o));-- // 3. Assert: status is true.- VERIFY(status);- }-- // 4. Let value be ! Get(value, identifier).- value = MUST(value.as_object().get(identifier_property));- }-- // 5. Assert: value is an Object or an Array.- VERIFY(value.is_object() || MUST(value.is_array(realm.vm())));-- // 6. Let keyValue be the result of converting a key to a value with key.- auto key_value = convert_a_key_to_a_value(realm, key);-- // 7. Let status be CreateDataProperty(value, last, keyValue).- auto status = MUST(value.as_object().create_data_property(JS::PropertyKey { last }, key_value));-- // 8. Assert: status is true.- VERIFY(status);-}--// https://w3c.github.io/IndexedDB/#delete-records-from-an-object-store-JS::Value delete_records_from_an_object_store(GC::Ref<ObjectStore> store, GC::Ref<IDBKeyRange> range)-{- // 1. Remove all records, if any, from store’s list of records with key in range.- store->remove_records_in_range(range);-- // 2. For each index which references store, remove every record from index’s list of records whose value is in range, if any such records exist.- for (auto const& [name, index] : store->index_set()) {- index->remove_records_with_value_in_range(range);- }-- // 3. Return undefined.- return JS::js_undefined();-}--// https://w3c.github.io/IndexedDB/#store-a-record-into-an-object-store-// NB: The steps of storing a record into an object store for one index which references store, as step 5 runs them for-// each such index.-static WebIDL::ExceptionOr<void> store_a_record_into_an_index(JS::Object& global_object, Index& index, JS::Value value, GC::Ref<Key> key)-{- auto& realm = HTML::relevant_realm(global_object);-- // 1. Let index key be the result of extracting a key from a value using a key path with value, index’s key path, and index’s multiEntry flag.- auto completion_index_key = extract_a_key_from_a_value_using_a_key_path(realm, value, index.key_path(), index.multi_entry());-- // 2. If index key is an exception, or invalid, or failure, take no further actions for index, and continue these steps for the next index.- if (completion_index_key.is_error())- return {};-- auto failure_index_key = completion_index_key.release_value();- if (failure_index_key.is_error())- return {};-- auto index_key = failure_index_key.release_value();- if (index_key->is_invalid())- return {};-- auto index_multi_entry = index.multi_entry();- auto index_key_is_array = index_key->type() == Key::KeyType::Array;- auto index_is_unique = index.unique();-- // 3. If index’s multiEntry flag is false, or if index key is not an array key,- // and if index already contains a record with key equal to index key,- // and index’s unique flag is true,- // then this operation failed with a "ConstraintError" DOMException.- // Abort this algorithm without taking any further steps.- if ((!index_multi_entry || !index_key_is_array) && index_is_unique && index.has_record_with_key(index_key))- return WebIDL::ConstraintError::create("Record already exists in index"_utf16);-- // 4. If index’s multiEntry flag is true and index key is an array key,- // and if index already contains a record with key equal to any of the subkeys of index key,- // and index’s unique flag is true,- // then this operation failed with a "ConstraintError" DOMException.- // Abort this algorithm without taking any further steps.- if (index_multi_entry && index_key_is_array && index_is_unique) {- for (auto const& subkey : index_key->subkeys()) {- if (index.has_record_with_key(*subkey))- return WebIDL::ConstraintError::create("Record already exists in index"_utf16);- }- }-- // 5. If index’s multiEntry flag is false, or if index key is not an array key- // then store a record in index containing index key as its key and key as its value.- // The record is stored in index’s list of records such that the list is sorted primarily on the records keys,- // and secondarily on the records values, in ascending order.- if (!index_multi_entry || !index_key_is_array) {- IndexRecord index_record = {- .key = *index_key,- .value = key,- };- index.store_a_record(index_record);- }-- // 6. If index’s multiEntry flag is true and index key is an array key,- // then for each subkey of the subkeys of index key store a record in index containing subkey as its key and key as its value.- // The records are stored in index’s list of records such that the list is sorted primarily on the records keys,- // and secondarily on the records values, in ascending order.- if (index_multi_entry && index_key_is_array) {- for (auto const& subkey : index_key->subkeys()) {- IndexRecord index_record = {- .key = *subkey,- .value = key,- };- index.store_a_record(index_record);- }- }-- return {};-}--// https://w3c.github.io/IndexedDB/#store-a-record-into-an-object-store-WebIDL::ExceptionOr<GC::Ptr<Key>> store_a_record_into_an_object_store(JS::Realm& realm, GC::Ref<ObjectStore> store, JS::Value value, GC::Ptr<Key> key, bool no_overwrite)-{- // 1. If store uses a key generator, then:- if (store->uses_a_key_generator()) {- // 1. If key is undefined, then:- if (key == nullptr) {- // 1. Let key be the result of generating a key for store.- auto maybe_key = store->generate_a_key();-- // 2. If key is failure, then this operation failed with a "ConstraintError" DOMException. Abort this algorithm without taking any further steps.- if (maybe_key.is_error())- return WebIDL::ConstraintError::create(Utf16String::from_utf8_without_validation(maybe_key.error().string_literal()));-- key = Key::create_number(static_cast<double>(maybe_key.value()));-- // 3. If store also uses in-line keys, then run inject a key into a value using a key path with value, key and store’s key path.- if (store->uses_inline_keys())- inject_a_key_into_a_value_using_a_key_path(realm, value, GC::Ref(*key), store->key_path().value());- }-- // 2. Otherwise, run possibly update the key generator for store with key.- else {- store->possibly_update_the_key_generator(GC::Ref(*key));- }- }-- // 2. If the no-overwrite flag was given to these steps and is true, and a record already exists in store with its key equal to key,- // then this operation failed with a "ConstraintError" DOMException. Abort this algorithm without taking any further steps.- auto has_record = store->has_record_with_key(*key);- if (no_overwrite && has_record)- return WebIDL::ConstraintError::create("Record already exists"_utf16);-- // 3. If a record already exists in store with its key equal to key, then remove the record from store using delete records from an object store.- if (has_record) {- auto key_range = IDBKeyRange::create(key, key, IDBKeyRange::LowerOpen::No, IDBKeyRange::UpperOpen::No);- delete_records_from_an_object_store(store, key_range);- }-- // 4. Store a record in store containing key as its key and ! StructuredSerializeForStorage(value) as its value.- // The record is stored in the object store’s list of records such that the list is sorted according to the key of the records in ascending order.- ObjectStoreRecord record { *key, make<HTML::StorageSerializationRecord>(MUST(HTML::structured_serialize_for_storage(realm.vm(), value))) };- store->store_a_record(move(record));-- // 5. For each index which references store:- for (auto const& [name, index] : store->index_set()) {- // AD-HOC: An index whose creation request has not been processed yet gets the records of store once it is.- if (index->is_pending_creation())- continue;-- TRY(store_a_record_into_an_index(realm.global_object(), index, value, *key));- }-- // 6. Return key.- return key;-}--// AD-HOC: The spec deserializes stored records infallibly, but a record read back from storage can be-// corrupt or written by a newer format version, so treat failure as the "error occurs while-// reading the value from the underlying storage" case: a "NotReadableError" DOMException.-static WebIDL::ExceptionOr<JS::Value> deserialize_a_stored_record(JS::Realm& realm, HTML::StorageSerializationRecord const& serialized)-{- auto value = HTML::structured_deserialize(realm.vm(), serialized, realm);- if (value.is_exception())- return WebIDL::NotReadableError::create(realm, "Stored value could not be read"_utf16);- return value;-}--// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-createindex-// AD-HOC: The index creation itself is processed as an asynchronous request within the upgrade transaction, so the-// index gets the records that its object store has once the requests made before createIndex() are processed.-// If those records violate the index's unique flag, the upgrade transaction is aborted with a "ConstraintError"-// DOMException.-void queue_the_creation_of_an_index(GC::Ref<IDBObjectStore> handle, GC::Ref<Index> index)-{- auto& realm = HTML::relevant_realm(handle->relevant_global_object());- auto transaction = handle->transaction();- index->set_pending_creation(true);-- // NB: The request has no transaction, so that nothing observes it, and the events fired at it if the transaction- // aborts first go nowhere.- auto request = IDBRequest::create(transaction->connection()->relevant_global_scope().this_impl(), handle);- transaction->request_list().enqueue(request, GC::create_function(GC::Heap::the(), [&realm, transaction, index, request]() {- if (request->aborted())- return;-- index->set_pending_creation(false);- auto store_the_records_into_the_index = [&]() -> WebIDL::ExceptionOr<void> {- for (auto const& record : index->object_store()->records()) {- auto value = TRY(deserialize_a_stored_record(realm, *record.value));- TRY(store_a_record_into_an_index(realm.global_object(), index, value, record.key));- }- return {};- };- auto result = store_the_records_into_the_index();-- request->set_processed(true);-- if (result.is_exception()) {- abort_a_transaction(transaction, result.exception().get<GC::Ref<WebIDL::DOMException>>());- return;- }-- // NB: Finish up like a request whose success event nobody listens to: the transaction commits once its request- // list is empty, if it is inactive by then.- queue_a_database_task(GC::create_function(GC::Heap::the(), [&realm, transaction, request]() {- if (request->aborted())- return;-- transaction->request_list().remove(request);- if (transaction->state() == IDBTransaction::TransactionState::Inactive && transaction->request_list().is_empty())- commit_a_transaction(realm, transaction);- transaction->request_list().check_all_processed();- }));-- transaction->request_list().on_request_processed();- }));-}--// https://w3c.github.io/IndexedDB/#convert-a-value-to-a-key-range-WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> convert_a_value_to_a_key_range(JS::Realm& realm, Optional<JS::Value> value, bool null_disallowed)-{- // 1. If value is a key range, return value.- if (value.has_value()) {- if (auto key_range = Bindings::idb_key_range_from_value(*value))- return GC::Ref { *key_range };- }-- // 2. If value is undefined or is null, then throw a "DataError" DOMException if null disallowed flag is true, or return an unbounded key range otherwise.- if (!value.has_value() || (value.has_value() && (value->is_undefined() || value->is_null()))) {- if (null_disallowed)- return WebIDL::DataError::create("Value is undefined or null"_utf16);-- return IDBKeyRange::create({}, {}, IDBKeyRange::LowerOpen::No, IDBKeyRange::UpperOpen::No);- }-- // 3. Let key be the result of converting a value to a key with value. Rethrow any exceptions.- auto key = TRY(convert_a_value_to_a_key(realm, *value));-- // 4. If key is "invalid value" or "invalid type", throw a "DataError" DOMException.- if (key->is_invalid())- return WebIDL::DataError::create("Value is invalid"_utf16);-- // 5. Return a key range containing only key.- return IDBKeyRange::create(key, key, IDBKeyRange::LowerOpen::No, IDBKeyRange::UpperOpen::No);-}--// https://w3c.github.io/IndexedDB/#count-the-records-in-a-range-JS::Value count_the_records_in_a_range(RecordSource source, GC::Ref<IDBKeyRange> range)-{- // 1. Let count be the number of records, if any, in source’s list of records with key in range.- auto count = source.visit(- [range](GC::Ref<ObjectStore> object_store) {- return object_store->count_records_in_range(range);- },- [range](GC::Ref<Index> index) {- return index->count_records_in_range(range);- });-- // 2. Return count.- return JS::Value(count);-}--// https://w3c.github.io/IndexedDB/#retrieve-a-value-from-an-object-store-WebIDL::ExceptionOr<JS::Value> retrieve_a_value_from_an_object_store(JS::Realm& realm, GC::Ref<ObjectStore> store, GC::Ref<IDBKeyRange> range)-{- // 1. Let record be the first record in store’s list of records whose key is in range, if any.- auto record = store->first_in_range(range);-- // 2. If record was not found, return undefined.- if (!record.has_value())- return JS::js_undefined();-- // 3. Let serialized be record’s value. If an error occurs while reading the value from the underlying storage, return a newly created "NotReadableError" DOMException.- auto const& serialized = *record->value;-- // 4. Return ! StructuredDeserialize(serialized, targetRealm).- return deserialize_a_stored_record(realm, serialized);-}--// https://w3c.github.io/IndexedDB/#iterate-a-cursor-WebIDL::ExceptionOr<GC::Ptr<IDBCursor>> iterate_a_cursor(JS::Realm& realm, GC::Ref<IDBCursor> cursor, GC::Ptr<Key> key, GC::Ptr<Key> primary_key, u64 count)-{- // 1. Let source be cursor’s source.- auto source = cursor->internal_source();-- // 2. Let direction be cursor’s direction.- auto direction = cursor->direction();-- // 3. Assert: if primaryKey is given, source is an index and direction is "next" or "prev".- auto direction_is_next_or_prev = direction == CursorDirection::Next || direction == CursorDirection::Prev;- if (primary_key)- VERIFY(source.has<GC::Ref<Index>>() && direction_is_next_or_prev);-- // 4. Let records be the list of records in source.- Variant<ReadonlySpan<ObjectStoreRecord>, ReadonlySpan<IndexRecord>> records = source.visit(- [](GC::Ref<ObjectStore> object_store) -> Variant<ReadonlySpan<ObjectStoreRecord>, ReadonlySpan<IndexRecord>> {- return object_store->records();- },- [](GC::Ref<Index> index) -> Variant<ReadonlySpan<ObjectStoreRecord>, ReadonlySpan<IndexRecord>> {- return index->records();- });-- // 5. Let range be cursor’s range.- auto range = cursor->range();-- // 6. Let position be cursor’s position.- auto position = cursor->position();-- // 7. Let object store position be cursor’s object store position.- auto object_store_position = cursor->object_store_position();-- // 8. If count is not given, let count be 1.- // NOTE: This is handled by the default parameter-- auto next_requirements = [&](Variant<ObjectStoreRecord, IndexRecord> const& record) -> bool {- // * If key is defined:- if (key) {- // * The record’s key is greater than or equal to key.- if (!record.visit([&](auto const& inner_record) {- return Key::greater_than_or_equal(inner_record.key, *key);- }))- return false;- }-- // * If primaryKey is defined:- if (primary_key) {- auto const& inner_record = record.get<IndexRecord>();-- // * The record’s key is equal to key and the record’s value is greater than or equal to primaryKey- if (Key::equals(inner_record.key, *key)) {- if (!Key::greater_than_or_equal(inner_record.value, *primary_key))- return false;- }- // * The record’s key is greater than key.- else {- if (!Key::greater_than(inner_record.key, *key))- return false;- }- }-- // * If position is defined and source is an object store:- if (position && source.has<GC::Ref<ObjectStore>>()) {- auto const& inner_record = record.get<ObjectStoreRecord>();-- // * The record’s key is greater than position.- if (!Key::greater_than(inner_record.key, *position))- return false;- }-- // * If position is defined and source is an index:- if (position && source.has<GC::Ref<Index>>()) {- auto const& inner_record = record.get<IndexRecord>();-- // * The record’s key is equal to position and the record’s value is greater than object store position- if (Key::equals(inner_record.key, *position)) {- if (!Key::greater_than(inner_record.value, *object_store_position))- return false;- }- // * The record’s key is greater than position.- else {- if (!Key::greater_than(inner_record.key, *position))- return false;- }- }-- // * The record’s key is in range.- return record.visit(- [&](auto const& inner_record) {- return range->is_in_range(inner_record.key);- });- };-- auto next_unique_requirements = [&](Variant<ObjectStoreRecord, IndexRecord> const& record) -> bool {- // * If key is defined:- if (key) {- // * The record’s key is greater than or equal to key.- if (!record.visit([&](auto const& inner_record) {- return Key::greater_than_or_equal(inner_record.key, *key);- }))- return false;- }-- // * If position is defined:- if (position) {- // * The record’s key is greater than position.- if (!record.visit([&](auto const& inner_record) {- return Key::greater_than(inner_record.key, *position);- }))- return false;- }-- // * The record’s key is in range.- return record.visit(- [&](auto const& inner_record) {- return range->is_in_range(inner_record.key);- });- };-- auto prev_requirements = [&](Variant<ObjectStoreRecord, IndexRecord> const& record) -> bool {- // * If key is defined:- if (key) {- // * The record’s key is less than or equal to key.- if (!record.visit([&](auto const& inner_record) {- return Key::less_than_or_equal(inner_record.key, *key);- }))- return false;- }-- // * If primaryKey is defined:- if (primary_key) {- auto const& inner_record = record.get<IndexRecord>();-- // * The record’s key is equal to key and the record’s value is less than or equal to primaryKey- if (Key::equals(inner_record.key, *key)) {- if (!Key::less_than_or_equal(inner_record.value, *primary_key))- return false;- }- // * The record’s key is less than key.- else {- if (!Key::less_than(inner_record.key, *key))- return false;- }- }-- // * If position is defined and source is an object store:- if (position && source.has<GC::Ref<ObjectStore>>()) {- auto const& inner_record = record.get<ObjectStoreRecord>();-- // * The record’s key is less than position.- if (!Key::less_than(inner_record.key, *position))- return false;- }-- // * If position is defined and source is an index:- if (position && source.has<GC::Ref<Index>>()) {- auto const& inner_record = record.get<IndexRecord>();-- // * The record’s key is equal to position and the record’s value is less than object store position- if (Key::equals(inner_record.key, *position)) {- if (!Key::less_than(inner_record.value, *object_store_position))- return false;- }- // * The record’s key is less than position.- else {- if (!Key::less_than(inner_record.key, *position))- return false;- }- }-- // * The record’s key is in range.- return record.visit(- [&](auto const& inner_record) {- return range->is_in_range(inner_record.key);- });- };-- auto prev_unique_requirements = [&](Variant<ObjectStoreRecord, IndexRecord> const& record) -> bool {- // * If key is defined:- if (key) {- // * The record’s key is less than or equal to key.- if (!record.visit([&](auto const& inner_record) {- return Key::less_than_or_equal(inner_record.key, *key);- }))- return false;- }-- // * If position is defined:- if (position) {- // * The record’s key is less than position.- if (!record.visit([&](auto const& inner_record) {- return Key::less_than(inner_record.key, *position);- }))- return false;- }-- // * The record’s key is in range.- return record.visit(- [&](auto const& inner_record) {- return range->is_in_range(inner_record.key);- });- };-- // 9. While count is greater than 0:- Variant<Empty, ObjectStoreRecord, IndexRecord> found_record;- while (count > 0) {- // 1. Switch on direction:- switch (direction) {- case CursorDirection::Next: {- // Let found record be the first record in records which satisfy all of the following requirements:- found_record = records.visit([&](auto content) -> Variant<Empty, ObjectStoreRecord, IndexRecord> {- auto value = content.first_matching(next_requirements);- if (value.has_value())- return *value;-- return Empty {};- });- break;- }- case CursorDirection::Nextunique: {- // Let found record be the first record in records which satisfy all of the following requirements:- found_record = records.visit([&](auto content) -> Variant<Empty, ObjectStoreRecord, IndexRecord> {- auto value = content.first_matching(next_unique_requirements);- if (value.has_value())- return *value;-- return Empty {};- });- break;- }- case CursorDirection::Prev: {- // Let found record be the last record in records which satisfy all of the following requirements:- found_record = records.visit([&](auto content) -> Variant<Empty, ObjectStoreRecord, IndexRecord> {- auto value = content.last_matching(prev_requirements);- if (value.has_value())- return *value;-- return Empty {};- });- break;- }-- case CursorDirection::Prevunique: {- // Let temp record be the last record in records which satisfy all of the following requirements:- auto temp_record = records.visit([&](auto content) -> Variant<Empty, ObjectStoreRecord, IndexRecord> {- auto value = content.last_matching(prev_unique_requirements);- if (value.has_value())- return *value;-- return Empty {};- });-- // If temp record is defined, let found record be the first record in records whose key is equal to temp record’s key.- found_record = Empty {};- if (!temp_record.has<Empty>()) {- auto temp_record_key = temp_record.visit(- [](Empty) -> GC::Ref<Key> { VERIFY_NOT_REACHED(); },- [](auto const& record) { return record.key; });-- found_record = records.visit([&](auto content) -> Variant<Empty, ObjectStoreRecord, IndexRecord> {- auto value = content.first_matching([&](auto const& content_record) {- return Key::equals(content_record.key, temp_record_key);- });- if (value.has_value())- return *value;-- return Empty {};- });- }-- break;- }- }-- // 2. If found record is not defined, then:- if (found_record.has<Empty>()) {- // 1. Set cursor’s key to undefined.- cursor->set_key(nullptr);-- // 2. If source is an index, set cursor’s object store position to undefined.- if (source.has<GC::Ref<Index>>())- cursor->set_object_store_position(nullptr);-- // 3. If cursor’s key only flag is false, set cursor’s value to undefined.- if (!cursor->key_only())- cursor->set_value(JS::js_undefined());-- // 4. Return null.- return nullptr;- }-- // 3. Let position be found record’s key.- position = found_record.visit(- [](Empty) -> GC::Ref<Key> { VERIFY_NOT_REACHED(); },- [](auto val) { return val.key; });-- // 4. If source is an index, let object store position be found record’s value.- if (source.has<GC::Ref<Index>>())- object_store_position = found_record.get<IndexRecord>().value;-- // 5. Decrease count by 1.- count--;- }-- // 10. Set cursor’s position to position.- cursor->set_position(position);-- // 11. If source is an index, set cursor’s object store position to object store position.- if (source.has<GC::Ref<Index>>())- cursor->set_object_store_position(object_store_position);-- // 12. Set cursor’s key to found record’s key.- cursor->set_key(found_record.visit(- [](Empty) -> GC::Ref<Key> { VERIFY_NOT_REACHED(); },- [](auto val) { return val.key; }));-- // 13. If cursor’s key only flag is false, then:- if (!cursor->key_only()) {-- // 1. Let serialized be found record’s value if source is an object store, or found record’s referenced value otherwise.- auto const& serialized = source.visit(- [&](GC::Ref<ObjectStore>) -> HTML::StorageSerializationRecord const& {- return *found_record.get<ObjectStoreRecord>().value;- },- [&](GC::Ref<Index> index) -> HTML::StorageSerializationRecord const& {- return index->referenced_value(found_record.get<IndexRecord>());- });-- // 2. Set cursor’s value to ! StructuredDeserialize(serialized, targetRealm)- cursor->set_value(TRY(deserialize_a_stored_record(realm, serialized)));- }-- // 14. Set cursor’s got value flag to true.- cursor->set_got_value(true);-- // 15. Return cursor.- return cursor;-}--// https://w3c.github.io/IndexedDB/#clear-an-object-store-JS::Value clear_an_object_store(GC::Ref<ObjectStore> store)-{- // 1. Remove all records from store.- store->clear_records();-- // 2. In all indexes which reference store, remove all records.- for (auto const& [name, index] : store->index_set()) {- index->clear_records();- }-- // 3. Return undefined.- return JS::js_undefined();-}--// https://w3c.github.io/IndexedDB/#retrieve-a-key-from-an-object-store-JS::Value retrieve_a_key_from_an_object_store(JS::Realm& realm, GC::Ref<ObjectStore> store, GC::Ref<IDBKeyRange> range)-{- // 1. Let record be the first record in store’s list of records whose key is in range, if any.- auto record = store->first_in_range(range);-- // 2. If record was not found, return undefined.- if (!record.has_value())- return JS::js_undefined();-- // 3. Return the result of converting a key to a value with record’s key.- return convert_a_key_to_a_value(realm, record.value().key);-}--// https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-object-store-WebIDL::ExceptionOr<GC::Ref<JS::Array>> retrieve_multiple_items_from_an_object_store(JS::Realm& realm, GC::Ref<ObjectStore> store, GC::Ref<IDBKeyRange> range, RecordKind kind, CursorDirection direction, Optional<WebIDL::UnsignedLong> count)-{- // 1. If count is not given or is 0 (zero), let count be infinity.- if (count.has_value() && *count == 0)- count = OptionalNone();-- // 2. Let records be an empty list of records.- GC::ConservativeVector<ObjectStoreRecord> records;-- // 3. If direction is "next" or "nextunique", set records to the first count of store’s list of records whose key is in range.- if (direction == CursorDirection::Next || direction == CursorDirection::Nextunique) {- records.extend(store->first_n_in_range(range, count));- }-- // 4. If direction is "prev" or "prevunique", set records to the last count of store’s list of records whose key is in range.- if (direction == CursorDirection::Prev || direction == CursorDirection::Prevunique) {- records.extend(store->last_n_in_range(range, count));- }-- // 5. Let list be an empty list.- auto list = MUST(JS::Array::create(realm, records.size()));-- // 6. For each record of records, switching on kind:- for (u32 i = 0; i < records.size(); ++i) {- auto& record = records[i];-- switch (kind) {- case RecordKind::Key: {- // 1. Let key be the result of converting a key to a value with record’s key.- auto key = convert_a_key_to_a_value(realm, record.key);-- // 2. Append key to list.- MUST(list->create_data_property_or_throw(i, key));- break;- }- case RecordKind::Value: {- // 1. Let serialized be record’s value.- auto const& serialized = *record.value;-- // 2. Let value be ! StructuredDeserialize(serialized, targetRealm).- auto entry = TRY(deserialize_a_stored_record(realm, serialized));-- // 3. Append value to list.- MUST(list->create_data_property_or_throw(i, entry));- break;- }- case RecordKind::Record: {- // 1. Let key be the record’s key.- auto key = record.key;-- // 2. Let serialized be record’s value.- auto const& serialized = *record.value;-- // 3. Let value be ! StructuredDeserialize(serialized, targetRealm).- auto value = TRY(deserialize_a_stored_record(realm, serialized));-- // 4. Let recordSnapshot be a new record snapshot with its key set to key, value set to value, and primary key set to key.- auto record_snapshot = IDBRecord::create(key, value, key);-- // 5. Append recordSnapshot to list.- Bindings::append_idb_record(realm, list, i, record_snapshot);- break;- }- }- }-- // 7. Return list.- return list;-}--// https://w3c.github.io/IndexedDB/#retrieve-a-referenced-value-from-an-index-WebIDL::ExceptionOr<JS::Value> retrieve_a_referenced_value_from_an_index(JS::Realm& realm, GC::Ref<Index> index, GC::Ref<IDBKeyRange> range)-{- // 1. Let record be the first record in index’s list of records whose key is in range, if any.- auto record = index->first_in_range(range);-- // 2. If record was not found, return undefined.- if (!record.has_value())- return JS::js_undefined();-- // 3. Let serialized be record’s referenced value.- auto serialized = index->referenced_value(*record);-- // 4. Return ! StructuredDeserialize(serialized, targetRealm).- return deserialize_a_stored_record(realm, serialized);-}--// https://w3c.github.io/IndexedDB/#retrieve-a-value-from-an-index-JS::Value retrieve_a_value_from_an_index(JS::Realm& realm, GC::Ref<Index> index, GC::Ref<IDBKeyRange> range)-{- // 1. Let record be the first record in index’s list of records whose key is in range, if any.- auto record = index->first_in_range(range);-- // 2. If record was not found, return undefined.- if (!record.has_value())- return JS::js_undefined();-- // 3. Return the result of converting a key to a value with record’s value.- return convert_a_key_to_a_value(realm, record->value);-}--// https://w3c.github.io/IndexedDB/#queue-a-database-task-void queue_a_database_task(GC::Ref<GC::Function<void()>> steps)-{- // To queue a database task, perform queue a task on the database access task source.- HTML::queue_a_task(HTML::Task::Source::DatabaseAccess, nullptr, nullptr, steps);-}--// https://w3c.github.io/IndexedDB/#cleanup-indexed-database-transactions-bool cleanup_indexed_database_transactions(GC::Ref<HTML::EventLoop> event_loop)-{- bool has_matching_event_loop = false;-- Database::for_each_database([&has_matching_event_loop, event_loop](Database& database) {- for (auto const& connection : database.associated_connections_as_root_vector()) {- for (auto const& transaction : connection->transactions()) {- // 2. For each transaction transaction with cleanup event loop matching the current event loop:- if (transaction->cleanup_event_loop() == event_loop) {- has_matching_event_loop = true;-- // 1. Set transaction’s state to inactive.- VERIFY(transaction->state() == IDBTransaction::TransactionState::Active);- transaction->set_state(IDBTransaction::TransactionState::Inactive);-- // https://w3c.github.io/IndexedDB/#transaction-commit- // The implementation must attempt to commit an inactive transaction when all requests placed- // against the transaction have completed and their returned results handled, no new requests have- // been placed against the transaction, and the transaction has not been aborted-- // FIXME: We skip committing if the transaction is waiting for prior writes.- // Update the steps here text if this becomes explicit in the spec:- // https://github.com/w3c/IndexedDB/issues/489#issuecomment-3994928473- if (!transaction->request_list().execution_is_blocked() && transaction->request_list().is_empty())- commit_a_transaction(HTML::relevant_realm(transaction->relevant_global_object()), transaction);-- // 2. Clear transaction’s cleanup event loop.- transaction->set_cleanup_event_loop(nullptr);- }- }- }- });-- // 1. If there are no transactions with cleanup event loop matching the current event loop, return false.- // 3. Return true.- return has_matching_event_loop;-}--// https://w3c.github.io/IndexedDB/#is-a-potentially-valid-key-range-bool is_a_potentially_valid_key_range(JS::Realm& realm, JS::Value value)-{- // 1. If value is a key range, return true.- if (Bindings::idb_key_range_from_value(value))- return true;-- // 2. Let key be the result of converting a value to a key with value.- // 3. If key is "invalid type" return false.- // 4. Else return true.- // AD-HOC: The type of value is checked instead, which is what decides whether the conversion returns- // "invalid type", so that the getters of an array's elements do not run twice.- if (value.is_number() || value.is_string())- return true;- if (value.is_object() && value.as_object().is_date())- return true;- if (value.is_object() && (is<JS::TypedArrayBase>(value.as_object()) || is<JS::ArrayBuffer>(value.as_object()) || is<JS::DataView>(value.as_object())))- return true;- if (value.is_object() && MUST(value.is_array(realm.vm())))- return true;- return false;-}--// https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-index-WebIDL::ExceptionOr<GC::Ref<JS::Array>> retrieve_multiple_items_from_an_index(JS::Realm& target_realm, GC::Ref<Index> index, GC::Ref<IDBKeyRange> range, RecordKind kind, CursorDirection direction, Optional<WebIDL::UnsignedLong> count)-{- // 1. If count is not given or is 0 (zero), let count be infinity.- if (count.has_value() && *count == 0)- count = OptionalNone();-- // 2. Let records be an empty list of records.- GC::ConservativeVector<IndexRecord> records;-- // 3. Switching on direction:- switch (direction) {- // "next"- case CursorDirection::Next: {- // 1. Set records to the first count of index’s list of records whose key is in range.- records.extend(index->first_n_in_range(range, count));- break;- }- // "nextunique"- case CursorDirection::Nextunique: {- // 1. Let rangeRecords be a list containing the index’s list of records whose key is in range.- auto range_records = index->first_n_in_range(range, OptionalNone());-- // 2. Let rangeRecordsLength be rangeRecords’s size.- auto range_records_length = range_records.size();-- // 3. Let i be 0.- size_t i = 0;-- // x. Append |rangeRecords[0]| to records.- // FIXME: https://github.com/w3c/IndexedDB/issues/480- if (range_records_length > 0)- records.append(range_records[0]);-- // 4. While i is less than rangeRecordsLength, then:- while (i + 1 < range_records_length) {- // 1. Increase i by 1.- i++;-- // 2. if record’s size is equal to count, then break.- if (records.size() == count)- break;-- // 3. If the result of comparing two keys using the keys from |rangeRecords[i]| and |rangeRecords[i-1]| is equal, then continue.- if (Key::equals(range_records[i].key, range_records[i - 1].key))- continue;-- // 4. Else append |rangeRecords[i]| to records.- records.append(range_records[i]);- }-- break;- }- // "prev"- case CursorDirection::Prev: {- // 1. Set records to the last count of index’s list of records whose key is in range.- records.extend(index->last_n_in_range(range, count));- break;- }- // "prevunique"- case CursorDirection::Prevunique: {- // 1. Let rangeRecords be a list containing the index’s list of records whose key is in range.- auto range_records = index->first_n_in_range(range, OptionalNone());-- // 2. Let rangeRecordsLength be rangeRecords’s size.- auto range_records_length = range_records.size();-- // 3. Let i be 0.- size_t i = 0;-- // x. Append |rangeRecords[0]| to records.- // FIXME: https://github.com/w3c/IndexedDB/issues/480- if (range_records_length > 0)- records.append(range_records[0]);-- // 4. While i is less than rangeRecordsLength, then:- while (i + 1 < range_records_length) {- // 1. Increase i by 1.- i++;-- // 2. if record’s size is equal to count, then break.- if (records.size() == count)- break;-- // 3. If the result of comparing two keys using the keys from |rangeRecords[i]| and |rangeRecords[i-1]| is equal, then continue.- if (Key::equals(range_records[i].key, range_records[i - 1].key))- continue;-- // 4. Else prepend |rangeRecords[i]| to records.- records.prepend(range_records[i]);- }-- break;- }- }-- // 4. Let list be an empty list.- auto list = MUST(JS::Array::create(target_realm, records.size()));-- // 5. For each record of records, switching on kind:- for (u32 i = 0; i < records.size(); ++i) {- auto& record = records[i];-- switch (kind) {- // "key"- case RecordKind::Key: {- // 1. Let key be the result of converting a key to a value with record’s value.- auto key = convert_a_key_to_a_value(target_realm, record.value);-- // 2. Append key to list.- MUST(list->create_data_property_or_throw(i, key));- break;- }- // "value"- case RecordKind::Value: {- // 1. Let serialized be record’s referenced value.- auto serialized = index->referenced_value(record);-- // 2. Let value be ! StructuredDeserialize(serialized, targetRealm).- auto value = TRY(deserialize_a_stored_record(target_realm, serialized));-- // 3. Append value to list.- MUST(list->create_data_property_or_throw(i, value));- break;- }-- // "record"- case RecordKind::Record: {- // 1. Let index key be the record’s key.- auto index_key = record.key;-- // 2. Let key be the record’s value.- auto key = record.value;-- // 3. Let serialized be record’s referenced value.- auto serialized = index->referenced_value(record);-- // 4. Let value be ! StructuredDeserialize(serialized, targetRealm).- auto value = TRY(deserialize_a_stored_record(target_realm, serialized));-- // 5. Let recordSnapshot be a new record snapshot with its key set to index key, value set to value, and primary key set to key.- auto record_snapshot = IDBRecord::create(index_key, value, key);-- // 6. Append recordSnapshot to list.- Bindings::append_idb_record(target_realm, list, i, record_snapshot);- break;- }- }- }-- // 6. Return list.- return list;-}--// https://w3c.github.io/IndexedDB/#create-a-request-to-retrieve-multiple-items-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> create_a_request_to_retrieve_multiple_items(JS::Realm& realm, IDBRequestSource source_handle, RecordKind kind, JS::Value query_or_options, Optional<WebIDL::UnsignedLong> count)-{- auto& vm = realm.vm();-- // 1. Let source be an index or an object store from sourceHandle.- // If sourceHandle is an index handle, then source is the index handle’s associated index.- // Otherwise, source is the object store handle’s associated object store.- auto source = source_handle.visit(- [](Empty) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBCursor>) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBIndex> index) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { return index->index(); },- [](GC::Ref<IDBObjectStore> object_store) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { return object_store->store(); });-- // 2. If source has been deleted, throw an "InvalidStateError" DOMException.- // 3. If source is an index and source’s object store has been deleted, throw an "InvalidStateError" DOMException.- auto is_source_or_object_store_deleted = source.visit(- [](GC::Ref<ObjectStore> object_store) { return object_store->is_deleted(); },- [](GC::Ref<Index> index) { return index->is_deleted() || index->object_store()->is_deleted(); });- if (is_source_or_object_store_deleted)- return WebIDL::InvalidStateError::create("Source or its object store has been deleted"_utf16);-- // 4. Let transaction be sourceHandle’s transaction.- auto transaction = source_handle.visit(- [](Empty) -> GC::Ref<IDBTransaction> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBCursor>) -> GC::Ref<IDBTransaction> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBIndex> index) -> GC::Ref<IDBTransaction> { return index->transaction(); },- [](GC::Ref<IDBObjectStore> object_store) -> GC::Ref<IDBTransaction> { return object_store->transaction(); });-- // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while creating retrieve multiple items request"_utf16);-- // 6. Let range be a key range.- GC::Ptr<IDBKeyRange> range;-- // 7. Let direction be a cursor direction.- CursorDirection direction = CursorDirection::Next;-- // 8. If running is a potentially valid key range with queryOrOptions is true, then:- // AD-HOC: Check if query_or_options is null following https://github.com/w3c/IndexedDB/issues/475- if (query_or_options.is_nullish() || is_a_potentially_valid_key_range(realm, query_or_options)) {- // 1. Set range to the result of converting a value to a key range with queryOrOptions. Rethrow any exceptions.- range = TRY(convert_a_value_to_a_key_range(realm, query_or_options));-- // 2. Set direction to "next".- direction = CursorDirection::Next;- }-- // 9. Else:- else {- // 1. Set range to the result of converting a value to a key range with queryOrOptions["query"]. Rethrow any exceptions.- range = TRY(convert_a_value_to_a_key_range(realm, TRY(query_or_options.get(vm, "query"_utf16))));-- // 2. Set count to queryOrOptions["count"].- count = TRY(TRY(query_or_options.get(vm, "count"_utf16)).to_u32(vm));-- // 3. Set direction to queryOrOptions["direction"].- auto direction_value = TRY(TRY(query_or_options.get(vm, "direction"_utf16)).to_utf16_string(vm));- if (direction_value == "next"_utf16)- direction = CursorDirection::Next;- else if (direction_value == "nextunique"_utf16)- direction = CursorDirection::Nextunique;- else if (direction_value == "prev"_utf16)- direction = CursorDirection::Prev;- else if (direction_value == "prevunique"_utf16)- direction = CursorDirection::Prevunique;- }-- // 10. Let operation be an algorithm to run.- auto operation = source.visit(- // 11. If source is an index, set operation to retrieve multiple items from an index with targetRealm, source, range, kind, direction, and count if given.- [&](GC::Ref<Index> index) {- return GC::create_function(GC::Heap::the(),- [&realm, index, range, kind, direction, count]() -> WebIDL::ExceptionOr<JS::Value> {- return TRY(retrieve_multiple_items_from_an_index(realm, index, GC::Ref(*range), kind, direction, count));- });- },- // 12. Else set operation to retrieve multiple items from an object store with targetRealm, source, range, kind, direction, and count if given.- [&](GC::Ref<ObjectStore> object_store) {- return GC::create_function(GC::Heap::the(),- [&realm, object_store, range, kind, direction, count]() -> WebIDL::ExceptionOr<JS::Value> {- return TRY(retrieve_multiple_items_from_an_object_store(realm, object_store, GC::Ref(*range), kind, direction, count));- });- });-- // 13. Return the result (an IDBRequest) of running asynchronously execute a request with sourceHandle and operation.- auto result = asynchronously_execute_a_request(realm, source_handle, operation);- dbgln_if(IDB_DEBUG, "Executing request for creating retrieve multiple items request with uuid {}", result->uuid());- return result;-}--WebIDL::ExceptionOr<GC::Ref<IDBRequest>> create_a_request_to_retrieve_multiple_items(JS::Realm& realm, IDBRequestSource source_handle, RecordKind kind, RetrieveMultipleItemsOptions const& options)-{- // 1. Let source be an index or an object store from sourceHandle.- // If sourceHandle is an index handle, then source is the index handle’s associated index.- // Otherwise, source is the object store handle’s associated object store.- auto source = source_handle.visit(- [](Empty) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBCursor>) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBIndex> index) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { return index->index(); },- [](GC::Ref<IDBObjectStore> object_store) -> Variant<GC::Ref<ObjectStore>, GC::Ref<Index>> { return object_store->store(); });-- // 2. If source has been deleted, throw an "InvalidStateError" DOMException.- // 3. If source is an index and source’s object store has been deleted, throw an "InvalidStateError" DOMException.- auto is_source_or_object_store_deleted = source.visit(- [](GC::Ref<ObjectStore> object_store) { return object_store->is_deleted(); },- [](GC::Ref<Index> index) { return index->is_deleted() || index->object_store()->is_deleted(); });- if (is_source_or_object_store_deleted)- return WebIDL::InvalidStateError::create("Source or its object store has been deleted"_utf16);-- // 4. Let transaction be sourceHandle’s transaction.- auto transaction = source_handle.visit(- [](Empty) -> GC::Ref<IDBTransaction> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBCursor>) -> GC::Ref<IDBTransaction> { VERIFY_NOT_REACHED(); },- [](GC::Ref<IDBIndex> index) -> GC::Ref<IDBTransaction> { return index->transaction(); },- [](GC::Ref<IDBObjectStore> object_store) -> GC::Ref<IDBTransaction> { return object_store->transaction(); });-- // 5. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.- if (!transaction->is_active())- return WebIDL::TransactionInactiveError::create("Transaction is not active while creating retrieve multiple items request"_utf16);-- // 6. Let range be a key range.- auto range = TRY(convert_a_value_to_a_key_range(realm, options.query));-- // 10. Let operation be an algorithm to run.- auto operation = source.visit(- // 11. If source is an index, set operation to retrieve multiple items from an index with targetRealm, source, range, kind, direction, and count if given.- [&](GC::Ref<Index> index) {- return GC::create_function(GC::Heap::the(),- [&realm, index, range, kind, direction = options.direction, count = options.count]() -> WebIDL::ExceptionOr<JS::Value> {- return TRY(retrieve_multiple_items_from_an_index(realm, index, range, kind, direction, count));- });- },- // 12. Else set operation to retrieve multiple items from an object store with targetRealm, source, range, kind, direction, and count if given.- [&](GC::Ref<ObjectStore> object_store) {- return GC::create_function(GC::Heap::the(),- [&realm, object_store, range, kind, direction = options.direction, count = options.count]() -> WebIDL::ExceptionOr<JS::Value> {- return TRY(retrieve_multiple_items_from_an_object_store(realm, object_store, range, kind, direction, count));- });- });-- // 13. Return the result (an IDBRequest) of running asynchronously execute a request with sourceHandle and operation.- auto result = asynchronously_execute_a_request(realm, source_handle, operation);- dbgln_if(IDB_DEBUG, "Executing request for creating retrieve multiple items request with uuid {}", result->uuid());- return result;-}--JS::ThrowCompletionOr<JS::Value> convert_a_key_path_to_a_value(JS::Realm& realm, KeyPath const& key_path)-{- return key_path.visit(- [&](Utf16String const& value) -> JS::ThrowCompletionOr<JS::Value> {- return JS::PrimitiveString::create(realm.vm(), value);- },- [&](Vector<Utf16String> const& value) -> JS::ThrowCompletionOr<JS::Value> {- return JS::Array::create_from<Utf16String>(realm, value.span(), [&](auto const& entry) -> JS::Value {- return JS::PrimitiveString::create(realm.vm(), entry);- });- });-}--}--namespace Web::Bindings {--void set_idb_request_result(JS::Realm& realm, IndexedDB::IDBRequest& request, GC::Ref<IndexedDB::IDBDatabase> database)-{- request.set_result(Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, database));-}--void resolve_database_info_list_promise(JS::Realm& realm, WebIDL::Promise const& promise, Vector<GC::Weak<IndexedDB::Database>> const& databases)-{- auto result = MUST(JS::Array::create(realm, 0));-- u32 result_index = 0;- for (auto const& db : databases) {- if (!db)- continue;-- // INTEROP: A database's version is not reported until its upgrade transaction commits, so that databases()- // does not pick up changes that have not been committed.- auto version = db->version();- if (auto upgrade_transaction = db->upgrade_transaction())- version = upgrade_transaction->original_version();-- if (version == 0)- continue;-- auto info = JS::Object::create(realm, realm.intrinsics().object_prototype());- MUST(info->create_data_property("name"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), db->name())));- MUST(info->create_data_property("version"_utf16_fly_string, JS::Value(version)));- MUST(result->create_data_property_or_throw(result_index++, info));- }-- WebIDL::resolve_promise(promise, result);-}--void append_idb_record(JS::Realm& realm, JS::Array& list, u32 index, GC::Ref<IndexedDB::IDBRecord> record)-{- MUST(list.create_data_property_or_throw(index, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, record)));-}--JS::Value idb_cursor_result(JS::Realm& realm, GC::Ptr<IndexedDB::IDBCursor> cursor)-{- if (!cursor)- return JS::js_null();- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, cursor);-}--Optional<JS::Value> key_path_value_for_blob_or_file(JS::Realm& realm, JS::Value value, StringView identifier)-{- auto* blob = value.is_object() ? Bindings::impl_from<FileAPI::Blob>(&value.as_object()) : nullptr;- if (blob) {- if (identifier == "size")- return JS::Value(blob->size());- if (identifier == "type")- return JS::PrimitiveString::create(realm.vm(), blob->type());- }-- if (auto* file = value.is_object() ? Bindings::impl_from<FileAPI::File>(&value.as_object()) : nullptr) {- if (identifier == "name")- return JS::PrimitiveString::create(realm.vm(), file->name());- if (identifier == "lastModified")- return JS::Value(static_cast<double>(file->last_modified()));- }-- return {};-}--GC::Ptr<IndexedDB::IDBKeyRange> idb_key_range_from_value(JS::Value value)-{- return Bindings::key_range_from_value(value);-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.hdeleted file mode 100644index 5d13ffe3942..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h+++ /dev/null@@ -1,90 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/StringView.h>-#include <AK/Variant.h>-#include <LibGC/RootVector.h>-#include <LibJS/Runtime/Realm.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Bindings/IDBCursor.h>-#include <LibWeb/Bindings/IDBObjectStore.h>-#include <LibWeb/HTML/DOMStringList.h>-#include <LibWeb/IndexedDB/IDBKeyRange.h>-#include <LibWeb/IndexedDB/IDBRequest.h>-#include <LibWeb/IndexedDB/Internal/Key.h>-#include <LibWeb/StorageAPI/StorageKey.h>-#include <LibWebCommon/WebIDL/Types.h>--namespace Web::IndexedDB {--class IDBCursor;--enum class RecordKind {- Key,- Value,- Record-};--using KeyPath = Variant<Utf16String, Vector<Utf16String>>;-using RecordSource = Variant<GC::Ref<ObjectStore>, GC::Ref<Index>>;--using RetrieveMultipleItemsOptions = Bindings::IDBGetAllOptions;--void open_a_database_connection(JS::Realm&, StorageAPI::StorageKey, Utf16String, Optional<u64>, GC::Ref<IDBRequest>, GC::Ref<GC::Function<void(WebIDL::ExceptionOr<GC::Ref<IDBDatabase>>)>>);-bool fire_a_version_change_event(JS::Realm&, Utf16FlyString const&, GC::Ref<DOM::EventTarget>, u64, Optional<u64>);-WebIDL::ExceptionOr<GC::Ref<Key>> convert_a_value_to_a_key(JS::Realm&, JS::Value, GC::RootVector<JS::Value> = {});-void close_a_database_connection(GC::Ref<IDBDatabase>, GC::Ptr<GC::Function<void()>> on_complete = nullptr, bool forced = false);-void upgrade_a_database(JS::Realm&, GC::Ref<IDBDatabase>, u64, GC::Ref<IDBRequest>, GC::Ref<GC::Function<void()>>);-void delete_a_database(JS::Realm&, StorageAPI::StorageKey, Utf16String, GC::Ref<IDBRequest>, GC::Ref<GC::Function<void(WebIDL::ExceptionOr<u64>)>>);-void abort_a_transaction(GC::Ref<IDBTransaction>, GC::Ptr<WebIDL::DOMException>);-JS::Value convert_a_key_to_a_value(JS::Realm&, GC::Ref<Key>);-JS::ThrowCompletionOr<JS::Value> convert_a_key_path_to_a_value(JS::Realm&, KeyPath const&);-bool is_valid_key_path(KeyPath const&);-GC::Ref<HTML::DOMStringList> create_a_sorted_name_list(Vector<String>);-GC::Ref<HTML::DOMStringList> create_a_sorted_name_list(Vector<Utf16String>);-void commit_a_transaction(JS::Realm&, GC::Ref<IDBTransaction>);-WebIDL::ExceptionOr<JS::Value> clone_in_realm(JS::Realm&, JS::Value, GC::Ref<IDBTransaction>);-WebIDL::ExceptionOr<GC::Ref<Key>> convert_a_value_to_a_multi_entry_key(JS::Realm&, JS::Value);-WebIDL::ExceptionOr<ErrorOr<JS::Value>> evaluate_key_path_on_a_value(JS::Realm&, JS::Value, KeyPath const&);-WebIDL::ExceptionOr<ErrorOr<GC::Ref<Key>>> extract_a_key_from_a_value_using_a_key_path(JS::Realm&, JS::Value, KeyPath const&, bool = false);-bool check_that_a_key_could_be_injected_into_a_value(JS::Realm&, JS::Value, KeyPath const&);-void fire_an_error_event(JS::Realm&, GC::Ref<IDBRequest>);-void fire_a_success_event(JS::Realm&, GC::Ref<IDBRequest>);-GC::Ref<IDBRequest> asynchronously_execute_a_request(JS::Realm&, IDBRequestSource, GC::Ref<GC::Function<WebIDL::ExceptionOr<JS::Value>()>>, GC::Ptr<IDBRequest> = nullptr);-void inject_a_key_into_a_value_using_a_key_path(JS::Realm&, JS::Value, GC::Ref<Key>, KeyPath const&);-JS::Value delete_records_from_an_object_store(GC::Ref<ObjectStore>, GC::Ref<IDBKeyRange>);-WebIDL::ExceptionOr<GC::Ptr<Key>> store_a_record_into_an_object_store(JS::Realm&, GC::Ref<ObjectStore>, JS::Value, GC::Ptr<Key>, bool);-void queue_the_creation_of_an_index(GC::Ref<IDBObjectStore>, GC::Ref<Index>);-WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> convert_a_value_to_a_key_range(JS::Realm&, Optional<JS::Value>, bool = false);-JS::Value count_the_records_in_a_range(RecordSource, GC::Ref<IDBKeyRange>);-WebIDL::ExceptionOr<JS::Value> retrieve_a_value_from_an_object_store(JS::Realm&, GC::Ref<ObjectStore>, GC::Ref<IDBKeyRange>);-WebIDL::ExceptionOr<GC::Ptr<IDBCursor>> iterate_a_cursor(JS::Realm&, GC::Ref<IDBCursor>, GC::Ptr<Key> = nullptr, GC::Ptr<Key> = nullptr, u64 = 1);-JS::Value clear_an_object_store(GC::Ref<ObjectStore>);-JS::Value retrieve_a_key_from_an_object_store(JS::Realm&, GC::Ref<ObjectStore>, GC::Ref<IDBKeyRange>);-WebIDL::ExceptionOr<JS::Value> retrieve_a_referenced_value_from_an_index(JS::Realm&, GC::Ref<Index>, GC::Ref<IDBKeyRange>);-JS::Value retrieve_a_value_from_an_index(JS::Realm&, GC::Ref<Index>, GC::Ref<IDBKeyRange>);-void queue_a_database_task(GC::Ref<GC::Function<void()>>);-bool cleanup_indexed_database_transactions(GC::Ref<HTML::EventLoop>);-bool is_a_potentially_valid_key_range(JS::Realm&, JS::Value);-WebIDL::ExceptionOr<GC::Ref<JS::Array>> retrieve_multiple_items_from_an_object_store(JS::Realm&, GC::Ref<ObjectStore>, GC::Ref<IDBKeyRange>, RecordKind, CursorDirection, Optional<WebIDL::UnsignedLong>);-WebIDL::ExceptionOr<GC::Ref<JS::Array>> retrieve_multiple_items_from_an_index(JS::Realm&, GC::Ref<Index>, GC::Ref<IDBKeyRange>, RecordKind, CursorDirection, Optional<WebIDL::UnsignedLong>);-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> create_a_request_to_retrieve_multiple_items(JS::Realm&, IDBRequestSource, RecordKind, JS::Value, Optional<WebIDL::UnsignedLong>);-WebIDL::ExceptionOr<GC::Ref<IDBRequest>> create_a_request_to_retrieve_multiple_items(JS::Realm&, IDBRequestSource, RecordKind, RetrieveMultipleItemsOptions const&);--}--namespace Web::Bindings {--WEB_API void set_idb_request_result(JS::Realm&, IndexedDB::IDBRequest&, GC::Ref<IndexedDB::IDBDatabase>);-WEB_API void resolve_database_info_list_promise(JS::Realm&, WebIDL::Promise const&, Vector<GC::Weak<IndexedDB::Database>> const&);-WEB_API void append_idb_record(JS::Realm&, JS::Array&, u32, GC::Ref<IndexedDB::IDBRecord>);-WEB_API JS::Value idb_cursor_result(JS::Realm&, GC::Ptr<IndexedDB::IDBCursor>);-WEB_API Optional<JS::Value> key_path_value_for_blob_or_file(JS::Realm&, JS::Value, StringView);-WEB_API GC::Ptr<IndexedDB::IDBKeyRange> idb_key_range_from_value(JS::Value);--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/ConnectionQueueHandler.h b/Libraries/LibWeb/IndexedDB/Internal/ConnectionQueueHandler.hdeleted file mode 100644index 25a73bddb80..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/ConnectionQueueHandler.h+++ /dev/null@@ -1,46 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Vector.h>-#include <AK/kmalloc.h>-#include <LibWeb/IndexedDB/Internal/RequestList.h>-#include <LibWeb/StorageAPI/StorageKey.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#connection-queues-class ConnectionQueueHandler {- struct Connection;--public:- AK_ALLOC_WITH_KMALLOC;-- static RequestList& for_key_and_name(StorageAPI::StorageKey const& key, Utf16String const& name);- static ConnectionQueueHandler& the()- {- static ConnectionQueueHandler& instance = *new ConnectionQueueHandler;- return instance;- }--private:- Vector<NonnullRefPtr<Connection>> m_open_requests;-- struct Connection final : public RefCounted<Connection> {- Connection(StorageAPI::StorageKey storage_key, Utf16String name)- : storage_key(move(storage_key))- , name(move(name))- {- }-- StorageAPI::StorageKey storage_key;- Utf16String name;- RequestList request_list;- };-};--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/Database.cpp b/Libraries/LibWeb/IndexedDB/Internal/Database.cppdeleted file mode 100644index 19ff4fabbbc..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Database.cpp+++ /dev/null@@ -1,215 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/NeverDestroyed.h>-#include <LibGC/Heap.h>-#include <LibWeb/IndexedDB/IDBDatabase.h>-#include <LibWeb/IndexedDB/IDBTransaction.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/ConnectionQueueHandler.h>-#include <LibWeb/IndexedDB/Internal/Database.h>--namespace Web::IndexedDB {--using IDBDatabaseMapping = HashMap<StorageAPI::StorageKey, HashMap<Utf16String, GC::Root<Database>>>;-static IDBDatabaseMapping& idb_databases()-{- static NeverDestroyed<IDBDatabaseMapping> databases;- return *databases;-}--void Database::for_each_database(AK::Function<void(Database&)> const& visitor)-{- for (auto const& [key, mapping] : idb_databases()) {- for (auto const& [_, database] : mapping) {- if (!database)- continue;- visitor(*database);- }- }-}--GC_DEFINE_ALLOCATOR(Database);--Database::~Database() = default;--GC::Ref<Database> Database::create(GC::Heap& heap, Utf16String const& name)-{- return heap.allocate<Database>(name);-}--void Database::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_upgrade_transaction);- visitor.visit(m_object_stores);-- if (m_pending_connection_wait.has_value())- visitor.visit(m_pending_connection_wait->callback);-}--GC::Ptr<ObjectStore> Database::object_store_with_name(Utf16String const& name) const-{- for (auto const& object_store : m_object_stores) {- if (object_store->name() == name)- return object_store;- }-- return nullptr;-}--Vector<GC::Weak<Database>> Database::for_key(StorageAPI::StorageKey const& key)-{- Vector<GC::Weak<Database>> databases;- for (auto const& database_mapping : idb_databases().get(key).value_or({})) {- databases.append(*database_mapping.value);- }-- return databases;-}--RequestList& ConnectionQueueHandler::for_key_and_name(StorageAPI::StorageKey const& key, Utf16String const& name)-{- auto& instance = ConnectionQueueHandler::the();- auto maybe_connection = instance.m_open_requests.find_if([&key, &name](Connection const& connection) {- return connection.storage_key == key && connection.name == name;- });-- if (!maybe_connection.is_end())- return (*maybe_connection)->request_list;-- auto new_connection = adopt_ref(*new Connection(key, name));- instance.m_open_requests.append(new_connection);- return new_connection->request_list;-}--Optional<Database&> Database::for_key_and_name(StorageAPI::StorageKey const& key, Utf16String const& name)-{- auto database_mapping = idb_databases().ensure(key, [] { return HashMap<Utf16String, GC::Root<Database>>(); });- if (auto maybe_database = database_mapping.get(name); maybe_database.has_value())- return *maybe_database.value();- return {};-}--ErrorOr<GC::Ref<Database>> Database::create_for_key_and_name(GC::Heap& heap, StorageAPI::StorageKey const& key, Utf16String const& name)-{- auto database_mapping = TRY(idb_databases().try_ensure(key, [] {- return HashMap<Utf16String, GC::Root<Database>>();- }));-- auto value = Database::create(heap, name);-- database_mapping.set(name, value);- idb_databases().set(key, database_mapping);-- return value;-}--ErrorOr<void> Database::delete_for_key_and_name(StorageAPI::StorageKey const& key, Utf16String const& name)-{- // FIXME: Is a missing entry a failure?- auto maybe_database_mapping = idb_databases().get(key);- if (!maybe_database_mapping.has_value())- return {};-- auto& database_mapping = maybe_database_mapping.value();- auto maybe_database = database_mapping.get(name);- if (!maybe_database.has_value())- return {};-- auto did_remove = database_mapping.remove(name);- if (!did_remove)- return {};-- idb_databases().set(key, database_mapping);-- return {};-}--void Database::associate(GC::Ref<IDBDatabase> connection)-{- m_associated_connections.append(connection);-}--void Database::dissociate(IDBDatabase& connection)-{- m_associated_connections.remove_all_matching([&](auto& entry) { return !entry || entry == &connection; });-}--GC::Ref<Database::AssociatedConnections> Database::associated_connections_as_heap_vector(GC::Heap& heap)-{- auto connections = heap.allocate<AssociatedConnections>();- for (auto& associated_connection : m_associated_connections) {- if (associated_connection)- connections->elements().append(*associated_connection);- }- return connections;-}--GC::RootVector<GC::Ref<IDBDatabase>> Database::associated_connections_as_root_vector()-{- GC::RootVector<GC::Ref<IDBDatabase>> connections {};- for (auto& connection : m_associated_connections) {- if (connection)- connections.append(*connection);- }- return connections;-}--GC::Ref<Database::AssociatedConnections> Database::associated_connections_as_heap_vector_except(GC::Heap& heap, IDBDatabase& connection)-{- auto connections = heap.allocate<AssociatedConnections>();- for (auto& associated_connection : m_associated_connections) {- if (associated_connection && associated_connection != &connection)- connections->elements().append(*associated_connection);- }- return connections;-}--void Database::wait_for_connections_to_close(ReadonlySpan<GC::Ref<IDBDatabase>> connections, GC::Ref<GC::Function<void()>> after_all)-{- bool all_closed = true;- for (auto const& entry : connections) {- if (entry->state() != ConnectionState::Closed) {- all_closed = false;- break;- }- }-- if (all_closed) {- queue_a_database_task(after_all);- return;- }-- VERIFY(!m_pending_connection_wait.has_value());- Vector<GC::Weak<IDBDatabase>> weak_connections;- weak_connections.ensure_capacity(connections.size());- for (auto const& connection : connections)- weak_connections.unchecked_append(connection);- m_pending_connection_wait = PendingConnectionWait {- .connections = move(weak_connections),- .callback = after_all,- };-}--void Database::check_pending_connection_wait()-{- if (!m_pending_connection_wait.has_value())- return;-- auto& wait = m_pending_connection_wait.value();- for (auto const& connection : wait.connections) {- if (connection && connection->state() != ConnectionState::Closed)- return;- }-- // All connections are closed - invoke the callback and clear the wait- auto callback = wait.callback;- m_pending_connection_wait.clear();- queue_a_database_task(callback);-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/Database.h b/Libraries/LibWeb/IndexedDB/Internal/Database.hdeleted file mode 100644index b27e7b3cd54..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Database.h+++ /dev/null@@ -1,93 +0,0 @@-/*- * Copyright (c) 2024-2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Forward.h>-#include <LibGC/HeapVector.h>-#include <LibGC/Ptr.h>-#include <LibGC/RootVector.h>-#include <LibGC/Weak.h>-#include <LibJS/Heap/Cell.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>-#include <LibWeb/StorageAPI/StorageKey.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#database-construct-class Database : public JS::Cell {- GC_CELL(Database, JS::Cell);- GC_DECLARE_ALLOCATOR(Database);--public:- void set_version(u64 version) { m_version = version; }- u64 version() const { return m_version; }- Utf16String name() const { return m_name; }-- void set_upgrade_transaction(GC::Ptr<IDBTransaction> transaction) { m_upgrade_transaction = transaction; }- [[nodiscard]] GC::Ptr<IDBTransaction> upgrade_transaction() { return m_upgrade_transaction; }-- void associate(GC::Ref<IDBDatabase> connection);- void dissociate(IDBDatabase& connection);- using AssociatedConnections = GC::HeapVector<GC::Ref<IDBDatabase>>;- GC::Ref<AssociatedConnections> associated_connections_as_heap_vector(GC::Heap&);- GC::Ref<AssociatedConnections> associated_connections_as_heap_vector_except(GC::Heap&, IDBDatabase& connection);- GC::RootVector<GC::Ref<IDBDatabase>> associated_connections_as_root_vector();-- ReadonlySpan<GC::Ref<ObjectStore>> object_stores() { return m_object_stores; }- GC::Ptr<ObjectStore> object_store_with_name(Utf16String const& name) const;- void add_object_store(GC::Ref<ObjectStore> object_store) { m_object_stores.append(object_store); }- void remove_object_store(GC::Ref<ObjectStore> object_store)- {- m_object_stores.remove_first_matching([&](auto& entry) { return entry == object_store; });- }-- [[nodiscard]] static Vector<GC::Weak<Database>> for_key(StorageAPI::StorageKey const&);- [[nodiscard]] static Optional<Database&> for_key_and_name(StorageAPI::StorageKey const&, Utf16String const&);- [[nodiscard]] static ErrorOr<GC::Ref<Database>> create_for_key_and_name(GC::Heap&, StorageAPI::StorageKey const&, Utf16String const&);- [[nodiscard]] static ErrorOr<void> delete_for_key_and_name(StorageAPI::StorageKey const&, Utf16String const&);-- static void for_each_database(AK::Function<void(Database&)> const& visitor);-- [[nodiscard]] static GC::Ref<Database> create(GC::Heap&, Utf16String const&);- virtual ~Database();-- void wait_for_connections_to_close(ReadonlySpan<GC::Ref<IDBDatabase>> connections, GC::Ref<GC::Function<void()>> after_all);- void check_pending_connection_wait();--protected:- explicit Database(IDBDatabase& database);-- explicit Database(Utf16String name)- : m_name(move(name))- {- }-- virtual void visit_edges(Visitor&) override;--private:- struct PendingConnectionWait {- Vector<GC::Weak<IDBDatabase>> connections;- GC::Ref<GC::Function<void()>> callback;- };-- Vector<GC::Weak<IDBDatabase>> m_associated_connections;- Optional<PendingConnectionWait> m_pending_connection_wait;-- // A database has a name which identifies it within a specific storage key.- Utf16String m_name;-- // A database has a version. When a database is first created, its version is 0 (zero).- u64 m_version { 0 };-- // A database has at most one associated upgrade transaction, which is either null or an upgrade transaction, and is initially null.- GC::Ptr<IDBTransaction> m_upgrade_transaction;-- // A database has zero or more object stores which hold the data stored in the database.- Vector<GC::Ref<ObjectStore>> m_object_stores;-};--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/Index.cpp b/Libraries/LibWeb/IndexedDB/Internal/Index.cppdeleted file mode 100644index e0b4112ded1..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Index.cpp+++ /dev/null@@ -1,172 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/BinarySearch.h>-#include <LibGC/Heap.h>-#include <LibWeb/IndexedDB/Internal/Index.h>-#include <LibWeb/IndexedDB/Internal/MutationLog.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>-#include <LibWeb/IndexedDB/Internal/RecordRange.h>--namespace Web::IndexedDB {--static int compare_index_records(IndexRecord const& a, IndexRecord const& b)-{- auto key_comparison = Key::compare_two_keys(a.key, b.key);- if (key_comparison != 0)- return key_comparison;-- return Key::compare_two_keys(a.value, b.value);-}--GC_DEFINE_ALLOCATOR(Index);--Index::~Index() = default;--GC::Ref<Index> Index::create(GC::Ref<ObjectStore> store, Utf16String const& name, KeyPath const& key_path, bool unique, bool multi_entry)-{- return GC::Heap::the().allocate<Index>(store, name, key_path, unique, multi_entry);-}--Index::Index(GC::Ref<ObjectStore> store, Utf16String const& name, KeyPath const& key_path, bool unique, bool multi_entry)- : m_object_store(store)- , m_name(name)- , m_unique(unique)- , m_multi_entry(multi_entry)- , m_key_path(key_path)-{- store->index_set().set(name, *this);-}--void Index::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_object_store);-- for (auto& record : m_records) {- visitor.visit(record.key);- visitor.visit(record.value);- }-}--void Index::set_name(Utf16String name)-{- // NOTE: Update the key in the map so it still matches the name- auto old_value = m_object_store->index_set().take(m_name).release_value();- m_object_store->index_set().set(name, old_value);-- m_name = move(name);-}--bool Index::has_record_with_key(GC::Ref<Key> key)-{- return AK::binary_search(m_records, key, nullptr, [](auto const& needle, auto const& record) {- return Key::compare_two_keys(needle, record.key);- }) != nullptr;-}--// https://w3c.github.io/IndexedDB/#index-referenced-value-HTML::StorageSerializationRecord const& Index::referenced_value(IndexRecord const& index_record) const-{- // Records in an index are said to have a referenced value.- // This is the value of the record in the index’s referenced object store which has a key equal to the index’s record’s value.- auto* store_record = AK::binary_search(m_object_store->records(), index_record.value, nullptr, [](auto const& needle, auto const& record) {- return Key::compare_two_keys(needle, record.key);- });- VERIFY(store_record);- return *store_record->value;-}--void Index::clear_records()-{- GC::ConservativeVector deleted { move(m_records) };- if (auto log = m_object_store->mutation_log(); log && !deleted.is_empty())- log->note_index_records_deleted(*this, move(deleted));-}--Optional<IndexRecord&> Index::first_in_range(GC::Ref<IDBKeyRange> range)-{- auto record_range = record_range_for_key_range(m_records, range);- if (record_range.start == record_range.end)- return {};- return m_records[record_range.start];-}--GC::ConservativeVector<IndexRecord> Index::first_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count)-{- GC::ConservativeVector<IndexRecord> records;- auto record_range = record_range_for_key_range(m_records, range);- for (size_t i = record_range.start; i < record_range.end; ++i) {- records.append(m_records[i]);-- if (count.has_value() && records.size() >= *count)- break;- }-- return records;-}--GC::ConservativeVector<IndexRecord> Index::last_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count)-{- GC::ConservativeVector<IndexRecord> records;- auto record_range = record_range_for_key_range(m_records, range);- for (size_t i = record_range.end; i > record_range.start;) {- --i;- records.append(m_records[i]);-- if (count.has_value() && records.size() >= *count)- break;- }-- return records;-}--u64 Index::count_records_in_range(GC::Ref<IDBKeyRange> range)-{- auto record_range = record_range_for_key_range(m_records, range);- return record_range.end - record_range.start;-}--void Index::store_a_record(IndexRecord const& record)-{- if (auto log = m_object_store->mutation_log())- log->note_index_record_stored(*this, record);-- // NOTE: The record is stored in index’s list of records such that the list is sorted primarily on the records keys, and secondarily on the records values, in ascending order.- if (m_records.is_empty() || compare_index_records(m_records.last(), record) <= 0) {- m_records.append(record);- return;- }-- m_records.insert(AK::lower_bound_index(m_records, record, compare_index_records), record);-}--void Index::remove_record(IndexRecord const& record)-{- auto index = AK::lower_bound_index(m_records, record, compare_index_records);- if (index < m_records.size() && compare_index_records(m_records[index], record) == 0)- m_records.remove(index);-}--void Index::remove_records_with_value_in_range(GC::Ref<IDBKeyRange> range)-{- auto log = m_object_store->mutation_log();- GC::ConservativeVector<IndexRecord> removed_records;- for (size_t i = 0; i < m_records.size();) {- auto const& record = m_records[i];- if (range->is_in_range(record.value)) {- auto removed_record = m_records.take(i);- if (log)- removed_records.append(removed_record);- continue;- }- i++;- }- if (!removed_records.is_empty())- log->note_index_records_deleted(*this, move(removed_records));-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/Index.h b/Libraries/LibWeb/IndexedDB/Internal/Index.hdeleted file mode 100644index 473c87973ea..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Index.h+++ /dev/null@@ -1,85 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Vector.h>-#include <LibGC/Ptr.h>-#include <LibJS/Heap/Cell.h>-#include <LibWeb/IndexedDB/IDBRecord.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>--namespace Web::IndexedDB {--using KeyPath = Variant<Utf16String, Vector<Utf16String>>;--// https://w3c.github.io/IndexedDB/#index-construct-class Index : public JS::Cell {- GC_CELL(Index, JS::Cell);- GC_DECLARE_ALLOCATOR(Index);--public:- [[nodiscard]] static GC::Ref<Index> create(GC::Ref<ObjectStore>, Utf16String const&, KeyPath const&, bool, bool);- virtual ~Index();-- void set_name(Utf16String name);- [[nodiscard]] Utf16String name() const { return m_name; }- [[nodiscard]] bool unique() const { return m_unique; }- [[nodiscard]] bool multi_entry() const { return m_multi_entry; }- [[nodiscard]] GC::Ref<ObjectStore> object_store() const { return m_object_store; }- [[nodiscard]] AK::ReadonlySpan<IndexRecord> records() const { return m_records; }- [[nodiscard]] KeyPath const& key_path() const { return m_key_path; }-- [[nodiscard]] bool is_deleted() const { return m_deleted; }- void set_deleted(bool deleted) { m_deleted = deleted; }-- [[nodiscard]] bool is_pending_creation() const { return m_pending_creation; }- void set_pending_creation(bool pending_creation) { m_pending_creation = pending_creation; }-- [[nodiscard]] bool has_record_with_key(GC::Ref<Key> key);- void clear_records();- Optional<IndexRecord&> first_in_range(GC::Ref<IDBKeyRange> range);- GC::ConservativeVector<IndexRecord> first_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count);- GC::ConservativeVector<IndexRecord> last_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count);- u64 count_records_in_range(GC::Ref<IDBKeyRange> range);- void store_a_record(IndexRecord const& record);- void remove_record(IndexRecord const& record);- void remove_records_with_value_in_range(GC::Ref<IDBKeyRange> range);-- HTML::StorageSerializationRecord const& referenced_value(IndexRecord const& index_record) const;--protected:- virtual void visit_edges(Visitor&) override;--private:- Index(GC::Ref<ObjectStore>, Utf16String const&, KeyPath const&, bool, bool);-- // An index [...] has a referenced object store.- GC::Ref<ObjectStore> m_object_store;-- // The index has a list of records which hold the data stored in the index.- Vector<IndexRecord> m_records;-- // An index has a name, which is a name. At any one time, the name is unique within index’s referenced object store.- Utf16String m_name;-- // An index has a unique flag. When true, the index enforces that no two records in the index has the same key.- bool m_unique { false };-- // An index has a multiEntry flag. This flag affects how the index behaves when the result of evaluating the index’s key path yields an array key.- bool m_multi_entry { false };-- // The keys are derived from the referenced object store’s values using a key path.- KeyPath m_key_path;-- bool m_deleted { false };-- // NB: Whether the request that creates the index in its upgrade transaction has yet to be processed. Until then,- // storing records into the object store leaves the index alone.- bool m_pending_creation { false };-};--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/Key.cpp b/Libraries/LibWeb/IndexedDB/Internal/Key.cppdeleted file mode 100644index 869f9c22313..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Key.cpp+++ /dev/null@@ -1,229 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- * Copyright (c) 2026, Sam Atkins <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/IndexedDB/Internal/Key.h>-#include <LibWeb/Infra/ByteSequences.h>-#include <LibWebCommon/Infra/Strings.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(Key);--static Key::KeyValueInternal to_key_value_internal(Key::KeyValue const& key_value)-{- return key_value.visit(- [](GC::Root<GC::HeapVector<GC::Ref<Key>>> const& keys) -> Key::KeyValueInternal {- return GC::Ref { *keys };- },- [](auto const& other) -> Key::KeyValueInternal { return other; });-}--Key::Key(KeyType type, KeyValue value)- : m_type(type)- , m_value(to_key_value_internal(value))-{-}--Key::~Key() = default;--GC::Ref<Key> Key::create(KeyType key, KeyValue value)-{- return GC::Heap::the().allocate<Key>(key, value);-}--Key::KeyValue Key::value()-{- return m_value.visit(- [](GC::Ref<GC::HeapVector<GC::Ref<Key>>> const& keys) -> KeyValue {- return GC::make_root(keys);- },- [](auto const& other) -> KeyValue { return other; });-}--// https://w3c.github.io/IndexedDB/#compare-two-keys-i8 Key::compare_two_keys(GC::Ref<Key> a, GC::Ref<Key> b)-{- // 1. Let ta be the type of a.- auto ta = a->type();-- // 2. Let tb be the type of b.- auto tb = b->type();-- // 3. If ta does not equal tb, then run these steps:- if (ta != tb) {- // 1. If ta is array, then return 1.- if (ta == KeyType::Array)- return 1;-- // 2. If tb is array, then return -1.- if (tb == KeyType::Array)- return -1;-- // 3. If ta is binary, then return 1.- if (ta == KeyType::Binary)- return 1;-- // 4. If tb is binary, then return -1.- if (tb == KeyType::Binary)- return -1;-- // 5. If ta is string, then return 1.- if (ta == KeyType::String)- return 1;-- // 6. If tb is string, then return -1.- if (tb == KeyType::String)- return -1;-- // 7. If ta is date, then return 1.- if (ta == KeyType::Date)- return 1;-- // 8. Assert: tb is date.- VERIFY(tb == KeyType::Date);-- // 9. Return -1.- return -1;- }-- // 4. Let va be the value of a.- auto const& va = a->m_value;-- // 5. Let vb be the value of b.- auto const& vb = b->m_value;-- // 6. Switch on ta:- switch (ta) {- case KeyType::Invalid:- VERIFY_NOT_REACHED();- // number- // date- case KeyType::Number:- case KeyType::Date: {- auto a_value = va.get<double>();- auto b_value = vb.get<double>();-- // 1. If va is greater than vb, then return 1.- if (a_value > b_value)- return 1;-- // 2. If va is less than vb, then return -1.- if (a_value < b_value)- return -1;-- // 3. Return 0.- return 0;- }- // string- case KeyType::String: {- auto const& a_value = va.get<Utf16String>();- auto const& b_value = vb.get<Utf16String>();-- // 1. If va is code unit less than vb, then return -1.- if (Infra::code_unit_less_than(a_value.utf16_view(), b_value.utf16_view()))- return -1;-- // 2. If vb is code unit less than va, then return 1.- if (Infra::code_unit_less_than(b_value.utf16_view(), a_value.utf16_view()))- return 1;-- // 3. Return 0.- return 0;- }- // binary- case KeyType::Binary: {- auto const& a_value = va.get<ByteBuffer>();- auto const& b_value = vb.get<ByteBuffer>();-- // 1. If va is byte less than vb, then return -1.- if (Infra::is_byte_less_than(a_value, b_value))- return -1;-- // 2. If vb is byte less than va, then return 1.- if (Infra::is_byte_less_than(b_value, a_value))- return 1;-- // 3. Return 0.- return 0;- }- // array- case KeyType::Array: {- auto const& a_value = va.get<GC::Ref<GC::HeapVector<GC::Ref<Key>>>>()->elements();- auto const& b_value = vb.get<GC::Ref<GC::HeapVector<GC::Ref<Key>>>>()->elements();-- // 1. Let length be the lesser of va’s size and vb’s size.- auto length = min(a_value.size(), b_value.size());-- // 2. Let i be 0.- u64 i = 0;-- // 3. While i is less than length, then:- while (i < length) {- // 1. Let c be the result of recursively comparing two keys with va[i] and vb[i].- auto c = compare_two_keys(*a_value[i], *b_value[i]);-- // 2. If c is not 0, return c.- if (c != 0)- return c;-- // 3. Increase i by 1.- i++;- }-- // 4. If va’s size is greater than vb’s size, then return 1.- if (a_value.size() > b_value.size())- return 1;-- // 5. If va’s size is less than vb’s size, then return -1.- if (a_value.size() < b_value.size())- return -1;-- // 6. Return 0.- return 0;- }- }-- VERIFY_NOT_REACHED();-}--String Key::dump() const-{- return m_value.visit(- [](GC::Root<GC::HeapVector<GC::Ref<Key>>> const& value) {- StringBuilder sb;- sb.append("["sv);- for (auto const& key : value->elements()) {- sb.append(key->dump());- sb.append(", "sv);- }- sb.append("]"sv);- return MUST(sb.to_string());- },- [](ByteBuffer const& value) {- return MUST(String::formatted("{}", value.span()));- },- [](Utf16String const& value) {- return value.to_utf8();- },- [](auto const& value) {- return MUST(String::formatted("{}", value));- });-}--void Key::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);-- m_value.visit(- [&](GC::Ref<GC::HeapVector<GC::Ref<Key>>> const& keys) {- visitor.visit(keys);- },- [](auto const&) { });-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/Key.h b/Libraries/LibWeb/IndexedDB/Internal/Key.hdeleted file mode 100644index 4580065d654..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/Key.h+++ /dev/null@@ -1,87 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- * Copyright (c) 2026, Sam Atkins <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/String.h>-#include <AK/Utf16String.h>-#include <AK/Variant.h>-#include <AK/Vector.h>-#include <LibGC/HeapVector.h>-#include <LibGC/Ptr.h>-#include <LibJS/Heap/Cell.h>--namespace Web::IndexedDB {--// https://w3c.github.io/IndexedDB/#key-construct-class Key : public JS::Cell {- GC_CELL(Key, JS::Cell);- GC_DECLARE_ALLOCATOR(Key);--public:- // A key also has an associated value, which will be either:- // * an unrestricted double if type is number or date,- // * a DOMString if type is string,- // * a byte sequence if type is binary,- // * a list of other keys if type is array.- using KeyValue = Variant<double, Utf16String, ByteBuffer, GC::Root<GC::HeapVector<GC::Ref<Key>>>>;- using KeyValueInternal = Variant<double, Utf16String, ByteBuffer, GC::Ref<GC::HeapVector<GC::Ref<Key>>>>;-- // A key has an associated type which is one of: number, date, string, binary, or array.- enum KeyType {- Invalid,- Number,- Date,- String,- Binary,- Array,- };-- [[nodiscard]] static GC::Ref<Key> create(KeyType, KeyValue);- virtual ~Key();-- [[nodiscard]] KeyType type() const { return m_type; }- [[nodiscard]] KeyValue value();-- [[nodiscard]] bool is_invalid() const { return m_type == Invalid; }-- [[nodiscard]] double value_as_double() const { return m_value.get<double>(); }- [[nodiscard]] Utf16String const& value_as_string() const { return m_value.get<Utf16String>(); }- [[nodiscard]] ByteBuffer const& value_as_byte_buffer() const { return m_value.get<ByteBuffer>(); }- [[nodiscard]] ReadonlySpan<GC::Ref<Key>> value_as_vector() const { return m_value.get<GC::Ref<GC::HeapVector<GC::Ref<Key>>>>()->elements(); }- [[nodiscard]] ReadonlySpan<GC::Ref<Key>> subkeys() const- {- VERIFY(m_type == Array);- return value_as_vector();- }-- [[nodiscard]] static GC::Ref<Key> create_number(double value) { return create(Number, value); }- [[nodiscard]] static GC::Ref<Key> create_date(double value) { return create(Date, value); }- [[nodiscard]] static GC::Ref<Key> create_string(Utf16String const& value) { return create(String, value); }- [[nodiscard]] static GC::Ref<Key> create_binary(ByteBuffer const& value) { return create(Binary, value); }- [[nodiscard]] static GC::Ref<Key> create_array(GC::Root<GC::HeapVector<GC::Ref<Key>>> const& value) { return create(Array, value); }- [[nodiscard]] static GC::Ref<Key> create_invalid(Utf16String const& value) { return create(Invalid, value); }-- [[nodiscard]] static i8 compare_two_keys(GC::Ref<Key> a, GC::Ref<Key> b);- [[nodiscard]] static bool equals(GC::Ref<Key> a, GC::Ref<Key> b) { return compare_two_keys(a, b) == 0; }- [[nodiscard]] static bool less_than(GC::Ref<Key> a, GC::Ref<Key> b) { return compare_two_keys(a, b) < 0; }- [[nodiscard]] static bool greater_than(GC::Ref<Key> a, GC::Ref<Key> b) { return compare_two_keys(a, b) > 0; }- [[nodiscard]] static bool less_than_or_equal(GC::Ref<Key> a, GC::Ref<Key> b) { return compare_two_keys(a, b) <= 0; }- [[nodiscard]] static bool greater_than_or_equal(GC::Ref<Key> a, GC::Ref<Key> b) { return compare_two_keys(a, b) >= 0; }-- AK::String dump() const;--private:- Key(KeyType, KeyValue);- virtual void visit_edges(Visitor&) override;-- KeyType m_type;- KeyValueInternal m_value;-};--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/MutationLog.cpp b/Libraries/LibWeb/IndexedDB/Internal/MutationLog.cppdeleted file mode 100644index 76065104dcc..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/MutationLog.cpp+++ /dev/null@@ -1,275 +0,0 @@-/*- * Copyright (c) 2025, zaggy1024- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/IndexedDB/IDBDatabase.h>-#include <LibWeb/IndexedDB/Inspection.h>-#include <LibWeb/IndexedDB/Internal/Database.h>-#include <LibWeb/IndexedDB/Internal/Index.h>-#include <LibWeb/IndexedDB/Internal/Key.h>-#include <LibWeb/IndexedDB/Internal/MutationLog.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(MutationLog);--MutationLog::MutationLog() = default;--GC::Ref<MutationLog> MutationLog::create()-{- return GC::Heap::the().allocate<MutationLog>();-}--void MutationLog::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- for (auto& entry : m_entries) {- entry.visit(- [&](ObjectStoreCreated&) {- },- [&](ObjectStoreDeleted&) {- },- [&](IndexCreated& e) {- visitor.visit(e.index);- },- [&](IndexDeleted& e) {- visitor.visit(e.index);- },- [&](ObjectStoreRenamed&) {- },- [&](IndexRenamed& e) {- visitor.visit(e.index);- },- [&](KeyGeneratorChanged&) {- },- [&](RecordsDeleted& e) {- for (auto& record : e.records)- visitor.visit(record.key);- },- [&](RecordStored& e) {- visitor.visit(e.key);- },- [&](IndexRecordsDeleted& e) {- visitor.visit(e.index);- for (auto& record : e.records) {- visitor.visit(record.key);- visitor.visit(record.value);- }- },- [&](IndexRecordStored& e) {- visitor.visit(e.index);- visitor.visit(e.record.key);- visitor.visit(e.record.value);- });- }-}--void MutationLog::note_object_store_created()-{- m_entries.append(ObjectStoreCreated {});-}--void MutationLog::note_object_store_deleted()-{- m_entries.append(ObjectStoreDeleted {});-}--void MutationLog::note_object_store_renamed(Utf16String old_name)-{- m_entries.append(ObjectStoreRenamed { move(old_name) });-}--void MutationLog::note_index_created(GC::Ref<Index> index)-{- m_entries.append(IndexCreated { index });-}--void MutationLog::note_index_deleted(GC::Ref<Index> index)-{- m_entries.append(IndexDeleted { index });-}--void MutationLog::note_index_renamed(GC::Ref<Index> index, Utf16String old_name)-{- m_entries.append(IndexRenamed { index, move(old_name) });-}--void MutationLog::note_key_generator_changed(u64 old_value)-{- m_entries.append(KeyGeneratorChanged { old_value });-}--void MutationLog::note_records_deleted(Vector<ObjectStoreRecord>&& records)-{- m_entries.append(RecordsDeleted { move(records) });-}--void MutationLog::note_record_stored(GC::Ref<Key> key)-{- m_entries.append(RecordStored { key });-}--void MutationLog::note_index_records_deleted(GC::Ref<Index> index, Vector<IndexRecord>&& records)-{- m_entries.append(IndexRecordsDeleted { index, move(records) });-}--void MutationLog::note_index_record_stored(GC::Ref<Index> index, IndexRecord record)-{- m_entries.append(IndexRecordStored { index, record });-}--void MutationLog::append_changes(Utf16String const& database_name, Utf16String const& object_store_name, TransactionChanges& changes) const-{- GC::RootVector<GC::Ref<Key>> stored_keys;- GC::RootVector<GC::Ref<Key>> changed_keys;- GC::RootVector<GC::Ref<Key>> deleted_keys;-- auto remove_key = [](Vector<GC::Ref<Key>>& keys, Key& key) {- return keys.remove_first_matching([&](auto const& existing) {- return Key::equals(existing, GC::Ref { key });- });- };-- auto append_deleted_key = [&](Key& key) {- if (remove_key(stored_keys, key))- return;- remove_key(changed_keys, key);- deleted_keys.append(GC::Ref { key });- };-- auto append_stored_key = [&](Key& key) {- if (remove_key(deleted_keys, key)) {- changed_keys.append(GC::Ref { key });- return;- }- stored_keys.append(GC::Ref { key });- };-- for (auto const& entry : m_entries) {- entry.visit(- [&](ObjectStoreCreated const&) {- changes.added.append({ database_name, object_store_name });- },- [&](ObjectStoreDeleted const&) {- changes.deleted.append({ database_name, object_store_name });- },- [&](ObjectStoreRenamed const& e) {- changes.deleted.append({ database_name, e.old_name });- changes.added.append({ database_name, object_store_name });- },- [&](IndexCreated const&) { },- [&](IndexDeleted const&) { },- [&](IndexRenamed const&) { },- [&](KeyGeneratorChanged const&) {- },- [&](RecordsDeleted const& e) {- for (auto const& record : e.records)- append_deleted_key(*record.key);- },- [&](RecordStored const& e) {- append_stored_key(*e.key);- },- [&](IndexRecordsDeleted const&) { },- [&](IndexRecordStored const&) { });- }-- for (auto const& key : stored_keys)- changes.added.append({ database_name, object_store_name, serialize_key_for_inspection(key) });-- for (auto const& key : changed_keys)- changes.changed.append({ database_name, object_store_name, serialize_key_for_inspection(key) });-- for (auto const& key : deleted_keys)- changes.deleted.append({ database_name, object_store_name, serialize_key_for_inspection(key) });-}--void MutationLog::revert(ObjectStore& store, GC::Ref<Database> database, GC::Ref<IDBDatabase> connection)-{- revert_entries(store, 0, database, connection);-}--void MutationLog::revert_from(ObjectStore& store, size_t position)-{- revert_entries(store, position, nullptr, nullptr);-}--void MutationLog::revert_entries(ObjectStore& store, size_t from_position, GC::Ptr<Database> database, GC::Ptr<IDBDatabase> connection)-{- // Temporarily clear the store's mutation log pointer so that the operations below- // don't re-log into this log while we're reverting it.- auto saved_log = store.mutation_log();- store.set_mutation_log(nullptr);-- for (size_t i = m_entries.size(); i-- > from_position;) {- m_entries[i].visit(- [&](ObjectStoreCreated&) {- VERIFY(database);- VERIFY(connection);- database->remove_object_store(store);- connection->remove_from_object_store_set(store);-- // https://w3c.github.io/IndexedDB/#abort-a-transaction- // Any object stores and indexes which were created during the transaction are now considered deleted- // for the purposes of other algorithms.- store.set_deleted(true);- for (auto const& [_, index] : store.index_set())- index->set_deleted(true);- },- [&](ObjectStoreDeleted&) {- VERIFY(database);- VERIFY(connection);- store.set_deleted(false);- for (auto const& [_, index] : store.index_set())- index->set_deleted(false);- database->add_object_store(store);- connection->add_to_object_store_set(store);- },- [&](IndexCreated& e) {- VERIFY(database);- e.index->object_store()->index_set().remove(e.index->name());-- // https://w3c.github.io/IndexedDB/#abort-a-transaction- // Any object stores and indexes which were created during the transaction are now considered deleted- // for the purposes of other algorithms.- e.index->set_deleted(true);- },- [&](IndexDeleted& e) {- VERIFY(database);- e.index->set_deleted(false);- e.index->object_store()->index_set().set(e.index->name(), e.index);- },- [&](ObjectStoreRenamed& e) {- store.set_name(e.old_name);- },- [&](IndexRenamed& e) {- e.index->set_name(move(e.old_name));- },- [&](KeyGeneratorChanged& e) {- store.key_generator().set(e.old_value);- },- [&](RecordsDeleted& e) {- for (auto& record : e.records)- store.store_a_record(record);- },- [&](RecordStored& e) {- store.remove_record_with_key(e.key);- },- [&](IndexRecordsDeleted& e) {- for (auto& record : e.records)- e.index->store_a_record(record);- },- [&](IndexRecordStored& e) {- e.index->remove_record(e.record);- });- }- m_entries.shrink(from_position);-- store.set_mutation_log(saved_log);-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/MutationLog.h b/Libraries/LibWeb/IndexedDB/Internal/MutationLog.hdeleted file mode 100644index 848e355c908..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/MutationLog.h+++ /dev/null@@ -1,129 +0,0 @@-/*- * Copyright (c) 2025, zaggy1024- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Variant.h>-#include <AK/Vector.h>-#include <LibGC/Ptr.h>-#include <LibJS/Heap/Cell.h>-#include <LibWeb/IndexedDB/IDBRecord.h>-#include <LibWeb/IndexedDB/Internal/KeyGenerator.h>-#include <LibWebCommon/IndexedDB/TransactionChanges.h>--namespace Web::IndexedDB {--class Database;-class IDBDatabase;-class Index;-class ObjectStore;--// Tracks mutations to an object store and its indexes so they can be reverted on request failure-// (asynchronously execute a request step 5.4) or transaction abort (abort a transaction step 2).-//-// For upgrade transactions, this also tracks schema-level changes (store/index creation and deletion).-// Schema entries are always at the boundaries: ObjectStoreCreated is always first (if present),-// and ObjectStoreDeleted is always last (if present). Index schema entries appear in order between-// data mutations.-class MutationLog : public JS::Cell {- GC_CELL(MutationLog, JS::Cell);- GC_DECLARE_ALLOCATOR(MutationLog);--public:- [[nodiscard]] static GC::Ref<MutationLog> create();-- // Schema-level entries (upgrade transactions only).- void note_object_store_created();- void note_object_store_deleted();- void note_object_store_renamed(Utf16String old_name);- void note_index_created(GC::Ref<Index>);- void note_index_deleted(GC::Ref<Index>);- void note_index_renamed(GC::Ref<Index>, Utf16String old_name);-- // Record that the key generator value was changed, saving the old value for revert.- void note_key_generator_changed(u64 old_value);-- // Record that records were deleted from the object store, saving them for re-insertion on revert.- void note_records_deleted(Vector<ObjectStoreRecord>&&);-- // Record that a new record was stored in the object store, saving the key for deletion on revert.- void note_record_stored(GC::Ref<Key> key);-- // Record that records were deleted from an index, saving them for re-insertion on revert.- void note_index_records_deleted(GC::Ref<Index>, Vector<IndexRecord>&&);-- // Record that a new record was stored in an index, saving it for deletion on revert.- void note_index_record_stored(GC::Ref<Index>, IndexRecord);-- // Undo all logged mutations in reverse order. Database and connection are required for schema entries.- void revert(ObjectStore&, GC::Ref<Database>, GC::Ref<IDBDatabase>);-- // Undo logged mutations from the given position forward (used for per-request revert on failure).- // Asserts that no schema entries are encountered.- void revert_from(ObjectStore&, size_t position);-- // Clear the log without reverting (used after successful transaction commit).- void clear() { m_entries.clear(); }-- void append_changes(Utf16String const& database_name, Utf16String const& object_store_name, TransactionChanges&) const;-- [[nodiscard]] size_t position() const { return m_entries.size(); }--protected:- explicit MutationLog();- virtual void visit_edges(Visitor&) override;--private:- void revert_entries(ObjectStore&, size_t from_position, GC::Ptr<Database>, GC::Ptr<IDBDatabase>);-- struct ObjectStoreCreated { };- struct ObjectStoreDeleted { };-- struct IndexCreated {- GC::Ref<Index> index;- };-- struct IndexDeleted {- GC::Ref<Index> index;- };-- struct ObjectStoreRenamed {- Utf16String old_name;- };-- struct IndexRenamed {- GC::Ref<Index> index;- Utf16String old_name;- };-- struct KeyGeneratorChanged {- u64 old_value;- };-- struct RecordsDeleted {- Vector<ObjectStoreRecord> records;- };-- struct RecordStored {- GC::Ref<Key> key;- };-- struct IndexRecordsDeleted {- GC::Ref<Index> index;- Vector<IndexRecord> records;- };-- struct IndexRecordStored {- GC::Ref<Index> index;- IndexRecord record;- };-- using Entry = Variant<ObjectStoreCreated, ObjectStoreDeleted, ObjectStoreRenamed, IndexCreated, IndexDeleted, IndexRenamed, KeyGeneratorChanged, RecordsDeleted, RecordStored, IndexRecordsDeleted, IndexRecordStored>;-- Vector<Entry> m_entries;-};--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/ObjectStore.cpp b/Libraries/LibWeb/IndexedDB/Internal/ObjectStore.cppdeleted file mode 100644index a9352dfab0d..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/ObjectStore.cpp+++ /dev/null@@ -1,213 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/BinarySearch.h>-#include <AK/Math.h>-#include <LibGC/Heap.h>-#include <LibWeb/IndexedDB/IDBKeyRange.h>-#include <LibWeb/IndexedDB/Internal/MutationLog.h>-#include <LibWeb/IndexedDB/Internal/ObjectStore.h>-#include <LibWeb/IndexedDB/Internal/RecordRange.h>--namespace Web::IndexedDB {--GC_DEFINE_ALLOCATOR(ObjectStore);--ObjectStore::~ObjectStore() = default;--GC::Ref<ObjectStore> ObjectStore::create(GC::Ref<Database> database, Utf16String name, bool auto_increment, Optional<KeyPath> const& key_path)-{- return GC::Heap::the().allocate<ObjectStore>(database, move(name), auto_increment, key_path);-}--size_t ObjectStore::mutation_log_position() const-{- if (!m_mutation_log)- return 0;- return m_mutation_log->position();-}--void ObjectStore::revert_mutations_from(size_t position)-{- if (m_mutation_log)- m_mutation_log->revert_from(*this, position);-}--ObjectStore::ObjectStore(GC::Ref<Database> database, Utf16String name, bool auto_increment, Optional<KeyPath> const& key_path)- : m_database(database)- , m_name(move(name))- , m_key_path(key_path)-{- database->add_object_store(*this);-- if (auto_increment)- m_key_generator = KeyGenerator {};-}--void ObjectStore::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_database);- visitor.visit(m_indexes);- visitor.visit(m_mutation_log);-- for (auto& record : m_records) {- visitor.visit(record.key);- }-}--void ObjectStore::remove_records_in_range(GC::Ref<IDBKeyRange> range)-{- if (m_records.is_empty())- return;-- // Since records are sorted by key, records in range form a contiguous block.- auto record_range = record_range_for_key_range(m_records, range);-- if (record_range.start < record_range.end) {- if (m_mutation_log) {- GC::ConservativeVector<ObjectStoreRecord> deleted;- deleted.ensure_capacity(record_range.end - record_range.start);- for (size_t i = record_range.start; i < record_range.end; ++i)- deleted.append(move(m_records[i]));- m_mutation_log->note_records_deleted(move(deleted));- }- m_records.remove(record_range.start, record_range.end - record_range.start);- }-}--void ObjectStore::remove_record_with_key(GC::Ref<Key> key)-{- size_t index = 0;- auto* record = AK::binary_search(m_records, key, &index, [](auto const& needle, auto const& record) {- return Key::compare_two_keys(needle, record.key);- });- if (record)- m_records.remove(index);-}--bool ObjectStore::has_record_with_key(GC::Ref<Key> key)-{- return binary_search(m_records, key, nullptr, [](auto const& needle, auto const& record) -> int {- return Key::compare_two_keys(needle, record.key);- }) != nullptr;-}--void ObjectStore::store_a_record(ObjectStoreRecord record)-{- if (m_mutation_log)- m_mutation_log->note_record_stored(record.key);-- // NOTE: The record is stored in the object store’s list of records such that the list is sorted according to the key of the records in ascending order.- if (m_records.is_empty() || Key::compare_two_keys(m_records.last().key, record.key) <= 0) {- m_records.append(move(record));- return;- }-- m_records.insert(first_record_index_with_key_at_or_after(m_records, record.key, false), move(record));-}--u64 ObjectStore::count_records_in_range(GC::Ref<IDBKeyRange> range)-{- auto record_range = record_range_for_key_range(m_records, range);- return record_range.end - record_range.start;-}--Optional<ObjectStoreRecord&> ObjectStore::first_in_range(GC::Ref<IDBKeyRange> range)-{- auto record_range = record_range_for_key_range(m_records, range);- if (record_range.start == record_range.end)- return {};- return m_records[record_range.start];-}--void ObjectStore::clear_records()-{- GC::ConservativeVector deleted_records { move(m_records) };- if (m_mutation_log && !deleted_records.is_empty())- m_mutation_log->note_records_deleted(move(deleted_records));-}--// https://w3c.github.io/IndexedDB/#generate-a-key-ErrorOr<u64> ObjectStore::generate_a_key()-{- // 1. Let generator be store's key generator.- auto& generator = key_generator();-- // 2. Let key be generator's current number.- auto key = generator.current_number();-- // 3. If key is greater than 2^53 (9007199254740992), then return failure.- if (key > static_cast<u64>(MAX_KEY_GENERATOR_VALUE))- return Error::from_string_literal("Key is greater than 2^53 while trying to generate a key");-- // 4. Increase generator's current number by 1.- if (m_mutation_log)- m_mutation_log->note_key_generator_changed(key);- generator.increment(1);-- // 5. Return key.- return key;-}--// https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator-void ObjectStore::possibly_update_the_key_generator(GC::Ref<Key> key)-{- // 1. If the type of key is not number, abort these steps.- if (key->type() != Key::KeyType::Number)- return;-- // 2. Let value be the value of key.- auto value = key->value_as_double();-- // 3. Set value to the minimum of value and 2^53 (9007199254740992).- value = min(value, MAX_KEY_GENERATOR_VALUE);-- // 4. Set value to the largest integer not greater than value.- value = AK::floor(value);-- // 5. Let generator be store's key generator.- auto& generator = key_generator();-- // 6. If value is greater than or equal to generator's current number, then set generator's current number to value + 1.- if (value >= static_cast<double>(generator.current_number())) {- if (m_mutation_log)- m_mutation_log->note_key_generator_changed(generator.current_number());- // NB: value + 1 is computed as an integer, as 2^53 + 1 does not fit in a double.- generator.set(static_cast<u64>(value) + 1);- }-}--GC::ConservativeVector<ObjectStoreRecord> ObjectStore::first_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count)-{- GC::ConservativeVector<ObjectStoreRecord> records;- auto record_range = record_range_for_key_range(m_records, range);- for (size_t i = record_range.start; i < record_range.end; ++i) {- records.append(m_records[i]);-- if (count.has_value() && records.size() >= *count)- break;- }-- return records;-}--GC::ConservativeVector<ObjectStoreRecord> ObjectStore::last_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count)-{- GC::ConservativeVector<ObjectStoreRecord> records;- auto record_range = record_range_for_key_range(m_records, range);- for (size_t i = record_range.end; i > record_range.start;) {- --i;- records.append(m_records[i]);-- if (count.has_value() && records.size() >= *count)- break;- }-- return records;-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/ObjectStore.h b/Libraries/LibWeb/IndexedDB/Internal/ObjectStore.hdeleted file mode 100644index 6c2e7df5407..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/ObjectStore.h+++ /dev/null@@ -1,102 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <AK/Optional.h>-#include <AK/String.h>-#include <AK/Variant.h>-#include <AK/Vector.h>-#include <LibGC/Ptr.h>-#include <LibJS/Heap/Cell.h>-#include <LibWeb/IndexedDB/IDBRecord.h>-#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/Database.h>-#include <LibWeb/IndexedDB/Internal/Index.h>-#include <LibWeb/IndexedDB/Internal/KeyGenerator.h>-#include <LibWeb/IndexedDB/Internal/MutationLog.h>--namespace Web::IndexedDB {--using KeyPath = Variant<Utf16String, Vector<Utf16String>>;--// https://w3c.github.io/IndexedDB/#object-store-construct-class ObjectStore : public JS::Cell {- GC_CELL(ObjectStore, JS::Cell);- GC_DECLARE_ALLOCATOR(ObjectStore);--public:- [[nodiscard]] static GC::Ref<ObjectStore> create(GC::Ref<Database>, Utf16String, bool, Optional<KeyPath> const&);- virtual ~ObjectStore();-- Utf16String name() const { return m_name; }- void set_name(Utf16String name) { m_name = move(name); }- Optional<KeyPath> const& key_path() const { return m_key_path; }- bool uses_inline_keys() const { return m_key_path.has_value(); }- bool uses_out_of_line_keys() const { return !m_key_path.has_value(); }- KeyGenerator& key_generator() { return *m_key_generator; }- bool uses_a_key_generator() const { return m_key_generator.has_value(); }- AK::HashMap<Utf16String, GC::Ref<Index>>& index_set() { return m_indexes; }-- [[nodiscard]] bool is_deleted() const { return m_deleted; }- void set_deleted(bool deleted) { m_deleted = deleted; }-- GC::Ref<Database> database() const { return m_database; }- ReadonlySpan<ObjectStoreRecord> records() const { return m_records; }-- void remove_records_in_range(GC::Ref<IDBKeyRange> range);- bool has_record_with_key(GC::Ref<Key> key);- void store_a_record(ObjectStoreRecord record);- void remove_record_with_key(GC::Ref<Key> key);- u64 count_records_in_range(GC::Ref<IDBKeyRange> range);- Optional<ObjectStoreRecord&> first_in_range(GC::Ref<IDBKeyRange> range);- void clear_records();- GC::ConservativeVector<ObjectStoreRecord> first_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count);- GC::ConservativeVector<ObjectStoreRecord> last_n_in_range(GC::Ref<IDBKeyRange> range, Optional<WebIDL::UnsignedLong> count);-- // https://w3c.github.io/IndexedDB/#generate-a-key- ErrorOr<u64> generate_a_key();- // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator- void possibly_update_the_key_generator(GC::Ref<Key>);-- // Mutation log access. The log is set externally by the readwrite transaction that owns it.- GC::Ptr<MutationLog> mutation_log() const { return m_mutation_log; }- void set_mutation_log(GC::Ptr<MutationLog> log) { m_mutation_log = log; }- [[nodiscard]] size_t mutation_log_position() const;- void revert_mutations_from(size_t position);--protected:- virtual void visit_edges(Visitor&) override;--private:- ObjectStore(GC::Ref<Database> database, Utf16String name, bool auto_increment, Optional<KeyPath> const& key_path);-- // AD-HOC: An ObjectStore needs to know what Database it belongs to...- GC::Ref<Database> m_database;-- // AD-HOC: An Index has referenced ObjectStores, we also need the reverse mapping- AK::HashMap<Utf16String, GC::Ref<Index>> m_indexes;-- // An object store has a name, which is a name. At any one time, the name is unique within the database to which it belongs.- Utf16String m_name;-- // An object store optionally has a key path. If the object store has a key path it is said to use in-line keys. Otherwise it is said to use out-of-line keys.- Optional<KeyPath> m_key_path;-- // An object store optionally has a key generator.- Optional<KeyGenerator> m_key_generator;-- // An object store has a list of records- Vector<ObjectStoreRecord> m_records;-- bool m_deleted { false };-- // AD-HOC: Tracks mutations for revert on request failure or transaction abort.- GC::Ptr<MutationLog> m_mutation_log;-};--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/RecordRange.h b/Libraries/LibWeb/IndexedDB/Internal/RecordRange.hdeleted file mode 100644index f11a9218751..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/RecordRange.h+++ /dev/null@@ -1,71 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Types.h>-#include <LibGC/Ptr.h>-#include <LibWeb/IndexedDB/IDBKeyRange.h>--namespace Web::IndexedDB {--struct RecordRange {- size_t start { 0 };- size_t end { 0 };-};--template<typename Records>-static size_t first_record_index_with_key_at_or_after(Records const& records, GC::Ref<Key> key, bool open)-{- size_t low = 0;- size_t high = records.size();-- while (low < high) {- size_t middle = low + (high - low) / 2;- auto comparison = Key::compare_two_keys(records[middle].key, key);- if (comparison < 0 || (comparison == 0 && open))- low = middle + 1;- else- high = middle;- }-- return low;-}--template<typename Records>-static size_t first_record_index_with_key_after(Records const& records, GC::Ref<Key> key, bool open, size_t start = 0)-{- size_t low = start;- size_t high = records.size();-- while (low < high) {- size_t middle = low + (high - low) / 2;- auto comparison = Key::compare_two_keys(records[middle].key, key);- if (comparison < 0 || (comparison == 0 && !open))- low = middle + 1;- else- high = middle;- }-- return low;-}--template<typename Records>-static RecordRange record_range_for_key_range(Records const& records, GC::Ref<IDBKeyRange> range)-{- size_t start = 0;- size_t end = records.size();-- if (auto lower = range->lower_key())- start = first_record_index_with_key_at_or_after(records, *lower, range->lower_open());-- if (auto upper = range->upper_key())- end = first_record_index_with_key_after(records, *upper, range->upper_open(), start);-- return { start, end };-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/RequestList.cpp b/Libraries/LibWeb/IndexedDB/Internal/RequestList.cppdeleted file mode 100644index f701d1fd8c5..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/RequestList.cpp+++ /dev/null@@ -1,113 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/IndexedDB/Internal/Algorithms.h>-#include <LibWeb/IndexedDB/Internal/RequestList.h>--namespace Web::IndexedDB {--void RequestList::enqueue(GC::Ref<IDBRequest> request, GC::Ref<GC::Function<void()>> steps)-{- m_entries.append({ request, steps });- maybe_process_next_request();-}--void RequestList::maybe_process_next_request()-{- if (m_blocked)- return;-- while (!m_entries.is_empty() && !m_entries.first().request)- m_entries.remove(0);-- for (auto& [request, steps] : m_entries) {- if (!request)- continue;- if (request->processed())- continue;- if (request->aborted())- continue;-- // If the steps are null here, the request is still executing, so we should wait until it is finished.- if (!steps)- return;-- queue_a_database_task(*steps);- steps = nullptr;- return;- }-}--void RequestList::on_request_processed()-{- maybe_process_next_request();-}--void RequestList::remove(GC::Ref<IDBRequest> request)-{- m_entries.remove_first_matching([&request](auto const& entry) {- return entry.request == request;- });-}--bool RequestList::is_empty() const-{- return m_entries.is_empty();-}--void RequestList::set_on_all_processed(GC::Ref<GC::Function<void()>> callback)-{- m_on_all_processed = callback;- check_all_processed();-}--void RequestList::clear_on_all_processed()-{- m_on_all_processed = nullptr;-}--void RequestList::check_all_processed()-{- if (!m_on_all_processed)- return;-- m_entries.remove_all_matching([](auto const& entry) { return !entry.request; });-- for (auto const& entry : m_entries) {- if (!entry.request->processed())- return;- }-- auto callback = move(m_on_all_processed);- callback->function()();-}--void RequestList::unblock_execution()-{- m_blocked = false;- maybe_process_next_request();-}--GC::Ref<IDBRequest> RequestList::RequestIterator::operator*() const-{- return *m_entries[m_index].request;-}--RequestList::RequestIterator& RequestList::RequestIterator::operator++()-{- ++m_index;- skip_null();- return *this;-}--void RequestList::RequestIterator::skip_null()-{- while (m_index < m_entries.size() && !m_entries[m_index].request)- ++m_index;-}--}diff --git a/Libraries/LibWeb/IndexedDB/Internal/RequestList.h b/Libraries/LibWeb/IndexedDB/Internal/RequestList.hdeleted file mode 100644index e3d7a17a7f4..00000000000--- a/Libraries/LibWeb/IndexedDB/Internal/RequestList.h+++ /dev/null@@ -1,74 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Vector.h>-#include <LibGC/Root.h>-#include <LibWeb/IndexedDB/IDBRequest.h>--namespace Web::IndexedDB {--class RequestList final {- AK_MAKE_NONMOVABLE(RequestList);- AK_MAKE_NONCOPYABLE(RequestList);--public:- RequestList() = default;-- void enqueue(GC::Ref<IDBRequest> request, GC::Ref<GC::Function<void()>> steps);- void remove(GC::Ref<IDBRequest> request);-- void on_request_processed();-- bool is_empty() const;-- void block_execution() { m_blocked = true; }- bool execution_is_blocked() const { return m_blocked; }- void unblock_execution();-- void set_on_all_processed(GC::Ref<GC::Function<void()>> callback);- void clear_on_all_processed();- void check_all_processed();- void maybe_process_next_request();--private:- struct Entry {- GC::Weak<IDBRequest> request;- GC::Root<GC::Function<void()>> steps;- };-- Vector<Entry> m_entries;- GC::Root<GC::Function<void()>> m_on_all_processed;- bool m_blocked { false };--public:- class RequestIterator {- public:- RequestIterator(Vector<Entry> const& entries, size_t index)- : m_entries(entries)- , m_index(index)- {- skip_null();- }-- GC::Ref<IDBRequest> operator*() const;- RequestIterator& operator++();- bool operator!=(RequestIterator const& other) const { return m_index != other.m_index; }-- private:- void skip_null();-- Vector<Entry> const& m_entries;- size_t m_index;- };-- RequestIterator begin() const { return { m_entries, 0 }; }- RequestIterator end() const { return { m_entries, m_entries.size() }; }-};--}diff --git a/Libraries/LibWeb/IndexedDB/RustIntegration.cpp b/Libraries/LibWeb/IndexedDB/RustIntegration.cppnew file mode 100644index 00000000000..71e42d82e4b--- /dev/null+++ b/Libraries/LibWeb/IndexedDB/RustIntegration.cpp@@ -0,0 +1,239 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/JsonArray.h>+#include <AK/JsonValue.h>+#include <AK/ScopeGuard.h>+#include <LibGC/Heap.h>+#include <LibGC/Weak.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibURL/RustIntegration.h>+#include <LibWeb/Bindings/MainThreadVM.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/WrapperWorld.h>+#include <LibWeb/DOM/Document.h>+#include <LibWeb/HTML/DOMStringList.h>+#include <LibWeb/HTML/EventLoop/EventLoop.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/StructuredSerialize.h>+#include <LibWeb/Page/Page.h>+#include <LibWeb/Platform/EventLoopPlugin.h>+#include <LibWeb/StorageAPI/StorageKey.h>+#include <LibWeb/WebIDL/DOMException.h>+#include <LibWeb/WebIDL/ExceptionOrUtils.h>+#include <LibWebCommon/IndexedDB/TransactionChanges.h>++// What the Rust implementation of IndexedDB asks of LibWeb's C++ code, declared on the Rust side in+// Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs.++using namespace Web;++extern "C" {++void web_rust_indexed_db_check_pending_connection_wait(JSVM*, void* database);++void* web_indexed_db_create_dom_exception(ReadonlyBytes name, FlatPtr message);+void* web_indexed_db_dom_exception_from_value(JSValue);+JSObject* web_indexed_db_wrap_dom_exception(void* realm, void* exception);+bool web_indexed_db_obtain_a_storage_key(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));+JSObject* web_indexed_db_create_dom_string_list(void* realm, FlatPtr const* strings, size_t count);+JSCompletion web_indexed_db_structured_serialize_for_storage(void* realm, JSValue, void* bytes, void (*append)(void*, u8 const*, size_t));+JSCompletion web_indexed_db_structured_deserialize(void* realm, ReadonlyBytes);+void web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*));+void web_indexed_db_run_in_parallel(void* cell, void (*steps)(JSVM*, void*));+void* web_indexed_db_main_thread_event_loop();+void web_indexed_db_enqueue_check_pending_connection_wait(void* database);+bool web_indexed_db_devtools_client_is_active(void* realm);+IndexedDB::TransactionChanges* web_indexed_db_create_transaction_changes();+void web_indexed_db_append_transaction_change(IndexedDB::TransactionChanges*, u8 kind, FlatPtr database_name, FlatPtr object_store_name, JsonValue* key);+void web_indexed_db_notify_devtools(void* realm, IndexedDB::TransactionChanges*);+JsonValue* web_indexed_db_json_number(double);+JsonValue* web_indexed_db_json_string(FlatPtr);+JsonValue* web_indexed_db_json_binary(ReadonlyBytes);+JsonValue* web_indexed_db_json_null();+JsonValue* web_indexed_db_json_array();+void web_indexed_db_json_array_append(JsonValue* array, JsonValue* value);+}++void* web_indexed_db_create_dom_exception(ReadonlyBytes name, FlatPtr message)+{+ return WebIDL::DOMException::create(FlyString::from_utf8_without_validation(name), Utf16String::from_raw(message)).ptr();+}++void* web_indexed_db_dom_exception_from_value(JSValue raw_value)+{+ auto value = JS::HostABI::value_from_abi(raw_value);+ if (!value.is_object())+ return nullptr;+ return Bindings::impl_from<WebIDL::DOMException>(&value.as_object());+}++JSObject* web_indexed_db_wrap_dom_exception(void* realm, void* exception)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto& dom_exception = *static_cast<WebIDL::DOMException*>(exception);+ return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, GC::Ref { dom_exception }).ptr());+}++bool web_indexed_db_obtain_a_storage_key(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*))+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto storage_key = StorageAPI::obtain_a_storage_key(HTML::relevant_settings_object(js_realm.global_object()));+ if (!storage_key.has_value())+ return false;+ URL::RustIntegration::lend_origin_to_ffi(storage_key->origin, [&](URL::FFI::FfiOrigin const& origin) {+ on_origin(ctx, &origin);+ });+ return true;+}++JSObject* web_indexed_db_create_dom_string_list(void* realm, FlatPtr const* strings, size_t count)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ Vector<String> names;+ names.ensure_capacity(count);+ for (size_t i = 0; i < count; ++i)+ names.unchecked_append(Utf16String::from_raw(strings[i]).to_utf8());+ auto list = HTML::DOMStringList::create(move(names));+ return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, list).ptr());+}++// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage+JSCompletion web_indexed_db_structured_serialize_for_storage(void* realm, JSValue raw_value, void* bytes, void (*append)(void*, u8 const*, size_t))+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto serialized = HTML::structured_serialize_for_storage(js_realm.vm(), JS::HostABI::value_from_abi(raw_value));+ if (serialized.is_exception())+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { WebIDL::exception_to_throw_completion(js_realm.vm(), js_realm, serialized.release_error()) });+ auto record = serialized.release_value();+ append(bytes, record.data.data(), record.data.size());+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::js_undefined() });+}++// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize+JSCompletion web_indexed_db_structured_deserialize(void* realm, ReadonlyBytes bytes)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ HTML::StorageSerializationRecord record { MUST(ByteBuffer::copy(bytes)) };+ auto value = HTML::structured_deserialize(js_realm.vm(), record, js_realm);+ if (value.is_exception())+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { WebIDL::exception_to_throw_completion(js_realm.vm(), js_realm, value.release_error()) });+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { value.release_value() });+}++// https://w3c.github.io/IndexedDB/#queue-a-database-task+void web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*))+{+ GC::Ref<GC::Cell> function = *static_cast<GC::Cell*>(cell);+ // NB: The task's captures, which the collector scans, keep the function alive until the steps run.+ HTML::queue_a_task(HTML::Task::Source::DatabaseAccess, nullptr, nullptr, GC::create_function(GC::Heap::the(), [function, steps] {+ steps(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), function.ptr());+ }));+}++void web_indexed_db_run_in_parallel(void* cell, void (*steps)(JSVM*, void*))+{+ GC::Ref<GC::Cell> function = *static_cast<GC::Cell*>(cell);+ // NB: The function's captures, which the collector scans, keep the cell alive until the steps run.+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [function, steps] {+ steps(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), function.ptr());+ }));+}++void* web_indexed_db_main_thread_event_loop()+{+ return &HTML::main_thread_event_loop();+}++void web_indexed_db_enqueue_check_pending_connection_wait(void* database)+{+ GC::Heap::the().enqueue_post_gc_task([database = GC::Weak<GC::Cell>(*static_cast<GC::Cell*>(database))] {+ if (!database)+ return;+ web_rust_indexed_db_check_pending_connection_wait(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), database.ptr().ptr());+ });+}++static GC::Ptr<DOM::Document> responsible_document(void* realm)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ return HTML::relevant_settings_object(js_realm.global_object()).responsible_document();+}++bool web_indexed_db_devtools_client_is_active(void* realm)+{+ auto document = responsible_document(realm);+ return document && document->page().client().has_active_devtools_client();+}++IndexedDB::TransactionChanges* web_indexed_db_create_transaction_changes()+{+ return new IndexedDB::TransactionChanges;+}++void web_indexed_db_append_transaction_change(IndexedDB::TransactionChanges* changes, u8 kind, FlatPtr database_name, FlatPtr object_store_name, JsonValue* key)+{+ IndexedDB::TransactionChange change { Utf16String::from_raw(database_name), Utf16String::from_raw(object_store_name) };+ if (key) {+ change.key = move(*key);+ delete key;+ }+ switch (kind) {+ case 0:+ changes->added.append(move(change));+ break;+ case 1:+ changes->changed.append(move(change));+ break;+ case 2:+ changes->deleted.append(move(change));+ break;+ default:+ VERIFY_NOT_REACHED();+ }+}++void web_indexed_db_notify_devtools(void* realm, IndexedDB::TransactionChanges* changes)+{+ ScopeGuard delete_changes = [&] { delete changes; };+ auto document = responsible_document(realm);+ if (!document)+ return;+ document->page().client().page_did_update_indexed_database(document->url().serialize(), *changes);+}++JsonValue* web_indexed_db_json_number(double value)+{+ return new JsonValue(value);+}++JsonValue* web_indexed_db_json_string(FlatPtr value)+{+ return new JsonValue(Utf16String::from_raw(value).to_utf8());+}++JsonValue* web_indexed_db_json_binary(ReadonlyBytes bytes)+{+ return new JsonValue(MUST(String::formatted("{}", bytes)));+}++JsonValue* web_indexed_db_json_null()+{+ return new JsonValue;+}++JsonValue* web_indexed_db_json_array()+{+ return new JsonValue(JsonArray {});+}++void web_indexed_db_json_array_append(JsonValue* array, JsonValue* value)+{+ array->as_array().must_append(move(*value));+ delete value;+}diff --git a/Libraries/LibWebCommon/IndexedDB/TransactionChanges.h b/Libraries/LibWebCommon/IndexedDB/TransactionChanges.hindex 1949043eeff..24923251426 100644--- a/Libraries/LibWebCommon/IndexedDB/TransactionChanges.h+++ b/Libraries/LibWebCommon/IndexedDB/TransactionChanges.h@@ -20,6 +20,8 @@ struct TransactionChange {};struct TransactionChanges {+ AK_ALLOC_WITH_KMALLOC;+Vector<TransactionChange> added;Vector<TransactionChange> changed;Vector<TransactionChange> deleted;diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmakeindex c74be06e5de..df5fed8070f 100644--- a/Meta/CMake/all_the_debug_macros.cmake+++ b/Meta/CMake/all_the_debug_macros.cmake@@ -21,7 +21,6 @@ set(HTTP_DISK_CACHE_DEBUG ON)set(HTTP_MEMORY_CACHE_DEBUG ON)set(HTTPJOB_DEBUG ON)set(ICO_DEBUG ON)-set(IDB_DEBUG ON)set(IDL_DEBUG ON)set(IMAGE_DECODER_DEBUG ON)set(IMAGE_LOADER_DEBUG ON)diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 3ceaed1ee30..dedc8205dfc 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -56,9 +56,10 @@ ALLOWED_REALM_MENTIONS = {"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage",),"IndexedDB": (+ 4,14,- 92,- "IndexedDB requests/cursors/records still materialize structured-clone values in selected realms",+ "the C++ glue of the Rust IndexedDB creates the factory in a global's realm and serializes, deserializes, "+ "and wraps values in a given realm",),"Infra": (2, 13, "JSON parse/serialization helpers still expose JS values in selected realms"),"Internals": (3, 3, "test-only internals still expose JS-facing helper objects and promises"),